var popAward, popPanel;
var t;
var emailRe =/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/
var loginVisible;
var code;
var instanceId = Math.ceil(Math.random() * 9999);
var delayLoginLoad = true;
 
// ------------------------
// FLASH SHELL SETUP
var site;
var flashVars = {
	memberCode				: code,
	rememberMe				: hasCookie ? 1 : 0,
	siteKey					: instanceId,
	serverZone				: "games",
	swfCore					: typeof(coreSWF) != "undefined" ? coreSWF : "final_core.swf",
	serverIP				: smartfoxServerIP,
	serverPort				: smartfoxServerPort,
	allowMultipleInstances	: allowMultipleInstances
};

var params = {
	allowScriptAccess	: "always",
	allowFullScreen		: "false",
	menu				: "false",
	scale				: "noscale",
	salign				: "t",
	wmode				: "opaque",
	bgColor				: "#000000",
	base				: "flash/"
};

var attributes = {
	id		: "site",
	name	: "site"
};

// ------------------------

function parseVersionString(str) {
    if (typeof (str) != 'string') { return false; }
    var x = str.split('.');
    // parse from string or default to 0 if can't parse
    var maj = parseInt(x[0]) || 0;
    var min = parseInt(x[1]) || 0;
    var pat = parseInt(x[2]) || 0;
    return {
        major: maj,
        minor: min,
        patch: pat
    }
}

function ShowFlash() {

    $(".oldSafari").hide();
    swfobject.embedSWF("flash/preloader.swf", "lobbyFrame", "960px", "100%", "10.0.2.45", false, flashVars, params, attributes);
}


var popovers;

// HIDE LOGIN FORM IF MEMBER CODE IN SESSION
var needsLogin = (code == "") ? true : false;

$(document).ready(function () {

    // check for older safari versions


    var d = navigator.userAgent.toLowerCase(),
        isSafari = (~d.indexOf("safari") && ! ~d.indexOf("chrome"));


    if (isSafari) { // if safari

        var userAgent = navigator.userAgent.toLowerCase();
        userAgent = userAgent.substring(userAgent.indexOf('version/'));
        userAgent = userAgent.substring(userAgent.indexOf('/') + 1, userAgent.indexOf(' '));
        version = userAgent;

        var running_version = parseVersionString(version);
        var min_version = parseVersionString('5.0.4');
        var isOk = "";

        if (running_version.major > min_version.major) {
            isOk = "true";
        }
        else {
            if (running_version.major < min_version.major) {
                isOk = "false";
            }
            else {
                if (running_version.major == min_version.major) {
                    if (running_version.minor > min_version.minor) {
                        isOk = "true";
                    }
                    else {
                        if (running_version.patch >= min_version.patch) {
                            isOk = "true";
                        }
                        else {
                            isOk = "false";
                        }
                    }
                }
            }
        }

        if (isOk == "true") {
            swfobject.embedSWF("flash/preloader.swf", "lobbyFrame", "960px", "100%", "10.0.2.45", false, flashVars, params, attributes);
        }
        else {

            $(".oldSafari").show();
            $(".noFlash").hide();
        }

    }
    else {
        swfobject.embedSWF("flash/preloader.swf", "lobbyFrame", "960px", "100%", "10.0.2.45", false, flashVars, params, attributes);
    }


    // DO THIS FIRST TO HIDE CHANGE FLICKER        
    Cufon.replace('h1, h2, h3,.fancybutton, #TB_title');

    //console.log("setting setTimeout");
    setTimeout(function () {

        //console.log("inside setTimeout");

        $("#reset").hide();

        if ($.url.param("reset") != null && $.url.param("reset") != undefined && $.url.param("reset") != "") {
            var id = $.url.param("id");
            var code = $.url.param("code");
            var href = $("#reset").attr('href') + "&id=" + id + "&code=" + code;
            $("#reset").attr('href', href);
            $("#reset").thickbox({ macFFBgHack: '/global/scripts/thickbox/macFFBgHack.png', loadingImage: '/global/scripts/thickbox/thickbox-loading.gif', iframe: true }).click();
        }

        $("#rem").click(function () {
            $(this).val($(this).is(':checked') ? 1 : 0);
        });

        //FLASH SETUP
        site = $("#site").get(0);
        //console.log("api=");
        //console.log(api);






        //LOGIN BAR
        loginVisible = $('#loginForm').height() > 0;
        $('#loginSubmit').attr('disabled', false);
        $('#loginGuestSubmit').attr('disabled', false);
        $('#loginForm .loginFields input').keypress(function (e) {
            if (e.which == 13) {
                $(this).blur();
                $('#loginForm .buttons #loginSubmit').focus().click();
            }
        });

        //DEFAULT THICKBOX SETUP
        popovers = $('a.thickbox').thickbox({
            macFFBgHack: '/global/scripts/thickbox/macFFBgHack.png',
            loadingImage: '/global/scripts/thickbox/thickbox-loading.gif',
            iframe: true
        });

        //round CORNER BUTTON
        $(document).fancyButton();
        //console.log("finished setTimeout");

    }, 3);
    //console.log("finished document ready");
});



