var gameOpen = false;

function getParamFromUrl(name) {
    var re = new RegExp("(?:\\?|\\&)" + name + "=([^\\&]*)");
    var match = document.location.search.match(re);
    return (match != null) ? match[1] : "";
}

var Flag = {
    init: function () {
        Flag.raw = getParamFromUrl("f");
        Flag.values = Flag.raw.split("");
    },
    dict: ["nxs", "popunder", "vsp", "downloadpixel", "ab"],
    get: function (name) {
        for (var i = 0, ii = Flag.dict.length; i < ii; i++) {
            if (Flag.dict[i] == name) {
                return (Flag.values[i] && Flag.values[i] == "1") ? true : false;
            }
        }
        return null;
    }
};
Flag.init();

function _addjs(u) {
    if (navigator.appName.indexOf("Microsoft") == 0 && d) document.write("<scr" + "ipt defer='defer' async='true' src='" + u + "'></scr" + "ipt>");
    else {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        s.src = u;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
    }
}

function _issem() {
    var __issem = false;
    var sid = emerpcomp.GetSerialID();
    var isnewsid = (sid != null && sid != "" && sid != knownsid);
    var issem = getReferrer();
    if (issem && isnewsid) {
        __issem = true;
    }
    return __issem;
}

function _isseo() {
    var __isseo = false;
    var sid = emerpcomp.GetSerialID();
    var isnewsid = (sid != null && sid != "" && sid != knownsid);
    var isseo = getReferrer();
    if (isseo && !isnewsid) {
        __isseo = true;
    }
    return __isseo;
}

var bannerserverlink = (typeof (CONSTANTS.bannerserver) != "undefined" && CONSTANTS.bannerserver != "") ? CONSTANTS.bannerserver : "http://banner.new.mansioncasino.com";

function gotourl(url) {
    isLink = true;
    document.location.href = url;
}

if (window.addEventListener) {
    window.addEventListener("load", __init, false);
} else {
    window.attachEvent("onload", __init);
}
var agt = navigator.userAgent.toLowerCase();

function changelanguage(lang) {
    savecookie('language', lang, 1000);
}

function addLeadingZero(value) {
    if (value < 10) {
        return '0' + value;
    } else {
        return value;
    }
}

function getAMPM(value) {
    return (value >= 12) ? "PM" : "AM";
}

function cutHoursToAMPM(value) {
    return (value == 12 || value == 0) ? 12 : value % 12;
}

function updateDateSpan() {
    var dateSpan = $('dateContainer');
    if (dateSpan) {
        var date = new Date();
        dateSpan.innerHTML = Days[date.getUTCDay()] + ", " + Months[date.getUTCMonth()] + " " + addLeadingZero(date.getUTCDate()) + ", " + addLeadingZero(date.getUTCFullYear()) + " - " + cutHoursToAMPM(date.getUTCHours()) + ":" + addLeadingZero(date.getUTCMinutes()) + " " + getAMPM(date.getUTCHours()) + " GMT";
    }
    setTimeout("updateDateSpan();", 10000);
}

function handleStartedSteps(step) {
    if ($('startedStep' + step).style.display == 'none') {
        $('startedStepImage' + step).src = 'http://images.mansioncasino.com/images/sarrowdown.gif';
        $('startedStep' + step).style.display = '';
    } else {
        $('startedStepImage' + step).src = 'http://images.mansioncasino.com/images/sarrowright.gif';
        $('startedStep' + step).style.display = 'none';
    }
}
function __init() {
    updateDateSpan();
    if (typeof (document.doonload) != "undefined") {
        document.doonload();
    }
}

var emerpcomp = null;
var counter = 0;
var userGuid = "";
document.EMERPCallbacks = [];

function EMERPCallback(comp, eventName) {
    emerpcomp = comp;
    userGuid = comp.GetUserID();
    document.shouldsendhphit = doubletracking();
    if (document.location.search.match(/[&\?]p=1/)) {
        document.shouldsendhphit = false;
        document.sshhwd = true;
    } else {
        document.sshhwd = false;
    }
    if (typeof (document.EMERPAdditionalCallback) != "undefined") document.EMERPAdditionalCallback(comp, eventName);
    else if (eventName == "DummyEvent") {
        if (typeof (document.shouldsendhphit) != "undefined" && document.shouldsendhphit) emerpcomp.SendEvent("", "?hphit", "cp");
    }
    if (typeof (document.EMERPCallbacks) != "undefined" && typeof (document.EMERPCallbacks.length) != "undefined") {
        for (var i = 0, ii = document.EMERPCallbacks.length; i < ii; i++) {
            document.EMERPCallbacks[i](comp, eventName);
        }
    }
    if (typeof (document.EMERPToUrchin) != "undefined") document.EMERPToUrchin(comp, eventName);

}

