/***
 * Rozszerzenia jQuery Validation
 */
jQuery.validator.addMethod("lettersonly", function(value, element) {
    return this.optional(element) || /^[a-zA-Z±æê³ñó¶¼¿¡ÆÊ£ÑÓ¬¯ ]+$/i.test(value);
}, "Proszê u¿ywaæ jedynie liter i spacji.");

jQuery.validator.addMethod("phonenumber", function(value, element) {
    return this.optional(element) || /^[0-9 +]+$/i.test(value);
}, "Proszê u¿ywaæ jedynie cyfr.");

jQuery.validator.addMethod("nip", function(value, element) {
    return this.optional(element) || validateNIP(value)
}, "Proszê podaæ prawid³owy numer NIP.");

jQuery.validator.addMethod("town", function(value, element) {
    return this.optional(element) || /^[a-zA-Z±æê³ñó¶¼¿¡ÆÊ£ÑÓ¬¯ \.\/]+$/i.test(value);
}, "Proszê u¿ywaæ jedynie liter i spacji.");

// Funkcja wymagana z powodu IE-hacka w jquery.validate.js
jQuery.validator.addMethod("selectrequired", function(value, element) {
    if (element.value=="") return false; else return true;
}, "To pole jest wymagane.");

function validateNIP(value)
{
    if ( !value.match( /^[0 -9]{3}-[0-9]{2}-[0-9]{2}-[0-9]{3}$/ )
            && !value.match( /^[0-9]{3}-[0-9]{3}-[0-9]{2}-[0-9]{2}$/ )
            && !value.match( /^[0-9]{10}$/ ) )
    return false;
    var my_nums = value.replace(/-/g,'');
    var valid_nums = "657234567";
    var sum=0;
    for (var temp=8;temp>=0;temp--)
        sum += (parseInt(valid_nums.charAt(temp)) * parseInt(my_nums.charAt(temp)));
    if ( (sum % 11) == 10 ? false : ((sum % 11) == parseInt(my_nums.charAt(9))) )
        return true;
    else
        return false;
}

/***
 * Inne funkcje
 */
function makeSublist(parent,child,isSubselectOptional,childVal)
{
    $("body").append("<select style='display:none' id='"+parent+child+"'></select>");
    $('#'+parent+child).html($("#"+child+" option"));

    var parentValue = $('#'+parent).attr('value');
    $('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());

    childVal = (typeof childVal == "undefined")? "" : childVal ;
    $("#"+child).val(childVal).attr('selected','selected');
    $('#'+child + " option").each( function (i) { $(this).val($(this).text());});

    $('#'+parent).change(function(){
        var parentValue = $('#'+parent).attr('value');
        $('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
        if(isSubselectOptional) $('#'+child).prepend("<option value='none' selected='selected'> -- Wybierz -- </option>");
        $('#'+child).trigger("change");
        $('#'+child).focus();
    });
}