/******************************
 * POPOVER WINDOWS
 * ****************************/
var pop = {

    page : function(u,t,h,w){  //url, title, height, width
        t = t ? t.toUpperCase() : 'GAMES.DEFENCEJOBS.GOV.AU'; 
        
        var hasQuery = false;
        if (u.indexOf('?',0) >=0)
            hasQuery = true;
            
        $("<a href='" + u + (hasQuery ? "&" : "?") + "height=" + h + "&width=" + w + "' title='" + t + "'></a>").thickbox({macFFBgHack: '/global/scripts/thickbox/macFFBgHack.png',loadingImage: '/global/scripts/thickbox/thickbox-loading.gif',iframe: true}).click();
    },

    signUp : function(){
        pop.page('/pages/signup/register.aspx', needsLogin ? 'SIGN UP' : 'EDIT YOUR DETAILS', '600', '627');
    }

}



/******************************
 * SIGN IN BAR & LOGIN
 * ****************************/

var auth = {

    toggleLoginDisplay : function() { 
    	if ($('#loginForm').height() > 0)
    	{
    		$('#loginForm').animate({opacity: 0}, 10).animate({height: 0}, 10);
    		$('#loginForm input').css('display', 'none');
    		$('#loginForm img').css('display', 'none');
    		$('#loginForm button').css('display', 'none');
    		$('#loginForm label').css('display', 'none');
    		loginVisible = false;
    	}
    	else if (!loginVisible && needsLogin)
    	{
    		$('#loginForm').css({height: 70}, 500).animate({opacity: 1}, 300);
			//$('#content').css({marginTop: "1"}, 1500);
    		$('#loginForm').css('display', 'block');
    		$('#loginForm input').css('display', 'inline');
    		$('#loginForm img').css('display', 'inline');
    		$('#loginForm button').css('display', 'inline');
    		$('#loginForm label').css('display', 'inline');
    		loginVisible = true;
    	}
    },
    
    toggleLoginDisplayIfNeeded : function() {
    	if (needsLogin && !loginVisible) auth.toggleLoginDisplay();
    },
    
    
    doLogin : function() {
    
       // console.log('loggins');
        
    	username = $('#loginEmail').val();
        password = $('#loginPassword').val();
        remember = $('#rem').val();
    
        if (!password || !username)return;
        
        $('#loginSubmit').attr('disabled', true);
    	
    	$('#site').focus();
    	
    	try {
    		site.signIn(username, password, Number(remember));	// Cast remember to a number, as Flash will marshal it into a String otherwise
    	}
    	catch (error) {
    		setTimeout(function() { auth.doLogin(username, password, remember); }, 500);
    	}
        
    },

    signInCallback :  function (status) {
		// status =
		// 	"success"
		// 	"fail"
		// 	"notActivated"
		  
		if (!loginVisible && (status == "fail" || status == "notActivated")) {
    		
            // if it wasn't a "success", then re-enable the login buttons
		
    		$('#loginSubmit').removeAttr('disabled');
			$('loginForm').style.display="block";
			needsLogin = true;
			
    		
		} else if (status == "success") {
			needsLogin = false;
			auth.toggleLoginDisplay();
            if(!delayLoginLoad && code!='') setTimeout(pages.reload, 2000);
            code='-';
		} else {
    		$('#loginSubmit').removeAttr('disabled');
			$('loginForm').style.display="block";
		}

        if(delayLoginLoad && code != ''){
            delayLoginLoad = false;
            pages.loadPage(currentUrl);
        }
        
	},

    signOutCallback  :  function () {
    	needsLogin = true;
    	auth.toggleLoginDisplay();
    	$('#loginSubmit').removeAttr('disabled');
    	$.get('/global/logout.aspx', pages.reload);
    	hasCookie=false;
    }

}

