//resize image
$(document).ready(function(){
	resizeGridProductImageNonAjax();
});
function resizeGridProductImageNonAjax()
{
	$("a.thumbnailLink").each(function(){
		//$(this).hide();
		$(this).waitForImages(function(){
			var image = $(this).find('img.productgridimg');
			resizeSpecificImage(image);
		});
		//$(this).show('fast');
	});
}
function resizeSpecificImage(image)
{
	/* Max width for the image */
	var maxWidth = 70;
	/* Max hieght for the image */
	var maxHeight = 70;
	/*Used for aspect ratio*/
	var ratio = 0;
	/*Current image width*/
	var width = image.width();
	/*Current image height */
	var height = image.height();
	
	var ratio = maxHeight/maxWidth;
	var newW = 0;
	var newH = 0;
	if(height/width > ratio)
	{
		if(height > maxHeight)
		{
			newW = Math.round(width*(maxHeight/height));
			newH = maxHeight;
		}
	}
	else
	{
		//width is problem
		if(width > maxWidth)
		{
			newH = Math.round(height*(maxWidth/width));
			newW = maxWidth;
		}
	}
	image.attr({
		width : newW,
		height : newH
	});
}
function resizeGridProductImage()
{
	$("img.productgridimg").each(function () {
		$(this).hide();
	});
	$("img.productgridimg").load(function () {
        resizeSpecificImage($(this));
		$(this).show('fast');
	});
}

function resizeProductImage()
{
	var productimage = document.getElementById("productviewimg");
	//alert(productimage);
	if(productimage != null && productimage != '') {
		var height = productimage.height;
		var width = productimage.width;
		//alert(height);
		var selectedSize = 0;
		if(height>=width)
		{
			selectedSize = height;
			if(selectedSize>167) selectedSize = 167;
			productimage.style.height = selectedSize + "px";
		}
		else
		{
			selectedSize = width;
			if(selectedSize>224) selectedSize = 224;
			productimage.style.width = selectedSize + "px";
		}
	}
}

//===================================for checkout step 1
$(document).ready(function() {
	$('.linkRemove').click(function() {
			//var pid = $(this).attr('rel');
			var ans = confirm("Are you sure?");
			//alert($(this).attr('rel'));
			if(ans) {
				$.post('../cart/removeItem',{
					pid:$(this).attr('rel')}, function(data) {
						if(data=='ok') {
							//alert("#div"+$(this).attr('rel'));
							//$("#div"+pid).css('display','none');	
							location.reload(true);
						}
				});
			}
			return false;
	});
});
//===================================end script check out step 1


//===================================for check shipping cost on ViewCart page

//===================================for checkout step 2
$(document).ready(function(){
	jQuery.validator.addMethod("newAddressRequired", function(value, element) {
		if (!$("input#newAddr").is(":checked")){
			return $(element).parents("div#invoiceDetails").length;
			
		}
		return !this.optional(element);
	}, "");
	
	jQuery.validator.messages.required = " * Required";
	jQuery.validator.messages.newAddressRequired = " * Required";
	
	$("#frmAddress").validate({
		rules: {
		    "Step2AddressForm[newAddress]": "newAddressRequired",
		    "Step2AddressForm[newSuburb]": "newAddressRequired",
		    "Step2AddressForm[newPostcode]": "newAddressRequired digits",
		    "Step2AddressForm[newState]": "newAddressRequired"
		},
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
			} else {}
		},
		onkeyup: false,
		submitHandler: function(form) {
			//$("div.form-error").hide();
			form.submit();
		},
		debug:false
	});
});

$(document).ready(function() {
	$('#plDelivery div.subPanel').css('display','none');
	$('#div_savedAddress').slideDown('medium');
	$('.radAddressOption').click(function() {
		//alert($(this).attr('title'));
		//alert($(this).attr('value'));
		//$('#plDelivery div.subPanel').css('display','none');
		$('#plDelivery div.subPanel').slideUp('medium');
		//$('#div_'+$(this).attr('value')).css('display','');
		$('#div_'+$(this).attr('value')).slideDown('medium');
	});
});

$(document).ready(function(){
	$("input#newAddr").click(function(){
		if(this.checked == true) {
			//$("#frmAddress").valid();
		}
	});
});
//====================================end for checkout step 2

