var __meta = false;

CategoryPage = Class.create({
	initialize: function() {
		this.fmSwitch = $('fmGameType');
		if (this.fmSwitch) this.switchTypeGame();
        this.sortingPngFix();
    },
    sortingPngFix: function() {
        if (typeof(DD_belatedPNG) != 'object' || !$('sortByParam')) return;
        $('sortByParam').select('img').each(function(el) { 
            if (/\.png$/i.test(el.src)) DD_belatedPNG.fixPng(el);
        });
    },
    switchTypeGame: function() {
    	this.fmSwitch.select('input').each(function(el) {
    		el.observe('click', this.fmAction.bind(this));
    	}.bind(this));
    },
    fmAction: function(event) {
    	this.fmSwitch.submit();
    	return false;
    }
});

ControlGamePage = Class.create({
    initialize: function() {
        this.window_control = $('controlsDrawerContainer');
        this.window_mygames = $('drawerMyBrowserGameContainer');
        this.window_livescores = $('drawerLiveLeaderboardContainer');
        this.btn_controlgame = $('buttonControlsGame');
        this.btn_mybrowsergames = $('buttonMyBrowserGames');
        this.btn_livescores = $('buttonLiveLeaderboard');
        this.mainContainer = $('containerProduct');
        this.valueLeftBorder = '49px';
        this.valueRightBorder = '272px';
		this.initControllers();
        this.initBrowserGamesList();
        if ((!this.btn_controlgame) && (!this.btn_mybrowsergames) && (!this.btn_livescores)) return;
        
        if (!(this.mainContainer).hasClassName('displayNone')) this.hideElementSelectIE6(this.mainContainer);
        if (this.btn_controlgame) {
            this.btn_controlgame.observe('click', function(event) {
                this.addEventOnButton(Event.element(event), this.window_control);
            }.bind(this));
        }
        if (this.btn_mybrowsergames) {
            this.btn_mybrowsergames.observe('click', function(event) {
                this.addEventOnButton(Event.element(event), this.window_mygames);
            }.bind(this));
        }
        if (this.btn_livescores) {
            this.btn_livescores.observe('click', function(event) {
                this.addEventOnButton(Event.element(event), this.window_livescores);
            }.bind(this));
        }
    },
    addEventOnButton: function(el, window) {
        if (window) {
            if (this.isAlreadyShowedWindow(window)) {
                this.hideWindow(window, true);
                el.removeClassName('btnPressed');
            }
            else {
                if ((window != this.window_control) && (this.window_control)) {
                    if (this.isAlreadyShowedWindow(this.window_control)) {
                        this.hideWindow(this.window_control, false);
                        this.btn_controlgame.down('span').removeClassName('btnPressed');
                    }
                }
                if ((window) != (this.window_mygames) && (this.window_mygames)) {
                    if (this.isAlreadyShowedWindow(this.window_mygames)) {
                        this.hideWindow(this.window_mygames, false);
                        this.btn_mybrowsergames.down('span').removeClassName('btnPressed');
                    }
                }
                if ((window) != (this.window_livescores) && (this.window_livescores)) {
                    if (this.isAlreadyShowedWindow(this.window_livescores)) {
                        this.hideWindow(this.window_livescores, false);
                        this.btn_livescores.down('span').removeClassName('btnPressed');
                    }
                } 
                this.showWindow(el, window);
            }
        }
    },
    showWindow: function(el, window) {
        if (this.isBrowserIE6()) {
            this.hideElementSelectIE6(this.mainContainer);
        }
        window.removeClassName('displayNone');
        el.addClassName('btnPressed');
        new Effect.Morph(window, {
            style: { left: this.valueLeftBorder },
            duration: 0.8,
            afterFinish: function(){
               if (this.isBrowserIE6()) {
                   this.hideElementSelectIE6(this.mainContainer);
               }
               if (window.down('div.scrollerDrawerWindow')) {
                   window.select('.scrollerDrawerWindow').each(function(el) {el.addClassName('utilScrollerDrawer')});
                   window.select('.scrollerDrawerWindow').each(function(el) {el.removeClassName('displayNone')});
               }
            }.bind(this)
        });    
    },
    hideWindow: function(window, needShow) {
        if (window.down('div.scrollerDrawerWindow')) {
            window.select('.scrollerDrawerWindow').each(function(el) {el.removeClassName('utilScrollerDrawer')});
            window.select('.scrollerDrawerWindow').each(function(el) {el.addClassName('displayNone')});
        }
        new Effect.Morph(window, {
            style: { left: this.valueRightBorder },
            duration: 0.6,
            afterFinish: function(){
                if (this.isBrowserIE6() && needShow) {
                    this.showElementSelectIE6(this.mainContainer);
                }
                window.addClassName('displayNone');
            }.bind(this)
        });
    },
    isAlreadyShowedWindow: function(window) {
        if (!window.hasClassName('displayNone')) {
            return true;
        }
        else {
            return false;
        }
    },
    isBrowserIE6: function() {
        Prototype.Browser.IEVersion = parseFloat(navigator.appVersion.split(';')[1].strip().split(' ')[1]);
        Prototype.Browser.IE6 = Prototype.Browser.IEVersion == 6;
        return Prototype.Browser.IE6;
    },
    hideElementSelectIE6: function(event) {
        if (!this.isBrowserIE6()) return;
        event.select('select').each(function(el) {
            if (el.hasClassName('needHideThisSelect')) {
                el.hide();
                el.addClassName('needShowThisSelect');
            }
        }.bind(this));
    },
    showElementSelectIE6: function(event) {
        event.select('select').each(function(el) {
            if (el.hasClassName('needShowThisSelect')) {
                el.show();
                el.removeClassName('needShowThisSelect');
            }
        }.bind(this));
    },
    initControllers: function() {
        this.keyboardTab = $('keyboardTab');
        this.joypadTab = $('joypadTab');
        if (!this.keyboardTab || !this.joypadTab) return ;
        this.keyboardTab.observe('click', function() {
            this.keyboardActive();
        }.bind(this));
        this.joypadTab.observe('click', function() {
            this.joypadActive();
        }.bind(this));
		this.drawerJoypad = $('drawerJoypad');
		this.drawerKeyboard = $('drawerKeyboard');
    },
    initBrowserGamesList: function() {
        if (this.btn_mybrowsergames) this.btn_mybrowsergames.observe('click', this.loadBrowserGamesList.bind(this));
    },
    loadBrowserGamesList: function() {
        if (!this.window_mygames.down('img').hasClassName('spinner')) return ;
        var browser = new Hash();
        try {
            var xml = writeFullyDownloadedListGamesEmulatorAllTechno();
            var xmlDoc = getXmlDoc(xml);
            result = xmlDoc.getElementsByTagName('ContentDescriptor');
            for (var i = 0; i < result.length; i++) {
                el = result.item(i);
                browser.set(el.getAttribute('Id'), new MetaGame(el.getAttribute('Id'), el.getAttribute('codeTechno')));
            }
            var url = new UrlConstructor('profile/get_games_info');
            new Ajax.Request(url.construct(), {
                method: 'post',
                parameters: 'games=' + browser.keys().toJSON(),
                onSuccess: function(transport) {
                    var obj = transport.responseText.evalJSON();
                    if (typeof(obj.games) != 'undefined') {
                        browser.keys().each(function(technoId) { 
                            if (typeof(obj.games[technoId]) == 'object') 
                                Object.extend(browser.get(technoId), obj.games[technoId]);
                            else
                                browser.unset(technoId);
                        }.bind(this));
                        this.renderBrowserGamesList(browser);
                    } 
                }.bind(this)
            });
        } catch(e) {
            log.err(e);
            this.hideWindow(this.window_mygames, false);
        }
    },
    renderBrowserGamesList: function(browserGamesList) {
        var container = this.window_mygames.down('.scrollerDrawerWindow');
        container.removeClassName('center');
        container.update('');
     
        var browserSorted = new Array();
        browserGamesList.each(function(item) {
            browserSorted[item.value.gameId] = item.value; 
        });   
        browserSorted.sort(sortByTitle);
        browserSorted.each(function(metaGame) {
            var link = new Element('a', {href: metaGame.gameUrl + '?autostart=1'});
            link.insert(new Element('p').update(metaGame.title));
            container.insert(link);
        });
    },
    keyboardActive: function() {
		if (this.joypadTab.hasClassName('inactiveTab')) return ;
		this.joypadTab.addClassName('inactiveTab');
		this.keyboardTab.removeClassName('inactiveTab');
		this.drawerKeyboard.removeClassName('displayNone');
		this.drawerJoypad.addClassName('displayNone');
    },
    joypadActive: function() {
		if (this.keyboardTab.hasClassName('inactiveTab')) return ;
		this.keyboardTab.addClassName('inactiveTab');
		this.joypadTab.removeClassName('inactiveTab');
        this.drawerKeyboard.addClassName('displayNone');
        this.drawerJoypad.removeClassName('displayNone');
    },
    initVolume: function() {
        if (!$('volumeComponent')) return;
        var zoom_slider = $('zoom_slider');

        var volume = new Control.Slider(zoom_slider.down('.handle'), zoom_slider, {
            range: $R(0, 100),
            sliderValue: 100,
            increment: 10,
            values: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
            onSlide: function(value) {
                //log.debug('change volume on slide. value: ' + value);
                //setVolumeAllTechno(value);
            },
            onChange: function(value) {
                log.debug('change volume on change. value: ' + value);
                setVolumeAllTechno(parseInt(value));
            }
        });
        $('volume_min').observe('click', function(event) {
            var value = volume.value - volume.increment;
            log.debug('change volume on button min. value: ' + value);
            volume.setValue(value);
        }.bind(this));
        $('volume_max').observe('click', function(event) {
            var value = volume.value + volume.increment;
            log.debug('change volume on button max. value: ' + value);
            volume.setValue(value);
        }.bind(this));
    }
});

