/* use to load functions after loading page - jquery util*/
var lang = $('meta[name=language]').attr('content');

$(document).ready(function() {
    
    $("#pageflip").hover(function() {
        $("#pageflip img , .msg_block").stop()
        .animate({
            width: '400px',
            height: '410px'
        }, 500);
    } , function() {
        $("#pageflip img").stop()
        .animate({
            width: '95px',
            height: '99px'
        }, 220);
        $(".msg_block").stop()
        .animate({
            width: '94px',
            height: '96px'
        }, 200);
    });

    //$('a[rel*=facebox], form[rel*=facebox]').facebox();

    $(this).bind("contextmenu", function(e) {
        //e.preventDefault();
        });
    $('.jqzoom').jqueryzoom( {
        xzoom: 200, //zooming div default width(default width value is 200)
        yzoom: 250, //zooming div default width(default height value is 200)
        offset: 10, //zooming div default offset(default offset value is 10)
        position: "right" //zooming div position(default position value is "right")	
    }
    );
    $('a.tooltip').tooltip({
        showURL: false,
        top: -5,
        left: 10
    }
    );
    $('input.submit_search_'+lang).tooltip({
        showURL: false,
        top: -5,
        left: 10
    }
    );
    var lang = $('meta[name=language]').attr('content');
    $("div.topButton img").not("[src*='hover']").hover(
        function() {
            var image = $(this);
            if(image.attr('src')) {
                image.attr('src', 'images/index/button_'+image.attr('name')+'_hover_'+lang+'.gif');
            }
        },
        function() {
            var image = $(this);
            image.attr('src', 'images/index/button_'+image.attr('name')+'_'+lang+'.gif');
        }
        );
	
    //runs slide shows
    MySlideShow2();
    $('#MySlideshow').slideshow(
    {
        width:488,      // width in px
        height:625,     // height in px
        index:0,        // start from frame number N
        time:3000,      // time out beetwen slides
        title:false,     // show title
        titleshow:false,// always show title
        callback:null,  // callback function - call when slide changed - receive index and label
        panel:true,     // show controls panel
        play:true,     // play slideshow
        loop:true,      // looping
        effect:'fade',  // aviable fade, scrollUp/Down/Left/Right, zoom, zoomFade, growX, growY
        effecttime:4000,// aviable fast,slow,normal and any valid fx speed value
        filter:false,    // remove <br/>, empty <div>, <p> and other stuff
        nextclick:false,      // bind content click next slide
        playclick:false,      // bind content click play/stop
        playhover:false,      // bind content hover play/stop
        playhoverr:false,     // bind content hover stop/play (reverse of playhover)
        playframe:false,       // show frame "Play Now!"
        loadframe:true,       // show frame with "loading"
        fullscreen:false,     // in full window size
        imgresize:false,      // resize image to slideshow window
        imgzoom:true,         // zoom image to slideshow window (for smaller side)
        imgcenter:true,       // set image to center
        imgajax:true,         // load images from links
        imglink:true,         // go to external link by click
        linkajax:false,       // load html from links

        controls :{         // show/hide controls elements
            'hide':false,    // show controls bar on mouse hover
            'first':true,   // goto first frame
            'prev':true,    // goto previouse frame (if it first go to last)
            'play':true,    // play slideshow
            'next':true,    // goto next frame (if it last go to first)
            'last':true,    // goto last frame
            'help':false,    // show help message
            'counter':true  // show slide counter
        }
    });
    $('#dialog').dialog({
        autoOpen: false,
        width: 503,
        height: 300,
        modal: true
    });
    $('#newsletter, #othersize').click(function(){
            $('div#dialog').html('');
            $('div#dialog').dialog({title: ''});
            $('div#dialog').dialog('open');
            $('div#dialog').dialog(
                'option', {width: 520, height: 400, position: ['center', 'middle']}
            );
            $.ajax({
                    url: $(this).attr('href'),
                    success: function(xml, msg) {
                        $('div#dialog').html(xml);
                    }
            });
            return false;
        });
    
    
    $('#przymierzalnia, .leftZakupy').click(function(){
            $('div#dialog').html('');
            $('div#dialog').dialog('open');
            $('div#dialog').dialog(
                'option', {width: 730, height: 700, position: ['center', 100]}
            );
            $.ajax({
                    url: $(this).attr('href'),
                    success: function(xml, msg) {
                        $('div#dialog').html(xml);
                    }
            });
            return false;
        });
    
    //formularz zamówienia / profil - paragon czy faktura
    $("input[name=bill_type]").bind('click change', function(){
        checkBillType();
    });
    checkBillType();
    
    //formularz zgłoszenia do pp 
    $("input[name=bill_type2]").bind('click change', function(){
        checkBillType2();
    });
    checkBillType2();
}
);

