var __meta = true;

Press = Class.create({
    initialize: function() {
        this.objects = $$('img.pictopress');
        if (this.objects.size() == 0) { return false };
        this.objects.first().setStyle({display: 'block'});
        $('boxPress_totalPage').update((this.objects.size() < 10) ? '0' + this.objects.size() : this.objects.size());
        this.currentPage = 0;
        this.initActions();
        this.render();
    },
    render: function() {
        this.objects.each(function(el) {
            el.setStyle({display: 'none'});
        });
        this.objects[this.currentPage].setStyle({display: 'block'});
        var displayCurrent = this.currentPage + 1;
        $('boxPress_currentPage').update((displayCurrent < 10) ? '0' + displayCurrent : displayCurrent);
        if (this.currentPage == 0) {
            $('boxPress_prev').addClassName('inactive');
        } else if (this.currentPage == (this.objects.size() - 1)) {
            $('boxPress_next').addClassName('inactive');
        } else {
            $('boxPress_prev', 'boxPress_next').each(function(el) {
                 el.removeClassName('inactive');
            });
        }
    },
    initActions: function() {
        $('boxPress_next').observe('click', function(){
            if (this.currentPage < (this.objects.size() - 1)) {
                this.currentPage++;
                this.render();
            }
        }.bind(this));
        $('boxPress_prev').observe('click', function(){
            if (this.currentPage > 0) {
                this.currentPage--;
                this.render();
            }
        }.bind(this));
    }
});
Newsletter = Class.create({
    initialize: function() {
        $$('.formnews').each(function(fm) {
            this.initElements(fm);
            fm.observe('submit', function(event) {
                this.showDialog(Event.element(event).down('img'));
                Event.stop(event);
            }.bind(this));
        }.bind(this));
        this.modal = null;
    },
    initElements: function(fm) {
        fm.down('input').observe('focus', function(event) {
            var elInput = Event.element(event);
            if (elInput.hasClassName('defaultText')) {
                elInput.value = '';
                elInput.removeClassName('defaultText');
            }
        }.bind(this));
        fm.down('label').observe('click', function(event) {
            this.showDialog(Event.element(event));
        }.bind(this));
    },
    showDialog: function(elImg) {
        var email = elImg.up('.formnews').down('input').getValue();
        var err = new ErrorManager();
        err.checkEmail(email);
        if (err.getErrors()) {
            return false;
        }
        var url = new UrlConstructor('Newsletter/Dialog');
        url.addVar('email', email);
        this.modal = new Control.Modal(false, {
            contents: function() {
                new Ajax.Request(url.construct(), {
                    onComplete: function(request){
                        this.modal.update(request.responseText);
                        this.initDialogAction();
                        Event.observe('modalClose', 'click', function() {
                            this.modal.close();
                        }.bind(this));
                    }.bind(this)
                });
                return i18n('loadingDialog');
            }.bind(this),
            fade: true,
            fadeDuration: 0.4,
            opacity: 0.8,
            width: 500,
            containerClassName: 'mfmodal'
        });
        this.modal.open();
    },
    initDialogAction: function() {
        $('saveemailok').observe('click', function() {
            var url = new UrlConstructor('newsletter/subscribe');
            url.setAction(true);
            $('saveemail').getElements().each(function(el) {
                url.addVar(el.readAttribute('name'), $F(el));
            });
            new Ajax.Request(url.construct(), {
                onSuccess: function(transport) {
                    var obj = transport.responseText.evalJSON();
                    var er = new ErrorManager(obj);
                    if (er.haveErrors()) {
                        this.modal.update(er.getHtmlContent());
                        Event.observe('errorsClose', 'click', function() {
                            this.modal.close();
                        }.bind(this));                       
                    } else {
                        alert(i18n('newsletter_alert_part1') + obj.email + i18n('newsletter_alert_part2'));
                        $$('.formnews').each(function(fm) {
                            var elInput = fm.down('input');
                            if (!elInput.hasClassName('defaultText')) {
                                elInput.value = '';
                            }
                        });
                        this.modal.close();
                    }
                }.bind(this)
            });
        }.bind(this));
    }
});

VideoScreeenShot = Class.create({
    initialize: function() {
        if (!$('thumbnailContent')) {return false;}
        if ($('thumbnailContent').offsetWidth < $('thumbnailContent').offsetHeight) {
			this.scrollLength = 340; // vertical scroll
		} else {
			this.scrollLength = 85;  // horizontal scroll
		}
        if ($('video-0').height <= 30) {
            $('video-0').src = 'http://img.metaboli.fr/common/V4/images/videoNo_sm.jpg';
        }
        $('video-0').addClassName('goodSizeVideo');
        this.countElements = $('thumbnailContent').childElements().size();
        this.countPages = Math.ceil(this.countElements/4);
        this.currentPage = 1;
        this.buttonNavUp = $('buttonNavUp');
        this.buttonNavDown = $('buttonNavDown');
        var sDiv = $('thumbnailContent').down();
        if ($('selectedItem').getValue() != 0) {
            var screen = parseInt($('selectedItem').getValue());
            sDiv = sDiv.next(screen - 1);
            if (screen > 3) {
                this.currentPage = Math.ceil(parseInt($('selectedItem').getValue()) / this.countPages);
            }
        }
        this.render();
        this.buttonNavDown.observe('click', function(event) {
            if (/downInactive/.test(Event.element(event).className)) {
                return false;
            }
            this.currentPage++;
            this.render();
        }.bind(this));
        this.buttonNavUp.observe('click', function(event) {
            if (/upInactive/.test(Event.element(event).className)) {
                return false;
            }
            this.currentPage--;
            this.render();
        }.bind(this));
        $('viewScreenshot').observe('click', this.modalView);
        $('thumbnailContent').select('img').each(function(elImg) {
            Event.observe(elImg, 'click', function(event) {
                var elImg = Event.element(event);
                this.selectItem(elImg);
            }.bind(this));
        }.bind(this));
        sDiv.addClassName('thumbSelected');
        this.selectItem(sDiv.down('img'));
    },
    render: function() {
        $('thumbnailContent').setStyle({
            marginTop: -(this.currentPage * this.scrollLength) + 'px'
        });
        $('thumbnailContent').setStyle({
            marginTop: -((this.currentPage - 1) * this.scrollLength) + 'px'
        });
        if (this.currentPage == 1) {
            this.buttonNavUp.addClassName('upInactive');
        } else {
            this.buttonNavUp.removeClassName('upInactive');
        }
        if (this.currentPage == this.countPages) {
            this.buttonNavDown.addClassName('downInactive');
        } else {
            this.buttonNavDown.removeClassName('downInactive');
        }
    },
    selectItem: function(elImg) {
        $('thumbnailContent').childElements().each(function(el) {
            el.removeClassName('thumbSelected');
        }.bind(this));
        if (/screen/.test(elImg.id)) {
            $('videoScript').update();
            $('productVideo').setStyle({display: 'none'});
            var container = $('productScreenshot');
            var r = elImg.src.match(/^(.*)_sm(.*)$/);
            container.down('img').src = r[1] + r[2];
            container.setStyle({display: 'block'});
        } else if (/video/.test(elImg.id)) {
            $('productScreenshot').setStyle({display: 'none'});
            if ($('videoScript')) {
                var video = elImg.src.match(/^(.*)_sm.*$/)[1] + '.flv';
                $('videoScript').innerHTML = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ' +
                    'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" ' +
                    'WIDTH="450" HEIGHT="450">' +
                        '<PARAM NAME=movie VALUE="' + $('videoPlayerUrl').getValue() + '">' +
                        '<PARAM NAME=quality VALUE=high>' +
                        '<PARAM NAME=bgcolor VALUE=#000000>' +
                        '<PARAM NAME=wmode VALUE=transparent>' +
                        '<PARAM NAME=flashvars VALUE="videoPath=' + video + '&lang=' + getLocale().lang + '">' +
                        '<EMBED FLASHVARS="videoPath=' + video + '&lang=' + getLocale().lang + '" src="' + $('videoPlayerUrl').getValue() + '"' +
                            'quality=high bgcolor="#000000" ' +
                            'WIDTH="450" HEIGHT="450" NAME="" ALIGN="" wmode="transparent" ' +
                            'TYPE="application/x-shockwave-flash" ' +
                            'PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">' +
                        '</EMBED>' +
                '</OBJECT>';
            }
            $('productVideo').setStyle({display: 'block'});
        }
        this.render();
        elImg.up('div').addClassName('thumbSelected');
    },
    modalView: function(event) {
        var elImg = Event.element(event);
//         var a = Builder.node('a', {href: elImg.src});
        var a = new Element('a', {href: elImg.src});
        this.modal = new Control.Modal(a, {
                fade: true,
                image: true,
                containerClassName: 'viewFullScrennShot'
        });
        this.modal.open();
    }
});

