$(document).ready(function(){    
    $('.size').click(function(){
        link = $(this).attr('href');
        $.getJSON(link, {}, function(response) {
            if(response.returner){
                $('#mini_cart #counter').html(response.counter);
                $('.adder').show();
            }
        });
        return false;
    });
    
    
    if($('.small_box').length>1) {
        $('.slider .small_box').hide();
        InOut( $('.slider .small_box:first') );
    } else {
        $('.small_box').fadeIn(500);
    }

    $('.privilage').click(function(){
        link = '/'+lang+'/profile/index/change-privilage/format/json';
        name = $(this).attr('name');

        if($(this).is(':checked')){
            state = 1;
        }
        else{
            state = 0;
        }
        $.getJSON(link, {
            privilage_id: name,
            portal: name[1],
            state: state
        }, function() {});
    });

    $('.design_table tbody tr:even').addClass('odd');

    $('input[name="delivery_type_id"]').click(function() {
        value = $(this).val();
        if(value==4) {
            $('input[name="payment_type_id"]').val(6);
            $('#ptype-6').attr("checked","checked");
        } else {
            if($('#ptype-6:checked')) {
                $('#ptype-6').attr('checked','');
                $('#ptype-1').attr('checked','checked');
            }
        }
    })

    $('input[name="payment_type_id"]').click(function() {
        value =  $('input[name="delivery_type_id"]:checked').val();
        if(value==4) {
            $('input[name="payment_type_id"]').val(6);
            $('#ptype-6').attr("checked","checked");
            return false;
        }
    })

    $('#ptype-6').click(function() {
        value = $('input[name="delivery_type_id"]:checked').val();
        if(value!=4) {
            alert("Płatność przy odbiorze możliwa jest tylko przy dostawie w opcji za pobraniem");
            return false;
        }
    })

    $('.del-product-alert').live('click', function() {
        if(!confirm('Czy na pewno usunąć wybrany produkt?')) {
            return false;
        }
    });

    $('.close').click(function(){
        $(this).parent().parent().parent().remove();
        return false;
    });

    $('.sizel a:first').click(function() {
        $(this).parent().children('ul').toggle();
        return false;
    });
    $('.sex a:first').click(function() {
        $(this).parent().children('ul').toggle();
        return false;
    });
    $('.popular a').click(function() {
        $(this).toggleClass('active');
    })
    $('.button_refresh').click(function() {
        $('.filter_list a').removeClass('active')
    } );

    $('.filter_size a').click(function() {
        wartosc = $(this).text();
        size_id = $(this).next('span').text();
        $('.sizel span').text(wartosc);
        $('.sizel a').addClass('active');
        $('.filter_size').hide();
        return true;
    })
    $('.filter_sex a').click(function() {
        wartosc = $(this).text();
        sex_id = $(this).next('span').text();
        $('.sex span').text(wartosc);
        $('.sex a').addClass('active');
        $('.filter_sex').hide();
        return true;
    })

    $('.close_a').click(function() {
        $('.adder').fadeOut();
        return false;
    })

    //koszyk index
    $('.quantity-input').each(function() {
        key = $(this).attr('id').split('-')[0];
        countPrices(key);
    });
    $('.quantity-input').change(function(){
        key = $(this).attr('id').split('-')[0];
        countPrices(key);
        return false;
    });

    //wybór faktury przy formularzu zamówienia
    $('#invoice_choice-1').click(function(){
        if($('#invoice_choice-1').attr('checked')){
            $('#invoice').show();
        }
    })
    $('#invoice_choice-0').click(function(){
        if($('#invoice_choice-0').attr('checked')){
            $('#invoice').hide();
        }
    })

    //wybór danych do wysyłki przy formularzu zamówienia
    $('#delivery_choice-1').click(function(){
        if($('#delivery_choice-1').attr('checked')){
            $('#delivery').show();
        }
    })
    $('#delivery_choice-0').click(function(){
        if($('#delivery_choice-0').attr('checked')){
            $('#delivery').hide();
        }
    })

    if($('#invoice_choice-1').attr('checked')){
        $('#invoice').show();
    }
    if($('#delivery_choice-1').attr('checked')){
        $('#delivery').show();
    }

    $('.product_picture_container').hover(function(){
        $(this).css('cursor','pointer');
    })
    $('.product_picture_container').click(function(){
        $('.magnifier').trigger('click');
    })

    $("#menu").children("li").hover(function() {
        $(this).children("ul").show();
        $(this).children('a.withchildren').addClass('active');
    }, function() {
        $(this).children("ul").hide();
        $(this).children('a.withchildren').removeClass('active');
    });

    
    if(lang=='en'){
        $search_val = "Product name...";
    }
    else{
        $search_val = "Nazwa produktu...";
    }
    if ( $("#product_name").val() == "" ) {
        $("#product_name").val($search_val);
    }
    $("#product_name").blur(function() {
        if( $(this).val() == "" ) $(this).val($search_val);
    });
    $("#product_name").focus(function() {
        if( $(this).val() == $search_val ) $(this).val("");
    });
    
    if(lang=='en')
        $code_val = "type a code";
    else
        $code_val = "wpisz kod kuponu";
    if ( $(".code_form #code").val() == "" ) {
        $(".code_form #code").val($code_val).css('color', '#EFEFEF');
    }
    $(".code_form #code").blur(function() {
        if( $(this).val() == "" ) $(this).val($code_val).css('color', '#EFEFEF');
    });
    $(".code_form #code").focus(function() {
        if( $(this).val() == $code_val ) $(this).val("").css('color', '#000000');
    });

    $('.change-lang').click(function(){
        var href = $(this).attr('href');
        var lang = href.replace('/', '');
        $.getJSON('/'+lang+'/default/index/save-language/format/json', {
            language: lang
        }, function(response) {
            if(response){
                window.location.href = href;
            }
        });
        return false;
    });

    $(".fancy, .magnifier").fancybox({
        'titleShow' : false,
        'transitionIn'	: 'elastic',
        'transitionOut'	: 'elastic'
    });
    $(".fancy-iframe").fancybox({
        'width' : '75%',
        'height' : '80%',
        'autoScale' : false,
        'titleShow' : false,
        'transitionIn'	: 'elastic',
        'transitionOut'	: 'elastic',
        'type' : 'iframe'
    });
    $(".fancy-size").fancybox({
        'width' : '80%',
        'height' : '80%',
        'autoScale' : false,
        'titleShow' : false,
        'transitionIn'	: 'elastic',
        'transitionOut'	: 'elastic',
        'type' : 'iframe'
    });

    $('#mce-EMAIL').click(function() {
        $(this).val('');
    })
    
    $('#follow').click(function() {
        but = $(this);
        if($(this).is(":checked")) {
            $.getJSON('/'+lang+'/default/comments/follow/f/1/format/json', {
                pattern_id: but.val()
            })
        } else {
            $.getJSON('/'+lang+'/default/comments/follow/f/0/format/json', {
                pattern_id: but.val()
            })
        }
    })
    
    $("#show_history").click(function() {
        $('.normal_comment').hide('slow');
        $('.history_comment').show('slow');
        $(this).parent().parent().children('li').removeClass('active');
        $(this).parent().addClass('active');
        return false;
    })
    
    $("#show_all_comments").click(function() {
        $('.normal_comment').show('slow');
        $('.history_comment').show('slow');
        $(this).parent().parent().children('li').removeClass('active');
        $(this).parent().addClass('active');
        return false;
    })
    
    $("#only_comments").click(function() {
        $('.history_comment').hide('slow');
        $('.normal_comment').show('slow');
        $(this).parent().parent().children('li').removeClass('active');
        $(this).parent().addClass('active');
        return false;
    })
});

