﻿// JScript File

//$(document).ready(function() {

//});



//create onDomReady Event
window.onDomReady = DomReady;

//Setup the event
function DomReady(fn) {
	//W3C
	if (document.addEventListener) {
		document.addEventListener("DOMContentLoaded", fn, false);
	}
	//IE
	else {
		document.onreadystatechange = function() { readyState(fn) }
	}
}

//IE execute function
function readyState(fn) {
	//dom is ready for interaction
	if (document.readyState == "interactive") {
		fn();
	}
}

//execute as soon as DOM is loaded
window.onDomReady(onReady);

//do on ready
function onReady() {
	ApplyFieldValuesToCache();
}


$.fn.pulsateElement = function(pulsateTime) {

    if (pulsateTime == undefined)
        pulsateTime = 700;

    $(this).show().fadeOut(pulsateTime);

    //    $(eId).show().fadeOut(pulsateTime, function() {
    //        $(this).show().fadeOut(pulsateTime);
    //    });

    return $(this);
}

function startUpdateTimeLeft(eId) {

    setTimeout("updateTimeLeft('" + eId + "');", 1000);
}

function updateTimeLeft(eId) {

    var timeLeftContainer = $(eId);

    if (timeLeftContainer != null && isNaN(timeLeftContainer)) {

        var secondsLeft = timeLeftContainer.text();

        secondsLeft--;

        if (secondsLeft >= 0)
            timeLeftContainer.text(secondsLeft);

        if (secondsLeft > 0)
            startUpdateTimeLeft(eId);
    }
}


/***** MULTIPLAYER QUEUE - START *****/
var _multiplayerQueueUserCount = -1;
var _multiplayerQueueIntervalCheck = "";
var _multiplayerQueueIsRefreshing = false;


function bindMultiplayerQueue(queueUserCount, refreshing) {
    _multiplayerQueueUserCount = queueUserCount;
    
    if (refreshing)
        $('div.multiPlayerQueueWrapper div#pulsateOverlay').pulsateElement();
}

function startMultiplayerQueueIntervalCheck(updateInterval) {

    if (_multiplayerQueueIntervalCheck == "")
        _multiplayerQueueIntervalCheck = setInterval("multiplayerQueueCheckUserCount()", updateInterval);
}

function stopMultiplayerQueueIntervalCheck() {

    if (_multiplayerQueueIntervalCheck != "")
        clearInterval(_multiplayerQueueIntervalCheck);
}

function multiplayerQueueCheckUserCount() {

    PageMethods.CheckMultiplayerUserCount(getMultiplayerQueueCheckUserCountCallback, getMultiplayerQueueCheckUserCountFailed);
}

function getMultiplayerQueueCheckUserCountCallback(result) {

    if (result != _multiplayerQueueUserCount) {
        refreshMultiplayerQueue(); // This method is created by the code-behind
    }

    //console.log(new Date().getTime() + " multiplayerQueue: usercount: " + _multiplayerQueueUserCount + " result: " + result);
}

function getMultiplayerQueueCheckUserCountFailed(error, userContext, methodName) {
    //console.log(error);
}

function multiplayerQueueClientClose() {

    var wrapper = $('div.multiPlayerQueueWrapper');

    wrapper.hide();
}

/***** MULTIPLAYER QUEUE - END *****/

/***** IMPORTANT MESSAGE BAR - START *****/
var _importantMessageActiveStatus = "0;0";
var _checkActiveImportantMessagesInterval = "";

var _clientClose = false;

var BARSTATUS_OPEN = 2
var BARSTATUS_OPENING = 1
var BARSTATUS_CLOSED = -2
var BARSTATUS_CLOSING = -1
var BARSTATUS_FADING = -3
var _importantMessageBarStatus = BARSTATUS_CLOSED;

function importantMessageBarSlideUp(barId, slideTime, autoClose) {

    //console.log('>importantMessageBarSlideUp');

    var e = $('#' + barId);

    if (slideTime > 0) {

        e.css('bottom', -e.outerHeight(true));

        _importantMessageBarStatus = BARSTATUS_OPENING;

        e.animate({ bottom: "+=" + (e.outerHeight(true)) }, slideTime, function() {
            _importantMessageBarStatus = BARSTATUS_OPEN;
            if (autoClose)
                setTimeout(function() {
                    if (_importantMessageBarStatus == BARSTATUS_OPEN)
                        importantMessageBarSlideDown(barId, status);
                }, 3000);
        });
    }
    else {
        e.css('bottom', 0);
        _importantMessageBarStatus = BARSTATUS_OPEN;
    }
}

