$.validator.addMethod("kodPocztowy", function(value, element) {
    return this.optional(element) || /^[0-9]{2}-[0-9]{3}$/.test(value);
}, "Proszę podać poprawny kod pocztowy.");

function isValidDate(date, r, m, d) {
    if (Object.prototype.toString.call(date) !== "[object Date]" )
        return false;
    if(isNaN(date.getTime()))
        return false;
    if(date.getDate() != d  || date.getMonth() !=m || date.getFullYear() != r)
        return false;
    else
        return true;
}

jQuery.extend(jQuery.validator.messages, {
    required: "Pole wymagane.",
    remote: "Please fix this field.",
    email: "Proszę podać poprawny adres e-mail.",
    url: "Please enter a valid URL.",
    date: "Please enter a valid date.",
    dateISO: "Proszę podać datę w formacie rrrr-mm-dd.",
    number: "Proszę podać poprawną liczbę.",
    digits: "Proszę podać poprawną liczbę.",
    creditcard: "Please enter a valid credit card number.",
    equalTo: "Please enter the same value again.",
    accept: "Proszę wybrać w plik w wymaganym formacie.",
    maxlength: jQuery.validator.format("Proszę podać co najmniej {0} znaki."),
    minlength: jQuery.validator.format("Proszę podać co najwyżej {0} znaki."),
    rangelength: jQuery.validator.format("Proszę podać od {0} do {1} znaków."),
    range: jQuery.validator.format("Proszę podać liczbę od {0} do {1}."),
    max: jQuery.validator.format("Proszę podać liczbę mniejszą lub równą {0}."),
    min: jQuery.validator.format("Proszę podać liczbę większą lub równą {0}.")
});

jQuery.validator.addMethod("numer", function(value, element) {
    return this.optional(element) || /^[0-9]{1}$|^[1-9]{1}[0-9]*$/.test(value);
}, jQuery.validator.messages.number);

$.validator.addMethod("pageRequired", function(value, element) {
    var $element = $(element)
    function match(index) {
        return currentStep == index && $(element).parents("#stepContent" + index ).length;
    }
    if (match(1) || match(2) || match(3) || match(4)) {
        return !this.optional(element);
    }
    return "dependency-mismatch";
}, $.validator.messages.required)



var closetimer = 0;
var menuitem = 0;

function menu_open(){
    menu_canceltimer();
    menu_close();
    menuitem = $(this).find('ul').css('visibility', 'visible');
}

function menu_close(){
    if(menuitem)
        menuitem.css('visibility', 'hidden');
}

function menu_timer(){
    closetimer = window.setTimeout(menu_close, 50);
}

