/* DEPTSKU 2 PAGE - HOMEPAGE */	
var activeProduct = "";
var activeDepartmentIndex = "";

/* Kickoff function - draws tabs and starts display of first department*/
function draw_tabs() {
	//get all sub departments and draw tabs in order for each sub dept
	var tabOutput = "<ul>";	
	for(sd=0; sd<dept_depts.length; sd++)
	{		
		tabOutput += "<li><a onClick=\"DisplayDeptDetail('"+sd+"',true); return false;\" href=\"javascript:;\" class=\"actuator\"><img id=\"HomeTab_"+sd+"\" src=\"assets/images/zinnia/HomeTabs/HomeTab_"+sd+".gif\" alt=\""+dept_depts[sd].dept_name+"\" /></a></li>";
	}	
	tabOutput += "</ul>";
	
	//write tabs to div
	document.getElementById("HomepageTabs").innerHTML = tabOutput;
	
	//activate first department initially
	DisplayDeptDetail(0);
}

/* Shows active dept tab and resets all other tabs to non-active state */
function activateDeptTab(theDeptIndex)
{
	for(sd=0; sd<dept_depts.length; sd++)
	{
		if(sd == theDeptIndex) document.getElementById("HomeTab_"+sd).src = "assets/images/zinnia/HomeTabs/HomeTab_"+sd+"Over.gif";
		else document.getElementById("HomeTab_"+sd).src = "assets/images/zinnia/HomeTabs/HomeTab_"+sd+".gif";
	}
}

/* Displays all the information for the selected department including the product detail for the first product*/
var cycler=0;
function DisplayDeptDetail(theDeptIndex,stopTimer) {			

	if(typeof stopTimer == "undefined") stopTimer = false;
	
	//if a number greater than the number of depts is passed in, reset to 0
	if(theDeptIndex>=dept_depts.length) theDeptIndex = 0;
	
	//show rolled out dept tab
	activateDeptTab(theDeptIndex);
		
	
	//if there are products in this department...
    if(dept_depts[theDeptIndex].attached_products.length>0){
		//clear out anything that may be showing already
		document.getElementById("HomepageDeptProductSection").innerHTML = "";
		
		//display dept name
		document.getElementById("HomepageDeptName").innerHTML = dept_depts[theDeptIndex].dept_name;
		document.getElementById("HomepageDeptName").style.display = "block";
	
		//display first product's image
		showActiveProductImage(dept_depts[theDeptIndex].attached_products[0].pf_id);
	
		//show first product in this dept as active product
		//document.getElementById("HomepageDeptProductSection").innerHTML = '<IFRAME SRC="product.asp?s_id='+i_jscript_uu_sid+'&dept_id='+dept_depts[theDeptIndex].dept_id+'&pf_id='+dept_depts[theDeptIndex].attached_products[0].pf_id+'&px_id=69" TITLE="Title" width="369" height="170" border="0" frameborder="0" scrolling="no" id="product_details" hspace="0" marginWidth="0"></IFRAME>';
		getProdInfo(dept_depts[theDeptIndex].attached_products[0].pf_id);
		
		//see show more link
		//if(dept_depts[theDeptIndex].attached_products.length>5){
			document.getElementById("HomepageSeeMore").innerHTML = '<a href="dept.asp?dept_id='+dept_depts[theDeptIndex].dept_id+'" onClick="return(visitargs(\'dept.asp\',\'dept_id='+dept_depts[theDeptIndex].dept_id+'\',\'URL\'));"><img src="assets/images/zinnia/HomePromotions/HomePromotionSeeMore.gif" /></a>';
			document.getElementById("HomepageSeeMore").style.display = "block";
		//} else {
		//	document.getElementById("HomepageSeeMore").innerHTML = '<img src="assets/images/spacer.gif" height="34">';
		//}
	
		//draw product listing for this dept
		document.getElementById("HomepageDeptProductListing").innerHTML = display_products_gen(dept_depts[theDeptIndex].attached_products);
		document.getElementById("HomepageDeptProductListing").style.display = "block";
	
		//set the active department index
		setActiveDepartment(theDeptIndex);
		
		//set the first product as active
		setActiveProduct(dept_depts[theDeptIndex].attached_products[0].pf_id);		
		
	} else { //no products to show in this department
		//clear dept name
		document.getElementById("HomepageDeptName").innerHTML = "";
		document.getElementById("HomepageDeptName").style.display = "none";
		
		//hide any product image
		document.getElementById('HomepagePromotion').style.backgroundImage = "none";
				
		//hide show more link
		document.getElementById("HomepageSeeMore").innerHTML = "";
		document.getElementById("HomepageSeeMore").style.display = "none";
		
		//hide product thumbs
		document.getElementById("HomepageDeptProductListing").innerHTML = "";
		document.getElementById("HomepageDeptProductListing").style.display = "none";
		
		//set the active department index
		setActiveDepartment(theDeptIndex);
		
		//show dept description
		document.getElementById("HomepageDeptProductSection").innerHTML = "<span style='margin:0px 0px 0px 0px; padding:0px 0px 0px 0px;'>" + dept_depts[theDeptIndex].dept_short_description + "</span>";	
	}
	
	if(!stopTimer){		
		//cycle to next dept after some time
		var theNextDI = parseInt(theDeptIndex)+1;
		cycler = setTimeout('DisplayDeptDetail('+theNextDI+')', 10000);	
	} else {
		//stop the cycle
		clearTimeout(cycler);
      	cycler = 0;
	}
}