$(document).ready(function(){
   $("ul#ptype-expander2").hide();
   $("ul#brand-expander2").hide();
   
   $("a.showmorelink").bind('click', function(){
	   $("ul#brand-expander1").slideUp(500);
	   $("ul#brand-expander2").slideDown(500);      
      return false;
   });
   $("a.showlesslink").bind('click', function(){
	   $("ul#brand-expander2").slideUp(500);
	   $("ul#brand-expander1").slideDown(500);      
      return false;
   });
   

   $("a.showlesstypelink").bind('click', function(){
	   $("ul#ptype-expander2").slideUp(500);
	   $("ul#ptype-expander1").slideDown(500);
	  return false;
   });
   
   $("a.showmoretypelink").bind('click', function(){
	   $("ul#ptype-expander1").slideUp(500);
	   $("ul#ptype-expander2").slideDown(500);
	  return false;
   });
});

//register and profile
$(document).ready(function() {
	$("a#btnSubmit").click(function(event){
		ie8SafePreventEvent(event);
		$("#frmRegister").submit();
		return false;
	});
	$("a#btnSubmit2").click(function(event){
		ie8SafePreventEvent(event);
		$("#frmProfile").submit();
		return false;
	});
});
function ie8SafePreventEvent(e){
    if(e.preventDefault){ e.preventDefault()}
    else{e.stop()};

    e.returnValue = false;
    e.stopPropagation();        
}

//processing data in client if necessary and submit
function frmRegisterSubmit(form)
{
	form.submit();
}
//validate data
$(document).ready(function() {
	/*
	jQuery.validator.addMethod("invoiceRequired", function(value, element) {
		if ($("input#chkToggleCheck").is(":checked"))
			return $(element).parents("div#invoiceDetails").length;
		return !this.optional(element);
	}, "");
	*/
	jQuery.validator.messages.required = " * Required";
	jQuery.validator.messages.email = " * Invalid Email";
	jQuery.validator.messages.digits = " * Not a number";
	jQuery.validator.messages.equalTo = " * Not match";
	jQuery.validator.messages.minlength = " * Too short ";
	jQuery.validator.messages.maxlength = " * Too long number ";
	//jQuery.validator.messages.invoiceRequired = " * Required";
	
	
	
	$("#frmRegister").validate({
		rules: {
		    "RegisterForm[password]": "required",
		    "RegisterForm[confirmPassword]": {
		      equalTo: "#RegisterForm_password"
		    },
		    "RegisterForm[firstName]": "required",
			//"RegisterForm[contactName]": "required",
		    "RegisterForm[email]": "required email",
		    "RegisterForm[confirmEmail]": {
		      equalTo: "#RegisterForm_email"
		    },
		    "RegisterForm[sSuburb]": "required",
		    "RegisterForm[sState]": "required",
		    "RegisterForm[sAddress]": "required",
		    "RegisterForm[sPostcode]": "required digits",
			"RegisterForm[sFax]": {
				digits: true,
				maxlength:10,
				minlength:8
			},
		    "RegisterForm[verifyCode]": "required",
			"RegisterForm[sHomephone]": {
				required: true,
				digits: true,
				maxlength:10,
				minlength:8
			},
		    "RegisterForm[sMobile]": {
				digits: true,
				maxlength:10,
				minlength:10
			}
		},
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? 'You missed 1 field or invalid input. It has been highlighted below'
					: 'You missed ' + errors + ' fields or invalid input. They have been highlighted below';
				$("div.user-error li").html(message);
				$("div.user-error").show();
			} else {
				$("div.user-error").hide();
			}
		},
		onkeyup: false,
		submitHandler: function(form) {
			//$("div.form-error").hide();
			frmRegisterSubmit(form);
		},
		debug:false
	});
	$("#frmProfile").validate({
		rules: {
		    "RegisterUpdateForm[password]": "required",
		    "RegisterUpdateForm[confirmPassword]": {
		      equalTo: "#RegisterUpdateForm_password"
		    },
		    "RegisterUpdateForm[firstName]": "required",
		    "RegisterUpdateForm[lastName]": "required",
		    "RegisterUpdateForm[email]": "required email",
		    "RegisterUpdateForm[sSuburb]": "required",
		    "RegisterUpdateForm[sState]": "required",
		    "RegisterUpdateForm[sAddress]": "required",
		    "RegisterUpdateForm[sPostcode]": "required digits",
		    "RegisterUpdateForm[contactName]": "required",
		    "RegisterUpdateForm[verifyCode]": "required",
			"RegisterUpdateForm[sHomephone]": {
				required: true,
				digits: true,
				maxlength:10,
				minlength:8
			},
		    "RegisterUpdateForm[sMobile]": {
				digits: true,
				maxlength:10,
				minlength:10
			},
		    "RegisterUpdateForm[sFax]": {
				digits: true,
				maxlength:10,
				minlength:8
			}
		},
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? 'You missed 1 field or invalid input. It has been highlighted below'
					: 'You missed ' + errors + ' fields or invalid input. They have been highlighted below';
				$("div.user-error li").html(message);
				$("div.user-error").show();
			} else {
				$("div.user-error").hide();
			}
		},
		onkeyup: false,
		submitHandler: function(form) {
			//$("div.form-error").hide();
			frmRegisterSubmit(form);
		},
		debug:false
	});
	
	$("#frmPaymentMethod").validate({
		rules: {
			"chkTerm": 'required'
		},
		messages: {
			"chkTerm": "<div style='position:absolute; color:#f00'>You have to check this box to continue</div>"
		}
	});
	$("#frmCCard").validate({
		rules: {
			"chkTerm": 'required'
		},
		messages: {
			"chkTerm": "<div style='position:absolute; color:#f00'>You have to check this box to continue</div>"
		}
	});
});


