$(document).ready(function(){
    $(".del").live('click', function() {
        link = $(this).attr('href');
        if(confirm('Czy na pewno usunąć wybrany element?')) {
            window.location = link
        }
        return false;
    });

    $(".delRow").live('click', function() {
        link = $(this).attr('href');
        if(confirm('Czy na pewno usunąć wybrany element?')) {
            $.post(link, {}, function(data) {})
            $(this).parent().parent().fadeOut('slow');
        }
        return false;
    });

    $(".delPicture").click(function() {
        link = $(this).attr('href');
        if(confirm('Czy na pewno usunąć wybrane zdjęcie?')) {
            $.post(link, {}, function(data) {});
            $(this).parent().fadeOut('slow');
        }
        return false;
    });

    //    $(".subcats").live('click', function() {
    //        link = $(this).attr('href');
    //
    //        $.post(link, {}, function(data) {
    //            $(".subcatsOdp").html(data)
    //        });
    //
    //        return false;
    //    });

    $('.sex').click(function() {
        $('.sex:checked').removeAttr('checked');
        $(this).attr('checked','checked');
        $(this).parent().parent().parent().children('li').removeClass('checked');
        $(this).parent().parent().addClass('checked');
        $('#models').html('');
        $('#models_attribs').html('');
        $.post('/index/sex-choice/format/html', {
            sex: $('input.sex:checked').val(),
            type_id: $('#type_id').val()
        }, function(data) {
            $('#models').html(data);
        });
    });
    
    $('.model').live('click', function() {
        $('.model:checked').removeAttr('checked');

        $(this).parent().parent().parent().children('li').removeClass('checked');
        $(this).parent().parent().addClass('checked');
        $(this).attr('checked','checked');
        model_id = $(this).val();

        $.post('/index/model-choice/format/html', {
            model_id: model_id
        }, function(data) {
            $('#models_attribs').html(data);
            model_price = parseMyFloat($('#price_'+model_id).html());
            $('#price').html(addZeroesToPrecision(model_price));
            sum_up();
        });
    });

    $('.color').live('click', function() {
        $('.color:checked').removeAttr('checked');

        $(this).parent().parent().parent().children('li').removeClass('checked');
        $(this).parent().parent().addClass('checked');
        $(this).attr('checked','checked');
    });

    $('.size').live('click', function() {
        $('.size:checked').removeAttr('checked');

        $(this).parent().parent().parent().children('li').removeClass('checked');
        $(this).parent().parent().addClass('checked');
        $(this).attr('checked','checked');
    });

    $('#step1_form #submit').click(function(){
        msg='';

        if($('.sex:checked').val()==null){
            msg += "Nie zaznaczono płci.\n";
        }
        
        if($.trim($('#models').text())!=''){
            if($('.model:checked').val()==null){
                msg += "Nie zaznaczono modelu.\n";
            }
        }

        if($.trim($('#models_attribs').text())!=''){
            if($('.size:checked').val()==null){
                msg += "Nie zaznaczono rozmiaru.\n";
            }
            if($('.color:checked').val()==null){
                msg += "Nie zaznaczono koloru.\n";
            }
        }
        
        if(msg!=''){
            alert(msg);
            return false;
        }
        else if($.trim($('#models').text())=='' || $.trim($('#models_attribs').text())==''){
            return false;
        }
    });

    $('#sessionPattern_file').hide();

    //    $('#quantity_input').click(function(){
    //        $('#step2_form #submit').removeAttr('disabled');
    //    });
    $('#step2_form #submit').click(function(){
        message = '';
        if($('#quantity_input').val()==''){
            message += 'Proszę wpisać wymaganą ilość produktów';
        }
        
        if($('.font:checked').html()!=null && $('#line1').val()==''){
            if(message!='') message += '\n';
            message += '\nWybrałeś czcionkę lecz nie wpisałeś linii napisu';
        }

        if($('.pattern:checked').html()==null && $('.font:checked').html()==null && $('#pattern_file').val() == undefined && $('#sessionPattern_file').html() == ''){
            if(!confirm("Czy na pewno chcesz kupić produkt bez żadnego wzoru?")){
                return false;
            }
            else{
                if(message!=''){
                    alert(message);
                    return false;
                }
            }
        }
        if(message!=''){
            alert(message);
            return false;
        }
    });

    $('.category').live('click', function() {
        href = $(this).attr('href');
        link = $(this);
        
        if(link.next().attr('class')=='sub'){
            link.next().remove();
            link.parent().removeClass('open');
            if($('#returned').length==0){
            }
            return false;
        }

        ul = link.parent().parent();
        if(ul.children('.open')){
            ul.children('.open').children('ul').remove();
            ul.children('.open').removeClass('open');
        }

        $.ajax({
            async: false,
            url: href,
            dataType: "html",
            success: function(response){
                link.after(response);
                link.parent().addClass('open');

//                link.parent().children('.sub_images').children().children('div').children('ul').children('li').children('a').first().addClass('AAAAAAAAAAAAAAA');
//                link.parent().children('.sub_images').children().children('.patterns_container').children('ul').first().children().first().children().first().addClass('active');
//                link.parent().children('sub_images').children().addClass('BLE');
//                ul:firstChild.addClass('active');
            }
        });
        return false;
    });

    $('.category_admin').live('click', function() {
        href = $(this).attr('href');
        link = $(this);

        if(link.parent().parent().next().attr('class')=='sub'){
            link.parent().parent().next().remove();
            link.parent().parent().removeClass('open');
            return false;
        }
        
        table = link.parent().parent().parent();
        if(table.children('.open').html()!=null){
            table.children('.open').next().remove();
            table.children('.open').removeClass('open');
        }

        $.ajax({
            async: false,
            url: href,
            dataType: "html",
            success: function(response){
                link.parent().parent().after(response);
                link.parent().parent().addClass('open');
            }
        });
        return false;
    });

    $('.color-change').live('click', function(){
       parent = $(this).parent();
       but = $(this);
       href = $(this).attr('href');
       $.ajax({
            async: false,
            url: href,
            dataType: "json",
            success: function(data){
                but.parent().parent().parent().prev('.mod-col-pats').children().hide();
                but.parent().parent().parent().prev('.mod-col-pats').children().removeClass('hide');
                $('#mcp_'+data.color_id).show();
                $('#palette').children().removeClass('active');
                parent.addClass('active');
            }
        });
        return false;
    });

    $('.cat-model').live('click', function(){
       arr = $(this).parent().parent().attr('id').split('_');
       pattern_id = arr[1];
       href = $(this).attr('href');
       $('#cat-mod-col-pats_'+pattern_id).html('');
       $('.cat-model').removeClass('active');
       $(this).addClass('active');
       $.ajax({
            async: false,
            url: href,
            dataType: "html",
            success: function(data){
                $('#cat-palette_'+pattern_id).html(data);
                $('#cat-palette_'+pattern_id+' :first.cat-color').trigger('click');
                
            }
        });
       
        return false;
    });

    $('.cat-color').live('click', function(){
       arr = $(this).parent().parent().attr('id').split('_');
       pattern_id = arr[1];
       href = $(this).attr('href');
       $.ajax({
            async: false,
            url: href,
            dataType: "html",
            success: function(data){
                $('#cat-mod-col-pats_'+pattern_id).html(data);
            }
        });
        return false;
    });

    $('#load_patterns').live('click', function(){
        if(!($(this).parent().hasClass('active'))){
            $(this).parent().parent().children('.active').removeClass('active');
            $(this).parent().addClass('active');
            $('#upload_pattern').hide();
            reset_price();
            reset_overprints_form();
            reset_pattern_file_form();
            $('#overprints').hide();
            $('#patterns').slideDown();
            $('#notices_container').show();
            $('.input_notice p').hide();
            $('.info_notice').hide();
            $('.input_notice .info_step1').show();
            $('#notices_container').removeClass('hide');
        }
        return false;
    });
    $('#load_upload_pattern').live('click', function(){
        if(!($(this).parent().hasClass('active'))){
            $(this).parent().parent().children('.active').removeClass('active');
            $(this).parent().addClass('active');
            $('#patterns').hide();
            reset_price();
            reset_overprints_form();
            reset_patterns_form();
            $('#overprints').hide();
            $('#upload_pattern').slideDown();
            $('#notices_container').show();
            $('.input_notice p').hide();
            $('.input_notice .info_step2').show();

            $('.info_notice').show();
            $('#notices_container').removeClass('hide');
        }
        return false;
    });
    $('#load_overprints').live('click', function(){
        if(!($(this).parent().hasClass('active'))){
            $(this).parent().parent().children('.active').removeClass('active');
            $(this).parent().addClass('active');
            reset_price();
            reset_patterns_form();
            reset_pattern_file_form();
            $('#patterns').hide();
            $('#upload_pattern').hide();
            $('#overprints').slideDown();
            $('#notices_container').show();
            $('.input_notice p').hide();
            $('.info_notice').show();
            $('.input_notice .info_step3').show();
            $('#notices_container').removeClass('hide');
        }
        return false;
    });

    $('.font').live('click', function(){
        font_id = $(this).val();
        font_price =  parseMyFloat($('#font_price_'+font_id).html());
        model_price =  parseMyFloat($('#model_price').val());
        new_price = model_price+font_price;
        $('#price').html(addZeroesToPrecision(new_price));
        sum_up();
    });

    $('.pattern').live('click', function(){
        pattern_id = $(this).val();
        $.getJSON('/index/pattern-choice/format/json',{
            pattern_id: pattern_id
        }, function(data) {
            if(data.pc_file!=null){
                $('.pattern_color').remove();
                $('#pattern_price_'+pattern_id).parent().after('<img class="pattern_color" src="'+data.pc_file+'" alt="wybrany wzór + model + kolor" />');
            }
        });
        pattern_price =  parseMyFloat($('#pattern_price_'+pattern_id).html());
        model_price =  parseMyFloat($('#model_price').val());
        new_price = model_price+pattern_price;
        $('#price').html(addZeroesToPrecision(new_price));
        sum_up();
    });
    $('#pattern_file').live('click', function(){
        sum_custom_files_prices();
        sum_up();
    });
    $('#extra_file').live('click', function(){
        sum_custom_files_prices();
        sum_up();
    });

    $('.delivery_type').click(function(){
        sum_up();
    });

    $('#quantity_input').keypress(function(e){
        if(e.which!=8 && e.which!=0 && e.which!=37 && e.which!=38 && e.which!=46 && e.which!=108 && (e.which<48 || e.which>57)) {
            alert('Możesz wpisać tylko liczbę.');
            return false;
        }
    });
    $('#quantity_input').keyup(function(){
        amount = $(this).val();
        if(amount.substr(0, 1)=='0'){
            $(this).val(1);
        }
        if(amount>=50){
            alert('Maksymalna ilość to 49.');
            $(this).val(1);
            return false;
        }
        if(amount!='' && amount!=0){
            $.ajax({
                async: true,
                url: '/index/check-price/format/json',
                dataType: "json",
                data: {amount: amount},
                success: function(response){
                    if(response.price!=0 && response.price!=null){
                        $('#price').html(addZeroesToPrecision(response.price));
                    }
                    sum_up();
                }
            });
        }
        return false;
    });

    $('#submitModel').click(function(){
        $('#addPicture').val(1)
    });

    $('#submitCategory').click(function(){
        $('#addPicture').val(1)
    });

    $('#submitPattern').click(function(){
        $('#addPicture').val(1)
    });

    $('#submitFont').click(function(){
        $('#addPicture').val(1)
    });

    $('#invoice-1').click(function(){
        if($('#invoice-1:checked')){
            
            $('#invoice').show();
        }
    })
    $('#invoice-0').click(function(){
        if($('#invoice-0:checked')){
            
            $('#invoice').hide();
        }
    })

    $('#colorToggle').click(function() {
        checked = $(this).attr('checked');

        if(checked == true) {
            $('.colors').attr('checked','checked');
        }
        else {
            $('.colors').attr('checked', false);
        }
    });

    $('#sizeToggle').click(function() {
        checked = $(this).attr('checked');

        if(checked == true) {
            $('.sizes').attr('checked','checked');
        }
        else {
            $('.sizes').attr('checked', false);
        }
    });

    $('#addColorSubmit').click(function() {
        $.post('/admin/colors/fastadd/format/html', {
            name: $('#colorName').val()
        }, function(data) {
            //            $('#colors-element').append(data);
            $('#listOfColors').append(data);
        //            $('#colorName').setAttribute('value', null);
        });

        return false;
    });

    $('#addSizeSubmit').click(function() {
        $.post('/admin/sizes/fastadd/format/html', {
            name: $('#sizeName').val()
        }, function(data) {
            //            $('#sizes-element').append(data)
            $('#listOfSizes').append(data)
        });

        return false;
    });

    $('.statusFilterOption').click(function() {
        status_id = $(this).attr('value');
        link = '/admin/orders/index/status/'+status_id;
        window.location = link
        
        return false;
    });

    $('.changeOrderStatus').change(function() {
        id = $(this).parent().children('.order_id').attr('value');
        status_id = $(this).attr('value');

        $.post('/admin/orders/status/format/html', {
            id: id,
            s_id: status_id
        }, function(data) {
            $('.changeOrderStatusOdp').html(data)
        });

        return false;
    });


    $('.assignOrderToTab').change(function() {
        select = $(this);
        
        orderId = select.parent().children('.order_id').attr('value');
        tabId = select.attr('value');
        
        // na koncu odejmowanie od 0 dokonuje konwersji z boolean na integer
        var sendMail = confirm('Czy wysłać wiadomość mailową do klienta ?') - 0;
        
        var url = '/admin/orders/assign-tab/format/html/send-mail/' + sendMail;
        $.post(url, {
            order: orderId,
            tab: tabId
        })
        .error(function() {
            alert('Wystąpił błąd');
        });
        
        return false;
    });


    $('input[name="assignOrdersToTabSubmit"]').click(function() {
        var selectedOrders = $('input[name="orders[]"]:checked');
        if (selectedOrders.length == 0) {
            alert('Nie wybrałeś żadnych zamówień do przypisania.');
            return false;
        } else {
            return true;
        }
    });

    $('input[name="changeSelectedSubmit"]').click(function() {
    	var selectedOrders = $('input[name="orders[]"]:checked');
        if (selectedOrders.length == 0) {
            alert('Nie wybrałeś żadnych zamówień do zmiany.');
            return false;
        }
    });

    $('input[name="deleteSelected"]').click(function() {
        var selectedOrders = $('input[name="orders[]"]:checked');
        if (selectedOrders.length == 0) {
            alert('Nie wybrałeś żadnych zamówień do skasowania.');
            return false;
        }
    });
    
    $('input[name="mergeSelected"]').click(function() {
        var selectedOrders = $('input[name="orders[]"]:checked');
        if (selectedOrders.length == 0) {
            alert('Nie wybrałeś żadnych zamówień do połączenia.');
            return false;
        }
    });

    reset_overprints_form();
    reset_patterns_form();
    reset_pattern_file_form();
    sum_up();
    
//    if($('#returned').length==0){
//    //        $('#step2_form #submit').attr('disabled','disabled');
//    }

    $("#loader").bind('ajaxSend', function() {
        $("#loader").show();
    }).bind('ajaxComplete', function() {
        $("#loader").hide();
    });

});