function getDownloadLink() {
    var userGuid = (emerpcomp != null) ? emerpcomp.GetUserID() : "";
    var pixel = (emerpcomp != null) ? emerpcomp.GetPixelID() : "";
    var dp = (emerpcomp != null) ? emerpcomp.GetDPID() : "";
    var banner_click = readcookie('banner_click');
    var lang = getCurrentLanguageParameter("");
    var siteURL = document.location.href.substring(22, 24);
    var siteParamURL = document.location.href.substring(22, 23);
    var uniqueLang = '/au/nz/uk/za/';
    var uniqueGeoLang = '/se@sv/gb@uk/';
    var geoLang = readcookie('lo');
    var geoLangNew = uniqueGeoLang.indexOf(geoLang);
    var geoLang = geoLangNew != -1 ? uniqueGeoLang.substring(geoLangNew + 3, geoLangNew + 5) : readcookie('lo');
    if (siteParamURL != '?') {
        lang = (uniqueLang.search(siteURL) != -1 ? "en" : lang);
        if (siteURL != geoLang) { lang = ""; }
    }
    var creferer = '';
    if ( banner_click !== null && banner_click !== "null" ) {
    	banner_click = banner_click.split(',');
	    if ( banner_click[4].length >0 && banner_click[4] !== '*' ) {
	    	creferer = banner_click[4];
	    }
    }
	var cref = new cRefererObj(creferer);
	cref.add('UserGUID', userGuid);
	cref.add('pixelid', pixel);
	cref.add('DP', dp);
    var downloadUrl = bannerserverlink + "/cgi-bin/SetupCasino.exe?opt_lang=" + lang + "&creferer=" + cref.toString();

    return downloadUrl;
}

var __pb = __pb || [];
function getpropertybag() {
    var rs = [];
    if (readcookie("b") != null) rs.push("proposition:" + readcookie("b"));
    if (typeof (currentsrc) != "undefined" && currentsrc != "undefined" && currentsrc != "") rs.push("DL:" + currentsrc);
    for (var i = 0; i < __pb.length; i++) rs.push(__pb[i]);
    return rs.join(";");
}
function trackdownload(flash) {
    var script = document.createElement("script");
	var referrer = readcookie('abreferrer');
	if ( referrer == null || referrer == "null" || referrer == '' ) {
		referrer = document.referrer;
	}
    script.src = "http://stat.mansioncasino.com/stats/track.php?r=" + escape(referrer) + ((flash) ? "&__f=true" : "") + "&__d=true&__b=cc&pb=" + getpropertybag();
    document.body.appendChild(script);
}

function doDownload(usepopup) {
    trackdownload();
    var w = null;
    if (usepopup) document.downloadmethod = "popup";
    if (document.location.href.match(/\/download\.html/i) || !navigator.userAgent.match(/(firefox|msie)/i)) document.downloadmethod = "iframe";
    if (typeof (document.downloadmethod) != "undefined" && document.downloadmethod == "popup") {
        try {
            w = window.open(getDownloadLink(), "popDown", "width=1,height=1,top=0,left=0");
        } catch (e) {
            w = null;
        }
        if (w != null) {
            if (!redirectafterdownload || document.location.href.match(/\/download\.html/i)) return;
            document.location.href = CONSTANTS.download_link;
        }
    }
    if (w == null || typeof (document.downloadmethod) == "undefined" || document.downloadmethod == "iframe") {
        var downloadframe = document.getElementById("download_iframe");
        if (downloadframe == null) {
            downloadframe = document.createElement("iframe");
            downloadframe.width = "1px";
            downloadframe.height = "1px";
            downloadframe.position = "absolute";
            downloadframe.left = "-100px";
            document.body.appendChild(downloadframe);
        }
        downloadframe.src = getDownloadLink();
        if (!redirectafterdownload || document.location.href.match(/\/download\.html/i)) return;
        window.setTimeout(function () {
            document.location.href = CONSTANTS.download_link;
        }, 4000);
    }
}
var senddownload = false;
var downloadattempts = 0;
var redirectafterdownload = true;
var currentsrc = "";

