$(document).ready(function () {
    //$('#block_tree a.nav').bind('click', function (evt) { juxG(this); return false; });
    //$('#block_stree a.nav').bind('click', function (evt) { juxG(this); return false; });
    //$('#block_list a.nav').bind('click', function (evt) { juxG(this); return false; });
    /*$('#block_navpath a').bind('click', function (evt) { alert('pig'); return false; });
    
    $('#block_tree a').toggle(
    function () {
    // ... тут необходимо внести изменения в код
    $(this).addClass("active");
    },
    function () {
    // тут оставляем так как есть
    $(this).removeClass("active");
    $(this).find('ul').slideUp('fast');
    }
    );*/

    $('ul.megamenu').megamenu();

    if (VirtualKeyboard == 'true') {
        $('input.kbd').bind('click', function (evt) { ShowKbd(this); return false; });
        $('#pop_up_keyboard').dialog({ autoOpen: false, position: 'center', width: '550' });
    }

    //$('#pop_up_admin_panel').dialog({ autoOpen: false, position: 'center', width: '99%' height: '800' });

    $('#pop_up_complaint').dialog({ autoOpen: false, position: 'center', width: '600' });
    //$('#pop_up_description').dialog({ autoOpen: false, position: 'center', width: '80%' });
    $('#pop_up_big_foto').dialog({ autoOpen: false, width: '600' });
    $('#pop_up_message').dialog({ autoOpen: false, position: 'center', width: '600' });

    $('img.img_mfoto').bind('click', function (evt) { ShowBigFoto(this); });
    $('img.img_mfoto').bind('mouseover', function (evt) { SetSmallFoto(this); });
    $('#SmallImage').bind('click', function (evt) { ShowBigFoto(this); });

    $('a.complaint').bind('click', function (evt) { ComplaintClick(this.href); return false; });
    $('a.cartopen').bind('click', function (evt) { CartOpen(this.href); return false; });

    $('div.filter_block').corner('10px');
    $('#DescCart_GoodsCount').corner('10px');

    $('div.News').corner('10px');
    $('#div_main_menu').corner('12px');
    $('#div_bottom_menu').corner('12px');
    $('div.div_rounded').corner('12px');
    $('div.post').corner('12px');
    


    $('a.cmptopen').bind('click', function (evt) { CmpOpen(this); return false; });
    $('a.flt').bind('click', function (evt) { FilterOpen(this); return false; });
    $('a.fltselected').bind('click', function (evt) { FilterOpen(this); return false; });
    if (PageOpener == 'inner') {
        $('a.descopen').bind('click', function (evt) { WindowOpen(this.href, 'Описание товара', 1000, 700); return false; });
    }
    CartOpen(null);
    if (document.getElementById('JaxCompare')) CmpOpen(null);
});
//-------------------------complaint----------------------------//
function ComplaintClick(url) {
    WindowOpen(url, 'Обратная связь', 450, 370);
}
//-------------------------desc----------------------------//
function WindowOpen(url, t, w, h) {
    var msg = $('#pop_up_description').dialog({ autoOpen: false, position: 'center', width: w, title: t });

    document.getElementById('pop_up_description').innerHTML = '<iframe name="showframe" src="' + url + '" width="100%" height="' + h + '" frameborder="0" />';
    if (url.indexOf('?')) url += '&rnd=' + Math.random();
    document.showframe.src = url;
    msg.dialog('close').dialog('open');
    return false;
};
//------------------------cmp---------------------------//
function CmpOpen(aurl) {
    var url;
    if (aurl != null) {
        url = aurl.href;
        var urldiv = $(aurl).children()[0];
        if (urldiv && urldiv.className == 'cmp_s') url = url + '&Qnt=0';
    } else {
        url = RootPath + 'CartInfo.aspx?Action=compare';
    }
    $.ajax({
        type: "GET",
        url: url + '&json=true&rnd=' + Math.random(),
        data: "{}",
        dataType: "json",
        error: CmpAjaxFailed,
        success: function (msg) {
            CmpSuccess(msg);
        }
    });
}
function CmpSuccess(msg) {
    $('div.cmp_s').removeClass("cmp_s").addClass("cmp");
    for (var i in msg.items) {
        var ob = msg.items[i];
        if (document.getElementById('c' + ob.key)) {
            if (ob.qnt - 0 > 0) document.getElementById('c' + ob.key).className = 'cmp_s';       
        }
    }
    //if (msg.Message > ' ') $('#pop_up_message').dialog('close').html(msg.Message).dialog('open');
    if (msg.ErroMessage > ' ') $('#pop_up_message').dialog('close').html(msg.Message).dialog('open');
    if (msg.GoodsCount > 0) $('#JaxCompare').html('Товаров в сравнении ' + msg.GoodsCount + ' ед. <a href="javascript:cmp_open();">сравнить</a>&nbsp;&nbsp; <a href="javascript:cmp_clear();">очистить</a><br />');
    else $('#JaxCompare').html(' ');
    setTimeout("$('#pop_up_message').dialog('close')", 500);
}
function CmpAjaxFailed(result) {
    $('#pop_up_message').dialog('close').html('CartError' + result.status + '  ' + result.statusText).dialog('open');
}
function cmp_open() {
    if (PageOpener == 'inner')
        WindowOpen(RootPath + 'compare/session', 'Сравнение товаров', 1000, 700);
    else
        window.open(RootPath + 'compare/session', "", "");
}
function cmp_clear() {
    $.get(RootPath + 'CartInfo.aspx?Action=compare&Qnt=all&rnd=' + Math.random(), function (data) { CmpOpen(null); });
}
//-------------------------------goods----------------------------//
function SortBy(column, sorttype) {
    document.getElementById('SortColumn').value = column;
    document.getElementById('SortType').value = sorttype;
    document.forms[0].submit();
}