//change which product is displaying
function DisplayProductDetail(theDept_id, thePf_id){		
	//change product details
	//document.getElementById('product_details').src = 'product.asp?s_id='+i_jscript_uu_sid+'&dept_id='+theDept_id+'&pf_id='+thePf_id+'&px_id=69';
	getProdInfo(thePf_id);
	
	//change bg image
	showActiveProductImage(thePf_id)
	
	setActiveProduct(thePf_id);
	
	return false;
}

//changes the bg image to the active product's image
function showActiveProductImage(thePf_id)
{
	document.getElementById('HomepagePromotion').style.backgroundImage = "url(Assets/product_images/"+thePf_id+"_3.jpg)";
}

//set which product is being displayed
function setActiveProduct(id){
	activeProduct = id;
	if(document.getElementById('productThumb' + id))
		document.getElementById('productThumb' + id).className='HomepageThumbActive';
	clearNonActiveProducts();
}

//which department index is the current dept index
function setActiveDepartment(deptIndex){
	activeDepartmentIndex = deptIndex;
}

function clearNonActiveProducts(){
	if(dept_depts[activeDepartmentIndex].attached_products.length>0) {
		//show up to 5 products
		var stoppingPoint = 5;
		
		//show all products if there are 5 or less
		if(dept_depts[activeDepartmentIndex].attached_products.length<5) stoppingPoint = dept_depts[activeDepartmentIndex].attached_products.length;
		
		//go through all products and set their className='HomepageThumb'	
		for(ap=0; ap<stoppingPoint; ap++) {
			if(document.getElementById('productThumb' + dept_depts[activeDepartmentIndex].attached_products[ap].pf_id) && dept_depts[activeDepartmentIndex].attached_products[ap].pf_id != activeProduct)
				document.getElementById('productThumb' + dept_depts[activeDepartmentIndex].attached_products[ap].pf_id).className='HomepageThumb';
		}
	}
}

