
/* used in conjunction with the estimated ship date functionality */
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";


//used to format YYYYMMDD in a 'pretty' manner
function handleDateFormat(D)	{
//D = Date formatted as YYYYMMDD
	y = D.substring(0,4);
	m = D.substring(4,6);
	d = D.substring(6);
	return m+'/'+d+'/'+y;
	}
	
	

function clearText(thefield)	{
	if (thefield.defaultValue == thefield.value)
		thefield.value = "";
	}



function replaceDefault(thefield)	{
	if (thefield.value == "")
		thefield.value = thefield.defaultValue;
	}
	
function openWindow(url) {
	adviceWin = window.open(url,'advice','status=no,width=640,height=480,menubar=no,scrollbars=yes');
	adviceWin.focus(true);
	}
	





/*

############    used in the product layout for the shipping time countdown 

good docs for date method.  http://www.javascriptkit.com/jsref/date.shtml
clock script came from here: http://dynamicdrive.com/dynamicindex6/dhtmlcount.htm
good help file for POSIX time: http://www.opengroup.org/onlinepubs/009695399/functions/strftime.html

*/
	
/* used to get tomorrows date */
function getnewdate(DAYS,NOW)	{
//http://bytes.com/groups/javascript/145645-get-date-tomorrow-need-help
	var daylength= 1*24*60*60*1000;
	var then = new Date(NOW*1+daylength*DAYS);
//	alert('now '+NOW+'\nthen '+then);
	return then;
	}


//  Script for countdown clock

function cdtime(container, targetdate, today){
	if (!document.getElementById || !document.getElementById(container)) return
		this.container=document.getElementById(container)
		this.currentTime=new Date(today)
		this.targetdate=new Date(targetdate)
		this.timesup=false
		this.updateTime()
		}

	cdtime.prototype.updateTime=function(){
		var thisobj=this
		this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
		setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
		}

	cdtime.prototype.displaycountdown=function(baseunit, functionref){
		this.baseunit=baseunit
		this.formatresults=functionref
		this.showresults()
		}

	cdtime.prototype.showresults=function(){
	var thisobj=this


	var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
	if (timediff<0){ //if time is up
		this.timesup=true
		this.container.innerHTML=this.formatresults()
		return
		}

	var oneMinute=60 //minute unit in seconds
	var oneHour=60*60 //hour unit in seconds
	var oneDay=60*60*24 //day unit in seconds
	var dayfield=Math.floor(timediff/oneDay)
	var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
	var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
	var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))

	if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
		hourfield=dayfield*24+hourfield
		dayfield="n/a"
		}

	else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
		minutefield=dayfield*24*60+hourfield*60+minutefield
		dayfield=hourfield="n/a"
		}
	else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
		var secondfield=timediff
		dayfield=hourfield=minutefield="n/a"
		}

	this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
	setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
	}
	
	
//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc




function formatresults()	{

//if ship deadline date/time not yet met
	if (this.timesup==false)	{
		if(arguments[2] <= 9)
			arguments[2] = '0'+arguments[2];
		if(arguments[3] <= 9)
			arguments[3] = '0'+arguments[3];
		var displaystring="Ships <span id='latencyShipDay4Clock'>"+shipDay+"</span> if ordered in the next "+arguments[1]+":"+arguments[2]+":"+arguments[3];
		}
//if ship deadline has passed. this gets displayed only if the deadline passes while the page is being viewed.
	else	{ 
		var displaystring="Order tomorrow before 4pm (CST) to have this item ship <span id='latencyShipDay4Clock'>"+getShipDate(default_latency)+"</span>."
		}
	return displaystring
	}
	
	





/*

######

This function accepts a date object as the parameter.  it checks the month, day and year to see if the date is a holiday.
The number of days that should be added to adjustedLatency is returned (0, 1 or 2).

*/

