/* -------------------------------------------------- *
 * Bulk Pricing Script
** -------------------------------------------------- */

$(document).ready(function()	{
	var colorsPricebox = $(".colors_pricebox");
	$.each(colorsPricebox.find("img"), function()	{
		if(this.parentNode.tagName.toLowerCase() != "a")	{
			return true;
		}
		
		var onclick = this.parentNode.getAttribute("onclick");
		if(!onclick)	{
			return true;
		}
		
		var onclickSplit = onclick.replace(/\s+/g, "").split('(');
		onclickSplit.shift();
		onclickSplit = onclickSplit.join('(').split("'");
		onclickSplit.shift();
		
		var indexOfComma = onclickSplit.indexOf(","),
			url = eval("('" + onclickSplit.slice(0, indexOfComma).join("'") + "')"),
			windowOpenParams = onclickSplit[onclickSplit.length - 2].split(","),
			iframeWidth = null,
			iframeHeight = null;
		
		$.each(windowOpenParams, function()	{
			var paramSplit = this.split("=");
			
			if(paramSplit[0] == "width")	{
				iframeWidth = paramSplit[1];
			}
			else if(paramSplit[0] == "height")	{
				iframeHeight = paramSplit[1];
			}
			
			if(!iframeWidth || !iframeHeight)	{
				return true;
			}
			
			return false;
		});
		
		iframeWidth = true;
		
		var parentNodeToCheck = this.parentNode,
			isValidParent = function(inParentNodeToCheck)	{
				return inParentNodeToCheck.tagName.toLowerCase() == "table" && inParentNodeToCheck.getAttribute("cellspacing") !== null && inParentNodeToCheck.getAttribute("cellpadding") !== null && inParentNodeToCheck.getAttribute("border") !== null && inParentNodeToCheck.getAttribute("width") != null
			};
		while(parentNodeToCheck)	{
			if(isValidParent(parentNodeToCheck))	{
				break;
			}
			
			parentNodeToCheck = parentNodeToCheck.parentNode;
		}
		
		if(!isValidParent(parentNodeToCheck))	{
			return false;
		}
		
		var newRow = document.createElement("tr"),
			newCell = document.createElement("td"),
			currentTbody = parentNodeToCheck.parentNode.parentNode.parentNode;
		newCell.setAttribute("colSpan", 3);
		newCell.setAttribute("colspan", 3);
		newCell.setAttribute("id", "discount_cell");
		newCell.id = "discount_cell";
		newCell.innerHTML = "Loading...";
		newRow.appendChild(newCell);
		
		currentTbody.insertBefore(newRow, currentTbody.lastChild);
		
		$.ajax({
			url:url,
			success:function(inData)	{
				$("#discount_cell")[0].innerHTML = inData;
			}
		});
		
		return false;
	});
});


$(document).ready(function(){
	$(".colors_pricebox img[src*='btn_quantitydiscounts']").hide();
});



/* -------------------------------------------------- *
 * Centering div on my account
** -------------------------------------------------- */



$(document).ready(function(){
	$(".needsCentering").parents('table').parents('td').css('text-align', 'center');
	$(".needsCentering").parents('table').css('display', 'inline');
	$(".needsCentering").parents('table').css('text-align', 'left');
});




/* -------------------------------------------------- *
 * Side menu current class
** -------------------------------------------------- */

/*
$(document).ready(function(){
	
	var path = window.location.pathname + window.location.search + window.location.hash;
	var home = "/";
	
	$("a[href='" + [path || home] + "']").each(function() {   
	        $(this).addClass("current");
	});

});
*/


$(document).ready(function(){
	
	var path = window.location.pathname + window.location.search + window.location.hash;
	
	$("a[href='" + [path] + "']").each(function() {   
	        $(this).addClass("current");
	});

});


/* -------------------------------------------------- *
 * Cart tab count update
** -------------------------------------------------- */


$(function(){
	jQuery.ajax({
		url: '/AjaxCart.asp',
		cache: false,
		dataType: 'text',
		success: function(data) {
			var json = eval('(' + data + ')');
			var quantity;
			var cartTotal;
			quantity = json.Totals[0].Quantity;
			cartTotal = json.Totals[0].CartTotal;
			jQuery("#mini_cart_summary").text("Items: " + quantity);
		},
		error: function() {
			return false;
		}
	});
});