function updatebaner(url) {
    var type = $('select#baner-type option:selected').val();
    if(type == 'image') {
        $('#row-size, #row-topic, #row-border').removeClass('displayNone');
        $('#baner-code').addClass('displayNone');
        $('#baner-preview img').css('max-width', '460px');
        $('#baner-preview img').css('width', '');
        $('#baner-preview img').css('height', '');

        var category = '';
        var size = '';
        if($('select#baner-category option:selected').val() != '0') {
            category = $('select#baner-category option:selected').val();
        }
        if($('select#baner-size option:selected').val() != '') {
            size = $('select#baner-size option:selected').val();
        }

        var newurl = url+$('select#baner-site option:selected').val();
        $('#baner-preview div#baner-image a').attr('href', newurl);

        var src = 'http://www.sisi.pl/images/index/banery-program/'+size+category+'.jpg';
        $('img#baner-img').attr('src',src);
        $('#baner-preview div#baner-txt').addClass('displayNone');
        $('#baner-preview div#baner-image').removeClass('displayNone');
    }
    else if(type == 'txt') {
        $('#row-size, #row-topic, #row-border').addClass('displayNone');
        var newurl = url+$('select#baner-site option:selected').val();
        $('#baner-preview div#baner-txt a').attr('href', newurl);
        $('#baner-preview div#baner-image').addClass('displayNone');
        $('#baner-preview div#baner-txt').removeClass('displayNone');
    }
    $('#baner-code').addClass('displayNone');
    $('fieldset#baner-preview').removeClass('displayNone');
}

function getbanercode() {
    var type = $('select#baner-type option:selected').val();
    if(type == 'image') {
        var width = '';
        var height = '';
        if($('select#baner-size option:selected').val() != '') {
            var sizes = $('select#baner-size option:selected').val().split("x");
            width = sizes[0];
            height = sizes[1];
        }
        $('#baner-preview img').css('max-width', '');

        $('#baner-preview img').css('width', width);
        $('#baner-preview img').css('height', height);

        $('#baner-html-code').html($('#baner-preview div#baner-image').html()); 
    }
    else if(type == 'txt') {
        
        $('#baner-html-code').html($('#baner-preview div#baner-txt').html()); 
    }
    $('#baner-preview').addClass('displayNone');
    $('#baner-code').removeClass('displayNone');
    
}

function scrollWin(target){
    $('html, body').animate({scrollTop: $("#"+target).offset().top}, 500);
}

function galleryBig(anchor) {
    $('img#bigImage').hide();
    $('ul.gallery_demo li').removeClass('active');
    if($(anchor).attr('href') !='') {
        $(anchor).parent().addClass('active');
        $('img#bigImage').attr('src', $(anchor).attr('href')).show();
    }
}

function checkBillType() {
    var obj = $("input[name=bill_type]:checked");
    //faktura
    if($(obj).val() == 'invoice') {
        $('input[name=nip]').removeAttr('readonly').parent().parent().removeClass('displayNone');
    }
    //paragon
    else  {
        $('input[name=nip]').attr('readonly', 'readonly').parent().parent().addClass('displayNone');
    }
}

function checkBillType2() {
    var obj = $("input[name=bill_type2]:checked");
    //faktura
    if($(obj).val() == 'invoice') {
        $('input[name=nip]').removeAttr('readonly').parent().parent().removeClass('displayNone');
        $('input[name=company]').removeAttr('readonly').parent().parent().removeClass('displayNone');
    }
    //paragon
    else  {
        $('input[name=nip]').attr('readonly', 'readonly').parent().parent().addClass('displayNone');
        $('input[name=company]').attr('readonly', 'readonly').parent().parent().addClass('displayNone');
    }
}

function addComment() {
    
    if($('div#productAddComment').hasClass('displayNone')) {
        $('div#productAddComment').removeClass('displayNone');
    } else {
        $('div#productAddComment').addClass('displayNone');
    }
}