HomePage = Class.create({
    initialize: function() {
        if (!$('mostPlayed')) return;
        if ($('mostPlayedContent').down('tr')) {
            $('mostPlayedContent').down('tr').addClassName('rolloverElementGame');
        }
        $('mostPlayed').select('tr').each(function(el) {
            el.observe('mouseover', this.overLineMostPlayed.bind(this));
        }.bind(this));
        $('mostPlayed').select('tr').each(function(el) {
            el.observe('mouseout', this.outLineMostPlayed.bind(this));
        }.bind(this));
    },
    overLineMostPlayed: function(event) {
        var elA = Event.element(event);
        if (!elA.hasClassName('rowLinkGame')) {
            elA = elA.up('tr');
        }
        $(elA).addClassName('rolloverElementGame');
        if ($('mostPlayedContent').down('tr') != $(elA)) {
            $('mostPlayedContent').down('tr').removeClassName('rolloverElementGame');
        }
    },
    outLineMostPlayed: function(event) {
        var elA = Event.element(event);
        if (!elA.hasClassName('rowLinkGame')) {
            elA = elA.up('tr');
        }
        $(elA).removeClassName('rolloverElementGame');
        $('mostPlayedContent').down('tr').addClassName('rolloverElementGame');
    }
});

GameRating = Class.create({
	initialize: function() {
		this.ratingSelector = $('ratingSelector');
		if (this.ratingSelector) this.ratingSelector.observe('change', this.saveRate.bind(this));
	},
	saveRate: function(event) {
		var rate = Event.element(event);
        var rateUrl = new UrlConstructor('game/add_rate');
        rateUrl.setAction(true);
        rateUrl.addVar('rating', rate.getValue());
        rateUrl.addVar('gameId', $('gameId').getValue());
        new Ajax.Request(rateUrl.construct(), {
        	method: 'get',
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
                var er = new ErrorManager(obj);
                if (er.getErrors()) return;
                this.disableRate();
                this.updateRate(obj.rating);
            }.bind(this)
        });
	},
	disableRate: function() {
		this.ratingSelector.disabled = true;
	},
	updateRate: function(rating) {
		$('gameRating').update(rating);
	}
});

LastPlayedEffect = Class.create({
    initialize: function() {
        if (typeof(isOk) != 'undefined') {
            if ((isOk == false) && $('hideMaskLastPlayed')) {
                $('hideMaskLastPlayed').removeClassName('displayNone');
            }
        } 
    }
});

/* NEED REFACTORING IN FUTURE */
Welcome = Class.create({
    initialize: function() {
        this.initConfirm();
        this.initUac();
        this.initFirewall();
        this.initDisplayProperties();
        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 isVista() {
    return navigator.userAgent.match(/windows\s+nt\s+6\.\d+;/i) ? true : false;
}

Registration = Class.create({
    initialize: function() {
        new CryptoInfo();
		this.initStep2();
		this.initPromo();
        this.initTypeCard();
        this.cancel();
    },
    initStep2: function() {
    	var buttonSubmit = $('buttonSubmit');
    	if (buttonSubmit) {
    		buttonSubmit.down('a').observe('click', function() {
    			ww.show(function() {
    				document.forms.paymentForm.submit();
    			});
    		});
    	}
    	var boxMonth = $('boxMonthPrice');
    	var boxYear = $('boxYearPrice');
        if ((boxMonth) && (boxYear)) {
	        boxMonth.observe('click', function() {
	        	if (!boxMonth.down('input').disabled) {
	        		boxMonth.down('input').checked = 'true';
	        		this.setOfferFrom(boxMonth);
	        	}
	        }.bind(this));
	        boxYear.observe('click', function() {
	        	if (!boxYear.down('input').disabled) {
		        	boxYear.down('input').checked = 'true';
		        	this.setOfferFrom(boxYear);
	        	}
	        }.bind(this));
        }
    },
    setOfferFrom: function(box) {
    	$$('input.formOffer').each(function(el) { el.value = box.down('input.offerId').value; });
    	$('calculatedPrice').update(box.down('input.price').value);
    },
    initPromo: function() {
    	var btPromo = $('verifyPromo');
    	if (!btPromo) return;
    	var fmPromo = $(document.forms.promoForm);
    	btPromo.observe('click', function() {
        	fmPromo.request({
        		method: 'get',
        		parameters: { offer: $('formOffer').value },
        		onComplete: function(transport) {
    	            var obj = transport.responseText.evalJSON();
    	            var er = new ErrorManager(obj);
    	            if (er.getErrors()) return;
    	            if (obj.promoOffer == 1) {
    	            	document.boxPrice.costPlan[0].disabled = true;
    	            	document.boxPrice.costPlan[1].disabled = true;
    	            	$('promoInput').disabled = true;
    	            	$$('input.formOffer').each(function(el) { el.value = obj.promoOfferId; });
    	            	$$('input.formPromo').each(function(el) { el.value = obj.promoCode; });
    	            	$('calculatedPrice').update(obj.price);
    	            } else if (obj.promoOfferWOPayment == 1) {
    	            	window.location = obj.url;
    	            }
        		}.bind(this)
        	});
    	}.bind(this));
    },
    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();
        });
    },
    initTypeCard: function() {
        var select = 'paymentType';
        if (!$(select)) { return false; }
        $(select).observe('change', function() {
            this.changeTypeCard(select);
        }.bind(this));
        this.changeTypeCard(select);
    },
    changeTypeCard: function(id) {
    	if ((['PAYPAL'].indexOf($(id).value) !== -1)) {
    		this.showPaypal();
    	} else {
    		this.resetForm();
    	}
    },
    showPaypal: function() {
    	 this.hideElements(['completeYourOrderContainer', 'headerPaymentArea', 'billingAddressBox']);
    	 this.hideElements($$('.paypalHide'));
    	 if ($('containerPaypal')) $('containerPaypal').removeClassName('displayNone');
    },
    resetForm: function() {
    	 this.showElements(['completeYourOrderContainer', 'headerPaymentArea', 'billingAddressBox']);
    	 this.showElements($$('.paypalHide'));
         if ($('containerPaypal')) {
            if (!$('containerPaypal').hasClassName('displayNone')) $('containerPaypal').addClassName('displayNone');    
         }
    },
    hideElements: function(arr) {
    	arr.each(function(el) { if (el = $(el)) el.hide()});
    },
    showElements: function(arr) {
    	arr.each(function(el) { if (el = $(el)) el.show()});
    }
});

function cancelReason() {
    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();
    });
}

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();
    }
});

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);
            }
        }
    });
}

/* END OF NEED REFACTORING IN FUTURE */

CryptoInfo = Class.create({
    initialize: function() {
        this.crypto = $('cryptoInfo');
        if (this.crypto) Event.observe(this.crypto, 'click', this.showCryptoInfo.bind(this));
    },
    showCryptoInfo: 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();
    }
});

