/*
function include(url) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript')
script.setAttribute('src', url);
document.getElementsByTagName('head').item(0).appendChild(script);
}

include("Scripts/ProsoftJS.js"); 

var Namespace = {
    Register: function(name) {
        var currentObj = "";
        var objParts = name.split(".");
        for (var i = 0; i < objParts.length; i++) {
            if (currentObj != "") currentObj += ".";
            currentObj += objParts[i];
            if (!this.Exists(currentObj)) this.Create(currentObj);
        }
    },

    Create: function(name) {
        eval(name + " = typeof(" + name + ") =='undefined' ? {} : " + name + "; ");
    },

    Exists: function(name) {
        var result = false;
        eval("try{if(" + name + "){result = true;}}catch(ex){}");
        return result;
    }
}

Namespace.Register("ProsoftJS");
*/
ProsoftJS = {}
ProsoftJS.TabControl = function(controlID, contentID) {
    var tabControl = Ext.get(controlID);
    var contentContainer = Ext.get(contentID);
    var tabs = tabControl.select('li', true);
    var contents = contentContainer.select('.tabContent', true);

    this.CreateTabs = function() {

        var i = 0;
        var contNumber = 0;
        for (i = 0; i < tabs.getCount(); i++) {
            if (tabs.item(i).select('a').item(0) != null && contents.item(contNumber) != null) {
                contents.item(contNumber).setVisibilityMode(Ext.Element.DISPLAY);
                tabs.item(i).select('a').item(0).dom.href = "javascript:void(0)";
                tabs.item(i).select('a').item(0).on('click', ActivateTab);
                contNumber++;
            }
        }

        /*tabs.each(function(tab) {

        if (tab.select('a').item(0) != null) {
        tab.content = curContent;
        tab.content.setVisibilityMode(Ext.Element.DISPLAY);
        tab.select('a').item(0).dom.href = "javascript:void(0)";
        tab.select('a').item(0).on('click', ActivateTab);
        curContent = curContent.next();
        }

        });*/
    }

    ActivateTab = function(e) {

        //var prevTab;
        var i = 0;
        var contNumber = 0;

        for (i = 0; i < tabs.getCount(); i++) {

            if (tabs.item(i).select('a').item(0) != null) {

                tabs.item(i).select('div').item(0).removeClass('active');
                tabs.item(i).select('div').item(0).removeClass('preactive');
                contents.item(contNumber).setVisible(false);

                if (tabs.item(i).select('a').item(0).dom == e.getTarget()) {
                    tabs.item(i).select('div').item(0).addClass('active');
                    if (i > 0) { tabs.item(i - 1).select('div').item(0).addClass('preactive'); }
                    contents.item(contNumber).setVisible(true);
                }

                contNumber++;
            }
        }

        /*
        tabs.each(function(tab) {

            if (tab.select('a').item(0) != null) {

                tab.select('div').item(0).removeClass('active');
        tab.select('div').item(0).removeClass('preactive');
        tab.content.setVisible(false);

                if (tab.select('a').item(0).dom == e.getTarget()) {
        tab.select('div').item(0).addClass('active');
        if (prevTab) { prevTab.select('div').item(0).addClass('preactive'); }
        tab.content.setVisible(true);
        }
        prevTab = tab;
        }
        });
        */
        return false;
    }
}

Ext.onReady(function() {
    tuneStyles();

    if (Ext.get('searchTabs') != null) {
        var tabControl = new ProsoftJS.TabControl('searchTabs', 'searchforms');
        tabControl.CreateTabs();
    }

    if (Ext.get('catalogTabHeaders') != null) {
        var catalogTabControl = new ProsoftJS.TabControl('catalogTabHeaders', 'catalogTabs');
        catalogTabControl.CreateTabs();

        SetStartTab();
    }

    SitesMenuStartUp();
});

SetStartTab = function() {
    // Если находимся в разделе классификатора по брендам, то переключаемся на вкладку брендов
    if (document.location.pathname.toLowerCase().search("/products/brands/") >= 0) {

        var contentContainer = Ext.get('catalogTabs');
        var contents = contentContainer.select('.tabContent', true);

        contents.item(0).setVisible(false);
        contents.item(1).setVisible(true);
    }
}

/* Функция скрытия/развертывания меню подсайтов */
SitesMenuStartUp = function() {
    var element = Ext.select('.sitesmenu-switch');    
    element.on('click', HideShowSitesMenu);
    return false;
}