Product = Class.create({
    initialize: function() {
        this.initFavorites('addGame');
        this.initFavorites('listGame');
        this.initAddRemoveFavorites();
		this.initParentalControlInfo();
    },
    initFavorites: function(elId) {
        if (!$(elId)) { return false; }
        Event.observe(elId, 'mouseover', function(event) {
            clearTimeout(this.ftimer);
            this.showFavoriteTip(elId);
        }.bind(this));
        Event.observe(elId, 'mouseout', function(event) {
            this.closeFavoriteTip(elId);
        }.bind(this));
    },
    showFavoriteTip: function(el) {
        $(el).down('div').setStyle({display: 'block'});
    },
    closeFavoriteTip: function(el) {
        this.ftimer = setTimeout(function() {
            $(el).down('div').setStyle({display: 'none'});
        }, 1000);
    },
    initAddRemoveFavorites: function() {
        if (!$('addGame') || !$('listGame')) { return false; }
        this.gameId = $('gameId').getValue();
        Event.observe('addGame', 'click', function() {
            var url = new UrlConstructor('favorite/add');
            url.setAction(true);
            url.addVar('id', this.gameId);
            new Ajax.Request(url.construct(), {
                onSuccess: function(transport, json) {
                    this.toggleFavoritesIcon();
                }.bind(this)
            });
        }.bind(this));
        Event.observe('listGame', 'click', function() {
            var url = new UrlConstructor('favorite/remove');
            url.setAction(true);
            url.addVar('id', this.gameId);
            new Ajax.Request(url.construct(), {
                onSuccess: function(transport, json) {
                    this.toggleFavoritesIcon();
                }.bind(this)
            });
        }.bind(this));
    },
    toggleFavoritesIcon: function() {
        if ($('addGame').getStyle('display') == 'block') {
            $('addGame').setStyle({display: 'none'});
            $('listGame').setStyle({display: 'block'});
        } else {
            $('addGame').setStyle({display: 'block'});
            $('listGame').setStyle({display: 'none'});
        }
    },
	initParentalControlInfo: function() {
		var modalId = $('parentalControlButton');
		if (!modalId) return false;
        var modal = new Control.Modal(modalId, {
                fade: true, opacity: 0.8, width: 500, containerClassName: 'mfmodal',
				onSuccess: function() {
				    Event.observe('modalClose', 'click', function() { modal.close(); });
				}
        });
	}
});

function getMovie(movieName) {
    if (Prototype.Browser.IE) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}
function triggerVideo() {
    try {
        var homeFlash = getMovie('flashObjectVideo');
        homeFlash.pageFinishedLoading();
    } catch (e) {
        setTimeout(triggerVideo, 1000);
    }
}

SimpleInPlaceEditor = Class.create({
    initialize: function(mainId) {
        this.main = $(mainId);
        if (!this.main) return ;
        this.btnEdit = this.main.down('a.edit');
        this.btnSave = this.main.down('a.save');
        this.btnCancel = this.main.down('a.cancel');
        Event.observe(this.btnEdit, 'click', this.toEditState.bind(this)); 
        Event.observe(this.btnCancel, 'click', this.toViewState.bind(this)); 
        Event.observe(this.btnSave, 'click', this.saveAction.bind(this)); 
    },
    saveAction: function() {
        this.main.request({
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
                var er = new ErrorManager(obj);
                if (er.getErrors()) 
                    return false;
                for (i in obj) {
                    if ($(i)) $(i).update(obj[i]);
                }
                this.toViewState();
            }.bind(this)            
        });
    },
    toEditState: function() {
        this.main.down('ul').addClassName('edit');
        
        this.btnEdit.hide();
        this.btnSave.removeClassName('displayNone');
        this.btnCancel.removeClassName('displayNone');
        
        this.main.select('p.value').invoke('hide');
        var editors = this.main.select('p.editor');
        editors.each(function(el) {
           el.removeClassName('displayNone');
           if (el.hasClassName('isDate')) {
                var arr = el.previous().innerHTML.match(/(\d+)\/(\d+)\/(\d+)/);
                if (arr) {
                    el.down('select').value = parseInt(arr[1], 10);
                    el.down('select', 1).value = parseInt(arr[2], 10);
                    el.down('select', 2).value = parseInt(arr[3], 10);
                }
           } else if (el.hasClassName('isPassword')) {
                if (el.down('input')) el.down('input').value = '';
                this.main.select('li.isPassword').invoke('removeClassName', 'displayNone');
           } else {
                if (el.down('input')) el.down('input').value = el.previous().innerHTML;
           }
        }.bind(this));
    },
    toViewState: function() {
        this.main.down('ul').removeClassName('edit');
        
        this.btnEdit.show();
        this.btnSave.addClassName('displayNone');
        this.btnCancel.addClassName('displayNone');
        
        this.main.select('p.value').invoke('show');
        var editors = this.main.select('p.editor');
        editors.each(function(el) {
            el.addClassName('displayNone');
            if (el.hasClassName('isPassword')) {
                this.main.select('li.isPassword').invoke('addClassName', 'displayNone');   
            }
        }.bind(this)); 
    }
});



Profile = Class.create({
    initialize: function() {
        this.personalInfo = new SimpleInPlaceEditor('personalInfoEdit');
        this.passwordEdit = new SimpleInPlaceEditor('passwordEdit');
        this.newsletterEdit = new SimpleInPlaceEditor('newsletterEdit');
        this.cancelInfo();
    },
    cancelInfo: function() {
        var containerId = $('cancelErrorContainer');
        if (!containerId) return ;
        var contents = containerId.innerHTML;
        containerId.update();
        var modal = new Control.Modal(false, {
            contents: contents, fade: true, fadeDuration: 0.4, opacity: 0.8, width: 600, containerClassName: 'mfmodal',
            afterOpen: function() {
                Event.observe('modalClose', 'click', function() { modal.close(); });
            }
        });
        modal.open();        
    }
});

function toggleFavorite(gameId) {
    var url = new UrlConstructor('profile/toggle_favorite');
    url.addVar('gameId', gameId);
    new Ajax.Request(url.construct(), {
        method: 'get',
        onSuccess: function(transport) {
            var obj = transport.responseText.evalJSON();
            if (obj.status != 0) {
                userGames.toggleFavorite(gameId, obj.status);
                userGames.setFavorite(obj.favorite);
            }
        }
    });
}

function showManual(gameId) {
    var url = new UrlConstructor('game/show_manual');
    url.addVar('gameId', gameId);
    new Ajax.Request(url.construct(), {
        method: 'get',
        onSuccess: function(transport) {
            var obj = transport.responseText.evalJSON();
            var er = new ErrorManager(obj);
            if (!er.getErrors()) {
                window.open(obj.manualHref);
            }
        }
    });
}

