var messageY = 0;

function setMousePosition(){
   var block = $("items");
   var blockoTopY = block.cumulativeOffset()[1];
   var clientHeight = document.documentElement.clientHeight;

   messageY = document.documentElement.scrollTop + document.body.scrollTop + clientHeight/2;

   if (messageY < blockoTopY){
       messageY = blockoTopY + 100;
   }
}

var Pager = Class.create();
Pager.prototype = {
    initialize: function(container, totalLabelId, pager, criterions, searchedItems, iconLoader, pager_template, pager_texts) {

        this.button = {};

        this.iconLoader = iconLoader;

        this.searchedItems = searchedItems;

        this.searchContent = $$(container);

        this.setPagerValues(pager);

        this.prefix_item = "page_";

        this.setcriterions(criterions);

        this.label = $(totalLabelId);

        this.strings = pager_texts;

        this.pagerValues = pager;

        this.setPagerButtonTexts(pager_template, pager_texts);

        this.setPagerViewAndListeners();

    } ,

    setPagerButtonTexts: function(id, buttonTexts) {
        try {
            this.pager_template = new Template($(id).innerHTML, /(^|.|\r|\n)(\__(\w+)__)/);
        } catch(e) {
        }

        try {
            this.button["first"] = this.pager_template.evaluate({text: buttonTexts["first"]});
            this.button["last"] = this.pager_template.evaluate({text: buttonTexts["last"]});
            this.button["next"] = this.pager_template.evaluate({text: buttonTexts["next"]});
            this.button["prev"] = this.pager_template.evaluate({text: buttonTexts["prev"]});
        } catch(e) {
            this.button["first"] = "<<";
            this.button["last"] = ">>";
            this.button["next"] = ">";
            this.button["prev"] = "<<";

        }
    } ,

    drawPagers : function() {
        if(this.pagerValues.countPages > 1) {
            var productsMessage = this.strings.productsFound.replace("\{0\}", this.pagerValues.countItems);
            productsMessage = productsMessage.replace("\{1\}", this.pageFrom);
            productsMessage = productsMessage.replace("\{2\}", this.pagerValues.countPages);

            this.label.innerHTML = productsMessage;
        } else {
            var oneProductMessage = this.strings.oneProductFound.replace("\{0\}", this.pagerValues.countItems);
            this.label.innerHTML = oneProductMessage;
        }

        if (this.countPages == 1) {
            return;
        }
        var mainPager = true;
        $A(this.searchContent).each(function(item) {
            this.drawPager(item, mainPager);
            mainPager = false;
        }.bind(this), this);

        this.showPagers();
    }   ,

    setPagerViewAndListeners : function() {
        this.drawPagers();
        this.setListeners();
    } ,
    drawPager : function(item, mainPager) {
        var page_blocks=[];

        if(mainPager){
            page_blocks['next'] = "<span id ='next_page'";
            page_blocks['first'] = "<span id ='first_page'";
            page_blocks['previous'] = "<span id ='previous_page'";
            page_blocks['last'] = "<span id ='last_page'";
        } else {
            page_blocks['next'] = page_blocks['first'] = page_blocks['previous'] =page_blocks['last'] = "<span";
        }
        item.innerHTML = "";
        if (this.left > 1) {
            item.insert(page_blocks['first'] + " class='" + this.prefix_item + "1 column button' onclick='setMousePosition(event)'>" + this.button["first"] + "</span>" + "<span class=\"space\">&nbsp;&nbsp;&nbsp;</span>");
        }

        if (this.pageFrom > 1) {
            item.insert(page_blocks['previous'] + " class='" + this.prefix_item + "" + (this.pageFrom - 1) + " column button' onclick='setMousePosition(event)'>" + this.button["prev"] + "</span>" + "<span class=\"space\">&nbsp;&nbsp;&nbsp;</span>");
        }
        var wr;
        for (var i = this.left; i <= this.right; i++) {
            if (i == this.right)
                wr = "<span class=\"column bullet\">&nbsp;&nbsp;&nbsp;</span>";
            else
                wr = "<span class=\"column bullet\">&nbsp;&bull;&nbsp;</span>";

            if (i == this.pageFrom) {
                item.insert("<span class=\"" + this.prefix_item + "" + i + "  column current\">" + i + "</span>" + wr);
            } else {
                item.insert("<span class=\"" + this.prefix_item + "" + i + " column\" onclick='setMousePosition(event)'>" + i + "</span>" + wr);
            }
        }

        if (this.pageFrom < this.countPages) {
            item.insert(page_blocks['next'] + " class='" + this.prefix_item + "" + (this.pageFrom + 1) + " column button' onclick='setMousePosition(event)'>" + this.button["next"] + "</span>" + "<span class=\"space\">&nbsp;&nbsp;&nbsp;</span>");
        }
        if (this.right < this.countPages) {
            item.insert(page_blocks['last'] + " class='" + this.prefix_item + "" + this.countPages + " column button' onclick='setMousePosition(event)'>" + this.button["last"] + "</span>");
        }
    }   ,

    reDrawPagers: function (number) {

        $A(this.searchContent).each(function(pager_line, number) {
            (pager_line).select(".current")[0].className = "";

        }.bind(this), this);
    }   ,

    setcriterions : function(criterions) {
        this.style = criterions.style;
        this.category = criterions.category;
    }   ,
    setPagerValues: function(pager) {
        if (pager != null) {
            this.left = pager.left;
            this.right = pager.right;
            this.pageFrom = pager.pageFrom;
            this.countPages = pager.countPages;
            this.countItems = pager.countItems;
        } else {
            this.left = 1;
            this.right = 1;
            this.pageFrom = 1;
            this.countPages = 1;
            this.countItems = 1;
        }
    } ,
    setListeners: function() {
        $A(this.searchContent).each(function(pager_line) {
            $A(pager_line.childElements()).each(function(link) {
                if ($(link).className.indexOf("page_") != -1) {
                    $(link).observe('click', function(evt) {
                        var number = parseInt(link.className.replace(this.prefix_item, ""));
                        this.pageFrom = number;
                        this.searchItemsByPagerParams();
                    }.bind(this), this);
                }
            }.bind(this), this);
        }.bind(this), this);

    }   ,
    hidePagers : function() {
        $A(this.searchContent).each(function(pager_line) {
            pager_line.parentNode.style.display = "none";
        });
    }   ,
    showPagers : function() {
        $A(this.searchContent).each(function(pager_line) {
            pager_line.parentNode.style.display = "";
        });
    }   ,

    searchItemsByPagerParams : function() {
        this.pagerItemAjaxListener();
    },

    pagerItemAjaxListener : function() {
        var params = "pageFrom=" + this.pageFrom + "&ajax=true";

        if (this.style != 'null') {
            params += "&style=" + this.style;
        }
        if (this.category != 'null') {
            params += "&category=" + this.category;

        }
        this.infoPageAjax = new Ajax.Request(
                this.iconLoader.searchUrl,
        {
            parameters : params,
            onComplete: function(transport) {
                this.processReceivedData(transport);
                this.iconLoader.messagesManager.hide();
            }.bind(this)    ,
            onCreate: function() {
                this.iconLoader.messagesManager.setText($(this.iconLoader.messages['loading']).innerHTML);
                this.iconLoader.messagesManager.show();
            }.bind(this)
        });
    },
    processReceivedData: function(transport) {
        var receivedData = [];
        receivedData = transport.responseText.evalJSON();
        // 0 - pager
        // 1 - searchedItems
        this.searchedItems = receivedData[0];
        this.setPagerValues(receivedData[1]);

        if (this.countPages > 1) {
            this.setPagerViewAndListeners();
        } else {
            this.hidePagers();
        }

        this.iconLoader.setSearchedIcons(this.searchedItems);
        this.iconLoader.drawSearchedIcons();
        this.iconLoader.setNewHash(this.searchedItems);
        this.iconLoader.mergeIcons(true, "icon", true);
    }
};