Profile = Class.create({
    initialize: function() {
        this.btnPassword = $('headerChangePassword');
        this.btnEmail = $('headerChangeEmail');
        this.btnUpdate = $('headerUpdateBilling');
        this.btnNewsletter = $('headerChangeNewsletter');
        this.payPalForm = $('payPalFormUpdate');
        this.initCreditCardUpdate();        
        this.initAccountPage();		
    },
    initCreditCardUpdate: function() {
        if (!this.btnUpdate) return ;
        this.btnUpdate.observe('click', this.toggleCardUpdatBlock.bind(this));
        if (this.payPalForm) return ;
        this.btnUpdate.next().down('a.cancelButtonInfo').observe('click', this.toggleCardUpdatBlock.bind(this));
        this.btnUpdate.next().down('a.saveButtonInfo').observe('click', this.creditCardUpdateProcess.bind(this));
    },
	initAccountPage: function() {
        if (!this.btnPassword && !this.btnEmail) return ;
        if (this.btnPassword) {
			this.btnPassword.observe('click', this.togglePasswordBlock.bind(this));
			this.btnPassword.next().down('a.cancelButtonInfo').observe('click', this.togglePasswordBlock.bind(this)); 
			this.btnPassword.next().down('a.saveButtonInfo').observe('click', this.savePassword.bind(this)); 
		} 
        if (this.btnEmail) {
			this.btnEmail.observe('click', this.toggleEmailBlock.bind(this));
			this.btnEmail.next().down('a.cancelButtonInfo').observe('click', this.toggleEmailBlock.bind(this));
			this.btnEmail.next().down('a.saveButtonInfo').observe('click', this.savePersonal.bind(this));
		}
        if (this.btnNewsletter) {
            this.btnNewsletter.observe('click', this.toggleNewsletterBlock.bind(this));
            this.btnNewsletter.next().down('a.cancelButtonInfo').observe('click', this.toggleNewsletterBlock.bind(this));
            this.btnNewsletter.next().down('a.saveButtonInfo').observe('click', this.saveNewsletter.bind(this));
        }
	},
	togglePasswordBlock: function() {
        if ($('containerChangePassword').hasClassName('displayNone')) {
            $('containerChangePassword').removeClassName('displayNone');
            $('headerChangePassword').down('.pic_box_toggle').removeClassName('state_collapse');
        } else {
            $('containerChangePassword').addClassName('displayNone');
            $('headerChangePassword').down('.pic_box_toggle').addClassName('state_collapse');
        }
	},
	toggleEmailBlock: function() {
        if ($('containerChangeEmail').hasClassName('displayNone')) {
            $('containerChangeEmail').removeClassName('displayNone');
            $('headerChangeEmail').down('.pic_box_toggle').removeClassName('state_collapse');
        } else {
            $('containerChangeEmail').addClassName('displayNone');
            $('headerChangeEmail').down('.pic_box_toggle').addClassName('state_collapse');
        }
	},
	toggleNewsletterBlock: function() {
        if ($('containerChangeNewsletter').hasClassName('displayNone')) {
            $('containerChangeNewsletter').removeClassName('displayNone');
            $('headerChangeNewsletter').down('.pic_box_toggle').removeClassName('state_collapse');
        } else {
            $('containerChangeNewsletter').addClassName('displayNone');
            $('headerChangeNewsletter').down('.pic_box_toggle').addClassName('state_collapse');
        }
	},
    toggleCardUpdatBlock: function() {
        if ($('containerUpdateBilling').hasClassName('displayNone')) {
            $('containerUpdateBilling').removeClassName('displayNone');
            $('headerUpdateBilling').down('.pic_box_toggle').removeClassName('state_collapse');
            if (!this.payPalForm) {
                this.clearCardUpdateInfo();
            }
        } else {
            $('containerUpdateBilling').addClassName('displayNone');
            $('headerUpdateBilling').down('.pic_box_toggle').addClassName('state_collapse');
        }
    },
    clearCardUpdateInfo: function() {
        var form = $('fmCardUpdate');
        form.getInputs('text').each(function(el) { el.value = '' });
        form.select('select').each(function(el) { el.selectedIndex = 0 });
    },
    savePassword: function(event) {
		var form = $('passwordEdit');
        var url = new UrlConstructor('profile/account_save_password');
        url.setAction(true);
        new Ajax.Request(url.construct(), {
            parameters: form.serialize(),
            method: 'post',
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
				form.getInputs('password').each(function(el) { el.value = ''; });
                var er = new ErrorManager(obj);
                if (er.getErrors()) return false;
                this.togglePasswordBlock();
                var modal = new Control.Modal(false, {
                    contents: obj.info,
                    fade: true,
                    fadeDuration: 0.4,
                    opacity: 0.8,
                    width: 500,
                    containerClassName: 'mfmodal'
                });
                modal.open();
                Event.observe('modalClose', 'click', function() { modal.close() });
            }.bind(this)
        });
    },
    savePersonal: function(event) {
		var form = $('infoEdit');
        var url = new UrlConstructor('profile/account_save_personal');
        url.setAction(true);
        new Ajax.Request(url.construct(), {
            parameters: form.serialize(),
            method: 'post',
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
                var er = new ErrorManager(obj);
				if (er.getErrors()) return ;
				this.toggleEmailBlock();
                var modal = new Control.Modal(false, {
                    contents: obj.info,
                    fade: true,
                    fadeDuration: 0.4,
                    opacity: 0.8,
                    width: 500,
                    containerClassName: 'mfmodal'
                });
                modal.open();
                Event.observe('modalClose', 'click', function() { modal.close() });
            }.bind(this)
        });
    },
    saveNewsletter: function(event) {
		var form = $('newsletterEdit');
        var url = new UrlConstructor('profile/account_save_newsletter');
        url.setAction(true);
        new Ajax.Request(url.construct(), {
            parameters: form.serialize(),
            method: 'post',
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
                var er = new ErrorManager(obj);
				if (er.getErrors()) return ;
				this.toggleNewsletterBlock();
                var modal = new Control.Modal(false, {
                    contents: obj.info,
                    fade: true,
                    fadeDuration: 0.4,
                    opacity: 0.8,
                    width: 500,
                    containerClassName: 'mfmodal'
                });
                modal.open();
                Event.observe('modalClose', 'click', function() { modal.close() });
            }.bind(this)
        });
    },
    creditCardUpdateProcess: function(event) {
        ww.show();
        var form = $('fmCardUpdate');
        var url = new UrlConstructor('profile/account_save_card_update');
        url.setAction(true);
        url.addVar('process', 'upgrade');
        new Ajax.Request(url.construct(), {
            parameters: form.serialize(),
            method: 'post',
            onSuccess: function(transport) {
                var obj = transport.responseText.evalJSON();
                var er = new ErrorManager(obj);
                if (er.getErrors()) return ;
                this.toggleCardUpdatBlock();
                this.clearCardUpdateInfo();
                var modal = new Control.Modal(false, {
                    contents: obj.info,
                    fade: true,
                    fadeDuration: 0.4,
                    opacity: 0.8,
                    width: 500,
                    containerClassName: 'mfmodal'
                });
                modal.open();
                Event.observe('modalClose', 'click', function() { modal.close() });
            }.bind(this)
        });
    }
});

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)
        });
    }
});

CancelInfo = Class.create({
    initialize: function() {
		var cancelLang = new String($('cancel').getValue());
		if (!cancelLang.empty()) this.showCancelInfo(cancelLang);
	},
	showCancelInfo: function(cancelLang) {
	    var modal = new Control.Modal(false, {
	        contents: function() {
	            var showInfo = new UrlConstructor('registration/cancel_info');
	            showInfo.addVar('lang', cancelLang);
	            new Ajax.Request(showInfo.construct(), {
	                onComplete: function(request){
	                    modal.update(request.responseText);
	                    Event.observe('modalClose', 'click', function() {
	                        modal.close();
	                    });
	                }
	            });
	            return i18n('loadingDialog');
	        },
	        fade: true,
	        fadeDuration: 0.4,
	        opacity: 0.8,
	        width: 500,
	        containerClassName: 'mfmodal'
	    });
	    modal.open();
	}
});

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;
    }
});