HideShowSitesMenu = function(e) {
    var container = Ext.select('.sitesmenu-container');
    var linkElement = Ext.select('.sitesmenu-switchlink', true);
    var iconElement = Ext.select('.sitesmenu-switch-icon', true);
    container.setVisibilityMode(Ext.Element.DISPLAY);

    if (iconElement.elements[0].className.indexOf('hide') != -1) {
        container.hide();
        iconElement.replaceClass('hide', 'show');
        linkElement.update('Показать все направления');
    }
    else {
        container.show();
        iconElement.replaceClass('show', 'hide');
        linkElement.update('Скрыть все направления');
    }

    return false;
}
/* ----Функция скрытия/развертывания меню подсайтов---- */

function tuneStyles() {
    if (Ext.isOpera || (Ext.isIE && !Ext.isIE7 && !Ext.isIE8)) {
        //Ext.get('liSearch1').setStyle('position', 'relative');
        //Ext.get('liSearch1').setStyle('right', '-1px');
        var elem = Ext.get('liSearch2');
        if (elem != null) {
            elem.setStyle('position', 'relative');
            elem.setStyle('right', '-1px');
        }
    }
}

/*Ф-ция, вызываемая из IE6.css*/
/*function getTop(searchForm) {
    if (searchForm.className == "searchform first-activated") {
        if (searchForm.style.display == "none")
            return "-1px";
            //return -searchForm.clientTop + "px";
    }
    else {
        return "-1px";
        //return -searchForm.clientTop + "px";
    }
}*/

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/
var Url = {

    // public method for url encoding
    encode: function(string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function(string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function setParBlockVis(treeid) {
    var tree = document.getElementById(treeid);
    if (tree) {
        changeDisplay(tree.firstChild.firstChild.lastChild);
    }
}

function changeDisplay(element, disp) {
    if (element) {
        if (!disp) { disp = 'block'; }
        if (element.style.display == 'none') {
            element.style.display = disp;
        }
        else {
            element.style.display = 'none';
        }
    }
}

// Поиск по складу
function stockSearch(initialValue, isSalePage, extraparams) {
    var searchInput = document.getElementById("orderNumberForStockSearch");
    var orderNo = searchInput.value == initialValue ? '' : searchInput.value;

    if (initialValue == orderNo)
        orderNo = '';

    var onlyOrder = "0", brand = "", type = "", ctrl, errCtrl = null;

    if (extraparams) {
        var params = extraparams.split(",");

        if (params && params.length > 0) {
            ctrl = document.getElementById(params[0]);
            if (ctrl && ctrl.checked)
            { onlyOrder = "1"; }
        }
        if (params && params.length > 1) {
            ctrl = document.getElementById(params[1]);
            if (ctrl && ctrl.selectedIndex > 0)
            { brand = ctrl.options[ctrl.selectedIndex].value; }
        }
        if (params && params.length > 2) {
            ctrl = document.getElementById(params[2]);
            if (ctrl && ctrl.selectedIndex > 0)
            { type = ctrl.options[ctrl.selectedIndex].value; }
        }
        if (params && params.length > 3) {
            errCtrl = document.getElementById(params[3]);
        }
    }

    if (isSalePage) {
        document.location = '/products/sale/?orderNo=' + escape(orderNo) + '&pageNo=1&onlyOrder=' + onlyOrder + '&brand=' + brand + '&type=' + type;
    }
    else {
        var searchInSale = document.getElementById("stockSearchInSale").checked;

        if ((orderNo != '' && orderNo.length > 2) || searchInSale) {
            if (searchInSale) {
                document.location = '/products/sale/?orderNo=' + escape(orderNo) + '&' + "&pageNo=1&onlyOrder=" + onlyOrder + '&brand=' + brand + '&type=' + type;
            }
            else {
                document.location = '/products/stocksearch/?orderNo=' + escape(orderNo) + '&' + 'searchInSale=' + searchInSale + "&pageNo=1&onlyOrder=" + onlyOrder + '&brand=' + brand + '&type=' + type;
            }
        }
        else {
            if (errCtrl) {
                errCtrl.style.display = 'inline';
            } else {
                alert('Необходимо ввести номер для заказа (не менее 3 символов).');
            }
        }
    }

    return false;
}

// Параметрический поиск по каталогу продукции
function parCatalogSearch(initialValue, isSalePage) {

    var hidd = document.getElementById("pstreecontid");

    if (!hidd || hidd.value == "") {
        alert("не найден идентификатор элемента каталога");
        return false;
    }

    var url = window.location.pathname + "?eid=" + hidd.value;
    hidd = document.getElementById("pstreeisext");
    if (hidd && hidd.value && hidd.value != "")
        url += "&ext=" + hidd.value;

    var evl = "", tvl = "", fvl = "", rvl = "", star, skiplist = "";

    var block = document.getElementById("pstree");

    var tags = block.getElementsByTagName("input");

    if (tags) {
        for (var i = 0; i < tags.length; i++) {
            var ctrl = tags[i];
            if (skiplist.indexOf(ctrl.id) >= 0) continue;

            var typeid = ctrl.id.match(/tp(\d+)_.*/)[1];

            /* начало: логические параметры */
            if (/.*_yes$/.test(ctrl.id) && ctrl.checked) {
                star = tvl == "" ? "" : "*";
                tvl = tvl + star + typeid;
            }

            if (/.*_no$/.test(ctrl.id) && ctrl.checked) {
                star = fvl == "" ? "" : "*";
                fvl = fvl + star + typeid;
            }
            /* конец: логические параметры */

            /* начало: диапазоны */
            if (/^(.+)_div(\d+)_gt$/.test(ctrl.id) || /^(.+)_div(\d+)_lt$/.test(ctrl.id)) {
                var cgt, clt;

                if (/^(.+)_div(\d+)_gt$/.test(ctrl.id)) {
                    cgt = ctrl;
                    clt = document.getElementById(ctrl.id.replace(/_gt$/, "_lt"));
                    skiplist = skiplist + "|" + clt.id;
                } else {
                    clt = ctrl;
                    cgt = document.getElementById(ctrl.id.replace(/_lt$/, "_gt"));
                    skiplist = skiplist + "|" + cgt.id;
                }

                var v1, v2, u1, u2;

                if (cgt.className == "active") {
                    v1 = cgt.value;
                    u1 = cgt.id.match(/_ud(\d*)_/)[1];
                }else{
                    v1 = "";
                    u1 = "";
                }

                if (clt.className == "active") {
                    v2 = clt.value;
                    u2 = clt.id.match(/_ud(\d*)_/)[1];
                }else{
                    v2 = "";
                    u2 = "";
                }

                if (u1 + u2 + v1 + v2 != "") {
                    star = rvl == "" ? "" : "#";
                    rvl = rvl + star + typeid + "*" + v1 + "*" + u1 + "*" + v2 + "*" + u2;
                }
            }
            /* конец: диапазоны */

            /* начало: списки */
            if (/^(.+)_opt(\d+)$/.test(ctrl.id)) {
                var optbase = ctrl.id.match(/^((.+)_opt)(\d+)$/)[1];
                var ii = 1, orlist = "";
                ctrl = document.getElementById(optbase + ii.toString());

                while (ctrl != null && ii < 100) {
                    skiplist = skiplist + "|" + ctrl.id;

                    if (ctrl.checked) {
                        var v3 = ctrl.getAttribute("xmlvalue").trim();
                        var u3 = ctrl.getAttribute("xmlunitid");
                        if (v3 && v3 != "") {
                            star = orlist == "" ? "" : "*";
                            orlist = orlist + star + v3 + "*" + (u3 ? u3 : "");
                        }
                    }

                    ii += 1;
                    ctrl = document.getElementById(optbase + ii.toString());
                }

                if (orlist && orlist != "") {
                    star = evl == "" ? "" : "#";
                    evl = evl + star + typeid + "*" + orlist;
                }
            }
            /* конец: списки */
        }
    }

    if (evl + rvl + tvl + fvl == "") {
        alert(initialValue);
    }
    else {
        url = url + "&evl=" + Url.encode(evl) + "&rvl=" + Url.encode(rvl) + "&tvl=" + Url.encode(tvl) + "&fvl=" + Url.encode(fvl) + "&pageNo=1";
        //alert(url);

        window.location = url;
    }

    return false;
}

function siteSearch(initialValue) {
    var searchInput = document.getElementById("valueForSiteSearch");
    var value = searchInput.value == initialValue ? '' : searchInput.value;

    if (value != '') {
        document.location = '/search/?query=' + escape(value);
    }
    else {
        alert('Необходимо ввести условие поиска.');
    }

    return false;
}

function catalogSearch(initialValue, minLength, extraparams) {
    var searchInput = document.getElementById("orderNumberForCatalogSearch");

    var onlyOrder = "0", brand = "", type = "", ctrl, errCtrl = null;
    if (extraparams) {
        var params = extraparams.split(",");

        if (params && params.length > 0) {
            ctrl = document.getElementById(params[0]);
            if (ctrl && ctrl.checked)
                onlyOrder = "1";
        }
        if (params && params.length > 1) {
            ctrl = document.getElementById(params[1]);
            if (ctrl && ctrl.selectedIndex > 0)
                brand = ctrl.options[ctrl.selectedIndex].value;
        }
        if (params && params.length > 2) {
            ctrl = document.getElementById(params[2]);
            if (ctrl && ctrl.selectedIndex > 0)
                type = ctrl.options[ctrl.selectedIndex].value;
        }
        if (params && params.length > 3) {
            errCtrl = document.getElementById(params[3]);
        }
    }

    if (searchInput) {
        var value = searchInput.value;
        if (searchInput.value == initialValue) {
            if (errCtrl) {
                errCtrl.style.display = 'inline';
            } else {
                alert(initialValue);
            }
        } else if (value.length < minLength) {
            if (errCtrl) {
                errCtrl.style.display = 'inline';
            } else {
                alert('Необходимо ввести как минимум ' + minLength.toString() + ' символа');
            }
        } else {
            document.location = '/products/catalogsearch/?orderNo=' + escape(value) + '&woquantcheck=true&searchInSale=false&pageNo=1&onlyOrder=' + onlyOrder + '&brand=' + brand + '&type=' + type;
        }
    }

    return false;
}

function onSearchKeyPressed(e, searchType, initialValue, isSalePage, extraparams) {
    e = e || window.event;
    var code = e.keyCode || e.which;

    if (code == 13) {
        if (searchType == 'stockSearch') {
            stockSearch(initialValue, isSalePage, extraparams);
        } else if (searchType == 'siteSearch') {
            siteSearch(initialValue);
        } else if (searchType == 'parCatalogSearch') {
            parCatalogSearch(initialValue, isSalePage);
        } else if (searchType == 'catalogSearch') {
            catalogSearch(initialValue, isSalePage, extraparams);
        }

        return false;
    }

    return true;
}

function handleKeyPress(e) {
    if (e.ctrlKey && (e.getKey() == Ext.EventObject.ENTER || e.getKey() == 10 || e.getKey() == 13)) {
        e.preventDefault();
        
        var text;

        if (document.selection) {
            text = document.selection.createRange().text;
        }
        else if (typeof document.getSelection == 'function') {
            text = document.getSelection();
        }
       
        if (text != '') {
            Prosoft.ProsoftWebSite.Web.WebServices.SendCommonInfoService.SendPageTextError(
                document.location.href, text, sendPageTextErrorCompleted, sendPageTextErrorFailed);
        }
        else {
            alert('Необходимо выделить соответствующий текст с ошибкой.');
        }
    }
}

function sendPageTextErrorCompleted(result) {
    alert('Информация об ошибке отправлена в службу поддержки сайта. Спасибо.');
}

function sendPageTextErrorFailed(error) {
    alert('Информация об ошибке не может быть отправлена: ' + error.get_message()+'.');
}

Ext.onReady(function() {
    Ext.EventManager.on(document, "keypress", handleKeyPress);
});


function Order()
{
}

function OrderLine(productID, productName)
{
    this.productID = productID;
    this.productName = productName;
    this.quantity = 0;
}

Order.prototype = 
{
    currentOrderLine: new OrderLine(0, '', 0),
    
    AddOrderLine: function()
    {
        Prosoft.ProsoftWebSite.Web.WebServices.OrderService.AddProductToOrder(this.currentOrderLine.productID, this.currentOrderLine.productName, this.currentOrderLine.quantity, this.AddProductCompleted, this.AddProductFailed);
    },
    
    AddProductCompleted: function(result)
        {
            if(typeof OrderCompleted == 'function')
                OrderCompleted(result);
        },    
        
    AddProductFailed: function(error)
        {
            //alert(error._message);
            
            if(typeof OrderFailed == 'function')
                OrderFailed(error);
        }    
}

order = new Order();

function SetProductID(productID)
{
    order.currentOrderLine.productID = productID;
}

function SetProductName(productName)
{
    order.currentOrderLine.productName = productName;
}

function SetProductQuantity(quantity)
{
    order.currentOrderLine.quantity = quantity;
}

function MakeOrder()
{
    order.AddOrderLine();
}



/*
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
    TargetControlID="customTextBox"
    ServiceMethod="GetOrderCompletionList"
    ServicePath="../../WebServices/OrderService.asmx"
    MinimumPrefixLength="2" 
    CompletionInterval="1000"
    EnableCaching="true"
    CompletionSetCount="12" 
>
</cc1:AutoCompleteExtender>
*/

/* заказ продукции - вынесено из Products/OrderBlock.ascx */
Ext.onReady(function() {
    Ext.EventManager.on(document, "click", handleClick);
});

// Закрытие формы заказа при клике вне формы
function handleClick(e, t) {
    var orderForm = Ext.get('orderForm');

    if (!e.within(orderForm) && orderDialogVisible && !orderDialogOpening) {

        closeOrderDialog();
    }

    orderDialogOpening = false;
}

// Показывается ли в текущий момент форма заказа
var orderDialogVisible = false;

// Открывается ли в текущий момент форма заказа
var orderDialogOpening = false;

// Показ формы заказа
function showOrderDialog(el, productID, orderName, contentElementID, price, isSale, unit, productName) {
    Ext.getDom('quantityContent').style.display = 'block';
    Ext.getDom('successContent').style.display = 'none';
    Ext.getDom('errorContent').style.display = 'none';
    Ext.getDom('quantity').value = '1';

    var orderForm = Ext.get('orderForm');

    // Сохраняем переданные данные заказа продукта
    orderForm.productID = productID;
    orderForm.orderName = orderName;
    orderForm.contentElementID = contentElementID;
    orderForm.price = price;
    orderForm.isSale = isSale;
    orderForm.unit = unit;
    orderForm.productName = productName;

    var coordinates = Ext.get(el).getXY();

    orderForm.fadeIn({ duration: 0.4 });
    orderForm.setLocation(coordinates[0] - 70, coordinates[1] - 100);
    Ext.getDom('quantity').focus();

    orderDialogVisible = true;
    orderDialogOpening = true;
}

// Закрытие формы заказа
function closeOrderDialog() {
    Ext.get('orderForm').fadeOut();
    orderDialogVisible = false;
}

// Заказ продукта
// Если baseUrl не null, то работает схема статического каталога
function orderProduct(baseUrl) {
    var quantity = Ext.getDom('quantity').value;

    if (isNumeric(quantity)) {
        var orderForm = Ext.get('orderForm');

        if (baseUrl) {
            orderLocal(orderForm, quantity, baseUrl);
        } else {
            Prosoft.ProsoftWebSite.Web.WebServices.SendCommonInfoService.AddProduct(
                orderForm.orderName, quantity, orderForm.contentElementID,
                orderForm.price, orderForm.isSale, orderForm.unit, orderForm.productName, orderCompleted, orderFailed);
        }
    }

    return false;
}

// Заказ продукта по нажатию Enter
function onOrderKeyPressed(e) {
    e = e || window.event;
    var code = e.keyCode || e.which;

    if (code == 13) {

        orderProduct();
        return false;
    }

    return true;
}

// Заказ завершен успешно
function orderCompleted(result) {
    Ext.getDom('quantityContent').style.display = 'none';
    Ext.getDom('successContent').style.display = 'block';
}

// Заказ завершен с ошибкой
function orderFailed(error) {
    //alert('Order failed: ' + error.get_message() + '.');
    Ext.getDom('quantityContent').style.display = 'none';
    Ext.getDom('errorContent').style.display = 'block';
}

// Является ли значение числовым
function isNumeric(value) {
    if (value == null || !value.toString().match(/^[-]?\d*[\.|,]?\d*$/)) return false;
    return true;
}

function orderLocal(orderForm, quantity, baseUrl) {
    var req_params, url;

    /* ВАЖНО: в web.config этого сайта д/б прописано следующее

    </system.web>
      <webServices>
        <protocols>
           <add name="HttpGet"/>
           <add name="HttpPost"/>
        </protocols>
      </webServices>
    </system.web>

    */
    url = baseUrl + "/WebServices/SendCommonInfoService.asmx/AddProduct";

    req_params = "orderNumber=" + orderForm.orderName
            + "&quantity=" + quantity
            + "&contentElementID=" + orderForm.contentElementID
            + "&price=" + orderForm.price
            + "&isSale=" + orderForm.isSale
            + "&unit=" + orderForm.unit
            + "&productName=" + orderForm.productName;

    dynamicTag(url + "?" + req_params);
    return false;
}

/* этот трик нужен, т.к. XmlHTMLRequest не допускает кроссдоменные вызовы */
function dynamicTag(url) {
    var request = url;
    try {
        var ctrl = document.getElementById("chscr");
        var script = document.createElement("img");
        script.setAttribute("src", request);
        var child = ctrl.firstChild;
        if (child) {
            ctrl.removeChild(child);
        }
        ctrl.appendChild(script);
        orderCompleted(null);
    } catch (e) {
        orderFailed(e);
    }
}

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();