function un_block(obj) {
    var iter = 0;
    var input = $(obj).parents().parents().parents().children('div.labCont:eq(2)').children('div.lab2').children('input');
    $(obj).children('select option:selected').each(function(i) {
        if($(this).val() == 'Y') {
            input.attr('price', input.val());
            iter = iter + 1;
        }
        else {
            input.attr('disabled','disabled');
        }
        if(iter != 0) {
            input.removeAttr('disabled');
        }
        else {
            input.val(input.attr('price'));
        }
    });
}

function showDedicationOptions() {
    if($('select#select_dedication').val() == 'Tak') {
        $('div#select_options').slideDown();
    }
    else {
        $('div#select_options').slideUp();
    }
}


function swapImage(newUrl, altUrl) {
    $('img#imageProduct').attr('src', newUrl);
    $('img#imageProduct').attr('jqimg', altUrl);
}

function checkVarieties(urlToLoad) {
    $('select#rozmiar').attr("disabled","disabled");
    $('select#kolor').attr("disabled","disabled");
    $('div#produktWarianty').load(urlToLoad,
        {
            rozmiar: $('#rozmiar').val(),
            kolor: $('#kolor').val()
        },
        function(responseText) {
            var rozm = $('select#rozmiar').val();
            var kol = $('select#kolor').val();
            $('input#size').val(rozm);
            $('input#colour').val(kol);

            $('select#rozmiar').removeAttr('disabled');
            $('select#kolor').removeAttr('disabled');
        }
    );
	
}

/**
 * funkcja sprawdzajaca stan magazynowy danego produktu
 * 
 */

function checkAvability(urlToLoad) {
    $.ajax( {
        url: urlToLoad,
        data: {size: $('select#rozmiar').val(), colour: $('input#colour').val()},
        type: "POST",
        success: function(response) {
            // explode danych
            aExplode = response.split(','); 
            iAvaliable = parseInt(aExplode[0]); // ilosc dost. szt. w magazynie
            sDostepnosc = aExplode[1]; // czas w jaki produkt bedzie dost.
            sDostepnosc = sDostepnosc.replace('dni', 'days');
            sTimeAvaliable = $('#inputDostepnosc').val();
            
            
            if (iAvaliable > 0) {
                if (parseInt($('#temp').length) < 1) {
                    $('#detailsSep').after('<div id="temp"><p class="data">'+sTimeAvaliable+': '+iAvaliable+' products</p><br /><p class="data">More in about '+sDostepnosc+'</p><div id="test" class="separator_gray"></div></div>'); 
                    $('#temp').hide();
                    $('#temp').slideDown();  
                    $('#detailsLink').html('[hide]');
                } else {                    
                    $('#temp').slideUp('fast');
                    $('#temp').remove();
                    $('#detailsLink').html('[details]');
                }
            }
        }
    });    
}

function emailnotify(varid, address, info) {
    if(!varid) {
        alert('Error varid');
        return false;
    }
    if(!address || address == 'email') {
        alert(info);
        return false;
    }
    var url = 'index/index/varietynotifier/varid/'+varid+'/address/'+address+'/';
    window.location = url;
}

function checkAddCart(kom1, kom2, kom3, kom4, kom5) {
    if($('#inputDostepnosc').val() == 'wybierz wariant' || $('#inputDostepnosc').val() == 'välj alternativ') {
        alert(kom1);
        return false;
    }
    else if($('#inputDostepnosc').val() == 'email') {
        alert(kom5);
        return false;
    }
    else if($('#inputDostepnosc').val().search('7') != -1 || $('#inputDostepnosc').val().search('14') != -1) {
        if(!confirm(kom2+' '+$('#inputDostepnosc').val()+' '+kom3)) {
            return false;
        }

    }
    else if($('#inputDostepnosc').val() == 'Brak' || $('#inputDostepnosc').val() == 'brak' || $('#inputDostepnosc').val() == 'niedostępny' || $('#inputDostepnosc').val() == 'niedostepny') {
        alert(kom4);
        return false;
    }
    $('form#add_to_cart').submit();
}

function makeAnOrder(newAction) {
    $('form#cartForm').attr({
        action: newAction
    });
    $('#cartForm').submit();
}

function showOther() {
    var country = $('select[name=country] option:selected');
    var country2 = $('select[name=country2] option:selected');
    var otherdata = $('input[name=otherData]');
    var disp = $('#sendData').css('display');
    if(disp == 'none') {
        $('#sendData').slideDown();
        $('#sendData').removeClass('displayNone');
        $('#otherData').val('Y');
        
    }
    else {
        $('#sendData').slideUp();
        $('#otherData').val('N');
    }
    checkCountryForm();
    //checks if selected klarna
    checkKlarna();
}