var prev_link = null;

function FilterOpen(elem) {
    url = elem.href;
    if (url != null && url != 'undefined') {
        url = url.replace("/catalog", "/jaxcatalog");
        url = url.replace('?f=', '?rnd=' + Math.random() + '&f=');
        prev_link = elem;
        UpdateGoods(url);
    }
}
function page(num) {
    if (!IsIntNum(num)) num = 0;
    if (document.getElementById('PageNum')) {
        document.getElementById('PageNum').value = num;
        var url = null;
        if (prev_link != null && prev_link != 'undefined') url = prev_link.href;
        else if (window.location) url = window.location.href;
        if (url != null && url != 'undefined' && url.indexOf("catalog") != -1) {
            url = url.replace("/catalog", "/jaxcatalog");
            var p = { pagenum: num, rnd: Math.random(), f: gparam('f', url), brand: gparam('brand', url), cat: gparam('cat', url) };
            if (url.indexOf('?') != -1) url = url.substring(0, url.indexOf('?'));
            UpdateGoods(url, p);
        } else document.forms[0].submit();
    }
}
function Sort(column) {
    if (document.getElementById('SortColumn') && document.getElementById('SortType')) {
        document.getElementById('SortColumn').value = column;
        if (document.getElementById('SortType').value == 'ascending') document.getElementById('SortType').value = 'descending';
        else document.getElementById('SortType').value = 'ascending';
        var url = null;
        if (prev_link != null && prev_link != 'undefined') url = prev_link.href;
        else if (window.location) url = window.location.href;
        if (url != null && url != 'undefined' && url.indexOf("catalog") != -1) {
            url = url.replace("/catalog", "/jaxcatalog");
            var p = { s_column: column, s_type: document.getElementById('SortType').value, rnd: Math.random(), f: gparam('f', url), brand: gparam('brand', url), cat: gparam('cat', url) };
            if (url.indexOf('?') != -1) url = url.substring(0, url.indexOf('?'));
            UpdateGoods(url, p);
        } else document.forms[0].submit();
    }
}
function PageListSize(elem) {
    if (document.getElementById('PageSize')) {
        document.getElementById('PageSize').value = elem.value;
        var url = null;
        if (prev_link != null && prev_link != 'undefined') url = prev_link.href;
        else if (window.location) url = window.location.href;
        if (url != null && url != 'undefined' && url.indexOf("catalog") != -1) {
            url = url.replace("/catalog", "/jaxcatalog");
            var p = { PageSize: elem.value, rnd: Math.random(), f: gparam('f', url), brand: gparam('brand', url), cat: gparam('cat', url) };
            if (url.indexOf('?') != -1) url = url.substring(0, url.indexOf('?'));
            UpdateGoods(url, p);
        }
        else
            document.forms[0].submit();
    }
}
function ListView(type) {
    if (document.getElementById('Miniatures')) {
        document.getElementById('Miniatures').value = type;
        var url = null;
        if (prev_link != null && prev_link != 'undefined') url = prev_link.href;
        else if (window.location) url = window.location.href;
        if (url != null && url != 'undefined' && url.indexOf("catalog") != -1) {
            url = url.replace("/catalog", "/jaxcatalog");
            var p = { Miniatures: type, rnd: Math.random(), f: gparam('f', url), brand: gparam('brand', url), cat: gparam('cat', url) };
            if (url.indexOf('?') != -1) url = url.substring(0, url.indexOf('?'));
            UpdateGoods(url, p);
        }
        else
            document.forms[0].submit();
    }
}
function UpdateGoods(url, p) {
    $.get(url, p, function (data) {
        $('#JaxGoodsList').html(data);
        $('img.img_mfoto').bind('click', function (evt) { ShowBigFoto(this); });
        $('img.img_mfoto').bind('mouseover', function (evt) { SetSmallFoto(this); });
        $('a.complaint').bind('click', function (evt) { ComplaintClick(this.href); return false; });
        $('a.cartopen').bind('click', function (evt) { CartOpen(this.href); return false; });
        $('a.cmptopen').bind('click', function (evt) { CmpOpen(this); return false; });
        $('a.flt').bind('click', function (evt) { FilterOpen(this); return false; });
        $('a.fltselected').bind('click', function (evt) { FilterOpen(this); return false; });
        if (PageOpener == 'inner') {
            $('a.descopen').bind('click', function (evt) { WindowOpen(this.href, 'Описание товара', 1000, 700); return false; });
        }
        $('div.filter_block').corner('10px');
        CartOpen(null);
        CmpOpen(null);
    });
}
//------------------------cart---------------------------//
function CartOpen(url) {
    if (url == null) url = RootPath + 'CartInfo.aspx?a=1';
    $.ajax({
        type: "GET",
        url: url + '&json=true&rnd=' + Math.random(),
        data: "{}",
        dataType: "json",
        error: CartFailed,
        success: function(msg) {
                  CartSuccess(msg);
        }
    });
}
function CartSuccess(msg) {
    for (var i in msg.items) {
        var ob = msg.items[i];
        if (document.getElementById('i' + ob.key)) {
            document.getElementById('i' + ob.key).className = 'cart_f';
            document.getElementById('i' + ob.key).innerHTML = ob.qnt - 0;
        }
    }
    if (msg.Message > ' ') $('#pop_up_message').dialog('close').html(msg.Message).dialog('open');
    if (msg.ErroMessage > ' ') $('#pop_up_message').dialog('close').html(msg.Message).dialog('open');
    setTimeout("$('#pop_up_message').dialog('close')", 500);
    $('#DescCart_GoodsCount').html('Корзина: ' + msg.GoodsCount + ' ед.');
    $('#Cart_GoodsCount').html('Товаров ' + msg.GoodsCount + ' ед.<br/> На сумму ' + msg.CartSum);
    try{
        if (parent) parent.$('#Cart_GoodsCount').html('Товаров ' + msg.GoodsCount + ' ед.<br/> На сумму ' + msg.CartSum);
        if (window.opener) window.opener.$('#Cart_GoodsCount').html('Товаров ' + msg.GoodsCount + ' ед.<br/> На сумму ' + msg.CartSum);
    }catch(ex_var){}    
}
function CartFailed(result) {
    $('#pop_up_message').dialog('close').html('CartError' + result.status + '  ' + result.statusText).dialog('open'); 
} 
//-------------------------------foto--------------------------------//
function ShowBigFoto(elem) {
    if ($('#pop_up_big_foto').dialog("isOpen")) $('#pop_up_big_foto').dialog('close');
    else {
        var bimg = elem.src.replace("small", "big").replace("min", "big");
        $('#pop_up_big_foto').html('<div style="cursor:hand; background: url(' + bimg + ') center no-repeat; width: 600px; height: 600px;" onclick="FotoClose()" />').dialog('open'); 
    }  
}
function FotoClose() {
    $('#pop_up_big_foto').dialog('close');
}
function SetSmallFoto(elem, dialog_pop_up_big_foto) {
    if (document.getElementById('SmallImage')) document.getElementById('SmallImage').src = elem.src.replace("min", "small");
    if ($('#pop_up_big_foto').dialog("isOpen")) {
        var img = elem.src.replace("min", "big");
        $('#pop_up_big_foto').dialog('close').html('<div style="cursor:hand; background: url(' + img + ') center no-repeat; width: 600px; height: 600px;" onclick="FotoClose()" />').dialog('open'); 
    }
}
//-------------------------kbd----------------------------//
var input_fild_id = '';
function kbd(value) {
    if (document.getElementById(input_fild_id)) {
        fild = document.getElementById(input_fild_id);
        switch (value) {
            case 'bksp':
            case 'Bksp':
            case 'delete':
            case 'del':
                val = fild.value;
                val = val.substring(0, (val.length - 1));
                fild.value = val;
                break;
            case 'space':
                fild.value = fild.value + ' ';
                break;
            case 'ru':
                document.getElementById('kb_en').style.display = 'none';
                document.getElementById('kb_ru').style.display = 'block';
                break;
            case 'en':
                document.getElementById('kb_en').style.display = 'block';
                document.getElementById('kb_ru').style.display = 'none';
                break;
            case 'Clear':
                fild.value = '';
                break;
            default:
                fild.value = fild.value + value;
                break;
        }
        if (document.getElementById('keyboard_inpit'))
            document.getElementById('keyboard_inpit').innerHTML = fild.value+'|';
        fild.focus();
    }
}
function CloseKeyboard() {
    $('#pop_up_keyboard').dialog('close');
}
function ShowKbd(elem) {
    input_fild_id = elem.id
    elem.focus();
    if (!$('#pop_up_keyboard').dialog("isOpen")) {
        document.getElementById('pop_up_keyboard').innerHtml = MakeRequest(RootPath + 'keyboard.aspx', 'win_pop_up_keyboard', 'pop_up_keyboard'); 
        $('#pop_up_keyboard').dialog("open");
    }
}
//////////////////////////////////////////////////////////////////////
var iframe_timeout = 0;