var MessagesManager = Class.create();
MessagesManager.prototype = {
    initialize: function(template) {
        this.template = $(template);
        this.templateText = $(template + "_text");
    },
    setText: function(text) {
        this.templateText.update(text);
    } ,
    show: function() {
        setMousePosition();
        $(this.template).setOpacity(1);
        $(this.template).style.top = messageY + "px";
        $(this.template).show();
    },
    hide: function(duraction) {
        if (arguments.length == 0) {
            duraction = 2;
        }
        Effect.Fade($(this.template), {duration: duraction});
    }

};
var ColumnManager = Class.create();
ColumnManager.prototype = {
    initialize: function() {
        this.column = $$(".main_indent")[0];
        Event.observe(window, 'resize', function() {
        }.bindAsEventListener(this));
    }
};

var loader;
var IconLoader = Class.create();
IconLoader.prototype = {
    initialize: function(
            searchType, // STATIC, AJAX
            searchContent, //  "content"
            searchUrl //like search.jhtml
            ) {
        this.searchType = searchType;
        this.searchContent = $(searchContent);
        this.searchUrl = searchUrl;
        this.ajax = {};
        this.searchedIcons = [];
        loader = this;
    },

    setMessagesManager: function(mm) {
        this.messagesManager = mm;
    },

    setMessages: function(obj) {
        this.messages = obj;
    },

    mergeAllIcons:function(prefix, si, cartItems){
        var exist = false;
        var opacity = 2;
        for (var i = 0; i < si.length; i++) {
        exist = false;
        try {
            var element = $(prefix + si[i].id);
            for (var j = 0; j < cartItems.length; j++) {
                try {
                    if (si[i].id == cartItems[j].id) {
                        element.style.filter = "alpha(opacity=" + opacity + "0)";
                        element.style.opacity = "0." + opacity;
                        exist = true;
                        break;
                    }
                } catch(e) {
                }
            }
            if (!exist) {
                element.style.opacity = "1";
                element.style.filter = "alpha(opacity=100)";
            }
        } catch(e) {
        }
        }
    },

    mergeIcons: function(isNeeded, prefix, useCurrent) {
        if (isNeeded) {
            var ci = cart.cartIcons;
            cart.cartIcons = cart.cartIcons.compact();

            if (useCurrent || cart.cartIcons.length == 0){
                this.mergeAllIcons(prefix, loader.searchedIcons, ci);
            }

            for (var k = 0; k < cart.cartIcons.length; k++){
                if (useCurrent){
                    loader = this;
                    if (loader == null){
                        loader = cart.getLoader("0");   
                    }

                } else {
                    var cartIcon = cart.cartIcons[k];
                    var packName = cartIcon.packName;
                    loader = cart.getLoader(packName);
                }
               this.mergeAllIcons(prefix, loader.searchedIcons, ci);
            }
            cart.setCartEmpty();
         }
        
        try {
            var countItemsBlock = $("cart_count_items");
            if (cart.cartIcons.size() >= 19 || cart.cartIcons.size() == 0){
                $('shopping_cart_row').style.display = "none";
            } else {
                 $('shopping_cart_row').style.display = "block";
            }
            countItemsBlock.update("(" + cart.cartIcons.size() + ")");
        } catch(e) {

        }
    },

//Pager on search page
    setPager :function(pagerObject) {
        this.pager = new Pager(
                pagerObject.pager_class,
                pagerObject.totalLabelId,
                pagerObject.pager_values,
                pagerObject.pager_criterions,
                this.searchedIcons,
                this,
                pagerObject.pager_template,
                pagerObject.pager_texts
                );
    },

    setTemplates: function(icon_t, tooltip_t, search_params_t) {
        try {
            this.icon_template = new Template($(icon_t).innerHTML, /(^|.|\r|\n)(\_(\w+)_)/);
        } catch (e) {
        }
        try {
            this.tooltip_template = new Template($(tooltip_t).innerHTML, /(^|.|\r|\n)(\_(\w+)_)/);
        } catch (e) {
        }
        try {
            this.search_params_template = new Template($(search_params_t).innerHTML, /(^|.|\r|\n)(\_(\w+)_)/);
        } catch (e) {
        }
    },

    showNoMoneyContent: function(itemsBlock, visible) {
        if (visible) {
            this.block = new Element('div',
            {
                style:'position:absolute; z-index:100;display:none;padding:0;margin:0; background:white;top:10px;left:10px'
            });
            document.body.appendChild(this.block);
            this.block.update($(itemsBlock).innerHTML);
            Effect.Appear(this.block);
        }
    },

    searchItemsByParams :  function() {
        this.setSearchParams();
        this.pager.setcriterions({style : $F(this.stylesId),  category: $F(this.categoriesId)});
        this.pager.pageFrom = 1;
        this.pager.searchItemsByPagerParams();
    },


    staticSearchItemsByParams :  function() {
        $(this.stylesId).form.submit();
    },


    processAndViewResult : function() {
        this.drawSearchedIcons();
    },

    setSearchedIcons: function(icons) {
        this.searchedIcons = icons;

    },

    drawSearchedIcons: function(without_buy_button, isDraggable, draw_remove_button) {
       if (arguments.length > 0) {
            this.drawIcons(this.searchedIcons, this.searchContent, without_buy_button, isDraggable, draw_remove_button);
        } else {
            this.drawIcons(this.searchedIcons, this.searchContent, false, true, false);
        }
    },

    drawIcons: function(icons, itemsBlock, without_buy_button, isDraggable, draw_remove_button) {
        $(itemsBlock).update('');
        $A(icons).each(function (icon) {
            this.drawIcon(icon, itemsBlock, "icon", without_buy_button, draw_remove_button);
            if (isDraggable)
                this.setIconDraggable(icon, "icon");
        }.bindAsEventListener(this));
    },

    drawIcon: function(icon, itemsBlock, prefix, without_buy_button, draw_remove_button) {
        var data = {
            id : prefix + icon.id,
            src : icon.src,
            alt: icon.alt,
            title: icon.title
        };
        itemsBlock.insert({bottom: this.icon_template.evaluate(data)});

        if (without_buy_button) this.removeBuyIconWidget(icon, prefix);
        else
            try {
                $("buyicon" + icon.id).observe('click', function() {
                    cart.addIconToShoppingCart(data.id, null, null);
                }.bindAsEventListener(this), this);
            }
            catch(e) {
            }

        try {
            var info_pic = $$('#' + prefix + icon.id + ' .info')[0];
            var tt = {
                productNumber: icon.productNumber,
                size: icon.size,
                software: icon.software,
                format: icon.format
            };
            var cc = this.tooltip_template.evaluate(tt);
            new ToolTip(info_pic, cc, {className : "tooltip"});
        } catch(e) {
        }

        if (draw_remove_button)
            this.drawRemoveIconWidget(icon, prefix);

    },

    drawRemoveIconWidget: function(icon, prefix, ajax) {

        var remove = $$("#" + prefix + icon.id + " .remove")[0];
        remove.style.visibility = "visible";

        Event.observe(remove, 'click', function() {
            cart.removeIconFromShoppingCart(icon, prefix, ajax);
        }.bindAsEventListener(this), this);

    },

    removeBuyIconWidget: function(icon, prefix) {
        try {
            $$("#" + prefix + icon.id + " .buy")[0].style.display = "none";
        } catch (e) {

        }

    },

    setBuyIcon: function(icon, showMessage) {
        if (showMessage) {
            try {
                $(icon).observe('click', function() {
                    this.messagesManager.setText($(this.messages['noMoney']).innerHTML);
                    this.messagesManager.show();
                    this.messagesManager.hide(4);
                }.bind(this));
            } catch (e) {

            }

        }
    },

    setIconDraggable: function(icon, prefix) {
        new Draggable($(prefix + icon.id), {
            revert:true,
            reverteffect: function(element, top_offset, left_offset) {
                var dur = Math.sqrt(Math.abs(top_offset ^ 2) + Math.abs(left_offset ^ 2)) * 0.02;
                new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
                    queue: {scope:'_draggable', position:'end'}
                });
            },
            endeffect: function(element) {
                //This empty func is needed to set element's current opacity
            }
        });
    },

    setParamsListeners: function(styleElement, categoryElement) {
        this.stylesId = $(styleElement);
        this.categoriesId = $(categoryElement);

    },

    setSearchParamsParentDiv : function(parent) {
       this.searchParamsParentDiv = $(parent);
    },
    setNewHash:function(icons){
        for(var i=0; i<icons.length; i++){
            searchedIconsArray.set("'"+icons[i].id+"'", icons[i].packName);            
        }
    }
};


