
function zstderr($MSG)	{
	if(typeof console != 'undefined')	{
		if(typeof $MSG == 'object')
			console.dir($MSG);
		else
			console.log($MSG);
		}
	}




// JavaScript Document
$(document).ready(function() {

//handles fixed positioning for 'need help' tab.
	$(window).scroll(function() {
		$('#helpTab').css('top', ($(this).scrollTop() + 145) + "px");
		$('#helpTabContents').css('top', ($(this).scrollTop() + 145) + "px");
		});
//adds action to help tab to open panel.
	$('#helpTab').click(function()	{
		$('#helpTabContents').show();
		if(typeof PleaseTrackClick == 'function') { PleaseTrackClick('LINK-NEEDHELP','Page: '+document.location())}
		});
//adds action to 'X' in need help to close panel.
	$('.closeHelpContents').click(function()	{
		$('#helpTabContents').hide();
		});

});

function clearText(thefield)	{
	if (thefield.defaultValue == thefield.value)
		thefield.value = "";
}






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 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;
	}
	



/* used to get a future 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;
	}


//the countdown function allows for server tme to be used via an ajax call. however, a date object is created via specl and that is set to the SERVERTIME var, so that is returned.
function serverTime()	{
	if(typeof SERVERTIME != 'undefined')
		return SERVERTIME
	else
		return new date();
	}


/*

######

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() == '4' && 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() == '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;
		}
	else if	(dateObj.getFullYear() == '2012'){
		if(dateObj.getDate() == '2' && dateObj.getMonth() == '0') //new years day (celebrated - the first falls on a sunday)
			dayCompensation = 1;
		else if(dateObj.getDate() == '16' && dateObj.getMonth() == '0') //MLK jr
			dayCompensation = 1;
		else if(dateObj.getDate() == '28' && dateObj.getMonth() == '4') //memorial day
			dayCompensation = 1;	
		else if(dateObj.getDate() == '3' && dateObj.getMonth() == '8') //labor day
			dayCompensation = 1;
		else if(dateObj.getDate() == '22' && dateObj.getMonth() == '10') //thanksgiving (add two to compensate for day after)
			dayCompensation = 2;
		else if(dateObj.getDate() == '23' && dateObj.getMonth() == '10') //day after thanksgiving
			dayCompensation = 1;
		else if(dateObj.getDate() == '25' && dateObj.getMonth() == '11') //christmas
			dayCompensation = 1;
		}
	zstderr('day compensation for holiday = +'+dayCompensation)
	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 adjustedDate=new Date(SERVERTIME);  //a local var handling and changing the date.

//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(SERVERTIME); //reset adjusted date to myDate and add latency and adjustedLatency.
	var isTodayAHoliday = checkIfHoliday(SERVERTIME); //is today a holiday?  0 for no. > 0 for yes.

	zstderr('adjusted latency = '+adjustedLatency);

	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
		}
	zstderr('ship date returned = '+weekday[adjustedDate.getDay()]+' '+(adjustedDate.getMonth()+1)+'/'+adjustedDate.getDate()+'/'+adjustedDate.getFullYear());
	return weekday[adjustedDate.getDay()]+' '+(adjustedDate.getMonth()+1)+'/'+adjustedDate.getDate()+'/'+adjustedDate.getFullYear();

	}



//pass in latency, either default or option specific. execute this function on page load and each time an inventory-able option select list is changed.
function displayShipInfo(latency,inv)	{

	if(latency === undefined)
		latency = DEFAULTLATENCY;

	zstderr('SERVERTIME = '+SERVERTIME);
	zstderr('DEADLINE = '+DEADLINE);
	zstderr('Hour of day = '+SERVERTIME.getHours());
	
 //Nuke any existing messages or clocks.
	$('.bamtar_ship_message').empty();
	$('.bamtar_ship_countdown').css('display','none');
	

	if(ISPREORDER == 1)	{
		zstderr('item is a preorder.');
		shipMessage = "<div class='invPreorder'></div>This item is a preorder and will ship on: "+handleDateFormat(SALESRANK);
		}
	else if(outofstock == true)		{
		zstderr('item(global inv) is a out of stock.');
		shipMessage = "<div class='invOutOfStock'></div>this item is currently out of stock.";
		}
	else if(inv < 1)		{
		zstderr('item(option) is a out of stock.');
		shipMessage = "<div class='invOutOfStock'></div>this item is currently out of stock.";
		}

	else if(latency > 1 )	{
		zstderr('latency > 1.');
		shipMessage = "<div class='invInStock'></div>Item normally ships in "+latency+" days. Expected ship date: "+getShipDate(latency);
		}
//if latency is greater than one, the fact that 'today' is a holiday isn't important here, it's handled in getShipDate.
	else if(checkIfHoliday(SERVERTIME) > 0 )	{
		zstderr('Today is a holiday.');
		shipMessage = "<div class='invInStock'></div>Due to holiday, the expected ship date is "+getShipDate(latency);
		}

	else if(SERVERTIME.getHours() > 13 && SERVERTIME.getDay() == 5)	{
		zstderr('it is a friday after 1pm PST.');
		shipMessage = "<div class='invInStock'></div>Item will ship on Monday";
		}
	else if(SERVERTIME.getDay() == 0 || SERVERTIME.getDay() == 6)	{
		zstderr('it is a saturday or a sunday.');
		shipMessage = "<div class='invInStock'></div>Item will ship on Monday";
		}
	

//will only get here if it is a monday - friday
	else if(SERVERTIME.getHours() < 14)	{
		zstderr("<div class='invInStock'></div>it is a monday through friday before 2pm PST.");
		$('.bamtar_ship_countdown').countdown({until: DEADLINE,compact: true,serverSync: serverTime}); //put a class of bamtar_ship_countdown on any element that needs the clock.
		$('.bamtar_ship_countdown').css('display','block');  //make sure clock is visible
		shipMessage = "<div class='invInStock'></div>Ships today if ordered in the next ";
		}
	else	{
		zstderr('else! should only get here if it is a monday thru thursday (non holiday) after 2pm PST');
		ad = getnewdate(1,DEADLINE); //Adjusted Deadline. don't change deadline because this function gets rerun.
		zstderr('adjusted deadline = '+ad);
		$('.bamtar_ship_countdown').countdown({until: ad,compact: true, serverSync: serverTime});
		$('.bamtar_ship_countdown').css('display','block');  //make sure clock is visible
		shipMessage = "<div class='invInStock'></div>Ships tomorrow if ordered in the next ";
		}

	$('.bamtar_ship_message').append(shipMessage); //update all tags with this class with shipping message.
	
	}



//Custom sogs


//jquery method for extending the class.
$.extend(handlePogs.prototype, {

	renderOptionCLICKTEXT_OVERRIDE:function(pog) {

	var pogid = pog.id;
	var parentDiv = document.getElementById('div_'+pogid);

	$('#pog_'+pogid+'_id').append("<span id='showValue_"+pogid+"' class='padRight20'></span>");


//output ? with hint in hidden div IF ghint is set
	if(pog['ghint'])
		gHintQmark(pogid,pog['ghint']);

	parentDiv.innerHTML += "<div class='clearAll'></div><div class='bottomMargin'></div>";

/* sog values are displayed only as thumbnails.  a hidden input is added to the dom and, onclick, the value of the sog is saved to the value of the hidden input */
	$('#addToCartFrm').append('<input type="hidden" value=""  name="pog_'+pogid+'" id="pog_'+pogid+'" />');
	
    var i = 0;
    var len = pog.options.length;
	var cssClass='';