function menu_canceltimer(){
    if(closetimer)
    {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}

$(document).ready(
    function(){
        $('.button').corner('4px');
        
        $('#menu > li').bind('mouseover', menu_open)
        $('#menu > li').bind('mouseout',  menu_timer)

        $('#menu li ul').each(function(){
            var maxSubmenuWidth = 0;
            $(this).find('.sub_content').each(function(){
                var width = $(this).width();
                
                if(width > maxSubmenuWidth) {
                    maxSubmenuWidth = width;

                }
            });

            $(this).find('.sub_content').width(maxSubmenuWidth)
            $(this).find('.last').find('.sub_content').width(maxSubmenuWidth);
            $(this).width(maxSubmenuWidth+40);
        });

        $('#search_input').focus(function(){
            if($(this).val() == 'wyszukaj...') {
                $(this).val('')
            }
        });

        $('#ankieta_form').submit(function() {
            if(sprawdzAnkiete() == false) return false;
        });

        $("#formNewsletter").submit(function() {
            sendNewsletter();
            return false;
        });

        $("#signInNewsletter").click(function(){
            sendNewsletter();
        });

        $("#signOutNewsletter").click(function(){
            $("#actionNewsletter").val('wypisz');
            sendNewsletter();
        });

    });



document.onclick = menu_close;

$(window).load(function() {
    var popup = $('#popup');
    popup.css({
        'margin-left': '-'+(popup.width()/2)+'px'
    });
    popup.css({
        'margin-top': '-'+(popup.height()/2)+'px'
    });
    popup.fadeIn(500);

    $('#popup-close').click(function() {
        popup.fadeOut(500);
    });
    
});

function sendNewsletter() {
    var email = $('#emailNewsletter').val();
    var action = $('#actionNewsletter').val();

    if(email == '' || !checkEmail(email)) {
        alert("Proszę podać poprawny adres e-mail.");
        return false;
    }

    if(action == 'zapisz') {
        if(!confirm('Zgodnie z ustawą z dnia 18 lipca 2002 r. (Dz.U. Nr 144 z 2002 r., poz. 1204) o świadczeniu usług drogą elektroniczną, od 10 marca 2003 r. wymagana jest zgoda adresata na otrzymywanie ofert handlowych w ten sposób. W związku z tym zwracamy się do Państwa z pytaniem czy wyrażają Państwo zgodę na otrzymywanie w przyszłości od nas ofert i innych informacji drogą elektroniczną?')) {
            return false;
        }
    } else if(action == 'wypisz') {
        $("#actionNewsletter").val('zapisz');
        if(!confirm('Czy napewno chcesz wypisać się z newslettera?')) {
             
            return false;
        }
    } else {
        return false;
    }
    $.post("ajax.php?action=newsletter", {
        newsletter: email,
        action: action
    },
    function(data){
        alert(data);
    });
    return true;
}


function zmien_wojewodztwo()
{
    var miejsce=$('#wojewodztwo').val();

    $.get("ajax.php?ak=wyswietl_miasta&i="+miejsce, function(data){
        $('#miasto_div').html(data);
    });

}

function wybierz_miasto(jezyk)
{
    miejsce=document.getElementById('miasta').value;
    if (miejsce>0)
    {
        if (jezyk=='pl') document.location.href='lokalizacje_id_5.html?krok=2&m='+miejsce;
        if (jezyk=='en') document.location.href='lokalizacje_id_120.html?krok=2&m='+miejsce;
        if (jezyk=='de') document.location.href='lokalizacje_id_13.html?krok=2&m='+miejsce;
    }
}

function wybierz_sklep(jezyk)
{
    miejsce=document.getElementById('sklepy').value;
    if (miejsce>0)
    {
        if (jezyk=='pl') document.location.href='lokalizacje_id_5.html?krok=3&m='+miejsce;
        if (jezyk=='en') document.location.href='lokalizacje_id_120.html?krok=3&m='+miejsce;
        if (jezyk=='de') document.location.href='lokalizacje_id_13.html?krok=3&m='+miejsce;
    }
}

function sprawdz_poziom(id)
{
    $.get("ajax.php?ak=sprawdz_poziom&i="+id, function(data){
        if (data>3)
        {
            alert('Brak uprawnień do edycji tej strony');
        }
    });
}

function lokalizacja_mapa(lat, lng) {


    if (GBrowserIsCompatible()) {
        var centerPoint = new GLatLng(lat, lng);

        var divMapa = document.getElementById('lokalizacja_mapa');

        var mapa = new GMap2(divMapa);
        //bounds = new GLatLngBounds();

        mapa.addControl(new GLargeMapControl());
        mapa.addControl(new GMapTypeControl());


        mapa.setCenter(centerPoint, 14);

        var ikona1 = new GIcon();
        ikona1.image = "http://www.polomarket.pl/punkt_etap_2.gif";
        ikona1.iconSize = new GSize(36, 22);
        ikona1.infoWindowAnchor = new GPoint(16,16);
        ikona1.iconAnchor = new GPoint(16,16);
        var marker = new GMarker(centerPoint, {
            icon: ikona1
        });
        mapa.addOverlay(marker);

    //        bounds.extend(marker.getPoint());
    //        mapa.setZoom(mapa.getBoundsZoomLevel(bounds));
    //        mapa.setCenter(bounds.getCenter());


    //mapa.setCenter(marker.getPoint());
    //google.maps.event.trigger(mapa, 'resize').
    // mapa.checkResize();

    }
}

function sprawdzAnkiete() {
    var ankieta = $('.ankieta');
    var error = false;
    ankieta.find('.ankieta_pytanie').each(function() {
        if($(this).find('input').size() > 0 ) {
            if($(this).find('input:checked').size() == 0) {
                error = true;
            }
        } else {
            if($(this).find('textarea').val() == '') {
                error = true;
            }
        }
    });
    if(error) {
        alert("Wypełnij wszystkie pola ankiety");
        return false;
    }
    return true;
}

function setLangValidators(lang) {
    $.validator.messages.required = lang.required;
    $.validator.messages.email = lang.email;
    $.validator.messages.accept = lang.accept;
}

function checkEmail(email){
    var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return pattern.test(email);
}

(function( $ ){

  $.fn.maxHeight = function() {

    var max = 0;

    this.each(function() {
      max = Math.max( max, $(this).height() );
    });

    return max;
  };
})( jQuery );

(function( $ ){

  $.fn.sameHeight = function() {
    var max = 0;
    this.each(function() {
      max = Math.max( max, $(this).height() );
    });
    this.height(max);
    return max;
  };
})( jQuery );

(function($){
    $.fn.centerX = function () {
        return this.each(function() {
            var left = ($(this).parent().parent().width() - $(this).outerWidth()) / 2;
            $(this).css({
                marginLeft: left+'px'
                });
        });
    }
})(jQuery);
