function setimg(){
  /*$("a[rel^='prettyPhoto']").prettyPhoto({
    theme: 'facebook',
    showTitle: true,
    modal: false,
    opacity: 0.9
  });*/

    $("a[rel^='prettyPhoto']").fancybox();

}

$(document).ready(function(){
    $('input[name="keywords"]').liveSearch({url: '/search/live?text='});
    $("#tabs").tabs();
    $("a[rel^='show_subcategories']").each(function() {
        var rels = $(this).attr('rel').split('_'); 
        $(this).attr('href', 'javascript:show_subs(' + rels[2] + ');'); 
    });
    $("a[rel^='prettyPhoto[iframe_href']").each(function() {
        var rels = $(this).attr('rel').split('_');
        $(this).attr('rel', 'prettyPhoto');
        if(rels[4] == 'pid') {
            var pid = rels[5];
        }
        $(this).attr('href', $(this).attr('href') + '?iframe=true&width=' + rels[2] + '&height=' + rels[3] + '&pid=' + pid); 
    });
    setimg();
    check_lower_price();
});


function check_lower_price() {
    var url = new String(document.location);
    var needle = '#lower_price';
    if(url.indexOf(needle) > 0) {
        $('div#lower_price').show();
        $('input#fio').focus();
    }
}

function show_subs(id) {
    $('#sub_categories' + id).slideToggle('slow');
}
function show_products(id, customer_id) {
    if($('tr#cat_' + id + ' td.products_place').hasClass('visible')) {
        $('tr#cat_' + id + ' td.products_place').removeClass('visible');
        $('tr#cat_' + id + ' td.products_place').slideToggle('slow');
        return;
    }

    var $_GET = {};

    document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
        function decode(s) {
            return decodeURIComponent(s.split("+").join(" "));
        }

        $_GET[decode(arguments[1])] = decode(arguments[2]);
    });
    $('span#loader_' + id).html('&nbsp;<img src="/templates/Spinningline/images/loader2.gif" />');
    $.post(request_url + 'price_products.php', { cid: id, customer_id: customer_id, stockcheck: $_GET['stockcheck'] }, function(data) {
        $('tr#cat_' + id + ' td.products_place').html(data);
        $('tr#cat_' + id + ' td.products_place').slideToggle('slow', function(){
            $(this).addClass('visible');
            $('span#loader_' + id).html('');
        });
    });
}

function add_to_cart(pid, max) {
    var promt_str = "Введите количество товара.";
    if(max > 0) promt_str += "\nМаксимальное количество товара для заказа: " + max;
    /*var qty = prompt(promt_str, "1");
    if(qty > 0) {
        $.post('/add_to_cart.php?action=add_product', { products_id: pid, cart_quantity: qty }, function(data) {
            $('#shopping_cart_place').html(data);
            $('.breadcrumbsModule').append('<div class="infobox">Товар добавлен в корзину. Вы можете <a href="/shopping_cart.php">перейти в корзину</a> или <a href="/checkout_shipping.php">оформить заказ</a>.</div>');
        });
    }*/

    var promt_str = "Максимальное количество для заказа: " + max + "";
    //var qty = prompt(promt_str, "1");
    var inp = '<input type="text" name="qty-'+ pid +'" id="qty-'+ pid +'" value="1" size="3" style="border:1px solid #AAAAAA; margin-top: 7px;">';
    var buyb = '<a href="javascript:add_to_cart_ok(' + pid + ')" title="Продолжить"><img src="/templates/Spinningline/images/buttons/russian/button_continue.jpg"></a>'
    $('body').append('<div id="qpromt-' + pid + '" style="width:350px;"><p>' + promt_str +'</p><table style="width:100%"><tr><td style="vertical-align: top; padding-top: 7px;">Желаемое количество товара:</td><td style="vertical-align: top; padding-right: 5px;">' + inp + '</td><td style="vertical-align: top;">' + buyb + '</td></tr></table></div>');
    //$.prettyPhoto.open('#qpromt-'+pid, 'Добавление товара в корзину', '');
    $.fancybox({
        'href': '#qpromt-'+pid,
        'transitionOut': 'none',
         onClosed: function() {
             $('body #qpromt-' + pid).remove();
         },
         onComplete: function() {
            $('#qty-'+pid).focus();
            $('#qty-'+pid).select();
            $('#qty-'+pid).keyup(function(e) {
                if(e.keyCode == 13) {
                    add_to_cart_ok(pid);
                }
            });
	 }
    });

    
}
function add_to_cart_ok(pid) {
    var qty = $('#qty-'+pid).val();
    if(qty > 0) {
        $.post('/add_to_cart.php?action=add_product', { products_id: pid, cart_quantity: qty }, function(data) {
            $('#qpromt-'+pid).remove();
            $('.infobox').remove();
            $.fancybox.close();
            window.scrollTo(0, 0);
            $('#shopping_cart_place').html(data);
            $('.breadcrumbsModule').append('<div class="infobox" style="display: none;">Товар добавлен в корзину. Вы можете <a href="/shopping_cart.php">перейти в корзину</a> или <a href="/checkout_shipping.php">оформить заказ</a>.</div>');
            $('.infobox').slideDown();
        });
    }
}
function show_lower_price() {
    $('div#lower_price').slideToggle('slow');
}

