﻿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();
        });
    });
}
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: currentValue,
            min: minValue,
            max: 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 + " vs. " +matches[i].AwayTeam.Name;
            
            if (names.length>24)
            {
                names =  matches[i].HomeTeam.Sname + " vs. " +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)
    }

}

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);


    
    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,false);
        SetText(lblDrawBestOdd,selectedMatch.Odd.DrawOdd,false);
        SetText(lblAwayBestOdd,selectedMatch.Odd.AwayOdd,false);
        if (selectedMatch.MatchOverUnverOdds !=null)
        {
            SetText(OverOddLabel,selectedMatch.MatchOverUnverOdds.OverOdd,false);
            SetText(UnderOddLabel,selectedMatch.MatchOverUnverOdds.UnderOdd,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";
   
    homeBestOdd_img.src = baseAffiliateImageURL + selectedMatch.Odd.HomeBetIcon;
    drawBestOdd_img.src = baseAffiliateImageURL + selectedMatch.Odd.DrawBetIcon;
    awayBestOdd_img.src = baseAffiliateImageURL + selectedMatch.Odd.AwayBetIcon;

    //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);
    PotentialWin();
}

        else
        {
            
            if (!selectedMatch.BetsAllowed)//upcoming
            {
                SetMatchDescriptionPanel(MatchUpComing);
                SetMatchNotificationPanel('',false);
                SetText(MatchOddsStatusSpanElement, "",false);
                SetText(OverUnderStatusSpanElement, "",false);
                ChangeSubmitUIState(true,true);
                
            }
            else if (IsServerTimeGreater(MatchDueDate))   //closed match 
            {
                 SetMatchDescriptionPanel(MatchClosed)
                 SetMatchNotificationPanel('',false);
                 SetText(MatchOddsStatusSpanElement, "",false);
                 SetText(OverUnderStatusSpanElement, "",false);
                 ChangeSubmitUIState(true,true);                    
                 
            }
            else
            {
                  if (isRegistered == true)
                  {
                     SetText(MatchOddsStatusSpanElement, PlayerNotPlacedYet.replace("@@@",''),false);
                     SetText(OverUnderStatusSpanElement, PlayerNotPlacedYet.replace("@@@",OptionalBet),false);
                     SetMatchNotificationPanel('',false);
                    
    
                
                          ChangeSubmitUIState(false,false);
                 }
                 else
                 {
                  SetMatchNotificationPanel('',false);
                 SetMatchDescriptionPanel(PlsSignIn);
                 SetText(MatchOddsStatusSpanElement, '',false);
                     SetText(OverUnderStatusSpanElement, '',false);
                     ChangeSubmitUIState(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);
    
 
    PageMethods.GetMatchGeneralStats(selectedMatch.MatchId,OnGetMatchGeneralStatsComplete,OnGetMatchGeneralStatsFailed);
   WebService.GetDiscussion(selectedMatch.MatchId,1, OnGetDiscussionComplete);
}

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 = " The Draw"; break;
    case 2 : teamName = selectedMatch.AwayTeam.Sname; break;
    }
    SetText(MatchOddsStatusSpanElement, PlayerPlaced.replace('@@@',userBet.ScoreBetAmount) + " on " + teamName  ,false);

    switch(parseInt(userBet.RankBetId))
    {
    case 3: teamName = " Over 2.5 "; 
    SetText(OverUnderStatusSpanElement, PlayerPlaced.replace('@@@',userBet.RankBetAmount) + " on " + teamName ,false);
    
    break;
    case 1: teamName = " Under 2.5 ";
    SetText(OverUnderStatusSpanElement, PlayerPlaced.replace('@@@',userBet.RankBetAmount) + " on " + teamName ,false);
 break;
  
    }

}


function OnGetDiscussionComplete(result)
{  
$('#MatchDiscussionAreaTable').empty();
    comments = eval(result);
   
    table = document.createElement('Table');
    table.className = "commentsGrid";
    tbody = document.createElement('tbody');
    
    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";  
            
            
            
            
            td = document.createElement('td');
            img = document.createElement('img');
            img.className = "img30x30";
            img.src =  imgBaseURL + comments[i].PlayerPosted.picture;
            td.appendChild(img);
            tr.appendChild(td);
            td = document.createElement('td');
            
            span = document.createElement('span');
            span.className = "userName";
            span.innerHTML = comments[i].PlayerPosted.username + " " + 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);
        } 
        table.appendChild(tbody);
          
        $('#MatchDiscussionAreaTable').append(table);
        
    }
}

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';
    }
  }  
  
  
  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 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);
        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 = 'Pos.';        
        tr.appendChild(td);    
            
        td = document.createElement('td');
        td.innerHTML = 'Team';
        tr.appendChild(td);    
        

        
        td = document.createElement('td');
        td.innerHTML = 'Pld';
        $(td).css("text-align","right");
        
        tr.appendChild(td);  
         
        td = document.createElement('td');
        td.innerHTML = 'W';
        $(td).css("text-align","right");

        tr.appendChild(td);  
        
        td = document.createElement('td');
        td.innerHTML = 'D';
        $(td).css("text-align","right");

        tr.appendChild(td);  
        
        td = document.createElement('td');
        td.innerHTML = 'L';
        $(td).css("text-align","right");

        tr.appendChild(td);      
        
        td = document.createElement('td');
        td.innerHTML = 'GD';
        $(td).css("text-align","right");
        tr.appendChild(td); 
              
        td = document.createElement('td');
        td.innerHTML = 'Pts';
        $(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("Current Standings");// +"'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('Match');
                td.appendChild(text);
                tr.appendChild(td);
                  td = document.createElement('td');
                text = document.createTextNode('Score');
                td.appendChild(text);
                
                tr.appendChild(td);
                  td = document.createElement('td');
                text = document.createTextNode('Date');
                $(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()*/ + " Vs. "+ lastMatchesJsonArray[j].AwayTeam.Sname;
                    if (lastMatchesJsonArray[j].HomeScore > lastMatchesJsonArray[j].AwayScore)
                    {
                        teamForm = teamForm +  " W";                       
                    }
                    else if (lastMatchesJsonArray[j].HomeScore == lastMatchesJsonArray[j].AwayScore)
                    {
                        teamForm =  teamForm + " D";
                    }
                    else
                    {
                        teamForm = teamForm + " L" ;
                    }
                }
                else
                {
                    text = lastMatchesJsonArray[j].HomeTeam.Sname + " Vs. "+ lastMatchesJsonArray[j].AwayTeam.Sname/*.bold()*/;
                    if (lastMatchesJsonArray[j].HomeScore < lastMatchesJsonArray[j].AwayScore)
                    {
                       teamForm = teamForm +  " W";
                    }
                    else if (lastMatchesJsonArray[j].HomeScore == lastMatchesJsonArray[j].AwayScore)
                    {
                        teamForm =  teamForm + " D";
                    }
                    else
                    {
                         teamForm = teamForm + " L" ;
                    }
                }
               
                
                //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("recent form: " + 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()
{
$('#MatchDiscussionButton').attr('disabled', true);

if ( $('#MatchDiscussionText').val() != shoutBoxDefault)
    PageMethods.SetDiscussionMessage(selectedMatch.MatchId,$('#MatchDiscussionText').val(), OnSetDiscussionMessageComplete,OnSetDiscussionMessageError);
}
 function OnSetDiscussionMessageComplete()
 {

    $("#MatchDiscussionText").val(shoutBoxDefault);
    $("#MatchDiscussionText").css("color", "gray");
    $('#MatchDiscussionButton').attr('disabled', false);
    $('#MatchDiscussionSubmitted').css("visibility","visible");
    $('#MatchDiscussionCountTitle').css("visibility","hidden");
    
    
 }
 function OnSetDiscussionMessageError()
 {
 $('#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"; 
         
          }  
            setMatchPanel(minPosMatch +  ',' +matchPosInArr);
            $("#matchInfo").css("display","block");
            $("#loadingDiv").remove();
                    
      }
/*Bet Page End*/



/*general functions*/



function doCount(obj, max) {
    $(obj.nextSibling.nextSibling).css("visibility", "visible");
    obj.nextSibling.nextSibling.innerHTML = obj.value.length + "/" + max + " characters";
    // document.getElementById(out).innerHTML =  obj.value.length + "/" +max + " characters";
}
function doCountValidate(obj, max) {
    if (obj.value.length < max)
        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;
    }
}

           

           

/**/



/*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
     });


 });
});

/********RSS***********/

/*	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'); }
          
          
          /**********RSS END***********/
(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: 180, // 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();