// create a function that turns the HTML anchor objects for sale items into 
// programmatically accessable objects.  We're going to make this a function so
// that we can use the same process to create both sales and daily-deal blocks.
function setBlocks( cssSelector ){
	// using the passed in css selector, loop through all items with that selector name
	$( cssSelector ).each( function( index ){
		// create the structure of the sales block including an image for displaying the 
		// advertising graphic inside of a masking (or clipping) div and a span for displaying
		// the time remaining or when the show will start
		$( this ).append( '<div><img /></div><span></span>' );
		// create the structure of the class
		var sale = {
			index: index, 	// an index to reference the object
			interval: 0, 	// this property is used to kill/set the timer function
			link: $( this ),	// a reference to the master div HTML element of the sales/daily-deal block
			mask: $( this ).find( 'div' ),  // a reference property to the masking (clipping) HTML element 
			image: $( this ).find( 'div > img' ), // a reference property to the HTML image element of the sale/daily-deal block
			display: $( this ).find( 'span' ), // a reference property to the time displaying HTML span element
			maskSource: '', // source file for the mask set in the initialize function
			adSource: ( $( this ).attr( 'rel' ).split( ';' ) )[0], // a property to hold the image path to the advertising graphic
			properties: $( this ).attr( 'rel' ).split( ';' ),	// a property to hold the entire unsplit properties set server side
			opens: new Date( ( $( this ).attr( 'rel' ).split( ';' ) )[1] ), // a property to hold the date the sale opens
			ends: new Date( ( $( this ).attr( 'rel' ).split( ';' ) )[2] ),	// a property to hold the date the sale ends
			now: new Date( ( $( this ).attr( 'rel' ).split( ';' ) )[3] ),	// a property to hold the server date
			dealPrice: $( this ).attr( 'rel' ).split( ';' )[4], // a property to hold the deal price
			brandName: $( this ).attr( 'rel' ).split( ';' )[5], // a property to hold the brand name
			//offset: $( this ).attr( 'rel' ).split( ';' )[4],	// a property to hold image offset (depreciated)
			height: $( this ).css( 'height' ),	// a property to hold the origional height of the sales block determined by the style sheet
			open: false,	// a boolean property to be used for conditional determinations later on if the sale is 'open' or 'closed'
			expired: false,	// a boolean property to be use for conditional determinations later on if the sale is 'expired' or 'current'
			errored: false,	//	a boolean property to be used for conditional determinations later on if the sale has a problem with it's settings
			overlay: new String(),	// a string property to hold the overlay image to go over the advertising graphic 
			timeLabel: 'Opens In: ',	// a string property to hold the leading text for the time display
			left: 0,	// a numeric property to hold milliseconds left when comparing now/opens - now/ends dates
			days: 0,	// a numeric property to hold the days left when comparing now/opens - now/ends dates
			hours: 0,	// a numeric property to hold the hours left when comparing now/opens - now/ends dates
			minutes: 0,	// a numeric property to hold the minutes left when comparing now/opens - now/ends dates
			seconds: 0,	// a numeric property to hold the seconds left when comparing now/opens - now/ends dates
			initialize: function(){ // a method for setting the initial properties that must be determined not set
				// make sure that the dates are set right and all the necessary properties are there...
				if( sale.now > sale.ends || sale.ends < sale.opens || sale.properties.length < 4 ){
					// if failed... ignore and kill the sales block
					sale.errored = true;
					sale.kill();
					return false;
				} else {
					// if success... 
					// set the value of the mask source
					sale.maskSource = sale.link.css( 'background-image' );
					// set the background-image css property of the embedded image block to the 
					// image path defined in the rel attribute of the master div created server side
					sale.image.css( 'background-image', 'url(\'' + sale.adSource + '\')' );
					// figure out and set if the sale is closed or open
					if( sale.now < sale.opens && sale.now < sale.ends ) sale.setState( 'closed' );
					if( sale.now > sale.opens && sale.now < sale.ends ) sale.setState( 'open' );
					// for IE... set the image to have an onclick event that mirrors the link
					sale.image.click( function(){ window.location = sale.link.attr( 'href' ); });
					// call the run method to start the timer
					
					if( sale.link.hasClass( 'daily-deal' ) ){ 
						 sale.mask.before( '<h2 class="daily-deal-brand-name">' + sale.brandName + '</h2><h2 class="daily-deal-price">$' + sale.dealPrice + '</h2>' );
					}
					/* added in 1.1 to adapt to a new daily-deal object */
					if( sale.link.hasClass( 'daily-del' ) ){
						//sale.image.attr( 'src', sale.adSource );
						//sale.image.css( 'background-image', 'none' );
					}
					
					sale.run();
				};
				// display the link on the stage by fading it in over a period of 1.5 seconds
				sale.link.fadeIn( 1500 );
				// for IE... set the image to have an onclick event that mirrors the link
				sale.image.attr( 'onclick', 'javascript:location="' + sale.link.attr( 'href' ) + '"' );
				// add this newly created sales object to the global sales array
				sales[ sales.length ] = sale;
			},
			run: function(){  // create a method that get's run every second and makes the necessary changes to itself
				// stop the clock... this is to defeat the memory leak problem of the setTimeout javascript function
				clearInterval( sale.interval );	
				// since we're using the server time instead of the client's time we need to increment the time a second
				sale.now.setTime( sale.now.getTime() + 1000 );
				// check to see if the sale is 'closed' (upcoming) or open
				if( sale.now < sale.opens && sale.now < sale.ends ){ // closed
					// determine and store the milliseconds left between now and when the sale opens
					sale.left = ( sale.opens.getTime() - sale.now.getTime() ) / 1000;
					// call the setState method to change the block from an 'open' sales block to a 'closed' sales block
					if( !sale.link.hasClass( 'closed' ) ) sale.setState( 'closed' );
				}
				// check to see if the sale is 'open'
				if( sale.now > sale.opens && sale.now < sale.ends ){ // open	
					// determine and store the milliseconds between now and when the sale closes
					sale.left = ( sale.ends.getTime() - sale.now.getTime() ) / 1000;	
					// call the setState method to change the block from a 'closed' state to an 'open' state
					if( !sale.link.hasClass( 'open' ) && !sale.link.hasClass( 'closing' ) ) sale.setState( 'open' );
				}
				// check to see if the sale has expired
				if( sale.now > sale.ends || sale.left <= 0 && sale.link.hasClass( 'saleblock' ) ){
					// if expired...
					// set the expired property to true
					sale.expired = true;
					// animate the sales block to 'shrink' off the screen over a period of 1 second
					sale.link.animate({ height:0 }, 1000, 'swing', function(){
						// once the animation completes...
						// call the kill method to remove the HTML reference from the DOM
						sale.kill(); 
						// call the flipUpcoming function to replace the dying/dead sale with an upcoming one
						flipUpcoming();
					});
				} else {
					// if not expired...
					// we need to get the milliseconds into something more user friendly
					sale.days = Math.floor( sale.left / 86400 );
					sale.left %= 86400;
					sale.hours = Math.floor( sale.left / 3600 );
					sale.left %= 3600;
					sale.minutes = Math.floor( sale.left / 60 );
					sale.left %= 60;
					sale.seconds = Math.floor( sale.left );
					// if the time remaining is less then 60 seconds we want to change it's state to 'closing' 
					// so the css can add the closing overlay graphics and create more urgency
					if( sale.days == 0 && sale.hours == 0 && sale.minutes == 0 && sale.seconds <= 59 && sale.link.hasClass( 'open' ) ) sale.setState( 'closing' );
					// check to see if the sale is a 'daily-deal' or an 'open' sale.  We're assuming the daily deal is ALWAYS open
					if( sale.open || sale.link.hasClass( 'daily-deal' ) ){
						// if so... display the amount of remaining
						sale.display.html( sale.timeLabel + '<em>' + sale.days + '</em> days : <em>' + sale.hours + '</em> hours : <em>' + sale.minutes + '</em> minutes : <em>' + sale.seconds + '</em> seconds' );
					} else {
						// if not... show the date the sale will open
						sale.display.html( sale.timeLabel + '<em>' + sale.displayDate( sale.opens ) ) + '</em>';
					}
					// recursively call the run function to rinse, wash repeat this functionality a second later
					sale.interval = setTimeout( sale.run, 1000 );
				}
			},
			displayDate: function( date ){ // create a method to return a passed date into the format we want to display
				var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
				var months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];

var ap = "AM";;
var dhour = date.getHours();
var dmin = date.getMinutes();
if (dhour   > 11) { ap = "PM";        }
if (dhour   > 12) { dhour = dhour - 12; }
if (dhour   == 0) { dhour = 12;        }
dmin = dmin + "";
if (dmin.length==1) {dmin = "0" + dmin;}


				return  days[ date.getDay() ] + ' - ' + months[ date.getMonth() ] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' - ' + dhour + ':' + dmin + ' ' + ap + '';
			},
			setState: function( state ){  // create a method to change the state (appearance) of the sales block
				// check to see if the sale is a sale or a daily-deal since daily-deals have no state changes
				if( sale.link.hasClass( 'saleblock' ) ){  
					// if it's a sale...
					// create an array of class names (the states) to remove from the master block
					var x = [ 'open', 'closed', 'closing' ];
					// indescriminatly kill them all
					for( var i = 0; i < x.length; i++ ) sale.link.removeClass( x[i] );
					// set the class to the state (apperance) we want the sale to have
					sale.link.addClass( state );
					// change the leading time label to one appropriate for it's state
					if( state == 'open' ){ sale.timeLabel = 'Closes In: '; sale.open = true; };
					if( state == 'closed' ){ sale.timeLabel = 'Opens: '; };
				}
				// check to see if the sale is a daily deal and if so set the appropriate time label
				if( sale.link.hasClass( 'daily-deal' ) ){
					sale.timeLabel = '<em style="font-size:.9em;">Time remaining for this daily deal:</em><br />';
				}
				// change the overlaying (masking) image to the new state
				if( !sale.link.hasClass( 'daily-deal' ) ){
					sale.overlay = sale.link.css( 'background-image' );
					sale.image.attr( 'src', sale.overlay.substring( sale.overlay.indexOf( '/img/' ), sale.overlay.indexOf( '.png' ) + 4 ) );
				} else {
					sale.image.attr( 'src', sale.adSource );
					sale.image.css( 'background-image', 'none' );
				}
			},
			kill: function(){ // create a method to remove or completely kill the sales HTML element from the dom
				clearInterval( sale.interval );
				sale.expired = true;
				sale.link.remove();
			}
		};
		sale.initialize();  // call the initialize method for this class to create it
	});
};

