/************************************************************************
* automaticSales is dependent on jQuery for simple tasks like setting the 
* background image and setting the new end date text. Include it after
* including jquery-x.x.x.js.
************************************************************************/

var monthName = new Array(	"January",
						"February",
						"March",
						"April",
						"May",
						"June",
						"July",
						"August",
						"September",
						"October",
						"November",
						"December");

var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var testDaysToAdd = 0;
var mainSaleImage1 = new Image();
var mainSaleImage2 = new Image();
var mainSaleImage3 = new Image();
var topBannerImage1 = new Image();
var topBannerImage2 = new Image();
var topBannerImage3 = new Image();
var topBannerImage4 = new Image();

// Change the images here to change them throughout the script.
mainSaleImage1.src = "images/banner0-superSummerHeld.jpg";
mainSaleImage2.src = "images/banner0-StimulusTuesday.jpg";
mainSaleImage3.src = "images/banner0-superSummer.jpg";


/************************************************************************************************************************************
/ This doesn't actually get the exact # of weeks since the Epoch. It starts the Sunday AFTER the Epoch, which was on a Thursday.
*************************************************************************************************************************************/
Date.prototype.getWeeksSinceEpoch = function()
{
	// Epoch was on Thursday, we want Sunday to be the start of the week count.
	var millisecondsSinceEpoch = (this.getTime() - (3 * 86400000));
	
	// Divide by number of milliseconds in a week (7 * 24 * 60 * 60 * 1000)
	return Math.floor(millisecondsSinceEpoch / 604800000);
}

Date.prototype.getDayOfYear = function()
{
	// First, we grab January 1st of this year
	var januaryFirst = new Date(this.getFullYear(), 0, 1);
	
	// We subtract January 1st from the current date to get
	// how many days it's been since Jan 1 in milliseconds.
	// Divide by # of milliseconds/day, voila: day of year.
	return Math.ceil((this - januaryFirst) / 86400000);
}

// If switchDailySale comes after switchMainSale, DailySale doesn't work.. figure out why
function updateSales()
{
	var currentDate = new Date();
	$("span#bigSaleText").html("Ends <span id=\"bigSaleDate\" class=\"dynamicDateFullTextual\"></span> at 11:59PM EST");
	switchDailySale(determineDailySaleItem(currentDate));
	switchMainSale(currentDate);
	updateClock();
}

function updateSaleItemPage(page)
{
	var currentDate = new Date();
	showSetSaleImages(determineDailySaleItem(currentDate), page);
	changeTextDates(determineMainSaleEndDate(currentDate));
}

function determineDailySaleItem(date)
{
	var saleItem;
	
	if (date.getDayOfYear() % 2 == 0)
	{
		saleItem = "bamboo";
	}
	else
	{
		saleItem = "energymax";
	}
	
	return saleItem;
}

function switchDailySale(saleItem)
{
	var topCubeNav = document.getElementById("topcube_nav");
	
	if (saleItem == "energymax")
	{
		/*
		topCubeNav.style.backgroundImage = "url('images/topcube_nav_blackfriday09.jpg')";		
		topCubeNav.firstChild.innerHTML = "Queen Bamboo Mattress &amp; Foundation<br clear=\"all\"><img src=\"images/spacer.gif\" width=\"222\" border=\"0\" height=\"96\">";
		topCubeNav.firstChild.href = "memory_foam_mattresses/bamboo_mattress_free_shipping/index.html";
		*/
	}
	else if (saleItem == "bamboo")
	{
		/*
		topCubeNav.style.backgroundImage = "url('images/topcube_nav_FreeTravelPillow.jpg')";
		topCubeNav.firstChild.innerHTML = "nothing...<br clear=\"all\"><img src=\"images/spacer.gif\" width=\"222\" border=\"0\" height=\"96\">";
		topCubeNav.firstChild.href = "memory_foam_mattresses/energymax_mattress_free_shipping/index.html";
		*/
	}
}

// unused
function cycleImages()
{
	var images = new Array(	"images/topcube_promo_presidents_blank.jpg",
							"images/topcube_promo_taxrefund_blank.jpg");
}

