/**
 * @author ANtek
 */
$.ajaxSetup({
    contentType: "application/x-www-form-urlencoded; charset=windows-1250"
});
var wordDiscount = false;
$(document).ready(function(){
    var required = "To pole jest wymagane";
    var evt = $.browser.msie ? "click" : "change";
    var doValidacji = {
        rules: {
            kontakt_email: {
                required: true,
                email: true
            },
            faktura_pelna_nazwa: {
                required: true,
                minlength: 2
            },
            faktura_adres: {
                required: true,
                minlength: 5
            },
            faktura_miejscowosc: {
                required: true,
                minlength: 3
            },
            faktura_kod_pocztowy: {
                required: true,
                postCode: true
            },
            faktura_nip: {
                required: true,
                nip: true
            },
            kontakt_imie: {
                required: true,
                minlength: 2
            },
            kontakt_nazwisko: {
                required: true,
                minlength: 2
            },
            kontakt_telefon: {
                required: true,
                minlength: 9
            }
        },
        messages: {
            kontakt_email: {
                required: "To pole jest wymagane",
                email: "Proszę podać właściwy email"
            },
            faktura_pelna_nazwa: {
                required: "To pole jest wymagane",
                minlength: "Proszę podać właściwą nazwę!"
            },
            faktura_adres: {
                required: "To pole jest wymagane",
                minlength: "Proszę podać właściwy adres!"
            },
            faktura_miejscowosc: {
                required: "To pole jest wymagane",
                minlength: "Proszę podać właściwą miejscowość!"
            },
            faktura_kod_pocztowy: {
                required: "To pole jest wymagane",
                postCode: "Proszę podać właściwy kod pocztowy"
            },
            faktura_nip: {
                required: "To pole jest wymagane",
                nip: "Proszę podać właściwy nip"
            },
            kontakt_imie: {
                required: "To pole jest wymagane",
                minlength: "Proszę podać właściwe imię!"
            },
            kontakt_nazwisko: {
                required: "To pole jest wymagane",
                minlength: "Proszę podać właściwe nazwisko!"
            },
            kontakt_telefon: {
                required: "Pole wymagane ze względu na obsługę kurierską",
                minlength: "Proszę podać właściwy numer telefonu!"
            }
        }
    };
				
    var adres_wysylkowy_var = function() {
        $("#wysylka_adresat").rules("add", {
            required: true,
            minlength: 3,
            messages: {
                required: "To pole jest wymagane",
                minlength: "Proszę podać właściwego adresata!"
            }
        });
        $("#wysylka_adres").rules("add", {
            required: true,
            minlength: 5,
            messages: {
                required: "To pole jest wymagane",
                minlength: "Proszę podać właściwy adres!"
            }
        });
        $("#wysylka_kod_pocztowy").rules("add", {
            required: true,
            postCode: true,
            messages: {
                required: "To pole jest wymagane",
                postCode: "Proszę podać właściwego adresata!"
            }
        });
        $("#wysylka_miejscowosc").rules("add", {
            required: true,
            minlength: 3,
            messages: {
                required: "To pole jest wymagane",
                minlength: "Proszę podać właściwą miejscowość!"
            }
        });

    };
								
    if(($("#dodatki_2:checked").val() != null || $("#dodatki_3:checked").val() != null) && ($("#wersja_programu_1:checked").val() != null || $("#wersja_programu_2:checked").val() != null)) {
        $(".dodatki_wersja_ograniczona").show();
        $("#tr_dodatek_id_4").show();
    }
    	
    $(".add").click(function () {
        var index = $(this).attr("title");
        var selektor = "#programy_au_" + index + " input";
        $(selektor).attr("value", zwrocZmienionaLiczbe(parseInt($(selektor).attr("value")), "add"));
    });
    $(".sub").click(function () {
        var index = $(this).attr("title");
        var selektor = "#programy_au_" + index + " input";
    			
        //    		$(selektor).attr("value", math.abs(parseInt($(selektor).attr("value")) - 1));
        $(selektor).attr("value", zwrocZmienionaLiczbe(parseInt($(selektor).attr("value")), "sub"));
    });
    if($("#adres_inny_wysylkowy:checked").val() != null) {
        $("#order_firstStep_sam").validate(doValidacji);
        $("#hiddenBox").show(1, adres_wysylkowy_var);
    		
        $("#wysylka_adresat input").attr("class","required");
    }
    $("#adres_inny_wysylkowy").bind(evt, function () {
        $("#order_firstStep_sam").validate(doValidacji);
        $("#hiddenBox").slideDown("normal",adres_wysylkowy_var);
    });
    $("#adres_wysylkowy").bind(evt, function () {
        $("#order_firstStep_sam").validate(doValidacji);
        $("#hiddenBox input").attr("value", "");
        $("#hiddenBox").slideUp("normal");
        $("#wysylka_adresat").rules("remove");
        $("#wysylka_adres").rules("remove");
        $("#wysylka_kod_pocztowy").rules("remove");
        $("#wysylka_miejscowosc").rules("remove");
    });
    if($("#wersja_programu_0:checked").val() != null) {
        $("#tr_dodatek_id_3").hide();
        $("#tr_dodatek_id_2").show();
    } else {
        $("#tr_dodatek_id_3").show();
        $("#tr_dodatek_id_2").hide();
    }
    $("#promo_1").bind(evt, function() {
        $("#promo_2").removeAttr("checked");
    });
    $("#promo_2").bind(evt, function() {
        $("#promo_1").removeAttr("checked");
    });
		
    $("input.number").change(function() {
        var value_num = $(this).attr("value");
        if(!isNaN(Number(value_num))) {
            $(this).attr("value", value_num);
        } else {
            $(this).attr("value", 0);
        }
    });
		
    /*
     * Formy płatnosci
     *
     */
    $('#formy_platnosci-rozwin a').toggle(
        function() {
            $('#formy_platnosci .float_left_inner').show();
            $(this).text('Zwiń Formy płatności');
        },
        function() {
            $('#formy_platnosci .float_left_inner').hide();
            $('#formy_platnosci .selected').show();
            $(this).text('Pokaż Formy płatności');
        }
    );
    $('#formy_platnosci-limited .float_left_inner').live('click', function() {
        $(this).find('input').attr('checked','checked');

        $('#formy_platnosci-limited .float_left_inner').removeClass('selected');
        $(this).addClass('selected');

        setOpisPlatnosci();
    });
    $('#formy_platnosci .selected').show();
    // Platnosci
    var platnosc_1 = "<strong>Pobranie.</strong>  Płatność gotówką u kuriera przy odbiorze. Realizacja zamówienia w ciągu 1-2 dni.";
    var platnosc_2 = "<strong>Przelew.</strong>  W końcowym etapie zamówienia zostanie wyświetlona faktura proforma z numerem konta i należną kwotą. Realizacja zamówienia nastąpi po wpłynięciu należności na nasze konto.";
    var platnosc_3 = "<strong>Płatność kartą.</strong> Po zakończeniu procedury zamawiania zostaniesz przełączony do operatora DotPay.pl obsługującego płatności kartami poprzez internet. Połączenie będzie szyfrowane. Dane o karcie zostaną przekazane tylko do tego operatora i nie docierają do naszej firmy. Realizacja zamówienia w ciągu 1-2 dni.";
    var platnosc_4 = "<strong>Płatność mTransfer.</strong> Po zakończeniu procedury zamawiania zostaniesz przełączony do systemu mBank-u obsługującego płatność mTransfer. Połączenie będzie szyfrowane. Realizacja zamówienia w ciągu 1-2 dni.";
    var platnosc_6 = "<strong>Platnosci.pl.</strong> Po zakończeniu procedury zamawiania zostaniesz przełączony do systemu PLATNOSCI.pl, a następnie do interfejsu płatniczego swojego banku. Połączenie będzie szyfrowane. Realizacja zamówienia w ciągu 1-2 dni.";
    if($("#customer-2:checked").val() != null) {
        var main_check = true;
    }
    setOpisPlatnosci();
    function setOpisPlatnosci() {
        if($("#platnosc_1:checked").val() != null) {
            $("#platnosc_opis").html(platnosc_1);
            $("#platnosc_opis").show();
            updateCeny();
            $("#infoDiscountMtrans").hide("fast");
        } else if($("#platnosc_2:checked").val() != null) {
            $("#platnosc_opis").html(platnosc_2);
            $("#platnosc_opis").show();
            updateCeny();
            $("#infoDiscountMtrans").hide("fast");
        } else if($("#platnosc_3:checked").val() != null) {
            $("#platnosc_opis").html(platnosc_3);
            $("#platnosc_opis").show();
            updateCeny();
            $("#infoDiscountMtrans").hide("fast");
        } else if($("#platnosc_5:checked").val() != null) {
            $("#platnosc_opis").html(platnosc_4);
            $("#platnosc_opis").show();
            updateCeny();
            $("#infoDiscountMtrans").show("fast");
        } else if($("#platnosc_6:checked").val() != null) {
            $("#platnosc_opis").html(platnosc_6);
            $("#platnosc_opis").show();
            updateCeny();
        }
    }
    if($("#platnosc_1:checked").val() != null) {
        $("#platnosc_opis").html(platnosc_1);
        zmianaCen(false);
        $("#infoDiscountMtrans").hide("fast");
    } else if($("#platnosc_2:checked").val() != null) {
        $("#platnosc_opis").html(platnosc_2);
        zmianaCen(false);
        $("#infoDiscountMtrans").hide("fast");
    } else if($("#platnosc_3:checked").val() != null) {
        $("#platnosc_opis").html(platnosc_3);
        zmianaCen(false);
        $("#infoDiscountMtrans").hide("fast");
    } else if($("#platnosc_5:checked").val() != null) {
        $("#platnosc_opis").html(platnosc_4);
        zmianaCen(true);
    } else if($("#platnosc_6:checked").val() != null) {
        $("#platnosc_opis").html(platnosc_6);
        zmianaCen(true);
    }
    $("#platnosc_1").bind(evt, function() {
        $("#platnosc_opis").html(platnosc_1);
        zmianaCen(false);
        $("#infoDiscountMtrans").hide("fast");
    });
    $("#platnosc_2").bind(evt, function() {
        $("#platnosc_opis").html(platnosc_2);
        zmianaCen(false);
        $("#infoDiscountMtrans").hide("fast");
    });
    $("#platnosc_3").bind(evt, function() {
        $("#platnosc_opis").html(platnosc_3);
        zmianaCen(false);
        $("#infoDiscountMtrans").hide("fast");
    });
    $("#platnosc_5").bind(evt, function() {
        $("#platnosc_opis").html(platnosc_4);
        zmianaCen(true);
        $("#infoDiscountMtrans").show("fast");
    });
 $("#platnosc_6").bind(evt, function() {
        $("#platnosc_opis").html(platnosc_6);
        zmianaCen(true);
        $("#infoDiscountMtrans").show("fast");
    });
    // end platnosci

    $(".inline_dodatki input").bind(evt, function() {
        if($("#wersja_programu_0:checked").val() != null) {
            $("#tr_dodatek_id_3").hide();
            $("#tr_dodatek_id_2").show();
            $("#tr_dodatek_id_3 input").removeAttr("checked");
        } else {
            $("#tr_dodatek_id_3").show();
            $("#tr_dodatek_id_2").hide();
            $("#tr_dodatek_id_2 input").removeAttr("checked");
        }
        if(($("#dodatki_2:checked").val() != null || $("#dodatki_3:checked").val() != null) && ($("#wersja_programu_1:checked").val() != null || $("#wersja_programu_2:checked").val() != null)) {
            $(".dodatki_wersja_ograniczona").slideDown("normal");
            $("#dodatki_opis input").attr("class","required");
            $("#tr_dodatek_id_4").show();
            $("#dodatki_4").attr("checked","checked");
        } else {
            $(".dodatki_wersja_ograniczona").slideUp("normal");
            $("#dodatki_opis input").removeAttr("class");
            $("#tr_dodatek_id_4").hide();
            $("#dodatki_4").removeAttr("checked");
        }
    });


		
    //Validation Step 1
    //		$("#order_firstStep").validate();

    $("#dalej_st1").click( function () {
        $("#order_firstStep_sam").validate(doValidacji);
    });

    $('#alert').jqm({
        overlay: 0,
        modal: true,
        trigger: false
    });
		
    // trigger an alert whenever links of class alert are pressed.
    $('a.alert').click(function() {
        alert('You Have triggered an alert!');
        return false;
    });
    $('#promos h3').toggle(
        function( ) {
            $(this).parent().find('.tresc').slideDown(100);
            $(this).parent().find('.rozwin a').text('zwiń');
        },
        function( ) {
            $(this).parent().find('.tresc').slideUp(100);
            $(this).parent().find('.rozwin a').text('rozwiń');
        }
        );
    $('.rozwin').toggle(
        function( ) {
            $(this).parent().find('.tresc').slideDown(100);
            $(this).parent().find('.rozwin a').text('zwiń');
        },
        function( ) {
            $(this).parent().find('.tresc').slideUp(100);
            $(this).parent().find('.rozwin a').text('rozwiń');
        }
        );
    if ( $('.hasloPromoCd').length > 0 ) {
        if ( $('.hasloPromoCd input').attr('value').length > 0) {
            $('.hasloPromoCd').parent().show(1);
            sprawdzKupon_wordCd();
        }
    }
    $(".hasloPromoCd .kodButton").click(function() {
        var kod = $('.hasloPromoCd .inputBox input').attr('value');
        if ( kod.length > 0 ) {
            sprawdzKupon_wordCd();
        } else {
            wordDiscount = false;
        }
    });
    $('.hasloPromoCd .inputBox input').change( function() {
        sprawdzKupon_wordCd();
    });
    function sprawdzKupon_wordCd() {
        $.ajax({
            type: "POST",
            url: "helpers/promoKodWordCdValidator.php",
            data: "code=" + $('.hasloPromoCd input').attr('value'),
            success: function(msg){
                switch( msg ) {
                    case '0' : {
                        $('#hasloInfoBoxCd').html('nie podano kodu');
                    //$('#kodInfoBox').slideDown(300).delay(800).fadeIn(400);
                    }
                    break;
                    case '1' : {
                        $('#hasloInfoBoxCd').html('Podany kod jest błędny');
                        $('#hasloInfoBoxCd').slideDown(300);
                        setTimeout("$('#hasloInfoBoxCd').slideUp(400)", 4500);
                        $('#hasloInfoBoxCd input').attr('class','error');
                        setTimeout("$('#hasloInfoBoxCd input').removeAttr('class')", 4500);
                        wordDiscount = false;
                        updateCeny();
                    }
                    break;
                    case '3' : {
                        $('#hasloInfoBoxCd').html('Kod jest poprawny.');
                        $('#hasloInfoBoxCd').slideDown(300);
                        setTimeout("$('#hasloInfoBoxCd').slideUp(400)", 4500);
                        $('#hasloInfoBoxCd input').attr('class','positive');
                        setTimeout("$('#hasloInfoBoxCd input').removeAttr('class')", 4500);
                        $('#hasloInfoBoxCd').attr('class','positive');
                        setTimeout("$('#hasloInfoBoxCd').removeAttr('class')", 4500);
                        wordDiscount = true;
                        updateCeny();
                    }
                    break;
                }
            // document.write( "Data Saved: " + msg );
            }
        });
    }
					
});
 
 
 
