/*
 * function creates a currency format with a given number
 */
jQuery.fn.number_Format = function(a, b, c, d){
    a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
    e = a + '';
    f = e.split('.');
    if (!f[0]) {
        f[0] = '0';
    }
    if (!f[1]) {
        f[1] = '';
    }
    if (f[1].length < b) {
        g = f[1];
        for (i = f[1].length + 1; i <= b; i++) {
            g += '0';
        }
        f[1] = g;
    }
    if (d != '' && f[0].length > 3) {
        h = f[0];
        f[0] = '';
        for (j = 3; j < h.length; j += 3) {
            i = h.slice(h.length - j, h.length - j + 3);
            f[0] = d + i + f[0] + '';
        }
        j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
        f[0] = j + f[0];
    }
    c = (b <= 0) ? '' : c;
    return f[0] + c + f[1];
}

jQuery.fn.calculate_total_Ammount = function(){
    var orders = parseFloat($('.ammount_cart').html());
    var delivery = parseFloat($('.shipment_price').html());
    //alert(orders);
    //alert(delivery);
    
    var total_ammount = $(document).number_Format(orders + delivery, 2, '.', '');
    
    $('#total_ammount').html('Łącznie do zapłaty: <span>' + total_ammount + ' zł</span>');
};

jQuery.fn.update_header_Cart = function(){
    $.ajax({
        url: "/ajax_cart.php",
        data: "action=update_header_cart",
        type: "POST",
        success: function(msg){
            $("#cart_info").html(msg);
        }
    });
};

jQuery.fn.my_photo_Sortable = function(){
    /*
     *Sortable list project photo
     */
    var opp = $('#sortable_list img').attr("opp");
    if (opp != 'true') {
        $("#sortable_list").sortable({
            handle: '.handle',
            update: function(){
                var order = $('#sortable_list').sortable('serialize');
                $.ajax({
                    url: "/ajax_response.php",
                    data: "action=sortable&" + order + "",
                    type: "GET",
                    loader: false
                });
            }
        });
    }
};

jQuery.fn.add_photo_to_Project = function(){

    var id = $(this).attr("rel");
    var opp = $(this).attr("opp");
    var action;
    if (opp == 'true') {
        action = 'wywolaj';
    }
    else {
        action = 'add_photo';
    }
    $.ajax({
        url: "/ajax_response.php",
        data: "action=" + action + "&id=" + id + "",
        type: "POST",
        loader: true,
        success: function(msg){
            $("#chosen_photos").html(msg);
            var alert_text = $("#alert").html();
            $("#category_description").find("#alert_box").html("<div class=\'alert\'>" + alert_text + "</div>").css("display", "block");
            $("#category_description").unblock();
            var c = $.cookie("fototrendypl_choosen_photos");
            if (eval(c) == null) {
                $("#category_description").find("form :input[name=\'submit_\']").css({
                    "display": "block"
                })
            }
            if (opp != 'true') {
                $("#sortable_list").sortable('destroy');
                $("#sortable_list").my_photo_Sortable();
            }
            else {
                //$('#new_photo img[rel=' + id + ']').parent().css('display', 'none');
                var display = 0;
                var num = 0;
                $("#new_photo img").each(function(){
                    num = num + 1;
                });
                $("#user_photos .choose_single_photo_box[style*='display']").each(function(){
                    display = display + 1;
                });
                if ((num - display) == 0) {
                    $("#append").html('Wybrano wszystkie zdjęcia');
                }
                $(this).next().next().removeAttr('checked');
            }
            $('img.handle').aToolTip({
                outSpeed: 10
            });
            
        },
        error: function(msg){
            $("#category_description").unblock();
        }
    });
    return false;
    
};

