if (!window.MvcSkel) { var MvcSkel = new Object(); }
Object.extend(MvcSkel, {
    getVar: function(name) {
        return ( $(name)) ?  $(name).value : false;
    }
});
ErrorManager = Class.create({
    initialize: function(obj) {
        if (!window.__errors) { __errors = new Object(); };
        if (!window.__errors_count) { __errors_count = 0 };
        this.errWin = null;
        if (typeof(obj) != 'undefined') {
            obj.errors.each(function(el) {
                el.msg.each(function(msg) {
                    this.raise(el.label, msg);
                }.bind(this));
            }.bind(this));
        }
    },
    raise: function(label, description) {
        if (typeof __errors[label] != 'object') {
            __errors[label] = new Array();
        }
        __errors[label].push(description);
        __errors_count++;
    },
    clear: function() {
        __errors = new Object();
        __errors_count = 0;
    },
    haveErrors: function() {
        return __errors_count ? true : false;  
    },
    getErrorsAlert: function() {
        if (!__errors_count) { return false; };
        var content = i18n('errorsTitle') + ':' + "\n";
        for(err in __errors) {
            f = true;
            __errors[err].each(function(e) {
                if (f) {
                    content += "\n" + err + ':' + "\n";
                    f = false;
                }
                content += "\t" + '- ' + e + "\n";
            });
        }
        alert(content);
        this.clear();
        return true;
    },
    getHtmlContent: function() {
        var content = '<div class="header">'
        content += '<h2>' + i18n('errorsTitle') + '</h2>';
        content += '<div class="close"><a id="errorsClose" href="javascript:void(0);">' + i18n('errorsClose') + '</a></div>'
        content += '</div>';
        content += '<table class="errors" cellpadding="0" cellspacing="0" border="0">';
        content += '<tbody>';
        for(err in __errors) {
            f = true;
            __errors[err].each(function(e) {
                content += '<tr>';
                if (f) {
                    content += '<td class="label" rowspan="' + __errors[err].size() + '">' + err + ':</td>';
                    f = false;
                }
                content += '<td class="description">- ' + e + '</td>';
                content += '</tr>';
            });
            content += '<tr><td class="space" colspan="2"></td></tr>';
        }
        content += '</tbody>';
        content += '</table>';
        return content;
    },
    getErrors: function() {
        if (!__errors_count) { return false; };
        this.errWin = new Control.Modal(false, {
            contents: this.getHtmlContent(),
            fade: true, fadeDuration: 0.5, opacity: 0.8,
            width: 450,
            containerClassName: 'mfmodal',
            afterOpen: function() {
                Event.observe('errorsClose', 'click', function() {
                    this.errWin.close();
                }.bind(this));
            }.bind(this)
        });
        this.errWin.open();
        this.clear();
        return true;
    },
    checkEmail: function(email) {
        var regexp = new RegExp('^[\\w\\-\\.]+@[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z0-9\\-]+$');
        if (!regexp.test(email)) {
            this.raise(i18n('errorEmail'), i18n('errorWrongEmail'));
        }
    }
});

GameAutocomplete = Class.create({
    initialize: function() {
        if (!$('autocompleteGames')) return false;
        this.limit = 15;
        var url = new UrlConstructor('search/autocomplete');
        url.addVar('limit', this.limit);
        var options = {
            script:url.construct() + '?',
            varname:'input',
            json:true, noresults: i18n('autocompleteNoResults'),
            shownoresults:false, maxresults:this.limit, minchars: 3,
            setWidth:true, minWidth:270, maxWidth:350,
            afterShow: this.pngFix.bind(this),
            callback: this.redirect.bind(this)
        };
        var json = new AutoComplete('autocompleteGames', options);
        this.defaultText();
    },
    pngFix: function(div) {
        if (typeof(DD_belatedPNG) != 'object') return;
        ['.ac_corner', '.ac_bar', '.ac_footer', '.ac_header'].each(function(val) { DD_belatedPNG.fix(val); });
    },
    redirect: function(obj) {
        var s = new UrlSeoConstructor('GAME_PRESENTATION');
        s.addSeoVar('game_name', obj.value.replace(/\s+|[^\w]+/ig, '-'));
        s.addSeoVar('game_id', obj.id);
        s.addSeoVar('game_category_id', 0);
        window.location = s.construct();
    },
    defaultText: function() {
        var form = $('searchGamesForm');
        if (!form) return;
        var autoInput = form.down('input');
        autoInput.observe('click', function() {
            if (!autoInput.hasClassName('firstEnterText')) return;
            autoInput.removeClassName('firstEnterText');
            if (autoInput.next()) { autoInput.next().addClassName('cancelSearch'); }
            autoInput.value = '';
        }.bind(this));
        autoInput.observe('blur', function() {
            if (autoInput.value == '') {
                autoInput.addClassName('firstEnterText');
                if (autoInput.next()) { autoInput.next().removeClassName('cancelSearch'); }
                autoInput.value = i18n('search_box_default_text');
            }
        }.bind(this));
    }
});