GameTapPlayerV2 = Class.create({
    initialize: function() {
        if (typeof(isDrmReadyOnClientComputer) != 'function') return ;
        if (this.isSupportedSystem()) return false;
        
        this.playerContainer = $('gameTapInstall');
        this.player = null;
        this.startNow = true;
        
        navigator.plugins.refresh(false);
        this.isUpdateAvailable(function(updateAvailable, isUpdate) {
            if (updateAvailable) this.redirectToInstallPage(isUpdate);
            else if (!browserGame) {
                try {
                    this.initializePlayer();
                } catch(e) {
                    log.debug('init failed');      
                }   
            }  
             
        }.bind(this));
    },
    isSupportedSystem: function() {
        if (!Prototype.System.isWin || (!Prototype.Browser.IE && !Prototype.Browser.Gecko)) {
            var cntx = $('context').getValue();
            if (/profile_games/.test(cntx)) {
                myGames = new MyGames();
            } 
            return true;
        }
        return false;
    },
    redirectToInstallPage: function(isUpdate) {
        this.startNow = false;
        var installUrl = new UrlSeoConstructor('INSTALLPLAYER_INSTALL');
        installUrl.addVar('browser', (Prototype.Browser.IE) ? 'IE' : 'FF');
        if (isUpdate) installUrl.addVar('type', 'update');
        if (gameTapPlayerType()&1) installUrl.addVar('process', 'migration');
        //alert('redirect to install/update');
        window.location = installUrl.construct();
    },
    needInstallFFPlugin: function() {
        for (var x=0; x<navigator.plugins.length; ++x) {
            if (navigator.plugins[x][0].type == "application/x-vnd-gametap-player") return false;
        }
        return true;
    },
    needShowGamesPath: function() {
        var code = this.player.CheckUpdate();
        log.debug('detect show games path:' + code);
        if (code != 0 && code != 1) {
            if (code == -1) return true;
        } 
        if (gameTapPlayerType()&1) return true;
        return false; 
    },
    isUpdateAvailable: function(callback) {
        if (Prototype.Browser.IE) {
            if (Cookie.get('ie_server_version')) {
                callback(true, true);
                return ;  
            } 
            try {
                new ActiveXObject("GameTapPlayer.GameTapPlayerCtrl");        
            } catch(e) {
                callback(true, false);
                return ;
            }
        } else {
            if (this.needInstallFFPlugin()) {
                callback(true, false);
                return ;
            }
        }
        this.createPlayerObject(function() {
            this.setUpdateUrls();
            var playerVersion = this.player.Version();
            var serverVersion = this.player.GetServerPluginVersion();
            log.debug('player version: ' + playerVersion + ' server version: ' + serverVersion);
            if (playerVersion != serverVersion) callback(true, true);
            else {
                var code = this.player.CheckUpdate();
                log.debug('check update:' + code);
                if (code != 0 && code != 1) {
                    if (code == -1) callback(true, false);
                    else callback(true, true);
                } else callback(false);
                return ; 
            } 
        }.bind(this));
    },
    setUpdateUrls: function() {
        this.player.SetUpdateUrls(DEFINE.get('PLAYER_BOOTSTRAP'), DEFINE.get('PLAYER_INSTALL'));          
    },
    setInstallerGamePath: function(path) {
        this.player.SetInstallerGamePath(path);  
    },
    createActiveX: function() {
        log.debug('try create ActiveX');
        try {
            this.playerContainer.insert('<object id="player_ActiveX"\
                     width="0" height="0"\
                     classid="CLSID:4f29de54-5eb7-4d76-b610-a86b5cd2a234"\
                     codebase="' + DEFINE.get('PLAYER_CAB') + this.version + '"></object>');
            this.player = $('player_ActiveX');
            this.player.setStyle({
                width: '0',
                height: '0'
            });
            if (this.player.Version() == Cookie.get('ie_server_version')) {
                Cookie.unset('ie_server_version');    
            }
            return true;
        } catch (e) {
            return false;
        }
    },
    createNPAPI: function() {
        log.debug('try create NPAPI');
        navigator.plugins.refresh(false);
        this.player = new Element('OBJECT', {
            'id': 'player_NPAPI',
            'width': 0,
            'height': 0,
            'type': 'application/x-vnd-gametap-player'
        });
        this.player.setStyle({
            width: '0',
            height: '0'
        });
        this.playerContainer.insert(this.player)
        this.player.Version();
    },
    createPlayerObject: function(callback, isUpdate) {
        log.debug('create player');
        if (Prototype.Browser.IE) {
            var retryCallback = function() {
                try {
                    callback();
                } catch (e) {
                    setTimeout(retryCallback, 1000);
                }
            }

            var version = null;
            if (isUpdate && !Cookie.get('ie_server_version')) {
                log.debug('check version');
                var playerLocal = new ActiveXObject("GameTapPlayer.GameTapPlayerCtrl");
                playerLocal.SetUpdateUrls(DEFINE.get('PLAYER_BOOTSTRAP'), DEFINE.get('PLAYER_INSTALL'));
                var serverVersion = playerLocal.GetServerPluginVersion();
                var playerVersion = playerLocal.Version();
                if (playerVersion != serverVersion && Cookie.get('ie_player_initialized')) {
                    log.debug('set cookie. server version:' + serverVersion);
                    Cookie.set('ie_restart_required', 1);
                    Cookie.set('ie_server_version', serverVersion, 60 * 60);
                }
                playerLocal.ShutdownPlayer();
                playerLocal = null;
            } 
            if (Cookie.get('ie_restart_required')) {
                log.debug('show restart required error');
                var modal = new Control.Modal(false, {
                    contents: function() {
                        var showInfo = new UrlConstructor('error/info');
                        showInfo.addVar('code', 'RESTART');
                        new Ajax.Request(showInfo.construct(), {
                            onComplete: function(request) {
                                modal.update(request.responseText);
                                $('modalClose').observe('click', function(){
                                    modal.close();
                                });
                            }
                        });
                        return i18n('loadingDialog');
                    },
                    fade: true, fadeDuration: 0.4, opacity: 0.8, width: 500, containerClassName: 'mfmodal'
                });
                modal.open();
                return ;                
            } else if (Cookie.get('ie_server_version')) {
                log.debug('version from cookie');
                version = Cookie.get('ie_server_version');
            } else if (serverVersion) {
                log.debug('version from plugin');
                version = serverVersion;
            }

            this.version = version ? ('#Version=' + version.replace(/\./g,",")) : '';
            l(this.version);
            
            try { 
                this.createActiveX();
                retryCallback();
            } catch(e) {
                l(e.message);
                $('player_ActiveX').remove();
                setTimeout(this.createActiveX.bind(this), 1000);            
            }
        } else {
            try {
                this.createNPAPI();
                callback();
            } catch(e) {
                l(e.message);
                $('player_NPAPI').remove();
                setTimeout(this.createNPAPI.bind(this), 1000);            
            }
            
        }    
    },
    destroyPlayerObject: function() {
        log.debug('destroy player object');
//        this.player.ShutdownPlayer();
        this.player.remove();
        this.player = null;  
    },
    initializePlayer: function() {
        this.destroyPlayerObject();
        try {
            log.debug('Player initialization');
            var bootStrap = DEFINE.get('PLAYER_BOOTSTRAP');
            var installUrl = DEFINE.get('PLAYER_INSTALL');
            if (Prototype.Browser.IE) Cookie.set('ie_player_initialized', 1);
            isDrmReadyOnClientComputer(playerLogin, ssoToken, bootStrap, installUrl, 'gameTapPlayer');
        } catch (e) {
            log.err(e);
        }
    }    
});