function display_products_gen(Dept_products_gen,p_display_type){ 
	
	var deptProdOutput = "";
	
	if (p_display_type==null){p_display_type=display_type;}
	if (Dept_products_gen.length >= 1){
		var n_product=0;
		var atn;      				
		
		//show up to 5 products
		var stoppingPoint = 5;
		
		//show all products if there are 5 or less
		if(Dept_products_gen.length<5) stoppingPoint = Dept_products_gen.length;
						
		
		for (atn=0;atn<stoppingPoint ;atn++){			
			if (page_option_5==1){				
								
				//product image				
				deptProdOutput += '<a href="#" onClick="DisplayProductDetail(\''+Dept_products_gen[atn].dept_id+'\',\''+Dept_products_gen[atn].pf_id+'\'); return false;"><img src="assets/product_images/'+Dept_products_gen[atn].pf_id+'_5.jpg" alt="'+Dept_products_gen[atn].pf_id+' - '+Dept_products_gen[atn].name+'" border="0" onError="this.src=\'Assets/images/spacer.gif\';" id=\"productThumb'+Dept_products_gen[atn].pf_id+'\" class=\"HomepageThumb\" width=\"58\" /></a>';
				
			} //end if page_option_5
		} //end for loop				
		
		deptProdOutput += "<img src=\"Assets/images/spacer.gif\" width=\"18\">";
		
	} //end if
	
	return(deptProdOutput);
} //end display_products_gen


/**
 * Calls the ajax request for product data
 * @param{string} pf_id is sent in the POST to specify which product's data we're requesting
 **/
var prodObj = null;
var isIE6 = (window.ActiveXObject)? true : false;
function getProdInfo_old(pf_id){
	if (!isIE6) { // iIE7, Mozilla, Safari, ...
		prodReq = new XMLHttpRequest();
		isIE6 = false;
	} else{ // IE6, below
		prodReq = new ActiveXObject("Microsoft.XMLHTTP");
		isIE6 = true;
	}

	/* determine page protocol */  
	var myTemp = window.location.href;  
	var tempSplit = myTemp.split(":");  
	var pageProt = tempSplit[0];  
	  
	prodReq.open('GET', document.location.protocol+'//'+document.location.hostname+'/enww/product_json.asp?pf_id='+pf_id+'&inventory=1', false);
	  
	prodReq.setRequestHeader('Content-type', 'application/xml');
	prodReq.onreadystatechange = function(){productCallback();}	// specify our callback function
	prodReq.send(null);
}


function getProdInfo(pf_id){

	var oXMLHttp = null; 	
	if (window.XMLHttpRequest) { // IE7, Mozilla, Safari, ...
		oXMLHttp = new XMLHttpRequest();
		isIE = false;	// *see note at top of code for this var
	} else if (window.ActiveXObject) { // IE6, below
		oXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
		isIE = true;
	}
	
	oXMLHttp.onreadystatechange = 
		function(){
			if(oXMLHttp.readyState == 4){	// 4 = complete
				if(oXMLHttp.status == 200) //200 = ok status
				{
					prodObj = eval('(' + oXMLHttp.responseText + ')');
					//document.getElementById("product_"+pf_id).innerHTML=oXMLHttp.responseText;
					//alert(oXMLHttp.responseText);					
					//document.write(oXMLHttp.responseText);
					showProd(prodObj);	// call function to display product					
				}
			}
			else {
				
				// So IE won't throw an error
				return false;
			}
		}
		
	oXMLHttp.open('GET', 'product_json.asp?pf_id='+pf_id+'&inventory=1', true);  
	oXMLHttp.send(null);
	
}

/**
 * Callback function called in getProdInfo, catches errors or bad statuses that may be returned
 **/
function productCallback(){
	try{
		if(prodReq.readyState == 4){	// 4 = complete
			prodObj = eval('(' + prodReq.responseText + ')');	// parse returned json object for our javascript to read
			showProd();	// call functino to display product /quickview window
			if (prodReq.status !=200) {
				alert('status != 200');
				return;
			}
		}
		else {
			// So IE won't throw an error
			return;
		}
	}catch(e){
		// improperly formed json
	}

}

/**
 * Populates and displays the quickview window for selected product
 **/
