/**
 * All materials custom written for Irrigation Direct by Xavier Berkeley
 *
 * @copyright	2009 Xavier Berkeley, LLC
 */
 /* All on-ready functions that we want to load to initialize the page should be included here 
 - note that prototype will aslo be generating some onready events that are default with 
   magento and will run asynchronously from this onready */

jQuery(document).ready(function(){
jQuery("div.col-left.sidebar").append(jQuery("#leftNav").remove());
});

function XbShippingObject()
{
	this.phrases=new Object();
	this.data=new Object();
	this.paint=function(){
		this.loadCartSubtotal();
		this._updateCostsHTML();
		this._updateMessagesHTML();
		this._prepareForm();
		this._clearMask();
		jQuery(".btn-remove").bind("click",XBPrepareDelete);
		return this;
	};
	this.init=function(){
		this.loadData();
		//window.miniZipForm = new VarienForm('mini-ship-form', true);
		this.set('originalSubtotal',this.get('subtotal')).set('originalZipCode',this.get('zipCode')).set('noFailureMessages',true);
		if(this.hasValidZip() && this.isFreeUnknown()){
			this.checkZip();
		}
		this.promptForZipIfNecessary();
		if(jQuery.cookie("shipzippagewait")){jQuery.cookie("shipzippagewait",Math.max(jQuery.cookie("shipzippagewait")-1,1),{path:'/'});}else{jQuery.cookie("shipzippagewait",1,{path:'/'});}
		return this;
	};
	this.loadData=function(){
		if(typeof XBShippingData=='object'){
			for(datagroup in XBShippingData){
				for(data in XBShippingData[datagroup]){
					this.set(data,XBShippingData[datagroup][data]);
				}
			}
		}
		if(typeof XBShippingMessages=='object'){
			for(datagroup in XBShippingMessages){
				for(data in XBShippingMessages[datagroup]){
					this.setPhrase(data,XBShippingMessages[datagroup][data]);
				}
			}
		}
		this.loadCartSubtotal();
		this.setValuesFromCookie();
		return this;
	};
	this.promptForZipIfNecessary=function(){if(this.get('promptForZip')==1&&!this.hasValidZip()&&jQuery.cookie("shipzippagewait")==1&&window.location.href.indexOf('-tubing-')!=-1){this.showZipDialog();}};
	this.showZipDialog=function(){try{jQuery("#shipping-zone-mask").appendTo("body").height(jQuery(document).height()).show();jQuery("#shipping-zone-wrapper").appendTo("body").center().css("z-index","9999").show();jQuery("#shipping-zone-zip").focus();}catch(e){}};
	this.hideZipDialog=function(){jQuery("#shipping-zone-wrapper").hide();jQuery("#shipping-zone-mask").hide();jQuery.cookie("shipzippagewait",25,{path:'/'});};
	this.loadCartSubtotal=function(){
		cartSub=parseFloat(((jQuery("a#minicart-cart span.price").html()).substring(1)).replace(',',''));
		if(cartSub!=this.get('subtotal')){
			this.set('subtotal',cartSub).set('shippingEstimate',0.00);
		}else{
			this.set('subtotal',cartSub);
		}
	};
	this.getSpendMoreAmount=function(){
		formatted=((arguments.length>0)&&(arguments[0]==true));
		try{
			amount=(this.isFreeShippingAmount())?0.0000:(this.get('freeShippingMinimum')-this.get('subtotal'));
			return formatted ? XBUtil.formatCurrency(amount,2):amount;
		}catch(e){
			if(formatted){
				return XBUtil.formatCurrency(0.0000,2);
			}else{
				return 0.0000
			}
		}
	};
	this.isValidZip=function(){
		z=arguments[0];
		if(!z){
			return false;
		}
		if(z.length<5||z.length>10){
			return false;
		}
		return true;
	};
	this.hasValidZip=function(){
		return this.isValidZip(this.get('zipCode'));
	};
	this.get=function(){
		try{
			return this.data[arguments[0]];
		}catch(e){
			return 0;
		}
	};
	this.set=function(){
		this.data[arguments[0]]=arguments[1];
		return this;
	};
	this.setPhrase=function(){
		this.phrases[arguments[0]]=arguments[1];
		return this;
	};
	this.getPhrase=function(){
		if(arguments.length==2){
			try{
				return XBUtil.sprintf(this.phrases[arguments[0]],arguments[1]);
			}catch(e){
				return '';
			}
		}else{
			try{
				return this.phrases[arguments[0]];
			}catch(e){
				return '';
			}
		}
	};
	this.getFreeShippingMessage=function(){
		//if(!this.shouldShowFreeMessage()&&this.get('noFailureMessages')){
		//	return '';
		//}
		if(this.isFreeNotAllowed()){
			return this.getPhrase('noFreeQualify');
		}
		else if(this.isFreeShipping()){
			return this.getPhrase('freeAvailable');
		}
		else if(this.isFreeAllowed()){
			return this.getPhrase('freeQualify',new Array(this.getSpendMoreAmount(true)));
		}
		else if(this.isFreeShippingAmount()){
			return this.getPhrase('freeMayBeAvailable');
		}
		return '';
	};
	this.getRateQuoteMessage=function(){
		return this.getPhrase('quoteStatusError');
	};
	this.getShippingAmount=function(){
		try{
			if(this.isFreeShipping()){
				return 0.00;
			}
			return this.get('shippingEstimate');
		}catch(e){
			return 0.00;
		}
	};
	this.getShippingDisplayAmount=function(){
	};
	this.shouldShowFreeMessage=function(){
		return !this.isFreeNotAllowed();
	};
	this.isFreeShippingAmount=function(){
		return this.get('subtotal')>=this.get('freeShippingMinimum');
	};
	this.isFreeShipping=function(){
		return (this.isFreeAllowed()&&this.isFreeShippingAmount());
	};
	this.isFreeAllowed=function(){
		return this.get('freeShippingAvailable')==1;
	};
	this.isFreeNotAllowed=function(){
		return this.get('freeShippingAvailable')==2;
	};
	this.isFreeUnknown=function(){
		return this.get('freeShippingAvailable')==0;
	};
	this.isUSPSAllowed=function(){
		return(this.get('weight')&&(this.get('weight')<2.0001)&&!this.isEmptyCart());
	};
	this.isEmptyCart=function(){
		return this.get('subtotal')<0.01;
	};
	this.isQuoteValid=function(){
		try{
			return this.get('subtotal')==this.get('originalSubtotal');
		}catch(e){
			return true;
		}
	};
	this.isFreeZipValid=function(){
		try{
			return this.get('zipCode')==this.get('originalZipCode');
		}catch(e){
			return true;
		}
	};
	this.isFreeZipReloadAllowed=function(){
		return false ;
		if(this.get('forceFreeZipReload')){
			return true;
		} 
		return false;
	};
	this.setValuesFromCookie=function(){
		if(!this.get('cookieValue')){
			return this;
		}
		if(this.hasValidZip()){
			return this;
		}
		try{
			cv=this.get('cookieValue').split("___");
			if(this.isValidZip(cv[0])){
				this.set('zipCode',cv[0]);
				if(cv.length>1){
					st=parseInt(cv[1]);
					if(st<3&&st>-1){
						this.set('freeShippingAvailable',st);
					}
				}
			}
		}catch(e){}
		return this;
	};
	this.isQuoteReloadAllowed=function(){
		return true ;
		return (!this.isEmptyCart()&&!this.isFreeShipping()&&(!this.isQuoteValid()||!this.isFreeZipValid()))
		};
	this.checkZip=function(){
		jQuery("#minicart-show").stopTime("hide");
		if(arguments.length>0){
			if(this.isValidZip(arguments[0])){
				this.set('zipCode',arguments[0]);
			}else{
				return false;
			}
		}
		if(!this.hasValidZip()){
			this.set('shippingEstimate',0.00).paint();
			return false;
		}
		if(this.isFreeZipReloadAllowed()){
			this._prepareMask();
			this._checkFreeShipping();
		}
		if(this.isQuoteReloadAllowed()){
			this._prepareMask();
			this.set('originalZipCode',this.get('zipCode')).set('originalSubtotal',this.get('subtotal'));
			this._checkRateQuote();
		}
	};
	this._checkFreeShipping=function(){
		jQuery.getJSON("/shippingzip",{is_ajax:1,zip_code:this.get('zipCode')},function(data){
			XBS.set('noFailureMessages',false).set('state',data[0]['state_abbreviation']).set('city',data[0]['city_name']).set('freeShippingAvailable',parseInt(data[0]['status'])).paint().set('noFailureMessages',true).set('originalZipCode',data[0]['zip_code']);
		});
	};
	this._checkRateQuote=function(){       
		jQuery.getJSON("/xbcheckout/onepage/miniSaveShipping/",{is_ajax:1,zip_code:this.get('zipCode')},function(data){
			try{
				if(data.status=='success'){
					XBS.set('shippingEstimate',parseFloat(data.rate)).set('quoteStatus',null).set('state',data.state_abbreviation).set('city',data.city_name).set('freeShippingAvailable',parseInt(data.freeShippingAvailable)).set('title',data.title).set('code',data.code).paint();
				}
				else{
					XBS.set('quoteStatus',data.status).set('shippingEstimate',0.00).set('freeShippingAvailable',data.freeShippingAvailable).paint();
					jQuery("#mini-ship-messages-js-quote").html('<div class="error-msg" style="margin:5px;">'+XBS.getRateQuoteMessage()+'</div>');
				}
			}catch(e){
				alert(e);
				XBS.set('subtotal',0.0000).set('shippingEstimate',0.00).paint();
			}
		});};
	this._setPriceDefaults=function(){
		if(isNaN(this.get('subtotal'))){
			this.set('subtotal',0.0000);
		}
		if(isNaN(this.get('shippingEstimate'))){
			this.set('shippingEstimate',0.00);
		}
	};
	this._updateCostsHTML=function(){
		this._setPriceDefaults();
		jQuery("#mini-ship-subtotal-product").html(XBUtil.formatCurrency(this.get('subtotal')));
		var sTitle="";
		if(this.isFreeShipping()){
			sCost='FREE';
			sTitle="UPS Ground";
		}else if((parseFloat(this.get('subtotal'))==0.0)&&this.hasValidZip()){
			sCost=XBUtil.formatCurrency(0.00,2);
		}else if(this.get('quoteStatus')){
			sCost=XBUtil.formatCurrency(0.00,2);
		}else if(this.get('shippingEstimate')>0){
			sCost=XBUtil.formatCurrency(this.get('shippingEstimate'));
			sTitle=this.get('shippingTitle')+" ("+this.get('weight').toString()+"lbs)";
		}else if(this.hasValidZip()){
			sCost=XBUtil.formatCurrency(0.00,2);
		}else{
			sCost=this.getPhrase('defaultPrice');
		}
            jQuery("#mini-ship-subtotal-shipping").attr("title",sTitle).html(sCost);
            jQuery("#mini-ship-subtotal-total").html(XBUtil.formatCurrency(this.get('subtotal')+this.getShippingAmount()));
        
	};
	this._updateMessagesHTML=function(){
		if(this.isFreeShipping()){
			msgclass='success-msg';
			jQuery(".userShippingMessage").html(this.getFreeShippingMessage()).removeClass("noticemsg").addClass("successmsg").css("visibility","visible") ;
		}else if(this.isFreeAllowed()){
			msgclass='notice-msg';
			jQuery(".userShippingMessage").html(this.getFreeShippingMessage()).removeClass("successmsg").addClass("noticemsg").css("visibility","visible") ;
		}else{
			msgclass='nothing';
			if(!this.hasValidZip()){jQuery(".userShippingMessage").css("visibility","visible");}else{jQuery(".userShippingMessage").css("visibility","hidden");}
		}
		jQuery("#mini-ship-messages-js").html(jQuery("<div>").addClass(msgclass).css("margin","5px").html(this.getFreeShippingMessage()));
		if(this.get('city') == ''){jQuery("#shippingLocation").click(function(){XBS.showZipDialog();}).html('<span id="ship-to-link" title="click to change your shipping location">Enter your Shipping Destination</span>');}else{jQuery("#shippingLocation").click(function(){XBS.showZipDialog();}).html('<span id="ship-to-link" title="click to change your shipping location">Shipping to:</span> '+this.get('city')+', '+this.get('state'));}
		
	};
	this._prepareForm=function(){
		jQuery("#mini-ship-input-zip").attr("value",(this.hasValidZip())?this.get('zipCode'):"Zip Code").bind("focus",XBZipFocus);
		jQuery("#mini-ship-form").unbind("submit").bind("submit",function(){
			XBS.checkZip(jQuery("#mini-ship-input-zip").attr("value"));return false;
		});
		jQuery("div.xbButton.xbButtonCalculateShipping").unbind("click").bind("click",function(){
			XBS.checkZip(jQuery("#mini-ship-input-zip").attr("value"));
			return false;
		});
	};
	this._prepareMask=function(){
		jQuery("#mini-ship-messages-js-quote").html("");
		jQuery("#mini-ship-messages-js").html("");
		jQuery("#mini-ship-mask").height(jQuery("#mini-ship").height()).show();
	};
	this._clearMask=function(){
		jQuery("#mini-ship-mask").hide();
	};
	this.prepareDelete=function(){
		this.set('subtotal',0.0000).set('shippingEstimate',0.00).paint();
	};
};
function XBPrepareDelete(){
	if(typeof XBS=='undefined'){
		window.XBS=new XbShippingObject();
	}
	XBS.prepareDelete();
};
function XBZipFocus(){
	jQuery(this).unbind("blur",XBZipFocus);
	if(jQuery(this).attr("value")=="Zip Code"){
		jQuery(this).attr("value","");
	}
};
jQuery(document).ready(function(){
	window.XBS=new XbShippingObject() ;
	XBS.init().paint();
});

