﻿$(document).ready(function () {

    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_complaint').dialog({ autoOpen: false, position: 'center', width: '600px' });
    $('#pop_up_big_foto').dialog({ autoOpen: false, width: 850, height: 850 });
    $('#pop_up_message').dialog({ autoOpen: false, position: 'center', width: '600' });

    $('a.complaint').bind('click', function (evt) { ComplaintClick(this.href); return false; });
    $('a.cartopen').bind('click', function (evt) { CartOpen(this.href); return false; });

    $('a.talking').bind('click', function (evt) {
        TalkingClick();
        $('a.send_msg').bind('click', function (evt) { SendMessage(this.href, 'qst=1'); return false; });
        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 InterClick(evt, bt) {
    enevt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13) {
        $('#' + bt).click();
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;

        return false;
    }
    return true;
} 

//-------------------------complaint----------------------------//
function ComplaintClick(url) {
    WindowOpen(url, 'Обратная связь', 436, 390);
}
var timeoutHandler = true;
function TalkingClick() {
    var popup = '<div id="pop_up_complaint">';
    popup += '<table width="400px"><tr class="light"><td><b>Текст:</b><br />';
    popup += '<textarea name="texts" rows="10" cols="20" id="texts" readonly="readonly" wrap="virtual" style="background-color:#FFFFC0;border-width:1px;border-style:Dotted;width:400px;"></textarea><br/>';
    popup += 'Сообщение*:<br /><textarea name="message" rows="4" cols="20" id="message" style="background-color:#FFFFC0;border-width:1px;border-style:Dotted;width:400px;"></textarea><br />';
    popup += '<small>* поле для ввода.</small>';
    popup += '</td></tr>';
    popup += '<tr class="dark"><td align="right"><a href="./chats/feedback.aspx" class="send_msg">Отправить</a></td></tr>';
    popup += '</table></div>';
    PopupOpen(popup, 450, "Разговор");
}
function PopupOpen(p, w, t) {
    var msg = $('#pop_up_description')
    .dialog({ autoOpen: false,
        position: 'center',
        open: function (event, ui) { TimeOutRequest('./chats/feedback.aspx', 'qst=1') },
        close: function (event, ui) { timeoutHandler = false; MakeRequest('./chats/close.aspx', '', 'texts') },
        width: w,
        title: t
    });
    document.getElementById('pop_up_description').innerHTML = p;

    msg.dialog('open');
    return false;
}
//-------------------------desc----------------------------//
function WindowOpen(url, t, w, h) {
    if (url.indexOf('?')) url += '&rnd=' + Math.random();
    var msg = $('#pop_up_description').dialog({ autoOpen: false, position: 'center', width: w, title: t });
    $('#pop_up_description').html('<iframe name="showframe" src="' + url + '" width="100%" height="' + h + '" frameborder="0" />');
    msg.dialog('close').dialog('open');
    return false;
};

function SendMessage(url, params) {
    if (params.length > 0)
        params += '&';
    params += 'msg=' + $('#message').attr('value');
    if (!IE) {
        params = params.replace(/\n/g, '\r\n');
    }
    MakeRequest(url, params, 'texts');
    $('#message').attr('value', '');
}
function TimeOutRequest(url, params) {
    if (timeoutHandler) {
        MakeRequest(url, params, 'texts');
        setTimeout(function () { TimeOutRequest(url, params) }, 5000);
    }
}
var IE = '\v' == 'v';
function MakeRequest(url, parameters, container) {
    $.ajax({
        type: "POST",
        url: url,
        data: parameters,
        dataType: "text",
        success: function (data) {
            if (IE) {
                data = data.replace(/\r\n/g, '<br>\n');
            }
            $('#' + container).html(data);
            var object = document.getElementById(container);
            object.scrollTop = object.scrollHeight - object.clientHeight;
        }
    });
}
//------------------------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] + '&Action=compare';
        if (arr[0] + '' == 'c') {
            if (elem.className == 'cmp_s') url = url + '&Qnt=0';
        } else if (arr[0] + '' == 'ac') {
            var elem_id = elem.id.substring(1);
            if (document.getElementById(elem_id).className == 'cmp_s') url = url + '&Qnt=0';
        }
    } else 
        var 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 />');
        $('#JaxMasterCompare').html('<a href="javascript:cmp_open();" class="active">Cравнить</a>: товаров ' + msg.GoodsCount);
    } 
    else 
    {
        $('#JaxMasterCompare').html(' ');
        $('#JaxCompare').html(' ');
    }

    if (msg.GoodsCount > 0) {
        $('#Cmp_GoodsBlock').show();
        $('#Cmp_GoodsBlockInfo').html('товаров ' + msg.GoodsCount);
    }
    else {
        $('#Cmp_GoodsBlock').hide();
    }

    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?Action=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) {
        window.location = url.substring(0, url.indexOf('?')) + "?f=" + gparam('f', url) + "&range=" + price_min + ';' + price_max + "&pr=" + gparam('pr', url);
    }
}