function importantMessageBarSlideDown(barId) {
    var e = $('#' + barId);
    _importantMessageBarStatus = BARSTATUS_CLOSING;
    e.animate({ bottom: "-=" + (e.outerHeight(true)) }, 500, function() { _importantMessageBarStatus = BARSTATUS_CLOSED; });
}

function importantMessageBarStep(step) {

    var _heightAnimationTime = 500;
    var _delayModifier = 10;

    var importantMessageBarWrapper = $('div.importantMessageBarWrapper');
    
    var currentItem = importantMessageBarWrapper.find('div.visibleDiv');
    var newItem;

    if (step == 1)
        newItem = currentItem.next('div.divMessage');
    else
        newItem = currentItem.prev('div.divMessage');

    if (newItem.length > 0) {

        var container = importantMessageBarWrapper.find('div#container');

        var totalCount = container.find('div.divMessage').size();

        var spanCounterPage = importantMessageBarWrapper.find('span#lblCounterPage');
        var currentPage = parseInt(spanCounterPage.text());
        currentPage += step;

        if (currentPage == 1)
            importantMessageBarWrapper.find('a#aNavigationPrevious').hide();
        else
            importantMessageBarWrapper.find('a#aNavigationPrevious').show();

        if (currentPage == totalCount)
            importantMessageBarWrapper.find('a#aNavigationNext').hide();
        else
            importantMessageBarWrapper.find('a#aNavigationNext').show();

        var currentItemHeight = currentItem.outerHeight(true);
        var newItemHeight = newItem.outerHeight(true);

        var diffItemHeight = newItemHeight - currentItemHeight

        container.height(currentItemHeight);

        currentItem.removeClass('visibleDiv');
        currentItem.hide();


        if (diffItemHeight != 0) {

            //container.find('div#divLoading').show();

            container.animate({ height: "+=" + diffItemHeight }, _heightAnimationTime, function() {
                newItem.addClass('visibleDiv');
                newItem.show();
                //container.find('div#divLoading').hide();
            });
            
        }
        else {
            newItem.addClass('visibleDiv');
            newItem.show();
        }

        spanCounterPage.text(currentPage);
    }

}

function importantMessageClientClose() {

    //console.log('>importantMessageClientClose');

    _clientClose = true;
        
    var importantMessageBarWrapper = $('div.importantMessageBarWrapper');

    var visibleDiv = importantMessageBarWrapper.find('div#container div.visibleDiv');

    var currentHeight = visibleDiv.outerHeight(true);
    var messageId = visibleDiv.find(':hidden').attr('value');

    var hiddenClose = importantMessageBarWrapper.find('.closeButton').next();

    hiddenClose.attr('value', currentHeight + ';' + messageId);

    var totalCount = importantMessageBarWrapper.find('div#container div.divMessage').size();

//    console.log(totalCount);    
    
    if (totalCount == 1) {
        importantMessageBarWrapper.hide();
        _importantMessageActiveStatus = "0;0";
    }

    visibleDiv.remove();
}

function bindImportantMessageBar(barWrapperId, animateSlideUp, barWidth) {

    //console.log(">bindImportantMessageBar: " + _importantMessageActiveStatus);

    var delayTime = 0;

    if (animateSlideUp)
        delayTime = 800;

    var importantMessageBarWrapper = $('div.importantMessageBarWrapper');

    importantMessageBarWrapper.show();
    importantMessageBarWrapper.css('width', barWidth);
    importantMessageBarWrapper.css('margin-left', -(importantMessageBarWrapper.outerWidth() / 2));

    importantMessageBarWrapper.find('a#aNavigationNext').click(function() {
        importantMessageBarStep(1);
        return false;
    });

    importantMessageBarWrapper.find('a#aNavigationPrevious').click(function() {
        importantMessageBarStep(-1);
        return false;
    });

    var numMessages = importantMessageBarWrapper.find('div#container div.divMessage').size();

    if (numMessages > 1)
        $('div.importantMessageBarWrapper a#aNavigationNext').show();

    importantMessageBarSlideUp(barWrapperId, delayTime, false);
}

