function showCart(){

var cookies=document.cookie;  //read in all cookies
var start = cookies.indexOf("ss_cart_" + serialNumber + "="); 
var cartvalues = "";
var linecount = 0;
var start1;
var end1;
var tmp;

if (start == -1)  //No cart cookie
{
  document.write("<span id=\"price\">$00.00<\/span>");
  document.write("<span id=\"items\">(0 Items)<\/span>");
}
else   //cart cookie is present
{
  start = cookies.indexOf("=", start) +1;  
  var end = cookies.indexOf(";", start);  

  if (end == -1)
  {
    end = cookies.length;
  }

  cartvalues = unescape(cookies.substring(start,end)); //read in just the cookie data

  start = 0;
  var total = "";
  while ((start = cartvalues.indexOf("|", start)) != -1)
  {
    start++;
    end = cartvalues.indexOf("|", start);
    if (end != -1)
    {
      linecount++;

      if (linecount == 2) // Total Quantity of Items
      {
        tmp = cartvalues.substring(start,end);
        colon = tmp.indexOf(":", 0);
         	total += "<span id=\"items\">(";
        	total += tmp.substring(colon+1,end - start);
        if ((tmp.substring(colon+1,end - start)) == 1 )
        {
          total += " Item";
        }
        else
        {
          total += " Items";
        }
        total += ")<\/span>"
      }
     

      if (linecount == 3)  // Product Subtotal
      {
        tmp = cartvalues.substring(start,end);
        colon = tmp.indexOf(":", 0);
        document.write("<span id=\"price\">");
        document.write(tmp.substring(colon+1,end - start));
        document.write("<\/span>");
        document.write(total)
      }

      start = end;
    }
    else
      break;
    }
  } // end while loop

  //close minicart HTML
}
/* end showCart() */



function initTabs(){
	$$(".tabs li").each(function(li, index){
		if(index == 0){
			li.addClassName("active")
		}
		li.observe("click", processTabClick).observe("mouseover", processTabOver).observe("mouseout", processTabOut)
	})
}
function processTabOver(event){
	Event.element(event).up("li").addClassName('over')
}
function processTabOut(event){
	Event.element(event).up("li").removeClassName('over')
}
function processTabClick(event){
	liClicked = Event.element(event).up("li");
	var i = -1;
	$$(".tabs li").each(function(li, index){
		if(li == liClicked){
			i = index
			li.addClassName("active")
		}else{
			li.removeClassName("active")
		}
	})
	$$(".tabscontent > div").each(function(d, index){
		if(index == i){
			d.show();
			fixCategoryList(d);
		}else{
			d.hide();
		}
	})
}
function fixCategoryList(obj){
	if(!obj){
		$$(".tabscontent > div")[0].select(".categorylist .categorylistname").each(function(d){
			var w = d.getWidth();
			var left = ((240 - 2*10) - w )/2
			d.setStyle({left: left + "px"})
		})	
	}else{
		obj.select(".categorylist .categorylistname").each(function(d){
			var w = d.getWidth();
			var left = ((240 - 2*10) - w )/2
			d.setStyle({left: left + "px"})
		})			
	}
}




function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name){
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);	
}


function submitForm(frm){
	frm = $(frm);
	
	var check = true;
	
	var defaultValues = {
		 getafreesample: {
			Address: 	"*Address",
			City: 		"*City",
			State: 		"*State",
			Zip: 		"*Zip/Postal Code",
			AccountNumber: "*FedEx / UPS Account Number"
		},
		getaquote :{
			HowManyItems: "*How many items?",
			WhenDoYouItems: "*When do you items?",
			HowManyColors: "*How many colors?",
			ShipToZIPPostalCode: "*Ship to ZIP / Postal Code"
		}
	}
	
	frm.select("input.required,select.required").each(function(o){
		if(o.nodeName == "INPUT"){
			if(o.value == defaultValues[frm["formtype"].value][o.name] || o.value.length == 0){
				o.addClassName("error")
				check = false;				
			}else{
				o.removeClassName("error")				
			}
		}else{
			//select
			if(o.value == ""){
				o.addClassName("error")
				check = false;
			}else{
				o.removeClassName("error")
			}
		}
	})
		
	if(check){
	
		frm.up(".popup").select(".loading")[0].show();
		frm.up(".popup").select(".submit")[0].hide();
	
		new Ajax.Request(frm.action, {method: "post",
			parameters: frm.serialize() + "&customerId=" + customerId,
			onSuccess: function (transport){			
				frm.up(".popup").select(".loading")[0].removeClassName("loading").addClassName("loadingdone").update("Your request has been sent.");
				
				var googleConversionImage = new Image()
				if(frm["formtype"].value == "getafreesample"){					
					googleConversionImage.src = "http://www.googleadservices.com/pagead/conversion/1020973514/?label=S14BCNas2wIQyqPr5gM&amp;guid=ON&amp;script=0";
				}else{
					googleConversionImage.src = "http://www.googleadservices.com/pagead/conversion/1020973514/?label=iIiyCN6c2wIQyqPr5gM&amp;guid=ON&amp;script=0";
				}
			},
			onFailure: function(){
				frm.up(".popup").select(".loading")[0].removeClassName("loading").addClassName("loadingdone").update("Your request has NOT been sent. Try again later.");
			}
		})		
	}
	return false;
}