/******************************
 * HEADER (Flash area)
 * ****************************/

var header = {
    setHeight : function (h) {
        $("#lobbyWrapper").css("height", h + "px");
    }
}






/******************************
 * HTML PAGES
 * ****************************/

var pages = {

    currentUrl: '',

    reload: function() {
        pages.loadPage(currentUrl);
    },

    loadPage: function(URL) {
		//alert(URL);

        currentUrl = URL;
        
        if(delayLoginLoad && code!='') return;

        window.scroll(0, 0);
        
        $('#content').html("&nbsp;");

        /* Scroll Wheel Remove code. */
        if (window.removeEventListener)
        	window.removeEventListener('DOMMouseScroll', wheel, false);
        else
            document.onmousewheel=null;     
            
        
        if (URL) {
            
            $('#content').addClass('loading');
            
            var xhr;
            
            if(xhr !== undefined) { xhr.abort(); } 
            
            xhr = $.ajax({
            
                url: URL,
                data : "instanceId=" + instanceId,
                cache: false,
                error: function(){  
                /* window.open(URL, "bob", "height=500, width=700, scrollbars=yes");*/
                 },
                success: function(data) {
                    $("#content").html(data);
                    $('#content').removeClass('loading');
                    
                    if(URL.toLowerCase().indexOf("gameplay.aspx") != -1){
                        auth.toggleLoginDisplay();
                        $('#footer p').hide();
                                    
            	        /* Scroll Wheel Initialization code. */
                        if (window.addEventListener)
                        	window.addEventListener('DOMMouseScroll', wheel, false);
                        window.onmousewheel = document.onmousewheel = wheel;
                    
                           
                        
                    }else{
                        auth.toggleLoginDisplayIfNeeded();
                        $('#footer p').show();
                    }
                                        
                    SWFAddress.setId("site");
                    
                    $('#content').fancyButton();
                    
                    // regular thickboxes
                    $('#content a.thickbox').thickbox({
                        macFFBgHack: '/global/scripts/thickbox/macFFBgHack.png',
                        loadingImage: '/global/scripts/thickbox/thickbox-loading.gif',
                        iframe: true
                    });
                
                    $('ul.awardList li img').bt({
                        contentSelector: "$('#' + $(this).attr('rel'))",
                        cssStyles: { color: '#666' },
                        fill: '#000',
                        width: 300,
                        strokeWidth: 2,
                        strokeStyle: '#666'
                    });
                    
                    Cufon.refresh();
                    google.trackPageview(currentUrl);
                
                }
        });
            
      
        }
    }


};



var searchBox = "searchFrame";
var playerSearch = {
	doSearch : function (args) {
		scriptName = "players_searchResults.asp";
		if(args.length==0)args=' ';
		args[0] = escape(args[0]);
		
		if($('playerSearchBox').value.length<2){alert("Please enter at least 2 characters, thanks!");}else{
		
			try{
				//load content
				var callback =	{
				   success : function (o) {$(searchBox).innerHTML = o.responseText;},
				   failure : function () { readFailure(scriptName); }
				};
				$C.asyncRequest("POST", "pages/" + scriptName , callback, args );
			}catch(err){ }

		}

	}
}

		
function openWindow(url, h, w){
  windowVar = window.open(url,"mywindow","menubar=0,scrollbars=1,resizable=1,width=" + w+ ",height=" + h);
}

function getGameInfo(a, b) {
    $.ajax({
        type: "POST",
        url: "/pages/ajax/multiplayer.aspx",
        dataType: "html",
        data: "a="+a+"&b="+b,
        success: function(msg) {
            processGameInfo(msg, a, b);
        }
    });
}

function processGameInfo(html, a, b) {
    if (html.length == 1) {
        setTimeout(function() { getGameInfo(a, b); }, 1000);
        return;
    }

    $('#multiplayerRatings').html(html).fadeIn();
    
}


