﻿// JScript File

var winHandle = null;
var dragobj = null;
var dragobjID = "";
var endDragStart = false;
var dragStartPos;
var elex = 0;
var eley = 0;
var grabx = 0;
var graby = 0;
var orix = 0;
var oriy = 0;
var balloonHelpFadeCounter = 0;
var balloonHelpFadeDirection = 0;

var leagueOvertimeColumn = [0,5,5,0,0,10,4,3,5,5 ];
var leagueTimePeriod =     [0,15,15,0,0,0,0,20,12,12 ]; 
var leagueNumPeriods =     [0,4,4,0,0,9,3,2,4,4 ];
var leagueTimePeriodOverTime =     [0,15,15,0,0,0,0,5,5,5 ];

var leagueAbrs = ["", "NFL","NCAAF","CFL","Arena","MLB","NHL","NCAAB","WNBA","NBA","MLS" ];
var spreadDivs = new Array();

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  return "";
}

function overDiv(event, id) {
	var coord = getMouseCoord(event).split(",");
	var grabx = coord[0];
	var currentGrabbed = document.getElementById( id );
	if ( currentGrabbed != null ) {
		var topGrabbed = (parseInt(coord[1])-parseInt(currentGrabbed.offsetTop)-111);
		if ( topGrabbed < 25 ) {
			currentGrabbed.style.cursor="hand";
		} else {
			currentGrabbed.style.cursor="default";
		}
	}
}

	


function dragGo(event) {

    dragobj = document.getElementById(dragobjID);

    if ( endDragStart == true ) {
		if (dragobj) {
		    setOpacity(dragobj,5);
		   
//		     if (dragobj.id.indexOf("Span_") != -1 && document.getElementById("Drag_From_Here") == null){
//                
//                oDiv=document.createElement("DIV");
//                oDiv.id = "Drag_From_Here";
//                oDiv.style.position = "absolute";
//                oDiv.style.zIndex = 500;
//                oDiv.style.left = dragobj.offsetLeft+"px";
//                oDiv.style.top = dragobj.offsetTop+"px";
//                oDiv.style.width = dragobj.offsetWidth+"px";
//                oDiv.style.height = dragobj.offsetHeight+"px";;
//                oDiv.style.borderColor="blue";
//                oDiv.style.borderStyle="solid";
//                oDiv.style.borderWidth="2px";
//                dragobj.parentNode.appendChild(oDiv);

//            } 
		    
			var coord = getMouseCoord(event).split(",");
			elex = orix + (coord[0]-grabx);
			eley = oriy + (coord[1]-graby);
			dragobj.style.position = "absolute";
			dragobj.style.left = (coord[0]-150).toString(10) + 'px';
			dragobj.style.top  = (coord[1]-60).toString(10) + 'px';
		}
		return false;
	}
}

function dragStart(event, id) {

	document.onmousedown = falsefunc; // in NS this prevents cascading of events, thus disabling text selection
	document.onmousemove = dragGo;
	document.onmouseup = dragStop;
	var coord = getMouseCoord(event).split(",");
	grabx = coord[0];
	graby = coord[1];
	dragStartPos = findPos(document.getElementById(id));
	dragobjID = id;
	endDragStart = true;
   
}


function dragStop(event) {
		
	if (dragobj) {
	
	    if (dragobj.id.indexOf("Game_") != -1){
	        var coord = getMouseCoord(event).split(",");
            dropGame(coord,dragobj.id);
	    }
		dragobj.style.zIndex = 5000;
	    setOpacity(dragobj,10);
		dragobj = null;
		
	}
	document.onmouseup = null;
	document.onmousedown = null; 
	document.onmousemove = null;  	
	endDragStart = false;
	
	
}

function setOpacity(obj, value) {
	obj.style.opacity = value/10;
	obj.style.filter = 'alpha(opacity=' + value*10 + ')';
}