function launchPlaytech(src) {
	savecookie('hideTheXsellPopup', true, 1);
    var source = document.location.href.replace(/^.*\//, "");
    if (typeof (src) != "undefined") source += ((source != "") ? ":" : "") + src;

    currentsrc = src;

    var ref_info_cookie = readcookie('banner_click');
    var get_ref_info = "?";
	var userGuid = (emerpcomp != null) ? emerpcomp.GetUserID() : "";
    var pixel = (emerpcomp != null) ? emerpcomp.GetPixelID() : "";
    var dp = (emerpcomp != null) ? emerpcomp.GetDPID() : "";
    var creferer = '';

    if (ref_info_cookie != null) {
        var ref_info = ref_info_cookie.split(",");
        creferer = ( ref_info[4] == '*' || ref_info[4] == '') ? '' : ref_info[4];
        get_ref_info = "?advertisercode=" + ref_info[0] + "&banner=" + ref_info[1] + "&profile=" + ref_info[2] + "&creferer=";
	} else {
	    get_ref_info = "?creferer=";
    }
	var cref = new cRefererObj(creferer);
	cref.add('UserGUID', userGuid);
	cref.add('pixelid', pixel);
	cref.add('DP', dp);
    window.open("http://cachebanner.mansioncasino.com/flash/20/casino_mansion/launchcasino.html" + get_ref_info +cref.toString()+"&"+ getCurrentLanguageParameter("language="), "newwindow", "width=800, height=600");
    if (emerpcomp != null) {
        if (document.sshhwd) emerpcomp.SendEvents([
            ["", "hphit", "cp"],
            ["", "download", "cf"]
        ], "download");
        else emerpcomp.SendEvent("", "download", "cf");
    } else sendflashdownload = true;

    if (typeof (_updatetimestamp) != "undefined") _updatetimestamp();
    _extgaq.push(['_trackEvent', 'Download', 'flash', 'full']);
    _extgaq.push(['_trackPageview', '/flashdownload.html']);
    if (readcookie("_fd") == null || readcookie("_fd") == "null") {
        _extgaq.push(['_trackPageview', '/download/flash/first']);
        savecookie("_fd", "1", 1000);
    } else if (readcookie("_fd") == "2") {
        _extgaq.push(['_trackPageview', '/download/flash/second']);
        savecookie("_fd", "3", 1000);
    }
	if (typeof(trackdownload) != "undefined") trackdownload(true);
}

function getCurrentLanguageParameter(prefix) {
    if (CONSTANTS.language == "") {
        return getCurrentLanguageParameterFromURI(prefix);
    } else {
        return (CONSTANTS.language != "") ? prefix + CONSTANTS.language : "";
    }
}

function getCurrentLanguageParameterFromURI(prefix) {
    var a = document.location.href.match(/mansioncasino.com\/([a-z]{2})\//);
    return (a != null && a.length > 1) ? prefix + a[1] : "";
}

function startDownload(src, avoidredirection, usepopup) {
    //if (avoidredirection) 
    redirectafterdownload = false;
    var source = document.location.href.replace(/^.*\//, "");
    if (typeof (src) != "undefined") source += ((source != "") ? ":" : "") + src;
    currentsrc = src;

    if (typeof (_updatetimestamp) != "undefined") _updatetimestamp();
    _extgaq.push(['_trackEvent', 'Download', 'exe', source]);
    _extgaq.push(['_trackPageview', '/clientdownload.html?' + src]);
    if (readcookie("_fd") == null || readcookie("_fd") == "null") {
        _extgaq.push(['_trackPageview', '/download/exe/first']);
        savecookie("_fd", "2", 1000);
    } else if (readcookie("_fd") == "1") {
        _extgaq.push(['_trackPageview', '/download/exe/second']);
        savecookie("_fd", "3", 1000);
    }

    isLink = true;
    var clienttype = "cd";
    try {
        if (!navigator.userAgent.match(/Windows/)) {
            clienttype = "cf";
        }
    } catch (e) { }
    downloadattempts = 0;
    startActualDownload(clienttype, usepopup);
	//Block VSP popup when user start dowwnload
	try { SwitchedOn = false;} catch(e) {} 
}

function startActualDownload(clienttype, usepopup) {
    if (emerpcomp == null || !cookiesreloaded) {
    	if ( emerpcomp !== null ) { 
    		reloadcookies( emerpcomp )
    	} else {
	        downloadattempts += 1;
	        if (downloadattempts < 8) {
	            window.setTimeout(function () {
	                startActualDownload(clienttype);
	            }, 1000);
	            return;
	        }
    	}
    }
    if (clienttype == "cd") {
		savecookie('hideTheXsellPopup', true, 1);
		try {
		    showDownloadPopup();
		} catch (e) { }
		doDownload(usepopup);
    } else {
        if (typeof (trackdownload) != "undefined") trackdownload(true);
        var ref_info_cookie = readcookie('banner_click');
        var get_ref_info = "?";
		var userGuid = (emerpcomp != null) ? emerpcomp.GetUserID() : "";
	    var pixel = (emerpcomp != null) ? emerpcomp.GetPixelID() : "";
	    var dp = (emerpcomp != null) ? emerpcomp.GetDPID() : "";
	    var creferer = '';

        if (ref_info_cookie != null) {
            var ref_info = ref_info_cookie.split(",");
            creferer = ( ref_info[4] == '*' || ref_info[4] == '') ? '' : ref_info[4];
            get_ref_info = "?advertisercode=" + ref_info[0] + "&banner=" + ref_info[1] + "&profile=" + ref_info[2] + "&creferer=";
		} else {
		    get_ref_info = "?creferer=";
        }
		var cref = new cRefererObj(creferer);
		cref.add('UserGUID', userGuid);
		cref.add('pixelid', pixel);
		cref.add('DP', dp);
        window.open("http://cachebanner.mansioncasino.com/flash/20/casino_mansion/launchcasino.html" + get_ref_info + cref.toString()+"&"+ getCurrentLanguageParameter("language="), "newwindow", "width=800, height=600");
    }
    if (emerpcomp != null) {
        if (document.sshhwd) emerpcomp.SendEvents([
            ["", "hphit", "cp"],
            ["", "download", clienttype]
        ], "download");
        else emerpcomp.SendEvent("", "download", clienttype);
    } else senddownload = true;
}

function startDownloadWORedirection(src) {
    startDownload(src, true);
}

function openForgot() {
    $('forgotPassword').style.display = '';
}

function closeForgot() {
    $('forgotPassword').style.display = 'none';
}

function findPosition(obj) {
    var pos = {
        x: 0,
        y: 0
    };
    try {
        while (obj.nodeName.toLowerCase() != "body") {
            pos.x += parseInt(obj.offsetLeft, 10);
            pos.y += parseInt(obj.offsetTop, 10);
            obj = obj.offsetParent;
        }
    } catch (e) { }
    return pos;
}

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) while (1) {
        curleft += obj.offsetLeft;
        if (!obj.offsetParent) break;
        obj = obj.offsetParent;
    }
    else if (obj.x) curleft += obj.x;
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) while (1) {
        curtop += obj.offsetTop;
        if (!obj.offsetParent) break;
        obj = obj.offsetParent;
    }
    else if (obj.y) curtop += obj.y;
    return curtop;
}

