//********************************************************************
//*-------------------------------------------------------------------
//* Licensed Materials - Property of IBM
//*
//* WebSphere Commerce
//*
//* (c) Copyright IBM Corp. 2007
//*
//* US Government Users Restricted Rights - Use, duplication or
//* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//*
//*-------------------------------------------------------------------
		
	/************************************************************
	 *	WORK PENDING											*
	 *	1. JavaDoc for Compare Function							*
	 *	2. Dependency of HTML forms and element					*
	 *	3. Moving Global variable and Functions to Global.js	*
	 *	4. Fixing few defect in Compare Functions				*
	 *		i.e:Should not accept same item in compareZone		*
	 *			Should allow to frag items from compareZone		* 
	 ************************************************************/


	dojo.require("dojo.widget.PopupContainer");
	dojo.require("dojo.widget.ContentPane");
	
	/******************************************************************************************************************
	 *                                        GLOBAL VARIABLES & FUNCTIONS                                            *
	 *                                                    START                                                       *
	 ******************************************************************************************************************/
QuickViewJS={
		waitMessage : "UNDEFINED",
		itemNo :"UNDEFINED",
		colorShown :"UNDEFINED",
		scene7 :"UNDEFINED",
		waitOnAdd: false,
		waitDisplayQV: false
		}
	       
function showQVContents(url, data) { 
	// get quick view pane by id
    var pane = dojo.widget.byId(this);

    data = pane.splitAndFixPaths(data, url);
    // show the contents recieved as response of XMLHttpRequest
	pane.setContent(data);
} 
 
function showQVWaitIcon(arguments) { 

	
		// hide the default loading... message                 
	    arguments.preventDefault();
	    // get quick view pane by id
	    var pane = dojo.widget.byId(this);
	    // wait icon, will be showed before the actual contents ready to load
	    var data = QuickViewJS.waitMessage;
		// show the wait icon
		pane.setContent(data);
	

}  

// update add to cart params, when quick view pop up hides
function onQVHideHandler(){ 
	/*
	try{
		var accessory_id = dojo.byId("whichaccessory"); 
		var accessory_catentid = dojo.byId("accessory_catentry");
		var accessory_qty = dojo.byId("accessory_qty");
		an_accessoryqty1 = eval("document.OrderItemAddForm.quantity_" + accessory_id.value);
			
		an_accessory1 = eval("document.OrderItemAddForm.catEntryId_" + accessory_id.value); 
		an_accessory1.checked = false;
		if(accessory_catentid.value != '' && accessory_catentid.value != '0'){
			an_accessory1.checked = true;
			an_accessory1.value = accessory_catentid.value;
			an_accessoryqty1.value = accessory_qty.value;
			
		}
	}catch(e){

	}
	*/ 
	// copied from dojo source
	var popup = dojo.widget.byId(this);
	dojo.widget.HtmlWidget.prototype.onHide.call(popup);
	//restore size of the domnode, see comment in
	//function onShow()
	/*if(popup.openedSize){             
		with(popup.domNode.style){
			width=popup.openedSize.w;        
			height=popup.openedSize.h;  
		}       
	}*/
	popup.processQueue();
	// end copy
}

function displayQV(quickviewId)
{
	//the quick view will fail unless the page is fully loaded
	if (QuickViewJS.waitDisplayQV)
	{
		var qvicon = document.getElementById(quickviewId);
		qvicon.style.visibility = "visible";
		qvicon.style.cursor = "pointer";
		qvicon.parentNode.display = "block";       
	}    
} 