/* -------------------------------------------------- *
 * Conditional Login
** -------------------------------------------------- */

/*
$(function(){
	
	var lcheck_url = window.location.protocol + '//' + window.location.host + '/myaccount.asp';
	jQuery.ajax({
	url: lcheck_url,
	type: 'GET',
	async: false,
	cache: false,
	success: function(data){
		if ($(data).find('#customer_name').length){
			$('.loggedOut').hide();
			$('.loggedIn #name').load('/myaccount.asp #customer_name');
			$('.loggedIn').fadeIn(400);
		}
		else {
			$('.loggedOut').fadeIn(400);
		}
	}
});

});
*/

/* -------------------------------------------------- *
 * Add clase to search div at top of category page
** -------------------------------------------------- */

$(function() {	

	$(".search_results_section table:first").addClass("productSortTable");;

});


/* -------------------------------------------------- *
 * Home Category Hover
** -------------------------------------------------- */

$(function() {	
	
	$('#homeCategories a').stop().hover(function() {
		$('#homeCategories a').not(this).stop().fadeTo(100, .6);
	}, function() {
		$('#homeCategories a').stop().fadeTo(100, 1);
	});
		
});



/* -------------------------------------------------- *
 * Nav Hover
** -------------------------------------------------- */

$(function() {	
	
	$('#nav li').stop().hover(function() {
		$(this).addClass("pulled");
	}, function() {
		$(this).removeClass("pulled");
	});
		
});

/* -------------------------------------------------- *
 * Search on Enter
** -------------------------------------------------- */

$("#searchInput").keyup(function(event){
  if(event.keyCode == 13){
    $("#searchBtn").click();
  }
});



/* -------------------------------------------------- *
 * ToggleVal 2.1 - Input Status
** -------------------------------------------------- */

(function($){$.fn.toggleVal=function(theOptions){if(!theOptions||typeof(theOptions)=="object"){theOptions=$.extend({focusClass:"tv-focused",changedClass:"tv-changed",populateFrom:"default",text:null,removeLabels:false},theOptions)}else if(typeof(theOptions)=="string"&&theOptions.toLowerCase()=="destroy"){var destroy=true}return this.each(function(){if(destroy){$(this).unbind("focus.toggleval").unbind("blur.toggleval").removeData("defText");return false}var defText="";switch(theOptions.populateFrom){case"alt":defText=$(this).attr("alt");$(this).val(defText);break;case"label":defText=$("label[for='"+$(this).attr("id")+"']").text();$(this).val(defText);break;case"custom":defText=theOptions.text;$(this).val(defText);break;default:defText=$(this).val()}$(this).addClass("toggleval").data("defText",defText);if(theOptions.removeLabels==true){$("label[for='"+$(this).attr("id")+"']").remove()}$(this).bind("focus.toggleval",function(){if($(this).val()==$(this).data("defText")){$(this).val("")}$(this).addClass(theOptions.focusClass).removeClass(theOptions.changedClass)}).bind("blur.toggleval",function(){if($(this).val()==""){$(this).val($(this).data("defText"))}$(this).removeClass(theOptions.focusClass);if($(this).val()!=$(this).data("defText")){$(this).addClass(theOptions.changedClass)}else{$(this).removeClass(theOptions.changedClass)}})})}})(jQuery);

$(function() {
	$("input.toggle").toggleVal({
    focusClass: "hasFocus",
    changedClass: "isChanged"
	});
});

$(function() {
	$("textarea.toggle").toggleVal({
    focusClass: "hasFocus",
    changedClass: "isChanged"
	});
});


/* -------------------------------------------------- *
 * Eleastic Textarea Expansion
** -------------------------------------------------- */

