function clearText(thefield)	{
	if (thefield.defaultValue == thefield.value)
		thefield.value = "";
	}


function enlargeImage(url) {
	z = window.open('','zoom_popUp','status=0,directories=0,toolbar=0,menubar=0,resizable=1,scrollbars=1,location=0');
	z.document.write('<html>\n<head>\n<title>Picture Zoom</title>\n</head>\n<body>\n<div align="center">\n<img src="' + url + '"><br>\n<form><input type="button" value="Close Window" onClick="self.close(true)"></form>\n</div>\n</body>\n</html>\n');
	z.document.close();
	z.focus(true);
	}


function openWindow(url,w,h) {
	adviceWin = window.open(url,'advice','status=no,width='+w+',height='+h+',menubar=no,scrollbars=yes');
	adviceWin.focus(true);
	}


/* when a thumbnail is moused over, need to display the mag glass icon on this image and hide it on the last image it was displayed on. */
function showHideGraphic(ID)	{
//	alert(lastID);
	document.getElementById(ID).style.display = 'block';
	if((lastID) && (lastID != ID))
		document.getElementById(lastID).style.display = 'none';
	}

/* cookies are used to remember state in the finder elements. */

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}







//used in the finder to open/close sog panels and set the classes on the headers. class is used to display a plus/minus sign.
//This gets called when the page is loaded IF a finder is present.
function changePromptStates()	{
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		if(c.indexOf("state_") == 1)	{
			stuff = c.split('=');
			id = stuff[0].substr(7);
			headerid = "finderHeader_"+stuff[0].substr(18);

//This changes the class on the finder header which will display a plus or minus sign according to whether the section is showing or hidden.
			if(stuff[1] == 'none')	{
				document.getElementById(headerid).className = "top_cat finder_header_more";
//				alert(stuff[1]);
				}
//sets the display of the SOG panel to the value in the cookie (block or none)
			document.getElementById(id).style.display = stuff[1];
			}
		else if(c.indexOf("showsoglink_") == 1)	{
			stuff = c.split('=');
//			alert(id);
			if(stuff[1] != "")	{
				changeDisplay("finder_"+stuff[1]);			
				changeDisplay("finder_morelink_"+stuff[1]);
				changeDisplay("finder_lesslink_"+stuff[1]);
				}
			}
		}
	}







// These functions are used by the advanced finder.

// used to determine whether a height needs to be set.  minheight isn't globally supported, so the content is loaded into a div and if the height of that div is over 500, then a scrolling div is added.
	
function setFinderHeight()	{
	var d = document.getElementById('finderContainer') // Get div element
	var dh = d.offsetHeight // div height
//	alert(dh);
	if(dh > 500)
		d.style.height = '500';
	}	

function changeDisplay(ID)	{
	if(document.getElementById(ID).style.display == 'block')
		document.getElementById(ID).style.display='none';
	else
		document.getElementById(ID).style.display = 'block';
	}



/*
Changes the display properties of the div containing the finder contents as well as the class on the header.  
 -> changing the display on the finder div hides/shows it.  A cookie is also set to remember state.
 -> changing the class on the finder header changes the plus sign to a minus and vice-versa.

This gets called on the page when a header is clicked.  This function should get called by changePromptStates() eventually to remove redundant code 
*/
function changeState(ID)	{
	changeDisplay("finderCase_"+ID);
	if(document.getElementById("finderCase_"+ID).style.display == 'none')
		document.getElementById("finderHeader_"+ID).className = "top_cat finder_header_more";
	else
		document.getElementById("finderHeader_"+ID).className = "top_cat finder_header_less";

	createCookie("state_finderCase_"+ID,document.getElementById("finderCase_"+ID).style.display,7);
	}




// preselects all the checkboxes on the page for the finder.

function PreselectMyItem(itemToSelect,formField)	{
	itemToSelect = itemToSelect.replace('%3A',':')
// Get a reference to the drop-down
	var myDropdownList = document.viewSortCriteria[formField];

// Loop through all the items
	for (iLoop = 0; iLoop< myDropdownList.options.length; iLoop++)	{    
		if (myDropdownList.options[iLoop].id == itemToSelect)	{
// Item is found. Set its selected property, and exit the loop
			myDropdownList.options[iLoop].selected = true;
			break;
			}
		}
	}




