$(document).ready(function () {

    $('#pop_up_complaint').dialog({ autoOpen: false, position: 'center', width: '620px' });
    $('#pop_up_big_foto').dialog({ autoOpen: false, position: 'center', width: '680px' });
    $('#pop_up_message').dialog({ autoOpen: false, position: 'center', width: '600px' });

    $('a.complaint').bind('click', function (evt) { ComplaintClick(this.href); return false; });
    $('a.cartopen').bind('click', function (evt) { CartOpen(this.href); return false; });

    $('div.minfoto').bind('click', function (evt) { ShowBigFoto(this); });
    //$('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; });
    // $('a.fltns').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);
});

function CallBack() {
    var msg = $('#pop_up_description').html('<iframe name="showframe" id="showframe" src="' + RootPath + 'CallBack.aspx" width="100%" scrolling="no" height="180" frameborder="0" />').dialog({ autoOpen: true, position: 'center', width: 440, title: 'Заказать обратный звонок' });
    // return false;
}
//-------------------------complaint----------------------------//
function ComplaintClick(url) {
    WindowOpen(url, 'Обратная связь', 450, 370);
}
//-------------------------desc----------------------------//
function WindowOpen(url, t, w, h) {
    var msg = $('#pop_up_description').html('<iframe name="showframe" id="showframe" src="' + url + '" width="100%" height="' + h + '" frameborder="0" />').dialog({ autoOpen: true, position: 'center', width: w, title: t });
    return false;
};
//------------------------cmp---------------------------//
function CmpOpen(elem) {
    if (elem) {
        var arr = elem.id.split('_');
        var url = RootPath + 'CartInfo.aspx?GoodsId=' + arr[1] + '&PropId=' + arr[2] + '&CategoryId=' + arr[3] + '&ActionTarget=compare';
        if (elem.className == 'cmp_s') url = url + '&Qnt=0';
    } else
        var url = RootPath + 'CartInfo.aspx?ActionTarget=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('AddToCart' + result.status + '  ' + result.statusText).dialog('open');
}
function cmp_open() {
    if (PageOpener == 'inner')
        WindowOpen(RootPath + 'compare/session?rnd=' + Math.random(), 'Сравнение товаров', 1000, 700);
    else
        window.open(RootPath + 'compare/session?rnd=' + Math.random(), "", "");
}
function cmp_clear() {
    $.get(RootPath + 'CartInfo.aspx?ActionTarget=compare&Qnt=all&rnd=' + Math.random(), function (data) { CmpOpen(null); });
}
//-------------------------------goods----------------------------//
function FilterView(type) {
    if (document.getElementById('FilterType')) {
        document.getElementById('FilterType').value = type;
        document.forms[0].submit();
    }
}

function SortBy(column, sorttype) {
    document.getElementById('SortColumn').value = column;
    document.getElementById('SortType').value = sorttype;
    document.forms[0].submit();
}

var prev_link = null;

function setPriceRange(price_min, price_max) {
    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("/jaxcatalog", "/catalog");
        window.location = url.substring(0, url.indexOf('?')) + "?f=" + gparam('f', url) + "&range=" + price_min + ';' + price_max;
    } else if (url != null && url != 'undefined' && url.indexOf("/search?val=") != -1) {
        window.location = window.location + '&range=' + price_min + ';' + price_max;
    }
}

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')) {
        $('html, body').animate({ scrollTop: 0 }, 'slow');
        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), range: gparam('range', 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), range: gparam('range', 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), range: gparam('range', 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), range: gparam('range', 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);

        $('a.complaint').bind('click', function (evt) { ComplaintClick(this.href); return false; });
        $('a.cartopen').bind('click', function (evt) { CartOpen(this.href); return false; });
        $('div.minfoto').bind('click', function (evt) { ShowBigFoto(this); });

        $('a.flt').bind('click', function (evt) { FilterOpen(this); return false; });
        $('a.fltselected').bind('click', function (evt) { FilterOpen(this); return false; });
        $('a.fltns').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);
        CmpOpen(null);
    });
}
//------------------------cart---------------------------//
/*
function CartSetQnt(elem)
{
    if (elem.parentNode && elem.parentNode.lastChild)
        CartOpen(elem.parentNode.lastChild.href + "&Qnt=" + elem.value);
}
*/
function CartSetQnt(elem) {
    if (elem.parentNode && elem.parentNode.firstChild) {
        CartOpen(elem.href + "&Qnt=-" + elem.parentNode.firstChild.value);
        elem.parentNode.firstChild.value = 1;
    }
}

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)) {
            if (ob.qnt - 0 > 0)
                document.getElementById('i' + ob.key).className = 'cart_f';
            else
                document.getElementById('i' + ob.key).className = 'cart';

            document.getElementById('i' + ob.key).value = 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);
    
    $('#Cart_GoodsCount').html('<b>' + msg.GoodsCount + '</b> ед.');
    try{
        if (parent) parent.$('#Cart_GoodsCount').html('<b>' + msg.GoodsCount + '</b> ед. на сумму <b>' + msg.CartSum + '</b> руб.');
        if (window.opener) window.opener.$('#Cart_GoodsCount').html('<b>' + msg.GoodsCount + '</b> ед. на сумму <b>' + msg.CartSum + '</b> руб.');
    }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');
    
        var img_path = '';
        if (elem.tagName == 'div' || elem.tagName == 'DIV') {
            //alert(elem.currentStyle);
            if (elem.currentStyle) { img_path = elem.currentStyle.backgroundImage.replace(/"/g, ''); }
            else if (elem.style.backgroundImage) { img_path = elem.style.backgroundImage.replace(/"/g, ''); }
            else { try { img_path = getComputedStyle(elem, '').getPropertyValue('background-image'); } catch (ex_var) { } }
        } else
            img_path = 'url(' + elem.src + ')';

        img_path = img_path.replace("small", "big").replace("min", "big");
        $('#pop_up_big_foto').html('<div style="cursor:hand; background: ' + img_path + ' center no-repeat; width: 620px; height: 620px;" 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'); 
    }
}


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 == "") { $.get(RootPath + 'jax/pathMenu.aspx?id=' + id, null, function (data) { $('#' + _id).html(data); }); } 
        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();
     }
}

function makeBMark(title, url) {
    if (window.sidebar) {
        window.sidebar.addPanel(title, url, "");
        alert("Уважаемый пользователь Mozilla (Firefox)!\nПосле того как Вы создадите закладку и вызовите ее из меню \'Закладки\',\nссылка откроется в боковой панели!\nЧтобы избежать этого, в меню \'Закладки\' щелкните правой клавишей мыши на ссылке, выберите \'Свойства\' и снимите галочку \'Загрузить закладку в боковую панель\'");

    } else if (window.opera && window.print) {
        alert("Уважаемый пользователь Opera!\nПосле того как Вы создадите закладку и вызовите ее из меню \'Закладки\',\nссылка откроется в боковой панели!\nЧтобы избежать этого, снимите галочку \'Отобразить на панели\' ");
        var mbm = document.createElement('a');
        mbm.setAttribute('rel', 'sidebar');
        mbm.setAttribute('href', url);
        mbm.setAttribute('title', title);
        mbm.click();
    } else if (document.all) {
        window.external.AddFavorite(url, title);
    }
}