function hideQV(quickviewId)
{
	document.getElementById(quickviewId).style.visibility = "hidden";                     
} 
function updateQVDisplay(prodId){ 
	
	

	var selectBox = dojo.byId("accessory_select"+prodId);

	user_input = selectBox.options[selectBox.selectedIndex].value
	
	var disp;
	var imgName;
	var color;
	var prodId;
	//alert("qv_"+user_input);
	var elem = dojo.byId("qv_"+user_input);
	//alert(elem);
	var dispStr ='';  
		
	if (elem == null)
		return;
	disp = elem.innerHTML;    
	splitter = disp.split(':');
	disp = splitter[0]; 
	imgName = splitter[1];
	color = splitter[2];
	esd = splitter[3];
	prodId = splitter[4];	
	price = splitter[5];				
			
		        
		
	// change the sku text
	var tmpId = 'qv_skuText_' + prodId;
    var skuText = dojo.byId(tmpId); 
	skuText.innerHTML = 'Item No.' + '  '+disp;
	
	 // change the text
	tmpId = 'qv_colorShown_' + prodId;
	
    var altViewText = dojo.byId(tmpId); 
	altViewText.innerHTML = 'Color Shown:' +'  '+ color;
	
	// change the esd text
	tmpId = 'qv_esd_' + prodId;
    var esdtext = dojo.byId(tmpId); 
	esdtext.innerHTML = 'Est. Ship Date:' +'  '+esd;
	
	var priceText = dojo.byId("productPrice"); 
   	if (priceText) 
		priceText.innerHTML = price;
		
	// change the main image
	tmpId = 'qv_mainImage_' + prodId;
	var mainimg = dojo.byId(tmpId);
	// change the button image back
    mainimg.setAttribute("src",'http://s7ondemand1.scene7.com/is/image/MoosejawMB/' + imgName);
    
    if (dojo.byId('bubble'))
 	{
 		dojo.html.setDisplay('bubble',false); 
 	}
 	
 	
}

function replaceQVImage(imageId, imageName, altTextId,altText)
{ 
	// change the image
	var mainimg = dojo.byId(imageId);
    mainimg.setAttribute("src",imageName);
    
    // change the text
	
    var altViewText = dojo.byId(altTextId);                                 
	altViewText.innerHTML = altText;       
}

function qv_AddToCart(prodId,itemId)
{ 
	_setCookie("shipOptions",""); 
	if (!QuickViewJS.waitOnAdd)
	{
		QuickViewJS.waitOnAdd = true;
		var avail=false;
		
		if (itemId!=''){
			var qv_singleResolvedItem=itemId;
			var qv_resolvedItem;
		}
		
		if (qv_singleResolvedItem != null && qv_singleResolvedItem != 'undefined') {
			qv_resolvedItem = qv_singleResolvedItem;
			avail=true;
		}else{
		
			//if size or color selected and only one companion color or size, then grab the tempSelected value and set colorSelcted or sizeSelected = to it
			
			
			var tmpColorSelected = qv_colorSelected;
			var tmpSizeSelected = qv_sizeSelected;
			
			if (qv_colorSelected == 'undefined' || qv_colorSelected == null)
			{
				if (qv_defaultColorSelected != 'undefined' && qv_defaultColorSelected !=null)
				{
					tmpColorSelected = qv_defaultColorSelected;
				}else{
					tmpColorSelected = '';
				}
			}
			
			if (qv_sizeSelected == 'undefined' || qv_sizeSelected == null)
			{
				if (qv_defaultSizeSelected != 'undefined' && qv_defaultSizeSelected !=null)
				{	
					tmpSizeSelected = qv_defaultSizeSelected;
				}else{
					tmpSizeSelected = '';
				}
			}
			
			var strToCompare = tmpColorSelected + '@' + tmpSizeSelected;
			
			//Make sure the user selected available color and size combination
			for(i=0;i<qv_availableItemsAttributeMapArray.length;i++){
				if(qv_availableItemsAttributeMapArray[i].startsWith(strToCompare)){
					avail=true;
					break;
				}
			}
		}
		var selectBox = eval("document.QVForm.accessory_select"+prodId);
		//user_input = selectBox.options[selectBox.selectedIndex].value;
		
		if (avail ==true && (qv_resolvedItem ==null || qv_resolvedItem=='undefined')){
			qv_resolvedItem=getResolvedSku(tmpSizeSelected,tmpColorSelected);
		}
		user_input = qv_resolvedItem;
	    if ( (user_input == "0") || (user_input == "undefined") || (user_input == null) || (avail!=true) ) {
	    	alert("Please make product selections, then click Add to Cart.");
			QuickViewJS.waitOnAdd = false;
	    	return;
	    }
	   	document.QVForm.catEntryId.value=user_input;
	   	resetPopulateArrayFlag();
	   		//if element for lastcmdname exists as a div, use it.
	   	if (dojo.byId('qv_lastCmdName'))
	   	{
	   		var cmdname = dojo.byId('qv_lastCmdName').innerHTML;
	   		cmdname = unescape(cmdname);
	   		while (cmdname.indexOf('&amp;') > -1)
				cmdname = cmdname.replace('&amp;','&');		
	   		document.QVForm.URL.value=cmdname+"&add=1";
	   	}
	   	
	   	//document.QVForm.action = "OrderItemAdd";
	   //	document.QVForm.submit();
	   	//add dojo js into header user mod..
		var params = [];
		params.storeId		= document.QVForm.storeId.value;
		params.catalogId	= document.QVForm.catalogId.value;
		params.orderId 		= document.QVForm.orderId.value;
		//params.quantity		= document.QVForm.quantity.value;
		params.quantity		= dojo.widget.byId("catqty").selectedVal;		
		params.orderItemId_old	= document.QVForm.orderItemId_old.value;
		params.orderItemId_new	= document.QVForm.orderItemId_new.value;
		params.catEntryId		= user_input;
		params.pageName			= document.QVForm.pageName.value;
		params.calculateOrder	= document.QVForm.calculateOrder.value;
		params.whichaccessory	= document.QVForm.whichaccessory.value;
		params.whichaccessory	= document.QVForm.whichaccessory.value;
		
		params.langId	= "-1";
		params.reLogonURL	= "AjaxActionErrorResponse";
		params.URL	= "AjaxActionResponse";
				
		
		wc.service.invoke("AjaxAddOrderItem",params);

		cursor_wait(); 
		var productName =  document.QVForm.productName.value;
		var str = document.getElementById(user_input).innerHTML;
		var item_array  = str.split(":");
		var itemPrice =	item_array[5];	
	
		
		var currency = 'RWP';
		
		if(itemPrice.indexOf("$") != -1)
		{
			itemPrice = itemPrice.replace('$','');
			currency = 'USD';
			itemPrice = trim(itemPrice);
		}
		
		//MJPRO-2047 Add shop 5 tags to ajax add to cart 
		cmCreateShopAction5Tag(user_input,productName,params.quantity,itemPrice,params.catalogId, params.storeId, currency); 
	}
    
}