GameTapInstallerV2 = Class.create(GameTapPlayerV2, {
    initialize: function() {
        this.cPath      = $('containerPath');
        this.cProgress  = $('containerProgress');
        this.inputPath  = $('gamesPath');
        this.btnPath    = $('browseForGamesPath');
        this.progressBar     = $('progressElement').down('.currentProgress');
        this.progressText    = $('progressElement').down('.textValueProgress');
        this.btnPathContinue = $('btnStartInstall').down('a');
        this.playerContainer = $('gameTapInstall');
        this.player     = null;
        
        this.inputPath.observe('change', this.changeGamesPath.bind(this));
        
        navigator.plugins.refresh(false);
        
        if (Prototype.Browser.IE) {
            this.installIEActiveX();
        } else {
            if (this.needInstallFFPlugin()) this.installFFPlugin();
            else {
                try {
                    this.createNPAPIForCheckVersion();                
                } catch(e) {
                    l(e.message);
                    $('player_NPAPI').remove();
                    setTimeout(this.createNPAPIForCheckVersion.bind(this), 1000);            
                }
            } 
        }        
    },
    createNPAPIForCheckVersion: function() {
        this.createNPAPI();
        this.setUpdateUrls();
        var playerVersion = this.player.Version();
        var serverVersion = this.player.GetServerPluginVersion()
        if (playerVersion != serverVersion) {
            log.debug('need update plugin');
            this.installFFPlugin();  
        } 
        else this.setInstallPath(); 
    },
    installFFPlugin: function() {
        InstallTrigger.startSoftwareUpdate(DEFINE.get('PLAYER_XPI') + '?clientTime='+(new Date()), 0);
    },
    installIEActiveX: function() {
        this.setInstallPath();
    },
    changeGamesPath: function() {
        log.debug('set path: ' + this.inputPath.value);
        this.setInstallerGamePath(this.inputPath.value);
    },
    btnChangePath: function() {
        this.inputPath.value = this.player.GetInstallerGamePath(true);
        this.changeGamesPath();
    },
    setInstallPath: function() {
        var isUpdate = parseInt($('isUpdate').value);
        log.debug('setInstallPath. is update: ' + (isUpdate ? 'true' : 'false'));
        this.createPlayerObject(function() {
            if (this.needShowGamesPath()) {
                this.cProgress.hide();
                this.cPath.show();
                this.btnPath.observe('click', this.btnChangePath.bind(this));
                this.btnPathContinue.observe('click', this.startInstall.bind(this));
                this.inputPath.value = this.player.GetInstallerGamePath(false);
                this.changeGamesPath();
            } else {
                this.startInstall();
            }
        }.bind(this), isUpdate);
    },
    startInstall: function() {
        log.debug('start install');
        this.cPath.hide();
        this.cProgress.show();
        this.setUpdateUrls();
        this.player.InitializePlugin(false, "");
    },
    setProgress: function(progress) {
        log.debug('progress: ' + progress);
        if (progress == 0) return null;
        this.progressBar.setStyle({width: ((progress == 100) ? 101 : progress) + '%'});
        this.progressText.update(progress + '%');    
    },
    initComplete: function() {
        this.setProgress(100);
        if (Prototype.Browser.Gecko) navigator.plugins.refresh(false);
        var s = new UrlSeoConstructor('PROFILE_DASHBOARD');
        setTimeout(function() { window.location = s.construct(); }, 3000); 
    }
});

var ww = null;
var gameControls = null;
var myGames = null;
var webPlayer = null;
var 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;
    }
	transparentbg('main_bg');
	ww = new WaitWindow();
	var cntx = $('context').getValue();
	if (!/installplayer_install/.test(cntx)) {
		new GameTapPlayerV2();
	} else {
        GameTapInstaller = new GameTapInstallerV2();
    }
    if (/profile_account/.test(cntx)) {
        new CryptoInfo();
        new Profile();
    } 
    if (/profile_.*/.test(cntx)) new LastPlayedEffect();
    if (/subscription_.*/.test(cntx)) new Registration();
    if (/welcome_.*/.test(cntx)) new Welcome();
    if (/game_.*/.test(cntx)) {
		gameControls = new ControlGamePage();
    	new GameRating();
    	new GamePage();
    }
    if (/registration_cancel/.test(cntx)) cancelReason();
    if (/game_videoscreenshots/.test(cntx)) new VideoScreeenShot();
    ['dropdownGenre', 'dropdownSubscription'].each(function(el) { new CategoryDropDownList(el) });
    ['fmX64'].each(function(el) { new SubmitFormByClick(el); });
	new CancelInfo();	
    new HomePage();
    new InitSWFobjects();
    new GameAutocomplete();
    new SubmitFormByLink();
    new CategoryPage();
    new MFTooltip();
});

Event.observe(document, 'click', function() {
	transparentbg('main_bg');
});

Prototype.System = {
	isMac: navigator.appVersion.indexOf("Mac") != -1 ? true : false,
	isNix: navigator.appVersion.indexOf("Linux") != -1 ? true : false,
	isWin: navigator.appVersion.indexOf("Windows") != -1 ? true : false
}

function l(x) {
    if (typeof(console) == 'object') console.log(x);
}

function gameTapPlayerType() {
    var hasActiveX=0, hasSilentPlayer=0, hasOldSilentPlayer=0, hasOldWebPlayer=0, hasRichPlayer=0;
    if (window.ActiveXObject) {
        var updater, playerTemp, browserTool;
        hasActiveX = 1;
        try { browserTool = new ActiveXObject("GameTap.BrowserToolCtrl.1"); } catch (e) { browserTool = null; }
        if (browserTool != null) hasRichPlayer = 1;
        try { updater = new ActiveXObject("GameTapWebUpdater.Main.1"); } catch (e) { updater = null; }
        if (updater != null) {
            if (typeof updater.Version == "undefined") hasOldWebPlayer    = 1;
            else                                       hasOldSilentPlayer = 1;
        }
        try { playerTemp = new ActiveXObject("GameTapPlayer.GameTapPlayerCtrl.1"); } catch (e) { playerTemp = null; }
        if (playerTemp != null) hasSilentPlayer = 1;
        browserTool = null;
        updater     = null;
        playerTemp  = null;
    } else {
        var i, numPlugins = navigator.plugins.length, plugin, clientVersion;
        hasActiveX = 0;
        for (var i=0; i < numPlugins; i++ ) {
            plugin = navigator.plugins[i];
            if (plugin.filename.toLowerCase() == "npgametaptool.dll") hasRichPlayer = 1;
            if (plugin.filename.toLowerCase() == "npgametapwebupdater.dll") {
                clientVersion = plugin.description.substring(plugin.name.length+1, plugin.description.length);
                if (clientVersion == "") hasOldWebPlayer    = 1;
                else                     hasOldSilentPlayer = 1;
            }
            if (plugin[0].type == "application/x-vnd-gametap-player") hasSilentPlayer = 1;
        }
    }
    return (hasActiveX << 7) | (hasSilentPlayer << 3) | (hasOldSilentPlayer << 2) | (hasOldWebPlayer << 1) | hasRichPlayer;
}

function showInfoModalWindow(url) {
    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();
                    });
                }
            });
            return i18n('loadingDialog');
        },
        fade: true, fadeDuration: 0.4, opacity: 0.8, width: 500,
        containerClassName: 'mfmodal'
    });
    modal.open();
}

function showErrorModalWindow(errorCode) {
    if ([4063, 4064, 4108, 'UD10', 'UD19', 'UD20', 'UD21', 'UD23'].indexOf(errorCode) !== -1) return ;
    if (errorCode > 5000) return ;
    var err = new ModalErrorWindow(errorCode);
    err.open();
}

WebPlayerButton = Class.create({
    initialize: function(classArr, label) {
        this.classArr = classArr;
        this.classArr.push('btn');
        this.el = new Element('div', {'class': this.classArr.join(' ')}).update(new Element('span').update(label));
        this.initEvents();
    },
    initEvents: function() {
        this.el.observe('mouseover', function() {
            if (this.el.hasClassName('btnNormal')) {
                this.el.observe('mouseout', function() {
                    if (this.el.hasClassName('btnHover')) {
                        this.el.removeClassName('btnHover');
                        this.el.addClassName('btnNormal');
                    }
                }.bind(this));        
                this.el.removeClassName('btnNormal');
                this.el.removeClassName('btnInactive');
                this.el.addClassName('btnHover');
            }
        }.bind(this));        
    },
    toNormal: function() {
        this.el.removeClassName('btnHover');
        this.el.removeClassName('btnInactive');
        this.el.addClassName('btnNormal');
        this.activateClick();
    },
    toInactive: function() {
        this.el.removeClassName('btnHover');
        this.el.removeClassName('btnNormal');
        this.el.addClassName('btnInactive');
        this.deactivateClick();
    },
    getButton: function() {
        return this.el;
    },
    setClickObserve: function(fn) {
        this.click = fn;
    },
    activateClick: function() {
        this.el.observe('click', this.click);
    },
    deactivateClick: function() {
        this.el.stopObserving('click', this.click);
    },
    observe: function(ev, fn) {
        this.el.observe(ev, fn);
    }  
});