UrlConstructor = Class.create();
UrlConstructor.prototype = {
    initialize: function(url) {
        this.action = false;
        this.vars = new Hash();
        this.url = url;
    },
    setAction: function(isAction) {
        this.action = isAction;
    },
    addVar: function(name, value) {
        this.vars.set(name, encodeURIComponent(value));
    },
    construct: function() {
        var url = MvcSkel.getVar('rootUrl');
        if (this.action) {
            url += "actionController/";
        }
        url += (this.url) ? this.url : '';
        this.vars.each(function(pair) {
            url += '/' + pair.key + '/' + pair.value;
        });
        return url;
    }
}

UrlSeoConstructor = Class.create({
    initialize: function(view) {
        this.vars = new Hash();
        this.seo = new Hash();
        this.view = view;
    },
    addVar: function(name, value) {
        this.vars.set(name, value);
    },
    addSeoVar: function(name, value) {
        this.seo.set(name, value);
    },
    construct: function() {
        var url = seourl.get(this.view);
        this.seo.each(function(pair) {
            var re = new RegExp("%" + pair.key + "%", "ig");
            url = url.replace(re, pair.value);
        });
        if (query = this.vars.toQueryString()) { url += '?' + query; }
        return url;
    }
});

ImageUploader = Class.create();
ImageUploader.prototype = {
    initialize: function() {
        this.options = {
            baseClass: 'uploader',
            baseProgress: 'progress',
            action: 'change'
        };
        this.form = null;
        this.timer = null;
        this.initAction();
    },
    initAction: function() {
        $$('input.' + this.options.baseClass).each(function(uploaderInput) {
            Event.observe(uploaderInput, this.options.action, function(event) {
                clearTimeout(this.timer);
                this.timer = this.activateUpload.bind(this).delay(5, Event.element(event));
            }.bind(this));
        }.bind(this));
    },
    activateUpload: function(activeInput) {
        var suffix = activeInput.up('form').id.match(/-(.*)$/)[1];
        this.form = $(this.options.baseClass + '-' + suffix);
        this.hideForm(suffix);
        this.form.submit();
    },
    hideForm: function(suffix) {
        this.form.hide();
        var prg = $(this.options.baseProgress + '-' + suffix);
        if (!prg) {
            this.form.up().appendChild(new Element('span', {
                'class': 'progressBar',
                id: this.options.baseProgress + '-' + suffix
            }).update('progress'));
        } else {
            prg.show();
        }
    },
    showForm: function(suffix) {
        $(this.options.baseProgress + '-' + suffix).hide();
        this.form.show();
        this.form.down('.uploader').value = '';
    },
    uploadComplete: function(suffix, file, url) {
//        alert(suffix + '-' + file + '-' + url);
        $(suffix + '-uploadedimg').src = url;
        this.showForm(suffix);
        this.form.down('.save').writeAttribute('value', file);
    },

    uploadError: function() {
        alert("Error");
    }
}