function bindImportantMessagesActiveStatus(activeStatus) {
//    console.log("bindImportantMessagesActiveStatus: " + activeStatus);
    _importantMessageActiveStatus = activeStatus;
}

function bindImportantMessagesIntervalCheck(updateInterval) {

    if (_checkActiveImportantMessagesInterval == "")
        _checkActiveImportantMessagesInterval = setInterval("checkActiveImportantMessages()", updateInterval);
}

function checkActiveImportantMessages() {

    if (_clientClose) {
        //console.log("_clientClose");
        _clientClose = false;
        return;
    }

    PageMethods.CheckImportantMessagesActiveStatus(getCheckActiveImportantMessagesCallback, getCheckActiveImportantMessagesFailed);
}

function getCheckActiveImportantMessagesCallback(result) {

    if (result != "" && result != _importantMessageActiveStatus) {
        //console.log("refreshing!");
        refreshImportantMessages(); // This method is created by the code-behind
    }

//    console.log(new Date().getTime() + " im: " + _importantMessageActiveStatus + " result: " + result);
}

function getCheckActiveImportantMessagesFailed(error, userContext, methodName) {

}
/***** IMPORTANT MESSAGE BAR - END *****/


function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
}


function game_show(title, text)
{
	if (text != '' && title != '')
	{
	    window.document.getElementById('gameboxtitle').innerHTML=title;
		window.document.getElementById('gameboxcontent').innerHTML=text;
		window.document.getElementById('gamebox').style.display='';
	}
}

function AchievementContinue() {
	$(".popupMessageOverlay").css("display", "none");
	__doPostBack('achievementPopup', 'hide');
}

function toggleElement(element) {

    var elementId = document.getElementById(element);

    if (elementId.style.display == 'none') {
        elementId.style.display = 'block';
    }
    else {
        elementId.style.display = 'none';
    }
    
}

function game_hide()
{
	window.document.getElementById('gamebox').style.display='none';	
	window.document.getElementById('gameboxtitle').innerHTML='';
	window.document.getElementById('gameboxcontent').innerHTML='';
}

function game_position (Ereignis) {
	
	if (!Ereignis)
   		Ereignis = window.event;
   		
	if (document.all) {
	    if (document.body && document.body.scrollTop)
	    {
	        tempX = event.clientX + document.body.scrollLeft;
	        tempY = event.clientY + document.body.scrollTop;
	    }
	    else
	    {
	        tempX = event.clientX + document.documentElement.scrollLeft;
	        tempY = event.clientY + document.documentElement.scrollTop;	    
	    }
	  } else {
	    tempX = Ereignis.pageX;
	    tempY = Ereignis.pageY;
	} 
	
	
	
	
	document.getElementById("gamebox").style.left  = (tempX + 15) + "px";
	document.getElementById("gamebox").style.top = (tempY - 50) + "px";
}

function game_position_left(Ereignis) {

    if (!Ereignis)
        Ereignis = window.event;

    if (document.all) {
        if (document.body && document.body.scrollTop) {
            tempX = event.clientX + document.body.scrollLeft;
            tempY = event.clientY + document.body.scrollTop;
        }
        else {
            tempX = event.clientX + document.documentElement.scrollLeft;
            tempY = event.clientY + document.documentElement.scrollTop;
        }
    } else {
        tempX = Ereignis.pageX;
        tempY = Ereignis.pageY;
    }

    document.getElementById("gamebox").style.left = (tempX - 150) + "px";
    document.getElementById("gamebox").style.top = (tempY + 10) + "px";
}

function OpenWindowEX(url, w, h, resizable)
{
	if (resizable == undefined || resizable == false)
		resizable = "no";
	else
		resizable = "yes";

    //var basestring="window"+new Date().getTime();
	var s = new String("width=" + w + ",height=" + h + ",resizable=" + resizable + ",scrollbars=yes");
	if(url.indexOf("?") == -1)
	    url = url + "?" + new Date().getTime();
	else
	    url = url + "&" + new Date().getTime();
	
	window.open(url, "popup", s);
}