InDownload = Class.create({
    initialize: function() {
        this.exentId = null;
		this.langPrefix = getLocale().path;
        if (playerReady()) {
			try {
				var gameList = writeInDownloadListGames();
				var r = new XMLDoc(gameList, function(e) { alert(e); });
				var list = r.docNode;
				var listSize = list.getAttribute('ListSize');
				if (listSize != 0) {
					var games = list.getElements('ContentDescriptor');
					for(i = 0; i < games.length; i++) {
						var game = new Game(GetGameInfo(games[i].getAttribute('Id')));
						if (game.isDownloadNow()) {
							this.exentId = game.getExentId();
							this.gameActive();
							break;
						}
					}
				}
				//this.exentId = 462052;
				//this.gameActive();
				//this.initUpdateInfo();
			} catch(e) {
			}
        }
    },
    addHeader: function(game) {
        var url = new UrlSeoConstructor('PROFILE_GAMES');
        return '<div class="topH3 boxBorderRight">' +
            '<h3 class="uni05_63">' + i18n('addHeaderGame1') + ' "' + game.getGameName() + '"</h3>' +
            '<p><span class="text">[ <a href="' + url.construct() +'">' + i18n('addHeaderGame2') + '</a> ]</span></p>' +
        '</div>';
    },
    addGradient: function() {
        return '<img src="' + $('skin').value + 'img/gradient.gif" alt="" class="gradientBG"></img>';
    },
    addBoxShot: function(game) {
        return '<img alt="Downloading..." class="game"' +
            'src="http://img.metaboli.fr/products/' + game.getId() + this.langPrefix + '/sm_box.jpg">' +
        '</img>' +
        '<a class="manual" href="javascript:showManual(' + game.getId() + ');">' + i18n('addBoxShot') + '</a>';
    },
    addInfoText: function() {
        return '<p class="infoText">' +
            i18n('addInfoText') +
        '</p>';
    },
    addProgresssBar: function(game) {
        return '<div id="progressBarBG">' +
            '<div id="progressBarFill" style="width: ' + game.downloadedPercent() + '%;"></div>' +
            '<div id="progressBarMark" style="margin-left: ' + game.minDownloadedPercent() + '%;"></div>' +
        '</div>';
    },
    downloadInfo: function(game) {
        return '<p class="downloadText">' +
            '<span id="current_percent">' + game.downloadedPercent() + '%</span>' +
            ' (<span id="current_downloaded">' + game.getDownloadedSize() + '</span>/' +
            '<span id="current_total">' + game.getFullSize() + '</span>) ' +
            ' - ' +
            '<strong id="current_time">00:00:00 ' + i18n('ElapsedTime_result') + '</strong>' +
        '</p>';
    },
    explainText: function() {
        return '<p class="explainText">' + i18n('explainText') + '</p>';
    },
    buttonStartStop: function() {
        return '<div class="buttonContainer">' +
            '<a id="buttonPause" class="buttonPause" href="javascript:buttonPauseDownloadList();">' + i18n('pauseDownloadList') + '</a>' +
            '<a id="buttonContinue" class="buttonContinue" href="javascript:buttonStartDownloadList();">' + i18n('startDownloadList') + '</a>' +
        '</div>';
    },
    buttonPlay: function(game) {
        return '<div id="buttonPlay_inactive" class="buttonPlay_inactive" style="display: block;"></div>' +
            '<a id="buttonPlay_active" class="buttonPlay_active" href="javascript:gemeLauncher(' + game.getExentId() + ', 1);" style="display: none;"></a>';
    },
    setStatus: function() {
        if (this.exentId) {
            var game = new Game(GetGameInfo(this.exentId));
            if (game.isDownloadNow()) {
                $('buttonPause').setStyle({
                    display: 'block'
                });
                $('buttonContinue').setStyle({
                    display: 'none'
                });
                this.initUpdateInfo();
            } else {
                $('buttonPause').setStyle({
                    display: 'none'
                });
                $('buttonContinue').setStyle({
                    display: 'block'
                });
            }
        }
    },
    gameActive: function() {
        var userGame = new Game(GetGameInfo(this.exentId));
        var html = new String();
        html += '<div class="boxDownload block">';
        html += this.addHeader(userGame);

        html += '<div class="boxDownloadContent">';
        html += this.addGradient();
        html += this.addBoxShot(userGame);
        html += this.addInfoText();
        html += this.addProgresssBar(userGame);
        html += this.downloadInfo(userGame);
        html += this.explainText();
        html += this.buttonStartStop();
        html += this.buttonPlay(userGame);
        html += '</div>';

        html += '</div>';
        $('boxDownloadContainer').insert(html);
        this.initUpdateInfo();
    },
    initUpdateInfo: function() {
        new PeriodicalExecuter(function(pe) {
            var game = new Game(GetGameInfo(this.exentId));
            if (game.isDownloadNow()) {
                $('progressBarFill').setStyle({width: game.downloadedPercent() + '%'});
                $('current_percent').update(game.downloadedPercent() + '%');
                $('current_downloaded').update(game.getDownloadedSize());
                $('current_total').update(game.getFullSize());
                $('current_time').update(game.getElapsedTime());
                if (game.isReady()) {
                    $('buttonPlay_inactive').setStyle({display: 'none'});
                    $('buttonPlay_active').setStyle({display: 'block'});
                    if (game.isFullyCached()) {
                        $('buttonPause').setStyle({display: 'none'});
                        $('buttonContinue').setStyle({display: 'none'});
                    }
                }
            } else {
                pe.stop();
            }
        }.bind(this), 1);
    }
});

Comingsoon = Class.create({
    initialize: function() {
        if (!$('rowWidth')) { return false; }
        this.gameCellWidth = 160;
        this.minMargin = 0;
        this.rowWidth = $('rowWidth').offsetWidth;
        this.run();
    },
    run: function() {
        var cellNumber = 0;
        var margin = 0;
        if ((this.rowWidth - (this.gameCellWidth + this.minMargin)) >= 0) {
            do {
                this.rowWidth = this.rowWidth - (this.gameCellWidth + this.minMargin);
                cellNumber++;
            } while ((this.rowWidth - (this.gameCellWidth + this.minMargin)) >= 0);
            this.rowWidth = this.rowWidth + this.minMargin;
            margin = Math.floor(this.rowWidth / (cellNumber - 1));
        }
        margin = margin + this.minMargin;
        document.write("<style>." + 'gameCell' + "{margin-right:" + margin + "px ! important;}</style>");
    }
});

Offer = Class.create({
    initialize: function() {
        this.initPCSpopup();
    },
    initPCSpopup: function() {
        var popupPCS = $('morePCS');
        if (popupPCS) {
            popupPCS.observe('click', function() {
                var url = new UrlConstructor('Index/PresentationPCS');
                var valuePopupHeight = 710;
                var browserHeight = window.innerHeight;
                if (browserHeight < 710) {
                    valuePopupHeight = browserHeight - 10; 
                }
                this.modal = new Control.Modal(false, {
                    contents: function() {
                        new Ajax.Request(url.construct(), {
                            onComplete: function(request){
                                this.modal.update(request.responseText);
                                if (browserHeight < 710) {
                                    $('modal_container').down('.containerPresentationPCS').setStyle({
                                        height: (valuePopupHeight - 30) + 'px'
                                    });
                                }
                                Event.observe('modalClose', 'click', function() {
                                    this.modal.close();
                                }.bind(this));
                            }.bind(this)
                        });
                        return i18n('loadingDialog');
                    }.bind(this),
                    fade: true,
                    fadeDuration: 0.4,
                    opacity: 0.8,
                    width: 850,
                    height: valuePopupHeight,
                    containerClassName: 'mfmodal'
                });
                this.modal.open();
            });
        }
    }    
});

