/** editor:cls, date:18.DEC.2007 
 * This Quickview javascript references the following HTML which is placed on the page directly wherever this js is used. This is the 'shell' html of the quickview popup window
 * It must be on the page before quickview.js is included
 * Also note that extra code is needed to include the quickview icon on the page
 *
 * <!-- begin feature: quickview -->
 * <iframe id="qv_iframe" style="height:510px;width:400px;z-index:9999979;position:absolute;top:150px;left:200px;visibility:hidden;"  src="assets/images/blank.html" ></iframe>
 * <div id="qv_window" style="width:450px;height:525px;position:absolute;background:#FFFFFF;padding:8px;z-index:9999980;visibility:hidden;">
 * 	<a id="closebtn" href="javascript:void(0)" onclick="closeProd(this);" style="font-weight: bold; float: right;">close [x]</a>xxx
 * 	<br/>
 * 	<div id="qv_error" class="ErrorMsg"></div>
 * 	<div id="qv_action"></div>
 * </div>
  * <script type="text/javascript" language="javascript" src="assets/images/includes/quickview.js"></script>
 * <!-- end feature: quickview -->
 *
 *<!-- begin popup feature - this calls the quickview window to open up - put this div on each product that gets shown on the page-->
 *<!-- notice on the function calls we are sending it the pf_id of whatever product we are doing the quickview on -->
 *<div class="qv-wrapper"><img onmouseout="hideQVIcon('qvicon_PF_ID_HERE');" onclick="getProdInfo('PF_ID_HERE');" onmouseover="popQVIcon('qvicon_PF_ID_HERE');" id="qvicon_PF_ID_HERE" style="visibility: hidden;" class="qvicon" src="assets/images/qvicon.gif"/></div>
 *<!-- end popup feature -->
 * add to product thumbs
 * onmouseover="popQVIcon('qvicon_PF_ID_HERE');"
 * onmouseout="hideQVIcon('qvicon_PF_ID_HERE');"
*/

/* JAT 8/3/07 - this is a new version of quickview.js  */
var prodReq, prodObj;								// prodReq holds the request object and prodObj holds the returned json object
var isIE = ((navigator.appName) == "Microsoft Internet Explorer")? true : false;	// need this for determining popup positioning
var isIE6 = (window.ActiveXObject)? true : false;	// need this for ajax stuff and whether to display an iframe behind popup
var qvWin = document.getElementById('qv_window');
if(isIE6){var qvIFrame = document.getElementById('qv_iframe');}	// to prevent select dropdowns from bleeding through the div
var qvErr = document.getElementById('qv_error');				// holds message to user if they haven't chosen a sku from dropdown to add to basket
var qvAction = document.getElementById('qv_action');			// holds the product form and action buttons (add to cart, wish, view cart)
//var qvLoader = document.getElementById('qv_loader');			// (moosejaw specific) animated gif for loading
var winHeight = 0;

/**
 * Displays the quick view icon when user rolls over the product image
 * @param{string} pf_id is used to find the id of the quickview icon image on the page.
 **/
function popQVIcon(qv_id){
	var qvicon = document.getElementById(qv_id);
	qvicon.style.visibility = "visible";
	qvicon.style.cursor = "pointer";
	qvicon.parentNode.display = "block";
	//qvicon.parentNode.visibility = "visible";
}

/**
 * Hides the quick view icon when user rolls off the product image
 * @param{string} pf_id is used to find the id of the quickview icon image on the page.
 **/
function hideQVIcon(qv_id){
	document.getElementById(qv_id).style.visibility = "hidden";
}