function determineMainSaleEndDate(date)
{
	var endDate = new Date();
	endDate.setMonth(date.getMonth());
	
	// Monday sale is only Monday, Tuesday sale carries until Thursday, and 
	// Thursday sale carries til the next Monday. endDates are one date
	// before expected because sales end at 11:59 PM.
	// ^???
	switch(date.getDay())
	{
		case 1:
			endDate.setDate(date.getDate());
			break;
			
		case 2:
			endDate.setDate(date.getDate());
			break;
			
		case 3:
			endDate.setDate(date.getDate() + 1);
			break;
		
		case 4:
			endDate.setDate(date.getDate());
			break;
			
		case 5:
			endDate.setDate(date.getDate() + 3);
			break;
			
		case 6:
			endDate.setDate(date.getDate() + 2);
			break;
			
		case 0:
			endDate.setDate(date.getDate() + 1);
			break;
	}
	
	endDate.setHours(23);
	endDate.setMinutes(59);
	endDate.setSeconds(59);
	return endDate;
}

function switchMainSale(date)
{
	var bigSaleImage = document.getElementById("bigSale");
	var endDate = new Date();
	endDate.setMonth(date.getMonth());
				
	var offerExpires = document.getElementById("offerExpiresDate");
	
	// Sunday through Monday
	var saleSequenceOne = new Array(	mainSaleImage1.src,
										mainSaleImage1.src,
										mainSaleImage2.src,
										mainSaleImage1.src,
										mainSaleImage1.src,
										mainSaleImage2.src,
										mainSaleImage2.src);
									
	var saleSequenceTwo = new Array(	mainSaleImage2.src,
										mainSaleImage2.src,
										mainSaleImage1.src,
										mainSaleImage2.src,
										mainSaleImage2.src,
										mainSaleImage1.src,
										mainSaleImage1.src);
	
	var saleSequenceThree = new Array(	mainSaleImage1.src,
										mainSaleImage1.src,
										mainSaleImage2.src,
										mainSaleImage3.src,
										mainSaleImage3.src,
										mainSaleImage1.src,
										mainSaleImage1.src);
	
	currentSaleSequence = saleSequenceThree;
	
	// If we're on a two-week sequence as before, we need to use this.
	// The new sequence is one week, so we can set it easily.
	/*
	if (date.getWeeksSinceEpoch() % 2 == 0)
		currentSaleSequence = saleSequenceOne;
	else
		currentSaleSequence = saleSequenceTwo;
	*/
	
	// Sales END Monday, Tuesday, and Thursday at midnight.
	switch(date.getDay())
	{
		case 1:		
			updateBannerAndDate(endDate, currentSaleSequence[date.getDay()], date.getDate());
			break;
			
		case 2:
			updateBannerAndDate(endDate, currentSaleSequence[date.getDay()], date.getDate());
			break;
			
		case 3:
			updateBannerAndDate(endDate, currentSaleSequence[date.getDay()], date.getDate() + 1);
			break;
			
		case 4:
			updateBannerAndDate(endDate, currentSaleSequence[date.getDay()], date.getDate());
			break;
			
		case 5:
			updateBannerAndDate(endDate, currentSaleSequence[date.getDay()], date.getDate() + 3);
			break;
			
		case 6:
			updateBannerAndDate(endDate, currentSaleSequence[date.getDay()], date.getDate() + 2);
			break;
		
		case 0:
			updateBannerAndDate(endDate, currentSaleSequence[date.getDay()], date.getDate() + 1);
			break;
	}
	
	//offerExpires.innerHTML = month[endDate.getMonth()] + " " + endDate.getDate();
	changeTextDates(endDate);
}

// Updates the main sale banner image and the end date.
// Sale banner is temporarily disabled.
function updateBannerAndDate(endDate, saleBanner, newEndDate)
{
	//bigSaleImage.src = saleBanner;
	$("div#banner0").css("backgroundImage", "url('" + saleBanner + "')");
	endDate.setDate(newEndDate);
}

function test()
{
	testDaysToAdd++;
	currentDate = new Date();
	newDate = new Date();
	
	newDate.setDate(currentDate.getDate() + testDaysToAdd);
	document.getElementById("testSpan").innerHTML = "testDaysToAdd: " + testDaysToAdd + " | test Month: " + monthName[newDate.getMonth()] + " | test Date: " + newDate.getDate() + " | Week #: " + newDate.getWeeksSinceEpoch();
	switchDailySale(determineDailySaleItem(newDate));
	showSetSaleImages(determineDailySaleItem(newDate));
	switchMainSale(newDate);
}