function gparam(pname, curl) {
    var q = curl;
    var i = q.indexOf(pname + '=');
    if (i == -1)   return "";

    var r = q.substr(i + pname.length + 1, q.length - i - pname.length - 1);
    i = r.indexOf('&');
    if (i != -1)  r = r.substr(0, i);
    return r.replace(/\+/g, ' ');
}

function juxG(elem) {
    if (checkJax()) {
        if (elem != prev_link) {
            if (prev_link != null) prev_link.className = 'nav';
            var url = elem.href;
            $('#block_tree a.active').removeClass("active");
            
            elem.className = 'active';
            if (prev_link != elem) {
                document.getElementById('rid').value = gparam('rid', url);
                document.getElementById('cid').value = gparam('cid', url);
                document.getElementById('scid').value = gparam('scid', url);
                MakeRequest(url.replace("Catalog.aspx", "jax/jaxCatalog.aspx"), '', 'JaxGoodsList');
                //MakeRequest(url.replace("Catalog.aspx", "jax/jaxCats.aspx"), '', 'JaxCats');
            }
            prev_link = elem;
        }
    }
    else  window.location = elem.href;
}

function h(id, end) {
    if (document.getElementById(id) && document.getElementById('n' + id)) {
        node = document.getElementById(id);
        img = document.getElementById('n' + id);
        if (node.style.display == 'none') {
            if (end == 0) { node.style.display = 'block'; img.className = 'minus'; }
            else { node.style.display = 'block'; img.className = 'minusend'; }
        } else {
            if (end == 0) { node.style.display = 'none'; img.className = 'plus'; }
            else { node.style.display = 'none'; img.className = 'plusend'; }
        }
    }
}