function qv_UpdateCart(orderId, prodId, existCatEntryId,itemId )
{
	if (!QuickViewJS.waitOnAdd)
	{
		QuickViewJS.waitOnAdd = true;
		
			var avail=false;
		if (itemId!=''){
			 var qv_singleResolvedItem=itemId;
			 var qv_resolvedItem;
		}
		
		if (qv_singleResolvedItem != null && qv_singleResolvedItem != 'undefined') {
			qv_resolvedItem = qv_singleResolvedItem;
			avail=true;
		}else{
		
			//if size or color selected and only one companion color or size, then grab the tempSelected value and set colorSelcted or sizeSelected = to it
			
			
			var tmpColorSelected = qv_colorSelected;
			var tmpSizeSelected = qv_sizeSelected;
			
			if (qv_colorSelected == 'undefined' || qv_colorSelected == null)
			{
				if (qv_defaultColorSelected != 'undefined' && qv_defaultColorSelected !=null)
				{
					tmpColorSelected = qv_defaultColorSelected;
				}else{
					tmpColorSelected = '';
				}
			}
			
			if (qv_sizeSelected == 'undefined' || qv_sizeSelected == null)
			{
				if (qv_defaultSizeSelected != 'undefined' && qv_defaultSizeSelected !=null)
				{	
					tmpSizeSelected = qv_defaultSizeSelected;
				}else{
					tmpSizeSelected = '';
				}
			}
			
			var strToCompare = tmpColorSelected + '@' + tmpSizeSelected;
			
			//Make sure the user selected available color and size combination
			for(i=0;i<qv_availableItemsAttributeMapArray.length;i++){
				if(qv_availableItemsAttributeMapArray[i].startsWith(strToCompare)){
					avail=true;
					break;
				}
			}
		}
		
		if (avail ==true && (qv_resolvedItem ==null || qv_resolvedItem=='undefined')){
			qv_resolvedItem=getResolvedSku(tmpSizeSelected,tmpColorSelected);
		}
			
		user_input = qv_resolvedItem;
	    if ( (user_input == "0") || (user_input == "undefined") || (user_input == null) || (avail!=true)) {
	    	alert("Please make product selections, then click Update Cart.");
			QuickViewJS.waitOnAdd = false;
	    	return;
	    }
   		document.QVForm.catEntryId.value=user_input;
	    
	    document.QVForm.orderItemId_old.value=existCatEntryId;
	   	document.QVForm.orderItemId_new.value=user_input;
	//   	document.QVForm.quantity=dojo.widget.byId("catqty").selectedVal;
	   	//if element for lastcmdname exists as a div, use it.
	   	if (dojo.byId('qv_lastCmdName'))
	   	{
	   		var cmdname = dojo.byId('qv_lastCmdName').innerHTML;
	   		cmdname = unescape(cmdname);
	   		while (cmdname.indexOf('&amp;') > -1)
				cmdname = cmdname.replace('&amp;','&');		
	   		document.QVForm.URL.value=cmdname;
	   	}
	   	document.QVForm.action = "QuickUpdate";
	   	resetPopulateArrayFlag();
	   	document.QVForm.submit();
 	}
    
}