// News Ticker
(function($) {
    $.fn.newsTicker = $.fn.newsticker = function(options) {
        var defaults = {
            url: '/pages/ajax/ticker.aspx',
            delay: 4000,
            element: 'ul.newsTicker'
        };
        var options = jQuery.extend(defaults, options);

        initTicker = function(el) {

            el.delay = options.delay;
            el.url = options.url;

            el.items = $("li", el);
            // hide all items (except first one)
            el.items.not(":eq(0)").hide().end();
            el.currentitem = 0;
            stopTicker(el);

            if (el.items.size() > 0) // list is preloaded with items
            {
                startTicker(el);
                $(el).css('display', 'block');
            }
            else // list is not preloaded with items
            {
                loadItems(el, function(response) {
                    $(el).append(response);

                    el.items = $("li", el);
                    // hide all items (except first one)
                    el.items.not(":eq(0)").hide().end();
                    el.currentitem = 0;
                    startTicker(el);
                    $(el).css('display', 'inline');
                });
            }
        };

        loadItems = function(el, callback) {
            $.ajax({
                type: "GET",
                url: el.url,
                success: callback,
                error: function() {
                    $(el).css('display', 'none');
                }
            });
        };
        startTicker = function(el) {
            el.tickfn = setInterval(function() { doTick(el) }, el.delay)
        };
        stopTicker = function(el) {
            clearInterval(el.tickfn);
        };
        pauseTicker = function(el) {
            el.pause = true;
        };
        resumeTicker = function(el) {
            el.pause = false;
        };
        doTick = function(el) {

            if ($(options.element).length == 0)
                stopTicker(el);

            // don't run if paused
            if (el.pause) return;
            // pause until animation has finished
            el.pause = true;
            // hide current item
            $(el.items[el.currentitem]).fadeOut("slow",
			    function() {
			        $(this).hide();
			        // move to next item and show

			        el.currentitem = ++el.currentitem % (el.items.size());

			        $(el.items[el.currentitem]).fadeIn("slow",
					    function() {
					        if (el.currentitem == el.items.size() - 1) {
					            // load more items
					            loadItems(el, function(response) {

					                // remove everything but the current item
					                el.items.not(":eq(" + el.currentitem + ")").remove();

					                $(el).append(response);

					                el.items = $("li", el);
					                // hide all items (except first one)
					                el.items.not(":eq(0)").hide().end();
					                // current item
					                el.currentitem = 0;
					                el.pause = false;
					            });
					        }
					        else // dont need to load more items, can unpause right now
					        {
					            el.pause = false;
					        }
					    }
				    );
			    }
		    );
        };
        this.each(
		function() {
		    if (this.nodeName.toLowerCase() != "ul") return;
		    initTicker(this);
		}
	)
        //.addClass("newsticker")
	.hover(
		function() {
		    // pause if hovered over
		    pauseTicker(this);
		},
		function() {
		    // resume when not hovered over
		    resumeTicker(this);
		}
	);
        return this;
    };

})(jQuery);



function swapBanner(swfFile, url, h, w){
	if($("#adbanner")){
       
        var flashVars = {  
        	clickTag: escape(url)
        };
        
        var params = {
        	allowScriptAccess: "never",
        	allowFullScreen: "false",
        	menu: "false",
        	salign: "t",
        	bgColor: "#000000",
        	quality: "high",
        	wmode: "opaque"
        };
        
        var attributes = {     };
        //swfobject.switchOffAutoHideShow();
        swfobject.embedSWF("/pages/bannerAds/" + escape(swfFile), "adbanner", w, h, "9", false, flashVars, params, attributes, function(){SWFAddress.setId("flashLobby");});
        //$("#adbanner").css('display','block');

		// Reset the SWFAddress ID, because it attached to SWFObject, it decides to change its
		// id whenever a new SWFObject instance is started. 
		
		
		
	}
}
    
function purge(d) {
    var a = d ? d.attributes : null;
	var i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            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]);
		}
    }
}

function wheel(event){
	var delta = 0;
	if (!event) event = window.event;
	if (event.wheelDelta) {
		delta = event.wheelDelta/120; 
		if (window.opera) delta = -delta;
	} else if (event.detail) {
		delta = -event.detail/3;
	}
	if (delta)
		//handle(delta);
        if (event.preventDefault)
                event.preventDefault();
        event.returnValue = false;
}