function GlobalSearch(event) {
    if (event == null || (event != null && event.keyCode != null && event.keyCode == 13)) {
        if (document.getElementById('Search')) {
            if (document.getElementById('Search').value.length < 3) {
                alert("Длина строки поиска не может быть меньше 3 символов");
                return;
            }
            document.forms[0].submit();
        } 
    }
}

function ResetFilter(){
    if(document.getElementById('brands')) document.getElementById('brands').value = '';
    if(document.getElementById('Search')) document.getElementById('Search').value = '';
    if(document.getElementById('TextBoxPriceMin')) document.getElementById('TextBoxPriceMin').value = '';
    if(document.getElementById('TextBoxPriceMax')) document.getElementById('TextBoxPriceMax').value = '';
    document.forms[0].submit();  
}

function Brand(id, elem) {
    //alert(document.getElementById('scid').value);
     if(document.getElementById('brands')){
        if(id > ''){
            document.getElementById('brands').value = id;
            document.getElementById('scid').value = document.getElementById('cid').value;
            document.forms[0].submit(); 
        }else{
            if(elem && elem != undefined){
                document.getElementById('brands').value = elem.value;
            }else{
                if(document.forms[0].brand && document.forms[0].brand.checked){
                    document.getElementById('brands').value = document.forms[0].brand.value;
                }else if(document.forms[0].brand){
                    size = document.forms[0].brand.length;
                    brands = '';   
                    for(i=0; i<size; i++){
                        if(document.forms[0].brand[i] && document.forms[0].brand[i].checked){
                          brands = brands + document.forms[0].brand[i].value + ",";
                        }
                    }
                    document.getElementById('brands').value = brands.substring(0, brands.length-1);
                }
                document.getElementById('scid').value = document.getElementById('cid').value;
                document.forms[0].submit();
            }     
        }
    }
}