/**
 * Populates and displays the quickview window for selected product
 add in new image paths and http://s7d2.scene7.com/is/image/Masseys/ for prod images **/
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

	// check if object has product info before going through all the display stuff
	if(!prodObj.pf_id){
		// in the rare case there is no product info returned - display a message to user & clear out quickview popup
		qvWin.style.height = "300px";
		if(isIE6){qvIFrame.style.height = "300px";}
		qvErr.innerHTML = "Sorry, product information is unavailable at this time.";
		return;
	}else if(prodObj.Items.length <= 0){	// if product comes back with no items
		qvWin.style.height = "300px";
		if(isIE6){qvIFrame.style.height = "300px";}
		qvErr.innerHTML = "Sorry but this product is sold out.";
		return;
	}	
	
	
	//holds the product display to be written to action div
	var actionMarkup = "";
	
	// begin form that will add product to basket
	actionMarkup += "<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\" >";
	
	actionMarkup += '<table align=\"left\" width="390" height=310 border="0" cellspacing="0" cellpadding="0">';
		
		//product name 
		actionMarkup += '<tr><td colspan=\"2\" valign="top" align="left"><div class="qv_ProductName">'+prodObj.name+'</div></td></tr>';
		
		// BEGIN LEFT SIDE
		actionMarkup += '<tr valign=top><td width=\"200\" align=\"left\">';
		//display main image with link to product
		actionMarkup += "<a href=\"product.asp?pf_id=" + prodObj.pf_id + "&\" onclick=\"return(visitargs('product.asp','pf_id=" + prodObj.pf_id + "&','URL'));\"><img id='prod_img' BORDER=0  VSPACE=0  width=200 HSPACE=0 ALT=\"" + prodObj.name + "\" title=\"" + prodObj.name + "\" src=\""+imgURLpre+prodObj.pf_id +"\"  onError=\"this.src='assets/images/spacer.gif';\"></a>";		
		actionMarkup += '</td><td style=\"text-align:left;\"><br/><br/>';
		
		// BEGIN RIGHT SIDE
		//display price
		// check onsale flag to see if sale price should be displayed.		
		actionMarkup += ( prodObj.on_sale == "true") ? "<span class='ListPricewSale'>Regular Price&nbsp;"+prodObj.list_price_str+"</span>&nbsp;<span class='SalePrice'>ON SALE!&nbsp;"+prodObj.sale_price_str+"</span>" : "<span class='ListPricewoSale'>Price&nbsp;"+prodObj.list_price_str+"</span>";			
			
		//display sku and qty dropdowns
		actionMarkup += '<br/><br/>'+draw_sku_option_qv();	
		
		// add to cart button
		if (prodObj.enable_basket==1 && prodObj.num_avail){		
			actionMarkup += '<br/><INPUT TYPE=Image  NAME="pbasket" SRC="assets/images/qvImages/qv_add2Cart.gif" BORDER=0 ALT="Add to your shopping cart">';
		};
		
		//REMOVED ADD TO WISH 
		//if (prodObj.enable_wish==1 && prodObj.num_avail){		// add to wish basket button
			// actionMarkup += '<br><INPUT TYPE=Image  NAME="wbasket" SRC="assets/images/btnaddwish.gif" BORDER=0 ALT="Add to your wish cart">';
		//}
		
		//product detail link
		actionMarkup += "<table style=\"padding:5px 0px;margin:13px 0px;border-top:1px solid #CCCCCC;border-bottom:1px solid #CCCCCC;\" cellspacing=\"0\" cellpadding=\"0\"><tr valign=\"top\"><td><a href=\"product.asp?pf_id=" + prodObj.pf_id + "&\" onclick=\"return(visitargs('product.asp','pf_id=" + prodObj.pf_id + "&','URL'));\"><img src=\"assets/images/qvImages/qv_seeDeets.gif\" alt=\"See Details\" border=\"0\" align=\"left\"></a></td>";

		actionMarkup += "<td><a href=\"javascript:shareproduct('share_new.asp','none','SURL','"+prodObj.pf_id+"','"+prodObj.image_file+"','"+escape(prodObj.name)+"');\"><img src=\"assets/images/qvImages/qv_send2friend.gif\" alt=\"Email This to a Friend\" border=\"0\" align=\"right\" style=\"\"></a></td></tr></table>";

	// right side description
    /** decription length checker -cls  **/
    var printableDescr = ""; // var to hold what will be printed as description
    
    //if no short description replace with long descr
    if (prodObj.short_description == "<BR>" ) 
    {
    
           // check to confirm prod descr Does NOT have default text 
          if(prodObj.description.indexOf("1972") == -1) 
          {        
            // if long description really long 
             if (prodObj.description.length > 320) {
             
               //  then substring it to shorten it and append elipse "..."  store in var            
                printableDescr = prodObj.description.substring(0,300) + "...  ";
              } else {
                  //else if no short descr and long descr not tooo long store in var
                   printableDescr = prodObj.description;
              }
           }
    } else {
        // there is a short descr !! yeah, so store that 
        printableDescr = prodObj.short_description;
    }
    //alert("UU tests do not be alarmed \n"+ prodObj.description.indexOf("1972"));
     //print out result of above          
    actionMarkup += '<br/><span class="qv_descr">'+ printableDescr +'</span>';
	actionMarkup += "</FORM><br class='clear'>";// end the form

	qvAction.innerHTML = actionMarkup;	// put form, add to cart, add to wish basket, view cart buttons inside div
	
	winHeight = 600;
	//make height 215 + height of image
	if(document.getElementById("prod_img"))
	{
		var img = document.getElementById("prod_img");
		winHeight = img.height;
	}
	
	// re-set the popup's height
	//qvWin.style.height = winHeight + "px";
	qvWin.style.height = "auto";
	
	if(isIE6){	// make iframe visible if IE
		//qvIFrame.style.height = winHeight + "px";
		qvIFrame.style.height = (winHeight + 80) +"px";
		//qvIFrame.style.left = ((document.body.clientWidth / 2) - 235) + "px";
		//qvIFrame.style.top = (document.documentElement.scrollTop + 50) + "px";
		qvIFrame.style.display = "block";
		qvIFrame.style.visibility = "visible";
		qvIFrame.style.zIndex = "9999979";
	}

	//qvLoader.style.display = "none";	// hide loader animation	
	qvWin.style.visibility = "visible";	// finally display the product quickview popup on the page
}


