$(document).ready(function(){

///form field initial values
//$('input').focus(function(){ $(this).css('color','#000') });
//$('input').blur(function(){ $(this).css('color','#000') });

///hover button
		$(".form-button").mouseover(function() {
		$(this).removeClass('form-button')
		$(this).addClass('form-button-hover')
		})
		$(".form-button").mouseout(function(){
		$(this).removeClass('form-button-hover')
		$(this).addClass('form-button')
		});

///Filter Sorting
		$('#unit').change(function()  { updateUnit($(this).val()); });
		$('#perpage').change(function() { updatePerPage($(this).val()); });
		$('#criteria').change(function() { updateSortBy($(this).val()); });
		$('#filter-length').change(function() { updateFilter('length',$(this).val());});
		$('#filter-width').change(function()  { updateFilter('width',$(this).val()); });
		$('#filter-depth').change(function()  { updateFilter('depth',$(this).val()); });
		$('#filter-compartments').change(function()  { updateFilter('compartments',$(this).val()); });
		$('#filter-clear').click(function()  { clearFilter(); });
		$('#custom-filter a').click(function()  { clearCustomFilter($(this).attr('id')); });


////Tab Box
		$("#details .tab_content").hide(); //Hide all content
		$("#details ul.tabs li:first").addClass("active").show(); //Activate first tab
		$("#details .tab_content:first").show(); //Show first tab content
		
		//On Click Event
		$("#details ul.tabs").tabs("select","tab1");
		$("#details ul.tabs li").click(function() {
		$("#details ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$("#details .tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		return false;
		});

///Lightbox
		$("a#large-link").fancybox({'overlayColor':'#000000','overlayOpacity':0.6,'transitionIn':'none', 'transitionOut':'none'});
		$("a.group").fancybox({'overlayColor':'#000000','overlayOpacity': 0.6,'transitionIn':'none', 'transitionOut':'none'});	

///thumbnail slider
		$('#alt-img').jcarousel({
		wrap: 'circular',
		slideEasing: "easeOutBounce",
		dispItems: 1
		});
		
//Product Thumbnail Switch
		$("#alt-img a").hover(
		function () {
		var largePath = $(this).attr("ret");
		$("#large").attr({ src: largePath });
		
		return false;
		},
		function () {
		var largePath = $(this).attr("ret");
		var ltBoxPath = $(this).attr("href");
		
		//update links to new image path
		$("#large-link").attr({ href: ltBoxPath });
		$("#large").attr({ src: largePath });
		return false;
		});

///other products slider
		$('#other-products').jcarousel({
		wrap: 'circular',
		slideEasing: "easeOutBounce",
		dispItems: 1
		});

///minimum qty check on submit
$('#addtocart').submit(function() {
	
	//alert("test")
	
	var qty = $('#qty').val();
	var minOrder = $('#min-order').val();
	
	if(qty % minOrder)
	{
	alert('Minimum order quantity is ' + minOrder +' or multiples of ' + minOrder +'. Please correct quantity.');
	return false;
	} else {
	return true;
	}
  
});


///limit compare checkboxes
$("input:checkbox").change(function(){checkComparison()});


///init page height
		var h = $(window).height() - 632; $('#social').height(h);
		jQuery.event.add(window, "resize", resizeFrame);

///menu colapse
		initMenu();

		$('.share').share({
		//url:		iUrl,
		//title:		iTitle,
		//description: iDesc,
		services:		['facebook', 'twitter', 'google', 'stumbleupon' , 'yahoo', 'linkedin'],
		img_size:		32,
		a_target:		'_Blank'
		});


		///Estimate Shipping Cost
		$('.estimate').click(function() {
		  
		  $(".estimate").html("<img src='/images/common/ajax-loader.gif'/>");
		  
		  var country = $("#country-code").val();
		  var zipcode = $("#postal-code").val();
		  var weight = $("#cart-weight").val();
		  var data = "country-code="+ country +"&postal-code="+ zipcode +"&cart-weight="+ weight
	
		
				$.ajax({  
				type: "POST",  
				url: "/index.php/site/ajaxEstimateShipping",  
				data: data,  
				success: function(response)
				{
					location.reload(); 
				}
				});
		
		
		});
		
		///more countries
		$('#more-countries').click(function() {
		 	$('#con-countries').hide();
		 	$('#all-countries').show();
		 	$('#con-countries select').attr('name','con-country-code');
		 	$('#all-countries select').attr('name','country-code');
		 	$('#more').html("<a id='less-countries' href=''>Less</a>");
		});
		
		///less countries
		$('#less-countries').click(function() {
		 	$('#all-countries').hide();
		 	$('#con-countries').show();
		 	$('#con-countries select').attr('name','country-code');
		 	$('#all-countries select').attr('name','all-country-code');
		 	$('#more').html("<a id='more-countries' href=''>More</a>");
		});
		
		///Canada Provinces
		$('#country-code').change(function() {
			
			var country = $(this).val();
		
			if(country == "CA")
			{
			$('#provinces').slideDown('slow');
			} else {
			$('#province-code').val('');
			$('#provinces').slideUp('slow');
			}
			
		});
		
		///Set Shipping Carrier and Cost
		$('#shipping-rates').change(function() {
		$('#estimatorform').attr('action','/index.php/site/updateShipping');
		$('#estimatorform').submit();
		});
		
		///Update Cart Contents
		$('#update-basket').click(function() {
		var parameter_string = '';
		allNodes = $('.process');
		
		for(i = 0; i < allNodes.length; i++) {
		var tempid = allNodes[i].id;
		var temp = new Array;
		temp = tempid.split("_");
		var real_id = temp[2];
		var real_value = allNodes[i].value;
		var div_code = allNodes[i].title;
		parameter_string += real_id +':'+real_value+':'+div_code+',';
		}
		var data = 'ids='+parameter_string;
		
		$.ajax({  
		type: "POST",  
		url: "/index.php/site/ajaxUpdateCart",  
		data: data,  
		success: function(response){  
		location.reload(); 
		}});
});
///min order warning on blur
$('.process').change(function() {
	var newQty = $(this).val();
	var mulQty = $(this).attr('mul');
	var prevQty = $(this).attr('pre');
	
	if(newQty % mulQty)
	{
	alert('Sorry you must order full cartons with a minimum qty of '+ mulQty);
	$(this).val(prevQty);
	}
	
   //alert('Qty ='+ newQty +' Mul ='+ mulQty +' Prev = '+prevQty);
});


///clone shipping
$('#clone-to-shipping').click(function() {
	
	var bfname = $("#b-fname").val()
	var blname = $("#b-lname").val()
	var bcname = $("#b-cname").val()
	var baddr1 = $("#b-addr1").val()
	var baddr2 = $("#b-addr2").val()
	var bcity = $("#b-city").val()
	var bstate = $("#b-state").val()
	var bzipcode = $("#b-zip").val()
	var bcountry= $("#b-country").val()
	var bphone = $("#b-phone").val()

  	$("#s-fname").val(bfname);
	$("#s-lname").val(blname);
	$("#s-cname").val(bcname);
	$("#s-addr1").val(baddr1);
	$("#s-addr2").val(baddr2);
	$("#s-city").val(bcity);
	$("#s-state").val(bstate)
	$("#s-zip").val(bzipcode);
	$("#s-country").val(bcountry);
	$("#s-phone").val(bphone);
	
});

////slide toggle title field
		$('#s-save').click(function() {$('#s-label').slideToggle();});
		$('#b-save').click(function() { $('#b-label').slideToggle(); });

////use a saved address
		$('#saved-addresses li a').click(function() {

		var type = $(this).attr("class");
        var address = $(this).attr("atr");
        
        var addressArray = address.split(':');
		
		if(type == "bill")
		{
			$("#b-fname").val(addressArray[0]);
			$("#b-lname").val(addressArray[1]);
			$("#b-cname").val(addressArray[2]);
			$("#b-addr1").val(addressArray[3]);
			$("#b-city").val(addressArray[4]);
			$("#b-state").val(addressArray[5])
			$("#b-zip").val(addressArray[6]);
			$("#b-country").val(addressArray[7]);
			$("#b-phone").val(addressArray[8]);

		} else {
			$("#s-fname").val(addressArray[0]);
			$("#s-lname").val(addressArray[1]);
			$("#s-cname").val(addressArray[2]);
			$("#s-addr1").val(addressArray[3]);
			$("#s-city").val(addressArray[4]);
			$("#s-state").val(addressArray[5])
			$("#s-zip").val(addressArray[6]);
			$("#s-country").val(addressArray[7]);
			$("#s-phone").val(addressArray[8]);
		}
		
return false;
});


///hide error and standard messages
		//$('.msg').delay(4000).slideUp('slow');

//label illuminate
		$('.txt-input').not('.search-dim').focus(function() {
			$(this).css('border', '1px #fe8300 solid')
			//$(this).prev('label').css('color', '#fe8300')	
		});
		
		$('.txt-input').not('.search-dim').blur(function() {
			$(this).css('border', '1px #000 solid')
			//$(this).prev('label').css('color', '#000')
		});

///end document ready
});

function checkComparison()
{
	// total allowed to be checked.
	var max_allowed = 4;
	
	// count how many checked.
	var checked = $("input:checked").size();
	
	// perform test.
	if ( checked > max_allowed ) {
	
	// is more than the max so uncheck.
	$(this).removeAttr("checked");
	
	// display error message.
	alert("You can only compare " + max_allowed + " products at a time.");
	
	}
}


function updateUnit(value)
{
	var data = 'unit='+ value;
		
		$.ajax({  type: "POST",  url: "/index.php/site/ajaxUpdateUnit",  data: data, 
		success: function(response)
		{ 
		location.reload();
		}
		});
}

function updatePerPage(value)
{
		var data = 'perpage='+ value;
		
		$.ajax({  type: "POST",  url: "/index.php/site/ajaxUpdatePerPage",  data: data, 
		success: function(response)
		{ 
		location.reload();
		}
		});
}

function clearCustomFilter(value)
{
		var data = 'f='+ value;
		
		console.log(value);
		
		$.ajax({  type: "POST",  url: "/index.php/site/ajaxFilterReset",  data: data, 
		success: function(response)
		{
		var id = value.replace("_", "-");
		$('#'+id).val('0');
		location.reload();
		}
		});
}

function updateSortBy(value)
{
		var data = 'sortby='+ value;
		
		$.ajax({  type: "POST",  url: "/index.php/site/ajaxUpdateSortBy",  data: data, 
		success: function(response)
		{ 
		location.reload();
		}
		});
}

function updateFilter(dim,value)
{
		var data = 'val='+ value +'&dim='+ dim;
		
		$.ajax({  type: "POST",  url: "/index.php/site/ajaxUpdateFilter",  data: data, 
		success: function(response)
		{ 
		location.reload();
		}
		});
}

function clearFilter()
{
		var data = 'clear-filter';
		
		$.ajax({  type: "POST",  url: "/index.php/site/ajaxClearFilter",  data: data, 
		success: function(response)
		{
		///reset dropdowns
		$('#filter-length').val('0');
		$('#filter-width').val('0');
		$('#filter-depth').val('0');
		$('#filter-compartments').val('0');
		location.reload();
		}
		});
}





function resizeFrame() 
{
    var h = $(window).height() -632;
    if(h <= 200){$("#social").height(200);} else {$("#social").height(h);}
}

function initMenu() {
$('#menu ul').hide();
var seg = $.url();
var category = seg.segment(4);
var subcategory = seg.segment(5);
 
 if(subcategory)
 {
 $('#menu .'+category).show();
 } else {
 $('#menu .'+category).slideDown();
 
 }

  }
