/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name.toLowerCase()] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}

//svsfunctions
function newline2break(text) {
	var newtext = escape(text);
	if(newtext.indexOf('%0D%0A') > -1) {
		re_nlchar = /%0D%0A/g ;
	}else if(newtext.indexOf('%0A') > -1) {
		re_nlchar = /%0A/g ;
	}else if(newtext.indexOf('%0D') > -1) {
		re_nlchar = /%0D/g ;
	}
	if (typeof(re_nlchar) == "undefined") { 
		return text; 
	} else { 
		text = unescape( newtext.replace(re_nlchar,'<br/>') );
		return text;
	}
}	
function OpenHelp(main, under){
	var height = 600;
	var width = 500;
	var left = (screen.width-width)/2;
	var top = (screen.height-height)/3;
	var url = "/spelbutik/help/hjalp_main.asp?main=" + main + "&under=" + under + "&helpsite=2";
	window.open(url, 'hjalp', 'height=' + height + ',width=' + width + ',left=' + left + ',top=' + top + ',resizable=no,status=no,menubar=no,scrollbars=no');
}
function openPokerFlash() {
	win_svs_pokerflashclient = window.open('https://flash.poker.svenskaspel.se/flashcgi/flashcgi.exe?ProductId=6001','svs_pokerflashclient', 'top='+((screen.height-530)/3)+', left='+((screen.width-750)/2)+', height=530, width=750, directories=no, location=no, menubar=no, status=no, toolbar=no, resizable=yes, scrollbars=yes,personalbar=no');
}
function openwebbtv(id){
	var xpos = 0;
	var ypos = 0;
	var idStr = "?id=";
	if(id != null && id != ""){
		idStr += id;
	} else {
		idStr = "";
	}
	if(screen.width > 802){
		xpos = (screen.width-800)/2;
	}
	if(screen.height > 503){
		ypos = (screen.height-500)/3;
	}
	params = "left="+xpos+",top="+ypos+",width=800,height=500,scrollbars=no,resizable=no,status=no";
	window.open("http://svenskaspel.qbrick.com/" + idStr,"webbTVsvenskaspel",params);
}
function openreg(){
	var vsid="1";
	var act=''
	if(arguments.length>0)vsid=arguments[0];
	if(arguments.length>1)act=arguments[1];
	openModalReg(vsid,act);
	return false;
	/*var vsid="1";
	if(arguments.length>0)vsid=arguments[0];
	var xpos=(screen.width-750)/2;
	var ypos=(screen.height-530)/3;
	window.open(user.secureUrl + "/regform/regstart.asp?vsid=" + vsid,"spelkontoreg","left="+xpos+",top="+ypos+",screenX="+xpos+",screenY="+ypos+",width=750,height=530,scrollbars=no,resizable=no,status=yes");
	return false;*/
}

if (getCookie("REG_OPENTRANS") == "1") setTimeout("openTransReg();",2000);
function openTransReg(){
	var cookiedomain = getCookieDomain();
	var expireDate = "Thu, 01-Jan-1970 00:00:01 GMT";
	document.cookie = "REG_OPENTRANS=0;Path=/;expires="+expireDate+";domain="+cookiedomain;
	dispatchEvent( { type: "showTransaction" } );
}

var regformurl = ''
var regform_waitercount = 0;
//if (getCookie("REG_OPEN") == "1") setTimeout("openModalReg(getCookie('REG_VSID'),getCookie('REG_KOD'));",2000);
if (getCookie("REG_OPEN") == "1") YAHOO.util.Event.onDOMReady(openRegOnDomReady,{vsid: getCookie('REG_VSID'), act: getCookie('REG_KOD')}, true);

function openRegOnDomReady(){
	openModalReg(this.vsid, this.act)
}

function openModalReg(){
	showWaiter();
	
	var cookiedomain = getCookieDomain();
	var expireDate = "Thu, 01-Jan-1970 00:00:01 GMT";
	document.cookie = "REG_OPEN=0;Path=/;expires="+expireDate+";domain="+cookiedomain;
	document.cookie = "REG_VSID=0;Path=/;expires="+expireDate+";domain="+cookiedomain;
	document.cookie = "REG_KOD=;Path=/;expires="+expireDate+";domain="+cookiedomain;
	
	var vsid="1";
	var act=''
	if(arguments.length>0)vsid=arguments[0];
	if(arguments.length>1)act=arguments[1];

	if (!(location.protocol=='https:'?true:false)){
		document.cookie = "REG_OPEN=1;Path=/;domain="+cookiedomain;
		document.cookie = "REG_VSID=" + vsid + ";Path=/;domain="+cookiedomain;
		document.cookie = "REG_KOD=" + act + ";Path=/;domain="+cookiedomain;
		location.href = secureUrl + '/p4.aspx' + location.search + (location.href.indexOf('pageid')<0?(location.href.indexOf('?')<0?'?':'&') + 'pageid='+defaultPageId:'');
		if(location.pathname.toLowerCase() == '/login.html'){
			location.href = location.href.toLowerCase().replace('login.html', 'p4.aspx')  + location.search + (location.href.indexOf('pageid')<0?(location.href.indexOf('?')<0?'?':'&') + 'pageid='+defaultPageId:'');
		}
		return false;
	}
	
	regformurl = secureUrl + '/regform/regstart.asp?vsid='+vsid+'&act=' + act + '&modal=1';
	
	//JS
	//Begin by creating a new Loader instance: 
	var loader_regform_modaldiv_js = new YAHOO.util.YUILoader(); 
	 
	//Add the module to YUILoader 
	loader_regform_modaldiv_js.addModule({ 
		name: "regform_modaldiv_js", //module name; must be unique 
		type: "js", //can be "js" or "css" 
		fullpath: secureUrl + "/regform/regform_modaldiv.js", //can use a path instead, extending base path 
		varName: "REGFORM_MODALDIV_JS" // a variable that will be available when the script is loaded.  Needed 
						// in order to act on the script immediately in Safari 2.x and below. 
		//requires: ['yahoo', 'event'] //if this module had dependencies, we could define here 
	}); 
 
	loader_regform_modaldiv_js.require("regform_modaldiv_js"); //include the new  module 
 
	// set the function that should exectute when the file loads 
	loader_regform_modaldiv_js.onSuccess = regform_hidewaiter; 
 
	loader_regform_modaldiv_js.insert(); 
	
	//CSS
	//Begin by creating a new Loader instance: 
	var loader_regform_modaldiv_css = new YAHOO.util.YUILoader(); 
	 
	//Add the module to YUILoader 
	loader_regform_modaldiv_css.addModule({ 
		name: "regform_modaldiv_css", //module name; must be unique 
		type: "css", //can be "js" or "css" 
		fullpath: secureUrl + "/regform/regform_modaldiv.css", //can use a path instead, extending base path 
		varName: "REGFORM_MODALDIV_CSS" // a variable that will be available when the script is loaded.  Needed 
						// in order to act on the script immediately in Safari 2.x and below. 
		//requires: ['yahoo', 'event'] //if this module had dependencies, we could define here 
	}); 
 
	loader_regform_modaldiv_css.require("regform_modaldiv_css"); //include the new  module 
 
	// set the function that should exectute when the file loads 
	loader_regform_modaldiv_css.onSuccess = regform_hidewaiter; 
 
	loader_regform_modaldiv_css.insert(); 
	
	return false;
}