var XBUtil={
formatCurrency:function(){
	fixed=2;if(arguments.length>1){fixed=arguments[1];}
	try{
	dc=parseFloat(arguments[0].toString().replace(/\$|\,/g,'')).toFixed(fixed).toString().split('.');
	if(isNaN(dc[0])){rval=0.0;return "$"+rval.toFixed(fixed).toString();}
    dollar=dc[0];cents=dc[1];var rgx = /(\d+)(\d{3})/;
    while (rgx.test(dollar)){dollar=dollar.replace(rgx, '$1'+','+'$2');}
	return "$"+dollar+"."+cents;
	}catch(e){rval=0.0;return "$"+rval.toFixed(fixed).toString();}
	},
sprintf:function(){
	str='';s=arguments[0];if(!s){return '';}s=s.split('%s');r=arguments[1];r.push('');for(i=0;i<s.length;i++){str+=s[i]+r[i]}return str;
	}
};
/* End of XBShipping */

function updateQuickCart( content ) {
    jQuery(".quickCart .cartwrap").css("visibility","hidden");
    jQuery(".quickCart, #minicart-show, #minicart-chad").unbind("mouseenter").unbind("mouseleave");
    
	jQuery(".quickCart").slideUp(300, function() {
		jQuery("#minicart").html( content );
		createQuickcartLinks();
		//XBShipping.updateSubtotal();
		//XBShipping.prepareQuickCartShipping();
		//XBShipping.getRate();
		try{XBS.init().paint().checkZip();}catch(e){}
		jQuery("#minicart-show").trigger("click");
		setupQuickcartEvents();
		startCartHideTimer(7500);
	});
}