function show_answers(id) {
    $('td#answer_table_' + id).slideToggle('slow');
}

function send_lower_price(pid) {
    $('input#button').attr('value', 'Идёт отправка...');
    $('div#lower_price input').each(function() {
        $(this).attr('disabled', 'disabled');
    });
    $('div#lower_price textarea').attr('disabled', 'disabled');
    
    var fio = $('input#fio').attr('value');
    var contact = $('input#email_tel').attr('value');
    var link = $('input#link').attr('value');
    var comment = $('textarea#comment').val();

    $.post(request_url + 'lower_price.php', { act: 'add_lower_price', pid: pid, fio: fio, contact: contact, link: link, comment: comment }, function(data) {
        
        if(data != 'Ok') {
            var dats = data.split(':');
            $('input#' + dats[1]).css({'border' : '1px red solid'});
            $('input#button').attr('value', 'Отправить');
            $('div#lower_price input').each(function() {
                $(this).attr('disabled', false);
            });
            $('div#lower_price textarea').attr('disabled', false);
            alert('Поля, отмеченные красной звёздочкой, обязательны для заполнения!');
        } else {
            $('div#lower_price').html('<p style="color: red; font-size: 16px; padding: 15px; font-weight: bold;">Спасибо за предоставленную информацию, в ближайшее время мы с Вами свяжемся!</p>');
        }
    });

}

function sc_activate(cid) {
    $('td#sc_message_place').html('Пожалуйста подождите...');
    $('span#sc_loader_place').html('&nbsp;<img src="/templates/Spinningline/images/gc/loader.gif" />');
    $('input#sc_code').attr('disabled', true);
    $('input#sc_button').attr('disabled', true);
    var code = $('input#sc_code').val();
    $.post('/shopping_cart_sc.php', { act: 'sc_activate', cid: cid, code: code }, function(data) {
        var html = '';
        if(data == 'false') {
            html = 'Неверный или недействительный промо код.';
        } else if (data == 'np') {
            html = 'Нет подходящих товаров.'
        } else {
            html = data;
            window.location.reload();
        }
        $('td#sc_message_place').html(html);
        $('span#sc_loader_place').html('');
        $('input#sc_code').attr('disabled', false);
        $('input#sc_button').attr('disabled', false);
    });
}


function gc_activate(cid) {
    $('td#gc_message_place').html('Пожалуйста подождите...');
    $('span#gc_loader_place').html('&nbsp;<img src="/templates/Spinningline/images/gc/loader.gif" />');
    $('input#gc_code').attr('disabled', true);
    $('input#gc_button').attr('disabled', true);
    var code = $('input#gc_code').val();
    $.post(request_url + 'gc.php', { act: 'gc_activate', cid: cid, code: code }, function(data) {
        var datas = data.split('|');
        var html = '';
        if(datas[0] == 'false') {
            html = 'Неверный код сертификата.';
        }
        if(datas[0] == 'true') {
            html = 'Сертификат на сумму ' + datas[1] + ' балла(ов) активирован.';
            $('span#user_balls').html(datas[2]);
        }
        $('td#gc_message_place').html(html);
        $('span#gc_loader_place').html('');
        $('input#gc_code').attr('disabled', false);
        $('input#gc_button').attr('disabled', false);
    });
}