function regform_loadiframe() {
	if (document.getElementById('regform_iframe')){
		document.getElementById('regform_iframe').src = regformurl;
	} else {
		frames['regform_iframe'].location.href = regformurl;
	}
}

function regform_hidewaiter(){
	regform_waitercount++;
	if (regform_waitercount > 1){
		revealModal('regform_modaldiv');
		setTimeout("regform_loadiframe();",2000);
		//regform_loadiframe();
		hideWaiter();
		regform_waitercount = 0;
		
	}
}

function  setCookie(cookiename,value,session,expiry)
	{
		var cookiedomain = getCookieDom();
		if (session)
		{
			document.cookie = cookiename + "=" + value + ";Path=/;domain="+cookiedomain+";";
		}
		else
		{
			document.cookie = cookiename + "=" + value + ";Path=/;domain="+cookiedomain+";expires=" + expiry;
		}
	}
function getCookieDom(){
		if (typeof(user)!='undefined') var url = getURLObject().publicUrl;
		if (typeof(url)=='undefined') var url = publicUrl;
		var cookiedomain = url.replace(new RegExp(/^https?\:\/\//i),"").replace(new RegExp(/^www\./i),"");
		return cookiedomain;
	}

function getCookie(cookiename) {
	
	var start = document.cookie.indexOf( cookiename + "=" );
	var len = start + cookiename.length + 1;
	if ( ( !start ) && ( cookiename != document.cookie.substring( 0, cookiename.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}


var Mouse = {x:0, y:0};
var Clicked = {x:0, y:0};
var Dragging = new Array();
document.onmousemove = getMousePos;
var lockedObjects = new Array();
var cFocus = null;
var maxZIndex;

function moveObj(obj, X, Y, relativeToPage, alignChanged) {
	if(makePath(obj)) {
		if(obj != undefined && obj != "undefined") {
			if(X == undefined || isNaN(X)) {
				X = Mouse.x;
			}
			if(Y == undefined || isNaN(Y)) {
				Y = Mouse.y;
			}
			if(relativeToPage == true) {
				var sizeObj = getVisibleSize();
				X += sizeObj.scrollLeft;
				Y += sizeObj.scrollTop;
			}
			X = X-leftFromBorder(makePath(obj).parentNode.id);
			
			var minX = -leftFromBorder(makePath(obj).parentNode.id);
			if(X<minX) X = minX;
			if(Y<0) Y = 0;
			makePath(obj).style.left = X+"px";
			makePath(obj).style.top = Y+"px";
			
			if(alignChanged != true)
				onAlignChanged();
		}
	}
}

function leftFromBorder(obj) {
	if(makePath(obj) != null) {
		var cObj = makePath(obj);
		var leftValue = Number(0);
		while(cObj.tagName != "BODY") {
			leftValue += Number(cObj.offsetLeft);
			cObj = cObj.parentNode;
		}
		return Number(leftValue);
	}else{
		return 0;
	}
}

function moveObjRelative(obj, X, Y) {
	X += makePath(obj).offsetLeft;
	Y += makePath(obj).offsetTop;
	makePath(obj).style.left = X+"px";
	makePath(obj).style.top = Y+"px";
}
function scrollPage(hor, ver) {
	window.scrollBy(hor, ver);
}
function getMousePos(e) {
	Mouse.x = fixE(e).clientX;
	Mouse.y = fixE(e).clientY;
	if(Dragging.length > 0) {
		for(e in Dragging) {
			moveObj(Dragging[e].object, Mouse.x-Dragging[e].x, Mouse.y-Dragging[e].y, Dragging[e].rtp);
		}
	}
}

function lockToObject(x, y, source, target)
{
	unLockObject(source, target); // remove old lock.
	lockedObjects.push({x:x, y:y, source:source, target:target});
	onAlignChanged();
}

function createDebugLink() {
	Debug = makePath("sessionhandler");
}

function unLockObject(source, target)
{
	for(var i = 0; i<lockedObjects.length;i++)
	{
		if(source == lockedObjects[i].source && target == lockedObjects[i].target)
		{
			lockedObjects.splice(i, 1);
			i--;
		}
	}
}

function onAlignChanged()
{
		for(var i = 0; i<lockedObjects.length;i++)
		{
			var X = 0;
			var Y = 0;
			
			var tagName = makePath(lockedObjects[i].target).tagName;
			if(tagName == "OBJECT" || tagName == "EMBED") {
				X = leftFromBorder(makePath(lockedObjects[i].target).parentNode.id);
				Y = Number(makePath(lockedObjects[i].target).parentNode.offsetTop);
			}else{
				X = leftFromBorder(lockedObjects[i].target);
				Y = Number(makePath(lockedObjects[i].target).offsetTop);
			}
			
			var xSign = lockedObjects[i].x.toString().substring(0,1);
			if(xSign == "+") {
				X += Number(makePath(lockedObjects[i].target).offsetWidth);
				X += Number(lockedObjects[i].x.toString().substring(1));
			}else if(xSign == "-") {
				X += Number(makePath(lockedObjects[i].target).offsetWidth);
				X -= Number(lockedObjects[i].x.toString().substring(1));
			}else{
				X += Number(lockedObjects[i].x);
			}
			
			var ySign = lockedObjects[i].y.toString().substring(0,1);
			if(ySign == "+") {
				Y += Number(makePath(lockedObjects[i].target).offsetHeight);
				Y += Number(lockedObjects[i].y.toString().substring(1));
			}else if(ySign == "-") {
				Y += Number(makePath(lockedObjects[i].target).offsetHeight);
				Y -= Number(lockedObjects[i].y.toString().substring(1));
			}else{
				Y += Number(lockedObjects[i].y);
			}
		
			tagName = makePath(lockedObjects[i].source).tagName;
			if(tagName == "OBJECT" || tagName == "EMBED") {
				var source = makePath(lockedObjects[i].source).parentNode;
			}else{
				var source = makePath(lockedObjects[i].source);
				//Debug.log("Source var INTE FLASH");
			}
			
			moveObj(source.id, X, Y, false, true);
		}
}

function newFocus(who)
{
	who = makePath(who).parentNode;
	if(who != "" && who != undefined && who != cFocus) {
		
		if(maxZIndex == undefined)
			getHighestDepth();
		else
			maxZIndex++;
		if(maxZIndex > 1000000)
			maxZIndex = 100;
		who.style.zIndex = maxZIndex;
		if(cFocus != null) {
			cFocus.style.zIndex = maxZIndex - 1;
		}
		cFocus = who;
	}
}

function getHighestDepth()
{
	var allElems = document.getElementsByTagName?
	document.getElementsByTagName("*"):
	document.all; // or test for that too
	maxZIndex = 0;
	for(var i=0;i<allElems.length;i++) {
		var elem = allElems[i];
		var cStyle = null;
		if (elem.currentStyle) {
			cStyle = elem.currentStyle;
		}
		else if (document.defaultView && document.defaultView.getComputedStyle) {
			cStyle = document.defaultView.getComputedStyle(elem,"");
		}
		var sNum;
		if (cStyle) {
			sNum = Number(cStyle.zIndex);
		} else {
			sNum = Number(elem.style.zIndex);
		}
		if (!isNaN(sNum)) {
			if(sNum<1000000)
				maxZIndex = Math.max(maxZIndex,sNum);
		}
	}
}

function fixE(e) {
	if (typeof e == 'undefined') e = window.event;
	if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
	if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
	return e;
}
//Börjar dra, relativt från där musen befinner sig vid init
function startDrag(obj) {
	Dragging.push({object:obj, x:Mouse.x-leftFromBorder(obj), y:Mouse.y-makePath(obj).offsetTop, rtp:false});
	moveObj(Dragging[Dragging.length-1].object, Mouse.x-Dragging[Dragging.length-1].x, Mouse.y-Dragging[Dragging.length-1].y, Dragging[Dragging.length-1].rtp);
}
//Användaren kan själv välja hur långt bort från musen något ska vara
function startDragAbsolute(obj, X, Y) {
	Dragging.push({object:obj, x:X, y:Y, rtp:true});
	moveObj(Dragging[Dragging.length-1].object, Mouse.x-Dragging[Dragging.length-1].x, Mouse.y-Dragging[Dragging.length-1].y, Dragging[Dragging.length-1].rtp);
}

function stopDrag(obj) {
	var iterator;
	iterator = Dragging.length;
	for(var i=0;i<iterator;i++) {
		if(Dragging[i].object == obj) {
			Dragging.splice(i, 1);
			iterator--;
		}
	}
}

function renderFlash(movie, width, height, id, swapOnFocus, wmode, embed)
{
	if(typeof(embed) == 'undefined')
		embed = false;

	if(!embed){
		newCreateEmbed(movie, width, height, id, swapOnFocus, wmode)
		return true;
	}
	pl_renderflash = true;
	var ret = createEmbed(movie, width, height, id, swapOnFocus, wmode);
	if(typeof(pl_renderflash) != 'undefined'){
		if (pl_renderflash) return ret;
	}
		pl_renderflash = false;
	document.write(ret);
}

function createEmbed(movie, width, height, id, swapOnFocus, wmode) {
	var hojd = "100%";
	if(BrowserDetect.browser == "Explorer"){
		hojd  = height;
	}
	var transparity = 'transparent';
	if(wmode == '1'){
		transparity = 'opaque';
	}
  //var embedStr = '<div id="flashelement'+ id.replace(/m/gi,'') + '" style="width:' + width + 'px;min-height:' + height + 'px;height: auto;_height:' + height + 'px;"><OBJECT CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" WIDTH="' + width + '" HEIGHT="' + hojd + '" ID="' + id + '" align="left">\n';
	
	var mrex = /^m\d+/i;
	var mid = id;
	if (mrex.test(id))
	{
		mid = id.replace(/^m/i,'');
	}
	//_height:' + height + 'px; bortaget från raden under
	var embedStr = '<div id="flashelement'+ mid + '" style="width:' + width + 'px;min-height:0px;height: auto;">';
	if(BrowserDetect.browser == "Explorer") {
		embedStr += '<OBJECT';
		
		if(swapOnFocus == true)
			embedStr += ' ONFOCUS=\'newFocus("'+id+'")\'';
		
		embedStr += ' CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" WIDTH="' + width + '" HEIGHT="' + hojd + '" ID="' + id + '" align="left">\n';	embedStr += '<PARAM NAME="movie" VALUE="'+movie+'"/>\n';
	    embedStr += '<PARAM NAME="quality" VALUE="autohigh"/>\n';
		
	    embedStr += '<PARAM NAME="wmode" VALUE="' + transparity + '" />\n';
		embedStr += '<PARAM NAME="salign" VALUE="lt" />';    
		embedStr += '</object>';
	}else{
		embedStr += '<EMBED'
		
		if(swapOnFocus == true)
			embedStr += ' ONFOCUS=\'newFocus("'+id+'")\'';
		
		embedStr += ' SRC="'+movie+'" WIDTH="' + width + '" HEIGHT="' + height + '" ID="' + id + '" NAME="' + id + '" SALIGN="lt" AUTOSTART="false" QUALITY="autohigh"  WMODE="' + transparity + '" align="left" TYPE="application/x-shockwave-flash"></EMBED>\n';
	}
	embedStr += '</div>\n';
	
	return embedStr;
}

function OpenSchool(url){
	var height=545;
	var width=756;
	var left=(screen.width-width)/2;
	var top=(screen.height-height)/3;
	var url2='https://svenskaspel.se/poker/'+url;
	window.open(url2, 'school', 'height=' + height + ',width=' + width + ',left=' + left + ',top=' + top + ',resizable=no,status=no,menubar=no,scrollbars=no');
}


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
		return 'Unknown browser';
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return false;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

/*
Copyright (c) Copyright (c) 2007, Carl S. Yestrau All rights reserved.
Code licensed under the BSD License: http://www.featureblend.com/license.txt
Version: 1.0.3
*/
var FlashDetect = new function(){
	var self = this;
	self.installed = false;
	self.raw = "";
	self.major = -1;
	self.minor = -1;
	self.revision = -1;
	self.revisionStr = "";
	var activeXDetectRules = [
		{
			"name":"ShockwaveFlash.ShockwaveFlash.7",
			"version":function(obj){
				return getActiveXVersion(obj);
			}
		},
		{
			"name":"ShockwaveFlash.ShockwaveFlash.6",
			"version":function(obj){
				var version = "6,0,21";
				try{
					obj.AllowScriptAccess = "always";
					version = getActiveXVersion(obj);
				}catch(err){}
				return version;
			}
		},
		{
			"name":"ShockwaveFlash.ShockwaveFlash",
			"version":function(obj){
				return getActiveXVersion(obj);
			}
		}
	];
	var getActiveXVersion = function(activeXObj){
		var version = -1;
		try{
			version = activeXObj.GetVariable("$version");
		}catch(err){}
		return version;
	};
	var getActiveXObject = function(name){
		var obj = -1;
		try{
			obj = new ActiveXObject(name);
		}catch(err){}
		return obj;
	};
	var parseActiveXVersion = function(str){
		var versionArray = str.split(",");//replace with regex
		return {
			"raw":str,
			"major":parseInt(versionArray[0].split(" ")[1], 10),
			"minor":parseInt(versionArray[1], 10),
			"revision":parseInt(versionArray[2], 10),
			"revisionStr":versionArray[2]
		};
	};
	var parseStandardVersion = function(str){
		var descParts = str.split(/ +/);
		var majorMinor = descParts[2].split(/\./);
		var revisionStr = descParts[3];
		return {
			"raw":str,
			"major":parseInt(majorMinor[0], 10),
			"minor":parseInt(majorMinor[1], 10), 
			"revisionStr":revisionStr,
			"revision":parseRevisionStrToInt(revisionStr)
		};
	};
	var parseRevisionStrToInt = function(str){
		return parseInt(str.replace(/[a-zA-Z]/g, ""), 10) || self.revision;
	};
	self.majorAtLeast = function(version){
		return self.major >= version;
	};
	self.minorAtLeast = function(version){
		return self.minor >= version;
	};
	self.revisionAtLeast = function(version){
		return self.revision >= version;
	};
	self.FlashDetect = function(){
		if(navigator.plugins && navigator.plugins.length>0){
			var type = 'application/x-shockwave-flash';
			var mimeTypes = navigator.mimeTypes;
			if(mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin && mimeTypes[type].enabledPlugin.description){
				var version = mimeTypes[type].enabledPlugin.description;
				var versionObj = parseStandardVersion(version);
				self.raw = versionObj.raw;
				self.major = versionObj.major;
				self.minor = versionObj.minor; 
				self.revisionStr = versionObj.revisionStr;
				self.revision = versionObj.revision;
				self.installed = true;
			}
		}else if(navigator.appVersion.indexOf("Mac")==-1 && window.execScript){
			var version = -1;
			for(var i=0; i<activeXDetectRules.length && version==-1; i++){
				var obj = getActiveXObject(activeXDetectRules[i].name);
				if(typeof obj == "object"){
					self.installed = true;
					version = activeXDetectRules[i].version(obj);
					if(version!=-1){
						var versionObj = parseActiveXVersion(version);
						self.raw = versionObj.raw;
						self.major = versionObj.major;
						self.minor = versionObj.minor; 
						self.revision = versionObj.revision;
						self.revisionStr = versionObj.revisionStr;
					}
				}
			}
		}
	}();
};
//var FlashDetectClass = new FlashDetect();
//FlashDetectClass.release = "1.0.3";

function DetectFlashVer(major, minor, revision)
{	
	var result = false;
	
	major = parseInt(major);
	minor = parseInt(minor);
	revision = parseInt(revision);

	if(FlashDetect.major <= major){
		if(FlashDetect.majorAtLeast(major)){
			if(FlashDetect.minorAtLeast(minor)){
				if(FlashDetect.revisionAtLeast(revision)){
					result = true;
				}
			}		
		}
	}else{
		// Om majorversion är högre än satta kravet så är vi i mål
		result = true;
	}
	

	return result;
}

function GetSwfVer()
{
	var s = FlashDetect.major + "_" + FlashDetect.minor + "_" + FlashDetect.revision;
	return s;
}

function checkFlashForced()
{
	if(!FlashDetect.majorAtLeast(10)){
		location.href = '/common/noflash.asp';
	}
}

function openFlashUpgrade()
{
	window.open("http://www.adobe.com/go/gntray_dl_getflashplayer_se", "_blank");	
}
Date.prototype.mDate = function(dateString){ 
	this.setYear(dateString.substr(0,4));
	this.setMonth(dateString.substr(5,2)-1);
	this.setDate(dateString.substr(8,2));
	this.setHours(dateString.substr(11,2));
	this.setMinutes(dateString.substr(14,2));
	this.setSeconds(dateString.substr(17,2));
}

//2002-02-02 12:12:12
Date.prototype.getMDate = function(){ 
	var year = this.getFullYear();
	var month = this.getMonth()+1;
	var day = this.getDate();
	var hour = this.getHours();
	var minute = this.getMinutes();
	var second = this.getSeconds();
	if (month < 10) month = '0' + month;
	if (day < 10) day = '0' + day;
	if (hour < 10) hour = '0' + hour;
	if (minute < 10) minute = '0' + minute;
	if (second < 10) second = '0' + second;
	return year + '-' + month  + '-' + day  + ' ' + hour  + ':' + minute  + ':' + second;
}

Date.prototype.addMonth = function(nrofmonths) //can only add and remove 1 month fixme
{
	if (nrofmonths > 0)
	{
		if (this.getMonth == 11)
		{
			this.setYear(this.getYear()+1)
			this.setMonth(0);
		}
		else
		{
			this.setMonth(this.getMonth()+1);
		}
	}
	else if (nrofmonths < 0)
	{
		if (this.getMonth == 1)
		{
			this.setYear(this.getYear()-1)
			this.setMonth(11);
		}
		else
		{
			this.setMonth(this.getMonth()-1);
		}
	}
return this;
}


function resetIE6(){
	var colsdiv = document.getElementById('columns');
	var flashReset=colsdiv.getElementsByTagName("object")
	for (var i = 0; i<flashReset.length ; i++)
	{
		flashReset[i].style.display = 'none';
	}
	setTimeout('resetIE6b();',1000);
}
	
function resetIE6b(){
	var colsdiv = document.getElementById('columns');
	var flashReset=colsdiv.getElementsByTagName("object")
	for (var i = 0; i<flashReset.length ; i++)
	{
		flashReset[i].style.display = '';
	}

}
//Hämtar infotext från element av typen InfoMessagesXML
function getInfoText(category, key){
	var text = eval("INFOMESSAGES_" + category.toUpperCase() + "['" + key + "']");
	if (typeof(text)=='undefined') text = "";
	return text;
}

//Hämtar feltext från element av typen InfoMessagesXML
function getErrorText(category, key){
	var text = eval("INFOMESSAGES_" + category.toUpperCase() + "['" + key + "']");
	if (typeof(text)=='undefined') text = "Ett fel har uppstått! Kontakta kundservice på 0770-11 11 11 eller försök igen.";
	return text;
}


//ByRef-params for use in function calls
function paramByRef()
{
    this.array = new Array(1);

    this.setValue = function(v) { this.array[0] = v; }
    this.getValue = function()  { return this.array[0]; }
}

function calculateCenterPosition(height, width, left, top) {
  //Send in height and width with desired values as paramByRef and send empty left and top as paramByRef
  //top and left will be calculated to position a window centered
  h = height.getValue();
  w = width.getValue();
  var winWidth = currentWidth();
  var winHeight = currentHeight();

  if (document.all) {
    winLeft = window.screenLeft;
    winTop = window.screenTop;
    winTop=winTop-25;
    winLeft=winLeft-5;
  }
  else {
    winLeft = window.screenX;
    winTop = window.screenY;
  }

  left.setValue(winLeft + (winWidth / 2) - (w / 2));
  top.setValue(winTop + (winHeight / 2) - (h / 2));
}

function currentWidth() {
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return [myWidth];
}

function currentHeight() {
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
      (document.documentElement.clientHeight) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
    myHeight=Number(myHeight)+20;
  } else if( document.body && (document.body.clientHeight) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
    myHeight=Number(myHeight)+20;
  }
  return [myHeight];
}

var paymentwin;
//Öppnar fönstret för bankkortsöverföringar
function openCCPayment(url) {
	openPayment(url, "ccpaymentwin", 450, 750, 0);
}

function closePaymentWin() {
	if(isCCPaymentOpen()){
		paymentwin.close();
	}
}

function isCCPaymentOpen() {
	var ret = false;
	if(paymentwin){
		ret = !paymentwin.closed;
	}
	return ret;
}

//Öppnar fönstret för internetbanksöverföringar
function openIBPayment(url) {
	openPayment(url, "ibpaymentwin", 768, 1024, 1);
}

var paymentAlertId = '';
//Generell funktion för att öppna fönster för bankkorts- och internetbanksöverföringar
function openPayment(url, windowname, height, width, scroll) {
	if (getCookie('SVSUID') == null || getCookie('SVSUID' == '') || getCookie('SVSCID') == null || getCookie('SVSCID' == '') || getCookie('SVSHANDLE') == null || getCookie('SVSHANDLE' == '')) {
		alert('Du är inte inloggad! Logga in och försök igen!');
		return false;
	} else {
		var h = new paramByRef();
		var w = new paramByRef();
		var l = new paramByRef();
		var t = new paramByRef();
		h.setValue(height);
		w.setValue(width);
		calculateCenterPosition(h, w, l, t);
		if(!url){
			url = "/common/blank.html";
		}
		if(!isCCPaymentOpen()){
			paymentwin = window.open(url, windowname,"location=1,status=0,scrollbars="+scroll+",width="+w.getValue()+",height="+h.getValue()+",left="+l.getValue()+",top="+t.getValue()+",menubar=0,resizable=1,directories=0,toolbar=0");
		}else{
			paymentwin.location.href = url;
		}
		
		if (paymentwin && typeof(paymentwin) != 'undefined') {
			paymentwin.focus();
		} else {
			paymentAlertId = showDialog(
				{ type: "toDialog", 
				respond: false, 
				mID: "paymentPopup", 
				caption: 'Det gick inte att öppna fönstret för överföringar!',
				msg: 'Du verkar ha någon typ av popup-blockerare aktiverad, du bör tillåta popup-fönster för svenskaspel.se i din webbläsare för att underlätta för dig i framtiden.<br><br><strong><a onclick="javascript:setTimeout(\'closePaymentPopup();\',250);" href="'+url+'" target="_blank">Klicka här för att fortsätta med din överföring</a></strong>', 
				buttons: ['Avbryt'] });
		}
	}
}

function closePaymentPopup() {
	cancelDialog(paymentAlertId);
}

//Sätter kaka med belopp för InternetBank-överföring
function setIBAmountCookie(amount) {
    setCookie('IBPaymentAmount', amount, true, null, true);
}

/////////////////////////////////
//funktioner från cspl
////////////////////////////////
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
    if (!isString(str)) return str;
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
    if (!isString(str)) return str;
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function isString() {
// Return a boolean value telling whether // the first argument is a string. 
	if (typeof arguments[0] == 'string') return true;
	if (typeof arguments[0] == 'object') {
		var criterion = arguments[0].constructor.toString().match(/string/i); 
		return (criterion != null);
	}
	return false;
}

function clearElement(id){
	var cell = document.getElementById(id);
	if (cell && cell != null)
	{
        clearElement2(cell);
	}
}

function clearElement2(cell){
	//fixme cleancss?
//	debugger;
	if (cell == null) return;
	if ( cell.hasChildNodes() )
	{
	    var i=0;
		while ( cell.childNodes.length >= 1 )
		{
	        clearElement2(cell.childNodes[i]);
	        cell.removeChild(cell.childNodes[i]);
	    }
	}
	if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == "8")
	{
	}
	else
	{
		purge(cell);
	}
    if (cell.id){
        var id = cell.id
        if (id.substring(0,1)=='d') removeModuleListener(id.replace('d','m'));
	    if (cell.tagName == 'DIV') cell.innerHTML = '';
	}
}

function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
		l = a.length;
        for (i = 0; i < l; i += 1) {
			if (a[i] == null) break;
			n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}
//TODO flytta till functions
function toggleDiv(id){
	document.getElementById(id).style.display = (document.getElementById(id).style.display!="block")? "block":"none";
}
function createXMLHttpRequest(){
	try{
		if(window.XMLHttpRequest) {
			var req = new XMLHttpRequest();
			// some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
			if(req.readyState == null){
				req.readyState = 1;
				req.addEventListener("load", 
					function(){
						req.readyState = 4;
						if(typeof req.onreadystatechange == "function")
							req.onreadystatechange();
					},false);
			}
			return req;
		}
		if(window.ActiveXObject)			{
				var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
				var o;
				for(var i = 0; i < progids.length; i++){
					try	{
						o = new ActiveXObject(progids[i]);
						return o;
					}catch (ex) {};
				}
				throw new Error("Could not find an installed XML parser");
			}
	}catch (ex){
		hideWaiter();
		alert('no xmlobject present');
	}
	return false;
}

function siteIdtoName(id){ //fulhack för webtrends
	var myArray = new Array('','','Förstasidan','sport','','poker','bingo','turspel','lotter','resultat','kundservice','om svenska spel','mina sidor','övrigt');
	return myArray[id];
}
function newCreateEmbed(movie, width, height, id, swapOnFocus, wmode){
	// Bortaget stöd för swaponfocus och extra div
	var transparity = 'transparent';
	if(wmode == '1'){
		transparity = 'opaque';
	}
	var mrex = /^m\d+/i;
	var targetDiv = id;
	if (mrex.test(id))
	{
		targetDiv = id.replace(/^m/i,'d');
	}
	var params = {
		id:id,
		align:"left",
		quality:"autohigh",
		wmode:transparity,
		salign:"lt"
	};
	var tmpObj = new parseQS(movie);
	var extraDiv = true;
	if(document.getElementById("flashelement" + targetDiv)){
	     extraDiv = false;
	}
	if(extraDiv)
	 document.write("<div id='flashelement" + targetDiv + "' style='width:" + width + "px;min-height:0px;height: auto;'>");
	/*if(tmpObj.FlashVars && tmpObj.FlashVars.divname)
	{
		document.write("<div id='" + targetDiv + "'></div>");
	} else {*/
		if(targetDiv != id)
		{
			document.write("<div id='" + id + "'></div>");
		} else {
			if(!document.getElementById(id))
			{
				document.write("<div id='" + id + "'></div>");
			}
		}
	//}
	if(extraDiv)
	 document.write("</div>");

	//		targetDiv = tmpObj.FlashVars.divname;
	if (height == "")
	{
		height='1'
	}
	var attributes = {};
	if(swapOnFocus == true)
	{
		attributes.onfocus = "newFocus('" + id + "')";
	}

	swfobject.embedSWF(tmpObj.MovieUrl, id, width, height, "9.0.0","expressInstall.swf", tmpObj.FlashVars, params, attributes);
}
function parseQS(MovieUrl){
	if(MovieUrl.indexOf("?") > 0){
		var tmpUrl = MovieUrl.substr(MovieUrl.indexOf("?")+1);
		if(tmpUrl.indexOf("#") > 0)
			tmpUrl = tmpUrl.substring(0,tmpUrl.indexOf("#"));
      var mittObj = new QuerystringToObject(tmpUrl);
		this.FlashVars = mittObj.params;
		tmpUrl = MovieUrl.substring(0,MovieUrl.indexOf("?"));
		var tmpString = "";
		obj = this.FlashVars
		for (var i in obj) {
		    if (i.toLowerCase() == "versionsnummer") {
		        tmpString = "versionsNummer=" + eval("this.FlashVars." + i) + "&";
		    }
		    if (i.toLowerCase() == "siteversion") {
		        tmpString += "siteversion=" + eval("this.FlashVars." + i) + "&";
		    }
		    if (i.toLowerCase() == "v") {
		        tmpString += "v=" + eval("this.FlashVars." + i);
		    }
		    
		}
		if (tmpString != "") {
		    tmpString = rtrim(tmpString, "&");
		    tmpString = "?" + tmpString;
		}
		this.MovieUrl = tmpUrl + tmpString;
	} else {
		this.MovieUrl = MovieUrl;
		this.FlashVars = null; 
	}
}
function QuerystringToObject(qs) { // optionally pass a querystring to parse
    this.params = new Object()
    this.get = Querystring_get

    if (qs == null)
        qs = location.search.substring(1, location.search.length)

    if (qs.length == 0) return

    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    qs = qs.replace(/\+/g, ' ')
    var args = qs.split('&') // parse out name/value pairs separated via &

    // split out each name=value pair
    for (var i = 0; i < args.length; i++) {
        var value;
        var pair = args[i].split('=')
        var name = unescape(pair[0])

        if (pair.length == 2)
            value = unescape(pair[1])
        else
            value = name

        this.params[name] = value
    }
}

/* Page header */
window.name = 'svenskaspel';
var oldSelId;
var siteArr = new Array();
var showingSearch = false;
function xml2Str(xmlNode) {
    try {
        // Gecko-based browsers, Safari, Opera.
        return (new XMLSerializer()).serializeToString(xmlNode);
    }
    catch (e) {
        try {
            // Internet Explorer.
            return xmlNode.xml;
        }
        catch (e) {//Strange Browser ??
            alert('Xmlserializer not supported');
        }
    }
    return false;
}
var errVar = true;
function checkArena() {
    var idStr;
    switch(currentSiteId)
    {
        case 3:            
            idStr = 'topNavSport';
            break;
        case 5:            
            idStr = 'topNavPoker';
            break;
        case 6:            
            idStr = 'topNavBingo';
            break;
        case 7:            
            idStr = 'topNavTurspel';
            break;
        case 8:            
            idStr = 'topNavLotter';
            break;
        case 9:            
            idStr = 'topNavResultat';
            break;
        case 10:
            idStr = 'topNavKundservice';
            break;
        case 11:
            idStr = 'topNavOmSvenskaSpel';
            break;
        default:
            //gör inget
    }                       
    
    if (oldSelId != idStr) {
        oldSelId = idStr
        changeSelected(idStr);
    }
}
function changeSelected(selId) {
    if (selId != 'undefined' && selId != undefined && selId != '') {
        var selectedElement = YAHOO.util.Dom.get(selId);
        YAHOO.util.Dom.addClass(selectedElement, "selected");
    }        
}
function topnavNavigate(obj, url) {
    obj.href = 'javascript:void(0)';
    getPage(url);
    return false;
}
function loadChangePin() {
    renderFlash('/common/changepin.swf?id=changepin&divName=flashelementchangepin&versionsNummer=' + versionGeneral + plQueryString, '320', '300', 'changepin', true);
}
function hideChangePin() {
    clearElement("flashelementchangepin");
    document.getElementById("changepinDiv").innerHTML = "<div id='flashelementchangepin'><div id='changepin'></div></div>";
}
function loadTrans(from) {
    pl_renderflash = true;
    var filename = '';
    if (from) {
        filename = 'transactionFromAccount.swf';
    } else {
        filename = 'transactionToAccount.swf';
    }
    renderFlash('/common/' + filename + '?id=transaktion&divName=flashelementtransaktion&ispopup=true&versionsNummer=' + versionGeneral + plQueryString, '781', '480', 'transaktion', true);
    pl_renderflash = false;
    window.document.transaktion.focus();
    newFocus('transaktion');
}
function hideTrans() {
    clearElement("flashelementtransaktion");
    document.getElementById("transaktionDiv").innerHTML = "<div id='flashelementtransaktion'><div id='transaktion'></div></div>";
}
function loadSearch(showPlayer) {
    if (!showingSearch) {
        pl_renderflash = true;
        if (document.getElementById("search").nodeName == "DIV")
            renderFlash('/common/search.swf?id=search' + (showPlayer == true ? '&player=true' : '') + '&divName=flashelementsearch&versionsNummer=' + versionGeneral + plQueryString, '1', '1', 'search', true);
        else
            document.getElementById("flashelementsearch").style.display = 'block';
        showingSearch = true;
        pl_renderflash = false;

    }
    else {
        hideSearch();
    }
}
function loadSearchPlayer() {
    loadSearch(true);
}
function hideSearch() {
    document.getElementById("flashelementsearch").style.display = 'none';
    showingSearch = false;
}
function showCard(id, xPos, yPos) {
    if (id != 'undefined' && id != '') {
        var thePath = makePath("flashelementvisit");
        loadVisitkort();
        // thePath = makePath("flashelementvisit");
        var sizeObj = getVisibleSize();
        if (xPos > 0)
            thePath.style.left = xPos - 160 + "px";
        else
            thePath.style.left = (sizeObj.width / 2 - 160 + sizeObj.scrollLeft) + "px"; //center on page
        if (yPos > 0)
            thePath.style.top = yPos - 100 + "px";
        else
            thePath.style.top = (sizeObj.height / 2 - 100 + sizeObj.scrollTop) + "px";
        var cardObj = new Object();
        cardObj.type = "showCard";
        cardObj.id = id;
        dispatchEvent(cardObj);
    }
}
function loadVisitkort() {
    document.getElementById("visitkortDiv").style.display = 'block';
    renderFlash('/common/visitkort.swf?id=visit&divName=flashelementvisit&versionsNummer=' + versionGeneral + '&pageid=3&name=&secure=True', '300', '220', 'visit', true);

}
function hideVisitkort() {
    document.getElementById("visitkortDiv").style.display = 'none';
    clearElement("flashelementvisit");
    document.getElementById("visitkortDiv").innerHTML = "<div id='flashelementvisit'><div id='visit'></div></div>";
}
function showCardAtMouse(id) {
    var sizeObj = getVisibleSize();
    showCard(id, Mouse.x + sizeObj.scrollLeft, Mouse.y + sizeObj.scrollTop);
}
function statListener() { }
statListener.prototype.handleEvent = function(e) {
    if (e) {
        if (e.type == "plPageLoadedCompleted") {
            if (e.siteId != 11 && e.siteId != 14) { //ej 'Om svenska spel' och 'förening'
                var sitester = document.getElementById("Sitester");

                if (sitester) {
                    sitester.style.display = "none";
                }
                runSitester();
            }
        }
    }
}
function goToSyn(synId){
    window.location.href = "/p4.aspx?pageid=Mina Sidor - Bolagsspel - Bolagssida&syndicateId=" + synId;
}
function getUser() {
    ucs.userId = getCookie("SVSUID");
    if (ucs.userId == null) ucs.userId = 0;
    ucs.customerId = getCookie("SVSCID");
    if (ucs.customerId == null) ucs.customerId = 0;
    ucs.loginHandle = getCookie("SVSHANDLE");
    if (ucs.loginHandle == null || ucs.loginHandle == '') ucs.loginHandle = 0;
    return ucs;
}
function GotoMinaSidorStart() {
	window.location.href = "/p4.aspx?pageid=" + minaSidorStartSidaPageId;
}
var ucs = new Object();
statListener = new statListener;
addModuleListener(statListener);


var timeoutTime = 400;

$(document).ready(function() {
    var mdd_dropdown = new Array("Sport", "Poker", "Bingo", "Turspel", "Lotter", "Resultat", "Kundservice", "OmSvenskaSpel");

    for (var i in mdd_dropdown) {
        $("#topNav" + mdd_dropdown[i]).hover(function() {
            var arena = $(this).attr("id").substring(6);

            if ($(".arena" + arena).hasClass("hideMenu")) {
                $(".arena" + arena).oneTime(timeoutTime, function() { MDD.ShowMenu(arena) });

                $(".arena" + arena).mouseleave(function() {
                    $(".arena" + arena).oneTime(timeoutTime, function() { MDD.HideMenu(arena) });
                });
                $(".arena" + arena).mouseenter(function() {
                    $(".arena" + arena).stopTime();
                    $("#topNav" + arena).addClass("active");
                    $(".arena" + arena).removeClass("hideMenu");
                });
            } else {
                $(".arena" + arena).stopTime();
            }
        }, function() {
            //när man slutar hovra på akutellt objekt i menyn
            var arena = $(this).attr("id").substring(6);
            $(".arena" + arena).stopTime();
            if (!($(".arena" + arena).hasClass("hideMenu"))) {
                $("#topNav" + arena).addClass("active");
                $(".arena" + arena).oneTime(timeoutTime, function() { MDD.HideMenu(arena) });
            }
        });


        $("#topNav" + mdd_dropdown[i]).focus(function() {
            var arena = $(this).attr("id").substring(6);
            $(".megaDropDownMenuItem").addClass("hideMenu");
            $(".nav-item").removeClass("active");
            if ($(".arena" + arena).hasClass("hideMenu")) {
                $(".arena" + arena).oneTime(timeoutTime, function() { MDD.ShowMenu(arena) });

                $(".arena" + arena).mouseleave(function() {
                    $(".arena" + arena).oneTime(timeoutTime, function() { MDD.HideMenu(arena) });
                });
                $(".arena" + arena).mouseenter(function() {
                    $(".arena" + arena).stopTime();
                    $("#topNav" + arena).addClass("active");
                    $(".arena" + arena).removeClass("hideMenu");
                });
            } else {
                $(".arena" + arena).stopTime();
            }
        });
    }
});


var MDD = function() {
    return {
        HideMenu: function(arena) {

            $(".arena" + arena).addClass("hideMenu");
            $("#topNav" + arena).removeClass("active");
        },
        ShowMenu: function(arena) {
            $(".megaDropDownMenuItem").addClass("hideMenu");
            $("#topNav" + arena).addClass("active");
            $(".arena" + arena).removeClass("hideMenu");
        }
    };
} ();

if (jQuery.browser.msie)
    jQuery(window).one("unload", function() {
        var global = jQuery.timer.global;
        for (var label in global) {
            var els = global[label], i = els.length;
            while (--i)
                jQuery.timer.remove(els[i], label);
        }
    });


jQuery.fn.extend({
    everyTime: function(interval, label, fn, times, belay) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, times, belay);
        });
    },
    oneTime: function(interval, label, fn) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, 1);
        });
    },
    stopTime: function(label, fn) {
        return this.each(function() {
            jQuery.timer.remove(this, label, fn);
        });
    }
});