// start timer to hide cart
function startCartHideTimer(duration) {
    if ( jQuery("#mini-ship-input-zip:focus").size() > 0 ) {
        return false;
    }
	jQuery("#minicart-show").stopTime("hide");
	jQuery("#minicart-show").oneTime(duration, "hide", function() {
        jQuery(".quickCart .cartwrap").css("visibility","hidden");
		jQuery(".quickCart").slideUp(300, function() {
            jQuery("#minicart-show").stopTime("ch-hide");
            jQuery("#minicart-chad").slideDown(200, function() {
                startChadHideTimer(6000);
            });
        });
		jQuery(document).unbind("click");
		createQuickcartLinks();
		setupQuickcartEvents();
	});
}

// set up click toggle functionality for #minicart-show
function createQuickcartLinks() {
	jQuery("#minicart-show, #minicart-chad").unbind("click").click( function() {
		jQuery("#minicart-show").unbind("click");
		jQuery(this).stopTime("hide");
        jQuery(".quickCart .cartwrap").css("visibility","hidden");
		jQuery(".quickCart").slideDown(500, function() {
				// on click anywhere but the update cart OK box or quickCart, hide quickCart
			jQuery(document).unbind("click").click( function(e) {
				setupQuickcartEvents();
				if ( jQuery(e.target).parents("#minicart").size() == 0 && jQuery(e.target).parents(".ajaxcartpro_confirm").size() == 0 ) {
                    jQuery(".quickCart .cartwrap").css("visibility","hidden");
					jQuery(".quickCart").slideUp(300);
					createQuickcartLinks();
					jQuery(document).unbind("click");
				}
			});
			jQuery("#minicart-show, #minicart-chad").unbind("click").click( function() {
				jQuery("#minicart-show").unbind("click");
				jQuery(document).unbind("click");
                jQuery(".quickCart .cartwrap").css("visibility","hidden");
				jQuery(".quickCart").slideUp(300, function(){
					createQuickcartLinks();
					setupQuickcartEvents();
				});
			});
            jQuery(".quickCart .cartwrap").hide().css("visibility","visible").fadeIn(200);
		});
	});
    jQuery("#minicartinner button.cart-button").attr("onclick","").unbind("click").click( xbCartLink );

}