function getMouseCoord(e) {
		var mousex,mousey;

		if (!e) e = window.event; // works on IE, but not NS (we rely on NS passing us the event)
			
		if (e)
		{ 
			if (e.pageX || e.pageY)
			{ // this doesn't work on IE6!! (works on FF,Moz,Opera7)
			mousex = e.pageX;
			mousey = e.pageY;
			}
			else if (e.clientX || e.clientY)
			{ // works on IE6,FF,Moz,Opera7
			// Note: I am adding together both the "body" and "documentElement" scroll positions
			//       this lets me cover for the quirks that happen based on the "doctype" of the html page.
			//         (example: IE6 in compatibility mode or strict)
			//       Based on the different ways that IE,FF,Moz,Opera use these ScrollValues for body and documentElement
			//       it looks like they will fill EITHER ONE SCROLL VALUE OR THE OTHER, NOT BOTH 
			mousex = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			mousey = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
			}
		}				
		return mousex+","+mousey;		
		
}
function falsefunc() { return false; }

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		} 
	}
	
	return [curleft,curtop];
} 

/* Works like document.getElementById but only searches from a given parent node.
 * Uses DFS Search 
 * Mark Kilfoil 2007
 */
function GetSubElementById(parentElement,subElementId){

    for(var i=0; i<parentElement.childNodes.length; i++){
        var childNode = parentElement.childNodes[i];
        if (childNode.id == subElementId){
            return parentElement.childNodes[i];
        }      
        var recursiveNode = GetSubElementById(childNode,subElementId);   
        if ( recursiveNode != null) return recursiveNode;
    }
    
    return null;
} 


function Set_Cookie( name, value, expires, path, domain, secure ) {
	
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );

}