WebPlayerSaveSlot = Class.create({
    initialize: function(slotId) {
        this.saved = false;
        this.slot = slotId;   
        this.desc = 'Slot ' + this.slot + ' - enter name';
    },
    setSaved: function(tstamp, desc, screen, aspect) {
        this.saved = true;
        this.tstamp = tstamp;
        this.desc = desc;
        this.screen = screen;
        this.aspect = aspect;
        this.setDateTime();
    },
    setDateTime: function() {
        var dateSaved = new Date();
        dateSaved.setTime(this.tstamp + (dateSaved.getTimezoneOffset() * 60000));
        var theHour = dateSaved.getHours();
        this.date = (dateSaved.getMonth() + 1) + "/" + dateSaved.getDate() + "/" + dateSaved.getFullYear();
        this.time = ((theHour <= 12) ? ((theHour == 0) ? 12 : theHour) : theHour - 12) + ":" + dateSaved.getMinutes() + ((theHour < 12) ? "am" : "pm");
    },
    getScreen: function(){
        var d = new Date();
        var src = this.screen + "?creationTime=" + ((new Date()).valueOf().toString());
        log.debug('slot: ' + this.slot + ' src: ' + src + ' aspect: ' + this.aspect);
        var img = new Element('img', {'src': src});
        img.hide();
        img.observe('load', function() {
            if (this.aspect > 1) {
                img.setStyle({
                    'width': '172px',
                    'height': parseInt(172/this.aspect) + 'px'
                });
                img.setStyle({
                    'marginTop': parseInt((137 - parseInt(img.getHeight())) / 2) + 'px'
                });
            }
            else {
                img.setStyle({
                    'height': '137px',
                    'width': parseInt(137 * this.aspect) + 'px'
                });
            }
            img.show();
        }.bind(this));
        return img;
    }
});

WebPlayer = Class.create({
    initialize: function(login, password, technoId, containerId) {
        this.player = null;
        this.define = {
            playerId:       'player',
            playerContainer:'browserPlayer',
            playerWidth:    666,
            playerHeight:   500
        };
        
        this.login = login;
        this.password = password;
        this.technoId = technoId;
        this.container = $(containerId);
        
        navigator.plugins.refresh(false);

        this.player  = new Element('object', {
            'id':       this.define.playerId,
            'width':    this.define.playerWidth + 'px', 
            'height':   this.define.playerHeight + 'px'
        });
        if (Prototype.Browser.IE) {
            // ActiveX Plugin.
            this.player.setAttribute("classid", "CLSID:4f29de54-5eb7-4d76-b610-a86b5cd2a234");
        } else {
            // NPAPI Plugin.
            this.player.setAttribute("type", "application/x-vnd-gametap-player");
        }
        this.container.insert(this.player);
        this.player.SetUpdateUrls(DEFINE.get('PLAYER_BOOTSTRAP'), DEFINE.get('PLAYER_INSTALL'));
        this.player.InitializePlugin(true, '');
        log.debug('insert webPlayer component done');
    },
    loginUser: function() {
        var loginString = "gametap://user=" + this.login + "," + this.password + ":999999999@player";
        this.player.LoginUser(loginString);
    },
    loadGame: function() {
        if ($('noticeAreaContent')) {
            log.debug('move HTML content and show launch process');
            this.player.insert({
                before: $('noticeAreaContent').innerHTML
            });
            $('noticeAreaContent').remove();
            $('browserGameLaunch').removeClassName('displayNone');
        }
        this.player.HidePlayer();
        log.debug('try get current game before load: ' + this.player.GetCurrentGame());
        urlServlet = new UrlSeoConstructor('ADD_TO_DOWNLOAD_LIST');
        StartDownloadGameTap(urlServlet.construct(), this.technoId, 1);
    },
    playGame: function() {
        log.debug('remove notice area and show player');
        $('noticeArea').remove();
        this.player.ShowPlayer();
        this.player.focus();
        player_play();
        log.debug('init fullscreen and reset buttons');
        this.initFullscreen();
        this.initReset();
    },
    setProgress: function(technoId, progress) {
        if (technoId = this.technoId && progress >= 0 && progress <=100) {
            $('browserCurrentProgress').setStyle({'width': progress + '%'});
            $('textValueProgress').update(progress + '%');
        }
    },
    setInDownloadState: function() {
        log.debug('show download progress bar');
        $('browserGameLaunch').addClassName('displayNone');
        $('gameDownloading').removeClassName('displayNone');
    },
    initFullscreen: function() {
        Event.observe('buttonFullscreen', 'click', function() {
            log.debug('fullscreen mode');
            this.player.Fullscreen();
        }.bind(this));  
    },
    initReset: function() {
        Event.observe('buttonResetGame', 'click', function() {
            log.debug('reset game');
            this.player.ResetGame();
        }.bind(this));  
    },
    shutdownPlayer: function() {
        this.player.ShutdownPlayer();
    },
    getSaveState: function() {
        try {
            var saveState = this.player.GetSaveStateInfo().evalJSON(); 
        } catch(e) {
            log.err(e);
        }
        var slots = new Hash();
        $R(1, 12).each(function(slotId) {
            var state = saveState.find(function(s) { 
                return s.slotNumber == slotId;
            }); 
            var slot = new WebPlayerSaveSlot(slotId);
            if (typeof(state) != 'undefined') {
                slot.setSaved(state.timeStamp, state.description, state.screenShotPath, state.aspectRatio); 
            }
            slots.set(slotId, slot); 
        });
        return slots;
    },
    getCurrentScreen: function(screen) {
        var src = this.player.GetCurrentGameScreenImageSource() + "?creationTime=" + ((new Date()).valueOf().toString()) + "&intensity=1&alpha=1";
        var img = new Element('img', {'src': src});
        img.hide();
        img.observe('load', function() {
            if (img.width / img.height > 1) {
                img.setStyle({
                    'width': '150px'
                });
            } else {
                img.setStyle({
                    'height': '110px'
                });
            }
            img.show();
        });
        return img;
    },
    addNumList: function(arr) {
        var ol = new Element('ol', {'class': 'numList'});
        arr.each(function(title) {
            ol.insert(new Element('li').update(title));
        });
        return ol;
    },
    addTopContainer: function(cntr, saveable) {
        var topClass = ['topContainer'];
        if (saveable) topClass.push('topContainerLine');
        var topContainer = new Element('div', {'class': topClass.join(' ')});
        topContainer.insert(new Element('div', {'class': 'currentScreen'}).update(this.getCurrentScreen()));
        this.btnResume = new WebPlayerButton(['btnResume'], 'Resume Game');
        this.btnResume.observe('click', this.onCancel.bind(this));
        topContainer.insert(this.btnResume.getButton());
        topContainer.insert(new Element('div', {'class': 'gamePaused'}).update('Game Paused'));
        if (saveable) {
            var ul = new Element('ul', {'class': 'gamePaused'});
            ul.insert(new Element('li', {'class': 'first'}).update('Saving or Loading a game'));
            ul.insert(new Element('li', {'class': 'second'}).update(
                new Element('div').update('Save Game')).insert(
                    this.addNumList(['Select a game slot.', 'Enter a name for the save.', 'Click the Save Game button.'])
                ).insert(
                    new Element('span', {'class': 'note'}).update('(Note: Select an occupied save slot to overwritean existing save.)'
                )
            ));
            ul.insert(new Element('li', {'class': 'third'}).update(new Element('div').update('Load Game')).insert(
                this.addNumList(['Select a game slot.', 'Click the Load Game button.'])
            ));
            topContainer.insert(ul);
        }
        cntr.insert(topContainer);
        return cntr;
    },
    addBottomContainer: function(cntr) {
        var bottomContainer = new Element('div', {'class': 'bottomContainer'});
        this.left = new Element('div', {'class': 'leftContainer'});
        this.getSaveState().each(function(pair) {
            var slot = pair.value;
            var cellClassArr = ['cellContainer'];
            var top = new Element('div', {'class': 'top'});
            var bottom = new Element('div', {'class': 'bottom'});
            
            if (slot.saved) {
                cellClassArr.push('saved');
                top.insert(slot.getScreen());
                bottom.insert(new Element('div').update(slot.desc));
                bottom.insert(new Element('div', {'class': 'date'}).update(slot.date));
                bottom.insert(new Element('div', {'class': 'time'}).update(slot.time));
            } else {
                bottom.update(slot.desc);
            }
             
            var slotSquere = new Element('div', {'class': cellClassArr.join(' '), 'id': 'cell-' + slot.slot});
            slotSquere.observe('click', this.cellClick.bind(this));
            slotSquere.insert(top);
            slotSquere.insert(bottom);
            
            this.left.insert(slotSquere);
        }.bind(this));
        this.right = new Element('div', {'class': 'rightContainer'});
        this.btnSaveGame = new WebPlayerButton(['btnCommon', 'btnInactive'], 'Save Game'); 
        this.btnSaveGame.setClickObserve(this.onSaveState.bind(this)); 
        this.btnLoadGame = new WebPlayerButton(['btnCommon', 'btnInactive'], 'Load Game'); 
        this.btnLoadGame.setClickObserve(this.onLoadState.bind(this)); 
        this.btnDeleteGame = new WebPlayerButton(['btnCommon', 'btnInactive'], 'Delete Game');
        this.btnDeleteGame.setClickObserve(this.onDeleteState.bind(this)); 
        this.btnCancelGame = new WebPlayerButton(['btnCommon', 'btnNormal'], 'Cancel');
        this.btnCancelGame.observe('click', this.onCancel.bind(this));
        [this.btnSaveGame, this.btnLoadGame, this.btnDeleteGame, this.btnCancelGame].each(function(btn) {
            this.right.insert(btn.getButton());
        }.bind(this));
        this.setButtonsPosition();
        bottomContainer.insert(this.left);
        bottomContainer.insert(this.right);
        cntr.insert(bottomContainer);
        return cntr;       
    },
    setButtonsPosition: function() {
        var s = this.right.childElements().size();
        this.right.setStyle({paddingTop: parseInt((350 - 27 * s)/2) + 'px'});
    },
    clearCells: function() {
        $$('.cellContainer').each(function(clearCell) {
            if (clearCell.hasClassName('selected')) {
                clearCell.removeClassName('selected');
                if (!clearCell.hasClassName('saved')) {
                    var bottom = clearCell.down('.bottom');
                    var prev = bottom.down('input.prev');
                    if (prev) bottom.update(prev.value);
                }
            }
        });
    },
    cellClick: function(event) {
        var cell = Event.element(event).up('.cellContainer');
        if (cell.hasClassName('selected')) return ;
        this.clearCells();
        cell.addClassName('selected');
        var bottom = cell.down('.bottom');
        if (cell.hasClassName('saved')) {
            this.btnSaveGame.toNormal();
            this.btnLoadGame.toNormal();
            this.btnDeleteGame.toNormal();
        } else {
            var input = new Element('input', {'type': 'text'});
            var inputPrev = new Element('input', {'class': 'prev', 'type': 'hidden', 'value': bottom.innerHTML});
            bottom.update(input);
            bottom.insert(inputPrev);
            input.focus();
            this.btnSaveGame.toNormal();
            this.btnLoadGame.toInactive();
            this.btnDeleteGame.toInactive();
        }
        this.cell = {
            cell: cell,
            saved: cell.hasClassName('saved') ? true : false,
            slot: cell.id.match(/cell-(\d+)/)[1],
            bottom: bottom,
            input: input,
            prev: inputPrev
        };
    },
    onSaveState: function() {
        if (this.cell.saved && !confirm('Replace save?')) {
            this.clearCells();
        } else {
            try {
                var save;
                if (this.cell.saved) {
                    save = this.getSaveState().get(this.cell.slot).desc;
                } else {
                    save = this.cell.input.value.blank() ? this.cell.prev.value : this.cell.input.value;    
                }
                this.player.SaveState(this.cell.slot, save);
                var slot = this.getSaveState().get(this.cell.slot);
                this.cell.bottom.update();
                this.cell.cell.addClassName('saved');
                this.cell.cell.down('.top').update('').insert(slot.getScreen());
                this.cell.bottom.insert(new Element('div').update(slot.desc));
                this.cell.bottom.insert(new Element('div', {'class': 'date'}).update(slot.date));
                this.cell.bottom.insert(new Element('div', {'class': 'time'}).update(slot.time));
                this.btnLoadGame.toNormal();
                this.btnDeleteGame.toNormal();
            } catch(e) {
                log.err(e);
            }
        }
    },
    onLoadState: function() {
        try {
            this.player.LoadState(this.cell.slot);
            this.onCancel();
        } catch(e) {
            log.err(e);
        }
    },
    onDeleteState: function() {
        if (confirm('Delete save?')) {
            try {
                this.player.DeleteSaveState(this.cell.slot);
                var slot = this.getSaveState().get(this.cell.slot);
                this.cell.bottom.update(slot.desc);
                this.cell.cell.removeClassName('saved');
                this.cell.cell.down('.top').update();
                this.btnLoadGame.toInactive();
                this.btnDeleteGame.toInactive();
            } catch(e) {
                log.err(e);
            }
        } else {
            this.clearCells();
        }
    },
    onCancel: function() {
        if (this.slContainer) {
            new Effect.Opacity(this.slContainer, {
                from: 1,
                to: 0,
                duration: 0.5,
                afterFinish: function(){
                    this.slContainer.remove();
                    this.slContainer = null;
                    this.player.ShowPlayer();
                }.bind(this)
            });
        }
    },
    onGamePause: function() {
        try {
            var currentGame = this.player.GetCurrentGame();
            var saveable = this.player.GetGameInfo(currentGame).evalJSON().strGameSaveable;
        } catch(e) {
            log.err(e);
        }
        this.player.HidePlayer();
        this.currentCell = false;
        this.slContainer = new Element('div', {'class': 'slContainer'});
        this.player.insert({
                before: this.addTopContainer(this.slContainer, saveable)
            });
        this.container.insert();
        if (saveable) 
            this.player.insert({
                before: this.addBottomContainer(this.slContainer)
            });
        this.slContainer.setOpacity(0);
        new Effect.Opacity(this.slContainer, { from: 0, to: 1, duration: 0.5 });
    },
    onGameResume: function() {
        this.onCancel();
    }
});

