
CONST.class_col_left_row_cnt_box = '#left-column .row_cnt_box_mm';
CALLBACK.updatePurchase = function() {
    resizeBlocks();
    $$('.partner_footer').each(function(el) {
        el.absolutize();
        el.relativize();
    });
};

IFrameZIndex = Class.create({
    initialize: function(id){
        this.iframeWrapper = $(id);
        if (!this.iframeWrapper) return false;
        this.iframe = this.iframeWrapper.down('iframe');
        this.body = $(document.body);
    },
    onMouseOver: function() {
        this.iframe.setStyle({
            'height': this.body.getHeight() + 'px'
        });
        this.iframeWrapper.setStyle({
            zIndex: 100
        });
    },
    onMouseOut: function(force) {
        if ($top().isOverlayOpened() && !force)
            return false;
        var height = 217;
        this.iframe.setStyle({
            'height': height + 'px'
        });
        this.iframeWrapper.setStyle({
            zIndex: 1
        });
    },
    updateClass: function(clazz) {
        this.iframe.addClassName(clazz);
    }
});

MMShoppingCart = Class.create(ShoppingCart, {
    initialize: function() {
        this.cookie = 'cart';
        this.maxItems = DEFINE.get('CART_MAXIMUM_ITEMS');
        this.maxGames = DEFINE.get('CART_MAXIMUM_GAMES');
        this.expire = DEFINE.get('CART_COOKIE_DAYS') *  84600;
        this.cart = new Array();
        this.loadFromCookie();
        this.initButtons();

        var url = new UrlSeoConstructor('CHECKOUT_INDEX');
        this.basketUrl = url.construct();
        this.basketId = DEFINE.get('BASKET_ID');
        this.syncBasket(true);
    },
    syncBasket: function(force) {
        if(force === undefined)
            force = false;

        var sync = Cookie.get('sync');
        if (force && $top() || sync && $top()) {
        	Cookie.unset('sync');
            $top().multiChannel.sso.refreshBasket(this.basketId, this.cart.size() + '', this.basketUrl, function() {
                $top().loadLinksInMainWindow();
                if (sync) {
                	window.location.reload();
            	}
            }.bind(this));
        }      
    },
    initButtons: function() {
        $$('.addToCart').invoke('observe', 'click', this.add.bindAsEventListener(this, true));
        $$('.addToPartnerCart').invoke('observe', 'click', this.add.bindAsEventListener(this, false));
    },
    add: function(event, redirect) {
        var el = Event.element(event).findNearest('a');
        var gameId = parseInt(el.className.match(/gameId-(\w+)\s?/)[1]);
        var isAGift = el.className.match(/isAGift/)!=null;
        this.addToCookie({
            'id':gameId,
            'gift':isAGift
        }, redirect);
    },
    addToCookie: function(gameObject, redirect) {
        var indexOfGameInCart = this.getGameIndexInCart(gameObject.id);
        if (this.cart.size() < this.maxItems && indexOfGameInCart < 0) {
            this.getContent(gameObject, redirect);
        } else if (this.cart.size() >= this.maxItems && indexOfGameInCart < 0) {
            var monostoreCode = MvcSkel.getVar('monostoreCode');
            if(monostoreCode!=false) {
                ModalWindows.showText(i18n('MONOSTORE_cart_maximum_reached ', $H({
                    countItems: this.maxItems,
                    countGames: this.maxGames,
                    monostore_code: monostoreCode
                })), i18n('cart_maximum_reached_title'));
            } else {
                ModalWindows.showText(i18n('cart_maximum_reached', $H({
                    countItems: this.maxItems,
                    countGames: this.maxGames
                })), i18n('cart_maximum_reached_title'));
            }
        } else {
            if (redirect) {
                window.location = this.basketUrl;
            } else
                ModalWindows.showText(i18n('cart_already_added'), i18n('cart_already_added_title'));
        }
    },
    getContent: function(gameObject, redirect) {
        var url = new UrlConstructor('game/add_to_cart');
        var c = this.cart.clone();
        c.push(gameObject);
        url.addVar('cart', c.toJSON());
        new Ajax.Request(url.construct(), {
            method: 'get',
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
                if (this.checkMaxGames(obj)) {
                    this.cart.push(obj.gameObject);
                    Cookie.set(this.cookie, this.cart.toJSON(), this.expire);
                    $top().multiChannel.sso.refreshBasket(this.basketId, this.cart.size(), this.basketUrl, function() {
                        $top().loadLinksInMainWindow();
                        if (redirect)
                            window.location = this.basketUrl;
                        else
                            new Effect.ScrollTo('partner_top_header', {
                                queue: 'end',
                                duration: 0.6
                            });
                    }.bind(this));
                }
            }.bind(this)
        });
    }
});