function toggleSavedListLoginDiv(thisdiv, destURL) {
	resetPopulateArrayFlag();
	toggleSavedListMenuDiv(thisdiv, destURL);
	
}

function qv_AddToWish(prodId)
{ 

	if (!QuickViewJS.waitOnAdd)
	{
    
    	QuickViewJS.waitOnAdd = true;
		var selectBox = eval("document.QVForm.accessory_select"+prodId);
		//user_input = selectBox.options[selectBox.selectedIndex].value;
		user_input = qv_resolvedItem;
	    if ( (user_input == "0") || (user_input == "undefined") || (user_input == null) ) {
	    	alert("Please make product selections, then click Save for Later.");
			QuickViewJS.waitOnAdd = false;
	    	return;
	    }
	   	document.QVForm.catEntryId.value=user_input;

	   	//if element for lastcmdname exists as a div, use it.
	   	if (dojo.byId('qv_lastCmdName'))
	   	{
	   		var cmdname = dojo.byId('qv_lastCmdName').innerHTML;
	   		cmdname = unescape(cmdname);
	   		while (cmdname.indexOf('&amp;') > -1)
				cmdname = cmdname.replace('&amp;','&');		
	   		document.QVForm.URL.value=cmdname;
	   	} 
	   	
	   	document.QVForm.action = "InterestItemAdd";
	   	document.QVForm.submit();
   	}    
}

//need a qv_updateWishListFunction

function selectAccessory(prodId,qvId)
{
	
	QuickViewJS.waitOnAdd = true;
	
	user_input = qv_resolvedItem;
    if ( (user_input == "0") || (user_input == "undefined") || (user_input == null) ) {
    	alert("Please make product selections, then click Add to Cart."); 
			QuickViewJS.waitOnAdd = false;		
    	return false;
    }
    
   	var selectedObj = dojo.byId("qvAccessoryString_"+user_input);
   	var displayObj = dojo.byId("qvColor_"+prodId);
   	var checkboxObj = dojo.byId("qvCheckbox_"+prodId);
   	
   	if (!checkboxObj.checked)
   	 dojo.byId("qvCheckbox_"+prodId).checked=true;
   	
   	checkboxObj.value = user_input;
   	
   	displayObj.innerHTML = selectedObj.innerHTML;
   	
   	return true;
   	
  // 	hidePopup(qvId);
 
}


function showAccessoryPopUp(prodId, pURL, pContentId)
{
	//var checkboxObj = dojo.byId("qvCheckbox_"+prodId);
	
	if (productPageLoaded)
	{
	  /* 	if (!checkboxObj.checked)
	   	{ 
	   		
	   		
	   		dojo.byId("qvColor_"+prodId).innerHTML="";
	   		return true;
	   	} */
	   	openPopup(pURL, pContentId);
   	} /*else
   	{
   		if (checkboxObj.checked)
	    	checkboxObj.checked = false;
	    else
	    	checkboxObj.checked = true; 
	    
	    return true;
   	}*/
   	
}

function closeAccessoryPopup(prodId,popUpId)
{
/*	var checkboxObj = dojo.byId("qvCheckbox_"+prodId);
	var selectStrHTML = dojo.byId("qvColor_"+prodId).innerHTML;
	//if checkbox is checked, but nothing was ever selected before...uncheck the box
   	if (checkboxObj.checked && selectStrHTML.length == 0)
   	{ 
   		dojo.byId("qvCheckbox_"+prodId).checked=false;
   		dojo.byId("qvColor_"+prodId).innerHTML="";
   		
   	}
  */ 	
   	hidePopup(popUpId);
}