function ProgressHandler(technoId, progress) {
    log.debug('ProgressHandler. technoId: ' + technoId + ' progress: ' + progress);
    var progress = parseInt(progress);

    if (typeof(GameTapInstaller) == 'object') GameTapInstaller.setProgress(progress);
    else if (typeof(gameManager) == 'object') {
        if (autoLaunch && !gameManager.inprocess.browser && gameManager.inprocess.technoId == technoId) {
            log.debug('launch precached game');
            try {
                if (myGames.inDownload.keys().first() != technoId) gameManager.onGameAddToListCB(technoId);
                autoLaunch = false;
                player_play();
            } catch (e) {
                log.err(e);
            }
        }
        if (gameManager.downloadClick && gameManager.downloadClick == technoId && !gameManager.redirectionInProcess) {
            ww.hide();
        }
    }
    if (webPlayer) webPlayer.setProgress(technoId, progress);
}

function StatusHandler(step, status){
    log.debug("StatusHandler Step: " + step + " Status: " + status);
    var cntx = $('context').getValue();
    var stepCodes = new Object();
        stepCodes.UNLOAD_GAME_COMPLETE                      = 0;     // unload game complete  
        stepCodes.USER_LOGIN_COMPLETE                       = 1;     // user login complete
        stepCodes.LOAD_GAME_COMPLETE                        = 2;     // load game complete
        stepCodes.PLAY_GAME_COMPLETE                        = 3;     // play game complete
        stepCodes.INIT_COMPLETE                             = 4;     // initialization complete (optional migration happens here)
        stepCodes.INITIAL_PRECACHE_DOWNLOAD_COMPLETE        = 10000; // game has reached precache minimum
        stepCodes.DOWNLOAD_STARTS                           = 10001; // download queue started
        stepCodes.DOWNLOAD_STOPS                            = 10002; // download queue stopped
        stepCodes.FULLY_DOWNLOADED                          = 10003; // game is fully downloaded
        stepCodes.PRIORITY_CHANGED                          = 10004; // game has changed priority 
        stepCodes.GAME_ENQUEUED                             = 10005; // game is added to the queue 
        stepCodes.GAME_DEQUEUED                             = 10006; // game is removed from the queue
        stepCodes.GAME_REMOVED                              = 10007; // game is removed from hard drive
        try{
            switch (step){
                case stepCodes.UNLOAD_GAME_COMPLETE:
                    log.debug("unload game completed successfully! "+status);
                    // not sure why this is logged out on unload complete
                    break;
                 case stepCodes.USER_LOGIN_COMPLETE:
                    if (isLoginPlayerDone) return ;
		    		log.debug("login completed successfully!");
                    isLoginPlayerDone = true;
                    if (webPlayer) {
                        webPlayer.loadGame();
                    }
                    if (typeof(gameManager) != 'undefined' && gameManager) {
                        gameManager.initGamePageButtonsV2();
                    }
					if (/profile_games/.test(cntx)) {
						log.debug('show my games list');
					    myGames = new MyGames();
						gameManager.initAutorun();
					}
					if (/profile_.*/.test(cntx)) {
						gameManager.initFavorites();
					}
                    break;
                case stepCodes.INIT_COMPLETE:
                    log.debug("init completed successfully!");
                    if (/installplayer_install/.test(cntx)) {
                        if (typeof(GameTapInstaller) == 'object') GameTapInstaller.initComplete();
                    } else {
                        log.debug('handle initialization event');
                        isInitPlayerDone = true;
                        if (webPlayer) {
                            webPlayer.loginUser();
                        } else {
                            player_login(p_login_gametap, p_sso_token_gametap);
                        } 
					}
                    break;
                case stepCodes.LOAD_GAME_COMPLETE:
                    log.debug("load game completed successfully! "+status);
                    
                    if (webPlayer) {
                        webPlayer.playGame();
                    } else {
                        if (autoLaunch == true) {
                            player_play();
                        }
                    }
                    break;
                case stepCodes.PLAY_GAME_COMPLETE:
                    log.debug("play game completed successfully! "+status);
                    if (typeof(gameManager) == 'object') {
						if (gameManager.inprocess.browser) {
							log.debug('try get controllers for browser game');
                            gameManager.updateBrowserGameController();
						}
                    }
                    ww.hide();
                    var rpUrl = new UrlConstructor('profile/recently_played');
                    rpUrl.addVar('technoId', status);
                    new Ajax.Request(rpUrl.construct(), {
                        onComplete: function(request){
                            
                        }
                    });
                    break;
                case stepCodes.INITIAL_PRECACHE_DOWNLOAD_COMPLETE:
                    log.debug("game is precached. techno id: "+status);
					if (typeof(myGames) == 'object') myGames.updateReadyToPlayCB(status);
                    break;
                case stepCodes.DOWNLOAD_STARTS:
				    log.debug('download starts');
				    if (typeof(myGames) == 'object') {
						myGames.gameDownloadingStartCB(myGames.inDownload.keys().first());
					} 
                    break;
                case stepCodes.DOWNLOAD_STOPS:
				    log.debug('download stops');
				    if (typeof(myGames) == 'object') {
						myGames.gameDownloadingStopCB(myGames.inDownload.keys().first());
					}
                    break;
                case stepCodes.FULLY_DOWNLOADED:
                    log.debug("fully downloaded game. techno id: " + status);
                    if (/profile_games/.test(cntx) && typeof(myGames) == 'object') {
                        myGames.moveGameToCompletedCB(status);
                    }  
                    try {
                        var seedLaunch = new UrlSeoConstructor('SPEED_LAUNCH');
                        createShortCutGameTap(status, seedLaunch.construct());
						log.err('speed launch created. Techno id: ' + status);
                    } catch (e) {
                        log.err('speed launch create failed. msg: ' + e.message);
                    }
                    break;
                case stepCodes.PRIORITY_CHANGED:
                    break;
                case stepCodes.GAME_ENQUEUED:
                    log.debug("add game to the queue. techno id: "+status);
                    if (webPlayer) {
                        webPlayer.setInDownloadState();
                    } else {
                        if (typeof(gameManager) == 'object') {
                            gameManager.onGameAddToListCB(status);
                            gameManager.downloadClick = status; 
                        }     
                    }
                    break;
                case stepCodes.GAME_DEQUEUED:
                        log.debug("removed game from the queue. techno id: "+status);
						if (typeof(myGames) == 'object') myGames.removeFromListCB(status);
                    break;
                case stepCodes.GAME_REMOVED:
                        log.debug("game removed. techno id: "+status);
						if (typeof(myGames) == 'object') myGames.removeGameCB(status, false);
                    break;
				default:
				    log.debug('unknown step. code: ' + step + ' status: ' + status);
            }
        }catch(e){
            log.err(e);
        }
}