function openLanguages() {
    if ($('languages').style.display == 'none') {
        $('languages').style.display = '';
        $('langArrow').style.display = 'none';
        $('langArrowDown').style.display = '';
    } else {
        $('languages').style.display = 'none';
        $('langArrow').style.display = '';
        $('langArrowDown').style.display = 'none';
    }
}
var traceoutput = "";

function trace(value) {
    traceoutput += value + "_";
}

function syncAffiliate(source, destinations) {
    var value = readcookie(source);
    for (var i = 0; i < destinations.length; i++) {
        savecookie(destinations[i], value);
    }
}

function setAffiliate(name, profile) {
    profile = profile ? profile : "default";
    var domain = "." + (document.domain.match(/\./ig).length > 1) ? document.domain.replace(/[^\.]*\./, "") : document.domain;
    var date = new Date(); date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString(); document.cookie = "banner_domainclick=" + name + ",," + profile + ",*,*" + expires + "; path=/" + ((domain != "") ? ";domain=" + domain : ""); document.cookie = "banner_click=" + name + ",," + profile + ",*,*" + expires + "; path=/" + ((domain != "") ? ";domain=" + domain : ""); document.cookie = "banner_download=" + name + ",," + profile + ",*,*" + expires + "; path=/" + ((domain != "") ? ";domain=" + domain : "");
}

function getaffiliate() {
    var match = (document.cookie.match(/banner_domainclick/)) ? document.cookie.match(/banner_domainclick=([\d\D]+)/i) : null;
    if (match != null && match[1].replace(/,.*/, "") != "default02") return match[1].replace(/,.*/, "");
    else return "";
}

function getdownloadaffiliate() {
    var match = (document.cookie.match(/banner_download/)) ? document.cookie.match(/banner_download=([\d\D]+)/i) : null;
    if (match != null && match[1].replace(/,.*/, "") != "default02") return match[1].replace(/,.*/, "");
    else {
        var tracker = getParamFromUrl("tracker");
        return (tracker != "default02") ? tracker : "";
    }
}
var __segment = "";
var synced = false;
var cookiesreloaded = false;