function alert(msg) {
    $('#alert')
    .jqmShow()
    .find('div.jqmAlertContent')
    .html(msg);
}
/* Overriding Javascript's Confirm Dialog */

// NOTE; A callback must be passed. It is executed on "cotinue". 
//  This differs from the standard confirm() function, which returns
//   only true or false!

// If the callback is a string, it will be considered a "URL", and
//  followed.

// If the callback is a function, it will be executed.

function zmianaCen(zm) {
    updateCeny();
//    var tmp;
//    for(var i=0;i<1;++i) {
//        if ((parseFloat($("#prod_" + i + " .amount").text()) > parseFloat($("#prod_" + i + " .tmp_price").attr("title"))) && zm == true) {
//            tmp = $("#prod_" + i + " .amount").text();
//            $("#prod_" + i + " .amount").text($("#prod_" + i + " .tmp_price").attr("title"));
//            $("#prod_" + i + " .tmp_price").attr("title",tmp);
//
//        } else if ((parseFloat($("#prod_" + i + " .amount").text()) < parseFloat($("#prod_" + i + " .tmp_price").attr("title"))) && zm == false) {
//            tmp = $("#prod_" + i + " .amount").text();
//            $("#prod_" + i + " .amount").text($("#prod_" + i + " .tmp_price").attr("title"));
//            $("#prod_" + i + " .tmp_price").attr("title",tmp);
//        }
//    }
}
function updateCeny( ) {
    var tmp;
    for(var i=0;i<3;++i) {

        if ( wordDiscount ) {
            tmp = programy[i];
            $("#prod_" + i + " .price").html( '<span class="old_price" title="Poprzednia cena: '+ tmp +' zł.">'+ tmp +' zł. </span><span class="amount">'+ countDiscount( tmp ) + '</span> zł. <span class="light">NETTO</span><div class="tmp_price" title="'+ tmp +'"/>');
        } else {
            $("#prod_" + i + " .price").html('<span class="amount">'+ programy[i] +'</span> zł. <span class="light">NETTO</span>');

        }

    }
}
function countDiscount( price ) {
    var znizka = 0;

    if ( wordDiscount ) {
        znizka += discount_word;
    }
    return Math.round( (price - price * znizka)*100) / 100 + '0';
}
function confirm(msg,callback) {
    $('#confirm')
    .jqmShow()
    .find('p.jqmConfirmMsg')
    .html(msg)
    .end()
    .find(':submit:visible')
    .click(function(){
        if(this.value == 'zakończ')
            (typeof callback == 'string') ?
            window.location.href = callback :
            document.last_step.submit();
        $('#confirm').jqmHide();
    });
}