function checkIfHoliday(dateObj)	{
	dayCompensation = 0;
//holidays that are always on the same date. adjust for these first.
	if(dateObj.getDate() == '25' && dateObj.getMonth() == '11') //no shipping on XMAS
		dayCompensation = 1;
	else if(dateObj.getDate() == '7' && dateObj.getMonth() == '6') //no shipping on july 4
		dayCompensation = 1;
	else if(dateObj.getDate() == '1' && dateObj.getMonth() == '0') //no shipping on new years day
		dayCompensation = 1;
	else if(dateObj.getDate() == '31' && dateObj.getMonth() == '11') //no shipping on new years eve (add two to compensate for new years day)
		dayCompensation = 2;

//	alert(dateObj.getDate()+' = '+dayCompensation);
//if one of the above holidays falls on a weekend, the script below compensates for that. also checks for 'irregular' holidays.
	if(dateObj.getFullYear() == '2010')	{
		if(dateObj.getDate() == '18' && dateObj.getMonth() == '0') //MLK jr
			dayCompensation = 1;
		else if(dateObj.getDate() == '31' && dateObj.getMonth() == '4') //memorial day
			dayCompensation = 1;	
		else if(dateObj.getDate() == '5' && dateObj.getMonth() == '6') //july 4
			dayCompensation = 1;
		else if(dateObj.getDate() == '6' && dateObj.getMonth() == '8') //labor day
			dayCompensation = 1;
		else if(dateObj.getDate() == '25' && dateObj.getMonth() == '10') //thanksgiving (add two to compensate for day after)
			dayCompensation = 2;
		else if(dateObj.getDate() == '26' && dateObj.getMonth() == '10') //day after thanksgiving
			dayCompensation = 2;

		}
	else if	(dateObj.getFullYear() == '2011'){
		if(dateObj.getDate() == '17' && dateObj.getMonth() == '0') //MLK jr
			dayCompensation = 1;
		else if(dateObj.getDate() == '30' && dateObj.getMonth() == '4') //memorial day
			dayCompensation = 1;	
		else if(dateObj.getDate() == '5' && dateObj.getMonth() == '8') //labor day
			dayCompensation = 1;
		else if(dateObj.getDate() == '24' && dateObj.getMonth() == '10') //thanksgiving (add two to compensate for day after)
			dayCompensation = 2;
		else if(dateObj.getDate() == '25' && dateObj.getMonth() == '10') //day after thanksgiving
			dayCompensation = 1;
		else if(dateObj.getDate() == '26' && dateObj.getMonth() == '11') //christmas
			dayCompensation = 1;
		}

	return dayCompensation;
	}