function showProgressBlockFor(el) {
            jQuery(el).next("dd.complete").slideToggle(200);
}
function setupQuickcartEvents() {
	// set width of quickCart so it looks right on first use in ie
	jQuery(".quickCart").css("width","240px");
	
	// Stop timer when mouse enters quickcart or minicart-show, start when it leaves
	jQuery(".quickCart, #minicart-show, #minicart-chad").unbind("mouseenter").unbind("mouseleave").hover( function() {      
			jQuery("#minicart-chad").slideDown(200);
            jQuery("#minicart-show").stopTime("hide");
            jQuery("#minicart-show").stopTime("ch-hide");
			// console.log("stop");
		}, function() {
			jQuery("#minicart-show").stopTime("hide");
            jQuery("#minicart-show").stopTime("ch-hide");
			startCartHideTimer(2000);
            startChadHideTimer(6000);
		});
}
function jtest(){
//alert(XBShipping.AVAILABLE);
}
// tierPricing charts
	function hideTierPriceCharts() {
		jQuery(".listTierPrice").each( function() {
			if ( jQuery(this).parents(".tierPricesIcon").size() > 0 ) {
				jQuery(this).css("visibility","hidden");
			}
			else {
				jQuery(this).css("visibility","visible").css("display","block");
			}
		});
		jQuery(document).unbind("click");
	}
	
	function setUpTierPriceCharts() {
		hideTierPriceCharts();
		jQuery(".tierPricesIcon").each( function() {
			jQuery(this).unbind("click").click( function() {
				hideTierPriceCharts();
				jQuery(this).children(".listTierPrice").css("visibility","visible");
				setTimeout('jQuery(document).click( function(e) { if ( jQuery(e.target).hasClass(".tierPricing") == false && jQuery(e.target).parents(".tierPricing").size() == 0 ) { hideTierPriceCharts(); setUpTierPriceCharts(); } });',100);
			});
		});
	}
	
    function setupCartTierPrices() {
        // initial setup of tier price blocks for the cart
        jQuery(".checkout-cart-index .cart-table .listTierPrice").each( function() {
            jQuery(this).append('<div class="yourPrice" style="width: 110px; position: absolute; display: none;"><div class="yourPriceText" style="padding: 1px 5px; float: left; text-align: left; width: 90px; font-size: 10px; color: #000000; font-weight: normal; line-height: 12px;">Your price</div><div style="float: right; width: 10px; color: #FF0000; font-weight: bold; line-height: 12px; font-size: 12px;">&raquo;</div></div>');
        });
        // Alignment fix for IE
        if ( jQuery.browser.msie ) {
            jQuery(".yourPrice").css("padding-top","2px");
        }
        
        // Set up "update cart" links for each row
        /*jQuery(".updateCart").each( function() {
            jQuery(this).click( function() {
                jQuery(this).parents("form").submit();
                return false;
            });
        });
        */
        // and the big one at the bottom
        jQuery(".update-cart").click( function() {
                jQuery("#cartForm").submit();
        });
        // On product page, highlight appropriate tier price for your quantity
        jQuery(".checkout-cart-index .cart-table .qtyBox .qty").each( function() {
            jQuery(this).change( function() {
                var qty = jQuery(this).val();
                var origQty = jQuery(this).siblings(".hqty").text();
                // Show or hide update cart button depending on whether quantity have changed
                if ( qty != origQty ) {
                    // jQuery(this).parents("td").find(".updateCart").show();
                    jQuery(this).parents("tr").addClass("needs-update");
                    if ( jQuery.browser.msie && Number( jQuery.browser.version ) < 8 ) {
                        jQuery("tr.needs-update").each( function() {
                            jQuery(this).find("td").css("background-color","#FAFAEC");
                        });
                    }
                }
                else {
                    if ( jQuery.browser.msie && Number( jQuery.browser.version ) < 8 ) {
                        jQuery("tr.needs-update").each( function() {
                            jQuery(this).find("td").css("background-color","#FFF");
                        });
                    }
                     jQuery(this).parents("tr").removeClass("needs-update");
                }
                jQuery(this).parents("tr").find(".tierPricing").find(".tierPriceQty").each( function() {
                    var tierRange = jQuery(this).html().replace(/,/g,"").replace(/\s/g,"").replace(/\t/g,"").split("-");
                    if ( jQuery(this).html().indexOf("+") != -1 ) {
                        tierRange = new Array();
                        tierRange[0] = jQuery(this).html().replace(/\s/g,"").replace(/,/g,"").replace(/\t/g,"").replace(/\+/g,"");
                        tierRange[1] = '999999999999';
                    }
                    if ( Number( qty ) >= Number( tierRange[0] ) && Number( qty ) <= Number( tierRange[1] ) ) {
                        
                        jQuery(this).siblings(".tierPrice").find(".price").addClass("active");
                        jQuery(this).siblings(".tierPrice").find(".qty").addClass("active");
                        var thisPrice = jQuery(this).siblings(".tierPrice").find(".price").text().replace("$","");
                        if ( jQuery(this).parents("table").find(".price.active").parents("tr").next("tr").size() > 0 ) {
                            var nextLowest =  jQuery(this).parents("table").find(".price.active").parents("tr").next("tr").find(".price").html().replace("$","");
                        }
                        jQuery(this).parents("table").parents("td").find(".yourPrice").find(".yourPriceText").html("Your price").css("text-align","right");
                        if ( nextLowest && Number(tierRange[1]) < 999999999999 ) {
                            var toBuy = (Number(tierRange[1])+1) - Number(qty);
                            var savings = ( Number( thisPrice ) - Number( nextLowest ) ) / Number( thisPrice );
                            if ( toBuy < 5 ) {
                                toBuy = "only "+ toBuy;
                            }
                            jQuery(this).parents("table").parents("td").find(".yourPrice").find(".yourPriceText").html("Buy "+ toBuy +" more to save "+ (Number(savings)*100).toFixed(0) + "% on these").css("text-align","left");
                        }
                        jQuery(this).parents("table").parents("td").find(".yourPrice").css("top", jQuery(this).parents("tr").find(".tierPrice").position()["top"]).css("left", jQuery(this).parents("tr").position()["left"]-115).show();
                    }
                    else {
                        jQuery(this).siblings(".tierPrice").find(".price").removeClass("active");
                        jQuery(this).siblings(".tierPrice").find(".qty").removeClass("active");
                    }
                });
            });
        });
        
        // Now trigger it onload
        jQuery(".checkout-cart-index .cart-table .qtyBox .qty").each( function() {
            jQuery(this).trigger("change");
        });
        setupQuantityBoxes();
    }
    
    function setupQuantityBoxes() {
        jQuery("input.qty").bind("blur",function(){if(isNaN(jQuery(this).attr("value"))){jQuery(this).attr("value","1");}
        });
        jQuery(".qtyBox span.plus").unbind("click").click(function(){
            var p=jQuery(this).parent().children("input");
            p.attr("value",isNaN(parseInt(p.attr("value"))+1)?1:parseInt(p.attr("value"))+1).change();
        });
        jQuery(".qtyBox span.minus").unbind("click").click(function(){
            var p=jQuery(this).parent().children("input");
            p.attr("value",isNaN(parseInt(p.attr("value"))+1)?1:(parseInt(p.attr("value"))-1)<1?1:parseInt(p.attr("value"))-1).change();
        });
    }
    
    function swapZoomForThumbPic( linkId ) {
    if ( jQuery("#"+linkId).size() == 0 ) {
        return false;
    }
    var linkEl = jQuery("#"+linkId);
        jQuery("#image").attr("src", linkEl.attr("href")).attr("title", linkEl.attr("title"));
        try {
            jQuery('.product-image-zoom').css('line-height', jQuery('.product-img-box').css('height') ); 
        }
        catch(err) {} 
        return false;
    }
    
    function hideRequiredInsertOptional() {
        jQuery("form .form-list, #freehat_form, #catalogrequest_form").find("label").each( function() {
            if ( jQuery(this).siblings(".required-entry, .validate-select").size() == 0 && jQuery(document).find(".required").size() > 0 && jQuery(this).parents("#checkout-payment-method-load").size() == 0 ) {
                if ( jQuery(this).html().indexOf("(Optional)") == -1 && jQuery(this).siblings(".input-box").size() == 0) {
                    jQuery(this).html(jQuery(this).html() +"<span class='label-explanation'> (Optional)</span>");
                }
            }
            else {
                jQuery(document).find(".required").hide();
            }
        });
    }
    
    // Checkout: Shipping method: Create a message on top for free shipping
    function  createhippingMethodMessage() {
         if(typeof window.XBS =='undefined'){window.XBS=newXbShippingObject();XBS.init();}
         if(XBS.shouldShowFreeMessage()) {
         	jQuery("#shipping-method-note").html(XBS.getFreeShippingMessage()).show();
         } 
         
         
//         if ( XBShipping.getAmountMoreToSpendForFreeShipping() > 0 ) {
//             jQuery("#shipping-method-note").html("Spend another $"+ XBShipping.getAmountMoreToSpendForFreeShipping() +" to get FREE shipping").show();
//         }
//         else {
//             jQuery("#shipping-method-note").html("You have qualified for FREE shipping.").show();
//         }
//         
    }
    
    // start timer to hide minicart chad (click here to view cart & shipping)
    function startChadHideTimer(duration) {
        // console.log("start");
        jQuery("#minicart-show").stopTime("ch-hide");
        jQuery("#minicart-show").oneTime(duration, "ch-hide", function() {
            jQuery("#minicart-chad").slideUp(200);
        });
    }