// create a function that takes the upcoming block from the bottom of the page and 
// turns it's display off while simultaneously turning on the display of the
// corresponding large image block on the main stage
function flipUpcoming(){
	// loop through all of the sales objects stored in the global 'sales' array
	for( var i = 0; i < sales.length; i++ ){
		// check to see if the sales block we're working with has the class salesblock (not daily-deal) and it's hidden
		if( sales[ i ].link.hasClass( 'saleblock' ) && sales[ i ].link.css( 'display' ) == 'none' ){
			// set the sales block to it's initial animation state which has 0 height then turn the display on
			sales[ i ].link.css( 'height', 0 );
			sales[ i ].link.css( 'display', 'block' );
			// animate the large sales block onto the stage by 'growing' it from a 0 height to it's actual height
			sales[ i ].link.animate({ height: sales[ i ].height }, 500, 'swing' );
			// fade the corresponding small sales block off the screen so there is always only one at a time
			$( 'div#upcoming > a.upcomingblock:first-child' ).fadeOut( 1000, function(){ $( this ).remove(); respaceUpcoming(); } );
			// return false to break out of the loop so we're not doing unecessary processing
			return false;
		}
	}
}

// create a function that cycles through every sale... upcoming or current and takes 
// the upcoming blocks and moves them to the bottom of the page.  This is to make sure
// that there are always 3 (or more) sales blocks in the main stage for visual balance.
function divideBlocks( sales ){
	// cycle through every block past the first 3
	for( var i = 3; i < sales.length; i++ ){
		// make sure we are only applying this to the sales blocks and not the daily deals
		if( sales[ i ].link.hasClass( 'saleblock' ) ){
			// if the sale is OPEN, it should never be placed at the bottom of the screen 
			// so we'll test to see if it is and allow it to be placed in the top even if
			// that makes more then 3 showing on the main stage.
			if( sales[ i ].open ) continue;  
			// take the information and properties from the large upcoming blocks generated and 
			// create matching small blocks at the bottom of the page starting with the HTML structure
			$( 'div#upcoming > div.clear' ).before( '<a id="upcoming_' + i + '" class="upcomingblock">' + sales[ i ].link.html() + '</a>' );
			// create a reference variable to the newly created upcoming block
			var upcomingBlock = $( 'a#upcoming_' + i );
			// create a reference variable to the newly created image block child of the upcoming block
			var img = upcomingBlock.find( 'div > img' );
			// set the source of the image to overlay graphic we want to display over the ad image
			img.attr( 'src', sales[i].adSource );
			// set the background-image property to the graphic we want to display for this block
			img.css( 'background-image', sales[i].overlay );
			// hide the corresponding main stage block that we just created a upcoming block image for
			sales[ i ].link.css( 'display', 'none' );
		}
	}
	// call the respacing function to display the remaining upcoming blocks evenly.
	respaceUpcoming();
}