function pay_gc() {
    var balls = $('input#pay_balls').val();
    location.href = 'checkout_confirmation.php?pay_gc=' + balls;
}

function send_review() {
    var fio = $('div#review_form input#fio').attr('value');
    var review = $('div#review_form textarea#review').val();

    $('div#review_form input#send_review').attr('value', 'Идёт отправка...');
    $('div#review_form input').each(function() {
        $(this).attr('disabled', 'disabled');
    });
    $('div#review_form textarea#review').attr('disabled', 'disabled');
    
    $.post(request_url + 'reviews.php', { act: 'add_review', fio: fio, content: review}, function(data) {
        if(data != 'Ok') {
            var dats = data.split(':');
            $('div#review_form ' + dats[1]).css({'border' : '1px red solid'});
            $('div#review_form input#send_review').attr('value', 'Отправить');
            $('div#review_form input').each(function() {
                $(this).attr('disabled', false);
            });
            $('div#review_form textarea#review').attr('disabled', false);
            alert('Все поля обязательны для заполнения!');
        }
        else {
            $('div#review_form').html('<p style="color: red; font-size: 16px; padding: 15px; font-weight: bold; text-align: center;">Спасибо за Ваш отзыв<br /><input type="button" value="Закрыть" onclick="jQuery(\'div#review_form\').dialog(\'close\');" /></p>');
        }
    });
}