(function(jQuery){jQuery.fn.extend({elastic:function(){var mimics=['paddingTop','paddingRight','paddingBottom','paddingLeft','fontSize','lineHeight','fontFamily','width','fontWeight'];return this.each(function(){if(this.type!='textarea'){return false}var $textarea=jQuery(this),$twin=jQuery('<div />').css({'position':'absolute','display':'none','word-wrap':'break-word'}),lineHeight=parseInt($textarea.css('line-height'),10)||parseInt($textarea.css('font-size'),'10'),minheight=parseInt($textarea.css('height'),10)||lineHeight*3,maxheight=parseInt($textarea.css('max-height'),10)||Number.MAX_VALUE,goalheight=0,i=0;if(maxheight<0){maxheight=Number.MAX_VALUE}$twin.appendTo($textarea.parent());var i=mimics.length;while(i--){$twin.css(mimics[i].toString(),$textarea.css(mimics[i].toString()))}function setHeightAndOverflow(height,overflow){curratedHeight=Math.floor(parseInt(height,10));if($textarea.height()!=curratedHeight){$textarea.css({'height':curratedHeight+'px','overflow':overflow})}}function update(){var textareaContent=$textarea.val().replace(/&/g,'&amp;').replace(/  /g,'&nbsp;').replace(/<|>/g,'&gt;').replace(/\n/g,'<br />');var twinContent=$twin.html();if(textareaContent+'&nbsp;'!=twinContent){$twin.html(textareaContent+'&nbsp;');if(Math.abs($twin.height()+lineHeight-$textarea.height())>3){var goalheight=$twin.height()+lineHeight;if(goalheight>=maxheight){setHeightAndOverflow(maxheight,'auto')}else if(goalheight<=minheight){setHeightAndOverflow(minheight,'hidden')}else{setHeightAndOverflow(goalheight,'hidden')}}}}$textarea.css({'overflow':'hidden'});$textarea.keyup(function(){update()});$textarea.live('input paste',function(e){setTimeout(update,250)});update()})}})})(jQuery);

$(function() {
	$('.elastic').elastic();
});

/* -------------------------------------------------- *
 * Auto Price Update http://forums.volusion.com/t5/Tips-amp-Tricks/Product-Price-automatically-updates-on-when-customer-selects-a/td-p/66972/page/3
** -------------------------------------------------- */

jQuery(function(){

	if ( typeof global_Current_ProductCode != "undefined" && jQuery("[name^=SELECT___] ").length )
	{

/* Copyright (c) 2009 Michael Manning (actingthemaggot.com) Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.*/
(function(A){A.fn.extend({currency:function(B){var C={s:",",d:".",c:2};C=A.extend({},C,B);return this.each(function(){var D=(C.n||A(this).text());D=(typeof D==="number")?D:((/\./.test(D))?parseFloat(D):parseInt(D)),s=D<0?"-":"",i=parseInt(D=Math.abs(+D||0).toFixed(C.c))+"",j=(j=i.length)>3?j%3:0;A(this).text(s+(j?i.substr(0,j)+C.s:"")+i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+C.s)+(C.c?C.d+Math.abs(D-i).toFixed(C.c).slice(2):""));return this})}})})(jQuery);jQuery.currency=function(){var A=jQuery("<span>").text(arguments[0]).currency(arguments[1]);return A.text()};

		function recal(){
			if(jQuery('select[name^="SELECT___"]').length ){
				//add up all selected options
				jQuery('select[name^="SELECT___"]').each(function(){
				var recal_var = 0;
				recal_var = jQuery(this).find("option:selected").text();	
			
					if (recal_var.indexOf('[Subtract -$') >0){
					price_result = recal_var.split('$')[1].slice(0,-1).replace(/,/g,'');
					current_val=current_val-price_result;
					}
					else if (recal_var.indexOf('[Add $') >0){
					price_result = parseFloat(recal_var.split('$')[1].slice(0,-1).replace(/,/g,''));
					current_val=current_val+price_result;
					}
				}); //each function
			} //if length

			if (jQuery('input[name^="SELECT___"][type="radio"]').length ){
				//add up all radio
				jQuery('input[name^="SELECT___"][type="radio"]:checked').each(function(){
				var recal_var = 0;
				recal_var = jQuery.trim(jQuery(this).next("span").text());

					if (recal_var.indexOf('[Subtract -$') >0){
					price_result = recal_var.split('$')[1].slice(0,-1).replace(/,/g,'');
					current_val=current_val-price_result;
					}
					else if (recal_var.indexOf('[Add $') >0){
					price_result = parseFloat(recal_var.split('$')[1].slice(0,-1).replace(/,/g,''));
					current_val=current_val+price_result;
					}
				}); //
			} //if length

			if (jQuery('input[name^="SELECT___"][type="checkbox"]').length ){
				//add up all radio
				jQuery('input[name^="SELECT___"][type="checkbox"]:checked').each(function(){
				var recal_var = 0;
				recal_var = jQuery.trim(jQuery(this).next("span").text());
	
					if (recal_var.indexOf('[Subtract -$') >0){
					price_result = recal_var.split('$')[1].slice(0,-1).replace(/,/g,'');
					current_val=current_val-price_result;
					}
					else if (recal_var.indexOf('[Add $') >0){
					price_result = parseFloat(recal_var.split('$')[1].slice(0,-1).replace(/,/g,''));
					current_val=current_val+price_result;
					}
				}); //each function
			} //if length

			jQuery('font.pricecolor.colors_productprice').find('.price1:last').html('$' + jQuery.currency(current_val,{s:",",d:".",c:2}));
			current_val=product_orig_price;
		}

	var parent = jQuery('input[type="radio"][name^="SELECT___"],input[type="checkbox"][name^="SELECT___"]').parent('td');
	parent.contents().filter(function() { return this.nodeType != 1; }).wrap('<span></span>');
	var current_val;
	var price_result;
	var product_orig_price = parseFloat(jQuery('font.pricecolor.colors_productprice:not(.pricecolorsmall)').find('.price1:last').text().replace('$','').replace(/,/g,''));
	current_val = product_orig_price;
	recal();
		jQuery('select[name^="SELECT___"],input[name^="SELECT___"]').change(function(){
		recal();
		}); //change

	jQuery("a[href^='javascript:change_option']").click(function(){
		var result_href = jQuery(this).attr('href').match(/\'(.*?)\'/)[1];
		var result_val = jQuery(this).attr('href').match(/\,(.*?)\)/)[1];
		change_option(result_href,result_val);
		recal();
		return false;
	});
	}
});