//adds options to the select list.
    while (i < len) {
		cssClass = "invAvailable";
		pogInvAvail = 1; //reset var. default to inventory available. inv is checked multiple times, so it's saved to a var instead of being looked up repeatedly.
		if(typeof MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['inv'] != 'undefined')	{
			if(MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['inv'] < 1){
				cssClass = 'invUnavailable';
				pogInvAvail = false;
				}
			else	{
				pogInvAvail = MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['inv'];
				}
			}

		optionPrompt = pog['options'][i]['prompt'];

		zstderr(optionPrompt+' inventory = '+MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['inv']);
		parentDiv.innerHTML += "<div class='floatLeft sogClickText "+cssClass+"'><a href='#' onClick=\"$('#pog_"+pogid+"').val('"+pog['options'][i]['v']+"'); $('#showValue_"+pogid+"').empty().append('"+optionPrompt+"'); displayShipInfo('"+MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['zoovy:ship_latency']+"',"+pogInvAvail+"); return false;\" title='"+optionPrompt+"'>"+optionPrompt+"<\/a><\/div>";
		i++;
       }

	
	parentDiv.innerHTML += "<div class='clearAll'></div>";
	},  //end clicktext_override


	renderOptionCLICKIMAGE_OVERRIDE:function(pog) {

	var pogid = pog.id;
	var parentDiv = document.getElementById('div_'+pogid);

	$('#pog_'+pogid+'_id').append("<span id='showValue_"+pogid+"' class='padRight20'></span>");


//output ? with hint in hidden div IF ghint is set
	if(pog['ghint'])
		gHintQmark(pogid,pog['ghint']);

	parentDiv.innerHTML += "<div class='clearAll'></div><div class='bottomMargin'></div>";

/* sog values are displayed only as thumbnails.  a hidden input is added to the dom and, onclick, the value of the sog is saved to the value of the hidden input */
	$('#addToCartFrm').append('<input type="hidden" value=""  name="pog_'+pogid+'" id="pog_'+pogid+'" />');


    var i = 0;
    var len = pog.options.length;


//adds options to the select list.
    while (i < len) {
		cssClass = 'invAvailable';
		pogInvAvail = 1; //reset var. default to inventory available. inv is checked multiple times, so it's saved to a var instead of being looked up repeatedly.
		if(typeof MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['inv'] != 'undefined')	{
			if(MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['inv'] < 1){
				cssClass = 'invUnavailable';
				pogInvAvail = false;
				}
			else	{
				pogInvAvail = MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['inv'];
				}
			}

		optionPrompt = pog['options'][i]['prompt'];


//if the image is set, display a thumb. otherwise, display clickable text.
		if(typeof MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['zoovy:prod_image1'] != 'undefined')	{
			parentDiv.innerHTML += "<div class='sogClickImage'><div class='"+cssClass+"' title='"+optionPrompt+"'><a href='"+zoovyImageUrl(MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['zoovy:prod_image1'],'','','ffffff')+"' rel='click-to-initialize: true' rev='"+zoovyImageUrl(MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['zoovy:prod_image1'],330,400,'ffffff')+"' onClick=\"$('#pog_"+pogid+"').val('"+pog['options'][i]['v']+"'); $('#showValue_"+pogid+"').empty().append('"+optionPrompt+"'); displayShipInfo('"+MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['zoovy:ship_latency']+"',"+pogInvAvail+"); MagicZoomPlus.update('zoom1',this.href,this.rev); return false;\"><img src='"+zoovyImageUrl(MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['zoovy:prod_image1'],50,50,'ffffff')+"' height='50' width='50' alt='"+optionPrompt+"' border='0' \/><\/a><\/div><\/div>";
			}
		else	{
			parentDiv.innerHTML += "<div class='sogClickImage no_underline'><div class='"+cssClass+" sogClickImageNotSet' onClick=\"$('#pog_"+pogid+"').val('"+pog['options'][i]['v']+"'); $('#showValue_"+pogid+"').empty().append('"+optionPrompt+"'); displayShipInfo('"+MYADD2CART_sku[sku+':'+pogid+pog['options'][i]['v']]['zoovy:ship_latency']+"',"+pogInvAvail+"); return false;\" title='"+optionPrompt+"'>"+optionPrompt+"<\/div><\/div>";

			}
		i++;
       }

	
	parentDiv.innerHTML += "<div class='clearAll'></div>";
	},  //end clickimage_override