var TransactionStatusRefresher = Class.create({
	initialize: function(operationId, timeout, url, status) {
		this.operationId = operationId;
		this.timeout = timeout;
		this.status =  status;
		this.url = url;
		this.timer = {};
		this.startTimer();
	},
    setInitialText:function(status){
        if ((status == "Purchases Approved" || status == "Subscription") && $("orderInfoText")){
            this.setVisibleElement(false, "orderInfoText");
        }
    },
	startTimer : function() {
		var timeInMili = 1000 * this.timeout;
     	this.timer = setInterval(function() {
			this.onTimer();
		}.bind(this), timeInMili);
	},
	onTimer : function() {
		new Ajax.Request(this.url, {
			method: 'post',
			parameters:{"operationId" : this.operationId, "status" : this.status} ,
			onComplete: function(transport) {
				this.onRequest(transport.responseText.evalJSON());
			}.bindAsEventListener(this)
		});
	},
	onRequest: function(data) {
        if (data['error'] != null) {
            window.location = "/";
        } else {
           if (data["status"] != this.status) {
                this.status = data["status"];
                this.setInitialText(this.status);
                if (data["view"] != null) {
                    $(this.operationId).update(data["view"]);
                }
                if (data["topText"] != null) {
                    $("topText").update(data["topText"]);
                }
                if (data["bottomText"] != null) {
                    $("bottomText").update(data["bottomText"]);
                }
            }
            if ((data["isContinue"] != null) && (data["isContinue"] == "false")) {
                clearInterval(this.timer);
            }
        }
    },
    setVisibleElement: function(visible, elementId) {
        if (visible) {
            document.getElementById(elementId).style.display = 'block';
        } else {
            document.getElementById(elementId).style.display = 'none';
        }
    }
});