HomeTabs = Class.create({
    initialize: function(){
        if (!$('home-tabs')) return;
        this.initTabs();
    },
    initTabs: function() {
        if($('home-tabs')) {
            new Control.Tabs('home-tabs', {
                afterChange: function(){
                    var activeLink = this.activeLink;
                    $A(this.links).each(function(link){
                        var id = link.id.substr(0, 2);
                        var activeId = activeLink.id.substr(0, 2);
                        if(link.id == activeLink.id){
                            if (link.hasClassName('active')) {
                                activeLink.hide();
                                $(id + '-active').show();
                                activeLink = $(id + '-active');
                                link.up('li').addClassName('active');
                            }
                        } else {
                            if (id != activeId) {
                                $(id + '-active').hide();
                                $(id + '-inactive').show();
                                link.up('li').removeClassName('active');
                            }
                        }
                    });

                    resizeBlocks();
                }
            });
        }
    }
});

function $top() {
    return window.frames['iframe_partner_header_top'] ? window.frames['iframe_partner_header_top'] : false;
}

function $mystore() {
    return $('iframeMystore');
}

function getContext() {
    return $('context').getValue();
}

function getLoginUrl() {
    return new UrlSeoConstructor('MM_LOGIN_URL');
}

function getLogoutUrl() {
    return new UrlSeoConstructor('MM_LOGOUT_URL');
}

function logoutProcess() {
    var url = new UrlSeoConstructor('MM_LOGOUT_URL')
    window.location = url.construct();
}

function changeMyStoreHeight(size, fast) {
    new Effect.Morph($mystore(), {
        style: 'height: ' + size + 'px',
        transition: fast ? Effect.Transitions.full : Effect.Transitions.linear,
        duration: 0.3
    });
}

function resizeBlocks() {
    var leftParentBlock = $('left-column');
    var leftEmptyBlock  = $('emptyBlock');
    var centerBlock = $('containerHome');
    if (leftParentBlock!=null && leftEmptyBlock!=null && centerBlock!=null) {

        var leftBlock = leftParentBlock.up('div.left_wrap');
        var centerBottomBlock = centerBlock.down('div.box_links');

        if (leftBlock!=null && centerBottomBlock!=null) {

            var centerHeight = centerBlock.getHeight();
            var centerMarginHeight = centerBottomBlock.getStyleValue('margin-top') - 10;
            var leftHeight = leftBlock.getHeight();
            var leftEmptyHeight = leftEmptyBlock.getHeight();

            if (leftHeight - leftEmptyHeight < centerHeight - centerMarginHeight) {
                leftEmptyBlock.setStyle({
                    height: (centerHeight - centerMarginHeight - (leftHeight - leftEmptyHeight)) + 'px'
                });
                centerBottomBlock.setStyle({
                    marginTop: 10 + 'px'
                });
            }
            else if (leftHeight - leftEmptyHeight > centerHeight - centerMarginHeight) {
                leftEmptyBlock.setStyle({
                    height: 0 + 'px'
                });
                centerBottomBlock.setStyle({
                    marginTop: 10 + (leftHeight - leftEmptyHeight - (centerHeight - centerMarginHeight)) + 'px'
                });
            }
            else if (MvcSkel.getVar('cresize')) {
                var p = centerBlock.getStyleValue('padding-top') + centerBlock.getStyleValue('padding-bottom');
                centerBlock.setStyle({
                    height: leftHeight - p + 'px'
                });
            }
        }
    }
}

CategoryIndexALoader.addMethods({
    processAfterFinish: function(obj) {
        // Update column sizes
        resizeBlocks();

        // Update title of catalog
        var titleBlock = $('categoryTitle');
        if(titleBlock!=null) {
            var gamesFound = 0;
            var results = obj.gamesFound.match(/^([0-9]+)/);
            if(results!=null && results)
                gamesFound = results[1];

            var category = "Ver todos los juegos";
            results = obj.breadcrumbContainer.match(/<strong>([^<]+)<\/strong>\s+<\/p>\s*<\/div>\s*<\/div>/);
            if(results!=null)
                category = results[1];

            titleBlock.update(category + ' (' + gamesFound + ')');
        }
    }
});

Event.observe(window, 'load', function() {
    var cntx = $('context').getValue();

    IFrameZIndex = new IFrameZIndex('partner_top_header');
    MMShoppingCart = new MMShoppingCart();
    if (!(/profile_.*/.test(cntx))) {
        HomeTabs = new HomeTabs();
    }
    if ($('submit') != null) {
    	$('submit').observe('click', function() {
	    	$('searchForm').submit();
	    });
	}
    
    resizeBlocks();

    if (/download_index/.test(cntx)) {
        //set a cookie 'sync' to true
        MMShoppingCart.reset();
        
    }
});