// makes sure all the 'view accessories' links are showing (instead of 'hide accessories') except for the sku in focus. 
function toggleShowHideLinks(SKU)	{
	
//reset all the links to 'show accessories' (which is the default behavior)
	for(i = 0; i < cartSkus.length; i++)	{
//make sure value isn't blank. here because of the blank spot in json that compensates for the comma issue in IE.
//		alert(cartSkus[i]);
		if(cartSkus[i] != '')	{
			$('showAccsLink_'+cartSkus[i]).style.display = 'block';
			$('hideAccsLink_'+cartSkus[i]).style.display = 'none';
			}
		}

//SKU isn't set, so hide the accessories list
	if(SKU == "")	{
		Effect.Shrink('contentProdlistAjaxAccsContainer');
		}
//the focus sku needs the 'show' and 'hide' accessories link toggled
	else	{
//		alert("in toggle. sku is set. sku = "+SKU+"     cartSkus.length = "+cartSkus.length);
		$('showAccsLink_'+SKU).style.display = 'none';
		$('hideAccsLink_'+SKU).style.display = 'block';
		}
	}



function showAccessories(SKU,CSVPRODS)	{

//	alert("STID = "+SKU+" and CSV = "+CSVPRODS);

//make sure csvprods are set.
	if(CSVPRODS != '' && CSVPRODS !== undefined)	{
		
//make sure accessory panel is open.
		if($('contentProdlistAjaxAccsContainer').style.display == 'none')	{
			Effect.Grow('contentProdlistAjaxAccsContainer');
			}

//blank out the accessories panel and then add the loading graphic.
		$('contentProdlistAjaxAccs').innerHTML = "";
		$('contentProdlistAjaxAccs').appendChild(LGFX);

		toggleShowHideLinks(SKU);
		updateAccList(CSVPRODS);
		}
//no products were passed so close the accessories panel.
	else
		toggleShowHideLinks();
	}


//ajax call to udpate the PRODLIST element used for accessories in the minicart.
function updateAccList(CSVPRODS) {
//	alert("updateAccList is getting run. CSV = "+CSVPRODS);
	var postBody = 'm=RenderElement&AJAX=1&format=WRAPPER&docid='+DOCID+'&element=PRODLIST_4AJAX&targetDiv=contentProdlistAjaxAccs&CSVPRODS='+CSVPRODS;
	new Ajax.Request(magic_url+'ajax/RenderElement', { postBody: postBody, asynchronous: 1,
		onComplete: function(request){handleResponse(request.responseText); } });
	}







/*
######################## for dealing with zoovy media library image generation
*/

//This function will generate an image url. no src or anything else, just the url.
//if you have to ask JT what these parameters are, you have no business being here.
function zoovyImage(IMGID,W,H,B,TAG)	{  
	if(TAG == 0 || TAG == '')
		return(image_base_url+"/W"+W+"-H"+H+"-B"+B+"/"+IMGID);   // need to add support for M and P?
	else
		return("<img src='"+image_base_url+"/W"+W+"-H"+H+"-B"+B+"/"+IMGID+"' height='"+H+"' width='"+W+"' border='0' alt='' />");
	}




/*
######################### FOR ajax add to cart ################
*/



function superAddToCart(id,pid) {

//	alert(id+' , '+pid);

//open modal.
	Modalbox.show($('detailedMiniCart'), {title: 'Shopping Cart', width: 700, height:530 });

	var postBody = 'm=AddToCart&cart='+session_id+'&pid='+pid;
	for (i = document.forms.length-1; i>=0; --i) {
		if (document.forms[i].elements['product_id']) {
			if (document.forms[i].elements['product_id'].value == pid) {
				postBody = postBody + '&' + Form.serialize(document.forms[i]);
			   new Ajax.Request(magic_url+'ajax/AddToCart', { postBody: postBody, asynchronous: 1,
			      onComplete: function(request){handleResponse(request.responseText); } }
			      ) ;
				}
			}
		}

	}









/*
######################## JSON cart class
*/