function loadcart(object, urlToLoad) {
    var divToLoad = $(object).parent('.date').parent('.userOrder').children('div:last');
    if(divToLoad.css('display') == 'block') {
        divToLoad.css('display', 'none');
    }
    else {
        divToLoad.css('display', 'block');
        divToLoad.html('Ładowanie danych...');
        divToLoad.load(urlToLoad);
    }
}

function windowOpen(url, width, height, scroll) {
    if(!scroll) {
        scroll = 'yes';
    }
    window.open(url, 'name', 'width='+width+',height='+height+',menubar=no,toolbar=no,scrollbars='+scroll);
}

function redirector(link, obj) {
    var url = link+'order_by/'+$(obj).val()+'/';
    window.location = url;	
}

function MySlideShow2(){
    $('div.mySlideShow').everyTime(7000, 'mySlideShow', function(obj){
        var indexToShow = 0;
        var nextIndex = 0;
        var aObjects = $(this).find('div.slide');
        var aActiveObj = $(this).find('div.active');
		
        if($(aActiveObj).length == 0) {
            $(aObjects[0]).addClass('active');
            indexToShow = 0;
        }
		
        //returns index of active class
        if(indexToShow != null) {
            aObjects.each(function(index){
                if($(aObjects[index]).hasClass('active')) {
                    indexToShow = index;
                }
                $(aObjects[index]).css('display', 'none');
            });
        }
		
        //checks index if last then next active is first one
        if(indexToShow == aObjects.length-1) {
            nextIndex = 0;
        }
        else {
            nextIndex = indexToShow + 1;
        }
        //shows and hides 
        $(aObjects[indexToShow]).removeClass('active').css('display', 'block');
        $(aObjects[nextIndex]).addClass('active');
		
		
    }, 0);
}

function MySlideShow() {
    //first 2 ale visible
    $('div.mySlideShow div.slide').each(function(index){
        if(index == 0) {
            $(this).css('display', 'block').css('float', 'left');
        }
        else if(index == 1) {
            $(this).css('display', 'block').css('float', 'right');
        }
    });
    $('div.mySlideShow').everyTime(7000, 'mySlideShow', function(obj){
        var indexToShow = 0;
        var nextIndex = 0;
        var aObjects = $(this).find('div.slide');
        var aActiveObj = $(this).find('div.active');
		
        if($(aActiveObj).length == 0) {
            $(aObjects[0]).addClass('active');
            indexToShow = 0;
        }
        //returns index of active class
        if(indexToShow != null) {
            aObjects.each(function(index){
                if($(aObjects[index]).hasClass('active')) {
                    indexToShow = index;
                }
                $(aObjects[index]).css('display', 'none');
            });
        }
        //checks index if last then next active is first one
        if(indexToShow == aObjects.length-1) {
            nextIndex = 0;
        }
        else {
            nextIndex = indexToShow + 1;
        }
        //shows and hides 
        $(aObjects[indexToShow]).removeClass('active').css('display', 'block').css('float', 'left');
        $(aObjects[nextIndex]).addClass('active').css('display', 'block').css('float', 'right');
    }, 0);
}

function checkCountryForm() {
    var country = $('select[name=country] option:selected');
    var country2 = $('select[name=country2] option:selected');
    var otherdata = $('input[name=otherData]');
    if(otherdata.val() == 'Y') {
        if(country2.val() != 'poland') {
            $('input[name=card_type][value=pobranie]').remove();
            $('span#pobranieTxt').hide();
            if(!$('input[name=card_type]:checked').val()) {
                $('input[name=card_type]:first').attr('checked', 'checked');
            }
        }
        else {
            if(!($('input[name=card_type][value=pobranie]').val() == 'pobranie')) {
                $('span#pobranieTxt').show().before('<input type="radio" value="pobranie" name="card_type" onclick="checkKlarna();">');
            }
            if(!$('input[name=card_type]:checked').val()) {
                $('input[name=card_type]:first').attr('checked', 'checked');
            }
        }
    }
    else {
        
        if(country.val() != 'poland') {
            $('input[name=card_type][value=pobranie]').remove();
            $('span#pobranieTxt').hide();
            if(!$('input[name=card_type]:checked').val()) {
                $('input[name=card_type]:first').attr('checked', 'checked');
            }
        }
        else {
            if(!($('input[name=card_type][value=pobranie]').val() == 'pobranie')) {
                $('span#pobranieTxt').show().before('<input type="radio" value="pobranie" name="card_type" onclick="checkKlarna();">');
            }
            if(!$('input[name=card_type]:checked').val()) {
                $('input[name=card_type]:first').attr('checked', 'checked');
            }
        }
    }
    checkKlarna();
}