function doubletracking() {
    if (synced) return false;
    var shouldsendhphit = true;
    synced = true;
    var knownaffiliate = emerpcomp.GetProperty("aff");
    var knownsid = emerpcomp.GetProperty("sid");
    var affiliate = getaffiliate();
    var downloadaffiliate = getdownloadaffiliate();
    var sid = emerpcomp.GetSerialID();
    var isnewaffiliate = (affiliate != "" && affiliate != knownaffiliate && !affiliate.match(/(Convertonet|convertonetC|ConvertonetC)/i));
    if (downloadaffiliate != "" && !downloadaffiliate.match(/(Convertonet|convertonetC|ConvertonetC)/i) && affiliate != downloadaffiliate && !isnewaffiliate) {
        isnewaffiliate = true;
        affiliate = downloadaffiliate;
        syncAffiliate("banner_download", new Array("banner_domainclick", "banner_click"));
    }
    var isnewsid = (sid != null && sid != "" && sid != knownsid);
    var isseo = getReferrer();
    var sidinurl = document.location.search.match(/[\?\&]SID=[0-9]+/);
    if (!isseo && affiliate == "" && sid == "") {
        trace("tu");
        emerpcomp.DeleteProperty("aff");
        emerpcomp.DeleteProperty("sid");
        emerpcomp.DeleteProperty("seo");
        __segment = 'Unknown';
        cookiesreloaded = true;
    } else if (!isnewaffiliate && !isnewsid && !sidinurl && ( !isseo || ( isseo && affiliate !== "" ) )) {
        trace("ka");
        emerpcomp.SetProperty("aff", affiliate);
        emerpcomp.SetProperty("seo", ( isseo ? 1 : 0 ));
        emerpcomp.SetProperty("sid", sid );
        emerpcomp.SetSerialID( sid );
        if ( typeof (document.shouldsendhphit) == "undefined" || (typeof (document.shouldsendhphit) != "undefined" && document.shouldsendhphit)) emerpcomp.SendEvent("", "?hphit", "cp");
        syncAffiliate("banner_domainclick", new Array("banner_click", "banner_download"));
        shouldsendhphit = false;
    } else if (isnewaffiliate && !sidinurl) {
        trace("na");
        emerpcomp.SetProperty("aff", affiliate);
        emerpcomp.SetProperty("seo", 0);
        emerpcomp.SetProperty("sid", 142150);
        emerpcomp.SetSerialID('142150');
        if ( typeof (document.shouldsendhphit) == "undefined" || (typeof (document.shouldsendhphit) != "undefined" && document.shouldsendhphit)) emerpcomp.SendEvent("", "?hphit", "cp");
        syncAffiliate("banner_domainclick", new Array("banner_click", "banner_download"));
        shouldsendhphit = false;
    } else if (isseo && !isnewsid) {
        trace("sc"); 
        var sessionID = 137026;
        emerpcomp.SetProperty("aff", "ConvertonetC");
        emerpcomp.SetProperty("seo", 1);
        emerpcomp.SetProperty("sid", sessionID);
        emerpcomp.SetSerialID(sessionID);
        setAffiliate("ConvertonetC", "seo");
        cookiesreloaded = true;
        try {
        	if ( checkCookie( 'p', '1') ) 
        		emerpcomp.SendEvent("", "?hphit", "cp");
        } catch ( e ) { console.info("Problem with HPHIT sending: "+e.description); }
        __segment = 'SEO';
        shouldsendhphit = false;
    } else if (isseo && isnewsid) {
        trace("smc");
        emerpcomp.SetProperty("aff", "ConvertonetC");
        emerpcomp.SetProperty("sid", sid);
        emerpcomp.SetProperty("seo", 0);
        setAffiliate("ConvertonetC", "sem");
        __segment = 'SEM';
        shouldsendhphit = false;
        cookiesreloaded = true;
    } else if (isnewsid && isnewaffiliate) {
        trace("ns");
        emerpcomp.SetProperty("aff", "ConvertonetC");
        emerpcomp.SetProperty("sid", sid);
        emerpcomp.SetProperty("seo", 0);
        setAffiliate("ConvertonetC", "media");
        __segment = 'Media/' + sid;
        cookiesreloaded = true;
    } else if (readcookie("__utmv") == null || readcookie("__utmv") == "null") {
        var _aff = emerpcomp.GetProperty("aff");
        var _sid = emerpcomp.GetProperty("sid");
        var _seo = emerpcomp.GetProperty("seo");
        if (_aff != "" && !_aff.match(/(Convertonet|convertonetC|ConvertonetC)/i)) __segment = 'Affiliate/' + _aff;
        else if (_seo == "1") __segment = 'SEO';
        else if (_sid != "") __segment = 'Media/' + sid;
        else __segment = 'Unknown';
        cookiesreloaded = true;
    } else {
        cookiesreloaded = true;
    }
    return shouldsendhphit;
}

function checkCookie( key, value ) {
	var cookie = readcookie( key );
	return ( cookie == value );
}