WaitWindow = Class.create({
    initialize: function() {
        if (typeof(ww) != 'undefined' && ww) return ;
        this.def = {
            overlayCloseOnClick: false,
            fade: true,
            fadeDuration: 0.4,
            opacity: 0.8,
            containerClassName: 'ajaxLoader'
        }
        this.modal = null;
        this.opened = false;
    },
    show: function(afterOpen) {
        var waitContent = new Element('div', {id: 'boxProcess'});
        var opt = { 
        		contents: [waitContent],
        		afterEffect: function() { if (Object.isFunction(afterOpen)) afterOpen(); },
                afterOpen: function() { this.opened = true; }.bind(this)
        		};
        this.modal = new Control.Modal(false, Object.extend(this.def, opt));
        this.modal.open();
        
    },
    hide: function() {
        if (this.opened) this.modal.close();
    }
});

InitSWFobjects = Class.create({
    initialize: function() {
        this.swf = new Array();
        this.swfobjects = new Array();
        $$('input.swf').each(function(swfInput, idx) {
            this.initObject(idx, swfInput.name, swfInput.value);
        }.bind(this));
        this.createObjects();
    },
    initObject: function(idx, prefix, target) {

        this.swf[idx] = {
            target: target,
            object: null,
            id: null,
            x: 0,
            y: 0,
            version: 0,
            variables: {},
            param: {}
        };
        $$('input.' + prefix).each(function(el) {
            if (/param/.test(el.className)) {
                eval('var obj = {' + el.name + ' : \'' + el.value + '\'}');
                Object.extend(this.swf[idx].param, obj);
            } else if (/variable/.test(el.className)) {
                eval('var obj = {' + el.name + ' : \'' + el.value + '\'}');
                Object.extend(this.swf[idx].variables, obj);
            } else {
                switch (el.name) {
                    case 'swfobject': this.swf[idx].object = el.value; break;
                    case 'swfid': this.swf[idx].id = el.value; break;
                    case 'swfx': this.swf[idx].x = el.value; break;
                    case 'swfy': this.swf[idx].y = el.value; break;
                    case 'swfversion': this.swf[idx].version = el.value; break;
                }
            }
        }.bind(this));
    },
    createObjects: function() {
        this.swf.each(function(swfobj, idx) {
            var params = {};
            for (i in swfobj.param) {
                eval('var tmp = {' + i + ': \'' + swfobj.param[i] + '\'};');
                Object.extend(params, tmp);
            }
            var flashvars = {};
            for (k in swfobj.variables) {
                eval('var tmp = {' + k + ': \'' + swfobj.variables[k] + '\'};');
                Object.extend(flashvars, tmp);
            }
            var attributes = {
                id: swfobj.id
            };
            swfobject.embedSWF(
                swfobj.object,
                swfobj.target,
                swfobj.x,
                swfobj.y,
                swfobj.version,
                "expressInstall.swf",
                flashvars,
                params,
                attributes
            );
        }.bind(this));
    }
});

CategoryDropDownList = Class.create({
    initialize: function(id) {
        this.button = $(id);
        if (!this.button) return false;
        this.list = $(this.button.className.match(/list-(\w+)\s?/)[1]);
        if (!this.list) return false;
        this.myEffects = {
                updown: 0.4
        };
        this.delay = 2000;
        this.timer = null;
        this.open = false;
        this.initAction();
    },
    initAction: function() {
        this.button.observe('click', this.openList.bind(this));
        this.button.observe('mouseover', this.clearTimer.bind(this));
        this.button.observe('mouseout', this.setTimer.bind(this));
        this.list.observe('mouseover', this.clearTimer.bind(this));
        this.list.observe('mouseout', this.setTimer.bind(this));
    },
    openList: function() {
        if (this.open) {
            this.closeList();
        } else {
            this.open = true;
            new Effect.BlindDown(this.list, {duration: this.myEffects.updown, transition: Effect.Transitions.sinoidal});
        }
    },
    closeList: function() {
        new Effect.BlindUp(this.list, {duration: this.myEffects.updown, transition: Effect.Transitions.sinoidal});
        this.open = false;
    },
    clearTimer: function() {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
    },
    setTimer: function() {
        if (!this.timer && this.open) {
            this.timer = setTimeout(function() {
                this.closeList();
                this.timer = null;
            }.bind(this), this.delay);
        }
    }
});