Registration = Class.create({
    initialize: function() {
		this.promoModal();
        this.initCrypto();
		this.initTypeCard();
        this.promoError();
        this.cancel();
        this.initCompatibility();
    },
    cancel: function() {
        if (!$('cancelSubscription')) { return false; }
        Event.observe('cancelSubscription', 'click', function() {
            var url = new UrlConstructor('registration/confirm_cancel');
            var modal = new Control.Modal(false, {
                contents: function() {
                    new Ajax.Request(url.construct(), {
                        onComplete: function(request){
                            modal.update(request.responseText);
                            Event.observe('modalClose', 'click', function() {
                                modal.close();
                            }.bind(this));
                            Event.observe('validate_cancel', 'click', function() {
                                var url = new UrlConstructor('registration/validate_cancel');
                                url.addVar('code', $('number').getValue());
                                new Ajax.Request(url.construct(), {
                                    onSuccess: function(transport) {
                                        var obj = transport.responseText.evalJSON();
                                        if (obj.validation == 0) {
                                            $('number_text').addClassName('errorText');
                                            $('number_alert').writeAttribute('title', obj.msg);
                                            $('number_alert').setStyle({
                                                display: 'block'
                                            });
                                            new MFTooltip();
                                        } else {
                                            $('transactionId').value = obj.tId;
                                            modal.close();
                                        }
                                    }.bind(this)
                                });
                            });
                        }
                    });
                    return i18n('loadingDialog');
                }.bind(this),
                fade: true,
                fadeDuration: 0.3,
                opacity: 0.8,
                width: 510,
                containerClassName: 'mfmodal',
                afterClose: function() {
                    if ($('transactionId').value != '') {
                        setTimeout(function() {
                            $('transactionId').up('form').submit();
                        }, 500);
                    }
                }
            });
            modal.open();
        });
    },
    initCrypto: function() {
        var cryptoInput = $('cryptoInfo');
        if (cryptoInput) {
            cryptoInput.observe('click', function() {
                var url = new UrlConstructor('Registration/Crypto');
                this.modal = new Control.Modal(false, {
                    contents: function() {
                        new Ajax.Request(url.construct(), {
                            onComplete: function(request){
                                this.modal.update(request.responseText);
                                Event.observe('modalClose', 'click', function() {
                                    this.modal.close();
                                }.bind(this));
                            }.bind(this)
                        });
                        return i18n('loadingDialog');
                    }.bind(this),
                    fade: true,
                    fadeDuration: 0.4,
                    opacity: 0.8,
                    width: 550,
                    height: 300,
                    containerClassName: 'mfmodal'
                });
                this.modal.open();
            });
        }
    },
    initCompatibility: function() {
        var compatibilityInput = $('compatibilityInfo');
        if (compatibilityInput) {
            compatibilityInput.observe('click', function() {
                var url = new UrlConstructor('Registration/Compatibility');
                this.modal = new Control.Modal(false, {
                    contents: function() {
                        new Ajax.Request(url.construct(), {
                            onComplete: function(request){
                                this.modal.update(request.responseText);
                                Event.observe('closeButton', 'click', function() {
                                    this.modal.close();
                                }.bind(this));
                            }.bind(this)
                        });
                        return i18n('loadingDialog');
                    }.bind(this),
                    fade: true,
                    fadeDuration: 0.4,
                    opacity: 0.6,
                    width: 390,
                    height: 230,
                    containerClassName: 'mfmodal'
                });
                this.modal.open();
            });
        }
    },
	promoModal: function() {
		var promoInput = null;
		this.modalOffer = null;
		if (promoInput = $('promoValid')) {
            var url = new UrlConstructor('registration/promo_info');
            url.addVar('promoCode', promoInput.getValue());
			url.addVar('promoClasse', $('promoClasse').getValue());
            this.modalOffer = new Control.Modal(false, {
                contents: function() {
                    new Ajax.Request(url.construct(), {
                        onComplete: function(request){
                            this.modalOffer.update(request.responseText);
                            Event.observe('modalClose', 'click', function() {
                                this.modalOffer.close();
                            }.bind(this));
                        }.bind(this)
                    });
                    return i18n('loadingDialog');
                }.bind(this),
                fade: true,
                fadeDuration: 0.4,
                opacity: 0.8,
                width: 550,
                height: 280,
                containerClassName: 'mfmodal'
            });
            this.modalOffer.open();
		}
	},
    promoError: function() {
        if ($('promoError')) {
            alert($('promoError').innerHTML);
        }
    },
	initTypeCard: function() {
		var select = 'carte_paiement';
		if (!$(select)) { return false; }
		$(select).observe('change', function() {
			this.changeTypeCard(select);
		}.bind(this));
		this.changeTypeCard(select);
	},
	changeTypeCard: function(id) {
		if (['SOLO_GB-SSL', 'MAESTRO-SSL'].indexOf($(id).value) !== -1) {
			this.hideFields();
            this.showPayment1();
		} else if (['ELV-SSL'].indexOf($(id).value) !== -1) {
			this.hideFields();
			this.showPayment2();
		} else if (['TPAY'].indexOf($(id).value) !== -1) {
			this.hideFields();
			this.showPaymentTpay();
		} else if (['PAYPAL'].indexOf($(id).value) !== -1) {
			this.hideFields();
			this.showPaymentPayPal();
		} else if (['AOL'].indexOf($(id).value) !== -1) {
			this.hideFields();
			this.showPaymentAol();
		} else if (['FHA'].indexOf($(id).value) !== -1) {
			this.hideFields();
			this.showPaymentFha();
		} else {
            this.hidePayment();
		}
	},
	showPaymentTpay: function() {
        new Effect.Morph('clientForm', {
            style: { height: '281px' },
            duration: 0.2,
            afterFinish: function(){
		        ['textnumcard', 'textdateexp', 'textcrypto', 'inputCardNumber', 'optionsExpire', 'inputCrypto', 'buttonSubmit'].each(function(el) {
		        	if (!$(el)) { return false; }
		            $(el).addClassName('displayNone');
		        });
		        ['tpay'].each(function(el) {
		        	if (!$(el)) { return false; }
		        	$(el).removeClassName('displayNone')
		        });
			}
        });
        new Effect.Morph('clientInfoBox', {
            style: { height: '350px' },
            duration: 0.2
        });
        new Effect.Morph('containerRight', {
            style: { height: '360px' },
            duration: 0.2
        });
        if ($('errorMessage')) {
            new Effect.Morph('errorMessage', {
                style: { top: '240px' },
                duration: 0.2
            });
        }
	},
	showPaymentPayPal: function() {
		new Effect.Morph('clientForm', {
			style: { height: '281px' },
			duration: 0.2,
			afterFinish: function(){
				['textnumcard', 'textdateexp', 'textcrypto', 'inputCardNumber', 'optionsExpire', 'inputCrypto', 'buttonSubmit'].each(function(el) {
					if (!$(el)) { return false; }
					$(el).addClassName('displayNone');
				});
				['paypal'].each(function(el) {
					if (!$(el)) { return false; }
					$(el).removeClassName('displayNone')
				});
			}
		});
		new Effect.Morph('clientInfoBox', {
			style: { height: '350px' },
			duration: 0.2
		});
		new Effect.Morph('containerRight', {
			style: { height: '360px' },
			duration: 0.2
		});
		if ($('errorMessage')) {
			new Effect.Morph('errorMessage', {
				style: { top: '240px' },
				duration: 0.2
			});
		}
	},
	showPaymentAol: function() {
		new Effect.Morph('clientForm', {
			style: { height: '281px' },
			duration: 0.2,
			afterFinish: function(){
				['textnumcard', 'textdateexp', 'textcrypto', 'inputCardNumber', 'optionsExpire', 'inputCrypto', 'buttonSubmit'].each(function(el) {
					if (!$(el)) { return false; }
					$(el).addClassName('displayNone');
				});
				['aol'].each(function(el) {
					if (!$(el)) { return false; }
					$(el).removeClassName('displayNone')
				});
			}
		});
		new Effect.Morph('clientInfoBox', {
			style: { height: '350px' },
			duration: 0.2
		});
		new Effect.Morph('containerRight', {
			style: { height: '360px' },
			duration: 0.2
		});
		if ($('errorMessage')) {
			new Effect.Morph('errorMessage', {
				style: { top: '240px' },
				duration: 0.2
			});
		}
	},
    showPaymentFha: function() {
        new Effect.Morph('clientForm', {
            style: { height: '300px' },
            duration: 0.2,
            afterFinish: function(){
                ['textnumcard', 'textdateexp', 'textcrypto', 'inputCardNumber', 'optionsExpire', 'inputCrypto', 'buttonSubmit'].each(function(el) {
                    if (!$(el)) { return false; }
                    $(el).addClassName('displayNone');
                });
                ['fha', 'fhaBtn'].each(function(el) {
                    if (!$(el)) { return false; }
                    $(el).removeClassName('displayNone')
                });
            }
        });
        new Effect.Morph('clientInfoBox', {
            style: { height: '369px' },
            duration: 0.2
        });
        new Effect.Morph('containerRight', {
            style: { height: '379px' },
            duration: 0.2
        });
        if ($('errorMessage')) {
            new Effect.Morph('errorMessage', {
                style: { top: '240px' },
                duration: 0.2
            });
        }
    },
	showPayment2: function() {
        new Effect.Morph('clientForm', {
            style: { height: '471px' },
            duration: 0.2,
            afterFinish: function() {
				['textnumcard', 'textdateexp', 'textcrypto', 'inputCardNumber', 'optionsExpire', 'inputCrypto'].each(function(el) {
                    $(el).addClassName('displayNone');
                });
				['elv', 'elvInfo', 'redInfo'].each(function(el) { $(el).removeClassName('displayNone') });
            }
        });
        new Effect.Morph('clientInfoBox', {
            style: { height: '540px' },
            duration: 0.2
        });
        new Effect.Morph('containerRight', {
            style: { height: '550px' },
            duration: 0.2
        });
        if ($('errorMessage')) {
            new Effect.Morph('errorMessage', {
                style: { top: '300px' },
                duration: 0.2
            });
        }
	},
	showPayment1 : function() {
		if (!$('clientForm')) {return false;}
		new Effect.Morph('clientForm', {
			style: { height: '321px' },
			duration: 0.2,
			afterFinish: function() {
				$$('.sPayment1').each(function(el) {
					el.removeClassName('displayNone');
				});
			}
		});
		new Effect.Morph('clientInfoBox', {
			style: { height: '390px' },
			duration: 0.2
		});
		new Effect.Morph('containerRight', {
			style: { height: '400px' },
			duration: 0.2
		});
		if ($('errorMessage')) {
			new Effect.Morph('errorMessage', {
				style: { top: '290px' },
				duration: 0.2
			});
		}
		//errorMessage//containerRight//clientInfoBox//clientForm
	},
	hideFields: function() {
        $$('.sPayment1').each(function(el) {
            el.addClassName('displayNone');
        });
        ['textnumcard', 'textdateexp', 'textcrypto', 'inputCardNumber', 'optionsExpire', 'inputCrypto', 'buttonSubmit'].each(function(el) {
            if ($(el)) { $(el).removeClassName('displayNone'); }
        });
        ['elv', 'elvInfo', 'redInfo', 'tpay', 'paypal', 'fha', 'fhaBtn', 'aol'].each(function(el) {
        	if ($(el)) { $(el).addClassName('displayNone'); }
        });
	},
	hidePayment : function() {
		if (!$('clientForm')) {return false;}
		new Effect.Morph('clientForm', {
			style: { height: '241px' },
			duration: 0.2,
			beforeStart: this.hideFields
		});
		new Effect.Morph('clientInfoBox', {
			style: { height: '310px' },
			duration: 0.2
		});
		new Effect.Morph('containerRight', {
			style: { height: '320px' },
			duration: 0.2
		});
		if ($('errorMessage')) {
			new Effect.Morph('errorMessage', {
				style: { top: '220px' },
				duration: 0.2
			});
		}
	}
});