function getReferrer() {
	var referrer = readcookie('abreferrer');
	if ( referrer == null || referrer == "null" || referrer == '' ) {
		referrer = document.referrer;
	}
    return extractSearch(referrer);
    function extractSearch(url) {
        if (!url) return;
        var sites = [
			/^http:\/\/[^\/]*?\b(google)(?:\.[^\.]+)*\/.+?[\?&]q=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(google\.com)\/.+?[\?&]q=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(google\.ca)\/.+?[\?&]q=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(google\.co\.uk)\/.+?[\?&]q=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(yahoo)\.co(?:m|\.[^\.]+)\/.+?[\?&]p=([^&#]*)/i,
			/^http:\/\/search\.(yahoo\.com)\/.+?[\?&]p=([^&#]*)/i,
			/^http:\/\/(uk\.search\.yahoo\.com)\/.+?[\?&]p=([^&#]*)/i,
			/^http:\/\/(ca\.search\.yahoo\.com)\/.+?[\?&]p=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(yhs4\.search\.yahoo\.com)\/.+?[\?&]p=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(bing\.com)\/.+?[\?&]q=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(yandex)\.[^\/]*\/.+?[\?&]text=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(baidu)\.[^\/]*\/.+?[\?&]wd=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(search)\.(aol)\.[^\/]*\/.+?[\?&]q=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(ask)\.[^\/]*\/.+?[\?&]q=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(search\.com)\/.+?[\?&]q=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(ricerca\.virgilio\.it)\/.+?[\?&]qs=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(rambler\.ru)\/.+?[\?&]query=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(onetonline\.org)\/.+?[\?&]s=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(onetcenter\.org)\/.+?[\?&]s=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(search\.seznam\.cz)\/.+?[\?&]q=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(excite\.com)\/.+?[\?&]Web\/([^\/&#]*)/i,
			/^http:\/\/[^\/]*?\b(live\.com)\/.+?[\?&]st=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(search\.lycos\.com)\/.+?[\?&]query=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(blog\.conduit\.com)\/.+?[\?&]s=([^&#]*)/i,
			/^http:\/\/[^\/]*?\b(conduit\.com)\/.+?[\?&]q=([^&#]*)/i,
		""];
        for (var m, i = sites.length - 2; i >= 0; --i) {
            if (m = sites[i].exec(url)) {
                return { site: m[1], keyword: decodeURIComponent(m[2]) };
            }
        }
    }
}

function reloadcookies(comp) {
    emerpcomp.SetProperty("aff", comp.GetProperty("aff"));
    emerpcomp.SetProperty("sid", comp.GetProperty("sid"));
    emerpcomp.SetProperty("seo", comp.GetProperty("seo"));
    emerpcomp.SetSerialID(comp.GetSerialID());
    cookiesreloaded = true;
}
var iframese = null;

function savecookie(name, value, days) {
    var date = new Date();
    date.setTime(date.getTime() + (((typeof (days) != "undefined") ? days : 3) * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
    document.cookie = name + "=" + value + expires + "; path=/;domain=.mansioncasino.com";
}

function readcookie(name) {
    var re = new RegExp("(?:^| )" + name + "=([^;]*)", "i");
    var matches = document.cookie.match(re);
    return (matches && matches.length == 2) ? matches[1] : null;
}

function deleteCookie(name) {
    savecookie(name, "", -1);
}
function deletecookie(name) { deleteCookie(name); }

var lastName = -1;

function gotoInfo(name) {
    if (lastName != -1 && name != lastName) {
        $(lastName).style.display = 'none';
        $(lastName + 'Row').className = 'doTableRow';
        $(lastName + 'Sep').className = 'doTableSep';
        $(lastName + 'D').className = $(lastName + 'D').className.replace('Open', '');
        $(lastName + 'W').className = $(lastName + 'W').className.replace('Open', '');
        $(lastName + 'Frame').src = '';
    }
    if ($(name).style.display == 'none') {
        $(name).style.display = '';
        $(name + 'Row').className = 'doTableRowOpen';
        $(name + 'Sep').className = 'doTableSepOpen';
        $(name + 'D').className = $(name + 'D').className + 'Open';
        $(name + 'W').className = $(name + 'W').className + 'Open';
        $(name + 'Frame').src = name + '/index.html?showlink=yes';
        document.location.href = '#link_' + name;
    } else {
        $(name).style.display = 'none';
        $(name + 'Row').className = 'doTableRow';
        $(name + 'Sep').className = 'doTableSep';
        $(name + 'D').className = $(name + 'D').className.replace('Open', '');
        $(name + 'W').className = $(name + 'W').className.replace('Open', '');
        $(name + 'Frame').src = '';
    }
    lastName = name;
}
var isLink = false;

function on_unload() {
    if (document.location.search.match(/(client|nxs)=true/) || Flag.get('nxs')) document.cookie = "ptclient=true; path=/;domain=.mansioncasino.com";
    if (typeof (CONSTANTS.xsell_disabled) != "undefined" && CONSTANTS.xsell_disabled == "true") return false;
    if (isLink || readcookie("ptclient") == "true" || readcookie("x") == "true") {
        return false;
    } else {
        var under = Math.round(Math.random());
        var o = window.open(CONSTANTS.xsell_link + under, "_new", "width=1024, height=707");
        if (o != null) {
            if (under == 0) {
                o.blur();
                window.focus();
            }
            document.cookie = "x=true; path=/;domain:.mansioncasino.com";
        }
        return true;
    }
}

function handleLinks(e) {
    if (window.event) {
        var srcEl = window.event.srcElement;
    } else {
        var srcEl = e.target;
    }
    var samePage = false;
    if (srcEl.href) {
        if (srcEl.href.toString().indexOf("#") != -1) {
            var path = srcEl.href.toString().substring(0, srcEl.href.toString().indexOf("#"));
            var name = srcEl.href.toString().substring(srcEl.href.toString().indexOf("#"));
            var urlpath = location.href.toString().substring(0, srcEl.href.toString().indexOf("#"));
            if (urlpath == path) {
                samePage = true;
            }
        }
    }
    var onclickLocation = false;
    if (!(null == srcEl.getAttribute('onclick'))) {
        if (srcEl.getAttribute('onclick').toString().indexOf("location") != -1) {
            onclickLocation = true;
        }
    }
    if (srcEl.tagName == 'A' || onclickLocation) {
        var parent = srcEl;
    } else {
        var parent = getParent(srcEl);
    }
    var hrefLink = false;
    if (!(null == parent.getAttribute('href')) && parent.getAttribute('href') != "") {
        if (parent.getAttribute('href').toString().indexOf("javascript") == -1) {
            hrefLink = true;
        }
    }
    var onclickLocationParent = false;
    if (!(null == parent.getAttribute('onclick'))) {
        if (parent.getAttribute('onclick').toString().indexOf("location") != -1) {
            onclickLocationParent = true;
        }
    }
    if ((parent.tagName == "A" && hrefLink && !samePage) || onclickLocationParent) {
        isLink = true;
    }
}

function getParent(obj) {
    var p = obj;
    try {
        while (true) {
            if (p.tagName.toLowerCase() == "a" || p.getAttribute("onclick") != null) break;
            p = p.parentNode;
        }
        return p;
    } catch (e) {
        alert(e.description);
    }
}

function ff(a) {
    document.write(a);
}

function launchChat(a) {
    var b = window.open(a, "chatWindow", "width=490,height=400,resizable=0,scrollbars=no,menubar=no,status=no");
    b.focus(true);
}

function showCountryNumber(c) {
    for (var a = 0; a <= (c.options.length - 1); a++) {
        var b = document.getElementById("num_" + c.options[a].value);
        b.style.display = "none";
    }
    var b = document.getElementById("num_" + c.value);
    b.style.display = "";
}

function openLanguages(a) {
    if (document.getElementById("langselector").style.display == "none") {
        document.getElementById("langselector").style.display = "";
        a.style.backgroundPosition = "0 -29px";
    } else {
        document.getElementById("langselector").style.display = "none";
        a.style.backgroundPosition = "0 0";
    }
};

function initxsell(priority) {
    if (typeof (CONSTANTS.xsell_disabled) == "undefined" || CONSTANTS.xsell_disabled != "no") {
        if (typeof (showxsell) != "undefined") CONSTANTS.xsell_disabled = (priority == "maybe") ? showxsell() : priority;
    }
    if (document.location.search.match(/[\?&]p=1/) || Flag.get('popunder')) CONSTANTS.xsell_disabled = "true";
    var Browser = {
        name: "",
        version: 6,
        init: function () {
            navigator.userAgent.replace(/(chrome|safari|opera|firefox|msie)/i, function (a, b) {
                Browser.name = b.toLowerCase();
                try {
                    switch (Browser.name) {
                        case "msie":
                            Browser.version = parseInt(navigator.userAgent.match(/msie ([0-9])/i)[1], 10);
                            break;
                        case "safari":
                            var version = parseInt(navigator.userAgent.match(/version\/([0-9])/i)[1], 10);
                            Browser.version = (version >= 4) ? 8 : (version == 3) ? 7 : 6;
                            break;
                        default:
                            Browser.version = (typeof document.body.style.maxHeight != "undefined") ? 7 : 6;
                    }
                } catch (e) { }
            });
        }
    };
    Browser.init();
    if (Browser.version >= 7) {
        if (document.addEventListener) document.addEventListener("mousemove", mousemove, false);
        else document.attachEvent("onmousemove", mousemove);
        // document.onmousemove = mousemove;
    }
}
var pos = [];

function flat(arr) {
    var output = [];
    for (var i = 0; i < pos.length; i++) output.push(pos[i].x + "," + pos[i].y);
    return output.join("<br />");
}
var mousecheckinterval = 0;

function mousemove(e) {
    window.clearInterval(mousecheckinterval);
    e = e || event;
    if (pos.length == 0 || pos[pos.length - 1].y > e.clientY) {
        pos.push({
            x: e.clientX,
            y: e.clientY
        });
        mousecheckinterval = window.setTimeout(checkmouseposition, 1500);
    } else pos = [];
}

function checkmouseposition() {
    if (pos.length < 2 || pos[pos.length - 1].y > 150) {
        pos = [];
        return;
    }
    if (pos[pos.length - 1].y > 10) {
        var lastgap = 10000;
        for (var i = pos.length - 1; i >= 1; i--) {
            var gap = pos[i - 1].y - pos[i].y;
            if (gap >= lastgap) {
                pos = [];
                return;
            }
            lastgap = gap;
        }
    }
    popup.show('xsell');
}

var popup = {};
popup.show = function (popup) {
    var currentHeight = 0;
    containerHeight = (document.all) ? document.documentElement.offsetHeight - 4 : document.documentElement.scrollHeight;
    bodyHeight = window.document.body.offsetHeight;

    if (containerHeight < bodyHeight) {
        currentHeight = bodyHeight;
    } else {
        currentHeight = containerHeight;
    }

    if (document.location.search.match(/(client|nxs)=true/) || Flag.get('nxs')) document.cookie = "xsell=true; path=/;domain=.mansioncasino.com";
    if (typeof (CONSTANTS.xsell_disabled) != "undefined" && CONSTANTS.xsell_disabled == "true") return false;

    var xSellCookie = readcookie("xsell");
    if (xSellCookie == "true") return;
    else {
        $("blocker").style.height = currentHeight + "px";
        $("blocker").style.display = '';
        $('xsell_title').innerHTML = CONSTANTS.xsellTitle;
        $('xsell_offer').innerHTML = CONSTANTS.xsellOffer;
        $('xsell_visit').innerHTML = CONSTANTS.xsellVisitURL;
        $('download_button').innerHTML = CONSTANTS.xsellDownloadTitle;


        $(popup).style.display = '';
        document.cookie = "xsell=true";

        $('xsell_iframe').src = "/xsell/gaxsell.html";
    }
};

function hideXsell(popup) {
    var iframe = document.getElementById('xsell_iframe').contentWindow;
    iframe.sendpageview('exit');
    $("blocker").style.display = 'none';
    $(popup).style.display = 'none';
}

function goTo(target) {
    var iframe = document.getElementById('xsell_iframe').contentWindow;
    if (target == 'main') {
        iframe.sendpageview('main');
        location.href = CONSTANTS.xsell_link;
    }
    else {
        iframe.sendpageview('download');
        location.href = CONSTANTS.xsellDownloadLink;
    }
}

function limitEvent(e) {
    if (!e && window.event) { // IE
        window.event.cancelBubble = true;
    } else if (e && e.stopPropagation) { // standard
        e.stopPropagation();
    }
}
function openWin(action, gameCode, lang, url) {
	//Block VSP popup when user start dowwnload
	try { SwitchedOn = false;} catch(e) {} 
    if (action == 'download' || action == 'bonus') { launchPlaytech(); }
    else if (action == 'download_r') { startDownload(); }
    else if (action == 'uniqueGames') { flashGame(gameCode, lang); return; }
    else if (action == 'playforreal') { playforreal(); }
    else if (action == 'openWin') {
        if (typeof (openWinParams) != 'undefined' && openWinParams != '') {
            var winParams = new Array;
            winParams[0] = "\'" + url + "\'";
            winParams[1] = "\'newWindow\'";
            winParams[2] = "\'" + openWinParams + "\'";
            eval('window.open(' + winParams[0] + ',' + winParams[1] + ',' + winParams[2] + ')');
            return;
        }
        window.open(url);
    }
    else { window.open("http://www.mansioncasino.com/za/info.html", "infowindow", 'directories=no,location=no,menubar=no,scrollbars=no,status=no,toolbar=no,resizable=no,width=670,height=470'); }
    return false;
}
function setButton(width, height, top, left, parentId, action, divElement, gameCode, lang, url) {
    if (isNaN(width)) width = 680;
    if (isNaN(height)) height = 480;
    if (isNaN(left)) left = 0;
    if (isNaN(top)) top = 0;

    if (divElement) { var newdiv = document.getElementById(divElement); }
    else {
        var newdiv = document.createElement("div");
        newdiv.style.width = width + "px";
        newdiv.style.height = height + "px";
        newdiv.style.position = "absolute";
        newdiv.style.top = top + "px";
        newdiv.style.left = left + "px";
        newdiv.style.cursor = "pointer";
        var parentElem = document.getElementById(parentId);
        if (parentElem) { document.getElementById(parentId).appendChild(newdiv); }
        else { return; }
    }
    newdiv.onclick = function (event) {
        limitEvent(event);
        openWin(action, gameCode, lang, url);
    };
}

function _as(u) {
    setTimeout(function () {
        var s = document.createElement('script');
        var f = document.getElementsByTagName('script')[0];
        s.type = 'text/javascript';
        s.async = true;
        s.src = u;
        f.parentNode.insertBefore(s, f);
    }, 1);

}

function markuser(s) {
    _as("//stat.mansioncasino.com/stats/track.php?__d=false&__b=cc&pb=" + s);
}

function callfromflash(action) {
    isLink = true;
    switch (action) {
        case "download":
            startDownload('flash');
            break;
        case "instantplay":
            launchPlaytech();
            break;
        case "vip":
            document.location.href = "/points/";
            break;
        case "promo":
            document.location.href = "/points/";
            break;
        case "promotion":
            document.location.href = "/promotions/latest-games/";
            break;
        default:
            alert('unknown action:' + action);
            break;
    }
}

function capture(path) {
    var urlpattern = new RegExp("(http|https)://(.*?)(/.*)?$");
    var parsedurl = path.match(urlpattern);
    path = (parsedurl != null ? parsedurl[parsedurl.length - 1] : path);
    if (path != 0) {
        _extgaq.push(function () { _gaq.push(['_setCustomVar', 3, 'Unique Image', path, 1]); });
        __pb.push('image:' + path);
    }
}

function cRefererObj( creferer ) {
	this.creferer = this.parse(creferer);
}

cRefererObj.prototype.parse = function ( creferer ) {
	var cret = new Object();
	if ( creferer !== '' && creferer !== '*' ) {
		var cref = unescape(creferer).split(';');
		for ( var idx in cref ) {
			var item = cref[idx].split(':',2);
			cret[item[0]] = item[1];
		}
	}
	return cret;
}

cRefererObj.prototype.add = function ( name, value ) {
	this.creferer[name] = value;
}

cRefererObj.prototype.get = function ( name ) {
	return ( typeof( this.creferer[name] ) == "string" ) ? this.creferer[name] : false;
}

cRefererObj.prototype.del = function ( name ) {
	delete this.creferer[name];
}

cRefererObj.prototype.toString = function ( ) {
	var cret = '';
	for ( var idx in this.creferer ) {
		cret = cret + idx + ':' + this.creferer[idx] + ';';
	}
	if ( cret.length > 0 ) {
		cret = cret.substr(0, cret.length - 1);
	}
	return cret;
}