MFTooltip = Class.create({
    initialize: function() {
        $$('.tooltip').each(this.initTip.bind(this));
    },
    getContent: function(content) {
        var el = new Element('div');
        var elSpan = new Element('span', {'class': 'tip'}).update(content);
        var elDiv = new Element('div', {'class': 'pointer'}).update('pointer');
        el.appendChild(elSpan);
        el.appendChild(elDiv);
        return el;
    },
    initTip: function(imgTip) {
        if (!imgTip.title.blank()) {
            var cName = 'righttip';
            var offsetX = 0;
            if (/lefttip/.test(imgTip.className)) {
                cName = 'lefttip';
                offsetX = -220;
            }
            var txt = imgTip.title.strip();
            imgTip.title = '';
            new Tip(
                imgTip,
                this.getContent(txt),
                {
                    className: cName,
                    effect: 'appear',
                    duration: 0.2,
                    delay: 0.2,
                    offset: {x: 14 + offsetX, y: -10},
                    onShow: function () {},
                    onHide: function () {}
                }
            );
        }
    }
});

SimpleDebug = Class.create({
	initialize: function() {
		this.level = 10;
		this.history = new Hash();
		this.saveInHistory = true;
	},
	onLoadInit: function(level) {
		this.saveInHistory = false;
        this.level = level ? level : 0;
        if (this.level == 0) {
        	_Debug = false;
        }
		this.win = this.create();
		if (this.level != 0) {
			this.history.each(function(pair){
				this.add(pair.value.m, pair.value.c);
			}.bind(this));
		}
		this.docScroll();
	},
	create: function() {
		var main = new Element('div', {id: 'debugWrapper'}).setStyle({
			position: 'absolute', bottom: '0', right: '0', height: '100px', width: '800px', 
			textAlign: 'left', backgroundColor: '#FFFFFF', zIndex: 1000
		}).hide();
		var content = new Element('div', {id: 'debugOut'}).setStyle({
			overflow: 'auto', height: '80px', marginTop: '5px'
		});
		var h = new Element('div').update('Debug window');
		var close = new Element('a').observe('click', this.closeDebug.bind(this)).update('[X]');
		close.setStyle({'float': 'right', cursor: 'pointer'});
        var clear = new Element('a').observe('click', this.clearDebug.bind(this)).update('[CLEAR]');
        clear.setStyle({'float': 'right', cursor: 'pointer'});
        var copy  = new Element('a').observe('click', this.copyDebug.bind(this)).update('[COPY (FF only)]');
        copy.setStyle({'float': 'right', cursor: 'pointer'});
        main.insert(close);
		main.insert(clear);
		main.insert(copy);
		main.insert(h);
		main.insert(content);
		$(document.body).insert(main);
		Event.observe(window, 'scroll', this.docScroll.bind(this), false);
		return main;
	},
	docScroll: function() {
		this.win.setStyle({bottom : -this.win.cumulativeScrollOffset().top + 'px'});
	},
	closeDebug: function() {
		this.win.hide();
	},
    clearDebug: function() {
        $('debugOut').update();
    },
    copyDebug: function() {
        var text = '';
        $('debugOut').select('div').each(function(logLine) {
             text += logLine.innerHTML + "\n";
        });
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"].getService();
        if (clipboard) clipboard = clipboard.QueryInterface(Components.interfaces.nsIClipboard);
        var transferable = Components.classes["@mozilla.org/widget/transferable;1"].createInstance();
        if (transferable) transferable = transferable.QueryInterface(Components.interfaces.nsITransferable);
        transferable.addDataFlavor("text/unicode");
        var textObj = new Object();
        var textObj = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        if (textObj) {
            textObj.data = text;
            transferable.setTransferData("text/unicode", textObj, text.length*2);
            var clipid=Components.interfaces.nsIClipboard;
            clipboard.setData(transferable,null,clipid.kGlobalClipboard);
        }       
    },
	decode: function(msg) {
		if (msg.inspect) {
			//msg = msg.inspect();
		} else if (msg.message && msg.name) {
			msg = msg.name.toString() + ': ' + msg.message.toString();
		} else if (msg.toString) {
			msg = msg.toString();
		}
		return msg.escapeHTML();
	},
	stop: function(msg) {
		if (this.level >= 4) {
			this.add(msg, 'green');
			alert('Log: ' + msg);
		} else if (this.level == -1) this.console(msg);
	},
	debug: function(msg) {
        if (this.level >= 3) this.add(msg, 'black');
        else if (this.level == -1) this.console(msg);
	},
    info: function(msg) {
        if (this.level >= 2) this.add(msg, 'gray');
        else if (this.level == -1) this.console(msg);
    },
	err: function(msg) {
		if (this.level >= 1) this.add(msg, 'red');
        else if (this.level == -1) this.console(msg);
	},
	add: function(msg, color) {
		if (this.saveInHistory) {
			this.history.set(this.history.size() + 1, {m: msg, c: color});
		} else {
			this.win.show();
			var cd = new Date();
			var line = new Element('div').setStyle({color: color});
			line.insert(new Element('b').update(
			 formatNumber(cd.getDate()) + '/' + formatNumber(cd.getMonth() + 1) + '/' + cd.getFullYear() + ' ' +
			 formatNumber(cd.getHours()) + ':' + formatNumber(cd.getMinutes()) + ':' + formatNumber(cd.getSeconds()) +
			 ':&nbsp;'));
			line.insert(this.decode(msg))
			this.win.down('div', 1).insert(line);
		}
	},
    console: function(msg) {
        try {
            if (typeof(console.log) == 'function') console.log(msg);
        } catch(e) { }
    }
});