/* -------------------------------------------------- *
 * Hide Update Price Button
** -------------------------------------------------- */

$(function() {
	$('input[name$="btnupdateprice"]').hide();
});


/* -------------------------------------------------- *
 *
** -------------------------------------------------- */

$(function(){
var current_val;
var price_result;
	if ( typeof global_Current_ProductCode != "undefined" && $("[name^=SELECT___] option").length )
	{
	var product_orig_price = parseFloat($(".price1:last").text().replace('$','').replace(/,/g,''));
	current_val = product_orig_price;
	$("select[name^='SELECT___'],input[name^='SELECT___'][type='radio']").change(function(){
	$("select[name^='SELECT___'],input[name^='SELECT___'][type='radio']").each(function(){
	var recal_var = $(this).find("option:selected").text();

		if (recal_var.indexOf('[Subtract -$') >0){
		price_result = recal_var.split('$')[1].slice(0,-1).replace(/,/g,'');
		current_val=current_val-price_result;
		}
		else if (recal_var.indexOf('[Add $') >0){
		price_result = parseFloat(recal_var.split('$')[1].slice(0,-1).replace(/,/g,''));
		current_val=current_val+price_result;
		}
	});
	$(".price1:last").html('$' + $.currency(current_val,{s:",",d:".",c:2}));
	current_val=product_orig_price;
	});
	$("a[href^='javascript:change_option']").each(function(){
var current_val2;
var price_result2;
var product_orig_price2 = parseFloat($(".price1:last").text().replace('$','').replace(/,/g,''));
		$(this).click(function() {
		var result_href = $(this).attr('href').match(/\'(.*?)\'/)[1];
		var result_val = $(this).attr('href').match(/\,(.*?)\)/)[1];
		change_option(result_href,result_val);

current_val2 = product_orig_price2;
$("select[name^='SELECT___'],input[name^='SELECT___'][type='radio']").each(function(){
var recal_var2 = $(this).find("option:selected").text();
		if (recal_var2.indexOf('[Subtract -$') >0){
		price_result2 = recal_var2.split('$')[1].slice(0,-1).replace(/,/g,'');
		current_val2=current_val2-price_result2;
		}
		else if (recal_var2.indexOf('[Add $') >0){
		price_result2 = parseFloat(recal_var2.split('$')[1].slice(0,-1));
		current_val2=current_val2+price_result2;
		}
});
$(".price1:last").html('$' + $.currency(current_val2,{s:",",d:".",c:2}));
current_val2=product_orig_price2;
		return false;
		});
	});
	}
});