jQuery.fn.add_check_photo_to_Project = function(){

    var ids = new Array();
    var id = '';
    var i = 0;
    $('#user_photos .choose_single_photo_box img').each(function(){
        if ($(this).parent().css('display') == 'none') {
            null;
        }
        else {
            var check = $(this).parent().find('.choose_single_photo_check').attr('checked');
            if (check == true) {
                id = $(this).attr("rel");
                ids[i] = id;
                i = i + 1;
                $(this).parent().css('display', 'none');
            }
        }
    });
    var text = ids.join(";");
    $.ajax({
        url: "/ajax_response.php",
        data: "action=wywolaj&option=check&ids=" + text + "",
        type: "POST",
        loader: true,
        success: function(msg){
            $("#chosen_photos").html(msg);
            var alert_text = $("#alert").html();
            $("#category_description").find("#alert_box").html("<div class=\'alert\'>" + alert_text + "</div>").css("display", "block");
            $("#category_description").unblock();
            $('img.handle').aToolTip({
                outSpeed: 10
            });
            
            var display = 0;
            var num = 0;
            $("#new_photo img").each(function(){
                num = num + 1;
            });
            $("#user_photos .choose_single_photo_box[style*='display']").each(function(){
                display = display + 1;
            });
            if ((num - display) == 0) {
                $("#append").html('Wybrano wszystkie zdjęcia');
            }
        },
        error: function(msg){
            $("#category_description").unblock();
        }
    });
    return false;
    
};


jQuery.fn.breadcrumbs = function(){
    /*
     * Breadcrumb show
     */
    var html = $('#breadcrumb_hide').html();
    $('#breadcrumb').html(html);
    if (html == '') {
        $('#breadcrumb').hide();
    }
};


jQuery.fn.calculate_shipment = function(){
    var str = $("form.shipment").serialize();
    $.ajax({
        url: "/ajax_cart.php",
        data: "action_ajax=check_shipment&" + str + "",
        type: "POST",
        success: function(msg){
            $(".shipment_total_price").html(msg).calculate_total_Ammount();
            $("#category_description").unblock();
        },
        error: function(msg){
            $("#category_description").unblock();
            $(document).calculate_total_Ammount();
        }
    });
    //return false;
};

function pokaz_ukryj(pokaz, ukryj){
    document.getElementById(pokaz).style.display = "block";
    
    var rozbite = ukryj.split(",");
    var count = (rozbite.length) - 1;
    var i = 0;
    for (i = 0; i <= count; i++) {
        document.getElementById("podmien" + rozbite[i]).style.display = "none";
    }
    
}

