﻿Sys.Browser.WebKit = {}; //Safari 3 is considered WebKit
if (navigator.userAgent.indexOf('WebKit/') > -1) {
    Sys.Browser.agent = Sys.Browser.WebKit;
    Sys.Browser.version = parseFloat(navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
    Sys.Browser.name = 'WebKit';
}

/// FaceBook Helpers /////
function facebook_onload(already_logged_into_facebook) {
    // user state is either: has a session, or does not.
    // if the state has changed, detect that and reload.
    FB.ensureInit(function() {
        FB.Facebook.get_sessionState().waitUntilReady(function(session) {
            var is_now_logged_into_facebook = session ? true : false;

            // if the new state is the same as the old (i.e., nothing changed)
            // then do nothing
            if (is_now_logged_into_facebook == already_logged_into_facebook) {

                return;
            }
           
            // otherwise, refresh to pick up the state change
            window.location.reload();
        });
    });
}

function facebook_Login() {

   // facebook_AskPermissions("email");
    //window.location.reload();
}

function facebook_AskPermissions(permissions) {
    FB.ensureInit(function() {
        FB.Connect.showPermissionDialog(permissions);
    });

}


function somecode() {

    FB.Connect.get_status().waitUntilReady(function(status) {
        switch (status) {
            case FB.ConnectState.connected:
                // ... do stuff ...
                break;
            case FB.ConnectState.appNotAuthorized:
            case FB.ConnectState.userNotLoggedIn:
                // ... show facebook login button ...
                break;
        }
    });
}

(function() 
{
	FBConnect = {
		app_url: "",
		api_secret: "",
		api_key: "",

		init: function (params)
		{
			FBConnect.api_key = params.api_key;
			FBConnect.api_secret = params.api_secret;
			FBConnect.app_url = params.app_url;
		},
	
		login: function () 
		{ 
			FB_RequireFeatures(["Connect"], function() { 
				FB.init(FBConnect.api_key, FBConnect.app_url + "xd_receiver.htm");
				FB.Connect.requireSession(function() {
					window.location.href = FBConnect.app_url + 'login/?fbc=1';
				}); 
			});
		},
		
		logout: function () 
		{ 	
			FB_RequireFeatures(["Connect"], function() { 
				FB.init(FBConnect.api_key, FBConnect.app_url + "xd_receiver.htm"); 
				FB.Connect.logout(function() { 
					window.location.href = FBConnect.app_url + 'logout/';
				});
			});
		},
		
		render: function ()
		{
			FB_RequireFeatures(["XFBML"], function()
			{
				FB.init(FBConnect.api_key, FBConnect.app_url + "xd_receiver.htm"); 
				//FB.XFBML.Host.autoParseDomTree = false;
			});
		}
		
	}
})();
if (!window.XMLHttpRequest) {
    window.XMLHttpRequest = function() {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}
isUpdating = false;
var value = null;
function OnLookup(targetID, predictionType, matchId, isHidden) {
    //  if (isHidden)
    //  {
    //     var betPlaced = "11";//$get('ctl00_cphMain_send_btn');
    //     if (betPlaced!=null)
    //     {
    //         setTimeout('OnLookup("'+targetID+'", "'+predictionType+'", "'+matchId+'", "' + isHidden + '")',Math.random()*1000);
    //          return;
    //     }
    //  }  
    //randno = Math.random();
    if (!isUpdating) {

        isUpdating = true;
        var xr = new XMLHttpRequest();
        var res = document.getElementById(targetID);
        var resPrevClassName = res.className;
        // res.innerHTML = ""; 
        xr.open("GET", serviceUrl + "?predictionType=" + predictionType + "&matchId=" + matchId, true);
        res.className = "dynamicPopulate_Updating";
        res.childNodes[0].innerHTML = "";
        res.childNodes[1].innerHTML = "";
        res.childNodes[3].innerHTML = "";
        res.childNodes[4].innerHTML = "";
        xr.onreadystatechange = function() {
            if (xr.readyState == 4) {

                if (xr.status == 200) // request succeeded   
                {
                    var results = xr.responseText.split('$$');
                    if (results[0] == "NCP") {
                        res.childNodes[4].innerHTML = TCResource_NCP;
                        //$get('hiddenNCP').innerHTML;
                    }
                    else {

                        res.childNodes[0].innerHTML = results[0].trim();
                        res.childNodes[1].innerHTML = "%";
                        if (results[1] == "Draw")
                        {
                            res.childNodes[3].innerHTML = TCResource_DRAW;                        
                        }
                        else
                        {
                            res.childNodes[3].innerHTML = results[1];
                        }

                    }


                }
                else {
                    res.childNodes[4].innerHTML = TCResource_ERR;
                }
                res.className = resPrevClassName;
                isUpdating = false;
            }
        }
        setTimeout(function(){xr.send(null);},750);

    }
    if (value != null) {
        matchId = value;
    }
    setTimeout('OnLookup("' + targetID + '", "' + predictionType + '", "' + matchId + '","' + isHidden + '")', Math.random() * 200000);
}

var IE = document.all ? true : false;

// Temporary variables to hold mouse x-y pos.s
var tempX = 0;
var tempY = 0;
var isFullDivOpen = false;
// Main function to retrieve mouse x-y pos.s

function showGraph(HomeTeamName, AwayTeamName, pdHome, pdDraw, pdAway, event) {


    var targ;
    if (!event) var event = window.event;
    if (event.target) targ = event.target;
    else if (event.srcElement) targ = event.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    if (IE) { // grab the x-y pos.s if browser is IE

        tempX = event.clientX + (Math.max(document.body.scrollLeft, document.documentElement.scrollLeft));
        tempY = event.clientY + (Math.max(document.body.scrollTop, document.documentElement.scrollTop));
        //   alert ("tempx: "+tempX+"; tempY: "+tempY);
    } else {  // grab the x-y pos.s if browser is NS
        tempX = event.pageX
        tempY = event.pageY
    }
    //  alert("event.pageX: "+event.pageX+"; event.pageY: "+event.pageY);
    // catch possible negative values in NS4
    if (tempX < 0) { tempX = 0 }
    if (tempY < 0) { tempY = 0 }

    /*  var daddy = targ.parentNode; //the div containing the 'plus' gif that triggered the event
    var grandaddy = daddy.parentNode; //the relatively positioned div conatining the 16 square divs
    if (grandaddy &&  grandaddy.id == "KO_ContDiv" && grandaddy.offsetLeft && grandaddy.offsetTop)
    {
    tempX = tempX - grandaddy.offsetLeft;
    tempY = tempY - grandaddy.offsetTop; //shift for relative positioning
    }
    if ( daddy.className.indexOf("Right") != -1)
    tempX = tempX - 154; //open the full info div more to the left 
    */
    var vertgraph = document.getElementById("vertgraph");
    if (vertgraph) {

        vertgraph.style.display = "block";
        vertgraph.style.left = (tempX + 2) + "px"; //prevent flickering by moving 2 px away from current mouse position
        vertgraph.style.top = (tempY + 2) + "px";
        /* return true*/
    }
    var max = Math.max(pdHome, pdDraw, pdAway);
    var barsHome = document.getElementById("barsHome");
    barsHome.style.height = (max == 0 ? 0 : ((pdHome * 100 / max) + 0)) + "px";
    barsHome.innerHTML = barsHome.title = pdHome + "%";
    
    var labelHome = document.getElementById("labelHome");
    labelHome.innerHTML = HomeTeamName;

    var barsDraw = document.getElementById("barsDraw");
    barsDraw.style.height = (max == 0 ? 0 : ((pdDraw * 100 / max) + 0)) + "px";
    barsDraw.innerHTML = barsDraw.title = pdDraw + "%";


    var barsAway = document.getElementById("barsAway");
    barsAway.style.height = (max == 0 ? 0 : ((pdAway * 100 / max) + 0)) + "px";
    barsAway.innerHTML = barsAway.title = pdAway + "%";
    var labelAway = document.getElementById("labelAway");
    labelAway.innerHTML = AwayTeamName;
}

/*function displayFullInfoDiv(event) {
 
}*/
function hideGraph(event) {
    /*   var targ;
    if (!event) var event = window.event;
    if (event.target) targ = event.target;
    else if (event.srcElement) targ = event.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
    targ = targ.parentNode; 
    var daddy = targ.parentNode;*/
    var vertgraph = document.getElementById("vertgraph");
    if (vertgraph) {
        //give the user a chance to move the mouse over the full info div without it closing
        setTimeout("fullDivHideAfterTimeOut ('" + vertgraph.id + "')", 200);
    }
    return true;
}
function fullDivHideAfterTimeOut(fullDivId) {
    if (!isFullDivOpen) {
        document.getElementById(fullDivId).style.display = 'none';
    }
}
function graph_mouseover(obj) {
    obj.style.display = 'block';
    isFullDivOpen = true;
}

function graph_mouseout(obj) {
    obj.style.display = 'none';
    isFullDivOpen = false;
}


/*	Simple Javascript RSS Reader Version 1.0
	Copyright (c) 2006 CS Truter
	Written by Christoff Truter
	email: Christoff@cstruter.com - (Please let me know if you intend to use the script) */

/* Replace all occurances of a string
  (Parameters) totalValue:'complete string' 
		oldValue:'value to be replaced' newValue:'value used for replace' */

function Replace(totalValue,oldValue,newValue)
{
	while(totalValue.indexOf(oldValue) > -1)
		totalValue=totalValue.replace(oldValue,newValue);
			return totalValue;
}

/* Get XML Node
   (Parameters) TagName:'XML Element' node:'Element row number' */

function getNode(TagName, node)
{
	var currentNode = (node == null) ? xmlDoc.getElementsByTagName(TagName) : 
					items[node].getElementsByTagName(TagName);
	if(currentNode.length > 0)
		return currentNode[0].firstChild.nodeValue;
}

/* Load XML Object
   (Parameters) rssFeed:'RSS File' Body:'Layer for RSS Body' Title:'Layer for RSS Title' */

function ReadRSS(rssFeed, Body, Title) 
{
	rssTitle = document.getElementById(Title);	
	rssBody = document.getElementById(Body);

	try
	{
		if (document.all)
		{
			var errorHappendHere = "Check Browser and security settings";
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		}
		else
		{
			var errorHappendHere = "Apparently one cant read remote xml via firefox, please copy the file to your server";
			xmlDoc = document.implementation.createDocument("","",null);
		}
	
		xmlDoc.async=false;
		xmlDoc.load(rssFeed);
	
		items=xmlDoc.getElementsByTagName('item');
		SetRSSTemplates();
	}
	
	catch(e)
	{
		rssTitle.innerHTML = 'Error occured';
		rssBody.innerHTML = 'Thrown Error:'+e.message+"<br/>Note: "+errorHappendHere;
	}
}

/* Set HTML Template
	Did it this way to make the look and feel of the feed easy customizable, dont like mixing
	layout with code. */

function SetRSSTemplates()
{
	if (rssBody)
	{
		var buffer = "";
		for(var i=0; i< items.length; i++) 
		{
			var output = (document.all) ? Replace(rssBody.innerHTML,"(::Link::)",getNode('link',i)) 
									   : Replace(rssBody.innerHTML,"%28::Link::%29",getNode('link',i));
			output = Replace(output,"(::Title::)",getNode('title',i));
			output = Replace(output,"(::Pubdate::)",getNode('pubDate',i));
			output = Replace(output,"(::Description::)",getNode('description',i));
			buffer+=output;
		}
		rssBody.innerHTML = buffer;
	}

	if (rssTitle)
	{
		var output = Replace(rssTitle.innerHTML,"(::Title::)",getNode('title'));
		output = (document.all) ? Replace(output,"(::Link::)",getNode('link'))
							   : Replace(output,"%28::Link::%29",getNode('link'));		
		output = Replace(output,"(::Description::)",getNode('description'));
		rssTitle.innerHTML = output;
	}
}

function LoadRSS()
{ ReadRSS(rssFeedLink, 'rssBodyTemplate', 'rssTitleTemplate'); }
          
/*******************************************************************************************
 * Object: Hashtable
 * Description: Implementation of hashtable
 * Author: Uzi Refaeli
 *******************************************************************************************/

//======================================= Properties ========================================
Hashtable.prototype.hash	 	= null;
Hashtable.prototype.keys		= null;
Hashtable.prototype.location	= null;

/**
 * Hashtable - Constructor
 * Create a new Hashtable object.
 */
function Hashtable(){
	this.hash = new Array();
	this.keys = new Array();

	this.location = 0;
}

/**
 * put
 * Add new key
 * param: key - String, key name
 * param: value - Object, the object to insert
 */
Hashtable.prototype.put = function (key, value){
	if (value == null)
		return;

	if (this.hash[key] == null)
		this.keys[this.keys.length] = key;

	this.hash[key] = value;
}

/**
 * get
 * Return an element
 * param: key - String, key name
 * Return: object - The requested object
 */
Hashtable.prototype.get = function (key){
		return this.hash[key];
}

/**
 * remove
 * Remove an element
 * param: key - String, key name
 */
Hashtable.prototype.remove = function (key){
	for (var i = 0; i < this.keys.length; i++){
		//did we found our key?
		if (key == this.keys[i]){
			//remove it from the hash
			this.hash[this.keys[i]] = null;
			//and throw away the key...
			this.keys.splice(i ,1);
			return;
		}
	}
}

/**
 * size
 * Return: Number of elements in the hashtable
 */
Hashtable.prototype.size = function (){
    return this.keys.length;
}

/**
 * populateItems
 * Deprecated
 */
Hashtable.prototype.populateItems = function (){}

/**
 * next
 * Return: true if theres more items
 */
Hashtable.prototype.next = function (){
	if (++this.location < this.keys.length)
		return true;
	else
		return false;
}

/**
 * moveFirst
 * Move to the first item.
 */
Hashtable.prototype.moveFirst = function (){
	try {
		this.location = -1;
	} catch(e) {/*//do nothing here :-)*/}
}

/**
 * moveLast
 * Move to the last item.
 */
Hashtable.prototype.moveLast = function (){
	try {
		this.location = this.keys.length - 1;
	} catch(e) {/*//do nothing here :-)*/}
}

/**
 * getKey
 * Return: The value of item in the hash
 */
Hashtable.prototype.getKey = function (){
	try {
		return this.keys[this.location];
	} catch(e) {
		return null;
	}
}

/**
 * getValue
 * Return: The value of item in the hash
 */
Hashtable.prototype.getValue = function (){
	try {
		return this.hash[this.keys[this.location]];
	} catch(e) {
		return null;
	}
}

/**
 * getKey
 * Return: The first key contains the given value, or null if not found
 */
Hashtable.prototype.getKeyOfValue = function (value){
	for (var i = 0; i < this.keys.length; i++)
		if (this.hash[this.keys[i]] == value)
			return this.keys[i]
	return null;
}


/**
 * toString
 * Returns a string representation of this Hashtable object in the form of a set of entries,
 * enclosed in braces and separated by the ASCII characters ", " (comma and space).
 * Each entry is rendered as the key, an equals sign =, and the associated element,
 * where the toString method is used to convert the key and element to strings.
 * Return: a string representation of this hashtable.
 */
Hashtable.prototype.toString = function (){

	try {
		var s = new Array(this.keys.length);
		s[s.length] = "{";

		for (var i = 0; i < this.keys.length; i++){
			s[s.length] = this.keys[i];
			s[s.length] = "=";
			var v = this.hash[this.keys[i]];
			if (v)
				s[s.length] = v.toString();
			else
				s[s.length] = "null";

			if (i != this.keys.length-1)
				s[s.length] = ", ";
		}
	} catch(e) {
		//do nothing here :-)
	}finally{
		s[s.length] = "}";
	}

	return s.join("");
}

/**
 * add
 * Concatanates hashtable to another hashtable.
 */
Hashtable.prototype.add = function(ht){
	try {
		ht.moveFirst();
		while(ht.next()){
			var key = ht.getKey();
			//put the new value in both cases (exists or not).
			this.hash[key] = ht.getValue();
			//but if it is a new key also increase the key set
			if (this.get(key) != null){
				this.keys[this.keys.length] = key;
			}
		}
	} catch(e) {
		//do nothing here :-)
	} finally {
		return this;
	}
};
/*
count down clock
*/

function countdown_clock(dateObj, format) {
    html_code = '<div id="countdown"></div>';
    document.write(html_code);
    countdown(dateObj, format);
}

function countdown(dateObj, format, countdownDiv, digSizeH, Vposition) {
  
    Today = new Date();
    Todays_Year = Today.getFullYear() - 2000;
    Todays_Month = Today.getMonth();

    //Convert both today's date and the target date into miliseconds.
    Todays_Date = Today; //(new Date(Todays_Year, Todays_Month, Today.getDate(),      Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();
    Target_Date = dateObj;

    //Find their difference, and convert that into seconds.                  
    Time_Left = Math.round((Target_Date - Todays_Date) / 1000);

    if (Time_Left < 0)
        Time_Left = 0;

  // countdownDiv = document.getElementById('countdown');
    switch (format) {
        case 0:
            //The simplest way to display the time left.
            countdownDiv.innerHTML = Time_Left + ' seconds';
            break;
        case 1:
            //More datailed.
            days = Math.floor(Time_Left / (60 * 60 * 24));
            Time_Left %= (60 * 60 * 24);
            hours = Math.floor(Time_Left / (60 * 60));
            if (hours < 10) hours = '0' + hours;
            Time_Left %= (60 * 60);
            minutes = Math.floor(Time_Left / 60);
            if (minutes < 10) minutes = '0' + minutes;
            Time_Left %= 60;
            seconds = Time_Left;
            if (seconds < 10) seconds = '0' + seconds;

            kids = $(countdownDiv).children();

            kids[0].style.backgroundPosition = (parseInt(days / 10) * -digSizeH).toString() + Vposition;
            kids[1].style.backgroundPosition = (parseInt(days % 10) * -digSizeH).toString() + Vposition;

            kids[2].style.backgroundPosition = (parseInt(hours / 10) * -digSizeH).toString() + Vposition;

            kids[3].style.backgroundPosition = (parseInt(hours % 10) * -digSizeH).toString() + Vposition;
            kids[4].style.backgroundPosition = (parseInt(minutes / 10) * -digSizeH).toString() + Vposition;
            kids[5].style.backgroundPosition = (parseInt(minutes % 10) * -digSizeH).toString() + Vposition;
            kids[6].style.backgroundPosition = (parseInt(seconds / 10) * -digSizeH).toString() + Vposition;
            kids[7].style.backgroundPosition = (parseInt(seconds % 10) * -digSizeH).toString() + Vposition;

            break;
        default:
            countdownDiv.innerHTML = Time_Left + ' seconds';
    }

    //Recursive call, keeps the clock ticking.
    var func = function() { countdown(dateObj, format, countdownDiv, digSizeH, Vposition); }
    setTimeout(func, 1000);
    //setTimeout('countdown(' + dateObj + ',' + format + ',' + countdownDiv + ',' + clockDescDiv + ');', 1000);
}

/*Cookie General*/

function setCookie(c_name, value, expiredays) {
    var exdate = new Date(); exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}


/*Bet Page */



function runEffect() {$("#matchInfo").effect('highlight', { color: '#555555' }, 500);}

function SetOverUnderSlider(minValue, maxValue, currentValue, status) {

    $(function() {
        $("#slider-range-min").slider("destroy");
        if (currentValue == undefined)
            currentValue = 0
        if (minValue == undefined)
            minValue = 0
        if (maxValue == undefined)
            maxValue = 0
        $("#slider-range-min").slider({
            range: "min",
            value: Math.floor(currentValue),
            min: Math.floor(minValue),
            max: Math.floor(maxValue),
            step: 5,
            slide: function(event, ui) {
                $("#amount").val(ui.value); OnOverUnderChange();
            }
        });
        $("#amount").val($("#slider-range-min").slider("value"));
    });
    if (status != undefined)
        $("#slider-range-min").slider(status);

    $("#amount").val($("#slider-range-min").slider("value"));

}

function SetMatchOddSlider(minValue, maxValue, currentValue, status) {

    $(function() {
        $("#slider-range-min-2").slider("destroy");
        if (currentValue == undefined)
            currentValue = 0
        if (minValue == undefined)
            minValue = 0
        if (maxValue == undefined)
            maxValue = 0
        $("#slider-range-min-2").slider({
            range: "min",
            value: currentValue,
            min: minValue,
            max: maxValue,
            step: 1,
            slide: function(event, ui) {
                $("#amount-2").val(ui.value);
                OnMatchOddsChange();
            }
        });
        $("#amount-2").val($("#slider-range-min-2").slider("value"));
    });

    if (status != undefined)
        $("#slider-range-min-2").slider(status);


    $("#amount-2").val($("#slider-range-min-2").slider("value"));


}





      
function addPane(headerText,content)
{       
    var matchesInPane = document.getElementById("gameList");   
  
    var header = document.createElement("a");
    header.className += "fg-button ui-state-highlight ui-corner-top title";
    SetText(header,headerText,false);
  matchesInPane.appendChild(header);
  matchesInPane.appendChild(content);
   
}
    
function createPanes()
{
 
    while(structure.next())
    {
        var matches = structure.getValue();
       
          var matchInfoContainer = document.createElement("ul");
        matchInfoContainer.setAttribute("id","gamesUL"+structure.location.toString());
        for (i=0;i< matches.length;i++)
        {
            var matchInfo = document.createElement("li");
            matchInfo.setAttribute("id","li"+matches[i].MatchId);
            var matchInfoAncor = document.createElement("a");
            matchInfoAncor.setAttribute("position",structure.location.toString() + "," + i.toString());
            matchInfoAncor.style.cursor = 'pointer';
            matchInfoAncor.className="fg-button fg-button-icon-left ui-state-default";
            var names = matches[i].HomeTeam.Name + vsString +matches[i].AwayTeam.Name;
            
            if (names.length>24)
            {
                names =  matches[i].HomeTeam.Sname +  vsString +matches[i].AwayTeam.Sname
            }
            iconSpan =  document.createElement('span');
            if (!matches[i].BetsAllowed)
            {
            iconSpan.className = "ui-icon ui-icon-clock";
            }
           if (bets.get(matches[i].MatchId) != undefined)
                iconSpan.className = "ui-icon ui-icon-check";
              
            SetText(matchInfoAncor,names,false);
            
             matchInfoAncor.insertBefore(iconSpan, matchInfoAncor.firstChild);
       $addHandler(matchInfoAncor,'click',matchInfoAncorOnclick);
      
          matchInfo.appendChild(matchInfoAncor); 
            matchInfoContainer.appendChild(matchInfo);
        }
         addPane(structure.getKey(),matchInfoContainer)
     }
     
     if (megaMatchName.length > 0)
     {
        megaMatchPane = document.createElement("ul");
        megaMatchPane_Game = document.createElement("li");
        megaMatchPane_Game_matchInfoAncor = document.createElement("a");
        megaMatchPane_Game_matchInfoAncor.style.cursor = 'pointer';
        megaMatchPane_Game_matchInfoAncor.className="fg-button fg-button-icon-left ui-state-default";
        SetText(megaMatchPane_Game_matchInfoAncor,megaMatchName,false);
        megaMatchPane_Game_matchInfoAncor.setAttribute("href",megaMatchLocation);
        megaMatchPane_Game.appendChild(megaMatchPane_Game_matchInfoAncor);
        megaMatchPane.appendChild(megaMatchPane_Game);
        MMiconSpan = document.createElement('span');
        if (megaMatecBetPlaced == true)
            MMiconSpan.className = "ui-icon ui-icon-check";
        megaMatchPane_Game_matchInfoAncor.insertBefore(MMiconSpan, megaMatchPane_Game_matchInfoAncor.firstChild);
        addPane(MegaMatchResource, megaMatchPane);
    }
    if (predictorChalangeName.length > 0)
     {
        predictorChalangePane = document.createElement("ul");
        predictorChalangePane_Game = document.createElement("li");
        predictorChalangePane_Game_matchInfoAncor = document.createElement("a");
        predictorChalangePane_Game_matchInfoAncor.style.cursor = 'pointer';
        predictorChalangePane_Game_matchInfoAncor.className="fg-button fg-button-icon-left ui-state-default";
        SetText(predictorChalangePane_Game_matchInfoAncor,predictorChalangeName,false);
        predictorChalangePane_Game_matchInfoAncor.setAttribute("href",predictorChalangeLocation);
        predictorChalangePane_Game.appendChild(predictorChalangePane_Game_matchInfoAncor);
        predictorChalangePane.appendChild(predictorChalangePane_Game);
        PCiconSpan = document.createElement('span');
        if (predictorChalangeBetPlaced == true)
            PCiconSpan.className = "ui-icon ui-icon-check";
        predictorChalangePane_Game_matchInfoAncor.insertBefore(PCiconSpan, predictorChalangePane_Game_matchInfoAncor.firstChild);
        addPane(predictorChalangeResource, predictorChalangePane);
    }
}

function matchInfoAncorOnclick()
{
$(document.getElementById("li"+hidMatchId.value.toString())).removeClass('selected');
        hidMatchId = document.getElementById('hidMatchId');
       // document.getElementById();
        this.parentNode.className += " selected";
		runEffect();
		setMatchPanel(this.attributes.getNamedItem("position").value);
		PotentialWin();
		
}
function setMatchPanel(position) {

    // Global
    CurrentPositin = new String();
    CurrentPositin = CurrentPositin.concat(position);

    awayTeamIcon_img.src = homeTeamIcon_img.src = cleanImage;
    
    structure.location = CurrentPositin.split(',')[0];

    var matches = new Array();
    matches = matches.concat(structure.getValue());
    selectedMatch = matches[CurrentPositin.split(',')[1]];


/********************************************************/
/*                   vars here                          */
/********************************************************/

    SetText(leagueName_lbl,selectedMatch.LeagueName,false);

    MatchParsedDate = new Date(selectedMatch.ScriptingPlayDateString); //.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
    MatchDueDate = new Date(selectedMatch.ScriptingDueDateString);
    // upper match date 
    //SetText(matchDate_lbl,MatchParsedDate.format("dd/MM/yyyy") + " " +  MatchParsedDate.format("HH:mm"),false);
    SetText(matchDate_lbl,selectedMatch.PlayDateString,false);

    $('.homeTeam').css("background-color", selectedMatch.HomeTeam.PrimaryColorHome);
    $('.awayTeam').css("background-color", selectedMatch.AwayTeam.PrimaryColorHome);
    $('#homeTeamLink span').css("color", selectedMatch.HomeTeam.SecondaryColorHome);
    $('#awayTeamLink span').css("color", selectedMatch.AwayTeam.SecondaryColorHome);
  
    // reset buttons state
    scores = document.getElementsByName('order_by2');
    for (i=0;i<scores.length;i++) {scores[i].checked = false; scores[i].disabled = false; }
    scores[0].odd =selectedMatch.Odd.HomeOdd;
    scores[1].odd =selectedMatch.Odd.DrawOdd;
    scores[2].odd =selectedMatch.Odd.AwayOdd;
   
    // reset buttons state
    rank = document.getElementsByName('order_by');
    for (i=0;i<rank.length;i++) { rank[i].checked = false; rank[i].disabled = false; }
    
    rank[0].odd =selectedMatch.MatchOverUnverOdds!=null? selectedMatch.MatchOverUnverOdds.OverOdd : 0;
    rank[1].odd =selectedMatch.MatchOverUnverOdds!=null? selectedMatch.MatchOverUnverOdds.UnderOdd : 0;
    
    // enable sliders
    SetMatchOddSlider(1,Math.max(Math.min(selectedMatch.MaxBet,walletJSON != null ?walletJSON.Balance[selectedMatch.League.LeagueId]: selectedMatch.MaxBet),1),Math.max(Math.min(Math.round(selectedMatch.MaxBet/2),walletJSON != null ?Math.round( walletJSON.Balance[selectedMatch.League.LeagueId]/2): Math.round(selectedMatch.MaxBet/2)),1),'enable');
    SetOverUnderSlider(0,selectedMatch.MaxBet/4,selectedMatch.MaxBet/8,'enable');
     
     
     //MatchOverUnverOdds":{"OddId":1983,"OverOdd":2.2,"OverAffiliateId":3,"UnderOdd":3.3,"UnderAffiliateId":4,"OverOddTraditional":"6/5","UnderOddTraditional":"23/10"
     if( oddsDisplay == 'Decimal')
     {
         SetText(lblHomeBestOdd, selectedMatch.Odd.HomeOdd.toFixed(2).replace('.00', ''), false);
         SetText(lblDrawBestOdd, selectedMatch.Odd.DrawOdd.toFixed(2).replace('.00', ''), false);
         SetText(lblAwayBestOdd, selectedMatch.Odd.AwayOdd.toFixed(2).replace('.00', ''), false);
        if (selectedMatch.MatchOverUnverOdds !=null)
        {
            SetText(OverOddLabel, selectedMatch.MatchOverUnverOdds.OverOdd.toFixed(2).replace('.00', ''), false);
            SetText(UnderOddLabel, selectedMatch.MatchOverUnverOdds.UnderOdd.toFixed(2).replace('.00', ''), false);
        }
        else
        {
            SetText(OverOddLabel,'N/A',false);
            SetText(UnderOddLabel,'N/A',false);
        }
        
    }
    else
    {
        SetText(lblHomeBestOdd,selectedMatch.Odd.homeTraditionalOdd,false);
        SetText(lblDrawBestOdd,selectedMatch.Odd.drawTraditionalOdd,false);
        SetText(lblAwayBestOdd,selectedMatch.Odd.awayTraditionalOdd,false);
        if (selectedMatch.MatchOverUnverOdds !=null)
        {
            SetText(OverOddLabel,selectedMatch.MatchOverUnverOdds.OverOddTraditional,false);
            SetText(UnderOddLabel,selectedMatch.MatchOverUnverOdds.UnderOddTraditional,false);
        }
        else
        {
            SetText(OverOddLabel,'N/A',false);
            SetText(UnderOddLabel,'N/A',false);
        }
    }
    
    SetText(document.getElementById('homeSpan2'),selectedMatch.HomeTeam.Sname,false);
    SetText(document.getElementById('awaySpan2'),selectedMatch.AwayTeam.Sname,false);
    
    SetText(lblHomeTeamName,selectedMatch.HomeTeam.Name.length > 13 ? selectedMatch.HomeTeam.Sname :selectedMatch.HomeTeam.Name ,false);
    SetText(lblAwayTeamName,selectedMatch.AwayTeam.Name.length > 13 ? selectedMatch.AwayTeam.Sname :selectedMatch.AwayTeam.Name,false);

    homeTeamIcon_img.src = baseTeamImageURL + selectedMatch.HomeTeam.Icon;
    awayTeamIcon_img.src = baseTeamImageURL + selectedMatch.AwayTeam.Icon;
   homeTeamLinkElement.href = root + "team/" + selectedMatch.HomeTeam.TeamId + "/" + selectedMatch.HomeTeam.Name + ".aspx";
   awayTeamLinkElement.href = root + "team/" + selectedMatch.AwayTeam.TeamId + "/" + selectedMatch.AwayTeam.Name + ".aspx";

    // set icon    
    homeBestOdd_img.src = baseAffiliateImageURL + selectedMatch.Odd.HomeBetIcon;
    drawBestOdd_img.src = baseAffiliateImageURL + selectedMatch.Odd.DrawBetIcon;
    awayBestOdd_img.src = baseAffiliateImageURL + selectedMatch.Odd.AwayBetIcon;

    //set link
    $("#LinkHomeBestOdd").attr("href",selectedMatch.Odd.HomeLink);
    $("#LinkDrawBestOdd").attr("href", selectedMatch.Odd.DrawLink);
    $("#LinkAwayBestOdd").attr("href", selectedMatch.Odd.AwayLink);
    

    //set matchid
    hidMatchId = document.getElementById('hidMatchId');
    hidMatchId.value = selectedMatch.MatchId;
   
   SetMatchDescriptionPanel(selectedMatch.Description)
   SetText(document.getElementById('leagueWalletSpan'),walletJSON !=null ? walletJSON.Balance[selectedMatch.League.LeagueId]: 0,false);
        
    //page title
    document.title = selectedMatch.HomeTeam.Name + vsString + selectedMatch.AwayTeam.Name + " @ " + MatchParsedDate.format("dd/MM/yyyy") + " " +  MatchParsedDate.format("HH:mm");

   $('#resetOUspan').css("visibility","visible");

        // set user bet
        userBet = bets.get(selectedMatch.MatchId)
        if (userBet != undefined)
        {
          $('#resetOUspan').css("visibility","hidden");
          MP_BottomDiv.style.display='none';
           scores[userBet.ScoreBetId].checked = true;
          if (userBet.RankBetId == "3")
            rank[0].checked = true;
          else if (userBet.RankBetId == "1")
            rank[1].checked = true;
      
          SetNotUserPlacedOn(userBet)
          
           for (i=0;i<scores.length;i++) {scores[i].disabled = true;}
           for (i=0;i<rank.length;i++) {rank[i].disabled = true;}
           
               // dsiable sliders
    SetMatchOddSlider(1,selectedMatch.MaxBet,userBet.ScoreBetAmount,'disable');
    SetOverUnderSlider(0,selectedMatch.MaxBet/4,userBet.RankBetAmount,'disable');
    ChangeSubmitUIState(true, true);
    ChangeEditButtonState(false, false);
    PotentialWin();
}

        else
        {
            
            if (!selectedMatch.BetsAllowed)//upcoming
            {
                SetMatchDescriptionPanel(MatchUpComing);
                SetMatchNotificationPanel('',false);
                SetText(MatchOddsStatusSpanElement, "",false);
                SetText(OverUnderStatusSpanElement, "",false);
                ChangeSubmitUIState(true, true);
                ChangeEditButtonState(true, true);
                
            }
            else if (IsServerTimeGreater(MatchDueDate))   //closed match 
            {
                SetMatchDescriptionPanel(MatchClosed);            
                 SetMatchNotificationPanel('',false);
                 SetText(MatchOddsStatusSpanElement, "",false);
                 SetText(OverUnderStatusSpanElement, "",false);
                 ChangeSubmitUIState(true, true);
                 ChangeEditButtonState(true, true);
            }
            else
            {
                  if (isRegistered == true)
                  {
                  
                  ////// by Miky  - 13/1/2010 - changed to this to clear errors see SS on that date
                    SetText(MatchOddsStatusSpanElement, '',false);
                     SetText(OverUnderStatusSpanElement, '',false);
                     SetMatchNotificationPanel('',false);



                     ChangeSubmitUIState(false, false);
                     ChangeEditButtonState(true, true);
                 }
                 else
                 {
                  SetMatchNotificationPanel('',false);
                  SetMatchDescriptionPanel(PlsSignIn);
                  $(matchDescriptionDiv).bind('click', function() { LoginBox('open'); });
                  $(matchDescriptionDiv).css('cursor', 'pointer');
                  $(matchDescriptionDiv).css('text-decoration', 'underline');
         
                 
                 
                 SetText(MatchOddsStatusSpanElement, '',false);
                     SetText(OverUnderStatusSpanElement, '',false);
                     ChangeSubmitUIState(true, true);
                     ChangeEditButtonState(true, true);
                 
                 }
            }
        }
  
   
    

    div = document.getElementById('TeamsStatsDiv');
    div.setAttribute("HomeTeam",selectedMatch.HomeTeam.Name);
    div.setAttribute("AwayTeam",selectedMatch.AwayTeam.Name);
    

$('#HomeTeamStatsDiv').html(div.attributes.getNamedItem("HomeTeam").value);
$('#AwayTeamStatsDiv').html(div.attributes.getNamedItem("AwayTeam").value);

    $('#HomeTeamStatsDiv').css("background-color",selectedMatch.HomeTeam.PrimaryColorHome);
    $('#AwayTeamStatsDiv').css("background-color", selectedMatch.AwayTeam.PrimaryColorHome);
    $('#HomeTeamStatsDiv').css("color", selectedMatch.HomeTeam.SecondaryColorHome);
    $('#AwayTeamStatsDiv').css("color", selectedMatch.AwayTeam.SecondaryColorHome);

    discussionId = selectedMatch.MatchId;
    WebService.GetMatchGeneralStats(selectedMatch.MatchId, OnGetMatchGeneralStatsComplete, OnGetMatchGeneralStatsFailed);
    WebService.GetDiscussion(discussionId, 1, OnGetDiscussionComplete);
   /// Finish
   /* NewDiscussionCount();*/
    
    
      
}

function NewDiscussionCount()
{

WebService.GetDiscussionLatestComments(discussionId,1,lastMessageId, OnNewDiscussionCountComplete);
 setTimeout("NewDiscussionCount()",10000);


}
function OnNewDiscussionCountComplete(result)
{
lastComments = eval(result);
var countNew = 0;

if (lastComments!=null && lastComments.length > 0 )
{
for (var i=0; i<lastComments.length; i++)
    if (lastComments[i].messageId > lastMessageId) countNew++;

if (countNew >0)
{
 $("#newComments").text(countNew + 'new comments');
 $("#newComments").css("visibility","visible");
 $("#newComments").click(function()
                        {
                            for (var j=0; j< lastComments.length; j++)
                            if (lastComments[j].messageId > lastMessageId)
                            {
                                tr = document.createElement('tr');
                            
                              if (j%2 == 0)
                                tr.className = "row";
                              else
                                tr.className = "row-alternate";




                                td = document.createElement('td');
                                ahref2 = document.createElement('a');
                                img = document.createElement('img');
                                img.className = "img30x30";
                                img.src = imgBaseURL + lastComments[j].PlayerPosted.picture;
                                ahref2.href = '/PlayerPage.aspx?pid=' + lastComments[j].PlayerPosted.Budget.UserId;
                                ahref2.appendChild(img);
                                td.appendChild(ahref2);
                                tr.appendChild(td);
                                td = document.createElement('td');

                                ahref = document.createElement('a');
                                ahref.className = "userName";
                                ahref.href = '/PlayerPage.aspx?pid=' + lastComments[j].PlayerPosted.Budget.UserId;
                                ahref.innerHTML = comments[j].PlayerPosted.username;
                                td.appendChild(ahref);
                                
                                span = document.createElement('span');
                                span.className = "commentDate";
                                span.innerHTML = eval(lastComments[j].date.replace(/\/Date\((\d+)\)\//gi, "new Date($1)")).format("dd/MM/yy HH:mm");
                                td.appendChild(span);

                                
                                td.appendChild(document.createElement('br'));
                                span = document.createElement('span');
                                span.innerHTML =  lastComments[j].message;
                                td.appendChild(span);

                                tr.appendChild(td);    
                                        
                    //            td = document.createElement('td');
                    //            td.innerHTML =
                    //            tr.appendChild(td);  
                          $('#MatchDiscussionAreaTable table tbody tr:first').after(tr);
                                
                                lastMessageId = lastComments[j].messageId;
                                }
                
                                $("#newComments").css("visibility","hidden");
                   });
         }
 }
}
function SetNotUserPlacedOn(userBet)
{
    SetMatchNotificationPanel(' ',false);
    SetText(MatchOddsStatusSpanElement, '' ,false);
    SetText(OverUnderStatusSpanElement,'',false);
 
    teamName = ""; 
    switch (parseInt(userBet.ScoreBetId))
    {
    case 0 : teamName = selectedMatch.HomeTeam.Sname; break;
    case 1: teamName = DrawResource; break;
    case 2 : teamName = selectedMatch.AwayTeam.Sname; break;
    }
    SetText(MatchOddsStatusSpanElement, PlayerPlaced.replace('@@@',userBet.ScoreBetAmount).replace('$$$',teamName)  ,false);

    switch(parseInt(userBet.RankBetId))
    {
        case 3: teamName = OverResource; 
    SetText(OverUnderStatusSpanElement, PlayerPlaced.replace('@@@',userBet.RankBetAmount).replace('$$$',teamName) ,false);
    
    break;
case 1: teamName = UnderResource;
    SetText(OverUnderStatusSpanElement, PlayerPlaced.replace('@@@',userBet.RankBetAmount).replace('$$$',teamName) ,false);
 break;
  
    }

}

lastMessageId = 0;

function OnGetDiscussionComplete(result) {
    
	var openComments = 7;
$('#MatchDiscussionAreaTable').empty();
    comments = eval(result);    
   
    table = document.createElement('Table');
    table.className = "commentsGrid";
    tbody = document.createElement('tbody');
    
    tr = document.createElement('tr');
     td = document.createElement('td');
      $(td).attr("colspan","2");
       $(td).attr("id","newComments");
       $(td).css("visibility","hidden");
       tr.appendChild(td);
       tbody.appendChild(tr);
    if( comments!=null)
    {
        for (i=0; i< comments.length; i++)
        {
            tr = document.createElement('tr');
        
          if (i%2 == 0)
            tr.className = "row";
          else
            tr.className = "row-alternate";

			if (i>openComments)
			{
			  tr.className += " CommentDisplayNone";
			}


            td = document.createElement('td');
            ahref2 = document.createElement('a');
            img = document.createElement('img');
            img.className = "img30x30";
            img.src = imgBaseURL + comments[i].PlayerPosted.picture;
            ahref2.href = '/PlayerPage.aspx?pid=' + comments[i].PlayerPosted.Budget.UserId; //TODO change base player page URL method
            ahref2.appendChild(img);
            td.appendChild(ahref2);
            tr.appendChild(td);
            td = document.createElement('td');

            ahref = document.createElement('a');
            ahref.className = "userName";
            ahref.href = '/PlayerPage.aspx?pid=' + comments[i].PlayerPosted.Budget.UserId; //TODO change base player page URL method
            ahref.innerHTML = comments[i].PlayerPosted.username + '&nbsp';
            td.appendChild(ahref);

            span = document.createElement('span');
            span.className = "ui-widget ui-corner-all " + comments[i].PlayerPosted.SnapShot.LoyaltyStatus + " mvp";
            span.innerHTML = comments[i].PlayerPosted.SnapShot.LoyaltyStatus;
            td.appendChild(span);
            
            span = document.createElement('span');
            span.className = "commentDate";
            span.innerHTML = eval(comments[i].date.replace(/\/Date\((\d+)\)\//gi, "new Date($1)")).format("dd/MM/yy HH:mm");
            td.appendChild(span);

            
            td.appendChild(document.createElement('br'));
            span = document.createElement('span');
            span.innerHTML =  comments[i].message;
            td.appendChild(span);

            tr.appendChild(td);    
                    
//            td = document.createElement('td');
//            td.innerHTML =
//            tr.appendChild(td);  
            tbody.appendChild(tr);
        } 
		if(comments.length >openComments )
		{
		  tr = document.createElement('tr');
     td = document.createElement('td');
      $(td).attr("colspan","2");
       $(td).attr("id","seeMoreComments");
	$(td).attr("isclosed",1);   
	$(td).html("Read more");
	$(td).bind('click',function()
		{
if($("#seeMoreComments").attr("isclosed") == 1)
{
$("#seeMoreComments").html("hide old comments");
$(".CommentDisplayNone").show();
$("#seeMoreComments").attr("isclosed",0);
}
else
{
$("#seeMoreComments").html("Read more");
$(".CommentDisplayNone").hide();
$("#seeMoreComments").attr("isclosed",1);
}
		});
       tr.appendChild(td);
       tbody.appendChild(tr);
		}
        table.appendChild(tbody);
          
        $('#MatchDiscussionAreaTable').append(table);
lastMessageId = comments[0].messageId;
    }
    $('#DiscussionPanel').removeClass('loader');
   $('#MatchDiscussionButton').css("visibility", "visible");
   
   
   
}

function createCommentRow(i, comment)
{
}



function ChangeEditButtonState(disableState, hiddenState) {
    /////// for now
    disableState = hiddenState = true;
    $(edit_btnElement).attr("disabled", disableState);

    if (hiddenState) {
        $(edit_btnElement).hide();

    }
    else {
        $(edit_btnElement).show();

    }
 
}

function ChangeSubmitUIState(disableState,hiddenState)
{
     $(send_btnElement).attr("disabled",disableState);
     $(send_btnNextElement).attr("disabled", disableState);
     
     if (hiddenState)
     {
        $(send_btnElement).hide();
        $(send_btnNextElement).hide();
        
     }
     else
     {
        $(send_btnElement).show();
        $(send_btnNextElement).show();
        
    }
     
 }                
 function SetMatchDescriptionPanel(Text)
 {
    if ( Text != null && Text !='')
    {
        SetText(matchDescriptionDiv,Text,true)
        matchDescriptionWrapperDiv.style.visibility = 'visible';
        matchDescriptionWrapperDiv.style.display = 'block';
       

    }
    else
    {
        SetText(matchDescriptionDiv,'',true)
        matchDescriptionWrapperDiv.style.visibility = 'hidden';
        matchDescriptionWrapperDiv.style.display = 'none';
    }
    $(matchDescriptionDiv).unbind('click');
    $(matchDescriptionDiv).css('cursor', 'text');
    $(matchDescriptionDiv).css('text-decoration', 'none');
  }  
  
  
  function OnOverUnderChange()
  {
    if (document.getElementById("amount").value > selectedMatch.MaxBet/4)
    {

        document.getElementById("amount").value = selectedMatch.MaxBet/4;
    }
    SetText(OverUnderStatusSpanElement, NotSaved, false);
     $('#slider-range-min').slider('option', 'value', document.getElementById("amount").value); 
    
    GlobalToDoOnChange();
  }
  
  function OnMatchOddsChange()
  { 
  walletForBet = Math.max(Math.min(selectedMatch.MaxBet,walletJSON != null ?walletJSON.Balance[selectedMatch.League.LeagueId]: selectedMatch.MaxBet),1);
    if (document.getElementById("amount-2").value > walletForBet )
    {

        document.getElementById("amount-2").value = walletForBet;
    }
    SetText(MatchOddsStatusSpanElement, NotSaved, false);
     $('#slider-range-min-2').slider('option', 'value', document.getElementById("amount-2").value); 
    GlobalToDoOnChange();
  }
  
  function GlobalToDoOnChange()
  {
    PotentialWin();
    SetMatchNotificationPanel('',false);
  }
  function SetMatchNotificationPanel(Text,isError)
    { 
     $(notificationsWrapperDivElement).toggleClass("ui-state-error", isError);
     $(notificationsWrapperDivElement).toggleClass("ui-state-focus", !isError);
     $(notificationsWrapperDivElement).find("span").toggleClass("ui-icon-info", isError);
     $(notificationsWrapperDivElement).find("span").toggleClass("ui-icon-circle-check", !isError);
     

    if ( Text != null && Text !='')
    {
        SetText(notificationsSpanElement,Text,true)
        notificationsWrapperDivElement.style.visibility = 'visible';
        notificationsWrapperDivElement.style.display = 'block';
    }
    else
    {
        SetText(notificationsSpanElement,'',true)
        notificationsWrapperDivElement.style.visibility = 'hidden';
        notificationsWrapperDivElement.style.display = 'none';
    }
  }  
  
  
  function resetOU()
  {
    rank = document.getElementsByName('order_by');
    for (i=0;i<rank.length;i++) { rank[i].checked = false; rank[i].disabled = false; }
    SetOverUnderSlider(0,selectedMatch.MaxBet,0,'enable');
    //TODO RESET THE OverUnder Potential Profit
    
  }
  
function IsServerTimeGreater(DateObj)
{
nowTime= new Date();

pageIsRunningMiliseconds = nowTime.getTime() - PageLoadTime.getTime();
if(ServerTime.getTime() + pageIsRunningMiliseconds > DateObj.getTime() )
    return true
else
    return false

}

function EditMatch() {


   $('#resetOUspan').css("visibility","visible");

        // set user bet
        userBet = bets.get(selectedMatch.MatchId)
      
      
           for (i=0;i<scores.length;i++) {scores[i].disabled = false;}
           for (i=0;i<rank.length;i++) {rank[i].disabled = false;}
           
               // dsiable sliders
    SetMatchOddSlider(1,selectedMatch.MaxBet,userBet.ScoreBetAmount,'enable');
    SetOverUnderSlider(0,selectedMatch.MaxBet/4,userBet.RankBetAmount,'enable');
    ChangeSubmitUIState(false, false);
    ChangeEditButtonState(true, true);
    PotentialWin();
}
function setMatchAJAX(goNext)
{
    GoNext = goNext;
    score = -1;
    rank = -1;
    // reset buttons state
    scores = document.getElementsByName('order_by2');
    for (i=0;i<scores.length;i++) 
    {
        if (scores[i].checked)
        score = scores[i].value;

    }
    // reset buttons state
    ranks = document.getElementsByName('order_by');
    for (i=0;i<ranks.length;i++) 
    {
        if(ranks[i].checked)
            rank = ranks[i].value;

    }
       hidMatchId = document.getElementById('hidMatchId');
       amount2 = document.getElementById("amount-2");
       amount = document.getElementById("amount");
     if (score == -1)
     {
     SetMatchNotificationPanel(Error2140,true);
        return;
     }
     else if (amount2.value == "0" || (rank!=-1 && amount.value=="0"))
     {
        SetMatchNotificationPanel(Error2101,true);
        return;
     }  
     
     SetMatchNotificationPanel("",false);
   
    PageMethods.SetMatchPrediction(hidMatchId.value,score,rank,amount2.value,amount.value,OnSetMatchPredictionComplete,OnSetMatchPredictionError);


}
function OnSetMatchPredictionError(result)
{
 SetMatchNotificationPanel("Error: " + result._message,true);

}
function OnSetMatchPredictionComplete(result)
{
    if (result == "NLI")
         SetMatchNotificationPanel(PlsSignIn,true);
    else if (result.indexOf("OK")!= -1)
    {
          $('#resetOUspan').css("visibility","hidden");
    
        // balance for current league
        document.getElementById(result.split('$')[1]).innerHTML= result.split('$')[2];
        
        // all leagues wallet  -- taking all spans finding the attrib leagueWallet -- getelements by name didn't work with ie
        leagueWallet = document.getElementsByTagName('span');
        
        sumWalletCount =0; //counter
        
        for (j=0;j<leagueWallet.length; j++)
        {
            if (leagueWallet[j].attributes.getNamedItem('leagueWallet')!=null)
                 sumWalletCount += parseInt(leagueWallet[j].innerHTML);
        }
        // set sum to screen
        document.getElementById('sumWallet').innerHTML = sumWalletCount;
       
        
        hidMatchId = document.getElementById('hidMatchId');
        amount2 = document.getElementById('amount-2');
                 // reset buttons state
        scores = document.getElementsByName('order_by2');
        for (i=0;i<scores.length;i++) 
        {
            if (scores[i].checked)
            score = scores[i].value;

        }
        // reset buttons state
        amount = document.getElementById('amount');
        
        ranks = document.getElementsByName('order_by');
        for (i=0;i<ranks.length;i++) 
        {
            if(ranks[i].checked)
                rank = ranks[i].value;

        }
              SetMatchNotificationPanel('',false);
             
        
        
        userBet = new Object();
        userBet.ScoreBetAmount =amount2.value;
        userBet.RankBetAmount = amount.value;
        userBet.MatchId =  hidMatchId.value;
        userBet.RankBetId = rank;
        userBet.ScoreBetId = score;
        bets.put(hidMatchId.value,userBet);  
       
        iconSpan =  document.createElement('span');    
        iconSpan.className = "ui-icon ui-icon-check";

        document.getElementById("li"+  hidMatchId.value).firstChild.appendChild(iconSpan);  
        $('#imgMId'+ hidMatchId.value.toString()).removeClass("ui-icon-circle-arrow-e imgArrow");
        $('#imgMId'+ hidMatchId.value.toString()).addClass("ui-icon-check imgCM");





        ChangeSubmitUIState(true, true);
        ChangeEditButtonState(false, false);
        walletJSON.Balance[result.split('$')[1].replace('league_','')] = result.split('$')[2];
        
        
        //complete
        SetNotUserPlacedOn(userBet)
         
          SetMatchOddSlider(undefined,undefined,undefined,'disabled');
          SetOverUnderSlider(undefined,undefined,undefined,'disabled');
           
          for (i=0;i<scores.length;i++){scores[i].disabled = true;}
          for (i=0;i<ranks.length;i++){ranks[i].disabled = true;}
          
          
          
          if (GoNext)
            {
                structure.location = CurrentPositin.split(',')[0];
                var matches = new Array();
                matches = matches.concat(structure.getValue());
                
                inLeague = parseInt(CurrentPositin.split(',')[0]);
                inGame = parseInt(CurrentPositin.split(',')[1]);
                gamesInLeague = matches.length;
              
                if (inGame+1< gamesInLeague)
                {
                    inGame = inGame +1;
                }   
                else if( inLeague + 1<  structure.size())
                {
                    inLeague = inLeague +1;
                    inGame = 0;
                }
                else
               {
                 inLeague =0;
                 inGame =0;
               }
               
                    structure.location = inLeague;
                    matches = new Array();
                    matches = matches.concat(structure.getValue());
                    
                    $(document.getElementById("li"+hidMatchId.value.toString())).removeClass('selected');
                    setMatchPanel(inLeague +  ',' + inGame.toString());
                    $(document.getElementById("li"+matches[inGame].MatchId.toString())).addClass('selected');
                    runEffect();
                    PotentialWin(); 
                
                    
            }
           



    

    }
    else if(result.indexOf("Error")!= -1)// Error
    {
    
        SetMatchNotificationPanel(eval(result.replace(',','')),true);        
       
    }
    else // generalError
    {
            SetMatchNotificationPanel(ErrorGeneral,true);        
      
    }
  
}


var MiniTable_divWrapperClassName = "";
var MiniTable_divWrapperClassNameH3 = "Stats-Table-Caption";
var MiniTable_tableWrapperDiv = "Stats-Table-Wrapper";
var MiniTable_tableClassName = "Stats-Table-Table";
var MiniTable_trClassName = "Stats-Table-Row";
var MiniTable_trClassNameMarked = "Stats-Table-Row-Marked";
var MiniTable_headerClassName = "Stats-Table-Header";

function OnGetMatchGeneralStatsComplete(result)
{
    lastMatchesJsonArray = eval(result);
    ShowTeamStatsContent('Home');
}
function ShowTeamStatsContent(type)
{
$('#StatsContentDiv').empty();
    formTable = document.createElement('div');
    leagueTable = document.createElement('div');
        
    if (typeof(lastMatchesJsonArray) != 'undefined')
    {
        if (type == 'Home')
        {
            $('#StatsContentDiv').css("background-color",selectedMatch.HomeTeam.PrimaryColorHome);

            $('#HomeTeamStatsDiv').css("background-position","0px 0px");
            $('#AwayTeamStatsDiv').css("background-position","-148px 0px");
            $('#HomeTeamStatsDiv').css("font-weight","bold");
            $('#AwayTeamStatsDiv').css("font-weight","normal");
            
            
            homeTeamGames = lastMatchesJsonArray[0];
            CreateFormTable(homeTeamGames,formTable,selectedMatch.HomeTeam);
        CreateLeagueTable(lastMatchesJsonArray[2],leagueTable,selectedMatch.HomeTeam);
        }
        else
        {
            $('#StatsContentDiv').css("background-color",selectedMatch.AwayTeam.PrimaryColorHome);

            $('#HomeTeamStatsDiv').css("background-position","-296px 0px");
            $('#AwayTeamStatsDiv').css("background-position","0px 0px");
            $('#AwayTeamStatsDiv').css("font-weight","bold");
            $('#HomeTeamStatsDiv').css("font-weight","normal");
            
        awayTeamGames = lastMatchesJsonArray[1];
        CreateFormTable(awayTeamGames,formTable,selectedMatch.AwayTeam);
        CreateLeagueTable(lastMatchesJsonArray[3],leagueTable,selectedMatch.AwayTeam);
        }
        formTable.className = MiniTable_divWrapperClassName;
       leagueTable.className = MiniTable_divWrapperClassName;
     
        $('#StatsContentDiv').append(formTable);
        $('#StatsContentDiv').append(leagueTable);
   }
}
function CreateLeagueTable(lastMatchesJsonArray,targetObject,Team)
{
    if (lastMatchesJsonArray !=null)
    {
        table = document.createElement('Table');
        table.className = MiniTable_tableClassName;
            $(table).css("color", Team.TextColorHome);
        tbody = document.createElement('tbody');
        tr = document.createElement('tr');
        tr.className = MiniTable_headerClassName;
        td = document.createElement('td');
        td.innerHTML = PosResource;        
        tr.appendChild(td);    
            
        td = document.createElement('td');
        td.innerHTML = TeamResource;
        tr.appendChild(td);    
        

        
        td = document.createElement('td');
        td.innerHTML = PldResource;
        $(td).css("text-align","right");
        
        tr.appendChild(td);  
         
        td = document.createElement('td');
        td.innerHTML = WResource;
        $(td).css("text-align","right");

        tr.appendChild(td);  
        
        td = document.createElement('td');
        td.innerHTML = DResource;
        $(td).css("text-align","right");

        tr.appendChild(td);  
        
        td = document.createElement('td');
        td.innerHTML = LResource;
        $(td).css("text-align","right");

        tr.appendChild(td);      
        
        td = document.createElement('td');
        td.innerHTML = GDResource;
        $(td).css("text-align","right");
        tr.appendChild(td); 
              
        td = document.createElement('td');
        td.innerHTML = PtsResource;
        $(td).css("text-align","right");
        tr.appendChild(td); 
        
        tbody.appendChild(tr);        
        for (j=0;j<lastMatchesJsonArray.length ;j++)
        {
            tr = document.createElement('tr');
            tr.className =  MiniTable_trClassName;
            $(tr).css("border-bottom-color", Team.TextColorHome);
     
            
            //Position
            td = document.createElement('td');
            td.innerHTML = lastMatchesJsonArray[j].Position;
            tr.appendChild(td);
            
             //teamname
            td = document.createElement('td');
            if (lastMatchesJsonArray[j].Name == Team.Name)
            {
                td.innerHTML =lastMatchesJsonArray[j].Sname.bold();
                  tr.className += " " +        MiniTable_trClassNameMarked;
            }
            else
            {
                 td.innerHTML = lastMatchesJsonArray[j].Sname;          
            }
                
            
            tr.appendChild(td);
            
       
      
        
            //played
            td = document.createElement('td');
            td.innerHTML = lastMatchesJsonArray[j].Played;
        $(td).css("width","10%");
        $(td).css("text-align","right");
            
            tr.appendChild(td);
            
             td = document.createElement('td');
            td.innerHTML = lastMatchesJsonArray[j].Wins;
        $(td).css("width","10%");
        $(td).css("text-align","right");
         
            tr.appendChild(td);
            
             td = document.createElement('td');
            td.innerHTML = lastMatchesJsonArray[j].Draws;
        $(td).css("width","10%");
        $(td).css("text-align","right");

            tr.appendChild(td);
            
             td = document.createElement('td');
            td.innerHTML = lastMatchesJsonArray[j].Losses;
        $(td).css("width","10%");
        $(td).css("text-align","right");

            tr.appendChild(td);
            
            td = document.createElement('td');
            td.innerHTML = lastMatchesJsonArray[j].GoalsDiffrence;
        $(td).css("width","10%");

        $(td).css("text-align","right");
            tr.appendChild(td);
           
            td = document.createElement('td');
            td.innerHTML = lastMatchesJsonArray[j].Points;
        $(td).css("width","10%");
        $(td).css("text-align","right");
        

            tr.appendChild(td);
            tbody.appendChild(tr);
            
        }
       $(tr).css("border-bottom-style","none"); /// remove from last row border
               table.appendChild(tbody);
        wrapDiv = document.createElement('div');
        wrapDiv.className = MiniTable_tableWrapperDiv;
        wrapDiv.appendChild(table);
        h3 = document.createElement('h3');
        h3.className = MiniTable_divWrapperClassNameH3;
        $(h3).css("color", Team.TextColorHome);
        txtNode = document.createTextNode(CurrentStandingsResource); // +"'s position snapshot");
        h3.appendChild(txtNode);
        targetObject.appendChild(h3);
        targetObject.appendChild(wrapDiv);
        
    }
}
function CreateFormTable(lastMatchesJsonArray,targetObject,Team)
{
SetText(targetObject,"",true);

if (lastMatchesJsonArray !=null)
{

table = document.createElement('Table');
table.className = MiniTable_tableClassName;
            $(table).css("color", Team.TextColorHome);

tbody = document.createElement('tbody');
teamForm = "";
            
            tr = document.createElement('tr');
             tr.className = MiniTable_headerClassName;
             td = document.createElement('td');
             text = document.createTextNode(MatchResource);
                td.appendChild(text);
                tr.appendChild(td);
                  td = document.createElement('td');
                  text = document.createTextNode(ScoreResource);
                td.appendChild(text);
                
                tr.appendChild(td);
                  td = document.createElement('td');
                  text = document.createTextNode(DateResource);
                $(td).css("text-align",'center');
                
                td.appendChild(text);
                tr.appendChild(td);
                tbody.appendChild(tr);
            for (j=0;j<lastMatchesJsonArray.length ;j++)
            {
                tr = document.createElement('tr');
                tr.className = MiniTable_trClassName;
            $(tr).css("border-bottom-color", Team.TextColorHome);
                
                //Home team, away team and form
                td = document.createElement('td');
          
                
                if (lastMatchesJsonArray[j].HomeTeam.Name == Team.Name)
                {                 
                    text = lastMatchesJsonArray[j].HomeTeam.Sname /*.bold()*/ +   vsString  + lastMatchesJsonArray[j].AwayTeam.Sname;
                    if (lastMatchesJsonArray[j].HomeScore > lastMatchesJsonArray[j].AwayScore)
                    {
                        teamForm = teamForm +  WResource;                       
                    }
                    else if (lastMatchesJsonArray[j].HomeScore == lastMatchesJsonArray[j].AwayScore)
                    {
                        teamForm =  teamForm + DResource;
                    }
                    else
                    {
                        teamForm = teamForm + LResource ;
                    }
                }
                else
                {
                    text = lastMatchesJsonArray[j].HomeTeam.Sname +  vsString  + lastMatchesJsonArray[j].AwayTeam.Sname/*.bold()*/;
                    if (lastMatchesJsonArray[j].HomeScore < lastMatchesJsonArray[j].AwayScore)
                    {
                       teamForm = teamForm +  WResource;
                    }
                    else if (lastMatchesJsonArray[j].HomeScore == lastMatchesJsonArray[j].AwayScore)
                    {
                        teamForm =  teamForm + DResource;
                    }
                    else
                    {
                         teamForm = teamForm + LResource ;
                    }
                }
               
                
                //td.style.width='50%';
                //td.style.padding='2px 6px'
                td.innerHTML = text;
                tr.appendChild(td);
                //away team
//                td = document.createElement('td');
//                text = document.createTextNode();
//                td.appendChild(text);
//                tr.appendChild(td);
               // home score - away score
                 td = document.createElement('td');
                text = document.createTextNode(lastMatchesJsonArray[j].HomeScore + " - " + lastMatchesJsonArray[j].AwayScore);
               // td.style.width='15%';
                td.appendChild(text);
                tr.appendChild(td);
                // play date
                 td = document.createElement('td');
                text = document.createTextNode(eval(lastMatchesJsonArray[j].PlayDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)")).format("dd/MM/yy"));
                td.appendChild(text);
                $(td).css("text-align",'right');
                
                tr.appendChild(td);
                tbody.appendChild(tr);
             
            }
            
//             var form = teamForm.split(' ');
//                for (var c=0; c<form.length; c++)
//                {
//                var newDiv = document.createElement('div');
//                newDiv.className = "floatLeft margin02";
//                $(newDiv).css("background-color","Gray");
//                $(newDiv).css("width","12px");
//                
//                SetText(newDiv,form[c],false);
//                shortFormElement.appendChild(newDiv);
//                }
//            txtNode = document.createTextNode(teamName +"'s recent form: " + teamForm);
            txtNode = document.createTextNode(recentForm.replace('@@@',teamForm));
     
            table.appendChild(tbody);
            tableDiv = document.createElement('div');
            tableDiv.className = MiniTable_tableWrapperDiv
            h3 = document.createElement('h3');
            $(h3).css("color", Team.TextColorHome);            
            h3.className = MiniTable_divWrapperClassNameH3;
            h3.appendChild(txtNode);
            
            tableDiv.appendChild(table);
            targetObject.appendChild(h3);
            targetObject.appendChild(tableDiv);
            
           
}
else
targetObject.innerHTML = "no matches";
}

function OnGetMatchGeneralStatsFailed(error, userContext, methodName)
{

SetText(document.getElementById('divStats'),error.get_message(),false);

}
var spanPotentialMOWin= document.getElementById('spanPotentialMOWin');
var spanPotentialOUWin = document.getElementById('spanPotentialOUWin');
var spanPotentialTotalWin = document.getElementById('spanPotentialTotalWin');
function PotentialWin()
{ 


    
    score = -1;
    rank = -1;
    // reset buttons state
    scores = document.getElementsByName('order_by2');
    for (i=0;i<scores.length;i++) 
    {
        if (scores[i].checked)
        score = scores[i].odd;

    }
    
     scoreAmount = parseInt(document.getElementById('amount-2').value);
     scorePotential = (scoreAmount * score) - scoreAmount;
     
     if (score == -1)
        scorePotential = 0;
     SetText(spanPotentialMOWin,scorePotential.toFixed(2).replace('.00',''),false);
    
    // reset buttons state
    ranks = document.getElementsByName('order_by');
    for (i=0;i<ranks.length;i++) 
    {
        if(ranks[i].checked)
            rank = ranks[i].odd;

    }
    rankAmount = document.getElementById('amount').value
    rankPotential = (rankAmount *rank)- rankAmount
    if (rank == -1)
        rankPotential = 0;
    SetText(spanPotentialOUWin,rankPotential.toFixed(2).replace('.00',''),false)
    SetText(spanPotentialTotalWin,(scorePotential + rankPotential).toFixed(2).replace('.00',''),false);
}
function SetDiscussionMessage(typeId) {
    $('#DiscussionPanel').addClass('loader');
    $('#MatchDiscussionButton').attr('disabled', true);
    $('#MatchDiscussionButton').css("visibility", "hidden");
if ($('#MatchDiscussionText').val() != shoutBoxDefault)     
    WebService.SetDiscussionMessage(discussionId, typeId, $('#MatchDiscussionText').val(), OnSetDiscussionMessageComplete(typeId), OnSetDiscussionMessageError);

}
function OnSetDiscussionMessageComplete(typeId) {
    $("#MatchDiscussionText").val(shoutBoxDefault);
    $("#MatchDiscussionText").css("color", "gray");
    $('#MatchDiscussionButton').attr('disabled', false);
    $('#MatchDiscussionSubmitted').css("visibility","visible");
    $('#MatchDiscussionCountTitle').css("visibility", "hidden");
    ShowNotification('Your Comment has been published','',5);
    var func  = function(){WebService.GetDiscussion(discussionId, typeId, OnGetDiscussionComplete)};
    setTimeout(func,2000); //patch
    
  
    

}
 function OnSetDiscussionMessageError(result) {
     alert(result._message);
 $('#MatchDiscussionButton').attr('disabled', false);
 }
          function doBetPageOnLoad() 
      {
                 
           

            for (j=0;j<matchesJsonArray.length ;j++)
            {
                var pane = structure.get(matchesJsonArray[j].League.Name + " - " + matchesJsonArray[j].SubSeason.Name)
                if (pane!=null) //exists
                {
                    pane.push(matchesJsonArray[j]);
                }
                else
                {
                    var a = new Array();
                    a.push(matchesJsonArray[j]);
                    structure.put(matchesJsonArray[j].League.Name + " - " + matchesJsonArray[j].SubSeason.Name,a);
                }
            }
            structure.moveFirst(); 


    
         if (betsJSON!= null)
             for (j=0;j<betsJSON.length ;j++)
             {
             bets.put(betsJSON[j].MatchId,betsJSON[j]);
             }
            
          createPanes();
          structure.moveFirst();    
          var minPosMatch = 0;
          var matchPosInArr = 0;
          ///requestMatchId = <asp:Literal id="requestMatchIdLiteral" Text="0" runat="server"/>;
          
          if (requestMatchId != 0)
          {
          
           while(structure.next())
            {
            
              for (var i=0; i<structure.getValue().length; i++)
              {
                if(structure.getValue()[i].MatchId == requestMatchId)
                {
                    minPosMatch = structure.location;
                    matchPosInArr = i;
                    document.getElementById("li"+ requestMatchId.toString()).className += " selected"; 
                }
              }
       }
          }
          else
          {
          // to get the first match at this league as minimum date
          structure.next();
          
            var minDate = eval(structure.getValue()[0].PlayDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
            var currentDate = new Date();
            while(structure.next())
            {
                currentDate = eval(structure.getValue()[0].PlayDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
         
                if (currentDate < minDate)
                {
                    minPosMatch =  structure.location;
                }
                    
            }
            document.getElementById("gamesUL" + minPosMatch.toString()).firstChild.className += " selected";

        }

               if (createAccordion == true) {
                    $('#gameList ul').hide();

                    $('#gameList .title').click(function() {
                       
                        $('#gameList ul').hide();
                        $(this).next().slideDown(300); 



                    });
               
                    $("#gamesUL" + minPosMatch.toString()).show();
                }
          
          
            setMatchPanel(minPosMatch +  ',' +matchPosInArr);
            $("#matchInfo").css("display","block");
            $("#MatchDiscussionAreaDiv").css("display","block");
            $("#loadingDiv").remove();
                    
      }
/*Bet Page End*/



/*general functions*/



      function doCount(obj, max, doCountObj) {
          $(doCountObj).css("visibility", "visible");
          $(doCountObj).text(obj.value.length + "/" + max + " chr");
    // document.getElementById(out).innerHTML =  obj.value.length + "/" +max + " characters";
}
function doCountValidate(e, obj, max) {
    if (obj.value.length < max || e.keyCode==46 || e.keyCode ==8)
        return true;
    else
        return false;
}

function SetText(obj, text, isHTML) {
    if (isHTML)
    { obj.innerHTML = text; return; }

    if (document.all) {
        obj.innerText = text;
    }
    else {
        obj.textContent = text;
    }
}





/* matches div info */

// Temporary variables to hold mouse x-y pos.s
var tempX = 0;
var tempY = 0;
var isFullDivOpen = false;
// Main function to retrieve mouse x-y pos.s

function displayFullInfoDiv(event) {
    var targ;
    if (!event) var event = window.event;
    if (event.target) targ = event.target;
    else if (event.srcElement) targ = event.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    if (IE) { // grab the x-y pos.s if browser is IE

        tempX = event.clientX + (Math.max(document.body.scrollLeft, document.documentElement.scrollLeft));
        tempY = event.clientY + (Math.max(document.body.scrollTop, document.documentElement.scrollTop));
    } else {  // grab the x-y pos.s if browser is NS
        tempX = event.pageX
        tempY = event.pageY
    }
    // catch possible negative values in NS4
    if (tempX < 0) { tempX = 0 }
    if (tempY < 0) { tempY = 0 }

    var daddy = targ.parentNode.parentNode; //the div containing the 'plus' gif that triggered the event
    var grandaddy = daddy.parentNode; //the relatively positioned div conatining the 16 square divs
    if (grandaddy && grandaddy.id == "KO_ContDiv" && grandaddy.offsetLeft && grandaddy.offsetTop) {
        tempX = tempX - grandaddy.offsetLeft;
        tempY = tempY - grandaddy.offsetTop; //shift for relative positioning
    }
    if (daddy.className.indexOf("Right") != -1)
        tempX = tempX - 154; //open the full info div more to the left

    if (daddy.className.indexOf("MoreRight") != -1)
        tempX = tempX - 26; //open the full info div more to the left 

    var fullDiv = document.getElementById(daddy.id + "_fullInfo");
    if (fullDiv) {

        fullDiv.style.display = "block";
        fullDiv.style.left = (tempX + 2) + "px"; //prevent flickering by moving 2 px away from current mouse position
        fullDiv.style.top = (tempY + 2) + "px";
        return true
    }
}
function hideFullInfoDiv(event) {
    var targ;
    if (!event) var event = window.event;
    if (event.target) targ = event.target;
    else if (event.srcElement) targ = event.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
    var daddy = targ.parentNode.parentNode;
    var fullDiv = document.getElementById(daddy.id + "_fullInfo");
    if (fullDiv) {
        //give the user a chance to move the mouse over the full info div without it closing
        setTimeout("fullDivHideAfterTimeOut ('" + daddy.id + "_fullInfo')", 200);
    }
    return true;
}
function fullDivHideAfterTimeOut(fullDivId) {
    if (!isFullDivOpen) {
        document.getElementById(fullDivId).style.display = 'none';
    }
}
function fullDiv_mouseover(obj) {
    obj.style.display = 'block';
    isFullDivOpen = true;
}

function fullDiv_mouseout(obj) {
    obj.style.display = 'none';
    isFullDivOpen = false;
}




/* end matches div info*/


/*document ready general*/ 
$(document).ready(function() {

try
{
   if (err!=null)
   {
    if (err.innerHTML!= "")
       {
            document.getElementById("InnerAlertPanel").innerHTML = err.innerHTML;
            document.getElementById("AlertPanel").style.display = 'block';
       }
   }
 }
 catch (Errr) { }

 //Click on the Football Divs
 $(".toDoDiv").click(function() {
     window.location = $(this).find("a").attr("href"); return false;
 });

 $(function() {


     // BUTTONS
     $('.fg-button').hover(
    		function() { $(this).removeClass('ui-state-default').addClass('ui-state-focus'); },
    		function() { $(this).removeClass('ui-state-focus').addClass('ui-state-default'); }
    	);

     // MENUS    	
     $('#flat1').menu({
         content: $('#flat1').next().html(),
         showSpeed: 400
     });
     $('#flat2').menu({
         content: $('#flat2').next().html(),
         showSpeed: 400
     });

     $('#flat4').menu({
         content: $('#flat4').next().html(),
         showSpeed: 400
     });
     $('#flat5').menu({
         content: $('#flat5').next().html(),
         showSpeed: 400
     });
     $('#flat6').menu({
         content: $('#flat6').next().html(),
         showSpeed: 400,
         width:228
     });


 });
});

/********RSS***********/

function ReadRSS(rssFeed) {
    try {
        $.get(rssFeed, function(d) {

            //find each 'item' in the file and parse it
            $(d).find('item').each(function() {

                //name the current found item this for this particular loop run
                var $item = $(this);
                // grab the post title
                var title = $item.find('title').text();
                // grab the post's URL
                var link = $item.find('link').text();
                // next, the description
                var description = $item.find('description').text();
                //don't forget the pubdate
                var pubDate = $item.find('pubDate').text();

                // now create a var 'html' to store the markup we're using to output the feed to the browser window
                var html = "<div class=\"entry\"><h2 class=\"postTitle\">" + title + "<\/h2>";
                html += "<em class=\"date\">" + pubDate + "</em>";
                html += "<p class=\"description\">" + description + "</p>";
                html += "<a href=\"" + link + "\" target=\"_blank\">Read More >><\/a><\/div>";

                //put that feed content on the screen!
                $('#feedContent').append($(html));
            });
        }, "xml");
    }

    catch (e) {
        alert(e);
    }
}



          
          /**********RSS END***********/
          
          
          
          
          
          
          
          /*!
* jquery.fixedHeaderTable. The jQuery fixedHeaderTable plugin
*
* Copyright (c) 2009 Mark Malek
* http://fixedheadertable.mmalek.com
*
* Licensed under MIT
* http://www.opensource.org/licenses/mit-license.php
*
* Launch  : October 2009
* Version : 0.1.1 beta
* Released: TBA
*/
(function($)
{

	$.fn.fixedHeaderTable = function(options) {
		var defaults = {
			loader: false,
			footer: false,
			colBorder: true,
			cloneHeaderToFooter: false,
			autoResize: false
		};
		
		var options = $.extend(defaults, options); // get the defaults or any user set options
		
		return this.each(function() {
			var obj = $(this); // the jQuery object the user calls fixedHeaderTable on
			
			buildTable(obj,options);
			
			if(options.autoResize == true) {
				$(window).resize( function() {
					if (table.resizeTable) {
						// if a timeOut is active cancel it because the browser is still being resized
						clearTimeout(table.resizeTable);
					}
				
					// setTimeout is used for resizing because some browsers will call resize() while the browser is still being resized which causes performance issues.
					// if the browser hasn't been resized for 200ms then resize the table
					table.resizeTable = setTimeout(function() {
					
						buildTable(obj,options);
						
					}, 200);
				});
			}
		});
	};
	
	var table = function() {
		this.resizeTable;
	}
	
	function buildTable(obj,options) {
		var objClass = obj.attr('class');
			
		var hasTable = obj.find("table").size() > 0; // returns true if there is a table
		var hasTHead = obj.find("thead").size() > 0; // returns true if there is a thead
		var hasTBody = obj.find("tbody").size() > 0; // returns true if there is a tbody
			
		if(hasTable && hasTHead && hasTBody) {
			var parentDivWidth = obj.width()-5; // get the width of the parent DIV
			var parentDivHeight = obj.height()-5; // get the height of the parent DIV
			var tableBodyWidth = parentDivWidth; // width of the div surrounding the tbody (overflow:auto)
			
			obj.css('position', 'relative'); // set the jQuery object the user passsed in to position:relative (just incase they did not set it in their stylesheet)
			
			if (obj.find('.fht_parent').size() == 0) {
				// if returns false then the plugin has not been used on this jQuery object
				obj.find('table').wrap('<div class="fht_parent"><div class="fht_table_body"></div></div>');
			}
			obj.find('.fht_parent').css('width', parentDivWidth+'px'); // set the width of the parent div
			obj.find('.fht_table_body').css('width', parentDivWidth+'px'); // set the width of the main table body (where the data will be displayed)
			
			var tableWidthNoScroll = parentDivWidth; // this is the width of the table with no scrollbar (used for the fixed header)
			
			obj.find('.fht_parent .fht_table_body table').addClass('fht_orig_table'); // add a class to identify the orignal table later on
			
			if(options.loader) {
				obj.find('.fht_parent').prepend('<div class="fht_loader"></div>');
				obj.find('.fht_loader').css({'width':parentDivWidth+'px', 'height': parentDivHeight+'px'});
			}
			
			obj.attr('id', obj.attr('class'));
			var tableWidthScroll = parentDivWidth;
			
			/*if (obj.find('.fht_parent .fht_orig_table').height() < obj.find('.fht_parent .fht_table_body').height()) {
				obj.find('.fht_parent table').css('width', tableWidthNoScroll+'px');
			}*/
			
			if ($.browser.msie == true) {
				// if IE subtract an additional 2px from the table to compensate for the scrollbar.  Allows the outside border of the table to be flush with the outside border of the fixed header
				// if IE subtract 15px to compensate for the scrollbar
				tableWidthScroll = tableWidthScroll - 20; // default for IE
			}
			else if (jQuery.browser.safari == true) {
				// if Safari subtract 14px to compensate for the scrollbar
				tableWidthScroll = tableWidthScroll - 16; // default for Safari
			}
			else {
				// if everything else subtract 15px to compensate for the scrollbar
				tableWidthScroll = tableWidthScroll - 19; // default for everyone else
			}

			obj.find('table.fht_orig_table').css({'width': tableWidthScroll+'px'}); // set the width of the table minus the scrollbar
			obj.find('table tbody tr:even td').addClass('even');
			obj.find('table tbody tr:odd td').addClass('odd');

			if (obj.find('table tbody tr td div.tableData').size() > 0 == false) {
				obj.find('table tbody tr td').wrapInner('<div class="tableData"><p class="tableData"></p></div>');
			}
			else {
				obj.find('table tbody tr td div.tableData').css('width','auto');
			}
			
			obj.find('table.fht_orig_table thead tr').css('display', '');
			
			if (obj.find('table thead tr th div.tableHeader').size() > 0 == false) {
				obj.find('table thead th').wrapInner('<div class="tableHeader"><p class="tableHeader"></p></div>');
			}
			else {
				obj.find('div.tableHeader').css('width', 'auto');
			}
			
			if (options.colBorder) {
				obj.find('.fht_parent table tr td:not(:last-child)').addClass('borderRight');
				obj.find('.fht_parent table tr th:not(:last-child)').addClass('borderRight');
			}
			
			obj.find('.fht_fixed_header_table_parent').remove();
			
			var html = "";
			html += "<div class='fht_fixed_header_table_parent'>"; // wraps around the entire fixed header
			html += "<!--[if IE]><div class='fht_top_right_header'></div><![endif]-->"; // adds a rounded corner to the top right of the header
			html += "<!--[if IE]><div class='fht_top_left_header'></div><![endif]-->"; // adds a rounded corner to the top left of the header
			html += "<div class='fht_fixed_header_table_border'>"; // creates the border for the header
			html += "<table class='fht_fixed_header_table'>"; // holds the thead that is cloned from the original table body
			html += "</table></div></div>"; // close all open div's and table tags
			
			obj.find('.fht_parent').prepend(html);
			
			obj.find('.fht_fixed_header_table_border').css('width', tableWidthScroll + 'px');
			
			obj.find('.fht_fixed_header_table_parent').css('width', parentDivWidth+'px');
			obj.find('table.fht_fixed_header_table').empty();
			
			obj.find('.fht_parent table thead').clone().prependTo('.' + objClass + ' .fht_fixed_header_table');
			
			obj.find('table.fht_fixed_header_table').css({'width': tableWidthScroll+'px'});

			var x = 0;
			var widthHidden = new Array();
			obj.find('.fht_parent table.fht_orig_table th').each(function() {
				if($(this).hasClass('th'+x) == false) {
					$(this).addClass('th'+x); // used to identify which column we are looking at
				}
				
				widthHidden[x] = $(this).width();
				x++;
			});
			
			var i = 0;
			var width = new Array();
			obj.find('.fht_parent table.fht_fixed_header_table th').each(function() {
				if($(this).hasClass('th'+i) == false) {
					$(this).addClass('th'+i);
				}
				width[i] = widthHidden[i];
				i++;
			});
			
			if(obj.find('table.fht_orig_table tbody tr td:first-child').hasClass('firstCell') == false) {
				obj.find('table.fht_orig_table tbody tr td:first-child').addClass('firstCell');
			}
			
			/*
			if (options.colBorder) {
				obj.find('.fht_parent table tr td:not(:last-child)').addClass('borderRight');
				obj.find('.fht_parent table tr th:not(:last-child)').addClass('borderRight');
			}*/
			
			var thCount = 0;
			var thWidth;
			var tdWidth;
			obj.find('table.fht_orig_table tbody tr:first td').each(function() {
				
				if ($(this).hasClass('firstCell')) {
					thCount = 0;
				}
				
				thWidth = width[thCount];
				tdWidth = $(this).width();
		
				$(this).children('div.tableData').css('width',thWidth+'px');
				obj.find('.fht_parent table.fht_fixed_header_table th.th'+thCount+' div.tableHeader').css('width', thWidth+'px');
				
				thCount++;
			});
			
			var footerHeight = 0;
			
			if (options.footer && !options.cloneHeaderToFooter) {
				if (!options.footerId) {
						// notify the developer they wanted a footer and didn't provide content
				}
				else {
					var footerId = options.footerId;
					if (obj.find('.fht_fixed_footer_border').size() == 1) {
						var footerContent = obj.find('.fht_fixed_footer_border').html();
					}
					else {
						$('#'+footerId).appendTo('.fht_parent');
						
						var footerContent = obj.find('#'+footerId).html();
					}
						obj.find('#'+footerId).empty();
						obj.find('#'+footerId).prepend('<div class="fht_cloned_footer"><!--[if IE 6]><div class="fht_bottom_left_header"></div><div class="fht_bottom_right_header"></div><![endif]--><div class="fht_fixed_footer_border"></div></div>');
						obj.find('.fht_fixed_footer_border').html(footerContent);
						obj.find('.fht_cloned_footer').css('width', obj.find('.fht_fixed_header_table_parent').width()+'px');
						obj.find('#'+footerId).css({'height': obj.find('#'+footerId).height() + 'px', 'width': obj.find('.fht_fixed_header_table_parent').width()+'px'});
						footerHeight = obj.find('#'+footerId).height();
				}
			}
			else if (options.footer && options.cloneHeaderToFooter) {
				obj.find('.fht_parent .fht_cloned_footer').remove()
				
				var html = "";
				html += "<div class='fht_cloned_footer'>"; // wraps around the entire fixed header
				html += "<!--[if IE]><div class='fht_bottom_right_header'></div><![endif]-->"; // adds a rounded corner to the top right of the header
				html += "<!--[if IE]><div class='fht_bottom_left_header'></div><![endif]-->"; // adds a rounded corner to the top left of the header
				html += "<div class='fht_fixed_footer_border'>"; // creates the border for the header
				html += "</div></div>"; // close all open div's and table tags
	
				obj.find('.fht_parent').append(html);

				obj.find('.fht_parent .fht_fixed_header_table_parent .fht_fixed_header_table_border table').clone().prependTo('.' + objClass + ' .fht_cloned_footer .fht_fixed_footer_border');
				obj.find('.fht_cloned_footer').css({'width': obj.find('.fht_parent .fht_fixed_header_table_parent').width()+'px', 'height': (obj.find('.fht_parent .fht_fixed_header_table_parent').height()-1)+'px'});
	
				footerHeight = obj.find('.fht_cloned_footer').height();
			}
			
			var headerHeight = obj.find('.fht_parent .fht_fixed_header_table_parent').height();
			var scrollDivHeight = parentDivHeight - footerHeight - headerHeight;
	
			obj.find('.fht_table_body').css({'width': tableBodyWidth+'px','height': scrollDivHeight+'px'}); // set the height of the main table body (where the data will be displayed) this also determines how much of the data is visible before a scroll bar is needed
			
			
			obj.find('table.fht_orig_table thead tr').css('display', 'none'); // hide the table body's header
	
			if(options.loader) {
				obj.find('.fht_loader').css('display', 'none');
			}
			
			obj.find('.fht_table_body').scroll(function() {
				obj.find('.fht_fixed_header_table_border').css('margin-left',(-this.scrollLeft)+'px');
				if (options.footer && options.cloneHeaderToFooter) {
					obj.find('.fht_fixed_footer_border').css('margin-left',(-this.scrollLeft)+'px');
				}
			});
		}
		else {
			$('body').css('background', '#f00');
			// build a dialog window that indicates an error in implementation
		}
	}	
})(jQuery);


/**purr*/

( function( $ ) {
	
	$.purr = function ( notice, options )
	{ 
		// Convert notice to a jQuery object
		notice = $( notice );
		
		// Add a class to denote the notice as not sticky
		if ( !options.isSticky )
		{
			notice.addClass( 'not-sticky' );
		};
		
		// Get the container element from the page
		var cont = document.getElementById( 'purr-container' );
		
		// If the container doesn't yet exist, we need to create it
		if ( !cont )
		{
			cont = '<div id="purr-container"></div>';
		}
		
		// Convert cont to a jQuery object
		cont = $( cont );
		
		// Add the container to the page
		$( 'body' ).append( cont );
			
		notify();

		function notify ()
		{	
			// Set up the close button
			var close = document.createElement( 'a' );
			$( close ).attr(	
				{
					className: 'close',
					href: '#close',
					innerHTML: 'Close'
				}
			)
				.appendTo( notice )
					.click( function ()
						{
							removeNotice();
							
							return false;
						}
					);
			
			// Add the notice to the page and keep it hidden initially
			notice.appendTo( cont )
				.hide();
				
			if ( jQuery.browser.msie && options.usingTransparentPNG )
			{
				// IE7 and earlier can't handle the combination of opacity and transparent pngs, so if we're using transparent pngs in our
				// notice style, we'll just skip the fading in.
				notice.show();
			}
			else
			{
				//Fade in the notice we just added
				notice.fadeIn( options.fadeInSpeed );
			}
			
			// Set up the removal interval for the added notice if that notice is not a sticky
			if ( !options.isSticky )
			{
				var topSpotInt = setInterval( function ()
				{
					// Check to see if our notice is the first non-sticky notice in the list
					if ( notice.prevAll( '.not-sticky' ).length == 0 )
					{ 
						// Stop checking once the condition is met
						clearInterval( topSpotInt );
						
						// Call the close action after the timeout set in options
						setTimeout( function ()
							{
								removeNotice();
							}, options.removeTimer
						);
					}
				}, 200 );	
			}
		}

		function removeNotice ()
		{
			// IE7 and earlier can't handle the combination of opacity and transparent pngs, so if we're using transparent pngs in our
			// notice style, we'll just skip the fading out.
			if ( jQuery.browser.msie && options.usingTransparentPNG )
			{
			notice.slideUp(1200, function(){notice.remove();});
			
//				notice.css( { opacity: 0	} )
//					.animate( 
//						{ 
//							height: '0px' 
//						}, 
//						{ 
//							duration: options.fadeOutSpeed, 
//							complete:  function ()
//								{
//									notice.remove();
//								} 
//							} 
//					);
			}
			else
			{
				// Fade the object out before reducing its height to produce the sliding effect
				notice.animate( 
					{ 
						opacity: '0'
					}, 
					{ 
						duration: options.fadeOutSpeed, 
						complete: function () 
							{
								notice.animate(
									{
										height: '0px'
									},
									{
										duration: options.fadeOutSpeed,
										complete: function ()
											{
												notice.remove();
											}
									}
								);
							}
					} 
				);
			}
		};
	};
	
	$.fn.purr = function ( options )
	{
		options = options || {};
		options.fadeInSpeed = options.fadeInSpeed || 500;
		options.fadeOutSpeed = options.fadeOutSpeed || 500;
		options.removeTimer = options.removeTimer || 4000;
		options.isSticky = options.isSticky || false;
		options.usingTransparentPNG = options.usingTransparentPNG || false;
		this.each( function() 
			{
				new $.purr( this, options );
			}
		);
		
		return this;
	};
})( jQuery );


  function ShowNotification(title, content, time)
    {
    var notice = '<div class="notice"><table width="100%" cellspacing="0" cellpadding="0"><tr><td class="notice-left">&nbsp;</td><td class="notice-body"><img src="http://kitchen.net-perspective.com/purr-example/info.png" alt="" /><h3>' + title + '</h3><p>' +content + '</p><a id="customCloseHref" class="fg-button ui-corner-all ui-state-default">OK <span id="notificationCount"></span></a></td><td class="notice-right">&nbsp;</td></tr></table></div>';
    
    $( notice ).purr(
							{
								usingTransparentPNG: true,isSticky: false,removeTimer: 5000,fadeOutSpeed :1000
							}
						);
				countDown(time);	
				$("#customCloseHref").click(function(){ $('.notice .close').click();			});
    }

				
function countDown(value)
{
if (value > 0)
{
    $('#notificationCount').text(value);
    var func =function(){ value = value -1; countDown(value);}
    setTimeout(func,1000);
 }

}



/**tool tip***/
/**
 * tools.tooltip 1.1.3 - Tooltips done right.
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/tooltip.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : November 2008
 * Date: ${date}
 * Revision: ${revision} 
 */
(function($) { 

	var instances = [];
	
	// static constructs
	$.tools = $.tools || {};
	
	$.tools.tooltip = {
		version: '1.1.3',
		
		conf: { 
			
			// default effect variables
			effect: 'toggle',			
			fadeOutSpeed: "fast",
			tip: null,
			
			predelay: 0,
			delay: 30,
			opacity: 1,			
			lazy: undefined,
			
			// 'top', 'bottom', 'right', 'left', 'center'
			position: ['top', 'center'], 
			offset: [0, 0],			
			cancelDefault: true,
			relative: false,
			oneInstance: true,
			
			
			// type to event mapping 
			events: {
				def: 			"mouseover,mouseout",
				input: 		"focus,blur",
				widget:		"focus mouseover,blur mouseout",
				tooltip:		"mouseover,mouseout"
			},			
			
			api: false
		},
		
		addEffect: function(name, loadFn, hideFn) {
			effects[name] = [loadFn, hideFn];	
		} 
	};
	
	
	var effects = { 
		toggle: [ 
			function(done) { 
				var conf = this.getConf(), tip = this.getTip(), o = conf.opacity;
				if (o < 1) { tip.css({opacity: o}); }
				tip.show();
				done.call();
			},
			
			function(done) { 
				this.getTip().hide();
				done.call();
			} 
		],
		
		fade: [
			function(done) { this.getTip().fadeIn(this.getConf().fadeInSpeed, done); },  
			function(done) { this.getTip().fadeOut(this.getConf().fadeOutSpeed, done); } 
		]		
	};   

	function Tooltip(trigger, conf) {

		var self = this, $self = $(this);
		
		trigger.data("tooltip", self);
		
		// find the tip
		var tip = trigger.next();
		
		if (conf.tip) {
			
			tip = $(conf.tip);
			
			// multiple tip elements
			if (tip.length > 1) {
				
				// find sibling
				tip = trigger.nextAll(conf.tip).eq(0);	
				
				// find sibling from the parent element
				if (!tip.length) {
					tip = trigger.parent().nextAll(conf.tip).eq(0);
				}
			} 
		} 				
		
		/* calculate tip position relative to the trigger */  	
		function getPosition(e) {	
			
			// get origin top/left position 
			var top = conf.relative ? trigger.position().top : trigger.offset().top, 
				 left = conf.relative ? trigger.position().left : trigger.offset().left,
				 pos = conf.position[0];

			top  -= tip.outerHeight() - conf.offset[0];
			left += trigger.outerWidth() + conf.offset[1];
			
			// adjust Y		
			var height = tip.outerHeight() + trigger.outerHeight();
			if (pos == 'center') 	{ top += height / 2; }
			if (pos == 'bottom') 	{ top += height; }
			
			// adjust X
			pos = conf.position[1]; 	
			var width = tip.outerWidth() + trigger.outerWidth();
			if (pos == 'center') 	{ left -= width / 2; }
			if (pos == 'left')   	{ left -= width; }	 
			
			return {top: top, left: left};
		}		

		
		// event management
		var isInput = trigger.is(":input"), 
			 isWidget = isInput && trigger.is(":checkbox, :radio, select, :button"),			
			 type = trigger.attr("type"),
			 evt = conf.events[type] || conf.events[isInput ? (isWidget ? 'widget' : 'input') : 'def']; 
		
		evt = evt.split(/,\s*/); 
		if (evt.length != 2) { throw "Tooltip: bad events configuration for " + type; }
				
		trigger.bind(evt[0], function(e) {
			
			// close all instances
			if (conf.oneInstance) {
				$.each(instances, function()  {
					this.hide();		
				});
			}
				
			// see if the tip was launched by this trigger
			var t = tip.data("trigger");			
			if (t && t[0] != this) { tip.hide().stop(true, true); }			
			
			e.target = this;
			self.show(e); 
			
			// tooltip close events
			evt = conf.events.tooltip.split(/,\s*/);
			tip.bind(evt[0], function() { self.show(e); });
			if (evt[1]) { tip.bind(evt[1], function() { self.hide(e); }); }
			
		});
		
		trigger.bind(evt[1], function(e) {
			self.hide(e); 
		});
		
		// ensure that the tip really shows up. IE cannot catch up with this.
		if (!$.browser.msie && !isInput && !conf.predelay) {
			trigger.mousemove(function()  {					
				if (!self.isShown()) {
					trigger.triggerHandler("mouseover");	
				}
			});
		}

		// avoid "black box" bug in IE with PNG background images
		if (conf.opacity < 1) {
			tip.css("opacity", conf.opacity);		
		}
		
		var pretimer = 0, title = trigger.attr("title");
		
		if (title && conf.cancelDefault) { 
			trigger.removeAttr("title");
			trigger.data("title", title);			
		}						
		
		$.extend(self, {
				
			show: function(e) {
				
				if (e) { trigger = $(e.target); }				

				clearTimeout(tip.data("timer"));					

				if (tip.is(":animated") || tip.is(":visible")) { return self; }
				
				function show() {
					
					// remember the trigger element for this tip
					tip.data("trigger", trigger);
					
					// get position
					var pos = getPosition(e);					
					
					// title attribute					
					if (conf.tip && title) {
						tip.html(trigger.data("title"));
					} 				
					
					// onBeforeShow
					e = e || $.Event();
					e.type = "onBeforeShow";
					$self.trigger(e, [pos]);				
					if (e.isDefaultPrevented()) { return self; }
			
					
					// onBeforeShow may have altered the configuration
					pos = getPosition(e);
					
					// set position
					tip.css({position:'absolute', top: pos.top, left: pos.left});					
					
					// invoke effect
					var eff = effects[conf.effect];
					if (!eff) { throw "Nonexistent effect \"" + conf.effect + "\""; }
					
					eff[0].call(self, function() {
						e.type = "onShow";
						$self.trigger(e);			
					});					
					
				}
				
				if (conf.predelay) {
					clearTimeout(pretimer);
					pretimer = setTimeout(show, conf.predelay);	
					
				} else {
					show();	
				}
				
				return self;
			},
			
			hide: function(e) {

				clearTimeout(tip.data("timer"));
				clearTimeout(pretimer);
				
				if (!tip.is(":visible")) { return; }
				
				function hide() {
					
					// onBeforeHide
					e = e || $.Event();
					e.type = "onBeforeHide";
					$self.trigger(e);				
					if (e.isDefaultPrevented()) { return; }
					
					effects[conf.effect][1].call(self, function() {
						e.type = "onHide";
						$self.trigger(e);		
					});
				}
				 
				if (conf.delay && e) {
					tip.data("timer", setTimeout(hide, conf.delay));
					
				} else {
					hide();	
				}			
				
				return self;
			},
			
			isShown: function() {
				return tip.is(":visible, :animated");	
			},
				
			getConf: function() {
				return conf;	
			},
				
			getTip: function() {
				return tip;	
			},
			
			getTrigger: function() {
				return trigger;	
			},
			
			// callback functions			
			bind: function(name, fn) {
				$self.bind(name, fn);
				return self;	
			},
			
			onHide: function(fn) {
				return this.bind("onHide", fn);
			},

			onBeforeShow: function(fn) {
				return this.bind("onBeforeShow", fn);
			},
			
			onShow: function(fn) {
				return this.bind("onShow", fn);
			},
			
			onBeforeHide: function(fn) {
				return this.bind("onBeforeHide", fn);
			},

			unbind: function(name) {
				$self.unbind(name);
				return self;	
			}			

		});		

		// bind all callbacks from configuration
		$.each(conf, function(name, fn) {
			if ($.isFunction(fn)) { self.bind(name, fn); }
		}); 		
		
	}
		
	
	// jQuery plugin implementation
	$.prototype.tooltip = function(conf) {
		
		// return existing instance
		var api = this.eq(typeof conf == 'number' ? conf : 0).data("tooltip");
		if (api) { return api; }
		
		// setup options
		var globals = $.extend(true, {}, $.tools.tooltip.conf);		
		
		if ($.isFunction(conf)) {
			conf = {onBeforeShow: conf};
			
		} else if (typeof conf == 'string') {
			conf = {tip: conf};	
		}

		conf = $.extend(true, globals, conf);
		
		// can also be given as string
		if (typeof conf.position == 'string') {
			conf.position = conf.position.split(/,?\s/);	
		}
		
		// assign tip's only when apiement is being mouseovered		
		if (conf.lazy !== false && (conf.lazy === true || this.length > 20)) {	
				
			this.one("mouseover", function(e) {	
				api = new Tooltip($(this), conf);
				api.show(e);
				instances.push(api);
			}); 
			
		} else {
			
			// install tooltip for each entry in jQuery object
			this.each(function() {
				api = new Tooltip($(this), conf); 
				instances.push(api);
			});
		} 

		return conf.api ? api: this;		
		
	};
		
}) (jQuery);



/***tool tip end**/

/*

Title:		jShowOff: a jQuery Content Rotator Plugin
Author:		Erik Kallevig
Version:	0.1.2
Website:	http://ekallevig.com/jshowoff
License: 	Dual licensed under the MIT and GPL licenses.

*/

(function($) {
    $.fn.jshowoff = function(settings) {
        var config = { animatePause: true, autoPlay: true, changeSpeed: 600, controls: true, controlText: { play: 'Play', pause: 'Pause', next: 'Next', previous: 'Previous' }, effect: 'fade', hoverPause: true, links: true, speed: 3000 }; if (settings) $.extend(true, config, settings); if (config.speed < (config.changeSpeed + 20)) { alert('jShowOff: Make speed at least 20ms longer than changeSpeed; the fades aren\'t always right on time.'); return this; }; this.each(function(i) {
            var $cont = $(this); var gallery = $(this).children().remove(); var timer = ''; var counter = 0; var preloadedImg = []; var howManyInstances = $('.jshowoff').length + 1; var uniqueClass = 'jshowoff-' + howManyInstances; var cssClass = config.cssClass != undefined ? config.cssClass : ''; $cont.css('position', 'relative').wrap('<div class="jshowoff ' + uniqueClass + '" />'); var $wrap = $('.' + uniqueClass); $wrap.css('position', 'relative').addClass(cssClass); $(gallery[0]).clone().appendTo($cont); preloadImg(); if (config.controls) { addControls(); if (config.autoPlay == false) { $('.' + uniqueClass + '-play').addClass(uniqueClass + '-paused jshowoff-paused').text(config.controlText.play); }; }; if (config.links) { addSlideLinks(); $('.' + uniqueClass + '-slidelinks a').eq(0).addClass(uniqueClass + '-active jshowoff-active'); }; if (config.hoverPause) { $cont.hover(function() { if (isPlaying()) pause('hover'); }, function() { if (isPlaying()) play('hover'); }); }; if (config.autoPlay && gallery.length > 1) { timer = setInterval(function() { play(); }, config.speed); }; if (gallery.length < 1) { $('.' + uniqueClass).append('<p>For jShowOff to work, the container element must have child elements.</p>'); }; function transitionTo(gallery, index) {
                var oldCounter = counter; if ((counter >= gallery.length) || (index >= gallery.length)) { counter = 0; var e2b = true; }
                else if ((counter < 0) || (index < 0)) { counter = gallery.length - 1; var b2e = true; }
                else { counter = index; }
                if (config.effect == 'slideLeft') { var newSlideDir, oldSlideDir; function slideDir(dir) { newSlideDir = dir == 'right' ? 'left' : 'right'; oldSlideDir = dir == 'left' ? 'left' : 'right'; }; counter >= oldCounter ? slideDir('left') : slideDir('right'); $(gallery[counter]).clone().appendTo($cont).slideIt({ direction: newSlideDir, changeSpeed: config.changeSpeed }); if ($cont.children().length > 1) { $cont.children().eq(0).css('position', 'absolute').slideIt({ direction: oldSlideDir, showHide: 'hide', changeSpeed: config.changeSpeed }, function() { $(this).remove(); }); }; } else if (config.effect == 'fade') { $(gallery[counter]).clone().appendTo($cont).hide().fadeIn(config.changeSpeed, function() { if ($.browser.msie) this.style.removeAttribute('filter'); }); if ($cont.children().length > 1) { $cont.children().eq(0).css('position', 'absolute').fadeOut(config.changeSpeed, function() { $(this).remove(); }); }; } else if (config.effect == 'none') { $(gallery[counter]).clone().appendTo($cont); if ($cont.children().length > 1) { $cont.children().eq(0).css('position', 'absolute').remove(); }; }; if (config.links) { $('.' + uniqueClass + '-active').removeClass(uniqueClass + '-active jshowoff-active'); $('.' + uniqueClass + '-slidelinks a').eq(counter).addClass(uniqueClass + '-active jshowoff-active'); };
            }; function isPlaying() { return $('.' + uniqueClass + '-play').hasClass('jshowoff-paused') ? false : true; }; function play(src) {
                if (!isBusy()) {
                    counter++; transitionTo(gallery, counter); if (src == 'hover' || !isPlaying()) { timer = setInterval(function() { play(); }, config.speed); }
                    if (!isPlaying()) { $('.' + uniqueClass + '-play').text(config.controlText.pause).removeClass('jshowoff-paused ' + uniqueClass + '-paused'); } 
                };
            }; function pause(src) { clearInterval(timer); if (!src || src == 'playBtn') $('.' + uniqueClass + '-play').text(config.controlText.play).addClass('jshowoff-paused ' + uniqueClass + '-paused'); if (config.animatePause && src == 'playBtn') { $('<p class="' + uniqueClass + '-pausetext jshowoff-pausetext">' + config.controlText.pause + '</p>').css({ fontSize: '62%', textAlign: 'center', position: 'absolute', top: '40%', lineHeight: '100%', width: '100%' }).appendTo($wrap).addClass(uniqueClass + 'pauseText').animate({ fontSize: '600%', top: '30%', opacity: 0 }, { duration: 500, complete: function() { $(this).remove(); } }); } }; function next() { goToAndPause(counter + 1); }; function previous() { goToAndPause(counter - 1); }; function isBusy() { return $cont.children().length > 1 ? true : false; }; function goToAndPause(index) { $cont.children().stop(true, true); if ((counter != index) || ((counter == index) && isBusy())) { if (isBusy()) $cont.children().eq(0).remove(); transitionTo(gallery, index); pause(); }; }; function preloadImg() { $(gallery).each(function(i) { $(this).find('img').each(function(i) { preloadedImg[i] = $('<img>').attr('src', $(this).attr('src')); }); }); }; function addControls() { $wrap.append('<p class="jshowoff-controls ' + uniqueClass + '-controls"><a class="jshowoff-play ' + uniqueClass + '-play" href="#null">' + config.controlText.pause + '</a> <a class="jshowoff-prev ' + uniqueClass + '-prev" href="#null">' + config.controlText.previous + '</a> <a class="jshowoff-next ' + uniqueClass + '-next" href="#null">' + config.controlText.next + '</a></p>'); $('.' + uniqueClass + '-controls a').each(function() { if ($(this).hasClass('jshowoff-play')) $(this).click(function() { isPlaying() ? pause('playBtn') : play(); return false; }); if ($(this).hasClass('jshowoff-prev')) $(this).click(function() { previous(); return false; }); if ($(this).hasClass('jshowoff-next')) $(this).click(function() { next(); return false; }); }); }; function addSlideLinks() { $wrap.append('<p class="jshowoff-slidelinks ' + uniqueClass + '-slidelinks"></p>'); $.each(gallery, function(i, val) { var linktext = $(this).attr('title') != '' ? $(this).attr('title') : i + 1; $('<a class="jshowoff-slidelink-' + i + ' ' + uniqueClass + '-slidelink-' + i + '" href="#null">' + linktext + '</a>').bind('click', { index: i }, function(e) { goToAndPause(e.data.index); return false; }).appendTo('.' + uniqueClass + '-slidelinks'); }); };
        }); return this;
    };
})(jQuery); (function($) { $.fn.slideIt = function(settings, callback) { var config = { direction: 'left', showHide: 'show', changeSpeed: 600 }; if (settings) $.extend(config, settings); this.each(function(i) { $(this).css({ left: 'auto', right: 'auto', top: 'auto', bottom: 'auto' }); var measurement = (config.direction == 'left') || (config.direction == 'right') ? $(this).outerWidth() : $(this).outerHeight(); var startStyle = {}; startStyle['position'] = $(this).css('position') == 'static' ? 'relative' : $(this).css('position'); startStyle[config.direction] = (config.showHide == 'show') ? '-' + measurement + 'px' : 0; var endStyle = {}; endStyle[config.direction] = config.showHide == 'show' ? 0 : '-' + measurement + 'px'; $(this).css(startStyle).animate(endStyle, config.changeSpeed, callback); }); return this; }; })(jQuery);



/**Please sign in plugin*/
    
    (
    function($) 
    {
        $.fn.pleaseSignIn = function(settings) 
        {
            var config = {title: "Notice!", content: "You must login or register before you can submit your bet!",LoginButtonText:"Login",RegisterButtonText:"Register",IgnoreButtonText:"Ignore"}; 
            if (settings) 
                $.extend(true, config, settings); 
            $(document.createElement("div")).attr("id","pleaseSignInDiv").text(config.content).css("display","none").prependTo ("body"); 
            
            return this.each(function(i,element) {$(element).click(function(){ createDialog(config.title,config.content,config.LoginButtonText,config.RegisterButtonText,config.IgnoreButtonText);});}); 
            
         function createDialog(title,content,LoginButtonText,RegisterButtonText,IgnoreButtonText)
         {       

            var l10nButtons = {};
            l10nButtons[IgnoreButtonText] = function(){$(this).dialog('close');};
            l10nButtons[RegisterButtonText] = function() { window.location = '/Register.aspx' };
            l10nButtons[LoginButtonText] = function() { LoginBox('open'); return false; };



         $("#pleaseSignInDiv").dialog({
        dialogClass: "",
        draggable: false,
        resizable: false,
        autoOpen: true,
        closeOnEscape: true,
        modal:true,
        position: ['center', 'center'],
        title: '<span class="ui-icon ui-icon-alert floatLeft marginR10"></span>' + title,
       buttons:l10nButtons,


        close: function(event, ui) {
             }
            });
         }
        }
             
    
})(jQuery);
(function($){var i=function(e){if(!e)var e=window.event;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation()};$.fn.checkbox=function(f){try{document.execCommand('BackgroundImageCache',false,true)}catch(e){}var g={cls:'jquery-checkbox',empty:'../../../style/v3/images/empty.png'};g=$.extend(g,f||{});var h=function(a){var b=a.checked;var c=a.disabled;var d=$(a);if(a.stateInterval)clearInterval(a.stateInterval);a.stateInterval=setInterval(function(){if(a.disabled!=c)d.trigger((c=!!a.disabled)?'disable':'enable');if(a.checked!=b)d.trigger((b=!!a.checked)?'check':'uncheck')},10);return d};return this.each(function(){var a=this;var b=h(a);if(a.wrapper)a.wrapper.remove();a.wrapper=$('<span class="'+g.cls+'"><span class="mark"><img src="'+g.empty+'" /></span></span>');a.wrapperInner=a.wrapper.children('span:eq(0)');a.wrapper.hover(function(e){a.wrapperInner.addClass(g.cls+'-hover');i(e)},function(e){a.wrapperInner.removeClass(g.cls+'-hover');i(e)});b.css({position:'absolute',zIndex:-1,visibility:'hidden'}).after(a.wrapper);var c=false;if(b.attr('id')){c=$('label[for='+b.attr('id')+']');if(!c.length)c=false}if(!c){c=b.closest?b.closest('label'):b.parents('label:eq(0)');if(!c.length)c=false}if(c){c.hover(function(e){a.wrapper.trigger('mouseover',[e])},function(e){a.wrapper.trigger('mouseout',[e])});c.click(function(e){b.trigger('click',[e]);i(e);return false})}a.wrapper.click(function(e){b.trigger('click',[e]);i(e);return false});b.click(function(e){i(e)});b.bind('disable',function(){a.wrapperInner.addClass(g.cls+'-disabled')}).bind('enable',function(){a.wrapperInner.removeClass(g.cls+'-disabled')});b.bind('check',function(){a.wrapper.addClass(g.cls+'-checked')}).bind('uncheck',function(){a.wrapper.removeClass(g.cls+'-checked')});$('img',a.wrapper).bind('dragstart',function(){return false}).bind('mousedown',function(){return false});if(window.getSelection)a.wrapper.css('MozUserSelect','none');if(a.checked)a.wrapper.addClass(g.cls+'-checked');if(a.disabled)a.wrapperInner.addClass(g.cls+'-disabled')})}})(jQuery);
/*-------------------------------------------------------------------- 
Scripts for creating and manipulating custom menus based on standard <ul> markup
Version: 3.0, 03.31.2009

By: Maggie Costello Wachs (maggie@filamentgroup.com) and Scott Jehl (scott@filamentgroup.com)
	http://www.filamentgroup.com
	* reference articles: http://www.filamentgroup.com/lab/jquery_ipod_style_drilldown_menu/
		
Copyright (c) 2009 Filament Group
Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
--------------------------------------------------------------------*/


var allUIMenus = [];

$.fn.menu = function(options){
	var caller = this;
	var options = options;
	var m = new Menu(caller, options);	
	allUIMenus.push(m);
	
	$(this)
	.mousedown(function(){
		if (!m.menuOpen) { m.showLoading(); };
	})	
	.click(function(){
		if (m.menuOpen == false) { m.showMenu(); }
		else { m.kill(); };
		return false;
	});	
};

function Menu(caller, options) {
	var menu = this;
	var caller = $(caller);
	var container = $('<div class="fg-menu-container ui-widget ui-widget-content ui-corner-all">'+options.content+'</div>');
	
	this.menuOpen = false;
	this.menuExists = false;
	
	var options = jQuery.extend({
		content: null,
		width: 190, // width of menu container, must be set or passed in to calculate widths of child menus
		maxHeight: 180, // max height of menu (if a drilldown: height does not include breadcrumb)
		positionOpts: {
			posX: 'left', 
			posY: 'bottom',
			offsetX: 0,
			offsetY: 0,
			directionH: 'right',
			directionV: 'down', 
			detectH: true, // do horizontal collision detection  
			detectV: false, // do vertical collision detection   /* Changed by ZOHAR couldn't pass parameter and on FF3.5 the menu shot UP*/
			linkToFront: false
		},
		showSpeed: 200, // show/hide speed in milliseconds
		callerOnState: 'ui-state-active', // class to change the appearance of the link/button when the menu is showing
		loadingState: 'ui-state-loading', // class added to the link/button while the menu is created
		linkHover: 'ui-state-hover', // class for menu option hover state
		linkHoverSecondary: 'li-hover', // alternate class, may be used for multi-level menus		
	// ----- multi-level menu defaults -----
		crossSpeed: 200, // cross-fade speed for multi-level menus
		crumbDefaultText: 'Choose an option:',
		backLink: true, // in the ipod-style menu: instead of breadcrumbs, show only a 'back' link
		backLinkText: 'Back',
		flyOut: false, // multi-level menus are ipod-style by default; this parameter overrides to make a flyout instead
		flyOutOnState: 'ui-state-default',
		nextMenuLink: 'ui-icon-triangle-1-e', // class to style the link (specifically, a span within the link) used in the multi-level menu to show the next level
		topLinkText: 'All',
		nextCrumbLink: 'ui-icon-carat-1-e'	
	}, options);
	
	var killAllMenus = function(){
		$.each(allUIMenus, function(i){
			if (allUIMenus[i].menuOpen) { allUIMenus[i].kill(); };	
		});
	};
	
	this.kill = function(){
		caller
			.removeClass(options.loadingState)
			.removeClass('fg-menu-open')
			.removeClass(options.callerOnState);	
		container.find('li').removeClass(options.linkHoverSecondary).find('a').removeClass(options.linkHover);		
		if (options.flyOutOnState) { container.find('li a').removeClass(options.flyOutOnState); };	
		if (options.callerOnState) { 	caller.removeClass(options.callerOnState); };			
		if (container.is('.fg-menu-ipod')) { menu.resetDrilldownMenu(); };
		if (container.is('.fg-menu-flyout')) { menu.resetFlyoutMenu(); };	
		container.parent().hide();	
		menu.menuOpen = false;
		$(document).unbind('click', killAllMenus);
		$(document).unbind('keydown');
	};
	
	this.showLoading = function(){
		caller.addClass(options.loadingState);
	};

	this.showMenu = function(){
		killAllMenus();
		if (!menu.menuExists) { menu.create() };
		caller
			.addClass('fg-menu-open')
			.addClass(options.callerOnState);
		container.parent().show().click(function(){ menu.kill(); return false; });
		container.hide().slideDown(options.showSpeed).find('.fg-menu:eq(0)');
		menu.menuOpen = true;
		caller.removeClass(options.loadingState);
		$(document).click(killAllMenus);
		
		// assign key events
		$(document).keydown(function(event){
			var e;
			if (event.which !="") { e = event.which; }
			else if (event.charCode != "") { e = event.charCode; }
			else if (event.keyCode != "") { e = event.keyCode; }
			
			var menuType = ($(event.target).parents('div').is('.fg-menu-flyout')) ? 'flyout' : 'ipod' ;
			
			switch(e) {
				case 37: // left arrow 
					if (menuType == 'flyout') {
						$(event.target).trigger('mouseout');
						if ($('.'+options.flyOutOnState).size() > 0) { $('.'+options.flyOutOnState).trigger('mouseover'); };
					};
					
					if (menuType == 'ipod') {
						$(event.target).trigger('mouseout');
						if ($('.fg-menu-footer').find('a').size() > 0) { $('.fg-menu-footer').find('a').trigger('click'); };
						if ($('.fg-menu-header').find('a').size() > 0) { $('.fg-menu-current-crumb').prev().find('a').trigger('click'); };
						if ($('.fg-menu-current').prev().is('.fg-menu-indicator')) {
							$('.fg-menu-current').prev().trigger('mouseover');							
						};						
					};
					return false;
					break;
					
				case 38: // up arrow 
					if ($(event.target).is('.' + options.linkHover)) {	
						var prevLink = $(event.target).parent().prev().find('a:eq(0)');						
						if (prevLink.size() > 0) {
							$(event.target).trigger('mouseout');
							prevLink.trigger('mouseover');
						};						
					}
					else { container.find('a:eq(0)').trigger('mouseover'); }
					return false;
					break;
					
				case 39: // right arrow 
					if ($(event.target).is('.fg-menu-indicator')) {						
						if (menuType == 'flyout') {
							$(event.target).next().find('a:eq(0)').trigger('mouseover');
						}
						else if (menuType == 'ipod') {
							$(event.target).trigger('click');						
							setTimeout(function(){
								$(event.target).next().find('a:eq(0)').trigger('mouseover');
							}, options.crossSpeed);
						};				
					}; 
					return false;
					break;
					
				case 40: // down arrow 
					if ($(event.target).is('.' + options.linkHover)) {
						var nextLink = $(event.target).parent().next().find('a:eq(0)');						
						if (nextLink.size() > 0) {							
							$(event.target).trigger('mouseout');
							nextLink.trigger('mouseover');
						};				
					}
					else { container.find('a:eq(0)').trigger('mouseover'); }		
					return false;						
					break;
					
				case 27: // escape
					killAllMenus();
					break;
					
				case 13: // enter
					if ($(event.target).is('.fg-menu-indicator') && menuType == 'ipod') {							
						$(event.target).trigger('click');						
						setTimeout(function(){
							$(event.target).next().find('a:eq(0)').trigger('mouseover');
						}, options.crossSpeed);					
					}; 
					break;
			};			
		});
	};
	
	this.create = function(){	
		container.css({ width: options.width }).appendTo('body').find('ul:first').not('.fg-menu-breadcrumb').addClass('fg-menu');
		container.find('ul, li a').addClass('ui-corner-all');
		
		// aria roles & attributes
		container.find('ul').attr('role', 'menu').eq(0).attr('aria-activedescendant','active-menuitem').attr('aria-labelledby', caller.attr('id'));
		container.find('li').attr('role', 'menuitem');
		container.find('li:has(ul)').attr('aria-haspopup', 'true').find('ul').attr('aria-expanded', 'false');
		container.find('a').attr('tabindex', '-1');
		
		// when there are multiple levels of hierarchy, create flyout or drilldown menu
		if (container.find('ul').size() > 1) {
			if (options.flyOut) { menu.flyout(container, options); }
			else { menu.drilldown(container, options); }	
		}
		else {
			container.find('a').click(function(){
				menu.chooseItem(this);
				return false;
			});
		};	
		
		if (options.linkHover) {
			var allLinks = container.find('.fg-menu li a');
			allLinks.hover(
				function(){
					var menuitem = $(this);
					$('.'+options.linkHover).removeClass(options.linkHover).blur().parent().removeAttr('id');
					$(this).addClass(options.linkHover).focus().parent().attr('id','active-menuitem');
				},
				function(){
					$(this).removeClass(options.linkHover).blur().parent().removeAttr('id');
				}
			);
		};
		
		if (options.linkHoverSecondary) {
			container.find('.fg-menu li').hover(
				function(){
					$(this).siblings('li').removeClass(options.linkHoverSecondary);
					if (options.flyOutOnState) { $(this).siblings('li').find('a').removeClass(options.flyOutOnState); }
					$(this).addClass(options.linkHoverSecondary);
				},
				function(){ $(this).removeClass(options.linkHoverSecondary); }
			);
		};	
		
		menu.setPosition(container, caller, options);
		menu.menuExists = true;
	};
	
	this.chooseItem = function(item){
		menu.kill();
		// edit this for your own custom function/callback:
		//$('#menuSelection').text($(item).text());	
		 location.href = $(item).attr('href');
	};
};

Menu.prototype.flyout = function(container, options) {
	var menu = this;
	
	this.resetFlyoutMenu = function(){
		var allLists = container.find('ul ul');
		allLists.removeClass('ui-widget-content').hide();	
	};
	
	container.addClass('fg-menu-flyout').find('li:has(ul)').each(function(){
		var linkWidth = container.width();
		var showTimer, hideTimer;
		var allSubLists = $(this).find('ul');		
		
		allSubLists.css({ left: linkWidth, width: linkWidth }).hide();
			
		$(this).find('a:eq(0)').addClass('fg-menu-indicator').html('<span>' + $(this).find('a:eq(0)').text() + '</span><span class="ui-icon '+options.nextMenuLink+'"></span>').hover(
			function(){
				clearTimeout(hideTimer);
				var subList = $(this).next();
				if (!fitVertical(subList, $(this).offset().top)) { subList.css({ top: 'auto', bottom: 0 }); };
				if (!fitHorizontal(subList, $(this).offset().left + 100)) { subList.css({ left: 'auto', right: linkWidth, 'z-index': 999 }); };
				showTimer = setTimeout(function(){
					subList.addClass('ui-widget-content').show(options.showSpeed).attr('aria-expanded', 'true');	
				}, 300);	
			},
			function(){
				clearTimeout(showTimer);
				var subList = $(this).next();
				hideTimer = setTimeout(function(){
					subList.removeClass('ui-widget-content').hide(options.showSpeed).attr('aria-expanded', 'false');
				}, 400);	
			}
		);

		$(this).find('ul a').hover(
			function(){
				clearTimeout(hideTimer);
				if ($(this).parents('ul').prev().is('a.fg-menu-indicator')) {
					$(this).parents('ul').prev().addClass(options.flyOutOnState);
				}
			},
			function(){
				hideTimer = setTimeout(function(){
					allSubLists.hide(options.showSpeed);
					container.find(options.flyOutOnState).removeClass(options.flyOutOnState);
				}, 500);	
			}
		);	
	});
	
	container.find('a').click(function(){
		menu.chooseItem(this);
		return false;
	});
};


Menu.prototype.drilldown = function(container, options) {
	var menu = this;	
	var topList = container.find('.fg-menu');	
	var breadcrumb = $('<ul class="fg-menu-breadcrumb ui-widget-header ui-corner-all ui-helper-clearfix"></ul>');
	var crumbDefaultHeader = $('<li class="fg-menu-breadcrumb-text">'+options.crumbDefaultText+'</li>');
	var firstCrumbText = (options.backLink) ? options.backLinkText : options.topLinkText;
	var firstCrumbClass = (options.backLink) ? 'fg-menu-prev-list' : 'fg-menu-all-lists';
	var firstCrumbLinkClass = (options.backLink) ? 'ui-state-default ui-corner-all' : '';
	var firstCrumbIcon = (options.backLink) ? '<span class="ui-icon ui-icon-triangle-1-w"></span>' : '';
	var firstCrumb = $('<li class="'+firstCrumbClass+'"><a href="#" class="'+firstCrumbLinkClass+'">'+firstCrumbIcon+firstCrumbText+'</a></li>');
	
	container.addClass('fg-menu-ipod');
	
	if (options.backLink) { breadcrumb.addClass('fg-menu-footer').appendTo(container).hide(); }
	else { breadcrumb.addClass('fg-menu-header').prependTo(container); };
	breadcrumb.append(crumbDefaultHeader);
	
	var checkMenuHeight = function(el){
		if (el.height() > options.maxHeight) { el.addClass('fg-menu-scroll') };	
		el.css({ height: options.maxHeight });
	};
	
	var resetChildMenu = function(el){ el.removeClass('fg-menu-scroll').removeClass('fg-menu-current').height('auto'); };
	
	this.resetDrilldownMenu = function(){
		$('.fg-menu-current').removeClass('fg-menu-current');
		topList.animate({ left: 0 }, options.crossSpeed, function(){
			$(this).find('ul').each(function(){
				$(this).hide();
				resetChildMenu($(this));				
			});
			topList.addClass('fg-menu-current');			
		});		
		$('.fg-menu-all-lists').find('span').remove();	
		breadcrumb.empty().append(crumbDefaultHeader);		
		$('.fg-menu-footer').empty().hide();	
		checkMenuHeight(topList);		
	};
	
	topList
		.addClass('fg-menu-content fg-menu-current ui-widget-content ui-helper-clearfix')
		.css({ width: container.width() })
		.find('ul')
			.css({ width: container.width(), left: container.width() })
			.addClass('ui-widget-content')
			.hide();		
	checkMenuHeight(topList);	
	
	topList.find('a').each(function(){
		// if the link opens a child menu:
		if ($(this).next().is('ul')) {
			$(this)
				.addClass('fg-menu-indicator')
				.each(function(){ $(this).html('<span>' + $(this).text() + '</span><span class="ui-icon '+options.nextMenuLink+'"></span>'); })
				.click(function(){ // ----- show the next menu			
					var nextList = $(this).next();
		    		var parentUl = $(this).parents('ul:eq(0)');   		
		    		var parentLeft = (parentUl.is('.fg-menu-content')) ? 0 : parseFloat(topList.css('left'));    		
		    		var nextLeftVal = Math.round(parentLeft - parseFloat(container.width()));
		    		var footer = $('.fg-menu-footer');
		    		
		    		// show next menu   		
		    		resetChildMenu(parentUl);
		    		checkMenuHeight(nextList);
					topList.animate({ left: nextLeftVal }, options.crossSpeed);						
		    		nextList.show().addClass('fg-menu-current').attr('aria-expanded', 'true');    
		    		
		    		var setPrevMenu = function(backlink){
		    			var b = backlink;
		    			var c = $('.fg-menu-current');
			    		var prevList = c.parents('ul:eq(0)');
			    		c.hide().attr('aria-expanded', 'false');
		    			resetChildMenu(c);
		    			checkMenuHeight(prevList);
			    		prevList.addClass('fg-menu-current').attr('aria-expanded', 'true');
			    		if (prevList.hasClass('fg-menu-content')) { b.remove(); footer.hide(); };
		    		};		
		
					// initialize "back" link
					if (options.backLink) {
						if (footer.find('a').size() == 0) {
							footer.show();
							$('<a href="#"><span class="ui-icon ui-icon-triangle-1-w"></span> <span>Back</span></a>')
								.appendTo(footer)
								.click(function(){ // ----- show the previous menu
									var b = $(this);
						    		var prevLeftVal = parseFloat(topList.css('left')) + container.width();		    						    		
						    		topList.animate({ left: prevLeftVal },  options.crossSpeed, function(){
						    			setPrevMenu(b);
						    		});			
									return false;
								});
						}
					}
					// or initialize top breadcrumb
		    		else { 
		    			if (breadcrumb.find('li').size() == 1){				
							breadcrumb.empty().append(firstCrumb);
							firstCrumb.find('a').click(function(){
								menu.resetDrilldownMenu();
								return false;
							});
						}
						$('.fg-menu-current-crumb').removeClass('fg-menu-current-crumb');
						var crumbText = $(this).find('span:eq(0)').text();
						var newCrumb = $('<li class="fg-menu-current-crumb"><a href="javascript://" class="fg-menu-crumb">'+crumbText+'</a></li>');	
						newCrumb
							.appendTo(breadcrumb)
							.find('a').click(function(){
								if ($(this).parent().is('.fg-menu-current-crumb')){
									menu.chooseItem(this);
								}
								else {
									var newLeftVal = - ($('.fg-menu-current').parents('ul').size() - 1) * 180;
									topList.animate({ left: newLeftVal }, options.crossSpeed, function(){
										setPrevMenu();
									});
								
									// make this the current crumb, delete all breadcrumbs after this one, and navigate to the relevant menu
									$(this).parent().addClass('fg-menu-current-crumb').find('span').remove();
									$(this).parent().nextAll().remove();									
								};
								return false;
							});
						newCrumb.prev().append(' <span class="ui-icon '+options.nextCrumbLink+'"></span>');
		    		};			
		    		return false;    		
    			});
		}
		// if the link is a leaf node (doesn't open a child menu)
		else {
			$(this).click(function(){
				menu.chooseItem(this);
				return false;
			});
		};
	});
};


/* Menu.prototype.setPosition parameters (defaults noted with *):
	referrer = the link (or other element) used to show the overlaid object 
	settings = can override the defaults:
		- posX/Y: where the top left corner of the object should be positioned in relation to its referrer.
				X: left*, center, right
				Y: top, center, bottom*
		- offsetX/Y: the number of pixels to be offset from the x or y position.  Can be a positive or negative number.
		- directionH/V: where the entire menu should appear in relation to its referrer.
				Horizontal: left*, right
				Vertical: up, down*
		- detectH/V: detect the viewport horizontally / vertically
		- linkToFront: copy the menu link and place it on top of the menu (visual effect to make it look like it overlaps the object) */

Menu.prototype.setPosition = function(widget, caller, options) { 
	var el = widget;
	var referrer = caller;
	var dims = {
		refX: referrer.offset().left,
		refY: referrer.offset().top,
		refW: referrer.getTotalWidth(),
		refH: referrer.getTotalHeight()
	};	
	var options = options;
	var xVal, yVal;
	
	var helper = $('<div class="positionHelper"></div>');
	helper.css({ position: 'absolute', left: dims.refX, top: dims.refY, width: dims.refW, height: dims.refH });
	el.wrap(helper);
	
	// get X pos
	switch(options.positionOpts.posX) {
		case 'left': 	xVal = 0; 
			break;				
		case 'center': xVal = dims.refW / 2;
			break;				
		case 'right': xVal = dims.refW;
			break;
	};
	
	// get Y pos
	switch(options.positionOpts.posY) {
		case 'top': 	yVal = 0;
			break;				
		case 'center': yVal = dims.refH / 2;
			break;				
		case 'bottom': yVal = dims.refH;
			break;
	};
	
	// add the offsets (zero by default)
	xVal += options.positionOpts.offsetX;
	yVal += options.positionOpts.offsetY;
	
	// position the object vertically
	if (options.positionOpts.directionV == 'up') {
		el.css({ top: 'auto', bottom: yVal });
		if (options.positionOpts.detectV && !fitVertical(el)) {
			el.css({ bottom: 'auto', top: yVal });
		}
	} 
	else {
		el.css({ bottom: 'auto', top: yVal });
		if (options.positionOpts.detectV && !fitVertical(el)) {
			el.css({ top: 'auto', bottom: yVal });
		}
	};
	
	// and horizontally
	if (options.positionOpts.directionH == 'left') {
		el.css({ left: 'auto', right: xVal });
		if (options.positionOpts.detectH && !fitHorizontal(el)) {
			el.css({ right: 'auto', left: xVal });
		}
	} 
	else {
		el.css({ right: 'auto', left: xVal });
		if (options.positionOpts.detectH && !fitHorizontal(el)) {
			el.css({ left: 'auto', right: xVal });
		}
	};
	
	// if specified, clone the referring element and position it so that it appears on top of the menu
	if (options.positionOpts.linkToFront) {
		referrer.clone().addClass('linkClone').css({
			position: 'absolute', 
			top: 0, 
			right: 'auto', 
			bottom: 'auto', 
			left: 0, 
			width: referrer.width(), 
			height: referrer.height()
		}).insertAfter(el);
	};
};


/* Utilities to sort and find viewport dimensions */

function sortBigToSmall(a, b) { return b - a; };

jQuery.fn.getTotalWidth = function(){
	return $(this).width() + parseInt($(this).css('paddingRight')) + parseInt($(this).css('paddingLeft')) + parseInt($(this).css('borderRightWidth')) + parseInt($(this).css('borderLeftWidth'));
};

jQuery.fn.getTotalHeight = function(){
	return $(this).height() + parseInt($(this).css('paddingTop')) + parseInt($(this).css('paddingBottom')) + parseInt($(this).css('borderTopWidth')) + parseInt($(this).css('borderBottomWidth'));
};

function getScrollTop(){
	return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
};

function getScrollLeft(){
	return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
};

function getWindowHeight(){
	var de = document.documentElement;
	return self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
};

function getWindowWidth(){
	var de = document.documentElement;
	return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
};

/* Utilities to test whether an element will fit in the viewport
	Parameters:
	el = element to position, required
	leftOffset / topOffset = optional parameter if the offset cannot be calculated (i.e., if the object is in the DOM but is set to display: 'none') */
	
function fitHorizontal(el, leftOffset){
	var leftVal = parseInt(leftOffset) || $(el).offset().left;
	return (leftVal + $(el).width() <= getWindowWidth() + getScrollLeft() && leftVal - getScrollLeft() >= 0);
};

function fitVertical(el, topOffset){
	var topVal = parseInt(topOffset) || $(el).offset().top;
	return (topVal + $(el).height() <= getWindowHeight() + getScrollTop() && topVal - getScrollTop() >= 0);
};

/*-------------------------------------------------------------------- 
 * javascript method: "pxToEm"
 * by:
   Scott Jehl (scott@filamentgroup.com) 
   Maggie Wachs (maggie@filamentgroup.com)
   http://www.filamentgroup.com
 *
 * Copyright (c) 2008 Filament Group
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 *
 * Description: Extends the native Number and String objects with pxToEm method. pxToEm converts a pixel value to ems depending on inherited font size.  
 * Article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/
 * Demo: http://www.filamentgroup.com/examples/pxToEm/	 	
 *							
 * Options:  	 								
 		scope: string or jQuery selector for font-size scoping
 		reverse: Boolean, true reverses the conversion to em-px
 * Dependencies: jQuery library						  
 * Usage Example: myPixelValue.pxToEm(); or myPixelValue.pxToEm({'scope':'#navigation', reverse: true});
 *
 * Version: 2.0, 08.01.2008 
 * Changelog:
 *		08.02.2007 initial Version 1.0
 *		08.01.2008 - fixed font-size calculation for IE
--------------------------------------------------------------------*/

Number.prototype.pxToEm = String.prototype.pxToEm = function(settings){
	//set defaults
	settings = jQuery.extend({
		scope: 'body',
		reverse: false
	}, settings);
	
	var pxVal = (this == '') ? 0 : parseFloat(this);
	var scopeVal;
	var getWindowWidth = function(){
		var de = document.documentElement;
		return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	};	
	
	/* When a percentage-based font-size is set on the body, IE returns that percent of the window width as the font-size. 
		For example, if the body font-size is 62.5% and the window width is 1000px, IE will return 625px as the font-size. 	
		When this happens, we calculate the correct body font-size (%) and multiply it by 16 (the standard browser font size) 
		to get an accurate em value. */
				
	if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
		var calcFontSize = function(){		
			return (parseFloat($('body').css('font-size'))/getWindowWidth()).toFixed(3) * 16;
		};
		scopeVal = calcFontSize();
	}
	else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };
			
	var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px' : (pxVal / scopeVal).toFixed(2) + 'em';
	return result;
};
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();