//v is the latency, either the default or the sog-specific.
function getShipDate(v) {
	v = v*1;  //make sure v is treated as a number.
	var adjustedLatency = 0;
	var myDate=new Date(today);  //used to reset adjusted date later. this is the 'control'.
	var adjustedDate=new Date(today);  //can't set this to = myDate because the changes later to adjusted date effected both vars.  odd.

//	alert('my date = '+myDate+'\nadjusted date = '+adjustedDate);

//compute adjusted latency.  check each day between now and X days from now (where X = default_latency) to make sure there are no holidays or weekends. If there are, compensate by incrementing adjustedLatency accordingly (1 or 2 days, depending on circumstance).
	for(i = 1; i <= v; i++)	{
		adjustedDate.setDate(adjustedDate.getDate()+1);
		if(adjustedDate.getDay() == 0 || adjustedDate.getDay() == 6) //it's a weekend, add 1 day to ship date
			adjustedLatency += 1;
		else  //only check for holiday IF not on a weekend. That way we don't double compensate
			adjustedLatency += checkIfHoliday(adjustedDate);
		}

	adjustedDate=new Date(today); //reset adjusted date to myDate and add latency and adjustedLatency.
	var isTodayAHoliday = checkIfHoliday(myDate); //is today a holiday?  0 for no. > 0 for yes.

//	alert(adjustedLatency);

//on a non-holiday weekday before 2pm pst (4 cst), item ships 'today'
	if(v == 1 && myDate.getDay() != 6  && myDate.getDay() != 0 && adjustedLatency == 0  && myDate.getHours() < 14 && isTodayAHoliday == 0)
		return 'today'
//on sunday-thursday after 4pm pst (4 cst), item ships 'tomorrow'
	else if(v == 1 && myDate.getDay() != 6  && myDate.getDay() != 5 && adjustedLatency == 0  && myDate.getHours() > 14 && isTodayAHoliday == 0)
		return 'tomorrow'
	else	{
		adjustedDate.setDate(adjustedDate.getDate()+(adjustedLatency+v));
		if(adjustedDate.getDay() == 0)
			adjustedDate.setDate(adjustedDate.getDate()+1); //it's a sunday, add 1 days
		else if(adjustedDate.getDay() == 6)
			adjustedDate.setDate(adjustedDate.getDate()+2); //it's a saturday, add 2 days
		else if(adjustedDate.getDay() == 5) //it's a friday after 2pm. add 3 days.
			adjustedDate.setDate(adjustedDate.getDate()+3); 
	
	//check to see if the estimated shipping date is a holiday. If so, compensate AND recheck to make sure compensated date is not on a weekend.  adjust if it is.		
		if(checkIfHoliday(adjustedDate) > 0)	{
			adjustedDate.setDate(adjustedDate.getDate()+checkIfHoliday(adjustedDate));
			if(adjustedDate.getDay() == 0)
				adjustedDate.setDate(adjustedDate.getDate()+1); //it's a sunday, add 1 days
			else if(adjustedDate.getDay() == 6)
				adjustedDate.setDate(adjustedDate.getDate()+2); //it's a saturday, add 2 days
			}
//		alert(weekday[adjustedDate.getDay()]+' '+(adjustedDate.getMonth()+1)+'/'+adjustedDate.getDate()+'/'+adjustedDate.getFullYear());
		return weekday[adjustedDate.getDay()]+' '+(adjustedDate.getMonth()+1)+'/'+adjustedDate.getDate()+'/'+adjustedDate.getFullYear();
		}
	}





//This function is executed as part of the option-specific latency.  It runs when a select list is changed.
//As per brendan, this feature was written to work with products that have 1 inventory-able option.

//v is the value of the option specific latency in the json.

function handleLatency(v)	{

	if(isPreorder == 1)	{
//if the item is a preorder, the tab ship date needs to be set. The ship date by add to cart is already set within the addtocart element itself.
		$('prodShipDateInTab').innerHTML = 'Estimated shipping date:  '+handleDateFormat(salesRank);
		}
	else	{

//if sog-specific latency is set to 1 or blank, it'll ship sameday/next day. 
		if(v == 1 || v == '')	{
			shipDay = getShipDate(1);
			}
	//option specific latency is set to > 1
		else if(typeof v == 'string')
			shipDay = getShipDate(v);
	//no option specific latency (fail safe). use product latency.
		else
			shipDay = getShipDate(default_latency);
	
	//latencyShipDay4Clock is an id on a span, set in the shared.js file. it only appears when a clock is present.
	//update clock if present and tab
		if($('latencyShipDay4Clock'))	{
			$('latencyShipDay4Clock').innerHTML = shipDay;
			$('prodShipDateInTab').innerHTML = 'Estimated shipping date:  '+shipDay;
			}
	
	//update shipping latency for non-clock items
		else	{
			
			o = 'Normally takes ';
			if(typeof v == 'string')
				o += v;
			else
				o += default_latency;
			o += ' day(s) to ship';
			$("JSONLatencyDisplay").innerHTML = o;
	//update the estimated shipping date in the tab.
			$('prodShipDateInTab').innerHTML = 'Estimated shipping date:  '+shipDay;
			}
		}
	}