jQuery.extend({
    timer: {
        guid: 1,
        global: {},
        regex: /^([0-9]+)\s*(.*s)?$/,
        powers: {
            // Yeah this is major overkill...
            'ms': 1,
            'cs': 10,
            'ds': 100,
            's': 1000,
            'das': 10000,
            'hs': 100000,
            'ks': 1000000
        },
        timeParse: function(value) {
            if (value == undefined || value == null)
                return null;
            var result = this.regex.exec(jQuery.trim(value.toString()));
            if (result[2]) {
                var num = parseInt(result[1], 10);
                var mult = this.powers[result[2]] || 1;
                return num * mult;
            } else {
                return value;
            }
        },
        add: function(element, interval, label, fn, times, belay) {
            var counter = 0;

            if (jQuery.isFunction(label)) {
                if (!times)
                    times = fn;
                fn = label;
                label = interval;
            }

            interval = jQuery.timer.timeParse(interval);

            if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
                return;

            if (times && times.constructor != Number) {
                belay = !!times;
                times = 0;
            }

            times = times || 0;
            belay = belay || false;

            if (!element.$timers)
                element.$timers = {};

            if (!element.$timers[label])
                element.$timers[label] = {};

            fn.$timerID = fn.$timerID || this.guid++;

            var handler = function() {
                if (belay && this.inProgress)
                    return;
                this.inProgress = true;
                if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
                    jQuery.timer.remove(element, label, fn);
                this.inProgress = false;
            };

            handler.$timerID = fn.$timerID;

            if (!element.$timers[label][fn.$timerID])
                element.$timers[label][fn.$timerID] = window.setInterval(handler, interval);

            if (!this.global[label])
                this.global[label] = [];
            this.global[label].push(element);

        },
        remove: function(element, label, fn) {
            var timers = element.$timers, ret;

            if (timers) {

                if (!label) {
                    for (label in timers)
                        this.remove(element, label, fn);
                } else if (timers[label]) {
                    if (fn) {
                        if (fn.$timerID) {
                            window.clearInterval(timers[label][fn.$timerID]);
                            delete timers[label][fn.$timerID];
                        }
                    } else {
                        for (var fn in timers[label]) {
                            window.clearInterval(timers[label][fn]);
                            delete timers[label][fn];
                        }
                    }

                    for (ret in timers[label]) break;
                    if (!ret) {
                        ret = null;
                        delete timers[label];
                    }
                }

                for (ret in timers) break;
                if (!ret)
                    element.$timers = null;
            }
        }
    }
});

function OpenWebbTvCatFunction(id){ 
var xpos = 0; var ypos = 0; var idStr = "?category=";
 if(id != null && id != ""){ idStr += id; } else { idStr = ""; } if(screen.width > 802){ xpos = (screen.width-800)/2; } if(screen.height > 503){ ypos = (screen.height-500)/3; } params = "left="+xpos+",top="+ypos+",width=800,height=500,scrollbars=no,resizable=no,status=no";
 window.open("http://svenskaspel.qbrick.com/" + idStr,"webbTVsvenskaspel",params); 
}