function create_dialog(text) {
    $('#dialog-modal').remove();
    text = (text != '' && typeof text != 'undefined') ? text : 'Loading...';
    $("body").append("<div id='dialog-modal'>" + text + "</div>");    
    $('#dialog-modal').dialog("destroy");

    return $('#dialog-modal');
}
function add_to_wishlist(pid) {
    var promt_str = "Сейчас этого товара нет на складе, но вы можете добавить его в лист заказов и как только товар появится на складе - вы получите уведомление.<br>Введите желаемое количество.";
    //var qty = prompt(promt_str, "1");
    var inp = '<input type="text" name="qty-'+ pid +'" id="qty-'+ pid +'" value="1" size="3" style="border:1px solid #AAAAAA; margin-top: 7px;">';
    var buyb = '<a href="javascript:add_to_wishlist_ok(' + pid + ')" title="Продолжить"><img src="/templates/Spinningline/images/buttons/russian/button_continue.jpg"></a>'
    $('body').append('<div id="qpromt-' + pid + '" style="width:350px;"><p>' + promt_str +'</p><table style="width:100%"><tr><td style="vertical-align: top; padding-top: 7px;">Желаемое количество товара:</td><td style="vertical-align: top; padding-right: 5px;">' + inp + '</td><td style="vertical-align: top;">' + buyb + '</td></tr></table></div>');
    $.fancybox({
        'href': '#qpromt-'+pid,
        'transitionOut': 'none',
         onComplete: function() {
            $('#qty-'+pid).focus();
            $('#qty-'+pid).select();
            $('#qty-'+pid).keyup(function(e) {
                if(e.keyCode == 13) {
                    add_to_wishlist_ok(pid);
                }
            });
	 }
    });

    
}
function add_to_wishlist_ok(pid) {
    var qty = $('#qty-'+pid).val();
    if(qty > 0) {
        $.post('/templates/Spinningline/ajax/request/wishlist.php?action=add', { pid: pid, qty: qty, comment: '' }, function(data) {
            $('#qpromt-'+pid).remove();
            $('.infobox').remove();
            $.fancybox.close();
            window.scrollTo(0, 0);
            //$('#shopping_cart_place').html(data);
            $('.headerCartControl').html(data);
            
            $('.breadcrumbsModule').append('<div class="infobox" style="display: none;">Товар добавлен в лист заказов. Как только товар поступит на склад - вы получите уведомление по e-mail. Вы можете <a href="/shopping_cart.php">перейти в корзину</a> для редактирования.</div>');
            $('.infobox').slideDown();
        });
    }
}
/*
function add_to_wishlist(pid) {
    var load_url = '/templates/Spinningline/ajax/request/wishlist.php?action=dialog',
        dialog = create_dialog('Загрузка...');

    dialog.load(load_url, {pid: pid}).dialog({
        width: 650,
        modal:   true,
        title:   "Добавить в список заказов",
        buttons: {
            'Отмена': function() {
                $(this).dialog('close');
            },
            'Добавить': function() {
                var qty = $("#qty");
                var comment = $("#comment");
                
                var tips = $(".validateTips");
                var valid_form = true;

                valid_form = valid_form && checkQty(qty, 'товаров для заказа', 0, 1000);
                valid_form = valid_form && checkLength(comment, 'комментария', 0, 255);
                
                if(valid_form) {
                    var add_url = load_url = '/templates/Spinningline/ajax/request/wishlist.php?action=add';
                    $(this).load(add_url, {pid: pid, qty: qty.val(), comment: comment.val()});
                    $(this).dialog('option', 'buttons', { "Ok": function() {
                        $(this).dialog("close");
                    }});
                }
            }
        },
        close: function() {
            $(this).dialog("destroy");
        }
    });
    
    return false;
}
*/
function edit_wishlist(wid) {
    var load_url = '/templates/Spinningline/ajax/request/wishlist.php?action=edit_dialog',
        dialog = create_dialog('Загрузка...');

    dialog.load(load_url, {wid: wid}).dialog({
        width: 350,
        modal:   true,
        title:   "Редактирование заказа на поставку",
        buttons: {
            'Отмена': function() {
                $(this).dialog('close');
            },
            'Сохранить': function() {
                var qty = $("#qty");
                var comment = $("#comment");
                
                var tips = $(".validateTips");
                var valid_form = true;

                valid_form = valid_form && checkQty(qty, 'товаров для заказа', 0, 1000);
                valid_form = valid_form && checkLength(comment, 'комментария', 0, 255);
                
                if(valid_form) {
                    var add_url = load_url = '/templates/Spinningline/ajax/request/wishlist.php?action=edit';
                    $(this).load(add_url, {wid: wid, qty: qty.val(), comment: comment.val()});
                    $(this).dialog('option', 'buttons', { "Ok": function() {
                        $(this).dialog("close");
                        document.location = 'customers_wishlist.php?r=' + Math.random();
                    }});
                }
            }
        },
        close: function() {
            $(this).dialog("destroy");
        }
    });
    
    return false;
}

function delete_wishlist(wid) {
    var load_url = '/templates/Spinningline/ajax/request/wishlist.php?action=delete_dialog',
        dialog = create_dialog('Загрузка...');
    dialog.load(load_url, {wid: wid}).dialog({
        width: 350,
        modal:   true,
        title:   "Удаление заказа на поставку",
        buttons: {
            'Отмена': function() {
                $(this).dialog('close');
            },
            'Удалить': function() {
                var add_url = load_url = '/templates/Spinningline/ajax/request/wishlist.php?action=delete';
                $(this).load(add_url, {wid: wid});
                $(this).dialog('option', 'buttons', { "Ok": function() {
                    $(this).dialog("close");
                    document.location = 'customers_wishlist.php?r=' + Math.random();
                }});
            }
        },
        close: function() {
            $(this).dialog("destroy");
        }
    });
    
    return false;
}

function updateTips(t) {
    tips
        .text(t)
        .addClass('ui-state-highlight');
}
    
function checkLength(o,n,min,max) {
    if ( o.val().length > max || o.val().length < min ) {
        o.addClass('ui-state-error');
        updateTips("Длина " + n + " должна быть от "+min+" до "+max+" знаков.");
        return false;
    }
    else {
        return true;
    }
}

function IsNumeric(input) {
   return (input - 0) == input && input.length > 0;
}

function checkQty(o,n,min) {
    var val = o.val();

    if (!IsNumeric(val) || val <= min ) {
        o.addClass('ui-state-error');
        updateTips("Количество " + n + " должно быть больше "+min+".");
        return false;
    }
    else {
        return true;
    }
}