/**
 * 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
 **/
function getProdInfo(pf_id){
	if(qvWin.style.visibility == "visible"){closeProd(qvWin.firstChild);}
	// set the popup positioning
	if(isIE6){		// ie6
		qvIFrame.style.left = ((document.body.clientWidth / 2) - 235) + "px";
		qvIFrame.style.top = (document.documentElement.scrollTop + 50) + "px";
		qvWin.style.left = qvIFrame.style.left;
		qvWin.style.top = qvIFrame.style.top;
	}else if(isIE){	// ie7
		qvWin.style.left = ((document.body.clientWidth / 2) - 235) + "px";
		qvWin.style.top = (document.body.scrollTop + 50) + "px";
	}else{			// ff + others
		qvWin.style.left = ((document.body.scrollWidth / 2) - 235) + "px";
		qvWin.style.top = (window.pageYOffset + 50) + "px";
	}

	// display the popup window with a 'loading' message to user until the product info has been loaded
	//qvLoader.style.display = "block";
	qvWin.style.visibility = "visible";
	if(isIE6){qvIFrame.style.display = "block";}

	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];  
	  
	/* determine correct path to use based on protocol (http vs https)  */  
	switch (pageProt)  {  
	  case "http":  
	    prodReq.open('GET', i_jscript_uu_rootURL+'product_json.asp?pf_id='+pf_id, true);
	    break;  
	  case "https":  
	    prodReq.open('GET', i_jscript_uu_rootSURL+'product_json.asp?pf_id='+pf_id, true);
	    break;  
	}

	prodReq.setRequestHeader('Content-type', 'application/xml');
	prodReq.onreadystatechange = function(){productCallback();}	// specify our callback function
	prodReq.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
	}

}

/**
 * Closes and clears out the product quickview window
 **/
function closeProd(win){
	// clear out divs
	qvErr.style.visibility = "hidden";	
	qvAction.innerHTML = "";	
	win.parentNode.style.visibility = "hidden";		// hide quickview popup
	if(qvIFrame){qvIFrame.style.display = "none";}	// hide iframe
}