function xbCartLink(){
	try{var uenc='/add/uenc/'+uencPage.replace(",","");}catch(e) {var uenc='';}
	document.location.href='/checkout/cart'+ uenc;
	}
jQuery(document).ready(function(){
        // Remove any default values in form fields put there bay shippingZip ajax call
        jQuery(".form-list input").each( function() {
                if( jQuery(this).val() == 'id_default_ship_estimate__000000' ) {
                    jQuery(this).val("");
                }
        }); 
        
        // Change checkout links on click
        jQuery("div.ajaxcartpro_confirm button.cart-button").attr("onclick","").unbind("click").click( xbCartLink );
        // Fix buttons inside <a> tags for crappy ie
        if(jQuery.browser.msie){
            jQuery('button').each( function() {
                if ( jQuery(this).attr("onclick") == undefined && jQuery(this).parent().get(0).tagName == 'A' ) {
                    jQuery(this).click( function() {
                        document.location.href=jQuery(this).parents("a").attr("href");
                    });
                }
            });
        }
        
        // alert( jQuery.browser.version );

		//a=setTimeout("jtest()",1000*15);
        // Set up valve and controller header toggle popups
		jQuery(".category-headerbox").find(".toggle").each( function() {
                jQuery(this).css("position","absolute").css("left",jQuery(".category-headerbox-txt").position()["left"] +10 ).css("top","10px") ;
		});
		jQuery(".category-headerbox").find(".switch").each( function() {
			if(jQuery.browser.msie){
				jQuery(this).css("left",Number( jQuery(this).css("left").replace("px","") )+ 8 + "px").css("font-size","24px").css("width","20px");
			}
			jQuery(this).mouseover( function() {
				jQuery("#toggle-"+ jQuery(this).attr("id")).fadeIn(200);
			});
			jQuery(this).mouseout( function() {
				jQuery("#toggle-"+ jQuery(this).attr("id")).fadeOut(200);
			});
		});
	
	/*
	var thisPage = window.location.pathname;
	var $origHREFs=Array();
	
	jQuery("#newNavList li a").each(function() {
		var target = jQuery(this).children("span").attr("class") ;
		$origHREFs[target]=jQuery(this).attr("href");
		jQuery(this).attr("href","#"+target);
	});
	
	var $navTabs = jQuery("#newNav").tabs({event: 'mouseover'}); var defaultTab = $navTabs.tabs('option','selected');
	jQuery("#newNavList li a").each(function() {
		jQuery(this).click(function(){location.href=$origHREFs[jQuery(this).children("span").attr("class")];}).css('cursor','pointer');
	});
	jQuery("#newNav").bind("mouseleave",function(){$navTabs.tabs('select',defaultTab);});
	
    // An extra bit to identify the active subcategory by URL (matching link to window location in top nav)
	jQuery("#newNav .ui-tabs-panel.ui-widget-content").not("ui-tabs-hide").find("ul li").each( function() {
		var link = jQuery(this).find("a").attr("href");
        // alert( "http://"+ window.location.hostname + thisPage.substring( 0, thisPage.lastIndexOf("\/") ) );
        var thisPageArr = thisPage.split("/");
        // We'll add to this string on each loop until we find a match btwn link and the page's url
        var lookingFor = "";
        for ( var i=0;i<thisPageArr.length;i++ ) {
            lookingFor += thisPageArr[i];
            if ( link == lookingFor || link == "http://"+ window.location.hostname + lookingFor ) {
                jQuery(this).find("a").addClass("active");
                break;
            }
            lookingFor += "/";
        }
	});
    */
	// jQuery("#left_nav").treeview();
	
	/* 11/12/09 - JO: moved these next 2 items down, nav should go first */
	createQuickcartLinks();
	setupQuickcartEvents();
    
    /*
	jQuery("#minicart li").removeClass("ui-state-default, ui-corner-top");
	// Add class "active" to the current category's link
	jQuery("#left_nav.treeview li.active a:first").addClass("active");
	
	// An extra bit to identify the active subcategory by URL (matching link to window location
	jQuery("#left_nav.treeview li.active ul li").each( function() {
		var link = jQuery(this).find("a").attr("href");
        // alert( link +"  "+ "http://"+ window.location.hostname+ "/"+ thisPage );
		if ( link == thisPage || link == "http://"+ window.location.hostname + thisPage ) {
			jQuery(this).find("a").addClass("active");
		}
	});
	*/
	//other tabs
	jQuery(".tabset").tabs();
	if ( jQuery(".tabset ul:first").find("li").size() == 1 ) {
		jQuery(".tabset ul:first").find("li").addClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active");
		jQuery("#product_description").addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");
	}
    
	setupQuantityBoxes();
	// Change the class aw_ajax_cart updates when the cart changes. Default is set in js/aw_ajaxcartpro/ajaxcartpro-1....js
	aw_cartDivClass = ".minicartinner";
	
	
	jQuery("div.showTierPrices input.qty").each( function() {
            jQuery(this).bind("click",function(){
                try{setUpTierPriceCharts();} 
                catch(e){};
                jQuery("#"+jQuery(this).attr("id")+"tierPrices").trigger("click");
            });
            jQuery(this).bind("change",function(){
                setUpTierPriceCharts();
                jQuery("#"+jQuery(this).attr("id")+"tierPrices").trigger("click");
            });
    });
    
	
	// initial setup of tier price blocks
	setUpTierPriceCharts();
    jQuery(".product-view .product-shop .listTierPrice").append('<div id="yourPrice" style="width: 80px; color: #F4A804; font-weight: bold; line-height: 20px; position: absolute; display: none;">Your price &raquo;</div>');
    
	// On product page, highlight appropriate tier price for your quantity
	jQuery(".product-view .product-shop .add-to-cart #qty").change( function() {
        var qty = jQuery(".product-view .product-shop .add-to-cart #qty").val();
        jQuery(".product-view .product-shop .listTierPrice .tierPricing .tierPriceQty").each( function() {
            var tierRange = jQuery(this).html().replace(/\s/g,"").replace(/\t/g,"").split("-");
            if ( jQuery(this).html().indexOf("+") != -1 ) {
                tierRange = new Array();
                tierRange[0] = jQuery(this).html().replace(/\s/g,"").replace(/\t/g,"").replace(/\+/g,"");
                tierRange[1] = '1000000';
            }
            jQuery(this).removeClass("active");
            if ( Number( qty ) >= Number( tierRange[0] ) && Number( qty ) <= Number( tierRange[1] ) ) {
            jQuery(this).css("border","1px solid #F4A804").css("border-right","0"); 
                jQuery(this).parents("tr").find("td.tierPrice").css("border","1px solid #F4A804").css("border-left","0");
                jQuery("#yourPrice").css("top", jQuery(this).position()["top"]).css("left", jQuery(this).position()["left"]-80).show();
            }
            else {
                jQuery(this).parents("tr").find("td").css("border","0").css("border-bottom","1px dotted #AFAFAD");
            }
        });
	});
    // Now trigger it onload
    jQuery(".product-view .product-shop .add-to-cart #qty").trigger("change");
	
    // Run function to set up tier prices for cart
    setTimeout('setupCartTierPrices();',2000);
    
    // decoration: stripe the charts, add both so that differetn styles can decide if odds or evens get the color:
    jQuery("table.xb-chart tbody tr:even").addClass("xb-stripe-even") ;
    jQuery("table.xb-chart tbody tr:odd").addClass("xb-stripe-odd") ;
	// get the shipping info in the Quick Cart
	//XBShipping.__init();
	//XBShipping.prepareQuickCartShipping() ;
    
    // if this is a cart page, the "checkout object will be present
    if (typeof checkout != "undefined") {
        // Mage's setMethod is used in conjnction with radio buttons for "check out as guest" and "register". We will overwrite it to respond to "whichMethod", which we'll pass with buttons
        checkout.setMethod =  function( whichMethod ){
                // alert("setMethod overwtitten");
                if ( whichMethod == 'guest' ) {
                    this.method = 'guest';
                    var request = new Ajax.Request(
                        this.saveMethodUrl,
                        {method: 'post', onFailure: this.ajaxFailure.bind(this), parameters: {method:'guest'}}
                    );
                    Element.hide('register-customer-password');
                    Element.show('checkout-register-toggle');
                    this.gotoSection('billing');
                }
                else if ( whichMethod == 'register' ) {
                    this.method = 'register';                            
                    var request = new Ajax.Request(
                        this.saveMethodUrl,
                        {method: 'post', onFailure: this.ajaxFailure.bind(this), parameters: {method:'register'}}
                    );
                    Element.show('register-customer-password');
                    Element.hide('checkout-register-toggle');
                    this.gotoSection('billing');
                }
                else{
                    alert(Translator.translate('Please choose to register or to checkout as a guest'));
                    return false;
                }
        };
        
        // Overwrite shippingMethod.validate in /skin/frontend/default/xavierberkeley/js/opcheckout.js to use a dropdown list instead of radio buttons (what were they thinking?)
        shippingMethod.validate =  function(){
            var methods = document.getElementsByName('shipping_method');
            if (methods.length==0) {
                alert(Translator.translate('Your order can not be completed at this time as there is no shipping methods available for it. Please make necessary changes in your shipping address.'));
                return false;
            }
    
            if(!this.validator.validate()) {
                return false;
            }
    
            if ( jQuery("#s_method").val() != "" ) {
                return true;
            }
            alert(Translator.translate('Please specify shipping method.'));
            return false;
        };
        
         // Overwrite payment.init() in /skin/frontend/default/xavierberkeley/js/opcheckout.js
        payment.init =  function(){
            var elements = Form.getElements(this.form);
            if ($(this.form)) {
                $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
            }
            var method = null;
            method = jQuery("#p_method").val();
            if (method) this.switchMethod(method);
            
            jQuery("#p_method").change( function() {
                payment.switchMethod( jQuery("#p_method").val() );
            });
        };
        
         // Overwrite payment.validate in /skin/frontend/default/xavierberkeley/js/opcheckout.js
         payment.validate =  function(){
            var methods = document.getElementsByName('payment[method]');
            if (methods.length==0) {
                alert(Translator.translate('Your order can not be completed at this time as there is no payment methods available for it.'));
                return false;
            }
            if ( jQuery("#p_method").val() != "" ) {
                return true;
            }
            alert(Translator.translate('Please specify payment method.'));
            return false;
         }
         
         // Overwrite the gotoSection and back functions to make sure the "checkoutsteps block at the top of the page updates when the active section does
         checkout.gotoSection = function(section) {
           if ( section == "shipping_method" ) {
               createhippingMethodMessage();
            }
            jQuery(".opc-state").removeClass("active");
            jQuery("#opc-state-"+ section).addClass("active");
            section = $('opc-'+section);
            section.addClassName('allow');
            this.accordion.openSection(section);
         }
         
         checkout.back = function() {
             if (this.loadWaiting) return;
             this.accordion.openPrevSection(true);
             var activeStep = jQuery(".section.active").attr("id").replace("opc-","opc-state-");
             jQuery(".opc-state").removeClass("active");
             jQuery("#"+ activeStep).addClass("active");
             if ( activeStep.indexOf("shipping_method") != -1 ) {
                 createhippingMethodMessage();
             }
         }
         
        shipping.syncWithBilling = function() {
            $('billing-address-select') && this.newAddress(!$('billing-address-select').value);
            $('shipping:same_as_billing').checked = true;
            if (!$('billing-address-select') || !$('billing-address-select').value) {
                arrElements = Form.getElements(this.form);
                for (var elemIndex in arrElements) {
                    if (arrElements[elemIndex].id) {
                        var sourceField = $(arrElements[elemIndex].id.replace(/^shipping:/, 'billing:'));
                        if (sourceField){
                            arrElements[elemIndex].value = sourceField.value;
                        }
                    }
                }
                //$('shipping:country_id').value = $('billing:country_id').value;
                shippingRegionUpdater.update();
                $('shipping:region_id').value = $('billing:region_id').value;
                $('shipping:region').value = $('billing:region').value;
                //shippingForm.elementChildLoad($('shipping:country_id'), this.setRegionValue.bind(this));
            } else {
                $('shipping-address-select').value = $('billing-address-select').value;
            }
            hideRequiredInsertOptional();
        }
        
        shipping.save = function(){
        if ($('shipping:telephone').value == '' ) {
                $('shipping:telephone').value = 0;
            }
        if (checkout.loadWaiting!=false) return;
        var validator = new Validation(this.form);
        if (validator.validate()) {
            checkout.setLoadWaiting('shipping');
            var request = new Ajax.Request(
                this.saveUrl,
                {
                    method:'post',
                    onComplete: this.onComplete,
                    onSuccess: this.onSave,
                    onFailure: checkout.ajaxFailure.bind(checkout),
                    parameters: Form.serialize(this.form)
                }
            );
        }
    }
        
        billing.save =  function() {
            if (checkout.loadWaiting!=false) return;
            // put in a dummy phone number if not entered
            if ($('billing:telephone').value == '' ) {
                $('billing:telephone').value = 0;
            }
                
            var validator = new Validation(this.form);
            if (validator.validate()) {
                if (checkout.method=='register' && $('billing:customer_password').value != $('billing:confirm_password').value) {
                    alert(Translator.translate('Error: Passwords do not match'));
                    return;
                }
                checkout.setLoadWaiting('billing');
    
    //            if ($('billing:use_for_shipping') && $('billing:use_for_shipping').checked) {
    //                $('billing:use_for_shipping').value=1;
    //            }
    
                var request = new Ajax.Request(
                    this.saveUrl,
                    {
                        method: 'post',
                        onComplete: this.onComplete,
                        onSuccess: this.onSave,
                        onFailure: checkout.ajaxFailure.bind(checkout),
                        parameters: Form.serialize(this.form)
                    }
                );
            }
        }
        
        /*
        billing.newAddress = function(isNew){
            if (isNew) {
                this.resetSelectedAddress();
                Element.show('billing-new-address-form');
                billing.setAddress( jQuery("#billing-address-select").val() );
            } else {
                Element.show('billing-new-address-form');
                billing.setAddress( jQuery("#billing-address-select").val() );
            }
        }
        
        
        billing.setAddress( jQuery("#billing-address-select").val() );
        Element.show('billing-new-address-form');
        
        jQuery("#billing-address-select").change( function() {
                billing.setAddress( jQuery("#billing-address-select").val() );
        });
        */
    }
    
    // Try to set the line-height in product zoom box so it fits image
    try {
        jQuery(".product-image-zoom").css("line-height", jQuery(".product-img-box").css("height") );
    }
    catch(err) {
        // do something
    }
    
    // If there are no additional images add lightbox to the main image
    if ( jQuery(".product-image-zoom").size() > 0 && jQuery(".more-views img").size() == 0 ) {
        jQuery(".product-image-zoom #image").wrap('<a href="'+ jQuery(".product-image-zoom #image").attr("src") +'" title="'+ jQuery(".product-image-zoom #image").attr("title").replace(/\"/g,'&quot;') +'" class="lightbox"></a>');
    }
    
    // Having the same image twice in the carousel for products bothered me but I wanted the large (default) one to still have lightbox...
    jQuery(".product-image-zoom #image").click( function() {
        // get the last bit of the src attribute
        var zoomPic = jQuery(this);
        var thisSrc = jQuery(this).attr("src");
        thisSrc = thisSrc.substring( thisSrc.lastIndexOf("/") );
        // Loop through the thumbnails until you find the same src
        jQuery(".more-views img").each( function() {
            if ( jQuery(this).attr("src").substring( jQuery(this).attr("src").lastIndexOf("/") ) == thisSrc ) {
                // trigger a click on that one
                jQuery(this).parents("a").trigger("click");
            };
        })
    });

    jQuery("a.lightbox").lightBox({
        overlayBgColor: '#000',
        overlayOpacity: 0.6,
        maxHeight: screen.height * 0.9,
        maxWidth: screen.width * 0.9,
        imageLoading: '/skin/frontend/default/xavierberkeley/images/lightbox-ico-loading.gif',
        imageBtnClose: '/skin/frontend/default/xavierberkeley/images/lightbox-btn-close.gif',
        imageBtnPrev: '/skin/frontend/default/xavierberkeley/images/lightbox-btn-prev.gif',
        imageBtnNext: '/skin/frontend/default/xavierberkeley/images/lightbox-btn-next.gif',
        containerResizeSpeed: 350,
        fixedNavigation: true
    });
    
    /*
    // VERY TEMPORARY ie6 fixes (playing around to get layout right, will fix CSS properly when what needs adjustment is established)
    if ( jQuery.browser.msie && jQuery.browser.version=="6.0") {
        jQuery(".page").css("width","1010px");
        jQuery(".col2-left-layout .col-main").css("margin-right","0px").css("width","715px");
        jQuery(".col-left").css("margin","0px 5px");
        jQuery(".content-right-box").css("margin-left","10px");
    }
    */
    // OK, we're going to hide all red asterisks (rewuired inputs) and put "(optional)" afeter each non-required field's label
    hideRequiredInsertOptional();
    
    
    // Hacky but elegent, this little bit truncates values in the address select menu in checkout
    jQuery("#opc .address-select > option").each( function() {
        if ( String(jQuery(this).text()).length > 105 ) {
            jQuery(this).text( jQuery(this).text().substring(0,102) +"..." );
        }
    });
    
    if ( jQuery("#newNavToo ul.sf-navbar li.current").size() == 0 ) {
        jQuery("#newNavToo ul.sf-navbar li:first").addClass("current");
    }
    // Social Networking links. Have to add these via js cuz magento caches calls to getCurrentUrl();
    var pageTitle = escape(document.title.replace(/\u2013/g,'-').replace(/\u2018/g,'\'').replace(/\u2019/g,'\'').replace(/\u201C/g,'"').replace(/\u201D/g,'"').replace(/[^\x20-\x7F]/g,'_'));
    var pageLocation = escape(document.location);
    // To add a link, add it to this array with a properly constructed URL. Put an icon in the image folder under its key.
    var shareSites = {
        email:          '#email-this-page',
        digg:           'http://digg.com/submit?phase=2&url='+ pageLocation +'&title='+ pageTitle ,
        delicious:      'http://del.icio.us/post?url='+ pageLocation  +'&title='+ pageTitle ,
	    stumbleUpon:       'http://www.stumbleupon.com/submit?url='+  pageLocation +'&title='+  pageTitle ,
	    twitter:        'http://twitter.com/home?status=Currently+reading+'+ pageLocation
	};
	// Append each link to the shareTools div in the footer
    for (var a in shareSites) {
            jQuery("#shareTools").append('<a class="sharelink" href="'+ shareSites[a] +'" target="_blank" id="share-link-'+ a +'"></a>');
    }
	jQuery("#share-link-email").click(emailPage);
	jQuery("#printTools").click(function(){window.print();});
	jQuery("div.video-teaser a").each(function(){
		jQuery(this).mouseover(function(){jQuery(this).find("img.play-video-button").attr('src','/video/thumbnails-play/_play-button-hover.png');});
		jQuery(this).mouseout(function(){jQuery(this).find("img.play-video-button").attr('src','/video/thumbnails-play/_play-button.png');});
	});
}); // end document ready

function emailPage(){
subject = escape(document.title.replace(/\u2013/g,'-').replace(/\u2018/g,'\'').replace(/\u2019/g,'\'').replace(/\u201C/g,'"').replace(/\u201D/g,'"').replace(/[^\x20-\x7F]/g,'_'));
str = 'mailto:?subject=' + subject + '&body=' + subject + '%0D%0Ahttp://' + location.host + location.pathname +'?src=em' ;
location.href=str;return false;} 

function xbDLToggle(id){jQuery("#definition"+id).toggle();if(jQuery("#definition"+id).css("display")=="none"){jQuery("#term"+id).removeClass("dton");}else{jQuery("#term"+id).addClass("dton");}}