function NewWindow(url) 
{
    window.open(url, "_NEW", "", "");
}


function OpenExternalWindow(url, width, height, windowname, scrollbar)
{
    if(typeof width == 'undefined')
        width=800;
    if(typeof height == 'undefined')
        height=600;
    //if(typeof windowname == 'undefined')
        windowname = "window"+new Date().getTime();
    if(typeof scrollbar == 'undefined')
        scrollbar = "yes";
        
	if(url.indexOf("?") == -1)
	    url = url + "?" + new Date().getTime();
	else
	    url = url + "&" + new Date().getTime();
	
    exWin = open(url,windowname,"width="+width+",height="+height+",resizable=yes,scrollbars="+scrollbar);
	exWin.focus();
	checkBlocker(exWin);
}

function OpenExternalWindowCost(url,text)
{
/*
    if(!confirm(text))
        return false;
        */
    var basestring= "exWin"+new Date().getTime();//"exWin";

    exWin = open(url,basestring,"width=800,height=600,resizable=yes,scrollbars=no");
	exWin.focus();
	checkBlocker(exWin);
	return true;
}

function checkBlocker(exWin)
{
  window.setTimeout(function(exWin)
    {
        return function()
        {
                if(exWin.closed == true){ alert ("It looks like you may have a Pop-Up Blocker installed.");  }
        }
    } (exWin), 500);
}

function startcounter(totalseconds, element, prefix)
{
    totalseconds--;
    
    minutesLeft = Math.floor(totalseconds/60);
    secondsLeft = Math.floor(totalseconds-(minutesLeft*60));
    
    if(secondsLeft < 10)
        secondsLeft = "0" + secondsLeft;
    
    var html = minutesLeft + ":" + secondsLeft;
    
    if(typeof prefix != 'undefined')
        html = prefix + html;
   
    if(totalseconds >= 0)
    {
        document.getElementById(element).innerHTML = html;
        setTimeout("startcounter("+totalseconds+", '"+element+"', '"+prefix+"')", 1000);
    }
}

function InsufficientFundsConfirm(text)
{
    var window = confirm(text);    
    if(window)
    {
        document.location.href = "Account/Deposit.aspx";
    }
    return window;
}

function InsufficientFundsConfirmNotAuthorized(text)
{
    var window = confirm(text);    
    if(window)
    {
        document.location.href = "Authorized/Account/Deposit.aspx";
    }
    return window;
}

var postBackElement;
function InitializeRequest(sender, args) {
    postBackElement = args.get_postBackElement();
    if (postBackElement.id == buttonLeftId || postBackElement.id == buttonRightId)
    {  
          fadeOut(upGamesId);
    }
}

function fadeOut(element)
{
    var obj = document.getElementById(element);  
    
    var animation = new AjaxControlToolkit.Animation.FadeOutAnimation(obj, .2, 20, 0.0, 0.9, true);         //Instantiate
    animation.play();                                   //Once everything is setup, it can be executed.
}

function Redirect(url)
{
    window.location = url;
}

function checkMaxLen(txt,maxLen)
{
    try{
        if(txt.value.length > (maxLen-1))
        {
            var cont = txt.value;
            txt.value = cont.substring(0,(maxLen -1));
            return false;
        }
    }
    catch(e){}

}

function ConfirmGoBack(txt) 
{
    var confirmBack = confirm(txt);

    if (confirmBack)
        history.go(-1);
    else
        return false;
}

function ClientValidation(source, args)
{
    args.IsValid = document.getElementById(cbxTerms).checked;
}

function ValidateThisPage(errorelement, message)
{    
    if(!Page_IsValid)
        document.getElementById(errorelement).innerHTML = message;
        
    return;
}

function doPostBackAsync(eventName, eventArgs)
{
    var prm = Sys.WebForms.PageRequestManager.getInstance();
 
    if( !Array.contains( prm._asyncPostBackControlIDs, eventName ) )
    {
        prm._asyncPostBackControlIDs.push(eventName);
    }
 
    if( !Array.contains( prm._asyncPostBackControlClientIDs, eventName ) )
    {
        prm._asyncPostBackControlClientIDs.push(eventName);
    }
 
    __doPostBack( eventName, eventArgs );
}

