$(function() {
	//rotate product images
	$("div#productimage-top").cycle({ 
			fx:      			'fade', 
			speedIn:  			600, 
			speedOut: 			1000, 
			sync:     			1, 
			delay:    			500,
			pager:    			'#productimage-bottom-pager', 
			containerResize:	0,
			pagerAnchorBuilder: pagerFactory
	});
	function pagerFactory(idx, slide) {
        var s = idx > 10 ? ' style="display:none"' : '';
        return '<li'+s+'><a href="#">'+(idx+1)+'</a></li>';
    };
	
	// Glow all images with glow class
	$("img.glow", this) .hover(
		function() { 
			if($(this).attr("src").indexOf("-on") == -1) {
				$(this).fadeTo("250", 0.5);
				$(this).attr("src", $(this).attr("src").replace(".png","-on.png#hover"));
				$(this).fadeTo("250", 1);
			} 
		}, 
		function() { 
			if($(this).attr("src").indexOf("-on.png#hover") != -1) {
				$(this).attr("src", $(this).attr("src").replace("-on.png#hover", ".png"));
			}
		}
	); 
	//launch order form on order button submit
	$("img.order", this) .click(
		function() { 
			//get product code
			sProductcode = $(this).attr('id');
			//launch order window
			window.open("/order.php5?productcode="+sProductcode,"","width=500,height=700,status=1,scrollbars=1");
		}
	); 
	//launch order form for SecuMate Marker on order button submit
	$("img.order-marker", this) .click(
		function() { 
			//get product code
			sProductcode = $(this).attr('id');
			
			//label image
			sLabelLogoImage = getCookie("label-logo-image");
			//label name
			sLabelFileName = Math.floor(Math.random()*100000001);
			
			//save label to file
			saveLabel(sLabelFileName);
			
			//launch order window
			window.open("/order.php5?productcode="+sProductcode+"&label-logo-image="+sLabelLogoImage+"&label-filename="+sLabelFileName+".png","","width=500,height=700,status=1,scrollbars=1");
		}
	); 
	//validate input field on blur
	$("input.validate", this) .blur(
		function() { 
			validateInput(this);
		}
	); 

	//validate select on blur
	$("select.validate", this) .blur(
		function() { 
			validateInput(this);
		}
	); 
	//validate form on submit
	$("form").submit(function() {
		var bPostform;
		//check all input fields for validation
		$(".validate").each(function(){
			var $bValidate = validateInput(this);
			if (!$bValidate) {
				bPostform = 'no-post';
			}
		});
		//check amount requirements
		iMinAmount = $("input.minamount").attr('value');
		iInputAmount = $("#aantal").attr('value'); 
		
		if (iInputAmount < iMinAmount) {
			
			$("#aantal").css("border-color", "#B82F1C");
			bPostform == 'no-post';
			return false;
		}
		//post form if al input fields are validated
		if (bPostform == 'no-post') {
			return false;
		} else {
			return true;
		}
	});
	//update minamount on option select
	$("select.setamount", this) .change(
		function() { 
			iMinAmount = $(this.options[this.selectedIndex]).attr("minamount");
			//set min amount hidden field
			$("input.minamount").attr({value: iMinAmount});
		}
	); 
	//do some actions after changing amount of product
	$("input.inputamount", this) .blur(
		function() {
			iInputAmount = this.value;
		
			//apply setup fees			
			for(i = 0; i < aSetupFeesQuantity.length; i++){
				if (iInputAmount >= aSetupFeesQuantity[i]) {
					iSetupFee = aSetupFeesFee[i];
				} 
			} 
			
			$('td.setupfee').empty().append('&euro; '+number_format(iSetupFee/100, 2, '.', ''));
			$('input.setupfee').attr({value: iSetupFee});
		}
	); 
	$(document).ready(function() {
		//old browser check
		sBrowser = $.browser.name;
		sBrowserVersion = $.browser.versionNumber;

		if (sBrowser == 'msie' && sBrowserVersion < '7') {
			$("#old-browser").show();
		}
	});
});

function validateInput(oInput) {
	sValidationType = $(oInput).attr('name');
	sValue = oInput.value;
	switch(sValidationType) {
		case 'straat':
			sRegex = /^[A-Za-z0-9-. ]{5,}$/g;
			sMessage = 'Min. 5 tekens, A-Z en 0-9';
		break;   
		case 'pc':
			sRegex = /^[A-Za-z0-9 ]{6,}$/g;
			sMessage = 'Min. 6 tekens, A-Z en 0-9';
		break;
		case 'aantal':
			sRegex = /^[0-9]{1,}$/g;
			sMessage = 'Dit moet een getal zijn';
		break;   
		case 'plaats':
			sRegex = /^[A-Za-z0-9-. ]{3,}$/g;
			sMessage = 'Min. 3 tekens, A-Z en 0-9';
		break;   
		case 'telefoon':
			sRegex = /^[0-9- ]{10,}$/g;
			sMessage = 'Min. 10 tekens, 0-9';
		break;   
		case 'mail':
			sRegex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
			sMessage = 'Geen geldig e-mail adres';
		break;
		
	}
	
	sTest = sValue.match(sRegex, '');
	if (!sTest) {
		$(oInput).css("border-color", "#B82F1C");
		$("label."+sValidationType).empty();
		$("label."+sValidationType).append("<b> ("+sMessage+")</b>");
		return false;
	} else {
		$(oInput).css("border-color", "#CCCCCC");
		$("label."+sValidationType).empty();
		$("label."+sValidationType).append('<img src="/img/icon-success.gif">');
		return true;
	}
}

function number_format( number, decimals, dec_point, thousands_sep ) {
 
    var n = number, prec = decimals, dec = dec_point, sep = thousands_sep;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    sep = sep == undefined ? ',' : sep;
 
    var s = n.toFixed(prec),
        abs = Math.abs(n).toFixed(prec),
        _, i;
 
    if (abs > 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec || '.');
    }
 
    return s;
}