function showProd(){
	
	// set "global vars" from product.js onto the json object instead
	prodObj.num_avail = false;	// make a num_avail in place of missing one	
	
	//holds the product display to be written to action div
	var actionMarkup = "";
	
	// begin form that will add product to basket
	actionMarkup += "<div style='width: 350px; height: 170px; float:right; padding:0px 19px 0px 0px;text-align:left;'><FORM METHOD=POST NAME=\"form2\" ACTION=\"" + i_jscript_uu_rootURL + "shopper_lookup.asp\" onsubmit=\"return checkSku();\">";
	actionMarkup += "<input type=hidden name=target id=target value=\"xt_orderform_additem.asp\">";
	actionMarkup += "<INPUT TYPE=HIDDEN NAME=\"auto_reg\" VALUE=\"1\">";
	actionMarkup += "<INPUT TYPE=HIDDEN NAME=s_id VALUE=" + i_jscript_uu_sid + " >";	
	actionMarkup += "<input type=hidden name=qty value=1>";
	if (user_guid !=' '){
		actionMarkup += "<INPUT TYPE=HIDDEN NAME=mscssid VALUE=" + user_guid + " >";
	}

	actionMarkup += "<INPUT TYPE=HIDDEN NAME=wish_id VALUE=" + GetParamterValueQv("wish_id") + " >";
	actionMarkup += "<INPUT TYPE=HIDDEN NAME=order_sid VALUE=" + GetParamterValueQv("order_sid") + " >";
	actionMarkup += "<INPUT TYPE=HIDDEN NAME=so_number VALUE=" + GetParamterValueQv("so_number") + " >";
	actionMarkup += "<INPUT TYPE=HIDDEN NAME=pf_id VALUE=" + prodObj.pf_id + " >";
	//actionMarkup += "<INPUT TYPE=HIDDEN Name=returnpath Value=\""+document.location.pathname+document.location.search+"&addfrom=qv\" >";
	
	//name
	actionMarkup += '<div id="product_detail_name">'+prodObj.name+'</div>';
	actionMarkup += '<div class="thinline"></div>';
	
	//short desc
	actionMarkup += '<div id="product_detail_desc">'+prodObj.short_description+'</div>';
	
	//options
	actionMarkup += '<div id="product_detail_options"><div class="BasketErrors" id="qv_error"></div><table id="tblOptions" cellspacing="0" cellpadding="0" border="0">'+draw_sku_option_qv()+'</table></div>';
	
	//price
	actionMarkup += '<div id="product_detail_price">';
	actionMarkup += ( prodObj.on_sale == "true") ? "<font class='ListPricewSale'>"+prodObj.list_price_str+"</font><br><font class='SalePrice'>Sale Price&nbsp;"+prodObj.sale_price_str+"</font>" : "<font class='ListPricewoSale'>"+prodObj.list_price_str+"</font>";
	actionMarkup += '</div><div class="thinline"></div>';

	//buttons
	actionMarkup += '<div style="text-align:right; vertical-align: top; max-height: 20px;"><a href="product.asp?pf_id='+prodObj.pf_id+'" onClick="return(visitargs(\'product.asp\',\'pf_id='+prodObj.pf_id+'\',\'URL\'));" target="_parent"><img src="assets/images/zinnia/HomePromotions/HomePromotionActionLinks_ViewDetails.gif" style="DISPLAY: inline; VERTICAL-ALIGN: text-top"></a>';

	if (prodObj.enable_basket==1){
		actionMarkup += '<img src="assets/images/zinnia/HomePromotions/HomePromotionActionLinks_Divider.gif" style="DISPLAY: inline; VERTICAL-ALIGN: text-top">';
		actionMarkup += "<INPUT TYPE=Image  NAME=\"pbasket\" id=\"btnAddButton\" SRC=\"assets/images/zinnia/HomePromotions/HomePromotionActionLinks_AddToCart.gif\" BORDER=0 ALT=\"Add to cart\" vspace=\"0\" hspace=\"0\" style=\"DISPLAY: inline; VERTICAL-ALIGN: text-top\">";
	}
	
	if (prodObj.enable_wish==1){
		actionMarkup += '<img src="assets/images/zinnia/HomePromotions/HomePromotionActionLinks_Divider.gif" style="DISPLAY: inline; VERTICAL-ALIGN: text-top">';
		actionMarkup += '<INPUT TYPE="Image" NAME="wbasket" id="WishListButton" SRC="assets/images/zinnia/HomePromotions/HomePromotionActionLinks_AddToWishlist.gif" BORDER="0" ALT="Add to wish list" vspace="0" hspace="0" style="DISPLAY: inline; VERTICAL-ALIGN: text-top">';
	}
	actionMarkup += '</div>';
	
	actionMarkup += "</FORM></div><br class='clear'>";// end the form

	document.getElementById("HomepageDeptProductSection").innerHTML = "";
	document.getElementById("HomepageDeptProductSection").innerHTML = actionMarkup;	
}