/*
 * StatusHandler Step: 10006 Status: 144981960
 */

function ErrorCodeHandler(errorCode){
    log.err('errorCodeHandler error code: ' + errorCode);

    if (typeof(gameManager) == 'object' && (4100 <= errorCode) && (errorCode <= 4199)) {
        gameManager.inprocess.technoId = 0;
    }

    switch(errorCode) {
        case 5010:
            if (webPlayer) webPlayer.onGamePause();
            break;
        case 5011:
            if (webPlayer) webPlayer.onGameResume();
            break;
        case 5008:  
            log.debug('HL_EVENT_MIGRATION_START');
            break;
        case 5009:  
            log.debug('HL_EVENT_MIGRATION_END');
			ProgressHandler(100);
            navigator.plugins.refresh(false);
			
	        Cookie.set('migration', 1, {
	            expires: (1).year(),
	            path: '/'
	        });
			
	        var sendEmailUrl = new UrlConstructor('install_player/send_email');
	        new Ajax.Request(sendEmailUrl.construct(), {
	            method: 'get',
	            onSuccess: function(transport) {
	                var obj = transport.responseText.evalJSON();
	                var er = new ErrorManager(obj);
					er.getErrors();
				    $('btnContinueUnactive').addClassName('displayNone');
                    var next = $('btnContinueActive').removeClassName('displayNone').down('a');
                    var s = new UrlSeoConstructor('PROFILE_DASHBOARD');
                    next.href = s.construct();
	            }.bind(this)
	        });
            break;
		case 5001:
		    log.debug('HL_EVENT_CONTROLLER_PLUGIN');
            if (typeof(gameManager) == 'object') {
                log.debug('try get controllers for browser game');
                gameManager.updateBrowserGameController();
            }
		case 5002:
		      log.debug('HL_EVENT_CONTROLLER_REMOVE');
            if (typeof(gameControls) == 'object') {
                log.debug('switch to keyboard controller tab');
                gameControls.keyboardActive();
            }
        default:    
            log.debug('Unknown error. Code: ' + errorCode);
			showErrorModalWindow(errorCode);
    } 
}

function UpdaterProgressHandler(progress, action, target){
	log.debug('UpdaterProgressHandler. progress: ' + progress);
	var progress = parseInt(progress);
	if (progress == 0) return null;
	$('progressElement').down('.currentProgress').setStyle({width: ((progress == 100) ? 101 : progress) + '%'});
	$('progressElement').down('.textValueProgress').update(progress + '%');
}

function UpdaterErrorCodeHandler(errorCode) {
	log.err('UpdaterErrorCodeHandler: ' + errorCode);
	showErrorModalWindow(errorCode);
}

function UpdaterStatusHandler(step, status){
    var stepCodes = new Object();
    stepCodes.INSTALL_NEW_PLAYER                = 1;     // the install is currenly in progress
    stepCodes.UPDATE_END                        = 2;     // update done
    log.debug('UpdaterStatusHandler: ' + step);
    switch(step) {
        case 1: 
        	log.debug('New player installing ...');
            break;
        case 2: 
            $('btnContinueUnactive').addClassName('displayNone');
            var next = $('btnContinueActive').removeClassName('displayNone').down('a');
			if (Prototype.Browser.Gecko) {
				log.debug('apply navigator.plugins.refresh(false)');
				navigator.plugins.refresh(false);
			}
            var step = gameTapPlayerType();
			log.debug('Update player done. Next step: ' + step);
            switch(step) {
                case 1:
                case 2:
                case 3:
                case 5:
                	var s = new UrlSeoConstructor('INSTALLPLAYER_MIGRATION');
					s.addVar('browser', (Prototype.Browser.IE) ? 'IE' : 'FF');
                	next.href = s.construct();
                    break;
                case 0:
                case 4:
					var s = new UrlSeoConstructor('PROFILE_DASHBOARD');
					next.href = s.construct();
                    break;
            }
            break;
    }
}

function parseUri(str) {
	var o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

function getElementsByName_iefix(tag, name) {
    var elem = document.getElementsByTagName(tag);
    var arr = new Array();
    for(i = 0, iarr = 0; i < elem.length; i++) {
         att = elem[i].getAttribute("name");
         if(att == name) {
              arr[iarr] = elem[i];
              iarr++;
         }
    }
    return arr;
}

function transparentbg(tbg_id) {
    var bak = getElementsByName_iefix("div", tbg_id);
    for(i = 0; i < bak.length; i++) {
         bak[i].style.height = bak[i].parentNode.clientHeight + "px";
    }
}