function checkTelForm() {
    checkCountryForm();
    var input = $('input[name^="home_phone"]').val();
    if(input.length < 7 && $('select[name^=card_type]').val() == 'pobranie') {
        alert('Proszę wpisać poprawny nr telefonu');
        return false;
    }
    getAddressKlarna();
}

function checkKlarna() {
    if($('input[name^=card_type]:checked').val() == 'klarna') {
        //rodzaj rachunku FV
        $('input[name=bill_type][value=receipt]').attr('checked','checked');
        $('input[name=bill_type][value!=receipt]').attr('disabled','disabled');
        
        //jeśli klarna wymuszamy wysyłkę na szwecję
        $('select[name^=country] option:selected').removeAttr('selected');
        $('select[name^=country] option[value$=sweden]').attr('selected', 'selected');
        $('select[name^=country] option[value!=sweden]').attr('disabled', 'disabled');
        
        //dane do wysylki nie moga sie roznic od danych placacego
        $('#sendData').css('display', 'none');
        $('input#otherData').val('N');
        $('input[name^=otherButton]').attr('readonly','readonly').attr('checked', false);
        $('div#otherDataCont').hide();
        $('input[name=pesel]').parent().parent().show();
        //jesli szwecja dane tylko z klarny (getAddress)
        if($('select[name^=country] option:selected').val() == 'sweden') {
            $('input[name^=first_name],input[name^=last_name],input[name^=street],input[name^=address_1],input[name^=address_2],input[name^=postal_code],input[name^=city]').attr("readonly", "readonly").addClass('disabled');
            $('#infoKlarna').show();
        }
        else {
            $('input[name^=first_name],input[name^=last_name],input[name^=street],input[name^=address_1],input[name^=address_2],input[name^=postal_code],input[name^=city]').removeAttr("readonly").removeClass('disabled');
            $('#infoKlarna').hide();
        }
    }
    else {
        $('select[name^=country] option').removeAttr('disabled');
        $('input[name=bill_type]').removeAttr('disabled');
        $('input[name=pesel]').val('').parent().parent().hide();
        $('input[name^=first_name],input[name^=last_name],input[name^=street],input[name^=address_1],input[name^=address_2],input[name^=postal_code],input[name^=city]').removeAttr("readonly").removeClass('disabled');
        
        //przywracanie funkcji dla adresu do wysylki
        $('div#otherDataCont').show();
        $('input[name^=otherButton]').attr('readonly',false);
    }
    checkBillType();
}

function getAddressKlarna(nosubmit) {
    if(!nosubmit) var nosubmit = false;
    //tylko dla szwecji pobieraj dane
    if($('input[name^=card_type]:checked').val() == 'klarna' && $('select[name^=country] option:selected').val() == 'sweden') {
        $.ajax({
            url: $('base').attr('href')+"index/cart/checkKlarnaAddress",
            data: "bReturnJSON=true&pesel="+$('input[name^=pesel]').val(),
            type: "GET",
            dataType: "JSON",
            success: function(msg) {
                if(msg == 'nopno' || msg == '') {
                    $('form#orderDataForm').submit();
                }
                if(msg.indexOf("error code") != -1) {
                    alert(msg);
                    return false;
                }
                var data = jQuery.parseJSON(msg);
                $('input[name^=first_name]').val(data.first_name);
                $('input[name^=last_name]').val(data.last_name);
                $('input[name^=street]').val(data.street);
                $('input[name^=address_1]').val(data.address_1);
                $('input[name^=address_2]').val(data.address_2);
                $('input[name^=postal_code]').val(data.postal_code);
                $('input[name^=city]').val(data.city);
                
            },
            complete: function () {
                if(nosubmit == false) {
                    $('form#orderDataForm').submit();
                }
            }

        });
    }
    else {
        if(nosubmit == false) {
            $('form#orderDataForm').submit();
        }
    }
}