function AppLoad() {
	Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
}

function EndRequest(sender, args) {

  // Check to see if there's an error on this request.
  // and don't throw the JavaScript alert.
  if (args.get_error() != undefined && true) // change to false for debug
  {
    args.set_errorHandled(true);
  }
}

function ismaxlength(obj, maxlen) { //Maxlength on Multiline textbox.
    if (obj.getAttribute && obj.value.length > maxlen)
        obj.value = obj.value.substring(0, maxlen)
}

function disableThis(obj) {
    if (obj.getAttribute)
        obj.disabled = true;
}

// ajax error handler
/*
Sys.Application.add_load(AppLoad); 
function AppLoad()
{
  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
  //Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequest);
}
 
function EndRequest(sender, args) {
  // Check to see if there's an error on this request.
  if (args.get_error() != undefined)
  {
    // If there is, show the custom error.
    //$get('Error').style.visibility = "visible";
 
    // Let the framework know that the error is handled, 
    //  so it doesn't throw the JavaScript alert.
    args.set_errorHandled(true);
  }
}
 
function BeginRequest(sender, args) {
  // Clear the error if it's visible from a previous request.
  if ($get('Error').style.visibility == "visible")
    CloseError();
}
 
function CloseError() {
  // Hide the error div.
  $get('Error').style.visibility = "hidden";
}


function Sys$WebForms$PageRequestManager$_endPostBack(error, response)
{
    this._processingRequest = false;

    this._request = null;
    this._additionalInput = null;

    var handler = this._get_eventHandlerList().getHandler("endRequest");
    var errorHandled = false;
    if (handler)
    {
        var eventArgs = new Sys.WebForms.EndRequestEventArgs(error, this._dataItems, response);
        handler(this, eventArgs);
        errorHandled = eventArgs.get_errorHandled();
    }
    this._dataItems = null;
    
    if (error && !errorHandled)
    {
        alert(error.message);
    }
}
*/


/*
    WESTLOTTO LOGIN
*/

function WLLogin() 
{	
    PageMethods.CheckIGELLogin(GetWLCallback, GetWLFailed);
}

function GetWLCallback(result)
{
    /// <summary>
    /// Is called when server sent result back
    /// </summary>
    /// <param name="result">
    /// Result of calling server method, 
    /// string - server time
	/// </param>
    if (result) 
    {
    	document.location = result;
    }
};
function GetWLFailed(error, userContext, methodName) {
    /// <summary>
    /// Callback function invoked on failure of the page method 
    /// </summary>
    /// <param name="error">error object containing error</param>
    /// <param name="userContext">userContext object</param>
    /// <param name="methodName">methodName object</param>
    if (error) 
    {
        // TODO: add error handling
       // alert(error.get_message());
    }
};

/*
CHECK FOR NEW FINALS
*/
function CheckFinals(url) 
{
    PageMethods.CheckNewFinal(url, GetCFCallback, GetWLFailed);
};

function GetCFCallback(result) 
{
    if (result)
        document.location = result;
};

function UpdateClock() 
{
    PageMethods.GetCurrentTime(GetClockCallback, GetWLFailed);
};

function GetClockCallback(result) {
    if (result)
    {
        var clock = document.getElementById("lblLeftMenuClock");
        if(clock != null)
            clock.innerHTML = result;
    }
};

function findMyText(needle) 
{
	if (document.getElementById("qualificationHighscoreDiv") == null)
		return;

    var haystackText = document.getElementById("qualificationHighscoreDiv").innerHTML;

	var match = new RegExp(">" +needle+ "<", "ig");
	var replaced = "";

	var boldText = "><span style=\"font-weight: bold;\">" + needle + "</span><";
	replaced = haystackText.replace(match, boldText);

	document.getElementById("qualificationHighscoreDiv").innerHTML = replaced;
}

function makeTextBold(sender, args) {
	try {
		findMyText(highscoreUsername);
	}
	catch (e) { }
}

function ApplyFieldValuesToCache() {
	if (!window.fieldValues)
		return;

	for (eId in fieldValues) {
		if (document.getElementById(eId) != null)
			document.getElementById(eId).innerHTML = fieldValues[eId];
	}
}