function GetListFromXml( strXml, strTag ) {
	try	{
		var xmlDoc = getXmlDoc(strXml, false);
		var liste = xmlDoc.getElementsByTagName( strTag );
		return liste;
	} catch( e ) {
		return "Exception";
	}
}

var modalCfgProcess = null;

function sendCheckConfigClient(xml) {
    
    if ($('isAuth').getValue() == 0 || !isOk) {
        var url = new UrlSeoConstructor('PROFILE_GAMES');
        window.location = url.construct();
    } else {
        modalCfgProcess = new Control.Modal(false, {
            contents: function(){
                return '<span>' + i18n('detectionInProcess') + '</span>';
            },
            fade: true,
            fadeDuration: 0.4,
            opacity: 0.8,
            width: 500,
            overlayCloseOnClick: false,
            containerClassName: 'mfmodalCfgProcess',
            afterOpen: function(){
                setTimeout(function(){
                    ckeckConfigClient(xml, '5,0,0,2', '5.0.76.0', '255.255.0.0', null, null, null);
                }, 2000);
            }
        });
        modalCfgProcess.open();
    }
}

function ckeckConfigClient(strComponentsGame, strPortalActiveXVersion, strClientVersion, strClientVersionMask, strSkinId, strSkinVersion, strSkinVersionMask) {
	if(isTechnoPresent(strPortalActiveXVersion, strClientVersion, strClientVersionMask, strSkinId, strSkinVersion, strSkinVersionMask)) {
		var strClient = GPlayerApi_GetPCDependences();
		var arrSwHw = compareSWHWdependency(strComponentsGame, strClient);
		printDependencyMCE(arrSwHw, 'NT', '');
	}
	modalCfgProcess.close();
}

function isTechnoPresent(strPortalActiveXVersion, strClientVersion, strClientVersionMask, strSkinId, strSkinVersion, strSkinVersionMask) {
	try {
        var techno = GPlayerApi_IsActiveXInstalled(strPortalActiveXVersion);
        if(techno) {
            techno = GPlayerApi_IsPlayerInstalled(strClientVersion, strClientVersionMask, strSkinId, strSkinVersion, strSkinVersionMask);
        }
        return techno;
    } catch(e) {
        return false;
	}
}