function updateLog(){
	var parameters = "action=update&sbid=" + ss_sbid
	$("sc-address-box").select("input,select").each(function(o){
		parameters += "&" + o.readAttribute("name") + "=" + escape(o.value);
	})	
	
	new Ajax.Request(baseUrl + "/log.php",{
		method: "post",
		parameters: parameters
	})
	
}

function removeLog(sbid){
	new Ajax.Request("/log.php",{
		method: "post",
		parameters: "action=remove&sbid=" + sbid
	})
}

var shippingInfo = ["Email", "Company", "ShipFirst", "ShipLast", "ShipPhone", "ShipAddress", "ShipCity", "ShipState", "zip_code", "country"]
var domain = ".backwoods.com"
//var domain = "localhost.com"
function preSubmit(){
	var state = $$("*[name='ShipState']")[0].value
	var zip = $$("input[name='zip_code']")[0].value
	if($$("*[name='country']").length > 0){
		var country = $$("*[name='country']")[0].value
	}else{
		var country = "United States"
	}
	
	if(state == "n" || zip == "" || country == ""){
		alert("In order to calculate your order's shipping rates we will need for you to complete the following three fields: \n\nState \nZip / Postal Code \nCountry");
		return false;
	}
	var email = $$("*[name='Email']")[0].value
	if(email == ''){
		alert("Please enter email address")
		return false;
	}
	
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
    if(!emailPattern.test(email)){
    	alert("Please enter valid email address")
    	return false;
    }
    return true;	
}
function saveShippingInfo(event){
	
	for(var i = 0; i < shippingInfo.length; i++){
		var id = "ss_" + shippingInfo[i];
		if(shippingInfo[i] == "zip_code"){
			setCookie(id, $$("*[name='zip_code']")[0].value, "", "/", domain);
		}else if(shippingInfo[i] == "country"){
			if($$("*[name='country']").length > 0){
				setCookie(id, $$("*[name='country']")[0].value, "", "/", domain);
			}
		}else{
			setCookie(id, $(id).value, "", "/", domain);
		}
	}
	//need to remove empty coupons and gift certificate
	$$("input[name='coupon_code']").each(function(o){
		if(o.value == "Coupon Code"){
			o.disabled = true;
		}
	})
	$$("input[name='giftcert_code']").each(function(o){
		if(o.value == "Certificate Number"){
			o.disabled = true;
		}
	})
	$$("input[name='giftcert_pin']").each(function(o){
		if(o.value == "PIN"){
			o.disabled = true;
		}
	})
	
	
	
	return true;
}
function saveShippingInfoCheckout(){
	
}
function loadShippingInfo(){
	$$("form.order")[0].observe("submit", saveShippingInfo)
	
	for(var i = 0; i < shippingInfo.length; i++){
		var id = "ss_" + shippingInfo[i];
		if(shippingInfo[i] == "zip_code"){
			var newValue = getCookie(id)
			if(newValue && newValue.length > 0 && newValue != null){
				$$("*[name='zip_code']")[0].value = newValue;
				$$("*[name='zip_code']")[0].defaultValue = newValue;
			}
		}else if(shippingInfo[i] == "country"){
			var newValue = getCookie(id)
			if(newValue && newValue.length > 0 && newValue != null){
				if($$("*[name='country']").length > 0){
					$$("*[name='country']")[0].value = newValue;
				}
			}
		}else{
			if($(id)){
				var newValue =getCookie(id);
				if(newValue && newValue.length > 0 && newValue != null){
					$(id).value = newValue;
				}
			}
		}
	}
}
function loadShippingInfoOnCheckout(){
	for(var i = 0; i < shippingInfo.length; i++){
		var id = "ss_" + shippingInfo[i];
		input = null;
		input2 = null;
		
		var newValue = getCookie(id)
		
		switch(shippingInfo[i]){
			case "Email":
				input = $$("*[name='" + shippingInfo[i] + "']")[0];
				break;
			case "Company":
				input = $$("*[name='ShipCompany']")[0];
				break;
			case "ShipFirst":
				input = $$("*[name='" + shippingInfo[i] + "']")[0];
				//input2 = $$("*[name='First']")[0];
				break;
			case "ShipLast":
				input = $$("*[name='" + shippingInfo[i] + "']")[0];
				//input2 = $$("*[name='Last']")[0];
				break;
			case "ShipPhone":
				input = $$("*[name='" + shippingInfo[i] + "']")[0];
				//input2 = $$("*[name='Phone']")[0];
				break;
			case "ShipAddress":
				input = $$("*[name='" + shippingInfo[i] + "']")[0];
				//input2 = $$("*[name='Address']")[0];
				break;
			case "ShipCity":
				input = $$("*[name='" + shippingInfo[i] + "']")[0];
				//input2 = $$("*[name='City']")[0];
				break;
			case "ShipState":
				if(newValue != "n"){
					input = $$("*[name='" + shippingInfo[i] + "']")[0];
					//input2 = $$("*[name='State']")[0];
				}
				break;
			case "zip_code":
				input = $$("*[name='ShipZip']")[0];
				//input2 = $$("*[name='Zip']")[0];
				break;
			case "country":
				input = $$("*[name='ShipCountry']")[0];
				//input2 = $$("*[name='Country']")[0];
				break;
		}

		
		if(input && newValue && newValue.length > 0 && newValue != null){
			input.value = newValue;
		}
		if(input2 && newValue && newValue.length > 0 && newValue != null){
			input2.value = newValue;
		}
	}	
}