function goToProductPage(url)
{
   window.location = url;
}

function removeThisImage(img)
{
	//dojo.html.setDisplay(img,false);
	document.getElementById(img).style.display='none';
	return;
}

function checkCookieExists(cookieName){
   //alert('Check if cookies vales');
   if(document.cookie.length > 0){
	      c_start=document.cookie.indexOf(cookieName + "=");
		  if (c_start!=-1)
		    {
			    c_start=c_start + cookieName.length+1 ;
			    c_end=document.cookie.indexOf(";",c_start);
			    if (c_end==-1) c_end=document.cookie.length
			    return(unescape(document.cookie.substring(c_start,c_end)));
		    }
        }
         return "";
}

/*dojo.addOnLoad(function(){
	//enable the quick view icon when the page loads
	QuickViewJS.waitDisplayQV = true;
	cookieValue = checkCookieExists('usercompproduct');
	if(cookieValue != null && cookieValue != ""){
	   var cookieArray = cookieValue.split(',');
	   for(var m=0; m < cookieArray.length; m++){
	      if(cookieArray[m] != "" && document.getElementById("compareProdCheckBox_"+cookieArray[m])){
	       //document.getElementById("compareProdCheckBox_"+cookieArray[m]).checked = 'true';
	       //document.getElementById("compareProdButton_"+cookieArray[m]).src = '/moosejaw/MoosejawStorefrontAssetStore/images/buttons/compare.gif';
	       var compCheckBoxArray = document.getElementsByName("compareProdCheckBox_"+cookieArray[m]);
	       var compButtonArray = document.getElementsByName("compareProdButton_"+cookieArray[m]);
	       
	       for ( var i = 0 ; i < compCheckBoxArray.length ; i++ ) {
	       	compCheckBoxArray[i].checked = 'true';
	       	compButtonArray[i].src = '/moosejaw/MoosejawStorefrontAssetStore/images/buttons/compare.gif';
	       }
	      } 
	   }
	}
}); 
*/

jQuery(document).ready(function() {

	//enable the quick view icon when the page loads
	//QuickViewJS.waitDisplayQV = true;
	cookieValue = checkCookieExists('usercompproduct');
	if(cookieValue != null && cookieValue != ""){
	   var cookieArray = cookieValue.split(',');
	   for(var m=0; m < cookieArray.length; m++){
	      if(cookieArray[m] != "" && document.getElementById("compareProdCheckBox_"+cookieArray[m])){
	       //document.getElementById("compareProdCheckBox_"+cookieArray[m]).checked = 'true';
	       //document.getElementById("compareProdButton_"+cookieArray[m]).src = '/moosejaw/MoosejawStorefrontAssetStore/images/buttons/compare.gif';
	       var compCheckBoxArray = document.getElementsByName("compareProdCheckBox_"+cookieArray[m]);
	       var compButtonArray = document.getElementsByName("compareProdButton_"+cookieArray[m]);
	       
	       for ( var i = 0 ; i < compCheckBoxArray.length ; i++ ) {
	       	compCheckBoxArray[i].checked = 'true';
	       	compButtonArray[i].src = '/moosejaw/MoosejawStorefrontAssetStore/images/buttons/compare.gif';
	       }
	      } 
	   }
	}
	
});



function _setCookie(name, value, expires, path, domain, secure)
{
	var day = new Date();
	day.setTime(day.getTime());
	var expire_on;

	if (expires == -1) {
 		expires_on = 'Mon, 1 Jan 1979 00:00:00 GMT';
 	}
 	else if (expires > 0) {
 		//expiration unit in days.
 		expires = expires * 1000 * 60 * 60 * 24;
 		var expires_date = new Date(day.getTime() + expires);
 		expires_on = expires_date.toGMTString();
 	}
 	else {
 		expires_on = null;
 	}

 	document.cookie = name + "=" +escape( value ) +
 	( ( expires ) ? ";expires=" + expires_on : "" ) +
 	( ( path ) ? ";path=" + path : "" ) +
 	( ( domain ) ? ";domain=" + domain : "" ) +
 	( ( secure ) ? ";secure" : "" );
}   

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