Options = Class.create({
    initialize: function() {
        this.delay = 2000;
        this.timer = new Array();
        this.actions();
    },
    actions: function() {
        $$('div.buttonOptions').each(function(el) {
            var exentId = el.id.match(/options-(\d+)/)[1];
            var optionsList = $('expand-' + exentId);
            Event.observe(el, 'click', function() {
                this.toggleOptions(el, optionsList, exentId);
            }.bind(this));
            Event.observe(optionsList, 'mouseover', function() {
                if (typeof(this.timer[exentId]) != 'undefined') {
                    clearTimeout(this.timer[exentId]);
                }
            }.bind(this));
            Event.observe(optionsList, 'mouseout', function() {
                this.delayedToggle(el, optionsList, exentId);
            }.bind(this));
        }.bind(this));
        $$('li > a.optionSet').each(function(aEl) {
            Event.observe(aEl, 'click', function(event) {

                var el = Event.element(event);
                var optionId = el.href.match(/option_(\d+)/)[1];
                var technoId = el.up('div.optionExpand').id.match(/expand-(\d+)/)[1];

                this.up($('options-' + technoId), el.up('div.optionExpand'), technoId);

                if (typeof(gameManager) == 'object')
                	gameManager.launch(technoId, 'exent', optionId);
                else
                	gemeLauncher(technoId, optionId);
            }.bind(this));
        }.bind(this));
    },
    delayedToggle: function(el, optionsList, exentId) {
        this.timer[exentId] = setTimeout(function() {
            this.toggleOptions(el, optionsList, exentId);
        }.bind(this), this.delay);
    },
    toggleOptions: function(el, optionsList, exentId) {

    	if (el.down('a') && el.down('a').href.match(/_inaccessibly/)) return;

    	var left = el.positionedOffset().left;
        var top = el.positionedOffset().top;

        if (el.hasClassName('mygames')) {
            var li = el.up('li');
            offsetLeft = offsetTop = 0;
            left += li.positionedOffset().left;
            top += li.positionedOffset().top;

            var btDownloaded = el.up('div.downloadedButtons');
            if (btDownloaded) {
                offsetLeft = btDownloaded.positionedOffset().left;
                offsetTop = btDownloaded.positionedOffset().top;
            }

            var btDownloading = el.up('div.downloadingButtons');
            if (btDownloading) {
                offsetLeft = btDownloading.positionedOffset().left;
                offsetTop = btDownloading.positionedOffset().top;
            }

            left += offsetLeft;
            top += offsetTop;
        }

        if (el.hasClassName('buttonOnFavorite')) {
            var item = el.up('div.boxfavourite');
            left += item.positionedOffset().left;
            top += item.positionedOffset().top;
        }

        if (el.hasClassName('buttonOnGame')) {
            var item = el.up('div.buttonContainer');
            var item2 = $('containerRight');

            left += item.positionedOffset().left - 14;
            top += item.positionedOffset().top;
        }

        optionsList.setStyle({
            top: top + 'px',
            left: left + 'px'
        });
        if (!el.hasClassName('expanded')) {
            this.down(el, optionsList, exentId);
        } else {
            this.up(el, optionsList, exentId);
        }
    },
    up: function(el, optionsList, exentId) {
        new Effect.Fade(optionsList, {
             duration: 0.4,
	         afterFinish: function() {
                el.removeClassName('expanded');
                if (typeof(this.timer[exentId]) != 'undefined') {
                    clearTimeout(this.timer[exentId]);
                }
	         }.bind(this)
        });
    },
    down: function(el, optionsList, exentId) {
        new Effect.Appear(optionsList, {
             duration: 0.4,
	         afterFinish: function() {
	             el.addClassName('expanded');
	             this.delayedToggle(el, optionsList, exentId);
	         }.bind(this)
        });
    }
});

OnCloseMessage = Class.create({
    initialize: function() {
        this.clickOnLink = false;
        try {
            if (affPopback != 0) {
                this.initPopback();
            }
        } catch(e) {

        }
    },
    initPopback: function() {
        Event.observe(window.document.body, 'click', function(event) {
            try {
                var ela = Event.findElement(event, 'a');
                if (ela != document && !ela.href.match(/\#/)) {
                    this.clickOnLink = true;
                }
            } catch(e) {

            }
        }.bind(this));
        Event.observe(window, 'beforeunload', function(event) {
            if (!this.clickOnLink && (Event.pointerY(event) < 0 || isNaN(Event.pointerY(event)))) {
                var popbackCount = getCookie('aPopback');

                if (popbackCount == null) {
                    setCookie('aPopback', 1, 30, '/');
                } else if (popbackCount >= 4) {
                    return;
                } else {
                    setCookie('aPopback', parseInt(popbackCount)+1, 30, '/');
                }
                event.returnValue = i18n('initPopback');
                var url = new UrlSeoConstructor('REGISTRATION_POPBACK');
                url.addVar('status', 'from_alert');
                window.location = url.construct();
            }
        }.bind(this));
    }
});

Popback = Class.create({
    initialize: function() {
        this.inProcess = false;
        this.initAction();
        this.initInfo();
		this.clearFieldOnClick();
    },
    initInfo: function() {
        if (!$('popback-info')) { return false; }
        Event.observe('popback-info', 'click', function() {
            var url = new UrlConstructor('registration/popback_info');
            this.modal = new Control.Modal(false, {
                contents: function() {
                    new Ajax.Request(url.construct(), {
                        onComplete: function(request){
                            this.modal.update(request.responseText);
                            Event.observe('modalClose', 'click', function() {
                                this.modal.close();
                            }.bind(this));
                        }.bind(this)
                    });
                    return i18n('loadingDialog');
                }.bind(this),
                fade: true,
                fadeDuration: 0.4,
                opacity: 0.8,
                width: 600,
                containerClassName: 'mfmodal'
            });
            this.modal.open();
        });
    },
    initAction: function() {
        if (!$('popbackAction')) { return false; }
        Event.observe('popbackAction', 'click', function() {
            if (!this.inProcess) {
                this.process();
            }
        }.bind(this));
    },
	clearFieldOnClick: function() {
		if (!$('email')) { return false; }
        $('email').observe('focus', function(event) {
            var elInput = Event.element(event);
            if (elInput.hasClassName('defaultText')) {
                elInput.value = '';
                elInput.removeClassName('defaultText');
            }
        }.bind(this));
    },
    process: function() {
        this.inProcess = true;
        var url = new UrlConstructor('registration/popback_action');
        url.setAction(true);
        url.addVar('email', $('email').getValue());
        url.addVar('confirm', $('confirm').getValue());
        url.addVar('gameId', $('gameId').getValue());
        new Ajax.Request(url.construct(), {
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
                var er = new ErrorManager(obj);
                this.inProcess = false;
                if (!er.getErrors()) {
                    this.showFinish(obj.content);
                }
            }.bind(this)
        });
    },
    showFinish: function(content) {
        var modal = new Control.Modal(false, {
            contents: content,
            fade: true,
            fadeDuration: 0.3,
            opacity: 0.8,
            width: 510,
            containerClassName: 'mfmodal',
            afterClose: function() {
                setTimeout(function() {
                    var url = new UrlConstructor('home.html?status=email_has_been_added');
                    window.location = url.construct();
                }, 500);
            }
       });
       modal.open();
       Event.observe('modalClose', 'click', function() {
            modal.close();
       });
    }
});

function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) { endstr = document.cookie.length; }
    return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}

function setCookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires_date.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

