﻿var code = 0;
var close = true;
var inProcess = false;
var page = 1;
var selectedPage = 0;
var productInfo = null;

var animated = false;
var direction = "";

var frameWidth = 920;
var tout = 0;

function init()
{
    try
    {
        $("imgClose").observe("click", closeInfo);
        $("imgProduct").observe("click", closeInfo);
        
        $("aPreviuosPage").href = "javascript:void(0);";
        $("aNextPage").href = "javascript:void(0);";
        $("aPreviuosPage").observe("click", getPage);
        $("aNextPage").observe("click", getPage);
        
        $("textPreviuosPage").href = "javascript:void(0);";
        $("textNextPage").href = "javascript:void(0);";
        $("textPreviuosPage").observe("click", getPage);
        $("textNextPage").observe("click", getPage);
        
        $("plist").observe("click", closeInfo);
        
        frameWidth = $("content").getWidth() - 50;
        $("frameContent").width = frameWidth;
        
        Event.observe(window, "resize", resizeFrame);
    }
    catch(ex) { }
}
function getPage()
{
    if (inProcess)
        return;
        
    if (this.id == "aPreviuosPage" || this.id == "textPreviuosPage")
    {
        page = page - 1;
        direction = "left";
    }
    else if (this.id == "aNextPage" || this.id == "textNextPage")
    {
        page = page + 1;
        direction = "right";
    }
    else
    {
        if (selectedPage < page)
        {
            page = selectedPage;
            direction = "left";
        }
        else
        {
            page = selectedPage;
            direction = "right";
        }
    }
        
    code = "page_" + page;
    $("loader").setStyle({ display: "block" });   
    callback();
}
function orderGarniture(id)
{
    if (inProcess)
        return;
        
    code = "garniture_" + id;
    callback();
}
function openInfo(id)
{
    if (inProcess)
        return;
        
    //code = "get_" + id;
    $("loader").setStyle({ display: "block" });  
    //callback();  
    new Ajax.Request(appPath + "/product.ashx",
    {
        parameters: { id: id },
	    onSuccess: function(transport)
	    {
	        $("loader").setStyle({ display: "none" });
               showInfo(transport.responseText.evalJSON());
               inProcess = false;
	    },
	    onFailure: function(transport)
        {
    	    $("loader").setStyle({ display: "none" });
    	    inProcess = false;
        }
    });
}
function compare()
{
    if (inProcess)
        return;
        
    code = "compare_" + code.split("get_")[0];
    $("loader").setStyle({ display: "block" });  
    callback();  
}
function order()
{
    
    if (inProcess)
        return false;
        
    if (code.indexOf("page_") > -1 || code.indexOf("get_") > -1)
        return true;
        
    if (code.indexOf("compare_") > -1)    
        return true;
        
    $("imgOrder").hide();
    $("imgCompare").hide();
    $("imgLoad").show();
    
    close = true;
    
    if (code.indexOf("garniture_") > -1)
    {
        code = code.split("garniture_")[1];
        close = false;
    }
    else
    {  
        try
        {
            yaCounter1354365.reachGoal('AddToBasket');
        }
        catch(ex) { }
        if (productInfo.Emplements.length > 1)
        {
            var selectedEmplement = 0;
            productInfo.Emplements.each(function(item, index)
                {
                    if ($("emplement_" + item.ID) && $("emplement_" + item.ID).checked)
                    {
                        selectedEmplement = item.ID;
                        throw $break;
                    }
                }
            );
            if (selectedEmplement == 0)
            {
                alert("Выберите вариант изделия!");
                return false;
            }
            else
                code = "" + selectedEmplement; 
            if ($("ddlEmplementSize"))
                code += "_" + $("ddlEmplementSize").value;     
        }   
        if ($("divRingSize").style.display == "")
            code += "_" + $("ddlRingSize").value; 
    }
    
    return true;
}
function callBackEvent(args)
{
    if (code.indexOf("get_") == 0)
    {
        $("loader").setStyle({ display: "none" });
        showInfo(args.evalJSON());
    }
    else if (code.indexOf("compare_") == 0)
    {
        $("loader").setStyle({ display: "none" });
        $("divCompareState").update(args);
        closeInfo(null);
        
        var coords = $("plist").cumulativeOffset();
        $("messageContainer").setStyle({ left: coords.left + ($("plist").getWidth() - $("messageContainer").getWidth()) / 2 - 30 + "px", top: coords.top + document.viewport.getScrollOffsets().top / 2 + 50 + "px" });
        $("messageContainer").update("Изделие добавлено к сравнению!");
        $("messageContainer").show();
        closeInfo(null);
        clearTimeout(tout);
        tout = setTimeout("hideMessage();", 1000);
    }
    else if (code.indexOf("page_") == 0)
    {        
        var list = args.evalJSON();
        
        var previuosFrame = null;
        
        if (direction == "left")
            previuosFrame = $$("div.frame")[0].remove();
            
        var nextFrame = $c("div", "", $("frameContainer"));
        
        if (direction == "left")
        {
            new Insertion.After(nextFrame, previuosFrame);
            $("frameContainer").setStyle({left: "-" + frameWidth + "px" });    
        }    
            
        nextFrame.addClassName("frame");
        nextFrame.setStyle({ height: "780px" });
        var table = $c("table", "frameContent", nextFrame);
        table.width = frameWidth + "px";
        table = $c("tbody", "", table);
        
        var tr = null;
        for (var i = 0; i < list.size(); ++i)
        {
            if (i % 4 == 0)
                tr = $c("tr", "", table);
            var td = $c("td", "", tr); 
            
            td.align = "center";
            
            var innerHtml = "";//"<a href='" + appPath + "/cart.aspx?id=" + list[i].ID + "'><img src='" + appPath + "/ii/addcart.gif' alt='Купить подарок' style='cursor: pointer; position: absolute; margin: 110px 0px 0px 110px' /></a>";
            if (list[i].PreviewImage)
            {
                innerHtml += "<a href='javascript:void(0);' onclick=\"openInfo('" + list[i].ID + "');\">";
                innerHtml += "<img src='" + list[i].PreviewImage + "'title='" + list[i].Name + "' alt='" + list[i].Name + "' />";
                innerHtml += "</a><div style='clear: both'></div>";
            }
            else
                innerHtml = "<div style='width:150px; height: 150px; border: solid 1px #666; background-color: #eee; text-align: center'></div>";
                
            innerHtml += "<a href='javascript:void(0);' onclick=\"openInfo('" + list[i].ID + "');\">" + list[i].Name + "</a><br />";
            innerHtml += "<span style='font-size:80%'>(" + list[i].Weight + " гр.)</span>";
            if (!list[i].IsMerchant || list[i].CustomPrice == "")
                innerHtml += "<div><span class='price'><span class='digit'>" + list[i].Price + "</span><span class='rub'>&nbsp;руб.</span></div>";
            else if (list[i].IsMerchant && list[i].CustomPrice != "")
                innerHtml += "<div><span style='font-size: 90%; font-weight: bold'>" + list[i].CustomPrice + "</span></div>";
                
            innerHtml += "<div><a href='" + appPath + "/cart.aspx?id=" + list[i].ID + "' style='color: Red; font-size: 80%; font-weight: bold'>Купить</a></div>";
         
            td.update(innerHtml);
        }
        
        animated = true;
        var x = (direction == "left") ? frameWidth : -frameWidth;
        new Effect.MoveBy($("frameContainer"), 0, x, { duration: 1, afterFinish: moveCompleted });
    }
    else
    {
        $("loader").setStyle({ display: "none" });
        $("divCartState").update(args);
        
        if (close)
        {
            closeInfo(null);
        
            var coords = $("plist").cumulativeOffset();
            $("messageContainer").setStyle({ left: coords.left + ($("plist").getWidth() - $("messageContainer").getWidth()) / 2 - 30 + "px", top: coords.top + document.viewport.getScrollOffsets().top / 2 + 50 + "px" });
            $("messageContainer").update("Изделие добавлено в корзину!");
            $("messageContainer").show();
            clearTimeout(tout);
            tout = setTimeout("hideMessage();", 1000);
        }
        else
        {
            $("imgOrder").show();
            $("imgCompare").show();
            $("imgLoad").hide();
            alert("Изделие добавлено в корзину!");
        }
    }
    inProcess = false;
}
function callBackError(args)
{
    inProcess = false;
    $("loader").setStyle({ display: "none" });
    closeInfo(null);
}
function showInfo(product)
{
    productInfo = product;
    code = "" + product.ID;
    
    $("imgLoader").hide();
    $("imgProduct").show();
    
    if (product.PreviewImage != "")
    {
        $("imgContainer").setStyle({ width: product.ImageWidth + "px", height: product.ImageHeight + "px" });
        $("imgProduct").setStyle({ width: product.ImageWidth + "px", height: product.ImageHeight + "px" });
        $('imgProduct').src = product.Image;
        $("imgContainer").setStyle({ display: "block" });
        $("imgProduct").setStyle({ display: "block" });
        $("imgLoader").setStyle({ marginTop: "250px" });
        if (Prototype.Browser.IE)
            $("imgLoader").setStyle({ marginTop: "0px" });
    }
    else
    {
        $("imgContainer").setStyle({ display: "none" });
        $("imgProduct").setStyle({ display: "none" });
    }
    
    if (Prototype.Browser.IE)
    {
        $("productContainer").addClassName("active");
        $("productContainer").show();
    }
    else
        $("plist").addClassName("active");
    
    var content = "<b>" + product.Name + "</b><br /><table width='100%'>";
    if (product.ActualPrice > 0 && product.Emplements.length == 1)
    {
        if (!product.IsMerchant || product.CustomPrice == "")
            content += "<tr><td style='color: red; font-size: 120%; font-weight: bold'>Цена:</td><td style='color: red; font-size: 120%; font-weight: bold'>" + product.ActualPrice + " руб.</td></tr>";
            
        if (product.IsMerchant && product.CustomPrice != "")    
            content += "<tr><td colspan='2' style='color: red; font-size: 120%; font-weight: bold'>" + product.CustomPrice + "</td></tr>";
    }
    content += "<tr><td>Артикул:</td><td><b>" + product.Articul + "</b></td></tr>";
    if (product.TradeMark != "")
        content += "<tr><td>Торговая марка:</td><td><a href='/catalog/k0m0i0t" + product.TmID + "/'>" + product.TradeMark + "</a></td></tr>";
    if (product.Brand != "")
        content += "<tr><td>Бренд:</td><td>" + product.Brand + "</td></tr>";
    if (product.Collection != "")
        content += "<tr><td>Коллекция:</td><td>" + product.Collection + "</td></tr>";
    if (product.Metal != "")
        content += "<tr><td>Металл:</td><td>" + product.Metal + "</td></tr>";
        
    var insertions = "";
    if (product.Insertion != "")
        insertions = product.Insertion.toLowerCase();
    if (product.AdditionalInsertions.length > 0)
    {
        if (insertions != "")
            insertions += ", ";
        product.AdditionalInsertions.each(function(item, index)
            {
                insertions += item.Name.toLowerCase();
                if (index != product.AdditionalInsertions.length - 1)
                    insertions += ", ";
            }
        );
    }    
    if (insertions != "")
        content += "<tr><td>Вставка:</td>" + insertions + "</td></tr>";
    
    content += "<tr><td>Средний вес:</td><td>" + Math.round(product.Weight*100)/100 + " гр.</td></tr>";
    
    if (product.Length != "")
        content += "<tr><td>Длина:</td>" + product.Length + " мм.</td></tr>";
        if (product.Width != "")
        content += "<tr><td>Ширина:</td>" + product.Width + " мм.</td></tr>";
        if (product.Depth != "")
        content += "<tr><td>Глубина:</td>" + product.Depth + " мм.</td></tr>";
        
    if (product.Description != "" && product.Emplements.length == 1)
        content += "<tr><td colspan='2'><div style='width: 200px; white-space: normal'>" + product.Description + "</div></td></tr>";
    if (product.AddDescription != "" && product.Emplements.length == 1)
        content += "<tr><td colspan='2' style='padding-top: 5px; font-size: 80%'><div style='width: 200px; white-space: normal'>" + product.AddDescription + "</div></td></tr>";    
        
    if (product.SpecialOffer != "")
        content += "<tr><td colspan='2'>Специальное предложение</td><td></tr><tr><td colspan='2'><div style='width: 200px; white-space: normal'>" + product.SpecialOffer + "</div></td></tr>";
        
    if (product.Insertions.length > 0 && product.Emplements.length == 1)
    {
        content += "<tr><td colspan='2'>Вставки:</td></tr><tr><td colspan='2'>";
        product.Insertions.each(function(item, index)
            {
                content += "<div style='margin: 0px 0px 2px 0px;'>" + item.Name + "</div>";
            }
        );
        content += "</td></tr>";
    }
        
    if (product.Garnitures.length > 0)
    {
        content += "<tr><td colspan='2'>Гарнитуры:</td></tr><tr><td colspan='2'>";
        product.Garnitures.each(function(item, index)
            {
                content += "<div style='float: left; margin: 3px; text-align: center'><a href='javascript:void(0);' onclick=\"openInfo('" + item.ID + "');\"><img src='" + item.PreviewImage + "' rel='garniture' style='height: 60px; width: 60px; border: solid 1px #532321' alt='" + item.Name + "' title='" + item.Name + "' /></a><br /><b style='color: Red'>" + item.ActualPrice + " руб.</b><br><img src='" + appPath + "/ii/scart.gif' rel='cart' style='cursor: pointer' title='В корзину' alt='В корзину' onclick=\"orderGarniture('" + item.ID + "');\" /></div>";
            }
        );
        content += "</td></tr>";
    }
    
    if (product.Images.length > 0)
    {
        content += "<tr><td colspan='2'>Дополнительные изображения:</td></tr><tr><td colspan='2'>";
        product.Images.each(function(item, index)
            {
                content += "<img src='" + product.ImagesUrl + item.PreviewName + "' rel='cart' style='height: 60px; width: 60px; border: solid 1px #532321; cursor: pointer; float: left; margin: 2px;' alt='' onclick='javascript: $(\"imgProduct\").src=\"" + product.ImagesUrl + item.LargeName + "\";' />";
            }
        );
        content += "</td></tr>";
    }
    
    if (product.Emplements.length > 1)
    {
        if (product.AllSizes.length > 0)
        {
            content += "<tr><td colspan='2'><b>Варианты исполнения</b></td></tr><tr><td colspan='2'>Выберите размер: <select id='ddlEmplementSize' onchange='selectEmplement(event);'><option value='0'></option>";
            product.AllSizes.each(function(item, index)
                {
                    content += "<option value='" + item + "'>" + item + "</option>";
                }
            );
            content += "</input></td></tr><tr><td id='emplementsContainer' colspan='2'></td></tr>";
        }
        else
        {
            content += "<tr><td colspan='2'><b>Варианты исполнения</b></td></tr><tr><td colspan='2'><table width='250px' style='white-space: normal'>";
            product.Emplements.each(function(item, index)
                {
                    if (index == 5)
                        throw $break;
                    content += "<tr><td valign='top'><input id='emplement_" + item.ID + "' name='emplement' type='radio' onclick='selectEmplement(" + index + ");' /></td><td><label for='emplement_" + item.ID + "'>" + item.Description + "<br />Вес: <b>" + item.Weight + " г.</b>&nbsp;<b style='color: red'>Цена: " + item.ActualPrice + " руб.<b></label></td></tr>";
                }
            );
            content += "</table></td></tr>";
        }
    }
    content += "</table>";
    
    $("divInfo").update(content);
    
    if (product.IsRing && product.Emplements.length == 1)
    {
        var sizesHtml = "";
        for (var i = 0; i < product.Sizes.size(); ++i)
            sizesHtml += "<option value='" + product.Sizes[i] + "'>" + product.Sizes[i] + "</option>";
        $("ddlRingSize").update(sizesHtml);
        $("divRingSize").show();
    }    
    else
        $("divRingSize").hide();
        
    if ((document.viewport.getDimensions().width - $("divProduct").getWidth()) / document.viewport.getDimensions().width < 0.2)
    {
        $("imgContainer").setStyle({ width: "300px", height: "300px" });
        $("imgLoader").setStyle({ marginTop: "175px" });
        if (Prototype.Browser.IE)
            $("imgLoader").setStyle({ marginTop: "20px" });
        $("imgProduct").setStyle({ width: "300px", height: "300px" });
    }    
        
    $("productContainer").setStyle({ width: $("plist").getWidth() + "px", height: $("plist").getHeight() + "px" });
    var coords = $("plist").cumulativeOffset();
    $("productContainer").setStyle({ left: coords.left + "px", top: coords.top + "px" });    
    
    $("divProduct").setStyle({ left: coords.left + ($("plist").getWidth() - $("divProduct").getWidth()) / 2 + "px", top: coords.top / 2 + document.viewport.getScrollOffsets().top - 50 + "px" });

    $("divProduct").show();
}
function showEmplements()
{
    var coords = $("plist").cumulativeOffset();
    $("emplementsListContainer").setStyle({ left: coords.left + ($("plist").getWidth() - $("emplementsListContainer").getWidth()) / 2 - 30 + "px", top: coords.top + document.viewport.getScrollOffsets().top / 2 - 150 + "px" });
    $("emplementsListContainer").show();
}
function closeInfo(ev)
{
    $("imgProduct").src = "";
    $("divProduct").hide();
    $("productContainer").hide();
    
    $("imgOrder").show();
    $("imgCompare").show();
    $("imgLoad").hide();
    
    $("plist").removeClassName("active");
    
    closeEmplements();
}
function closeEmplements()
{
    $("emplementsListContainer").hide();
}
function selectEmplement()
{
    if (productInfo.AllSizes.length == 0)
        return;
    
    var content = "<table width='250px' style='white-space: normal'>";
    var count = 0;
    productInfo.Emplements.each(function(item, index)
        {
            if (count == 5)
                throw $break;
            
            var found = false;    
            for (var i = 0; i < item.Sizes.size(); ++i)
                if (item.Sizes[i] == $("ddlEmplementSize").value)
                {
                    found = true;
                    break;
                }
            if (found)
            {
                content += "<tr><td valign='top'><input id='emplement_" + item.ID + "' name='emplement' type='radio'/></td><td><label for='emplement_" + item.ID + "'>" + item.Description + "<br />Вес: <b>" + item.Weight + " г.</b>&nbsp;<b style='color: red'>Цена: " + item.ActualPrice + " руб.<b></label></td></tr>";
                count++;
            }
        }
    );
    content += "</table>";
    $("emplementsContainer").update(content);
}
function moveCompleted()
{
    animated = false;
    
    if (direction == "right")
    {
        $$("div.frame")[0].remove();
        $("frameContainer").setStyle({ left: "0px" });
        
        $("aPreviuosPage").style.visibility = "visible";
        $("textPreviuosPage").style.visibility = "visible";
        if (page == pageCount)
        {
            $("aNextPage").style.visibility = "hidden";
            $("textNextPage").style.visibility = "hidden";
        }
    }
    else
    {
        $$("div.frame")[1].remove();
        
        $("aNextPage").style.visibility = "visible";
        $("textNextPage").style.visibility = "visible";
        if (page == 1)
        {
            $("aPreviuosPage").style.visibility = "hidden";
            $("textPreviuosPage").style.visibility = "hidden";
        }    
    }
    
    $("loader").setStyle({ display: "none" });
    updatePager();
}
function updatePager()
{
    var baseUrl = window.location.pathname.split("page")[0].split("index.aspx")[0];
    var totalGroupCount = Math.ceil(pageCount / 20);
    var innerHtml = "";
    
    var list = new $A();
    
    if (page != 1)
        list[list.size()] = 1;

    if (page < 7)
    {
        for (var i = 2; i < page; ++i)
            list[list.size()] = i;
    }
    else
    {
        for (var i = page - 5; i < page; ++i)
            list[list.size()] = i;
    }

    list[list.size()] = page;

    if (page > pageCount - 6)
    {
        for (var i = page + 1; i < pageCount; ++i)
            list[list.size()] = i;
    }
    else
    {
        for (var i = page + 1; i < page + 6; ++i)
            list[list.size()] = i;
    }

    if (page != pageCount)
        list[list.size()] = pageCount;
        
    for (var i = 0; i < list.size(); i++)
    {
        if (list[i] == pageCount && page < pageCount - 6)
            innerHtml += "&nbsp;...&nbsp;";

        innerHtml += "&nbsp;";
        var cpage = (list[i] == page);
        var pageUrl = (list[i] == 1) ? "index.aspx" : "page-" + list[i] + ".aspx";
        if (!cpage)
            innerHtml += "<a href='" + baseUrl + pageUrl + "' onclick='selectedPage=" + list[i] + "; getPage(); return false;'>"
        if (cpage)
            innerHtml += "<b class=selected>";
        
        innerHtml += list[i];

        if (cpage)
            innerHtml += "</b>";
        if (!cpage)
            innerHtml += "</a>";
        if (list[i] < pageCount)
                innerHtml += "&nbsp;";
        
        if (list[i] == 1 && page > 7)
            innerHtml += "&nbsp;...&nbsp;";
    }
    
    $("pager").update(innerHtml);
}
function resizeFrame()
{
    try
    {
        frameWidth = $("content").getWidth()- 50;
        $("frameContent").width = frameWidth + "px";
        $("frameContent").setStyle({ width: frameWidth + "px" });
    }
    catch(e) { }
}
function hideMessage()
{
    Effect.Fade("messageContainer");
}