//rounds the input number to the desired precision
//and returns the rounded number
function roundToPrecision(inputNum, desiredPrecision){
    var precisionGuide = Math.pow(10, desiredPrecision);
    return(Math.round(inputNum * precisionGuide) / precisionGuide);
}

//converts the input number into a string and adds zeroes
//until the desired precision is reached and then
//returns the new string
function toPrice(inputNum, desiredPrecision){
    if(desiredPrecision == undefined) desiredPrecision=2;
    inputNumRounded = roundToPrecision(inputNum, desiredPrecision)


    var beforeComma;
    var afterComma;
    var numString = inputNumRounded + "";

    comma = numString.search(/\./);
    if(comma == -1){
        beforeComma = numString;
        afterComma = "";
    }
    else{
        beforeComma = numString.substring(0,comma);
        afterComma = numString.substring(comma+1, numString.length);
    }
    while (afterComma.length < desiredPrecision) {
        afterComma += "0";
    }

    if(lang=='en'){
        return ('$'+beforeComma+'.'+afterComma);
    }
    else{
        return(beforeComma+','+afterComma+' zł');
    }
}

function countPrices(key){
    var price = fromPrice($('#'+key+'-price').val());
    var help = fromPrice($('#'+key+'-help').val());
    var quantity = parseInt($('#'+key+'-quantity').val());
    
    $('#'+key+'-sum').val(toPrice(price * quantity));
    $('#'+key+'-hsum').val(toPrice(help * quantity));
    countAllSum();
}

function countAllSum(){
    var allsum = 0
    $('.sum-input').each(function() {
        var partsum = $(this).val();
        allsum += fromPrice(partsum);
    });
    var allhelp = 0
    $('.help-input').each(function() {
        allhelp += fromPrice($(this).val());
    });
    $('#allsum').val(toPrice(allsum));
    $('#allhelp').text(toPrice(allhelp));
}

function fromPrice(str){
    str = str.replace('$','');
    str = str.replace('zł','');
    return parseFloat(str.replace(',','.'));
}

function nextSlide() {
    next = $('.slider div.visible').next('div.small_box');
    $('.slider div.visible').fadeOut(1200, function() {
        $(next).addClass('visible');
        $(this).removeClass('visible')
    } );
}

function InOut( elem )
{
    elem.delay()
    .fadeIn(2000)
    .delay(2000)
    .fadeOut( 
        function(){ 
            if(elem.next().length > 0)
            {
                InOut( elem.next() );
            }
            else
            {
                InOut( elem.siblings(':first'));
            }
                         
        }
        );
}

