// JavaScript Document

//Setting up the global variable to start Mini Shopping Cart as being hidden
var showMiniCart = false;
var CurrentSeasonFolder = "shop";

function OpenCart()
{
	if(showMiniCart == false)
	{ 
	  showMiniCart = true;
	  document.getElementById("TheCart").style.display = "";
	  document.getElementById("plusMinus").className = "plusMinus_open";
	  document.getElementById("MiniCartDropShadow").style.display = "";
	  
	}
	else
	{ 
	  showMiniCart = false;
	  document.getElementById("TheCart").style.display = "none";
	  document.getElementById("plusMinus").className = "plusMinus";
	  document.getElementById("MiniCartDropShadow").style.display = "none";
	}
}

/* // old code, hidden on 2/10/2010
function OpenCart()
{
		if(showMiniCart == false)
		{ 
		  //document.getElementById("SCMiniArrow").src = "/shop/images/arrow_down.gif";
		  showMiniCart = true;
		  document.getElementById("MiniContentHolder").style.display = "";
		  document.getElementById("MiniCartWrapper").style.display = "";
		  document.getElementById("MiniCartDropShadow").style.display = "";
		  
		}
		else
		{ 
		  //document.getElementById("SCMiniArrow").src = "/shop/images/arrow_right.gif"; 
		  showMiniCart = false;
		  document.getElementById("MiniContentHolder").style.display = "none";
		  document.getElementById("MiniCartWrapper").style.display = "none";
		  document.getElementById("MiniCartDropShadow").style.display = "none";
		}
}
*/
function AddCatalogToOrder(theCheckbox, isChecked)
{
	var AddCatalog;
	if(isChecked == true)
	{ AddCatalog = 'yes'; }
	else
	{ AddCatalog = 'no'; }
	processajax ("/"+CurrentSeasonFolder+"/includes/CO_AddCatalog.php?AddCatalog="+AddCatalog, document.getElementById("AddCatalogDIV"), "get", "");
}
//AJAX Functions to submit a form.
function getformvalues(fobj, valfunc){
	var str = "";
	aok = true;
	var val;
	//Run through a list of all objects contained within the form.
	for(var i = 0; i < fobj.elements.length; i++){
		// see if the element is a checkbox, if so, see if it is checked, if so, pass the value
		if(fobj.elements[i].type == 'checkbox' && fobj.elements[i].checked)
		{ str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&"; }
		else if(fobj.elements[i].type != 'checkbox')
		{ str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&"; } 
	}
	//Then return the string values.
	return str;
}

function submitform(theform, serverPage, objID, valfunc){
	var file = serverPage;
	var str = getformvalues(theform,valfunc);
	//alert(str);
	//If the validation is aok.
	if(aok == true){
		obj = document.getElementById(objID);
		processajax(serverPage, obj, "post", str);
	}
}
function launchProductQuickView(GarmentID,VersionID)
{
	//alert(VersionID);
	document.getElementById("ProductQuickView").innerHTML = "<div style='position:relative;'><BR /><center><image src='images/loader.gif' valign='middle'/><BR />Loading Product Quick View</center><BR /></div>";
	document.getElementById("BackgroundOverlay").style.height = document.body.clientHeight+"px";
	document.getElementById("BackgroundOverlay").style.display = '';
	//alert("GID: " + GarmentID + "\r\nVID: " + VersionID);
	if(showMiniCart == true){ OpenCart(); }
	document.getElementById("ProductQuickView").style.display = "";
	document.getElementById("ProductQuickView").style.top = GetScrollPositionY()+30+"px";
	var serverPage = "/"+CurrentSeasonFolder+"/includes/ProductQuickView.php?GID="+GarmentID+"&VID="+VersionID;
	processajax (serverPage, document.getElementById("ProductQuickView"), "get", "");
	//document.getElementById("BackButtonPlaceHolder").src = "/"+CurrentSeasonFolder+"/includes/back_button_placeholder.htm";
}
function launchProductDescription(GarmentID)
{
	document.getElementById("ProductDescHTML").innerHTML = "<div style='position:relative;'><BR /><center><image src='images/loader.gif' valign='middle'/><BR />Loading Product Quick View</center><BR /></div>";
	var serverPage = "/"+CurrentSeasonFolder+"/includes/Product_Description.php?GID="+GarmentID;
	processajax (serverPage, document.getElementById("ProductDescHTML"), "get", "");
	//document.getElementById("BackButtonPlaceHolder").src = "/"+CurrentSeasonFolder+"/includes/back_button_placeholder.htm";
}
/* // hidden on 2/10/2010
function closeQuickView()
{
	//document.getElementById("ProductQuickView").innerHTML = "<div style='position:relative;'><BR /><center><image src='images/loader.gif' valign='middle'/><BR />Loading Product Quick View</center><BR /></div>";
	document.getElementById("ProductQuickView").style.display = "none";
	document.getElementById("BackgroundOverlay").style.display = "none";
	//processajax (", document.getElementById("ProductQuickView"), "get", "");	
}*/
function changeAddToCartOptions(GID,VersionSKU,whichSize)
{
	ChangeColor("",GID,VersionSKU,"");
	
	//alert(GID+" "+VersionSKU+" "+whichSize);
	this.document.AddToCartForm.Color.selectedIndex = whichSize;
	var whichColor = whichSize - 1;
	//alert('http://www.ibex.com/Photos/'+ProductItemArray[GID][2][whichColor][0]);
	this.document.images['ProductImage'].src = '/Photos/'+ProductItemArray[GID][2][whichColor][0];
	//alert("a");
	this.document.AddToCartForm.VersionID.options.length = 1;
	var sizes = ProductItemArray[GID][2][whichColor];
    for (var j=1;j<sizes.length;j++)
    {
	   document.AddToCartForm.VersionID.options[j] = new Option(sizes[j],ProductItemArray[GID][3][whichColor][j]);
    }
}

function AddItemToCart()
{
	//alert("AddingItemToCart");
	if(!document.AddToCartForm.GCType && document.AddToCartForm.VersionID.options.selectedIndex == 0)
	{ alert("You must select a size to add this item to your cart."); }
	else
	{
	  var str = getformvalues(document.AddToCartForm,'');
	  processajax("/"+CurrentSeasonFolder+"/includes/_MiniCart.php?KeepOpen=1", document.getElementById("ShoppingCartHolster"), "post", str);
	  OpenCart();
	}
}
function AddItemToWishList()
{
	var RateWish = document.getElementById("RateWish").options.selectedIndex;
	if(!document.AddToCartForm.GCType && document.AddToCartForm.VersionID.options.selectedIndex == 0)
	{ alert("You must select a size to add this item to your wish list."); }
	else
	{
	  var str = getformvalues(document.AddToCartForm,'');
	  str += "RateWish="+RateWish+"&";
	  //alert(str);
	  processajax("/"+CurrentSeasonFolder+"/includes/Wishlist_AddTo.php", document.getElementById("Wishlist_Include"), "post", str);
	  
	}
}

function removeItemFromCart(ItemNumber,RefreshPage)
{ 
  if(RefreshPage == 1)
  { location.href = "ShoppingCart.php?KeepOpen=1&RemoveItem="+ItemNumber; }
  else if(RefreshPage == 2)
  { location.href = "CO_ReviewOrder.php?KeepOpen=1&RemoveItem="+ItemNumber; }
  else if(RefreshPage == 3)
  { location.href = "My_Account.php?SFL=1&RemoveItem="+ItemNumber; }
  else
  { processajax("/"+CurrentSeasonFolder+"/includes/_MiniCart.php?KeepOpen=1&RemoveItem="+ItemNumber, document.getElementById("ShoppingCartHolster"), "get",""); }
  
}
// when a user clicks on the "Save For Later" link from the miniShoppingCart
function saveForLater(ItemNumber,RefreshPage,AddOrRemove)
{ 
  if(RefreshPage == 1)
  { location.href = "ShoppingCart.php?KeepOpen=1&SaveForLaterItemID="+ItemNumber+"&AddOrRemove="+AddOrRemove; }
  else if(RefreshPage == 2)
  { location.href = "CO_ReviewOrder.php?KeepOpen=1&SaveForLaterItemID="+ItemNumber+"&AddOrRemove="+AddOrRemove; }
  else if(RefreshPage == 3)
  { location.href = "My_Account.php?SFL=1&SaveForLaterItemID="+ItemNumber+"&AddOrRemove="+AddOrRemove; }
  else
  { processajax("/"+CurrentSeasonFolder+"/includes/_MiniCart.php?KeepOpen=1&SaveForLaterItemID="+ItemNumber+"&AddOrRemove="+AddOrRemove, document.getElementById("ShoppingCartHolster"), "get",""); }
  
}
function showFabricPreview(e,FabricID)
{ 
  obj = document.getElementById("FabricPreview");
  obj.innerHTML = "<div style='position:relative;'><BR /><center><image src='images/loader.gif' valign='middle'/><BR />Loading Fabric Preview</center><BR /></div>";
  //alert(CurrentSeasonFolder);
  processajax("/"+CurrentSeasonFolder+"/includes/Fabrics.php?FabricID="+FabricID, document.getElementById("FabricPreview"), "get",""); 
  posy = e.clientY;
  posx = e.clientX;
  //obj.style.right = posx + "px";
  obj.style.top = posy + "px";
  obj.style.left = "185px";
  obj.style.display = "";
}



function showLoadingImage(obj)
{
  document.getElementById(obj).innerHTML = "<div style='position:relative;'><BR /><center><image src='images/circle_loading.gif' valign='middle'/><BR />Loading Products</center><BR /></div>";
}

function SCQuickEdit(Thumbnail,GID,VersionSKU,Color,Size,WhichSizeImage,VersionID)
{
  if(Color)	
  { 
    document.getElementById("ItemColor").innerHTML = "<b class='TEXT_BurntOrange'>Select Color:</b> " + Color;
	document.images["PhotoThumb"].src = "/Photos/"+Thumbnail;
	processajax("/"+CurrentSeasonFolder+"/includes/ShoppingCartSizes.php?GID="+GID+"&VersionSKU="+VersionSKU, document.getElementById("ShoppingCartSizes"), "get","");
	document.EditItem.VersionID.value = '';
	document.getElementById("ItemSize").innerHTML = "<b class='TEXT_BurntOrange'>Select Size:</b> please select a size"; 
	document.EditItem.NumSizes.value = Size
  }
  if(Size)
  {
	for(var i=1;i<=document.EditItem.NumSizes.value;i++)
	{
		var theSrc = document.images["Sizes"+i].src;
		var theSrc2 = document.images["Sizes"+WhichSizeImage].src;
		document.images["Sizes"+i].src = theSrc.replace("_roll","");
	}
	document.images["Sizes"+WhichSizeImage].src = theSrc2.replace(".jpg","_roll.jpg");
	document.EditItem.VersionID.value = VersionID;
	document.getElementById("ItemSize").innerHTML = "<b class='TEXT_BurntOrange'>Select Size:</b> " + Size;  
  }
}
// Update an item in the shopping cart
function UpdateItem()
{
	var errormsg = "";
	if(document.EditItem.VersionID.value == "")
	{ errormsg += "- You must select a SIZE\r\n"; }
	if(document.EditItem.Qty.value == "" || document.EditItem.Qty.value < 1 || document.EditItem.Qty.value > 10 || (parseInt(document.EditItem.Qty.value) != parseFloat(document.EditItem.Qty.value)))
	{ errormsg += "- The QUANTITY you have entered is invalid.\r\n"; }
	if(document.EditItem.Amount)
	{ 
	  var theAmount = document.EditItem.Amount.value;
	  //alert(theAmount + "\r\nThe Length: " + theAmount.length);
	  //alert(theAmount.substring(1));
	  var validAmount = true;
	  for(var i=0;i<theAmount.length;i++)
	  { 
	    //alert(theAmount.charAt(i));
		if(!parseInt(theAmount.charAt(i)) && theAmount.charAt(i) != 0 && theAmount.charAt(i) != '$' && theAmount.charAt(i) != ".")
		{ validAmount = false; }
	  }
	  
	  if(validAmount == false){ errormsg += "- The Amount of the gift certificate is not valid."; }
	  
	   
	}
	if(errormsg)
	{ alert("You have the following errors with your Product Quick Edit:\r\n--------------------------------------------------------------------------\r\n\r\n"+errormsg+"\r\n--------------------------------------------------------------------------"); }
	else
	{ document.EditItem.action="ShoppingCart.php"; document.EditItem.submit(); }
}
function UpdateCart()
{
	//alert(document.UpdateShoppingCart.Items.value);
	var errormsg = '';
	for(var i=1;i<=document.UpdateShoppingCart.Items.value;i++)
	{
		if(parseInt(document.UpdateShoppingCart["Qty"+i].value) != parseFloat(document.UpdateShoppingCart["Qty"+i].value))
		{ errormsg += "- The quantity for item #:"+i+" is not a valid number.\r\n"; }
		          
	  
	}
	
	if(errormsg != '')
	{
		alert("The following errors exist.  Please fix the mistakes and click on 'Save Changes' to update your cart.\r\n--------------------------------------------------------------------------------------------\r\n"+errormsg+"\r\n--------------------------------------------------------------------------------------------");
	}
	else
	{
		document.UpdateShoppingCart.action="ShoppingCart.php";
		document.UpdateShoppingCart.submit();
	}
}
function showAutoSuggestFocus()
{
	document.getElementById("SearchSuggestions").innerHTML = "<div style='padding:10px'>Auto Suggestions building....</div>";
}
function autoSuggest(theForm)
{
	var SearchTerm = theForm.Search.value;
	if(SearchTerm == '')
	{ 
		document.getElementById("SearchSuggestions").innerHTML = "Loading Search Suggestions";
	}
	else
	{
		processajax("/"+CurrentSeasonFolder+"/includes/searchSuggestions.php?Search="+SearchTerm, document.getElementById("SearchSuggestions"), "get","");
		document.getElementById("SearchSuggestions").style.display = '';
	}

}

function checkCompareSelected(){
	var TotalCompared = 0;
	var Elem = document.getElementById('CompareProducts').elements;
	alert(document.getElementById('CompareProducts').value);
	if(Elem["Compare1"])
	{
	  
	  for(var i=1;i <= document.CompareProducts.NumProds.value; i++)
	  {
		if(Elem["Compare"+i].checked == true)
		{ TotalCompared++; }
	  }
	}
	if(TotalCompared == 0)
	{
	  alert("You must have at least two items in your cart to compare.");	
	}
	else if(TotalCompared <= 1)
	{ 
		alert("You must select more than one product to compare.");
		return false;
	}
	else
	{ document.CompareProducts.submit(); }
}
function showPQVButton(PQVButton)
{
	if(document.getElementById(PQVButton).style.display == "none")
	{ document.getElementById(PQVButton).style.display = ""; }
	else
	{ document.getElementById(PQVButton).style.display = "none"; }
}
// The function below will alert the user that an item in their cart is no longer available and will be removed.
function ItemWillBeRemoved(ProductName)
{
	OpenCart();
	var WhichProducts = ProductName.replace(/RETURN/,"\r\n-");
	alert("The following item(s) in your shopping cart are now sold out:\r\n_______________________________________________________________\r\n"+WhichProducts+"\r\n\r\n_______________________________________________________________\r\nThey will be removed from your cart after you leave this page.");
}





var alertTimerId = 0;



function launchItemDESCHandler(e,showHide,GarmentID)
{
  var arrowPosition = "middle";
  var myWidth = 0, myHeight = 0; var PositionFromLeft = 0;
  if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  else
  {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  }
  var CursorY = e.clientY;
  var CursorX = e.clientX;
  
  
  var PageY = 0;
  var PageX = 0;
  if (!e) var e = window.event; 
    if (e.pageX || e.pageY) 
    { 
        PageX = e.pageX; 
        PageY = e.pageY; 
    } 
    else if (e.clientX || e.clientY) 
    { 
        PageX = e.clientX + document.documentElement.scrollLeft; 
        PageY = e.clientY + document.documentElement.scrollTop; 
    } 
	//alert("posx: " + posx + "\r\nposy: " + posy);
  
  // if the cursor is too close to the top edge, move the Page Description Box(PageY variable) down by 150 pixels
  if(CursorY <= 150)
  { PageY += 150; arrowPosition = 35; }
  else if((myHeight - CursorY) <= 150)
  { PageY -= 150; arrowPosition = 285; }
  else
  { arrowPosition = 150; }
  
  // Finds how many pixels are in each margin outside of the centered 1000 pixel website
  var Margins = ((myWidth - 1000) / 2);
  var SpaceOnRight = 1000 - (CursorX - Margins);
  if(myWidth <= 1000)
  { PositionFromLeft = CursorX-20; }
  else
  { PositionFromLeft = CursorX; }
  if(showHide == 1)
  {
    // Start the timer
    alertTimerId = setTimeout ("launchItemDescription("+CursorY+","+CursorX+","+PageY+","+PageX+","+PositionFromLeft+","+SpaceOnRight+","+GarmentID+","+arrowPosition+")", 0 );
  }
  else
  {
    document.getElementById('ProductDescription').style.display = 'none';
	clearTimeout ( alertTimerId );
  }
}
function launchItemDescription(CursorY,CursorX,PageY,PageX,PositionFromLeft,SpaceOnRight,GarmentID,arrowPosition)
{  
  //alert("arrowPositin: " + arrowPosition);
  if(SpaceOnRight <= 340)
  { 
    PositionFromLeft = CursorX-350; 
    document.getElementById('ArrowPointerLeft').style.display = 'none';
	document.getElementById('ArrowPointerRight').style.top = arrowPosition+'px';
    document.getElementById('ArrowPointerRight').style.display = '';
	
  }
  else
  {
    document.getElementById('ArrowPointerLeft').style.display = '';
	document.getElementById('ArrowPointerLeft').style.top = arrowPosition+'px';
    document.getElementById('ArrowPointerRight').style.display = 'none';
	PositionFromLeft += 20;
  }
  
  document.getElementById('ProductDescription').style.left = PositionFromLeft+'px';
  document.getElementById('ProductDescription').style.top = PageY-200+'px';
  document.getElementById('ProductDescription').style.display = '';
  launchProductDescription(GarmentID);
  
  
}
function popTheBuzz()
{
	window.open('http://www.ibexbuzz.com','IbexBuzz','height=500,width=750,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,status=yes');	
}
function submitSearch(TheForm)
{
	//var TheValue = document.TheForm.Search.value;
	var SearchWhat = document.SearchBox.Search.value;
	//alert("Searching...");
	if(SearchWhat == "" || SearchWhat.match("Enter Keyword"))
	{ alert("You Must Enter a Search Term."); }
	else
	{ document.SearchBox.submit(); }
}

function suggestZip(event,theZip,theDIV,fieldZIP,fieldCITY,fieldSTATE)
{
  if((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105))
  {
    document.getElementById(theDIV).style.display = '';
    processajax ("/"+CurrentSeasonFolder+"/includes/Suggest_Zip.php?Z="+theZip+"&theDIV="+theDIV+"&fieldZIP="+fieldZIP+"&fieldCITY="+fieldCITY+"&fieldSTATE="+fieldSTATE, document.getElementById(theDIV), "get", "");
  }
  else
  {
    var changeZip;
		
    if (window.event)
	{
		event = window.event;
	}
	
	var selectedZip = parseInt(document.getElementById("selectZip_"+theDIV).value);
	
	
	if(event.keyCode == "40")
	{ 
	  if(selectedZip == 0)
	  { changeZip = 1; }
	  else
	  { changeZip = selectedZip; }
	  
	  
	  
	  if(selectedZip < parseInt(document.getElementById("totalSugs_"+theDIV).value))
	  { 
	    document.getElementById("Zip_"+theDIV+"_"+changeZip).className = 'ZipSug';
	    selectedZip++;
	    document.getElementById("selectZip_"+theDIV).value = selectedZip;
	    document.getElementById("Zip_"+theDIV+"_"+selectedZip).className = 'ZipSug_Highlight';
	  }
	}
	if(event.keyCode == "38")
	{
	  changeZip = selectedZip;
	  document.getElementById("Zip_"+theDIV+"_"+changeZip).className = 'ZipSug';
	  selectedZip--;
	  document.getElementById("selectZip_"+theDIV).value = selectedZip;
	  document.getElementById("Zip_"+theDIV+"_"+selectedZip).className = 'ZipSug_Highlight';
	}
	if(event.keyCode == "13")
	{
	  selectSug(document.getElementById("selectZip_"+theDIV).value,theDIV,fieldZIP,fieldCITY,fieldSTATE);
	}
  }
}
function selectSug(sugNum,theDIV,fieldZIP,fieldCITY,fieldSTATE)
{
  //alert(" sugNum: "+sugNum+"\r\n theDIV: "+theDIV+"\r\n fieldZIP: "+fieldZIP+"\r\n fieldCITY: "+fieldCITY+"\r\n fieldSTATE: "+fieldSTATE+"\r\n");
  document.getElementById(theDIV).style.display = 'none';
  document.getElementById(fieldZIP).value = document.getElementById("Zipcode_"+theDIV+"_"+sugNum).value;
  document.getElementById(fieldSTATE).value = document.getElementById("State_"+theDIV+"_"+sugNum).value;
  document.getElementById(fieldCITY).value = document.getElementById("City_"+theDIV+"_"+sugNum).value;
}




//Function to create an XMLHttp Object.
function getxmlhttp(){

	// Create a boolean variable to check for a valid Internet Explorer Instance.
	var xmlhttp = false;
	
	//Check if we are using IE.
	try {
		//If the Javascript version is greater than 5.
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} 
	catch(e) {
		//If not, then use the older active x object
		try {
			//If we are using Internet Explorer.
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	catch(E) {
		//Else we must be using a non-IE browser.
		xmlhttp = false;
		}
	}
	
	//If we are using a non-IE browser, create a javascript instance of the object.
	if(!xmlhttp && typeof XMLHttpRequest != 'undefined')
	{ 
		xmlhttp = new XMLHttpRequest();
	}
	
	return xmlhttp;
}

//Function to process an XMLHttpRequest.
function processajax (serverPage, obj, getOrPost, str){
	//Get an XMLHttpRequest object for use.
	//alert("processajax");
	xmlhttp = getxmlhttp();
	if(getOrPost == "get"){
		xmlhttp.open("GET", serverPage);
		xmlhttp.onreadystatechange = function(){
			if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
				obj.innerHTML = xmlhttp.responseText;
			}
		}
		xmlhttp.send(null);
	}else{
		xmlhttp.open("POST",serverPage,true);
		xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		xmlhttp.onreadystatechange = function(){
			if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
				obj.innerHTML = xmlhttp.responseText;
			}
		}
		xmlhttp.send(str);
	}
}