/**
 * make sure a product sku has been selected from dropdown before adding to basket
 * @param{boolean} onchange is a flag that is set to true if being called from the sku dropdown onchange event
 */
function checkSku(onchangeFlag){
	var qvErr = document.getElementById('qv_error');
	var skuSelect;
	if(document.getElementById('sku')){skuSelect = document.getElementById('sku');}	// only grab the sku select dropdown if it exists on the page

	if(onchangeFlag){	// only do this stuff if being called from the select box onchange
		if(skuSelect.value != ""){
			qvErr.style.display = "none";
		}
		return;
	}else{
		if(skuSelect){
			if(skuSelect.value == ""){	// only do this stuff if being called from the form2 onsubmit
				qvErr.style.display = "block";
				//qvWin.style.height = (winHeight + 40) + "px";
				return false;
			}else{
				qvErr.style.display = "none";
				return true;
			}
		}else{
			// if there is no sku select
			qvErr.style.display = "none";
			return false;
		}
	}
}


/* draws the sku dropdown */
/**
 * Returns true if 'e' is contained in the array 'a'
 * @author Johan Känngård, http://dev.kanngard.net
 */
function contains(a, e) {
	if(a!=null)
		for(j=0;j<a.length;j++)if(a[j]==e)return true;
	return false;
}

function draw_sku_option_qv()
{	
	// set differences in vars		
	var product_var = prodObj.Items;
	
	var attr_label = new Array();
	attr_label[0] = prodObj.attr_label1;
	attr_label[1] = prodObj.attr_label2;	
	
	var skuMarkup = "";
	var num_avail = 0;
	var dropdownattr1 = "";
	var attrname = "";
	var dropdown_label="";
	if (product_var.length >= 1 ){
		if(product_var.length==1){			
			//skuMarkup += '<TR><td class="ProductPropertyLabel" align="left" valign="top">' + attr_label[0] + ':</TD>';
			//skuMarkup += '<td class="ProductProperty" align="left" valign="top">' + product_var[0].attr_value1 + '</TD></TR>';
			//if(attr_label[1]!=""){
			//	skuMarkup += '<TR><td class="ProductPropertyLabel" align="left" valign="top">' + attr_label[1] + ':</TD>';
			//	skuMarkup += '<td class="ProductProperty" align="left" valign="top">' + product_var[0].attr_value2 + '</TD></TR>';
			//}
			//skuMarkup += "<TR><TD colspan=2>" + product_var[0].avail_msg;
			skuMarkup += "<INPUT TYPE=HIDDEN id=\"sku\" NAME=\"sku\" VALUE=\"" + product_var[0].sku + "\" >";
			//skuMarkup += "</TD></tr>";
		}else{	

			skuMarkup += "<tr>";
			skuMarkup += '<td class="ProductPropertyLabel" align="left" valign="top"></td>';
			skuMarkup += '<td class="ProductProperty" align="left" valign="top">';
									
			skuMarkup += "<SELECT class=\"\" NAME=\"sku\" id=\"sku\">";
			i=0;
			labelstr= "Select Color/Size";/*"-- select ";
			while (attr_label[i]!= "" && i < attr_values.length ) {
				labelstr=labelstr + attr_label[i] + " ";
				i++;
			}
			labelstr+="--";*/
			writeoption_qv("",labelstr ,'');
			
			var separator=" - ";
			
			for (var atn=0;atn< product_var.length ;atn++){
				//empty separator if secdond attr is empty
				if(product_var[atn].attr_value2=="") separator="";
				
				//draw options
				if (prodObj.useVariantPrice=="True"){
					if(product_var[atn].avail!=0){
						if (prodObj.on_sale=="True"){
							skuMarkup += writeoption_qv(product_var[atn].sku,(product_var[atn].attr_value1 + separator + product_var[atn].attr_value2 + " - $"+ OKStrOfPenny(product_var[atn].price_sale)) + "" ,'');
						}else{
							skuMarkup += writeoption_qv(product_var[atn].sku,(product_var[atn].attr_value1 + separator + product_var[atn].attr_value2 + " - $"+ OKStrOfPenny(product_var[atn].price_list)) + "" ,'');
						}
					}
					
				}else{
					if(product_var[atn].avail!=0){
						if (product_var[atn].avail_msg==""){
							product_var[atn].avail_msg="on back order";
						}
						skuMarkup += writeoption_qv(product_var[atn].sku,(product_var[atn].attr_value1 + separator + product_var[atn].attr_value2) + "",'');
					}
				}
			}//end for
			skuMarkup += "</SELECT></TD>";	
			skuMarkup += "</TR>";
		}//end else
	}//end if
	
	return skuMarkup;
} //end draw_sku_option