/**
 * 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 skuSelect;
	if(document.getElementById('sku')){skuSelect = document.getElementById('sku');}	// only grab the sku select dropdown if it exists on the page
	//test
	//alert("UU testing do not be alarmed 1) "+skuSelect.value);
	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 ){
		prodObj.num_avail = true;
		if(product_var.length==1){
			skuMarkup += "<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0>";
			skuMarkup += "<TR VALIGN=TOP ><TD class=ProductAttrlabel >" + attr_label[0] + "</TD><TD>";
			if (product_var[0].avail != "0") {
				num_avail=1;
				skuMarkup += "&nbsp;" + product_var[0].attr_value1;
			} else 
			{
				skuMarkup += "<BR>Sorry but this product is not available.";
			
			}
			skuMarkup += "<INPUT TYPE=HIDDEN id='sku' NAME='sku' VALUE=\"" + product_var[0].sku + "\" >";
			skuMarkup += "</td></TR></TABLE>";
		}
		else
		{	
			skuMarkup += "<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0>";
	
			i=attr_label.length-1;
			labelstr="";
			while (attr_label[i]!= "" && i >=0 ) {
			labelstr=labelstr + attr_label[i] + " ";
			i=i-1;
			}
			//writeoption_qv("",labelstr ,sel_values[0]);
			for (atn=0;atn< product_var.length ;atn++){
				if (product_var[atn].avail != "0") {
				  if (num_avail == 0){
				    skuMarkup += "<TR VALIGN=TOP><td><span class=ProductAttrlabel><b>Select From:</b><br/>";
				    skuMarkup += "<div id=ddDiv><SELECT class=ProductAttrqv NAME='sku' id='sku' >";
				  }
				  if (prodObj.useVariantPrice=="True"){
				    if (prodObj.on_sale=="True"){
				      skuMarkup +=writeoption_qv(product_var[atn].sku,(product_var[atn].attr_value2 + " - " + product_var[atn].attr_value1 + " $"+ OKStrOfPenny(product_var[atn].price_sale)+"&nbsp;") ,'');
				    } else {
				      skuMarkup +=writeoption_qv(product_var[atn].sku,(product_var[atn].attr_value2 + " - " + product_var[atn].attr_value1 + " $"+ OKStrOfPenny(product_var[atn].price_list)+"&nbsp;") ,'');
				    }
				  } else {
				    skuMarkup +=writeoption_qv(product_var[atn].sku,(product_var[atn].attr_value2 + " - " + product_var[atn].attr_value1+"&nbsp;") ,'');
				  }
				  num_avail++;
				}
			}//end for
			skuMarkup += "</select></div></td></tr>";
			
			if (num_avail > 0){
				// jat 12/18/07 - removing quantity dropdown for now
				//skuMarkup += "<td class=ProductAttrlabel>&nbsp;Qty</td><td><div id=ddDiv><SELECT class=ProductAttr NAME='qty' id='qty'>";
				//for(na=1;na<=5;na++){skuMarkup += "<option value=\""+na+"\">"+na+"&nbsp;</option>";}
				//skuMarkup += "</select></div></td>";
			}else{
			  skuMarkup += "<TR VALIGN=TOP><TD class=ProductAttrlabel><BR>So sorry but this product is not available.</td></tr>";
			}
			skuMarkup += "</TABLE>";
		}
	}
	
	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;
}


/* draws quick view icon on search thumbnail
*/
function draw_search_qv(product_pfid)
{
	document.write("<div class=\"qv-wrapper\">");
	document.write("<img src=\"assets/images/qvicon.gif\" class=\"qvicon\" style=\"visibility:hidden;\" ");
	if(window.XMLHttpRequest){document.write("style=\"left:0px;\" ");}	// add in an ie7 hack
	document.write("id=\"qvicon_" + product_pfid  + "\" ");
	document.write("onmouseover=\"popQVIcon('qvicon_" + product_pfid  + "');\" ");
	document.write("onclick=\"getProdInfo('" +  product_pfid + "');\" ");
	document.write("onmouseout=\"hideQVIcon('qvicon_" + product_pfid  + "');\" /></div>");
}



/* 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> #Text_field_3# <BR><BR>";
	emailbody = emailbody + "<A HREF=\"#URL#\" >";
	emailbody = emailbody + "<img src=\"" + imgURLpre + "" + apf_id + "?$THUMB$\"  ALT=\"" + aproduct_name + "\" border=0>";
	emailbody = emailbody + "</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