function TreeView(type) {
    if (document.getElementById('tstyle')) {
        document.getElementById('tstyle').value = type;
        document.forms[0].submit();
    }
}
//------------------------menu--------------------------*/

var menuTimerID = '0';
var menuPrevID = '0';

function showMenu(id) {
    if (document.getElementById(id)) {
        if (menuPrevID > '0' && menuTimerID > 0) {
            clearTimeout(menuTimerID);
            document.getElementById(id).style.display = "none";
            if (menuPrevID != id && document.getElementById(menuPrevID)) document.getElementById(menuPrevID).style.display = "none";
        }
        document.getElementById(id).style.display = "block";
    }
}

function hideMenu(id)
{
    if (document.getElementById(id)) {
            menuTimerID = setTimeout('document.getElementById("' + id + '").style.display = "none";', 400);
            menuPrevID = id;
    }
}

function showJaxPath(id) {
    var _id = 'menu' + id;
    if (document.getElementById(_id)) {
        if(document.getElementById(_id).innerHTML == "") MakeRequest(RootPath+'jax/pathMenu.aspx?id=' + id, '', _id);
        showMenu(_id);
    }
}

function hidePath(id) {
    hideMenu('menu' + id)
}

function showJaxGroup(id) {
    var _id = 'group' + id;
    if (document.getElementById(_id) && menuPrevID == '0') {
        menuPrevID = _id;
    }
}
       
function hideGroup(id) {
    hideMenu('group'+id)
}
//-------------------------------check--------------------------------//
function checkQuantity(elem) {
    str = elem.value;
    if (IsIntNum(str) == false && str.length > 0) {
        alert("неправильный ввод: " + str);
        elem.value = 0;
    }
}
function checkIntNum(elem, v) {
    str = elem.value;
    if (IsIntNum(str) == false && str.length > 0) {
        alert("неправильный ввод: " + str);
        elem.value = v;
    }
}
function IsIntNum(sText){
   ValidChars = "0123456789";
   IsNumber=true;
   for (i = 0; i < sText.length && IsNumber == true; i++){ 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) IsNumber = false;
   }
   return IsNumber; 
}
function IsFloatNum(sText){
   ValidChars = "0123456789.";
   IsNumber=true;
   for (i = 0; i < sText.length && IsNumber == true; i++){ 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1)  IsNumber = false;
   }
   return IsNumber;
}
function CheckLength(elem, slength){
    str = elem.value;
    if(str.length > slength){
         alert("Длина введенной строки превышает допустимый размер в "+slength+" символов");
         elem.value = str.substring(0, slength);
    }
}
//cart
function GoodsAction(act, key){
    if(document.getElementById('cart_action')){
       document.getElementById('cart_action').value = act;
       document.getElementById('cart_productKey').value = key;
       document.forms[0].submit();
    }
}

function SetAction(act){
    if(document.getElementById('cart_action')){
       document.getElementById('cart_action').value = act;
    }
}

function OrderAction(act){
    GoodsAction(act, '');
}

function DelProduct(key){
    GoodsAction('delete', key)
}
function ChangeProduct(key){
    GoodsAction('change',key);
}
function IncreaseQuantity(key){
    GoodsAction('increase', key);
}
function DecreaseQuantity(key){
    GoodsAction('decrease',key);
}

function MoneyBack(key){
    if(document.getElementById('mb'+key)){
        document.getElementById('cart_productKey').value = key;
        if(document.getElementById('mb'+key).checked)
            document.getElementById('cart_action').value = 'add_moneyback';
        else
            document.getElementById('cart_action').value = 'rm_moneyback';
            
        document.forms[0].submit();
     }
}

function SetQuantity(key){
    if(document.getElementById('qnt'+key)){
        document.getElementById('cart_productKey').value = key;
        new_quantity = document.getElementById('qnt'+key).value;
        if(IsIntNum(new_quantity)){
            document.getElementById('cart_productQuantity').value = new_quantity;
            document.getElementById('cart_action').value = 'set_quantity';
        }else{
            alert('Количество товара можно задать только целым числом!');
            document.getElementById('qnt'+key).value = 1;
        } 
        document.forms[0].submit();
     }
}