// create a function that sets the spacing for the small upcoming shows at the bottom
// of the branding page.  This needs to be a function that can be called so that 
// when a small one moves to the large stage it can respace the remaining ones
function respaceUpcoming(){
	// cycle through each upcoming sales block and apply the proper spacing to every other one.
	$( 'a.upcomingblock' ).each( function( index ){
		$( this ).css( 'margin' , ( index % 2 == 0 ) ? '20px 20px 0 0' : '20px 0 0 0' );
	});
}

var sales = new Array();

$( document ).ready( function(){
	// create an object to store the general settings for the overlays (popups)
	var overlayOptions = { speed:'fast', close:'a.overlay-close', expose:{ speed:'fast', opacity:.8, color:'#a12a00' } };
	// call the setBlocks function to turn any anchors's with the class 'saleblock' into objects
	setBlocks( 'a.saleblock' );
	// call the setBlocks function to turn any anchors's with the class 'daily-deals' into objects
	setBlocks( 'a.daily-deal' );
	// call the divideBlocks function to take all of the sales blocks, determine which are 
	// upcoming and put some of them at the bottom of the page
	divideBlocks( sales );
	// For any overlay div's (popups) append an anchor that when clicked on closes the pop up
	$( 'div.overlay' ).append( '<a class="overlay-close"></a>' );
	// Marry any anchors with the class 'policy' to the overlay (popup) that we want to display
	// when clicked.  This is determined by the rel attribute of the anchor which matches the 
	// overlay div's (popup) id
	$( 'a.policy[rel]' ).overlay( overlayOptions ).load();
	// Marry any anchors in the naviation bar to it's corresponding overlay div (popup)
	$( 'div#navigation > a[rel]' ).overlay( overlayOptions ).load();
	// Marry any anchors with the class 'option' (these are the anchors in the floating gray sidebar) to 
	// their corresponding overlay div
	$( 'a.option[rel]' ).overlay( overlayOptions ).load();
	
	// create a temporary variable to store a copy of the overlay options object so
	// we can add additional properties/functions without upsetting the base overlay options object
	var fpX = overlayOptions;
	// attach a function to the overlay option that sets the cursor focus to the first form
	// element inside the forgot password overlay so users do not have to click on the text
	// box first.
	fpX.onLoad = function(){ $( 'div#forgot-password-top > input#email-address' ).focus(); }
	// Marry the forgot password link on the homepage with the corresponding overlay div (popup)
	$( 'a#forgot-password-link[rel]' ).overlay( fpX ).load();
	
	// Set the cursor focus on the e-mail input field of the sign-in page.  This code 
	// is ignored if fired on any other page then the index (or sign-in) page.
	$( 'input#email' ).focus();
	// Bind the validator fucntion to the login form which handles checking for 
	// valid information entered by the user for the sign-in form.
	$( '#login-form' ).validator();
	// Bind the validator function to the forgot password form which handles checking
	// for valid information entered by the user for the forgot password form
	$( '#forgot-password-form' ).validator();
	// Create a custom function to use for the validation of the registration form
	// that checks to make sure that the passwords entered matched.
	// this code will fire AFTER the validator handles it's normal routine.
	$( '#registration-form' ).validator({
		onSuccess: function(){
			if( $( 'password' ).val() != $( 'password-verify' ).val() ){
				return false;
			}
		}
	});
	
	// The following code will handle the display of an error message in the form of an
	// overlay (popup) when the round trip to the server determines that there was a 
	// problem with the login information.  It will take ANYTHING written in the div
	// with the ID login-fail and display it in pop up form for the user to see.
	
	// check to see if the div is void of information and if not, start the process
	if( $( 'div#login-fail' ).html() != '' ){
		try {
			// create a temporary variable to store a copy of the overlayOptions object
			// so we can add an additional property to it without disrupting the origional 
			// settings of the overlay options object.
			var x = overlayOptions;
			// we have to add api = true to it's list of properties because the overlay 
			// itself is not bound to an anchor object
			x.api = true;
			// format the contents of the login-fail overlay div to provide the necessary appearance
			$( 'div#login-fail' ).html( '<div>' + $( 'div#login-fail' ).text() + '</div><a class="overlay-close"></a>' ); 
			// display the login-fail overlay to the screen.
			$( 'div#login-fail' ).overlay( x ).load();
		} catch( e ){};
	};
});