$(document).ready(function(){
    // if is coockie and user choose all required photos
    var c = $.cookie("fototrendypl_choosen_photos");
    if (eval(c) == null) {
        var opp = $("#category_description").find("form :input[name=\'submit_\']").attr("opp");
        if (opp != 'true') {
            $("#category_description").find("form :input[name=\'submit_\']").css({
                "display": "block"
            })
        }
    }
    
    
    //if user click on button and not choose all required photos
    $("#category_description").find("form :input[name=\'submit_\']").live("click", function(){
        var c = $.cookie('fototrendypl_choosen_photos');
        if (eval(c) != null) {
            alert('Ilość zdjęć pozostała do wybrania: ' + c);
            $(this).css({
                "display": "none"
            })
            return false;
        }
    });
    /*
     *Lightbox
     */
    $('a.lightbox').lightBox(); // Select all links with lightbox class
    $('#chosen_photos_noaction').find('a[rel=lightbox]').lightBox(); // Select all links with lightbox class
    /*
     * Copy template text to hidden input
     */
    $('input[name=submit_summary]').click(function(){
        var val = $("div#template_text").find('textarea[name=template_text]').val();
        $("input[name=template_text]").val(val);
        $("input[name=save_template_text]").val(val);
    });
    /*
     *
     * Product Tabs
     */
    $('#tabs').tabs();
    
    
    /* On Page */
    $('select#on_page_list').change(function(){
        var href = $(this).val();
        location.href = href;
    });
    
    /* Sort form */
    $('select#sort-list').change(function(){
        var href = $(this).val();
        location.href = href;
    });
    
    /* change album */
    $('select#album_list').change(function(){
        var href = $(this).val();
        location.href = href;
    });
    /*
     * Menu
     */
    $('#cssdropdown li.headlink').hover(function(){
        $('ul', this).css('display', 'block');
    }, function(){
        $('ul', this).css('display', 'none');
    });
    
    
    // function to 'check' the fake ones and their matching checkboxes
    $(".login_checkbox").live('click', function(){
        ($(this).hasClass('login_checkbox_checked')) ? $(this).removeClass('login_checkbox_checked') : $(this).addClass('login_checkbox_checked');
        ($(this).hasClass('login_checkbox_checked')) ? $('#login').find("input.login_checkbox_hidden").attr("checked", "checked") : $('#login').find("input.login_checkbox_hidden").removeAttr("checked");
        return false;
    });
    
    /*
     *  Validation
     */
    $("form.shipment_form").validate({
        rules: {
        
            user_name: "required",
            user_adress: "required",
            user_surname: "required",
            user_postal_code: "required",
            user_city: "required",
            user_email: {
                required: true,
                email: true
            }
        },
        
        
        
        errorLabelContainer: ".alert",
        showErrors: function(errorMap, errorList){
            this.defaultShowErrors();
            $(".alert").html("Liczba nieprawidłowych pól: " + this.numberOfInvalids());
        },
        highlight: function(element, errorClass){
            $(element).addClass(errorClass);
            $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
        },
        unhighlight: function(element, errorClass){
            $(element).removeClass(errorClass);
            $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
        }
        
        
        
        
    })
    /*
     *   shipment form
     */
    $('.diffrent_shipment_check').click(function(){
        // Checked, copy values
        $(".diffrent_shipment input[name=shipment_name]").val($("form.shipment_form input[name=user_name]").val()).removeAttr("disabled");
        $(".diffrent_shipment input[name=shipment_surname]").val($("form.shipment_form input[name=user_surname]").val()).removeAttr("disabled");
        $(".diffrent_shipment input[name=shipment_adress]").val($("form.shipment_form input[name=user_adress]").val()).removeAttr("disabled");
        $(".diffrent_shipment input[name=shipment_postal_code]").val($("form.shipment_form input[name=user_postal_code]").val()).removeAttr("disabled");
        $(".diffrent_shipment input[name=shipment_city]").val($("form.shipment_form input[name=user_city]").val()).removeAttr("disabled");
        $(".diffrent_shipment input[name=shipment_telephone]").val($("form.shipment_form input[name=user_telephone]").val()).removeAttr("disabled");
        
    });
    
    $('input.delete_project').live('click', function(){
        var x = window.confirm("Czy napewno chcesz usunąć ten projekt?")
        if (x) 
            null;
        else 
            return false;
    });
    
    $("a.remove_from_cart").live("click", function(){
        var id = $(this).attr("rel");
        var x = window.confirm("Czy napewno chcesz usunąć produkt?")
        if (x) 
            null;
        else 
            return false;
        
        $.ajax({
            url: "/ajax_cart.php",
            data: "action=remove_item&id=" + id + "",
            type: "POST",
            loader: true,
            success: function(msg){
                var c = $.cookie("fototrendypl_empty_cart");
                if (eval(c) != null) {
                    $("#category_description").html(msg)
                    var date = new Date();
                    date.setTime(date.getTime() - (1 * 24 * 60 * 60 * 1000));
                    $.cookie('fototrendypl_empty_cart', '1', {
                        path: '/',
                        expires: date
                    });
                }
                else {
                    $("#order_items").html(msg);
                }
                $(this).update_header_Cart();
                $(this).calculate_total_Ammount();
                $("#category_description").unblock();
            },
            error: function(msg){
                $("#category_description").unblock();
            }
        });
        return false;
    });
    
    
    // Cart how much
    $("a.update_cart").live("click", function(){
        $(".how_much input").focus();
        var str = $("form.how_much").serialize();
        $.ajax({
            url: "/ajax_cart.php",
            data: "action=update_cart&" + str + "",
            type: "POST",
            loader: true,
            success: function(msg){
                $(".ammount_cart").html(msg);
                $("#category_description").unblock();
            }
        });
        $.ajax({
            url: "/ajax_cart.php",
            data: "action=update_cart_list&" + str + "",
            type: "POST",
            loader: true,
            success: function(msg){
                $("#order_items").html(msg);
                $(this).calculate_shipment();
                $(this).update_header_Cart();
                $("#category_description").unblock();
            },
            error: function(msg){
                $(this).calculate_shipment();
                $("#category_description").unblock();
            }
        });
        return false;
    });
    
    $(".delivery select, .delivery input").live("change", function(){
        $(document).calculate_shipment();
    });
    $('#delivery_select').change(function(){
        var val = $(this).val();
        if (val == '4') {
            $('#check').css({
                'display': 'none'
            });
            $('#delivery_check_2, #delivery_check_3').removeAttr("checked").calculate_shipment();
        }
        else {
            $('#check').css({
                'display': 'block'
            }).calculate_shipment();
        }
    });
    
    
    $(".choose_single_photo").live('click', function(){
        $(this).add_photo_to_Project();
    });
    $(".add_check_photo").live('click', function(){
        $(this).add_check_photo_to_Project();
    });
    
    
    
    
    
    
    $('#chosen_photos li').find(".handle").live("click", function(){
        var pid = $(this).attr("pid");
        var opp = $(this).attr("opp");
        var action;
        if (opp == 'true') {
            action = 'wywolaj_remove_photo';
        }
        else {
            action = 'remove_photo';
        }
        var id = $(this).attr("rel");
        $.ajax({
            url: "/ajax_response.php",
            data: "action=" + action + "&id=" + id + "",
            type: "POST",
            loader: true,
            success: function(info){
                $("#chosen_photos").html(info);
                var alert_text = $("#alert").html();
                $("#category_description").find("#alert_box").html("<div class=\'alert\'>" + alert_text + "</div>")
                $("#category_description").unblock();
                if (opp != 'true') {
                    $("#sortable_list").sortable('destroy');
                    $("#sortable_list").my_photo_Sortable();
                    var c = $.cookie("fototrendypl_choosen_photos");
                    if (eval(c) != null) {
                        $("#category_description").find("form :input[name=\'submit_\']").css({
                            "display": "none"
                        })
                    }
                }
                else {
                    var i = 0;
                    $('#chosen_photos img').each(function(){
                        i = i + 1;
                    })
                    if (i == 0) {
                        $("#category_description").find("form :input[name=\'submit_\']").css({
                            "display": "none"
                        })
                    }
                    $('#append').html('');
                    $('#new_photo img[rel=' + pid + ']').parent().css('display', '');
                }
                $('img.handle').aToolTip({
                    outSpeed: 10
                });
                
            },
            error: function(msg){
                $("#category_description").unblock();
            }
        });
        return false;
    });
    
    $("form.choose_template").live("click", function(){
        var str = $(this).serialize();
        $.ajax({
            url: "/ajax_response.php",
            data: "action=add_template&" + str + "",
            type: "POST",
            loader: true,
            success: function(msg){
                $("#choosen_template_box").html(msg);
                
                var date = new Date();
                var COOKIE_NAME = 'fototrendypl_template';
                date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
                $.cookie(COOKIE_NAME, '1', {
                    path: '/',
                    expires: date
                });
                
                var alert_text = $("#alert").html();
                $("#category_description").find("#alert_box").html("<div class='alert'>" + alert_text + "</div>").css("display", "block");
                $("#category_description").unblock();
                $("#category_description").find("form :input[name=sumbit_template]").css({
                    "display": "block"
                })
            },
            error: function(msg){
                $("#category_description").unblock();
            }
        });
    });//End add_template action
    /*
     *   Register show
     */
    $('#register_box a.register_more').click(function(){
        $(".show_all_data").toggle("slow");
        return false;
    });
    
    /*
     *   diffrent_shipment show
     */
    $('.diffrent_shipment_check').click(function(){
        if ($(this).attr("checked")) {
            $(".diffrent_shipment").toggle("slow");
        }
        else {
            $(".diffrent_shipment").toggle("slow");
        }
        //
        return false;
    });
    
    /*
     *   update order description
     */
    $('form#order input[name=submit_shipment]').click(function(){
        var str = $('div#description textarea[name=description]').val();
        $.ajax({
            url: "/ajax_cart.php",
            data: "action=save_description&value=" + str + "",
            type: "POST",
            success: function(msg){
                $("#choosen_template_box").html(msg);
            }
        });
    });
    
    /*
     *   Szukajka
     */
    $("#search .input").autocomplete('/ajax_search.php', {
        matchContains: true,
        minChars: 0,
        autoFill: false,
        scrollHeight: 300
    });
    $('input.input').click(function(){
        var val = $(this).val();
        if (val == 'Szukaj produktu...') {
            $(this).val('');
        }
    });
    
    /*
     *  Pomoc w colorboxie
     */
    $('.ajax_help').click(function(){
        var url_value = $(this).attr('href');
        $("#ajax_help_box").html('<div style="text-align:center;"><img src="/img/ajax-loader.gif" /></div>');
        $.ajax({
            url: url_value,
            success: function(msg){
                $("#ajax_help_box").html(msg).css({
                    "display": "block"
                });
            }
        });
        return false;
    });
    $("#ajax_help_box").draggable({
        handle: '#title'
    });
    $('div.close').live("click", function(){
        $("#ajax_help_box").css({
            "display": "none"
        });
    });
    
    /*
     *   Regulamin w help boxie
     */
    $('.ajax_help_s').click(function(){
        var url_value = $(this).attr('rel');
        $("#ajax_help_box").html('<div style="text-align:center;"><img src="/img/ajax-loader.gif" /></div>');
        $.ajax({
            url: url_value,
            success: function(msg){
                $("#ajax_help_box").html(msg).css({
                    "display": "block"
                });
            }
        });
        return false;
    });
    
    /*
     *   Podświetlanie wybranego zdjęcia
     */
    $('input.check_photo').live('click', function(){
        ($(this.parentNode.parentNode).hasClass('photo-checked')) ? $(this.parentNode.parentNode).removeClass('photo-checked').addClass('photo-list') : $(this.parentNode.parentNode).addClass('photo-checked').removeClass('photo-list');
    });
    
    
    $('input.choose_single_photo_check').live('click', function(){
        ($(this.parentNode).hasClass('photo-checked')) ? $(this.parentNode).removeClass('photo-checked').addClass('photo-list') : $(this.parentNode).addClass('photo-checked').removeClass('photo-list');
    });
    /*
     *   Zaznacz wszytskie zdjęcia z albumu
     */
    $(".check_all_photo").live('click', function(){
        var checked_status = this.checked;
        $("input.check_photo").each(function(){
            this.checked = checked_status;
            ($(this).attr('checked') == false) ? $(this.parentNode.parentNode).removeClass('photo-checked').addClass('photo-list') : $(this.parentNode.parentNode).addClass('photo-checked').removeClass('photo-list');
        });
        ($(this).attr('checked') == true) ? $(this.parentNode).find('label').html('Odznacz wszystkie') : $(this.parentNode).find('label').html('Zaznacz wszystkie');
    });
    
    $(".check_all_photo_s").live('click', function(){
        var checked_status = this.checked;
        $("input.choose_single_photo_check").each(function(){
            if ($(this).parent().css('display') == 'none') {
                null;
            }
            else {
                this.checked = checked_status;
                ($(this).attr('checked') == false) ? $(this.parentNode).removeClass('photo-checked').addClass('photo-list') : $(this.parentNode).addClass('photo-checked').removeClass('photo-list');
            }
            
        });
        ($(this).attr('checked') == true) ? $(this.parentNode).find('label').html('Odznacz wszystkie') : $(this.parentNode).find('label').html('Zaznacz wszystkie');
    });
    /*
     *   Odwróć zaznaczenie
     */
    $("#reverse_check").live('click', function(){
        $("input.check_photo").each(function(){
            ($(this).attr('checked') == true) ? $(this.parentNode.parentNode).removeClass('photo-checked').addClass('photo-list') : $(this.parentNode.parentNode).addClass('photo-checked').removeClass('photo-list');
            ($(this).attr('checked') == true) ? $(this).removeAttr('checked') : $(this).attr('checked', 'checked');
        });
        return false;
    });
    
    $("#reverse_check_s").live('click', function(){
        $("input.choose_single_photo_check").each(function(){
            if ($(this).parent().css('display') == 'none') {
                null;
            }
            else {
                ($(this).attr('checked') == true) ? $(this.parentNode).removeClass('photo-checked').addClass('photo-list') : $(this.parentNode).addClass('photo-checked').removeClass('photo-list');
                ($(this).attr('checked') == true) ? $(this).removeAttr('checked') : $(this).attr('checked', 'checked');
            }
        });
        return false;
    });
    
    
    
    /*
     *   Pokaż wybór albumu
     */
    $('select#album-action-select, select#album-move').change(function(){
        var val = $(this).val();
        var name = $('#album-action-select :selected').attr('rel');
        if (val == 'move' || val == 'blank') {
            if (val == 'blank') {
                $('#album-move').css('display', 'none')
            }
            else {
                $('#album-move').css('display', 'block')
            }
        }
        else {
            if (name == 'blank') {
                $('#album-move').css('display', 'none')
            }
            $('#album_photos').attr('action', val);
        }
    });
    
    $('form#album_photos .submit').click(function(){
        var val = $('#album-action-select :selected').val();
        var name = $('#album-action-select :selected').attr('rel');
        var num;
        $("input.check_photo").each(function(){
            if ($(this).attr('checked') == true) {
                num = 2;
            }
        });
        if (num != 2) {
            alert('Nie wybrałeś żadnego zdjęcia');
            return false;
        }
        
        if (val == 'blank') {
            alert('Nie wybrałeś żadnej akcji');
            return false;
        }
        document.album_photos.submit();
    })
    /*
     *   Pokaż ukryj link publiczny do albumu
     */
    $('input#show-public').click(function(){
        var val;
        if ($(this).attr('checked') == true) {
            val = 1;
            $("#album-key").css('display', 'block');
        }
        else {
            val = 0;
            $("#album-key").css('display', 'none');
        }
        var id = $(this).attr('rel');
        $.ajax({
            url: "/ajax_response.php",
            data: "action=album_public&id=" + id + "&val=" + val + "",
            type: "POST"
        });
    });
    /*
     *   Pokaż exif
     */
    $('input#show_exif').click(function(){
        var val;
        if ($(this).attr('checked') == true) {
            val = 1;
        }
        else {
            val = 0;
        }
        var id = $(this).attr('rel');
        $.ajax({
            url: "/ajax_response.php",
            data: "action=album_show_exif&id=" + id + "&val=" + val + "",
            type: "POST"
        });
    });
    
    
    /*
     *   Pokaż inputy zmiany nazwy i ospisu albumu
     */
    $('#album-options #name').toggle(function(){
        $('#album-options input.name').css('display', 'block')
    }, function(){
        $('#album-options input.name').css('display', 'none')
    });
    $('#album-options #description').toggle(function(){
        $('#album-options input.description').css('display', 'block')
    }, function(){
        $('#album-options input.description').css('display', 'none')
    });
    $('#album-options input[type=submit].name').click(function(){
        var id = $('#album-options input.name').attr('rel');
        var val = $('#album-options input.name').val();
        $.ajax({
            url: "/ajax_response.php",
            data: "action=album_name&id=" + id + "&val=" + val + "",
            type: "POST"
        });
        $('#album-options input.name').css('display', 'none');
        var text = '<label>' + val + '</label>';
        $('#self_content_header').html(text);
        $('#album-options input[type=text].name').val(val);
        return false;
    })
    $('#album-options input[type=submit].description').click(function(){
        var id = $('#album-options input.description').attr('rel');
        var val = $('#album-options input.description').val();
        $.ajax({
            url: "/ajax_response.php",
            data: "action=album_desc&id=" + id + "&val=" + val + "",
            type: "POST"
        });
        $('#album-options input.description').css('display', 'none')
        $('#description_box').html(val);
        $('#album-options input[type=text].description').val(val);
        return false;
    })
    $('#album-key').click(function(){
        $(this).focus();
        $(this).select();
    })
    
    /*
     *   Prompt for album delete and album delete plus photo
     */
    $('.remove_album').click(function(){
        var x = window.confirm("Czy napewno chcesz usunąć ten album? Wszystkie zdjęcia zostaną przeniesione do Albumu głównego")
        if (x) 
            null;
        else 
            return false;
    });
    $('.remove_album_plus').click(function(){
        var x = window.confirm("Czy napewno chcesz usunąć ten album i wszystkie znajdujące się w nim zdjęcia?")
        if (x) 
            null;
        else 
            return false;
    });
    $('.delete_photo').click(function(){
        var x = window.confirm("Czy napewno chcesz usunąć to zdjęcie?")
        if (x) {
            var id = $(this).attr('rel');
            $.ajax({
                url: "/ajax_response.php",
                data: "action=delete_photo&id=" + id + "",
                type: "POST"
            });
            $(this.parentNode.parentNode).css('display', 'none');
            return false;
        }
        else {
            return false;
        }
    });
    
    
    
    var i = 0;
    var api = [];
    $.api = api;
    $('img.crop').each(function(){
        var w;
        var h;
        var ws = $(this).width();
        var hs = $(this).height();
        var ratio;
        //alert(ws); alert(hs);
        var wh = $(this).attr('wh')
        var ht = $(this).attr('ht')
        var prw = $('.change option:selected', $(this).parents(".single-photo:first")).attr('prw');
        var prh = $('.change option:selected', $(this).parents(".single-photo:first")).attr('prh');
        var patch = $(this).parents(".single-photo:first");
        // var ddd = $(patch).find('.change option:selected').attr('prw');
        // alert(ddd);
        if (ws > hs) {
            if (ws / hs > prw) {
                w = 0;
                h = hs * prw;
                var a = 0;
                var b = ws;
                var d = (ws - (hs * prw)) / 2;
                var c = ws - d;
            }
            else {
                w = ws;
                h = 0;
                var a = (hs - (ws * prh)) / 2;
                var b = ws;
                var c = 0;
                var d = 0;
            }
            ratio = prw;
        }
        else {
            w = 0;
            h = hs;
            var a = hs;
            var b = 0;
            var d = (ws - (hs * prh)) / 2;
            var c = ws - d;
            ratio = prh;
        }
        
        api.push($.Jcrop(this, {
            setSelect: [d, a, c, b],
            maxSize: [w, h],
            minSize: [w, h],
            bgColor: 'black',
            bgOpacity: .7,
            allowResize: false,
            allowSelect: false,
            sideHandles: false,
            aspectRatio: ratio,
            onChange: function(c){
                $(patch).find('.x').val(c.x);
                $(patch).find('.y').val(c.y);
                $(patch).find('.w').val(c.w);
                $(patch).find('.h').val(c.h);
                $(patch).find('.x2').val(c.x2);
                $(patch).find('.y2').val(c.y2);
            },
            onSelect: function(c){
                $(patch).find('.x').val(c.x);
                $(patch).find('.y').val(c.y);
                $(patch).find('.w').val(c.w);
                $(patch).find('.h').val(c.h);
                $(patch).find('.x2').val(c.x2);
                $(patch).find('.y2').val(c.y2);
            }
        }));
    });
    
    
    $('.change').change(function(){
        var ratio;
        var id = $(this).attr('id');
        var pr_r = $('option:selected', this).attr('pr_r');
        $('.pr_r', $(this).parents(".single-photo:first")).val(pr_r);
        
        var ws = $('.crop', $(this).parents(".single-photo:first")).width();
        var hs = $('.crop', $(this).parents(".single-photo:first")).height();
        var wh = $('.crop', $(this).parents(".single-photo:first")).attr('wh')
        var ht = $('.crop', $(this).parents(".single-photo:first")).attr('ht')
        var prw = $('option:selected', this).attr('prw');
        var prh = $('option:selected', this).attr('prh');
        $(api).each(function(index, element){
            if (index == id) {
                if (ws > hs) {
                    if (ws / hs > prw) {
                        w = 0;
                        h = hs * prw;
                        var a = 0;
                        var b = ws;
                        var d = (ws - (hs * prw)) / 2;
                        var c = ws - d;
                    }
                    else {
                        w = ws;
                        h = 0;
                        var a = (hs - (ws * prh)) / 2;
                        var b = ws;
                        var c = 0;
                        var d = 0;
                    }
                    ratio = prw;
                }
                else {
                    w = 0;
                    h = hs;
                    var a = hs;
                    var b = 0;
                    var d = (ws - (hs * prh)) / 2;
                    var c = ws - d;
                    ratio = prh;
                }
                
                element.setOptions({
                    aspectRatio: ratio,
                    setSelect: [d, a, c, b],
                    maxSize: [w, h],
                    minSize: [w, h]
                });
            }
        });
    });
    
    /*
     *   add new album - check album name
     */
    $('#add-album input.submit').click(function(){
        var text = $('#add-album input[name=album_name]').val();
        if (text != '') {
            return true
        }
        else {
            alert('Podaj nazwę albumu');
            return false;
        }
        
    });
    
    // toggle #price-table
    $('#show-price-table').click(function(){
        $('#price-table').slideToggle()
        var state = $(this).html();
        // Change the state
        state = (state == 'Ukyj tabelke cen' ? 'Pokaż tabelke cen' : 'Ukyj tabelke cen');
        $(this).html(state);
        return false;
    })
    
    $('#show_new_box .button').click(function(){
        $('#new_box').slideToggle();
    });
    
    
    
    /***********************************************/
    
    $('.single_template a img').aToolTip({
        outSpeed: 10
    });
    $('form.choose_template a').aToolTip({
        outSpeed: 10
    });
    $('img.choose_single_photo').aToolTip({
        outSpeed: 10
    });
    $('img.handle').aToolTip({
        outSpeed: 10
    });
    $('.atooltip').aToolTip({
        outSpeed: 10
    });
    
    /*
     *     Show info about photos in print_photo.php
     */
    var display = 0;
    var num = 0;
    $("#new_photo img").each(function(){
        num = num + 1;
    });
    $("#user_photos .choose_single_photo_box[style*='display']").each(function(){
        display = display + 1;
    });
    if ((num - display) == 0) {
        $("#append").html('Wybrano wszystkie zdjęcia');
    }
    
    /* 
     * Set start total_ammount
     */
    var is_photo = $.cookie("fototrendypl_choosen_photos");
    if (eval(is_photo) == null) {
        opp = $("#category_description").find("form :input[name=\'submit_\']").attr("opp");
        if (opp != 'true') {
            $("#category_description").find("form :input[name=\'submit_\']").css({
                "display": "block"
            })
        }
    }
    var is_template = $.cookie("fototrendypl_template");
    if (eval(is_template) == '1') {
        $("#category_description").find("form :input[name=sumbit_template]").css({
            "display": "block"
        })
    }
    
    
    $(document).calculate_total_Ammount();
    $(document).my_photo_Sortable();
    $(document).breadcrumbs();
    //end
});