ModalErrorWindow = Class.create({
    initialize: function(errorCode) {
        this.modal = new Control.Modal(false, {
            contents: function() {
                var showError = new UrlConstructor('error/by_code');
                showError.addVar('code', errorCode);
                new Ajax.Request(showError.construct(), {
                    onComplete: function(request) {
                        this.modal.update(request.responseText);
                        $('modalClose').observe('click', this.close.bind(this));
                    }.bind(this)
                });
                return i18n('loadingDialog');
            }.bind(this),
            afterClose: this.afterClose.bind(this),
            beforeOpen: this.beforeOpen.bind(this),
            fade: true, fadeDuration: 0.4, opacity: 0.8, width: 500, containerClassName: 'mfmodal'
        });
    },
    open: function() {
        this.modal.open();        
    },
    close: function() {
        this.modal.close();
    },
    afterClose: function() {
        if ($('browserPlayer')) $('browserPlayer').show();
    },
    beforeOpen: function() {
        if ($('browserPlayer')) $('browserPlayer').hide();
    }
});


SubmitFormByLink = Class.create({
    initialize: function() {
        this.defaultClass = 'submitFormByLink';
        $$('.submitFormByLink').each(function(el) {
            el.observe('click', function() {
                var form = el.up('form');
                if (!form.down('.search_text').hasClassName('firstEnterText')) form.submit();
                else {
                    var url = new UrlSeoConstructor('CATEGORY_INDEX_ALL');
                    window.location = url.construct();
                }  
            });    
        });
    }
});

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 i18n(key, hash) {
    var t = lang.get(key);
    if (!t && Object.isFunction(l)) l('i18n constant not defined. Const: ' + key);
    if (hash) {
        hash.each(function(r) {
            t = t.replace(new RegExp('(%' + r.key + '%)', 'i'), r.value);
        });
    }
    return t;
}

function getLocale() {
	var lang = null;
	try {
		if (Prototype.Browser.IE) {
			lang = $$('meta[httpEquiv="Content-Language"]').first().content.toLowerCase();
		} else {
			lang = $$('meta[http-equiv="Content-Language"]').first().content.toLowerCase();
		}
	} catch (e) {
		lang = 'fr';
	}
	var path = '';
	if (lang == 'en') {
		path = '/en';
	} else if (lang == 'de') {
		path = '/de';
	} else if (lang == 'it') {
        path = '/it';
    } else if (lang == 'sv') {
        path = '/sv';
    }
	return {lang: lang, path: path};
}

function getPortalId() {
	if (portal = $('portalId')) {
		return portal.getValue();
	}
	return false;
}

function formatNumber(num) {
    return (num < 10) ? '0' + num : num;
}

function l(log) {
    if (typeof(console) == 'object' && DEFINE.get('IS_DEV')) console.log(log);
}