function PromoView(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("/jaxcatalog", "/catalog");
        window.location = url.substring(0, url.indexOf('?')) + "?f=" + gparam('f', url) + "&range=" + gparam('range', url) + "&pr=" + type;
    }
}

function page(num) {
    if (!IsIntNum(num)) num = 0;
    if (document.getElementById('PageNum')) {
        document.getElementById('PageNum').value = num;
        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';
        document.forms[0].submit();
    }
}
function PageListSize(elem) {
    if (document.getElementById('PageSize')) {
        document.getElementById('PageSize').value = elem.value;
        document.forms[0].submit();
    }
}
function ListView(type) {
    if (document.getElementById('Miniatures')) {
        document.getElementById('Miniatures').value = type;
        document.forms[0].submit();
    }
}

//------------------------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')", 5000);
    $('#Cart_GoodsCount').html('товаров ' + msg.GoodsCount + ' на сумму ' + msg.CartSum);

    if (msg.GoodsCount > 0) {
        $(".cartL").addClass("cartLink");
        $('#Cart_GoodsBlock').show();
        $('#Cart_GoodsBlockInfo').html('товаров ' + msg.GoodsCount + '<br /> на сумму ' + msg.CartSum);
    }
    else 
    {
        $(".cartLink").addClass("cartL");
        $('#Cart_GoodsBlock').hide();
    }

    try{
        if (parent) parent.$('#Cart_GoodsCount').html('товаров ' + msg.GoodsCount + ' на сумму ' + msg.CartSum);
        if (window.opener) window.opener.$('#Cart_GoodsCount').html('товаров ' + msg.GoodsCount + ' на сумму ' + 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');

    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: 800px; height: 800px;" 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: 800px; height: 800px;" 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")) {
        $.get(RootPath + 'jax/keyboard.aspx', null, function (data) { $('#pop_up_keyboard').html(data); });
        $('#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 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 TreeView(type) {
    if (document.getElementById('tstyle')) {
        document.getElementById('tstyle').value = type;
        document.forms[0].submit();
    }
}
//------------------------menu--------------------------*/
function ShowProp(elem, p_id) {
    var id = 'p' + p_id;
    if (document.getElementById(id)) {
        if (document.getElementById(id).style.display == "none") {
            elem.src = elem.src.replace('lp.gif','lm.gif');
            document.getElementById(id).style.display = "block";
        } else {
            document.getElementById(id).style.display = "none";
            elem.src = elem.src.replace('lm.gif', 'lp.gif');
        }
    }
}

function ShowMultiSelect(id) {
    $('#SSel' + id).hide();
    $('#MSel' + id).show();
}
function MultiSelect(id) {
    var str = '';
    if (document.forms[0].mltsel && document.forms[0].mltsel.checked) {
        str = document.forms[0].mltsel.value + ';';
    } else if (document.forms[0].mltsel) {
        size = document.forms[0].mltsel.length;
        for (i = 0; i < size; i++) {
            if (document.forms[0].mltsel[i] && document.forms[0].mltsel[i].checked) {
                str = str + document.forms[0].mltsel[i].value + ";";
            }
        }
    }

    if (str > '' && window.location) {
        url = window.location.href;
        if (url != null && url != 'undefined' && url.indexOf("catalog") != -1) {
            window.location = url.substring(0, url.indexOf('?')) + "?f=" + gparam('f', url) + str;
        }
    }
}
function showTypes(id) {
    if (document.getElementById(id)) {
        if (document.getElementById(id).style.display == "block")
            document.getElementById(id).style.display = "none";
        else {
            $('div.goods_flt_types').hide();
            document.getElementById(id).style.display = "block";
        }
    }
}

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();
     }
}