/**
 * Paweł Iwanowski
 */
$(function(){
    /**
     * Przeliczanie wartości zamawianych odbitek
     */
    $("#print-photos-form .size, #print-photos-form .qt").live('change', function(){
        var price = 0;
        var price_p;
        var qt;
        var ok = true;
        $('#print-photos-form select.size option:selected').each(function(){
            qt = $(".qt", $(this).parents(".single-photo:first")).val();
            price_p = parseFloat($(this).attr('price')) * qt;
            price = price_p + price;
            var numericExpression = /^[0-9]+$/;
            if (qt.match(numericExpression)) {
                $(".qt", $(this).parents(".single-photo:first")).css('border', '1px solid #4991DA');
            }
            else {
                alert('Podaj poprawna liczbę');
                $(".qt", $(this).parents(".single-photo:first")).css('border', 'solid 1px red');
                ok = false;
            }
        });
        if (ok == true) {
            price = $(document).number_Format(price, 2, '.', '');
            $('.photo-ammount').html(price + ' zł');
        }
        //return false;
    });
    
    $("#print-photos-form .apply-to-all").click(function(){
        var id = $(this).attr('id');
        var wybrany = $(this).parents(".single-photo:first");
        var ilosc = $('.qt', wybrany).val();
        var rozmiar = $('.size', wybrany).val();
        var papier = $('.type', wybrany).val();
        $("#print-photos-form .single-photo").each(function(){
            $('.qt', this).val(ilosc);
            $('.size', this).val(rozmiar);
			$('.size', this).trigger('change');
            $('.type', this).val(papier);
        });
        return false;
    });
});