function reset_overprints_form(){
    $('.font:checked').removeAttr('checked');
    $('.line').val('');
}
function reset_patterns_form(){
    $('.pattern:checked').removeAttr('checked');
}
function reset_pattern_file_form(){
    $('#pattern_file').val('');
    $('#extra_file').val('');
}
function reset_price(){
    model_price =  parseMyFloat($('#model_price').val());
    $('#price').html(addZeroesToPrecision(model_price));
    sum_up();
}
function sum_up(){
    var quantity;
    if($('#quantity_input').length!=0){
        quantity = $('#quantity_input').val();
    }
    else if($('#quantity').length!=0){
        quantity = $('#quantity').html();
    }
    if(quantity == '' || quantity == 0) quantity = 1;
    $('#quantity').html(quantity);
    product_price =  parseMyFloat($('#price').html());

    new_price = parseInt(quantity)*product_price;

    if($('#delivery_cost').length!=0){
        id = $('input.delivery_type:checked').val();
        var delivery_cost;
        if(isNaN(id))
            delivery_cost = 0
        else
            delivery_cost = parseMyFloat($('#delivery_price_'+id).html());
        $('#delivery_cost').html(addZeroesToPrecision(delivery_cost));
        new_price = new_price + delivery_cost;
    }
    $('#sum_price').html(addZeroesToPrecision(new_price));
}

function sum_custom_files_prices(){
    pattern_file_price =  parseMyFloat($('#pattern_file_price').val());
    extra_file_price =  parseMyFloat($('#extra_file_price').val());
    model_price =  parseMyFloat($('#model_price').val());
    new_price = model_price+pattern_file_price+extra_file_price;
    $('#price').html(addZeroesToPrecision(new_price));
}

//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 addZeroesToPrecision(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";
    }
    return(beforeComma+','+afterComma+' zł');
}

function parseMyFloat(number){
    if(number != null){
        number = number.toString();
        if(number.indexOf(' zł') != -1){
            number = number.replace(' zł', '');
        }
        if(number.indexOf(',') != -1){
            number = number.replace(',', '.');
        }
        return parseFloat(number);
    }
    else{
        return 0;
    }
}

function isNumber(x){
  return ( (typeof x === typeof 1) && (null !== x) && isFinite(x) );
}