// Shows the sale banner images on the Bamboo and Energy-MAX pages, dependent upon which one is on sale.
function showSetSaleImages(saleItem, page)
{
	var topImageContainer = document.getElementById("topSpecialSaleBanner");
	var bottomImageContainer = document.getElementById("bottomSpecialSaleBanner");
	
	if (saleItem == "bamboo" && page == "bamboo")
	{
		topImageContainer.innerHTML = "<a href=\"../../itemdesc.asp?ic=BAM6350MATT_SET\"><img src=\"../../images/todays_special_bam63.gif\" border=\"0\"></a><br>";
		bottomImageContainer.innerHTML = "<a href=\"../../itemdesc.asp?ic=BAM8150MATT_SET\"><img src=\"../../images/todays_special_bam81.gif\" border=\"0\"></a><br>";
	}
	else if (saleItem == "energymax" && page == "energymax")
	{
		topImageContainer.innerHTML = "<a href=\"../../itemdesc.asp?ic=INT6350MATT_SET\"><img src=\"../../images/todays_special_INT63.gif\" border=\"0\"></a><br>";
		bottomImageContainer.innerHTML = "<a href=\"../../itemdesc.asp?ic=INT8150MATT_SET\"><img src=\"../../images/todays_special_INT81.gif\" border=\"0\"></a><br>";
	}
}

// Takes the end date for a sale
function changeTextDates(date)
{	
	var spans = document.getElementsByTagName("span");
	var c = 0;
	var length = 0;
	
	for (c = 0, length = spans.length; c < length; c++)
	{
		if (spans[c].className == "dynamicDateNumeric")
		{
			// getMonth() returns 0-11, so add 1
			spans[c].innerHTML += (date.getMonth() + 1) + "/" + date.getDate() + " ";
		}
		else if (spans[c].className == "dynamicDateTextual")
		{
			spans[c].innerHTML += monthName[date.getMonth()] + " " + date.getDate() + " ";
		}
		else if (spans[c].className == "dynamicDateFullTextual")
		{
			spans[c].innerHTML += weekday[date.getDay()] + ", " + monthName[date.getMonth()] + " " + date.getDate() + " ";
		}
	}
}

// Ajax returns the number of seconds left between now and endDate.
// THIS IS DEPENDENT ON SERVER TIME BEING EST!
function updateClock()
{
	var endDate = determineMainSaleEndDate(new Date());
	
	var html = $.ajax({
		  url: "countdownTimer.asp",
		  cache: false,
		  type: "POST",
			data:	"year=" + endDate.getFullYear() + "&month=" + (endDate.getMonth() + 1) + "&day=" + endDate.getDate(),
		  dataType: "html",
		  success: function(seconds){
				startTimer(seconds)
		  }
		}
	);
}

// Splits up remaining seconds into intervals of days, hours, minutes, seconds.
// Uses jQuery to spit out the timer HTML, decrements the time left,
// then calls setTimeout on itself at an interval of 1 second.
function startTimer(seconds)
{
	var days;
	var hours;
	var minutes;
	
	// Time is up, so update the sale end date and restart everything.
	if (seconds <= 0)
	{
		clearTimeout(t);
		updateSales()
	}

	remainingSeconds = seconds;
	days = Math.floor(seconds / 86400);
	seconds -= (days * 86400);
	hours = Math.floor(seconds / 3600);
	seconds -= (hours * 3600);
	minutes = Math.floor(seconds / 60);
	seconds -= (minutes * 60);
	html = "<h2>Sale Ends In</h2>" +
	"<p id=\"days\">" +
		"<span>" + days + "</span>Days" +
	"</p>" +
	"<p id=\"hours\">" +
		"<span>" + hours + "</span>Hours" +
	"</p>" +
	"<p id=\"minutes\">" +
		"<span>" + minutes + "</span>Minutes" +
	"</p>" +
	"<p id=\"seconds\">" +
		"<span>" + seconds + "</span>Seconds" +
	"</p>";
	$("div.timer").html(html);
	
	remainingSeconds -= 1;
	//t = setTimeout("startTimer(remainingSeconds)", 1000);
	t = setTimeout("startTimer(remainingSeconds)", 1000);
}

// Gets a query string parameter
function getParameterByName(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}