function writeoption_qv(option,display,select){
	var optMarkup = "";
	if (select==option){selected=" SELECTED";}else{selected="";}
	option=String(option);
	option=option.replace(/'/g,"&#39;");
	optMarkup += "<OPTION Value='"+option+"'"+ selected +">"+ display + "</option>";
	return optMarkup;
}

function GetParamterValueQv(ParameterName)
{
var EQUAL = "=";
var AMP = "&";
var QUE = "?";
var EMPTY = "";
var url = window.document.URL.toString();
if (url.indexOf(QUE) > 0 ) {
var Parameters = url.split(QUE)[1].split(AMP);

	for (i = 0; i < Parameters.length; i++ ){
		if (Parameters[i].indexOf(EQUAL) > 0 ){
		var ParameterValue = Parameters[i].split(EQUAL);

		if (ParameterValue[0]== ParameterName ) {
		return ParameterValue[1];
		}
		}
	}
}
return EMPTY;
}


/* function called to share product with a friend*/
function shareproduct(PageURL,args,SURL,apf_id,aimage,aproduct_name)
{
	if(typeof apf_id == "undefined") apf_id = pf_id;
	if(typeof aimage == "undefined" && product_image[0].image) aimage = product_image[0].image;
	if(typeof aproduct_name == "undefined") aproduct_name = product_name;
	
	var plink;
	var emailbody;
	var url;
	if (args.indexOf("=")<0 ||args.indexOf("&")<0 ){
		args="";
	}
	if (user_guid !=' ')
	{		
		PageURL =PageURL + '?mscssid='+ user_guid+ '&pf_id='+apf_id+ '&'+ args ;
	}else{
		PageURL =PageURL + '?pf_id='+apf_id+ '&'+ args ;
	}
	
	plink=i_jscript_uu_rootURL+"product.asp?pf_id="+ apf_id +"&" ;
	emailbody = "Dear #RecipientName#,<BR><br>#Text_field_3#<BR><BR>I found this. <BR><A HREF=#URL#>Click here</a> to check it out <BR>or cut-n-paste this link into your browser:<BR><BR><A HREF=#URL#>#URL#</a><BR><BR> #FromName#<BR> #FromEmail#";
	/*emailbody="Dear #RecipientName#,<BR> #Text_field_3# <BR><BR>";
	if (aimage!=""){
		emailbody = emailbody + "<A HREF=\"#URL#\"><img src=\""+i_jscript_uu_rootURL+"assets/product_images/"+aimage+"\" border=0 alt=\""+ aproduct_name+"\"></a>";
	}
	emailbody = emailbody + "<A HREF=\"#URL#\">"+ aproduct_name + "</a><BR>" ;
	emailbody = emailbody + "from #FromName# at <A href=\"mailto:#FromEmail#\">#FromEmail# <BR>" ;*/
	window.location=PageURL +"referer="+escape(plink)+"&email_body="+escape(emailbody)+"&target="+ escape(window.location.href)+"&";
	//Note: This return is required as well
	// false tells the browser to ignore the default action entirely
	//usage Click Here II
	return(false);
} //end shareproduct