$().ready(function() {
    $('#confirm').jqm({
        overlay: 88,
        modal: true,
        trigger: false
    });
  
    // trigger a confirm whenever links of class alert are pressed.
    $('.confirm').click(function() {
        confirm('Jeżeli chcesz jeszcze coś poprawić lub uzupełnić kliknij wróć, jeżeli wszystko jest w porządku, zakończ zamówienie.', 1);
        return false;
    });
});

// End of  Overriding Javascript's Confirm Dialog
 

function zwrocZmienionaLiczbe(liczba, dzialanie) {
    if (isNaN(liczba)) {
        return 0;
    }
    switch(dzialanie) {
        case 'add' : {
            if(liczba < 99) {
                return ++liczba;
            } else {
                return liczba;
            }
        }
        break;
        case 'sub' : {
            if(liczba > 0) {
                return --liczba;
            } else {
                return liczba;
            }
        }
        break;
    }
    return 0;
}
function print_r(theObj){
    if(theObj.constructor == Array ||
        theObj.constructor == Object){
        document.write("<ul>")
        for(var p in theObj){
            if(theObj[p].constructor == Array||
                theObj[p].constructor == Object){
                document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
                document.write("<ul>")
                print_r(theObj[p]);
                document.write("</ul>")
            } else {
                document.write("<li>["+p+"] => "+theObj[p]+"</li>");
            }
        }
        document.write("</ul>")
    }
}