Welcome = Class.create({
    initialize: function() {
        this.initConfirm();
        this.initUac();
        this.initFirewall();
        this.initDisplayProperties();
        this.initPlay();
        this.initInstallStatus();
		if ($('vista') && isVista()) {
			$('vista').value = 1;
		}
    },
    initInstallStatus: function() {
        if (!$('playerStatusContent')) { return false; }
        var sContext = null;
        if (playerReady()) {
            sContext = 'player_installed';
        } else {
            sContext = 'player_not_installed';
        }
        var browser = null;
        if (Prototype.Browser.IE) {
            browser = 'ie';
        } else if (Prototype.Browser.Gecko) {
            browser = 'gecko';
        }
        var url = new UrlConstructor('welcome/' + sContext);
        url.addVar('browser', browser);
		url.addVar('vista', isVista() ? 1 : 0);
        new Ajax.Request(url.construct(), {
            onSuccess: function(transport) {
                $('playerStatusContent').update(transport.responseText);
                if (isVista()) {
                    $('dxVista').value = 1;
                }
            }.bind(this)
        });
    },
    initUac: function() {
        if (!$('uacShow')) { return false; }
        Event.observe('uacShow', 'click', function() {
            var url = new UrlConstructor('welcome/vista_uac');
            this.modal = new Control.Modal(false, {
                contents: function() {
                    new Ajax.Request(url.construct(), {
                        onComplete: function(request){
                            this.modal.update(request.responseText);
                            Event.observe('modalClose', 'click', function() {
                                this.modal.close();
                            }.bind(this));
                        }.bind(this)
                    });
                    return i18n('loadingDialog');
                }.bind(this),
                fade: true,
                fadeDuration: 0.4,
                opacity: 0.8,
                width: 950,
                containerClassName: 'mfmodal'
            });
            this.modal.open();
        });
    },
    initFirewall: function() {
        if (!$('firewallShow')) { return false; }
        Event.observe('firewallShow', 'click', function() {
            var url = new UrlConstructor('welcome/firewall_info');
            url.addVar('type', $('selectedFirewall').getValue());
            this.modal = new Control.Modal(false, {
                contents: function() {
                    new Ajax.Request(url.construct(), {
                        onComplete: function(request){
                            this.modal.update(request.responseText);
                            Event.observe('modalClose', 'click', function() {
                                this.modal.close();
                            }.bind(this));
                        }.bind(this)
                    });
                    return i18n('loadingDialog');
                }.bind(this),
                fade: true,
                fadeDuration: 0.4,
                opacity: 0.8,
                width: 850,
                containerClassName: 'mfmodal'
            });
            this.modal.open();
        });
    },
    initDisplayProperties: function() {
        if (!$('showDisplayProperties')) { return false; }
        Event.observe('showDisplayProperties', 'click', function() {
            var url = new UrlConstructor('welcome/display_properties');
            url.addVar('isVista', (isVista()) ? 1 : 0);
            this.modal = new Control.Modal(false, {
                contents: function() {
                    new Ajax.Request(url.construct(), {
                        onComplete: function(request){
                            this.modal.update(request.responseText);
                            Event.observe('modalClose', 'click', function() {
                                this.modal.close();
                            }.bind(this));
                        }.bind(this)
                    });
                    return i18n('loadingDialog');
                }.bind(this),
                fade: true,
                fadeDuration: 0.4,
                opacity: 0.8,
                width: 850,
                containerClassName: 'mfmodal'
            });
            this.modal.open();
        });
    },
    initPlay: function() {
        if (!$('addToDownloadUrl') || !$('technoGameId')) { return false; }
        $$('a.add_to_download_list').each(function(el) {
            el.observe('click', function() {
                if (playerReady()) {
                    if (playerVersionCheck(function() {
                            downloadLauncher($('technoGameId').getValue(), 1);
                    })) {
                        downloadLauncher($('technoGameId').getValue(), 1);
                    } else {
                        return false;
                    }
                } else {
                    var url = new UrlSeoConstructor('PROFILE_GAMES');
                    window.location = url.construct();
                }
            });
        });
    },
    initConfirm: function() {
        if (!$('confirm')) { return false; }
        Event.observe('confirm', 'click', function(event) {
            var el = Event.element(event);
            if (el.checked) {
                this.active($('continue'));
            } else {
                this.unactive($('continue'));
            }
        }.bind(this));
    },
    active: function(el) {
        el.src = el.src.replace(/_un/, '_');
        el.disabled = false;
    },
    unactive: function(el) {
        el.src = el.src.replace(/_a/, '_una');
        el.disabled = true;
    }
});

function playerReady() {
    try {
        if (isDrmReadyOnClientComputer()) {
            return true;
        }
        return false;
    } catch(e) {
        return false;
    }
}

function isVista() {
    return navigator.userAgent.match(/windows\s+nt\s+6\.\d+;/i) ? true : false;
}

MultiPlayerKey  = Class.create({
    initialize: function() {
        this.modal = null;
        this.initMultiPlayerKey();
    },
    initMultiPlayerKey: function() {
        $$('a.getMultiplayerKey').each(function(el) {
            Event.observe(el, 'click', function(event) {
                var link = Event.element(event);
                if (link.up('a')) {
                    link = link.up('a');
                }
                var gameId = link.href.match(/.*?_(\d+)/)[1];
                this.show(gameId);
            }.bind(this));
        }.bind(this));
    },
    show: function(gameId) {
        this.modal = new Control.Modal(false, {
            contents: function() {
                var url = new UrlConstructor('game/multiplayer_key');
                url.addVar('gameId', gameId);
                new Ajax.Request(url.construct(), {
                    onComplete: function(request){
                        this.modal.update(request.responseText);
                        Event.observe('modalClose', 'click', function() {
                            this.modal.close();
                        }.bind(this));
                        Event.observe('fmMultiPlayer', 'submit', function(event) {
                             this.getMultiplayerKey(gameId);
                             Event.stop(event);
                        }.bind(this));
                        Event.observe('sendKey', 'click', function() {
                            this.getMultiplayerKey(gameId);
                        }.bind(this));
                    }.bind(this)
                });
                return i18n('loadingDialog');
            }.bind(this),
            fade: true,
            fadeDuration: 0.4,
            opacity: 0.8,
            width: 500,
            containerClassName: 'mfmodal'
        });
        this.modal.open();
    },
    getMultiplayerKey: function(gameId) {
        var url = new UrlConstructor('game/get_multiplayer_key');
        url.setAction(true);
        url.addVar('email', $('keyEmail').getValue());
        url.addVar('gameId', gameId);
        new Ajax.Request(url.construct(), {
            onComplete: function(transport) {
                var obj = transport.responseText.evalJSON();
                var er = new ErrorManager(obj);
                if (!er.getErrorsAlert()) {
                    alert(i18n('getMultiplayerKey'));
                    this.modal.close();
                }
            }.bind(this)
        });
    }
});

Help  = Class.create({
    initialize: function() {
        this.support();
    },
    support: function() {
        if (!$('problemType')) { return false; }
        Event.observe('problemType', 'change', function(event) {
            this.supShow($('problemType').getValue());
            this.setSubject($('problemType').options[$('problemType').selectedIndex].text);
        }.bind(this));
        Event.observe('text', 'focus', function(event) {
            var tArea = Event.element(event);
            if (!tArea.hasClassName('changed')) {
                tArea.value = '';
                tArea.addClassName('changed');
            }
        });
    },
    setSubject: function(subject) {
        $('subject').value = subject;
    },
    supShow: function(showId) {
        $$('.supItem').each(function(item) {
            item.addClassName('displayNone');
            $('supLabel').addClassName('displayNone');
        });
        if (show = $(showId)) {
            $('supLabel').removeClassName('displayNone');
            show.removeClassName('displayNone');
        }
    }
});

function getExternalUrl(protocol) {
	if (url = $('externalUrl')) {
		url = url.getValue();
		if (typeof(protocol) != 'undefined' && protocol) {
			url = url.replace(/^http|https/i, protocol);
		}
		return url;
	}
	return false;
}

function isDEAvsCheck() {
	return $('isDEAvsCheck') ? true : false;
}