//used for switchplate covers.  displays options in a grid style with each option having a quantity box.

	xinit: function($super) {
		zstderr($super);
//		this.addHandler("pogid","P0","renderOptionSIMPLETHUMBNAIL_OVERRIDE");
//		this.addHandler("pogid","AP","renderOptionCLICKTEXT_OVERRIDE");
//		this.addHandler("type","select","renderOptionCLICKTEXT_OVERRIDE");
		this.addHandler("pogid","AO","renderOptionCLICKTEXT_OVERRIDE");
		this.addHandler("pogid","A0","renderOptionCLICKTEXT_OVERRIDE");
		this.addHandler("pogid","AN","renderOptionCLICKIMAGE_OVERRIDE");
		this.addHandler("pogid","B1","renderOptionCLICKIMAGE_OVERRIDE");
		}
	});
	


function doesNodeExist(node) {
    if (node == undefined)
		return false;
	else
		return true;
}




//modal for actually displaying the video.
function showVideo(vid)	{
	$('#prodPageVideo-'+vid).dialog({
		"width": 550,
		"modal": true
		});
	}

//pass in an array of youtube video ids and a thumb and hidden div is created for each. when the thumbnail is clicked, 'showVideo' function is executed.
function showVideoThumbs(a)	{
	tdiv = $('#prodPageVideoList'); //target div
	
	tdiv.append("<div class='zcolor_light' id='videoHeader'>Videos<\/div>");
	
	$.each(a,function()	{
		tdiv.append("<div class='prodPageVideoThumb pointer' style='position:relative; background-image:url(//i3.ytimg.com/vi/"+this+"/default.jpg);' onClick='showVideo(\""+this+"\"); return false;'><div class='prodPageVideoIcon'><\/div><\/div>");
		tdiv.append("<div id='prodPageVideo-"+this+"' class='prodPageVideoPlayer' title='Watch Video'><iframe title='YouTube video player' width='480' height='390' src='//www.youtube.com/embed/"+this+"' frameborder='0' style='width:480px; height:390px;' allowfullscreen></iframe><br \/><\/div>");
//		tdiv.append("<div id='prodPageVideo-"+this+"' class='prodPageVideoPlayer' title='Watch Video'><object width='480' height='390'><param name='movie' value='http://www.youtube.com/v/"+this+"?fs=1&amp;hl=en_US'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='http://www.youtube.com/v/"+this+"?fs=1&amp;hl=en_US' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='480' height='390'></embed></object></div>");
		
		});
	}


MagicZoomPlus.options = {
  'background-color':'#000000',
  'background-opacity':'50',
  'opacity-reverse':'true',
  'selectors-mouseover-delay':'0'
 }

MagicThumb.options = {'click-to-initialize':'true',  'background-color':'#000000',
  'background-opacity':'50'}
  
function removeSpecialChars(strVal)     {
       spacefix = / /gi;
       strVal = strVal.replace(/[^a-zA-Z 0-9]+/g,'');
       strVal = strVal.replace(spacefix,'-');
       return strVal;
       }  