// this function gets the cookie, if it exists
function Get_Cookie( name ) {
		
	//alert(currentViewDate);
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	
	if ( start == -1 || (( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )) {
		return '';
	}
	
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
    if ( Get_Cookie( name ) ) {
        document.cookie = name + "=" +
            ( ( path ) ? ";path=" + path : "") +
            ( ( domain ) ? ";domain=" + domain : "" ) +
            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

function getOffsetTop(element){
	var mOffsetTop = element.offsetTop;
	var mOffsetParent = element.offsetParent;

	while(mOffsetParent){
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	return mOffsetTop;
}

function addToCustomPage(LeagueID, EventID, strFutureBalloon, event){
    // add game to the cookie
    var today = new Date();	
    var content;	    
	var dateString =  today.getDate() +"."+ (today.getMonth()+1) +"."+ today.getFullYear();
	var gamebox = document.getElementById("Game_"+LeagueID+"_"+EventID); 
	var iframeContainer = document.getElementById("frameContainer"); 
    AddGameCookie(LeagueID, EventID, dateString);
    
    //creating the pop-up balloon with the link to the custom page
    
    try {
		content = document.getElementById("content"); 
		 
	}
	catch (error) {
	}
	
	if (content == null){			
		content = parent.document.getElementById("content");
		parent.ImagesURL= ImagesURL; 
		parent.ScoresURL= ScoresURL;
		parent.addToCustomPage(LeagueID, EventID, strFutureBalloon, event);
	}
    else
    {
        var coord = getMouseCoord(event).split(","); 
        var oDiv;
        var balloonImage;
        
        oDiv = document.createElement("DIV");
	    oDiv.id = "CustomLink";
	    oDiv.style.position = "absolute";
	    oDiv.style.left = parseInt(coord[0])+20+ "px";
	    
	    // if we are on an iframe page then we add in the offset of the parent
	    if (iframeContainer != null)
	    {
	         oDiv.style.top = (parseInt(getOffsetTop(iframeContainer))+parseInt(coord[1])-35) + "px";
	    }
	    else
	    {
	        oDiv.style.top = parseInt(coord[1])-35+ "px";
	    }    
	    oDiv.style.width = 240;
	    oDiv.style.height = 55;	
	    oDiv.style.zIndex = 5000; 

        if (strFutureBalloon == "true")
        {
            balloonImage = "future.gif"
        }
        else
        {
            balloonImage = "custom.gif"
        }
        
	    oDiv.innerHTML = "<span onclick=\"openWindow();\"><img src='"+ImagesURL+"/scores/general/"+balloonImage+"' border='0' /></span>";
    	try 
    	{
			var adDiv = document.getElementById("extraad"); 
		}
		catch (error) {
		}
		if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 )
		{
		    if(adDiv != null)
			    adDiv.style.zIndex = -1;
		} 
	   
	    content.appendChild(oDiv);
	    CustomBalloonFade = 1500;
	    fadeCustomPageBalloon(content);
	    event.returnValue = false;
	 }
        
}

function MouseOverBetstatus(LeagueID, EventID, event){
    
    //creating the pop-up balloon for betstatus
    var gamebox = document.getElementById("Game_"+LeagueID+"_"+EventID);
    var betImg = document.getElementById("BetStatus_"+LeagueID+"_"+EventID);
    var coord = getMouseCoord(event).split(","); 
    var betDiv;
    
    betDiv = document.createElement("DIV");
	betDiv.id = "HelpBetStatus";
	betDiv.style.position = "absolute";
	betDiv.style.left = parseInt(coord[0])+ "px";
	betDiv.style.top = parseInt(coord[1])-35+ "px";
	betDiv.style.width = 240;
	betDiv.style.height = 55;	
	betDiv.style.zIndex = 500;

	betDiv.innerHTML = "<img src='"+ImagesURL+"/scores/general/betstatus.gif' border='0' />";
	gamebox.appendChild(betDiv);
        
}

function MouseOutBetstatus(){
    
    //creating the pop-up balloon for betstatus
    var balloon = document.getElementById("HelpBetStatus");
    if ( balloon != null ) 
    {
		balloon.parentNode.removeChild(balloon);
	}
       
}

function fadeCustomPageBalloon(gamebox) {

	var oDiv = document.getElementById( "CustomLink" );
	
	//if we are on an iframe page
	if (oDiv == null){			
		oDiv = parent.document.getElementById("CustomLink"); 
	}
	
	if ( oDiv != null ) {
		CustomBalloonFade -= 10;
		if ( CustomBalloonFade < 0 ) {
			oDiv.parentNode.removeChild(oDiv);
			try 
			{
			    var adDiv = document.getElementById("extraad"); 
			}
			catch (error) {
			}
			if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 )
			{
			    if(adDiv != null)
			        adDiv.style.zIndex = 1;
			}	
		} else if ( CustomBalloonFade < 100 ) {
			oDiv.style.opacity = CustomBalloonFade;
			oDiv.style.filter = 'alpha(opacity=' + CustomBalloonFade + ')';
			window.setTimeout("fadeCustomPageBalloon();", 1 );			
		} else {
			window.setTimeout("fadeCustomPageBalloon();", 1 );
		}				
	} 	
}

function openWindow() {
			
	if ( winHandle == null || winHandle.closed ) {
		winHandle = window.open(ScoresURL+"/custom-scores.aspx", 'customScores');
	}
	winHandle.focus();
}


function AddGameCookie(leagueID, eventID, dateString){


    var games = Get_Cookie('game_selector_'+leagueID+"-"+dateString);
    if (games.indexOf(eventID) == -1){
        games = games +leagueID+"_"+eventID+ '.';
    }
    
    Set_Cookie( 'game_selector_'+leagueID+"-"+dateString, games, 3, '/', '.covers.com', '' );
    
    var leagueOrder = Get_Cookie("LeagueOrder-"+dateString);
       
    if (leagueOrder.indexOf(leagueID) == -1)
    {   //first game for a league so add it to the end of the leagueorder cookie
        leagueOrder = leagueOrder + leagueID + ".";
        Delete_Cookie("LeagueOrder-"+dateString);
        Set_Cookie( "LeagueOrder-"+dateString, leagueOrder, 3, '/', '.covers.com', '' );
    }
}

function CustomBetgraphOdds(leagueID, eventID, oddsType)
{
    var gamediv = document.getElementById("Game_"+leagueID+"_"+eventID);
    var oddsCell = document.getElementById(oddsType+"_bottom"+leagueID+"_"+eventID); 
    if (oddsCell== null){
        oddsCell = document.getElementById(oddsType+"_top"+leagueID+"_"+eventID);
        if(oddsType=='spread'){
            if(oddsCell != null)
                return (parseFloat(oddsCell.innerHTML) * (-1)); 
            else
                return 0;
        }
        else{
            if (oddsCell== null)
                return 0;
            else
                return parseFloat(oddsCell.innerHTML);
        }
    }
    else
        if(oddsCell != null){
            return parseFloat(oddsCell.innerHTML);
        }  
}

function AddOddsCookie(id, total, spread, dateString){


    var games = Get_Cookie('CustomScoresOdds-'+dateString);
    if (games.indexOf(id) == -1){
        games = games + id+' '+total+' '+spread+ '/';
    }
    else
    {
         var start = games.indexOf(id);
         var oldgamestring = games.substring(games.indexOf(id))
         var end = oldgamestring.indexOf("/");
         oldgamestring = oldgamestring.substring(0,end);
         games = games.replace(oldgamestring,id+' '+total+' '+spread);
    }
    
    Set_Cookie( 'CustomScoresOdds-'+dateString, games, 3, '/', '.covers.com', '' );
}

function UpdateOddsFromCookie(spanobject, LeagueID, EventID,  dateString, cookieString){

    //eg of cookieString: 9_741787~215~17/
   
    //get this games string from the cookie
    var gamestring = cookieString.substring(cookieString.indexOf(LeagueID+"_"+EventID));
    var end = gamestring.indexOf("/");
    gamestring = gamestring.substring(0,end);
    var odds_array= gamestring.split(" ");
    var totalCell = document.getElementById("total_top"+LeagueID+"_"+EventID);
    var spreadCell = document.getElementById("spread_bottom"+LeagueID+"_"+EventID);
    var ScoreStatus = document.getElementById("Status_"+LeagueID+"_"+EventID);
    var visitScore = document.getElementById("VisitScore_"+LeagueID+"_"+EventID);
    var homeScore = document.getElementById("HomeScore_"+LeagueID+"_"+EventID);
    var multiplier = 1;
    if (totalCell == null){
        totalCell= document.getElementById("total_bottom"+LeagueID+"_"+EventID);
        spreadCell= document.getElementById("spread_top"+LeagueID+"_"+EventID);
        multiplier= -1;
    }
 
    //updates betstatus with custom odds
    if (ScoreStatus !=null && visitScore != null && homeScore != null)
    {
        BetStatus.GetBetStatus(LeagueID,odds_array[2],odds_array[1],ScoreStatus.innerHTML,visitScore.innerHTML,homeScore.innerHTML, EventID, UpdateBetstatus_callback)  
    }
        //gets odds values from the cookie and sets the cells html
    if(totalCell != null && spreadCell != null){
        totalCell.innerHTML = odds_array[1];
        spreadCell.innerHTML = odds_array[2] * multiplier;
    }
}

function UpdateBetstatus_callback(response){
    var a = response.value;
    var BetTop=document.getElementById("BetStatusTop_"+a.LeagueID+"_"+a.EventID);
    var BetBottom=document.getElementById("BetStatusBottom_"+a.LeagueID+"_"+a.EventID);
    if(BetTop.innerHTML != a.BetStatusTop || BetBottom.innerHTML != a.BetStatusBottom){
        BetTop.innerHTML=a.BetStatusTop;
        BetBottom.innerHTML=a.BetStatusBottom;
    }
}

function RemoveGameCookie(id, dateString){
    var games = Get_Cookie('CustomScoresGameIds-'+dateString);
    var start = games.indexOf(id);
    if (start != -1){
        var end = start + id.length + 1;
        games = games.substring(0,start) +  games.substring(end,games.length);
        Set_Cookie( 'CustomScoresGameIds-'+dateString, games, 3, '/', '.covers.com', '' );
    }
}


function FlashScorebox (GameDivID, Flashes, ScoreDivID)
{
    var color;
    var updateGame = document.getElementById(GameDivID);
    var ScoreDiv = document.getElementById(ScoreDivID);

    if ( Flashes % 2 == 1) 
    {	
        updateGame.style.borderColor= '#f10303';		
		if (ScoreDiv != null)
		{
		    ScoreDiv.style.color = '#f10303';
		    ScoreDiv.style.fontWeight="Bold";
        }
	} 
	else 
	{
        updateGame.style.borderColor = '#6d7891';
        if (ScoreDiv != null)
        {
            ScoreDiv.style.color = '#900000';
            ScoreDiv.style.fontWeight="Bold";
	    }
	}
	
    if (Flashes > 0)
    {
         Flashes = Flashes -1;   
         window.setTimeout("FlashScorebox('"+GameDivID+"', "+Flashes+", '"+ScoreDivID+"');",1500);
    }
    else
    {
        if(ScoreDiv != null){
            ScoreDiv.style.fontWeight="";
            if(ScoreDivID.indexOf('_5_') > 0 || ScoreDivID.indexOf('_6_') > 0 || ScoreDivID.indexOf('_9_') > 0)
                ScoreDiv.style.color = '#900000';
            else
                ScoreDiv.style.color = '#000000';
        }
    }
}