﻿var browser = '';
function DetectBrowser() {
	var ns4 = document.layers; 
	var op5 = (navigator.userAgent.indexOf('Opera 5') != -1) 
		||(navigator.userAgent.indexOf('Opera/5') != -1);
	var op6 = (navigator.userAgent.indexOf('Opera 6') != -1) 
		||(navigator.userAgent.indexOf('Opera/6') != -1);
	var agt = navigator.userAgent.toLowerCase();
	var mac = (agt.indexOf("mac") != -1);
	var ie = (agt.indexOf("msie") != -1); 
	var mac_ie = mac && ie;
	if (ns4) browser = 'ns4';
	if (op5) browser = 'op5';
	if (op6) browser = 'op6';
	if (mac) browser = 'mac';
	if (ie) browser = 'ie';
	if (mac_ie) browser = 'mac_ie';
}
function SortTable(id, dir) {
    var href = document.location.href;
    if (href.indexOf("?" + id + dir) == -1 &&
        href.indexOf("&" + id + dir) == -1) {
        if (href.indexOf('?') != -1) {
            href += "&" + id + dir;
        }
        else {
            href += "?" + id + dir;
        }
        document.location.href = href;
    }
}
function DeleteFromSort(id) {
    var href = document.location.href;
    if (href.indexOf("?" + id + "a") != -1) {
        href = href.replace("?" + id + "a", "?");
        if (href.indexOf("?") == parseInt(href.length - 1)) {
            href = href.replace("?", "");
        }
        href = href.replace("?&", "?");
        document.location.href = href;
        return false;
    }
    if (href.indexOf("?" + id + "d") != -1) {
        href = href.replace("?" + id + "d", "?");
        if (href.indexOf("?") == href.length) {
            href = href.replace("?", "");
        }
        href = href.replace("?&", "?");
        document.location.href = href;
        return false;
    }
    if (href.indexOf("&" + id + "a") != -1) {
        href = href.replace("&" + id + "a", "&");
        if (href.lastIndexOf("&") == href.length - 1) {
            href = href.substring(0, href.length - 1);
        }
        href = href.replace("?&", "?");
        document.location.href = href;
        return false;
    }
    if (href.indexOf("&" + id + "d") != -1) {
        href = href.replace("&" + id + "d", "&");
        if (href.lastIndexOf("&") == href.length - 1) {
            href = href.substring(0, href.length - 1);
        }
        href = href.replace("?&", "?");
        document.location.href = href;
        return false;
    }
}
function SubmitForm() {
    var form_table = document.getElementById("filters-form");
    var inputs = form_table.getElementsByTagName("input");
    var checkboxes = [];
    for (var j = 0; j < inputs.length; j++) {
        if (inputs[j].type == "checkbox" &&
            inputs[j].checked) {
            checkboxes.push(inputs[j]);
        }
    }
    var filters = "";
    for (var i = 0; i < checkboxes.length; i++) {
        
        filters += "f" + checkboxes[i].id + "=" + checkboxes[i].nextSibling.innerHTML + "&";
    }
    if (filters != "") {
        filters = "?" + filters.substring(0, filters.length - 1);
        var form = document.getElementsByTagName("form")[0];
        var action = form.action;
        if (action.indexOf("?") != -1) {
            action = action.substring(0, action.indexOf("?"));
        }
        if (action.indexOf(".aspx") != -1) {
            if (action.indexOf("/") != -1) {
                action = action.substring(0, action.lastIndexOf("/"));
            }
            else {
                action = "";
            }
        }
        if (document.location.href.indexOf("buy") == -1) {
            action += "/buy/computers/" + filters;
            document.location.href = action;
            return;
        }
        form.action = action + "/" + filters;
        setTimeout("document.getElementsByTagName('form')[0].submit();", 100);
    }
    return false;
}
function DeSubmitForm() {
    var form = document.getElementsByTagName("form")[0];
    var action = form.action;
    if (action.indexOf("?") != -1) {
        if (action.indexOf("f_") != -1) {
            action = action.substring(0, action.indexOf("?"));
            if (action.indexOf("buy/computers") != -1) {
                action = "/"
                form.action = action;
                document.location.href = "/";
                return;
            }
            else
                form.action = action + "/";
            
            setTimeout("document.getElementsByTagName('form')[0].submit();", 100);
        }
    }
}
var Basket = function() {
    var goods =  [];
    var AddGoods = function(id_goods, count) {
        var new_goods = {};
        new_goods.id = id_goods;
        new_goods.count = count;
        goods.push(new_goods);
    }
    var DeleteGoods = function(id_goods) {
        var new_goods = [];
        for (var i = 0; i < goods.length; i++) {
            if (goods[i].id != id_goods) {
                new_goods.push(goods[i]);
            }
        }
        goods = new_goods;
    }
    var SetGoods = function(id_goods, count) {
        var pos = GoodsExists(id_goods);
        if (pos > -1) {
            goods[pos].count = count;
        }
        else {
            AddGoods(id_goods, count);
        }
    }
    var GetGoods = function(id_goods) {
        for (var i = 0; i < goods.length; i++) {
            if (goods[i].id == id_goods)
                return {id_goods: id_goods, count: goods[i].count };
        }
        return {id_goods: id_goods, count: -1 };
    }
    var GoodsExists = function(id_goods) {
        for (var i = 0; i < goods.length; i++) {
            if (goods[i].id == id_goods)
                return i;
        }
        return -1;
    }
    this.Open = function() {
        PopupWindow("/my/basket.aspx", "basket", 700, 700, 0, 0);
        return false;
    }
    var ShowBasket = function(id_goods) {
        var coords = Find_ElementCoords("goods-price-add");
        var basket = document.getElementById("Basket_" + id_goods);
        basket.style.display = "block";
        basket.style.visibility = "visible";
        basket.style.left = coords.left + "px";
        basket.style.top = (parseInt(coords.top) - 82) + "px";
        //alert((parseInt(coords.top) - 100) + "px");
    }
    var HideBasket = function(id_goods) {
        document.getElementById("Basket_" + id_goods).style.display = "none";
        document.getElementById("Basket_" + id_goods).style.visibility = "hidden";
    }
    var Create = function(id_goods) {
        var html = "<div id=\"basket-form\">" +
            "<p id=\"basket_goods_present\">Этот товар уже есть в корзине<br /><br /></p>" + 
            "<p id=\"basket_goods_nopresent\">Добавить товар в корзину<br /><br /></p> <p>в количестве" +
            "<input onkeyup=\"bf.isNumber_Validate(this);\" id=\"basket_count_" + id_goods + "\" class=\"basket_goods_count\" type=\"text\" />" +
            "<input id=\"basket_goods_button_ok\" type=\"button\" onclick=\"bf.OK(" + id_goods + ");\" />" + 
            "<input id=\"basket_goods_button_cancel\" type=\"button\" onclick=\"bf.Delete(" + id_goods + ");\" /></p>" + 
        "</div>";
        var basket = document.getElementById("Basket_" + id_goods);
        basket.innerHTML = html;
    }
    this.Get = function(id_goods) {
        this.ShowPreloder(id_goods);
        var reqOptions = new RequestOptions();
        reqOptions.completeFunction = bf.Get_OnComplete;
        reqOptions.completeFunction_Args = id_goods;
        reqOptions.errorFunction = function(text, args) {};
        reqOptions.requestPage = "basket";
        reqOptions.Add("action", "get");
        reqOptions.Add("id", id_goods);
        var isConnect = createRequest();
        if (isConnect) {
            processRequest(reqOptions);
        }
        else {
            alert("Не удалось соединится с удаленным хостом, попробуйте еще раз.");
        }
    }
    this.Save = function(id_goods, count) {
        this.ShowPreloder(id_goods);
        var reqOptions = new RequestOptions();
        reqOptions.completeFunction = bf.Save_OnComplete;
        reqOptions.completeFunction_Args = id_goods;
        reqOptions.errorFunction = function(text, args) { alert("error"); };
        reqOptions.requestPage = "basket";
        reqOptions.Add("action", "add");
        reqOptions.Add("id", id_goods);
        reqOptions.Add("count", count);
        var isConnect = createRequest();
        if (isConnect) {
            processRequest(reqOptions);
        }
        else {
            alert("Не удалось соединится с удаленным хостом, попробуйте еще раз.");
        }
    }
    this.Update = function(id_goods, count) {
        this.ShowPreloder(id_goods);
        var reqOptions = new RequestOptions();
        reqOptions.completeFunction = bf.Save_OnComplete;
        reqOptions.completeFunction_Args = id_goods;
        reqOptions.errorFunction = function(text, args) {};
        reqOptions.requestPage = "basket";
        reqOptions.Add("action", "update");
        reqOptions.Add("id", id_goods);
        reqOptions.Add("count", count);
        var isConnect = createRequest();
        if (isConnect) {
            processRequest(reqOptions);
        }
        else {
            alert("Не удалось соединится с удаленным хостом, попробуйте еще раз.");
        }
    }
    this.Delete = function(id_goods) {
//        if (GetGoods(id_goods).count != -1) {
//            this.ShowPreloder(id_goods);
//            var reqOptions = new RequestOptions();
//            reqOptions.completeFunction = bf.Delete_OnComplete;
//            reqOptions.completeFunction_Args = id_goods;
//            reqOptions.errorFunction = function(text, args) { alert(text); };
//            reqOptions.requestPage = "basket";
//            reqOptions.Add("action", "delete");
//            reqOptions.Add("id", id_goods);
//            var isConnect = createRequest();
//            if (isConnect) {
//                processRequest(reqOptions);
//            }
//            else {
//            
//            }
//        }
//        else {
//            HideBasket(id_goods);
//        }
        HideBasket(id_goods);
    }
    this.OK = function(id_goods) {
        if (GoodsExists(id_goods) != -1) {
            var new_count = document.getElementById("basket_count_" + id_goods).value;
            if (GetGoods(id_goods).count != new_count &
                GetGoods(id_goods).count != "-1") {
                this.Update(id_goods, new_count);
            }
            else {
                if (GetGoods(id_goods).count == "-1") {
                    this.Save(id_goods, new_count);
                }
                else {
                    HideBasket(id_goods);
                }
            }
        }
        else {
            //error
        }
    }
    this.Get_OnComplete = function(text, args) {
        SetGoods(args, text);
        if (text != "-1") {
            document.getElementById("basket_goods_present").style.display = "block";
            document.getElementById("basket_goods_nopresent").style.display = "none";
        }
        else {
            document.getElementById("basket_goods_present").style.display = "none";
            document.getElementById("basket_goods_nopresent").style.display = "block";
        }
        if (text == "-1") {
            text = "1";
        }
        document.getElementById("basket_count_" + args).value = text;
        bf.HidePreloder();
    }
    this.Show = function(id_goods) {
        if (GoodsExists(id_goods) == -1) {
            Create(id_goods);
        }
        ShowBasket(id_goods);
        this.Get(id_goods);
    }
    
    this.DeleteAll = function() {
    
    }
    this.Save_OnComplete = function(text, args) {
        var txt = text.substring(0, text.indexOf(" "));
        SetGoods(args, txt);
        bf.HidePreloder();
        HideBasket(args);
        UpdateBasketCount(text);
    }
    this.Save_OnError = function(text, args) {
    
    }
    this.Delete_OnComplete = function(text, args) {
        DeleteGoods(args);
        bf.HidePreloder();
        HideBasket(args);
    }
    this.ShowPreloder = function(id_goods) {
    
        if (document.getElementById("basket_form_preloder") == null) {
        
            var div = document.createElement("div");
            
            div.id = "basket_form_preloder";
            div.style.position = "absolute";
            //div.style.backgroundImage = "url(/images/empty_pixel.png)";
           div.style.zIndex=3;
            
            var s = Get_ElemSize("Basket_" + id_goods);
            
            var c = Find_ElementCoords("Basket_" + id_goods);
            
            div.style.left = c.left + 114 + "px";
            div.style.top = (parseInt(c.top) + 119) + "px";
            div.style.width = 20 + "px";
            div.style.height = 20 + "px";
            div.innerHTML = "<img src=\"/images/loader.gif\" />";
            document.getElementById("Basket_" + id_goods).appendChild(div);
        }
        else {
            document.getElementById("basket_form_preloder").style.display = "block";
        }
    }
    this.HidePreloder = function() {
        setTimeout("document.getElementById(\"basket_form_preloder\").style.display = \"none\"", 10);
    }
    var Find_ElementCoords = function(id) {
        var obj = document.getElementById(id);
        var currLeft = 0;
        var currTop = 0;
        if (obj.offsetParent) {
            currLeft = obj.offsetLeft;
            currTop = obj.offsetTop;
            while (obj = obj.offsetParent) {
                //currLeft += obj.offsetLeft;
                //currTop += obj.offsetTop;
            }
        }
        return { left: currLeft, top: currTop };
    }
    this.isNumber_Validate = function(input) {
        if(input.value.length > 0 && !input.value.match(/^[0-9]+$/g)) {
           input.value = input.value.replace(/[^0-9]*/g,'');
           window.alert("Вводите только цифры!");
        }
        else {
            if (parseInt(input.value)==0)
                input.value = "1";
        }
    }
}
var bf = new Basket();