var handleCart = Class.create({


	addHandler: function(key,value,f) {
	// adds a new entry to the this.handlers e.g.:
		this.handlers[ key+"." + value ] = f;
		},



	initialize: function(cartJSON) {
		this.cartJSON = cartJSON;
		this.handlers = {};
		this.addHandler("type","product","renderItemProduct");
		this.addHandler("type","coupon","renderItemCoupon");
		},

// return an array of option id's
	listProductIDs: function() {
		r = Array();
		for(var key in this.cartJSON.product) {
			r.push(key);
			}
		return(r);
		},

	getItemById: function(stid)	{
		return this.cartJSON.product[stid];
		},

//total number of items in cart. takes into account quantities and coupons.
	getTotalCount: function()	{
		return this.cartJSON.global.totalcount;
		},

//total number of unique items in cart. disregards mulitple quantities of same item.
	getUniqueItemCount: function()	{
		return countProperties(this.cartJSON.product);
		},

//item id is the entire STI
	renderItem: function(itemObject,id)	{
//anything that needs to be done globally per item should be done here.
		if (this.handlers["itemObject."+itemObject]) {
			return(eval("this."+this.handlers["itemObject."+itemid]+"(itemObject)"));
			}
		else if (this.handlers["type."+itemObject.type]) {
			return(eval("this."+this.handlers["type."+itemObject.type]+"(itemObject,id)"));
			}
		else if (itemObject == '' || itemObject == null || itemObject == undefined) {
//failsafe for blank added as a result of IE comma issue.
			}
		else {
			return(eval("this."+this.handlers["unknown."]+"(itemObject)"));
			}
		},

	renderItemCoupon: function(itemObject,stid) {
//		$("zCartItem_"+stid).append("type = coupon and couponid = "+stid);
		},

renderItemProduct: function(itemObject,stid) {
//		console.log('in render product '+stid);
//stid container gets added to the dom becuase a child in that div MUST be on the dom.
//the rest of the container contents are unessential and NOT added to the dom.
		var attrs = {
			'style' : 'border-top:1px solid #ffd45a; padding:4px; position:relative; clear:both;',
			'id' : stid+'Container'
			}
		
		var div = new Element('div',attrs);
//changed sku_link to sku_url because of some encoding issues with IE and Chrome. This seems to globally work better.		
		div.update("<div style='float:left; margin: 0 4px 4px 0;'>"+zoovyImage(itemObject.prod_thumb,70,70,'ffffff',1)+"</div><div style='margin-bottom:3px;'><b>"+itemObject.prod_name+"</b></div><div style='padding-bottom:3px;' ><a href='"+itemObject.sku_url+"'>"+stid+"</a></div><div style='padding-bottom:3px;' >"+itemObject.price+" x "+itemObject.quantity+" = "+itemObject.extended+" <span style='padding-left:10px;'><a href='/cart.cgis'>update quantity</a></span></div><div style='padding-bottom:3px;' >"+itemObject.pogs.unescapeHTML()+"</div><div style='clear:both;'></div>");
		$('JSONCartDisplay').insert(div);

//The containers for the show and hide buttons for accessories must be part of the DOM so they can be manipulated.
		attrs = {
			'id' : 'showAccsLink_'+stid,
			'style' : 'clear:both;  height:20px;'
			}
		div = new Element('div',attrs);

		if(itemObject.accessory_products != '')	{
			div.update("<a href='#' style='display:block; cursor:pointer' onClick=\"showAccessories('"+stid+"','"+itemObject.accessory_products+"'); return false;\"><img src='"+wrapper_url+"/bm10_mc_showaccessories-150x20.png' width='150' height='20' alt='show accessories' border='0' /></a>");
			$(stid+'Container').insert(div);

			attrs = {
				'id' : 'hideAccsLink_'+stid,
				'style' : 'clear:both; display:none; margin-left:-6px; height:20px;'
				}
			div = new Element('div',attrs);
			div.update("<a href='#' style='display:block; cursor:pointer' onClick=\"toggleShowHideLinks(''); return false;\"><img src='"+wrapper_url+"/bm10_mc_hideaccessories-150x20.png' width='150' height='20' alt='show accessories' border='0' /></a>");
			$(stid+'Container').insert(div);
			}

		},

renderSimpleCart: function()	{
	var targetDiv = $('JSONSimpleCartDisplay');
	targetDiv.addClassName('chkout_simple_cart_container');
	$('content').addClassName('chkout_content');
	var headerDiv = "<div class='ztitle' id='chkoutSimpleCartHeader' style='padding:3px;'>Order Contents</div>";
	targetDiv.insert(headerDiv);
	var cartItemIds = this.listProductIDs();
	cartSkus.length = 0;  //empty the cart skus array.
// the -1 in the length below is to compensate for the last entry in the json being blank. if/when the cart json is upgraded, CHANGE THIS.
	for ( var i=0, len=cartItemIds.length-1; i < len; ++i) {
		var itemObject = this.getItemById(cartItemIds[i]);
		stid = cartItemIds[i];
//stid container gets added to the dom becuase a child in that div MUST be on the dom.
//the rest of the container contents are unessential and NOT added to the dom.

		var attrs = {
			'style' : 'border-top:1px solid #ffffff; padding:4px; position:relative; clear:both;',
			'id' : stid+'ContainerChkout',
			'className' : 'ztable_row'
			}
		
		var div = new Element('div',attrs);
//changed sku_link to sku_url because of some encoding issues with IE and Chrome. This seems to globally work better.		
		div.update("<div style='float:right; width:140px;'><div style='margin-bottom:3px;'>"+itemObject.prod_name+"</div><div style='padding-bottom:3px;' >"+itemObject.price+" x "+itemObject.quantity+" = "+itemObject.extended+" </div><div style='padding-bottom:3px;' >"+itemObject.pogs.unescapeHTML()+"</div></div><div style='float:left;'>"+zoovyImage(itemObject.prod_thumb,40,40,'efefef',1)+"</div><div style='clear:both;'></div>");
		targetDiv.insert(div);
		}
	},


	renderTotals: function()	{
		if(this.cartJSON.global.totalcount > 0)	{
			$('minicartTotals').innerHTML = "";  //blank out current contents.

			$('minicartTotals').innerHTML += "<div style='float:left;'>"+this.cartJSON.global.totalcount+" items:</div><div style='float:right;'>"+this.cartJSON.global.subtotal+"</div><div style='clear:both; padding-bottom:2px;'></div>";
			
			if(this.cartJSON.global.salestax != null)
				$('minicartTotals').innerHTML += "<div style='float:left;'>FL. Sales Tax ("+this.cartJSON.global.salestax.taxrate+"%)</div><div style='float:right;'>"+this.cartJSON.global.salestax.taxtotal+"</div><div style='clear:both; padding-bottom:2px;'></div>";
					
			if(this.cartJSON.global.bonding != null)
				$('minicartTotals').innerHTML += "<div style='float:left;'>Bonding</div><div style='float:right;'>"+this.cartJSON.global.bonding.value+"</div><div style='clear:both; padding-bottom:2px;'></div>";
					
			if(this.cartJSON.global.shipping != null)
				$('minicartTotals').innerHTML += "<div style='float:left;'>Shipping/<a href='#' onClick=\"window.open('"+category_url+"/help.surcharge-explanation/?wrapper="+popup_theme+"','advice','status=no,width=650,height=500,menubar=no,scrollbars=yes'); return false\">Surcharge</a>:</div><div style='float:right;'>"+this.cartJSON.global.shipping.surchargevalue+"</div><div style='clear:both; padding-bottom:2px;'></div>";
			
			$('minicartTotals').innerHTML += "<div style='float:left;'>Total</div><div style='float:right;'>"+this.cartJSON.global.grandtotal+"</div><div style='clear:both; padding-bottom:2px;'></div>";
			}
		},
		
	renderCart: function()	{
//		console.log('got into renderCart');
		$('JSONCartDisplay').innerHTML = ""; //remove loading message or any existing cart items displayed.
//		console.log('got past resetting inner html');
		var cartItemIds = this.listProductIDs();
//		console.log(cartItemIds);
		cartSkus.length = 0;  //empty the cart skus array.
		for ( var i=0, len=cartItemIds.length; i < len; ++i) {
			var itemObject = this.getItemById(cartItemIds[i]);
			this.renderItem(itemObject,cartItemIds[i]);
			if(itemObject.accessory_products != '' && cartItemIds[i] != '')	{
				cartSkus.push(cartItemIds[i]);
				lastCartSkuAccs = cartItemIds[i]; //will get reset each time in the loop. will contain last stid of items in cart that has accessories.
				}
			}
		this.renderTotals();
//update and display the accessories to match the last item in the cart that has accessories, if present.
//		alert("lastCartSku is set: "+lastCartSkuAccs);
		if(lastCartSkuAccs){
			showAccessories(lastCartSkuAccs,jsonCart.product[lastCartSkuAccs].accessory_products)}
		else{
			toggleShowHideLinks()
			};
		
		}
	});

