function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function sprintf( ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Ash Searle (http://hexmen.com/blog/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Paulo Ricardo F. Santos
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: sprintf("%01.2f", 123.1);
    // *     returns 1: 123.10
    // *     example 2: sprintf("[%10s]", 'monkey');
    // *     returns 2: '[    monkey]'
    // *     example 3: sprintf("[%'#10s]", 'monkey');
    // *     returns 3: '[####monkey]'
 
    var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
    var a = arguments, i = 0, format = a[i++];
 
    // pad()
    var pad = function(str, len, chr, leftJustify) {
        if (!chr) {chr = ' ';}
        var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
        return leftJustify ? str + padding : padding + str;
    };
 
    // justify()
    var justify = function(value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
        var diff = minWidth - value.length;
        if (diff > 0) {
            if (leftJustify || !zeroPad) {
                value = pad(value, minWidth, customPadChar, leftJustify);
            } else {
                value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
            }
        }
        return value;
    };
 
    // formatBaseX()
    var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
        // Note: casts negative numbers to positive ones
        var number = value >>> 0;
        prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
        value = prefix + pad(number.toString(base), precision || 0, '0', false);
        return justify(value, prefix, leftJustify, minWidth, zeroPad);
    };
 
    // formatString()
    var formatString = function(value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
        if (precision != null) {
            value = value.slice(0, precision);
        }
        return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
    };
 
    // doFormat()
    var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) {
        var number;
        var prefix;
        var method;
        var textTransform;
        var value;
 
        if (substring == '%%') {return '%';}
 
        // parse flags
        var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
        var flagsl = flags.length;
        for (var j = 0; flags && j < flagsl; j++) {
            switch (flags.charAt(j)) {
                case ' ': positivePrefix = ' '; break;
                case '+': positivePrefix = '+'; break;
                case '-': leftJustify = true; break;
                case "'": customPadChar = flags.charAt(j+1); break;
                case '0': zeroPad = true; break;
                case '#': prefixBaseX = true; break;
            }
        }
 
        // parameters may be null, undefined, empty-string or real valued
        // we want to ignore null, undefined and empty-string values
        if (!minWidth) {
            minWidth = 0;
        } else if (minWidth == '*') {
            minWidth = +a[i++];
        } else if (minWidth.charAt(0) == '*') {
            minWidth = +a[minWidth.slice(1, -1)];
        } else {
            minWidth = +minWidth;
        }
 
        // Note: undocumented perl feature:
        if (minWidth < 0) {
            minWidth = -minWidth;
            leftJustify = true;
        }
 
        if (!isFinite(minWidth)) {
            throw new Error('sprintf: (minimum-)width must be finite');
        }
 
        if (!precision) {
            precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
        } else if (precision == '*') {
            precision = +a[i++];
        } else if (precision.charAt(0) == '*') {
            precision = +a[precision.slice(1, -1)];
        } else {
            precision = +precision;
        }
 
        // grab value using valueIndex if required?
        value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
 
        switch (type) {
            case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
            case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
            case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
            case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'i':
            case 'd':
                number = parseInt(+value, 10);
                prefix = number < 0 ? '-' : positivePrefix;
                value = prefix + pad(String(Math.abs(number)), precision, '0', false);
                return justify(value, prefix, leftJustify, minWidth, zeroPad);
            case 'e':
            case 'E':
            case 'f':
            case 'F':
            case 'g':
            case 'G':
                number = +value;
                prefix = number < 0 ? '-' : positivePrefix;
                method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
                textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
                value = prefix + Math.abs(number)[method](precision);
                return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
            default: return substring;
        }
    };
 
    return format.replace(regex, doFormat);
}
function formatPrice(value,waluta) {
	waluta = waluta != undefined ? waluta : 'zł'; 
	return sprintf('%.2f %s',value,waluta).replace('.',',');
}