function Get_ElemSize(id) {
    var width = Get_ElemSizeWidthById(id);
    var height = Get_ElemSizeHeightById(id);
    return [width, height];
}
function Get_ElemSizeHeightById(id) {
    if (browser == '') DetectBrowser();
    var obj = document.getElementById(id);
    if (browser == 'ns4')
        return obj.clip.height;
    if (browser == 'op5')
        return obj.style.pixelHeight;
    else
        return obj.offsetHeight;
}
function Get_ElemSizeWidthById(id) {
    if (browser == '') DetectBrowser();
    var obj = document.getElementById(id);
    if (browser == 'ns4')
        return obj.clip.width;
    if (browser == 'op5')
        return obj.style.pixelWidth;
    else
        return obj.offsetWidth;
}
function PopupWindow(url, name, width, height, top, left) {
    left = parseInt((getWidthHeight().width - width) / 2);
    var properties = 'location=yes,width='+width+',height='+height+',top='+top+',left='+left+
    'toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=yes,resizable=yes';
    popupWin = window.open(url, name, properties); 
    popupWin.focus();
}
function getWidthHeight() {
    var w = 0;
    var h = 0;
    if (typeof(window.innerWidth) == 'number') {
    //Non-IE
        w = window.innerWidth;
        h = window.innerHeight;
    }
    else 
    if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
    //IE 6+ in 'standards compliant mode'
        w = document.documentElement.clientWidth;
        h = document.documentElement.clientHeight;
    }
    else 
    if (document.body && (document.body.clientWidth || document.body.clientHeight )) {
        //IE 4 compatible
        w = document.body.clientWidth;
        h = document.body.clientHeight;
    }
    return {width:w,height:h};
}
function MonitoringBasket() {
    document.location.href = "/my/cabinet.aspx"
}
function UpdateBasketCount(str_count) {
    var basket = document.getElementById("basket");
    var a = basket.getElementsByTagName("a")[0];
    if (str_count == "пусто" || str_count == "0") {
        a.onclick = function() {
            return false;
        }
        a.innerHTML = "В корзине: пусто";
    }
    else {
        a.onclick = function() {
            PopupWindow('/my/basket.aspx', 'basket', 700, 600, 0, 0); 
            return false;
        }
        a.innerHTML = "В корзине: " + str_count;
    }
    return false;
}
function RequestBasketCount() {
    var reqOptions = new RequestOptions();
    reqOptions.completeFunction = BasketCount_OnComplete;
    reqOptions.errorFunction = function(text, args) {};
    reqOptions.requestPage = "basket";
    reqOptions.Add("action", "getcount");
    var isConnect = createRequest();
    if (isConnect) {
        processRequest(reqOptions);
    }
    else {
        alert("Не удалось соединится с удаленным хостом, попробуйте еще раз.");
    }
}
function BasketCount_OnComplete(text, args) {
    UpdateBasketCount(text);
}
function search1() {
    var q = document.getElementById("search").value;
    if (q != "") {
        var buy = "computers";
        var h = document.location.href;
        if (h.indexOf("buy/") != -1) {
            buy = h.substring(h.indexOf("buy/") + 4);
        }
        if (h.indexOf("buy-") != -1) {
            buy = h.substring(h.indexOf("buy-") + 4);
        }
        document.location.href = "/search.aspx?q=" + q + "&buy=" + buy;
    }
    return false;
}
function submitform(event) {
    var code = 0;  
    var NS4 = (document.layers) ? true : false;
    if (NS4)
        code = event.which;
    else
        code = event.keyCode;
    if (code == 13) {
        return search1();
    }
}