function newPrintPopup(url)
{
  var win = window.open(url, "_blank", "toolbar=no, location=no, directories=no, status=no, menubar=no, resizable=YES, copyhistory=no, scrollbars=Yes,width=750, height=650, top=50, left=100");
  win.focus();
}

 // Product view script
$(document).ready(function(){
	$("#freight-link").click(function(){
		$("#plFreight").fadeIn();
		return false;
	}) ;

	$("#btnFreightSubmit").click(function() {
		// call ajax to get freight information
		$("#lblResult").fadeIn();
	});

	$("#btnFreightClose").click(function() {
		$("#lblResult").html("");
		$("#plFreight").fadeOut();
	});
	
}) ;
var mainHost = "/";
// Search Function
$(document).ready(function() {
	var defaultSearchText = "Search Products...";
	$('#keyword').focus(function() {
		if($(this).val()==defaultSearchText) {
			$(this).val("");
		}
	});
	
	$('#keyword').blur(function() {
		if($(this).val()=="") {
			$(this).val(defaultSearchText);
		}
	});
	
	$('#keyword').keydown(function(event) {
		
		if(event.which==13) {
			if($(this).val() == defaultSearchText) $(this).val("");
			var url = mainHost +  "catalog/search/" +$(this).val();
			//alert(url);
			//url = url + "";
			window.location.href = url; 
			event.preventDefault();
		}
	});
	
	$(".link-search").click(function(event){
		event.preventDefault();
		if($("#keyword").val() == defaultSearchText) $("#keyword").val("");
		var url = mainHost + "catalog/search/"+$("#keyword").val();
		window.location.href = url; 
	});
});

//============FAQ EFFECT====================
$(document).ready(function() {
	  $('#faqs h3').each(function() {
	    var tis = $(this), state = false, answer = tis.next('div').hide().css('height','auto').slideUp();
	    tis.click(function() {
	      state = !state;
	      answer.slideToggle(state);
	      tis.toggleClass('active',state);
	    });
	  });
	});

//=============ONCLICK ON PROMOTION==============
function gotoPromotion(tag)
{
	window.open(tag.alt,'_newtab');
}


/*** 
    Simple jQuery Slideshow Script
    Released by Jon Raasch (jonraasch.com) under FreeBSD license: free to use or modify, not responsible for anything, etc.  Please link out to me if you like it :)
***/

function slideSwitch() {
    var $active = $('#slideshow IMG.active');

    if ( $active.length == 0 ) $active = $('#slideshow IMG:last');

    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        : $('#slideshow IMG:first');

    // uncomment the 3 lines below to pull the images in random order
    
    // var $sibs  = $active.siblings();
    // var rndNum = Math.floor(Math.random() * $sibs.length );
    // var $next  = $( $sibs[ rndNum ] );


    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});

//====================HANDLE IMAGE ERROR=======================
function ImageError(source,link){
    source.src = link;
    source.onerror = "";//avoid stack overflow on IE
    return true;
}
