jQuery.validator.addMethod("regexp", function(value, element, param) {
	return !value.length || (new RegExp("^" + param + "$")).test(value);
},"Neplatná hodnota.");

jQuery.extend(jQuery.validator.messages, {
	required: "Tento údaj je povinný.",
	email: "Zadaný e-mail je neplatný.",
	regexp: "Zadaný údaj je neplatný."
});

formSubmited = false;

function validateIc(ic, element){
	if(!ic.length)
		return true;
	
	if(!ic.match(new RegExp("^\\d{8}$")))
		return false;

    for(i=0,a=0; i<7; a+=ic[i]*(8-i),i++);

    a = a % 11;

    if (a===0 || a===10) c = 1;
    else if (a===1) c = 0;
    else c = 11-a;

    return parseInt(ic[7]) === c;
}

function validateRc(rc, element){
	if(!(matches = rc.match(new RegExp('^(\\d{2})(\\d{2})([0-3][0-9])/?(\\d{3})(\\d?)$'))))	 
    	return false;
	year = matches[1];
	month = matches[2];
	day = matches[3];
	ext = matches[4];
	c = matches[5];

    if(c==='')
        return year < 54;

    mod = parseInt(year+month+day+ext,10) % 11;
    
    year = parseInt(year,10);
    month = parseInt(month,10);
    day = parseInt(day,10);
    ext = parseInt(ext,10);
    c = parseInt(c,10);    
    
    if(mod==10) mod = 0;
    if(mod!=c)
        return false;

    year += year<54 ? 2000 : 1900;

    if(month>70 && year>2003) month -= 70;
    else if(month>50) month-=50;
    else if(month>20 && year>2003) month -= 20;
    
    date = new Date(year,month-1,day);
    if(year!=date.getFullYear() || month!=date.getMonth()+1 || day!=date.getDate())
        return false;

    return true;
}

function validateDic(dic, element){
	if(!dic.length)
		return true;
	else if(dic.length<2)
		return false;
	
	id = dic.substr(0,2).toUpperCase();
	x = dic.substr(2);
	
	if(id!='CZ' && id!='SK' || x.length<8 || x.length>11)
		return false;
	
	return x.length==8 ? validateIc(x) : validateRc(x);
}


jQuery.validator.addMethod("ic", validateIc);
jQuery.validator.addMethod("dic", validateDic);
jQuery.extend(jQuery.validator.messages, {
	ic: "Zadané IČ je neplatné.",
	dic: "Zadané DIČ je neplatné."
});



$(function(){
	$('#validate_form input[name^=del_]').keyup(function(){
		if(formSubmited){
			$('#validate_form').valid();
		}
	});
	$('#validate_form input:submit').click(function(){
		formSubmited = true;
	});

	$('#validate_form.order_form input:submit').click(function(){
		if(!$('#validate_form').valid()){
			window.alert("Některá z položek nebyla správně vyplněna!\nObjednávku nelze odeslat.");
		}
	});
	
	
	//vytisteni objednavky
	if($('#order_print').length){
		$('#order_print').click(function(){
			if(window.confirm('Objednávka bude pouze vytištěna, nedojde k jejímu odeslání.\nChcete-li objednávku odeslat, použijte prosím tlačítko Odeslat.')){
				window.print();
			}
		});
		$('#order_print').show();
	}
});