function show_zip_loading(){
	if($("zip_loading")){
		$("zip_loading").show();//slideDown({duration: 0.5});
	}
}
function stop_zip_loading(){
	if($("zip_loading")){
		$("zip_loading").hide();//slideUp({duration: 0.5})
	}
}

function show_zip_error(msg){
	if($("zip_error")){
		$("zip_error").update(msg).show();
	}
}
function hide_zip_error(){
	if($("zip_error")){
		$("zip_error").hide();
	}
}

function zip_changed_process(){
	var func;
	func = document.getElementsByName("function");
	for (i = 0; i < func.length; i++) { 
		if (func[i].type == "hidden") {
      	//zip_recalc = 1;
      	
      	$('step3').show();
      	
      	show_zip_loading();      

      	var oldValue = func[i].value;

      	func[i].value = "zip_code_changed";

		var form = $$("form.order")[0]
	
		var parameters = form.serialize();
	
		parameters = parameters.replace("coupon_code", "coupon_code_");
		parameters = parameters.replace("giftcert_code", "giftcert_code_");
		parameters = parameters.replace("giftcert_pin", "giftcert_pin_");
	
		new Ajax.Request(form.action, {
			method: form.method,
			parameters: parameters,
			onSuccess: function(transport){
				document.order.zip_code.defaultValue = document.order.zip_code.value;
			
				var html = transport.responseText;
				
				//finding errors
				
				var start = html.indexOf('<div class="scerrors">')
				if(start > 0){
					end = html.indexOf("</div>", start) + 6;
					
					if(html.substring(start, end).indexOf("ups_error") > 0){
						error = html.substring(start, end).replace(/(<([^>]+)>)/ig,"").replace(/(\r\n|\n|\r)/gm,"")
						show_zip_error(error);
					}else{
						hide_zip_error();
					}
				}else{
					hide_zip_error();
				}
			
				var start = html.indexOf('<table class="taxnship">')
			
				if(start > 0){
					end = html.indexOf('</table>', start) + 8;
					html = html.substring(start, end)				
					$('zipandtaxbox').update(html);					
				}else{
					show_zip_error("Shipping costs cannot be computed for some items in your cart. Please contact the merchant.");
				}
				stop_zip_loading();
			}			
		})
	
		func[i].value = oldValue;
				
	
		}
  	}
}