$(document).ready(function() {

    var emailbox_str = (language == 'pl') ? 'wpisz e-mail' : 'enter your email address';
    var emailbox = $('div.newsletter input.emailbox, form#newsletter_form input#eml');
    
    emailbox.focus(function() {
        if ($(this).attr('value') == emailbox_str) {
            $(this).attr('value',''); 
        }
    });
    emailbox.blur(function() {
        if ($(this).attr('value') == '') {
            $(this).attr('value',emailbox_str); 
        }
    });
    $('div.newsletter input.emailbox').attr('value',emailbox_str);
    
    $.validator.addMethod(
            "regex",
            function(value, element, regexp) {
                var check = false;
                var re = new RegExp(regexp);
                return this.optional(element) || re.test(value);
            },
            "Please check your input."
    );

    
    
    $('div.koszyk input.przelicz').hide();
    $('div.koszyk input[name=ilosc]').focus( function() {
    	$(this).next('input.przelicz').show();
    });
    $('div.koszyk td form, form.opis').each(function() {
    	$(this).validate({
    		rules: {
    			ilosc: {
    				required: true,
    				number: true,
    				min: 1
    			},
    			taste: {
    				required: true,
    				min: 1
    			}

    		},
    	    invalidHandler: function() {
    			if ($('select[name=taste]').val() == 0) {
    				alert("Wybierz smak produktu.");
    			} else {
    				alert("Niedozwolone znaki. Ilość musi być dodatnią liczbą.");
    			}
    		},
    		errorClass: "nil",
    		errorPlacement: function() {}
        	
    
    	});
    });
    
    
    $('td.right input.inny')
    .attr('disabled','true')
    .addClass('disabled');
    $('td.right')
    .addClass('disabled');
    
    $('td.right input[name=shipping_address_match]')
    .removeAttr('checked')
    .click(function() {
        if ($(this).attr('checked')) {
            $('td.right input.inny').parent().andSelf()
            .removeAttr('disabled')
            .removeClass('disabled');
        } else {
            $('td.right input.inny').parent().andSelf()
            .attr('value','')
            .addClass('disabled')
            .removeClass('error');
            $('td.right input.inny').attr('disabled','true');
            $('td.right label.error').hide();
        }
    });
    
    $('form.dane').validate({
        
        highlight: function(element, errorClass) {
            $(element).addClass('error');
        },
        
        errorPlacement: function(error, element) {
        	if (element.attr("name") == "check_ustawa") {
        		$('div#check1error').html(error);
        	} else if (element.attr("name") == "check_regulamin") {
        		$('div#check2error').html(error);
        	} else {
        		error.insertBefore(element);
        	}
        },
        
        rules: {
            invoice_name: "required",
            invoice_surname: "required",
            invoice_NIP: {
                rangelength: [10,10]
            },
            invoice_city: "required",
            invoice_code: {
                required: true,
                regex: /^[0-9][0-9]-[0-9][0-9][0-9]$/
            },
            invoice_street: "required",
            invoice_house: "required",
//            lokal: "number",
            invoice_tel: "required",
            invoice_email: "required email",
            shipping_name: "required",
            shipping_surname: "required",
            shipping_NIP: {
                rangelength: [10,10]
            },
            shipping_city: "required",
            shipping_code: {
                required: true,
                regex: /^[0-9][0-9]-[0-9][0-9][0-9]$/
            },
            shipping_street: "required",
            shipping_house: "required",
//            dost_lokal: "number",
            shipping_tel: "required",
            shipping_email: "required email"
        },
        
        messages: {
            invoice_name: "Podaj imię",
            invoice_surname: "Podaj nazwisko",
            invoice_NIP: "Podaj 10 cyfr",
            invoice_city: "Podaj miejscowość",
            invoice_code: "Podaj poprawny kod pocztowy",
            invoice_street: "Podaj ulicę",
            invoice_house: "Podaj numer domu",
            invoice_tel: "Podaj numer telefonu",
            invoice_email: {
                required: "Podaj adres e-mail",
                email: "Podaj prawidłowy adres"
            },
            shipping_name: "Podaj imię",
            shipping_surname: "Podaj nazwisko",
            shipping_city: "Podaj miejscowość",
            shipping_code: "Podaj poprawny kod pocztowy",
            shipping_street: "Podaj ulicę",
            shipping_house: "Podaj numer domu",
            shipping_tel: "Podaj numer telefonu",
            
            check_regulamin: "Potwierdź zapoznanie się z regulaminem sklepu",
            check_ustawa: "Wyraź zgodę na przetwarzanie danych osobowych"
            	
        },
        highlight: function(element, errorClass) {
        	if ($(element).attr('type') != 'checkbox')
        		$(element).addClass(errorClass);
        }
        	
    });
    
    $('form.formaplatnosci').validate({
    	rules: {
    		formaplatnosci: {
    			required: true
    		}
    	},
    	invalidHandler: function() {
			alert("Wybierz formę płatności.");
		},
		errorPlacement: function() {}
    	
    });
    
    $('form#newsletter_form').validate({
    	rules: {
    		eml: "required email",
    		zgoda: "required"
    	},
    	messages: {
    		eml: {
    			required: language == 'pl' ? "Uzupełnij to pole." : 'Complete this field',
    			email: language == 'pl' ? "Niepoprawny e-mail" : 'Incorrect e-mail address'
    		},
    		zgoda: language == 'pl' ? "Musisz wyrazić zgodę na przetwarzanie danych." : 'You must consent to personal data processing.'
    	},
    	errorPlacement: function(error, element) {
    		if (element.attr("name") == "eml") {
    			$('#check1error').html(error);
    		} else if (element.attr("name") == "zgoda") {
        		$('#check2error').html(error);
        	} 
        }
    	
    	
    });
    
    
    $('.jqzoom').jqzoom({
        title: false,
        zoomWidth: 200,
        zoomHeight: 200,
        hideEffect:'fadeout',
        fadeoutSpeed: 'fast',
        preloadText: language == 'pl' ? 'wczytuję' : 'loading'
    });
    
    
    $('div.productsearchbox select[name=s2]').change(searchChangeFunc);
    searchChangeFunc();
});

var searchChangeFunc = function() {
	var txt1 = (language == 'pl') ? '--wybierz--' : '--select--';
	var txt2 = (language == 'pl') ? '(brak kategorii)' : '(no categories)';
	var txt3 = (language == 'pl') ? '--wybierz kategorię--' : '--select category--';
	
	var tgt = $('div.productsearchbox select[name=s]');
	var base = '<option value="0">'+txt1+'</option>';
	var empty = '<option value="0">'+txt2+'</option>';
	if ($(this).val() > 0) {
		var t = types[$(this).val()];
		if (t.length > 0)
			tgt.html(base+types[$(this).val()]);
		else
			tgt.html(empty);
		tgt.removeAttr('disabled');
	} else {
		tgt.attr('disabled','disabled');
		tgt.html('<option value="0">'+txt3+'</option>');
	}
};
var searchSetFunc = function(opt,opt2) {
	var tgt = $('div.productsearchbox select[name=s]');
	var k = $('div.productsearchbox select[name=s2]');
	k.val(opt2);
	k.change();
	tgt.val(opt);
}