MEDEAvs = Class.create({
    initialize: function(exentId) {
        this.exentId = new String(exentId);
        this.gameId = this.exentId.match(/^(.+).{2}$/)[1];
		this.modal = null;
		this.avsRequestId = 'avsRequest';
		this.avsPinRequestId = 'avsPinRequest';
		this.avsShowPinFormId = 'avsShowPinForm';
		this.toAvsFormId = 'toAvsForm';
		this.toAvsPinFormId = 'toAvsPinForm';
		this.errorCheckboxId = 'checkBoxInfo';
        this.modalOptions = {
            width: 750,
            fade: true,
            fadeDuration: 0.4,
            opacity: 0.8,
            overlayCloseOnClick: false,
            containerClassName: 'mfmodal',
            afterUpdate: function() {
                this.initClose();
            }.bind(this)
        };
        this.callback = Prototype.emptyFunction;
        this.checkEsrbCode();
    },
    cb: function(func) {
        if (typeof(func) == 'function')
            this.callback = func;
    },
    run: function() {
        if (typeof(this.callback) == 'function')
            this.callback();
    },
    initClose: function() {
        $('modalClose').observe('click', function() {
            this.modal.close();
        }.bind(this));
    },
    checkEsrbCode: function() {
        var urlGameInfo = new UrlConstructor('profile/games_get_game_info');
        urlGameInfo.addVar('geoip', 1);
        new Ajax.Request(urlGameInfo.construct(), {
            method: 'post',
            parameters: 'games=' + new Array(this.exentId).toJSON(),
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
                var esrbCode = obj.esrbCode[this.exentId];
				var countryCode = obj.geoip[this.exentId].countryCode;
                if (parseInt(esrbCode.code) >= 18 && countryCode == 'DE') {
                    this.getAvsForm();
                } else {
                    this.run();
                }
            }.bind(this)
        });
    },
    getAvsForm: function() {
        var urlAvsForm = new UrlConstructor('mede/avs_form');
        new Ajax.Request(urlAvsForm.construct(), {
            onSuccess: function(transport) {
                this.showAvsForm(transport.responseText);
            }.bind(this)
        });
    },
    showAvsForm: function(content) {
        if (this.modal) {
            this.modal.update(content);
        } else {
            this.modal = new Control.Modal(false, Object.extend(this.modalOptions, { contents: content }));
            this.modal.open();
        }
        if (fm = $(this.avsRequestId)) {
            fm.observe('submit', this.avsRequest.bind(this));
        }
        if (gp = $(this.avsShowPinFormId)) {
            gp.observe('click', this.avsShowPinForm.bind(this));
        }
    },
    avsRequest: function(event) {
        Event.stop(event);
		$(this.avsRequestId).request({
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
                if (obj.errors.size()) {
                    this.avsFailed();
                } else {
                    this.modal.close();
                    this.run()
                }
            }.bind(this)
		});
    },
    avsFailed: function() {
        $(this.avsRequestId).select('input[type="text"]').invoke('addClassName', 'errInput');
        $(this.avsRequestId).down('div.avsError').removeClassName('displayNone');
    },
    avsShowPinForm: function() {
        var c = parseInt(getCookie('tp'));
        if (c >= 3) {
            this.avsPinFailed();
            return false;
        }
        var urlAvsPinForm = new UrlConstructor('mede/avs_pin_form');
        new Ajax.Request(urlAvsPinForm.construct(), {
            onSuccess: function(transport) {
                this.showAvsPinForm(transport.responseText);
            }.bind(this)
        });
    },
    showAvsPinForm: function(content) {
        this.modal.update(content);
        if (toAvs = $(this.toAvsFormId)) {
            toAvs.observe('click', this.getAvsForm.bind(this));
        }
        if (fm = $(this.avsPinRequestId)) {
            fm.observe('submit', this.avsPinRequest.bind(this));
        }
    },
    avsPinRequest: function(event) {
        Event.stop(event);
        if (!$(this.avsPinRequestId).down('input[type="checkbox"]').getValue()) {
            $(this.errorCheckboxId).addClassName('errText');
            return false;
        }
        $(this.avsPinRequestId).request({
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
                if (obj.errors.size()) {
                    this.avsPinFailed();
                } else {
                    this.pinRequestSuccess();
                }
            }.bind(this)
        });
    },
    avsPinFailed: function() {
        var c = parseInt(getCookie('tp'));
        c = c ? c + 1 : 1;
        setCookie('tp', c, 1, '/');
        var urlAvsPinFailed = new UrlConstructor('mede/avs_pin_request_failed');
        urlAvsPinFailed.addVar('failed', c);
        new Ajax.Request(urlAvsPinFailed.construct(), {
            onSuccess: function(transport) {
                this.modal.update(transport.responseText);
                if (toAvsPin = $(this.toAvsPinFormId)) {
                    if (c >= 3)
                        toAvsPin.observe('click', this.getAvsForm.bind(this));
                    else
                        toAvsPin.observe('click', this.avsShowPinForm.bind(this));
                }
            }.bind(this)
        });
    },
    pinRequestSuccess: function() {
        var urlAvsPin = new UrlConstructor('mede/avs_pin_request_success');
        new Ajax.Request(urlAvsPin.construct(), {
            onSuccess: function(transport) {
                this.modal.update(transport.responseText);
                $('medeAvs').down('input').observe('click', function() {
                    this.modal.close();
                }.bind(this));
            }.bind(this)
        });
    }
});

SubmitFormByClick = Class.create({
	initialize: function(fmId) {
        this.fmSubmit = $(fmId);
        if (!this.fmSubmit) return ;
        this.fmSubmit.select('input').each(function(el) {
            el.observe('click', this.fmAction.bind(this));
        }.bind(this));
        this.fmSubmit.select('img').each(function(el) {
            el.observe('click', function() {
                var x64 = this.fmSubmit.select('input').first();
                x64.checked = !x64.checked;
                this.fmAction();
            }.bind(this));
        }.bind(this));
	},
    fmAction: function() {
        this.fmSubmit.submit();
        return false;
    }
});

var newWindow = '';

function openPopup(url, w, h) {
	if (!w) { w = '640'; }
	if (!h) { h = '480'; }
	if (!newWindow.closed && newWindow.location) {
		newWindow.location.href = url;
	} else {
		newWindow = window.open(url, 'name', 'width=' + w + ',height=' + h + ',menubar=no,toolbar=no,location=no,scrollbars=yes');
		if (!newWindow.opener) { newWindow.opener = self; }
	}
	if (window.focus) { newWindow.focus(); }
	return false;
}

InDownloadGlde = Class.create(InDownload, {
    addHeader: function(game) {
        var url = new UrlSeoConstructor('PROFILE_GAMES');
        return '<div class="topH3 boxBorderRight">' +
            '<h3 class="uni05_63">' +
				'<strong>' + i18n('addHeaderGame1') + ' "' + game.getGameName() + '"</strong>' +
				'<em>' + i18n('addHeaderGame1') + ' "' + game.getGameName() + '"</em>' +
			'</h3>' +
			'<div class="topH3Right pngFix"></div>' +
            '<p><span class="text">[ <a href="' + url.construct() + '">' + i18n('addHeaderGame2') + '</a> ]</span></p>' +
        '</div>';
    }
})

function GPlayerApi_InvokeCB(notification) {
	if (typeof(gameManager) == 'object') { 
		gameManager.exentNotification(notification); 
		return; 
	} else {
		log.err('Old player deprecated');
	}
}

function publisherErrorLoad(el) {
    el = $(el);
	el.hide();
	el.next().removeClassName('displayNone');
}

var ww = null;
var log = null;
log = new SimpleDebug();

Event.observe(window, 'load', function() {
	var logLevel = null;
	try { 
		logLevel = DEFINE.get('LOG_LEVEL');
	} catch(e) { 
		logLevel = 0; 
	}
	log.onLoadInit(logLevel);
    if (typeof(redirectStepWait) == 'function') {
		new InitSWFobjects();
        redirectStepWait();
        return true;
    }
    var cntx = $('context').getValue();
    ww = new WaitWindow();
    if (/profile_games/.test(cntx)) {
        myGames = new MyGames();
    }
    if (/woj_changenewsletter/.test(cntx)) {
    	new Registration();
    } 
    if (/index_offer/.test(cntx)) {
        new Offer();
    }
    
    switch (document.body.className) {
        case 'game':
        	new Options();
            new MultiPlayerKey();
            new VideoScreeenShot();
            if (MvcSkel.getVar('portalId') != 'glde') {
                new Product();
            } else {
                new GamePage();
            }
            break;
        case 'index':
            new Press();
            break;
        case 'registration':
            new Registration();
            new Popback();
            break;
        case 'profile':
            new Profile();
            new MultiPlayerKey();
            break;
        case 'welcome':
            new Welcome();
            break;
        case 'help':
            new Help();
            break;
    }

    ['dropdownGenre', 'dropdownAlpha', 'dropdownSubscription'].each(function(el) { new CategoryDropDownList(el) });
    ['fmX64'].each(function(el) { new SubmitFormByClick(el); });
    
    new GameAutocomplete();
    new SubmitFormByLink();
    new InitSWFobjects();
    new Newsletter();
    new MFTooltip();
    new OnCloseMessage();
    if ($('flashObjectVideo')) {
        triggerVideo();
    }
});
