﻿ErrorBubble = { };
ErrorBubble.ShowError = function() { }

Utils.isMSIE = (navigator.userAgent.indexOf("MSIE") > -1) ? true : false;
Utils.isMSIE6 = (navigator.userAgent.indexOf("MSIE 6") > -1) ? true : false;

Utils.SetDefaultText = function(itemID) {
	var item = $(itemID);

	if (item.type == "text" && item.title != null && item.title != '') {
		item.addEvent("focus", Utils.DefaultTextFocus);
		item.addEvent("blur", Utils.DefaultTextBlur);

		if (item.value == '') {
			item.value = item.title;
		}
	}
}

Utils.DefaultTextFocus = function() {
    if (this.title == this.value) { this.value = ''; }
}

Utils.DefaultTextBlur = function() {
    if (this.value == '') { 
		this.value = this.title; 
    }
}

// Since IE fails at applying a background to a table row.
Utils.AdjustTableCellBackground = function(tableID) {
	if (Utils.isMSIE) {
		var rows = $(tableID).getElements("TR.adjustCellBG");
		
		rows.each(function(row) {
			var width = 0;
			var cells = row.getElements("TD");
			
			cells.each(function(cell) {
				$(cell).setStyle("background-position", "-" + width + "px 0px");
				
				width += cell.getWidth();
			});
		});
	}
}

Utils.OnLoad = function(func) {
	var previous = window.onload;
	
	window.onload = function(e) {
		if (previous != null) { previous(e); }
		func(e);
	}
}

Utils.OnScroll = function(func) {
	var previous = window.onscroll;
	
	window.onscroll = function(e) {
		if (previous != null) { previous(e); }
		func(e);
	}
}

// Joins two collections.
Utils.Concat = function(a, b) {
  for (var i = 0, node; node = b[i]; i++)
	a.push(node);
  return a;
}

 // Gets the key code associated with the event.
Utils.GetEventKeyCode = function(e) {
    if (window.event) {
        return e.keyCode;
    } else if (e.which) {
        return e.which;
    }
}

// Due to NET using a single form for all forms, this makes certain the correct form is submitted
// by determining the form object that has focus and submitting the form by clicking the first button
// found after the user presses the enter key.
Utils.SubmitByCorrectButton = function(form, e) {
	try {
		var caller = Utils.GetEventCaller(e);
	    
		if (Utils.GetEventKeyCode(e) == 13 && caller.type.toLowerCase() != "textarea") {
			var elements    = $(form).getElements("SELECT,INPUT,BUTTON");
			var callerFound = false;
	        
			for (var i = 0; i < elements.length; i++) {
				var element = elements[i];
				var type    = element.type;
				
				if (element.id == caller.id) { callerFound = true; }
				if (type)                    { type        = type.toLowerCase(); }

				if (callerFound && (type == "image" || type == "submit")) {
					buttonNotClicked = false;
					element.click();
					break;
				}
			}
	        
			return false;
		}
		
	} catch (ex) { console.log(ex); }
    
    return true;
}

Utils.GetEventKeyCode = function(e) {
    if (window.event) {
        return e.keyCode;
    } else if (e.which) {
        return e.which;
    }
}

Utils.GetEventCaller = function(e) {
    if (window.event) {
        return e.srcElement;
    } else if (e.which) {
        return e.target;
    }
}

Utils.GetCaller = function(e) {
	var caller = Utils.isMSIE ? $(e.relatedTarget) : $(e.target);
	return caller;
}

Utils.FollowMouse = function(e, bubble) {
	var top = e.page.y + 5;
	var left = e.page.x + 5;

	bubble.setStyle("top", top + "px");
	bubble.setStyle("left", left + "px");
}

Utils.SetupBubble = function(caller, bubble) {
	if (caller.init != true) {
		caller.bubble = $(bubble);
		
		caller.addEvent("mousemove", function(e) { 
			if (this.bubble != null) {
				Utils.FollowMouse(e, this.bubble);
			}
		});
		
		caller.addEvent("mouseout", function(e) { 
			if (this.bubble != null) {
				this.bubble.setStyle("display", "none");
			}
		});
		
		caller.init = true;
	}
}

Utils.Clone = function(original) {
	var copy = { };
	
	for (var i in original) {
        if (typeof original[i] == 'object') {
            copy[i] = Utils.Close(original[i]);
        } else { 
            copy[i] = original[i];
        }
    }
    
    return copy;
}

Utils.ParseNETDate = function(string) {
	var year = string.substring(0, 4);
	var month = string.substring(5, 7);
	var day = string.substring(8, 10);
	var hour = string.substring(11, 13);
	var minute = string.substring(14, 16);
	var second = string.substring(17, 19);
	
	if (month.indexOf("0") == 0) {
		month = month.substring(1, 2);
	}
	
	month = parseInt(month) - 1;
	
	return new Date(year, month, day, hour, minute, second);
}

try {
	if (console == null) { }
} catch(ex) {
	console = { };
	console.log = function(str) {
		if (str == null) { str = ""; }
		$("console").innerHTML += ("<p>" + str + "</p>");
	}
}

Utils.TellAFriend = function(pageUrl, title) {
    if (pageUrl == '' || title == '')
        return;
    var escapedPageUrl = escape(pageUrl);
    var escapedPageTitle = escape(title);
    var popup = window.open(Utils.WebsiteURL + "tell-a-friend.aspx?pt=" + escapedPageTitle + "&pu=" + escapedPageUrl,
        "uwantabetTellAFriend", "status=0,menubar=0,location=0,toolbar=0,directories=0,scrollbars=1,width=640,height=530");
    popup.focus();
}

Utils.PreLoadHoverImages = function() {
	var images = "blackButtonHL.png,orangeButtonHL.png,pinkButtonHL.png,orangeButtonPlainHL.png,orangeButtonPlainLargeHL.png,orangeButtonPlainExtraLargeHL.png,pinkButtonPlainHL.png,topMenuHighlight.png,joinNowOver.png,forumGoHL.png,paginationStartHL.png,paginationBackHL.png,paginationLastHL.png,paginationNextHL.png,bbeditor/bbButtonBoldHL.gif,bbeditor/bbButtonUnderlineHL.gif,bbeditor/bbButtonItalicHL.gif,bbeditor/bbButtonHRHL.gif,bbeditor/bbButtonImageHL.gif,bbeditor/bbButtonLinkHL.gif,bbeditor/bbButtonQuoteHL.gif,oddsPaginateNextHL.gif,oddsPaginateBackHL.gif,oddsForumButtonSummaryHL.gif";
	var list = images.split(",");
	
	for (var i = 0; i < list.length; i++) {
		var link = Utils.WebsiteURL + "App_Assets/images/" + list[i];
		var img = new Image();
		
		img.src = link;
	}
	
}

Utils.OnLoad(function() { Utils.PreLoadHoverImages(); });


// ## SPORTS MENU

Sports.IsFutures = (window.location.href.indexOf("futures-betting.aspx") > -1);
Sports.IsOddsSummary = (window.location.href.indexOf("odds-summary.aspx") > -1);
Sports.IsOddsComparison = (window.location.href.indexOf("odds-comparison.aspx") > -1);

Sports.InitDropDown = function() {
	var dropDowns = $$(".leftNavSubMenu");
	
	for (var i = 0; i < dropDowns.length; i++) {
		var sub = dropDowns[i];
		
		sub.SportID = sub.id.replace('sportsDropDownSub-', '');
		Sports.LoadChildSports(sub.SportID);
		
		// Open this menu if it contains the sport id currently in use on the page.
		function complete() {
			var s = this.element;
			
			if (Sports.MainSportID == s.SportID) {
				Sports.ShowDropDown(Sports.MainSportID);
			}
		}
        
        var height = sub.getStyle("height");
        var effect = new Fx.Morph(sub, {duration: 0, transition: Fx.Transitions.Sine.easeOut, onComplete: complete });
        effect.start({ "margin-top": [-(height.toInt())] });
	}
	
	
}

Sports.LoadChildSports = function(sportID) {
	var data = Sports.List[sportID];
	
	if (data != null) {
		var children = data.Children;
		var events = data.Events;
		
		var childContainer = $('sportChildren-' + sportID);
		var eventContainer = $('sportEvents-' + sportID);
		var emptyContainer = $('sportEmpty-' + sportID);
		
		childContainer.listType = "children";
		eventContainer.listType = "events";
		
		childContainer.SportID = sportID;
		eventContainer.SportID = sportID;
		
                // NPL clear the list if it has anything in it
                childContainer.options.length = 0;
                eventContainer.options.length = 0;

		childContainer.addEvent("change", function(e) { Sports.SelectionUpdatedChild(e); });
		eventContainer.addEvent("change", function(e) { Sports.SelectionUpdatedEvent(e); });
		
		// If this event has no immediate events, but is also a multi competitor event, then show a link to the futures betting.
		if (events.length == 0 && data.HasMultiCompetitorEvents == true) {
			childContainer.options[childContainer.options.length] = new Option('[Please Select]', '');
			childContainer.options[childContainer.options.length] = new Option('Futures Betting', 'futures');
			
			if (sportID == Sports.SportID && Sports.IsFutures) {
				childContainer.selectedIndex = childContainer.options.length - 1;
				Sports.SelectChild(childContainer, childContainer.selectedIndex);
			}
		}
		
		// If this sport has children, print them.
		if (children.length > 0) {
			if (events.length == 0 && data.HasMultiCompetitorEvents == true) {
				childContainer.options[childContainer.options.length] = new Option('------------------------------', '');
			} else {
				childContainer.options[childContainer.options.length] = new Option('[Please Select]', '');
			}
			
			var index = 0;
			
			for (var i = 0; i < children.length; i++) {
				var child = children[i];
				var name = child.SportName;
				
				if (child.SportLevel > 2) {
					name = " - " + name;
				}
				
				var option = new Option(name, child.SportID);
				option.data = child;
				
				childContainer.options[childContainer.options.length] = option;
				
				// If we are on a page where this child should be selected, then mark it to be selected.
				if (child.SportID == Sports.SportID) {
					index = childContainer.options.length - 1;
				}
			}
			
			// If we have not already selected anything, select the marked index.
			if (childContainer.selectedIndex == 0) {
				childContainer.selectedIndex = index;
				Sports.SelectChild(childContainer, childContainer.selectedIndex);
			}
		}
		
		// If there are children, show the child box.
		if (childContainer.options.length > 0) {
			childContainer.style.display = "block";
		}
		
		if (events.length > 0) {
			Sports.LoadEvents(sportID, data);
		}
	}
}

Sports.SelectionUpdatedChild = function(e) {
	var select = $(e.target);
	var selectedIndex = select.selectedIndex;
	
	Sports.SelectChild(select, selectedIndex);
}

Sports.SelectionUpdatedEvent = function(e) {
	var select = $(e.target);
	var selectedIndex = select.selectedIndex;
	
	Sports.UpdateLink(select);
}

Sports.SelectChild = function(select, selectedIndex) {
	var selectedOption = select.options[selectedIndex];
	var data = selectedOption.data;
	
	var sportID = select.SportID;
	var eventContainer = $('sportEvents-' + sportID);
	var emptyContainer = $('sportEmpty-' + sportID);

	// Nothing selected.
	if (selectedOption.value.length == 0 || selectedOption.value == 'futures') {
		eventContainer.style.display = "none";
		emptyContainer.style.display = "none";
	
	// If we have no data available for this particular item, then there is no point trying to do anything about it.
	} else if (data.HasEvents == false && data.HasMultiCompetitorEvents == false && data.HasChildren == false) {
		eventContainer.style.display = "none";
		emptyContainer.style.display = "block";
		
	// If this item does not have any data, but it has children, select the first child with data.
	} else if (data.HasEvents == false && data.HasMultiCompetitorEvents == false && data.HasChildren == true) {
		select.selectedIndex = selectedIndex + 1;
		Sports.SelectChild(select, select.selectedIndex);
	
	// Otherwise, just load data for this item.
	} else {
		emptyContainer.style.display = "none";
		Sports.LoadEvents(sportID, data);
	}
					
	Sports.UpdateContainer(sportID);
	Sports.UpdateLink(select);
}

Sports.LoadEvents = function(sportID, data) {
	var events = data.Events;
	var eventContainer = $('sportEvents-' + sportID);
	
	eventContainer.MainSportID = sportID;
	eventContainer.SportID = data.SportID;
	
	// Clear previous options.
	for (var i = eventContainer.options.length - 1; i >= 0; i--) {
		eventContainer.options[i] = null;
	}
	
	eventContainer.options[eventContainer.options.length] = new Option('[Please Select]', '');
	
	// If the selected sport has multi competitor events, we want to show futures betting for this item.
	if (data.HasMultiCompetitorEvents == true) {
		eventContainer.options[eventContainer.options.length] = new Option('Futures Betting', 'futures');
		
		// If the current sport is active on the page and this is the futures betting page, select this option.
		if (eventContainer.SportID == Sports.SportID && Sports.IsFutures) {
			eventContainer.selectedIndex = eventContainer.options.length - 1;
		}
	}
	
	// If the selected sport has standard events, we want to show those events and the odds summary.
	if (data.HasEvents == true) {
		eventContainer.options[eventContainer.options.length] = new Option('Odds Summary', 'summary');
		
		if (eventContainer.SportID == Sports.SportID && Sports.IsOddsSummary) {
			eventContainer.selectedIndex = eventContainer.options.length - 1;
		}
		
		eventContainer.options[eventContainer.options.length] = new Option('------------------------------', '');
		
		if (events.length > 0) {
			for (var i = 0; i < events.length; i++) {
				var _event = events[i];
				eventContainer.options[eventContainer.options.length] = new Option(_event.EventName, _event.EventID);
				
				if (Sports.EventID == _event.EventID) {
					eventContainer.selectedIndex = eventContainer.options.length - 1;
				}
			}
		}
	}
	
	// If nothing has been selected, select the first option with stuff in it.
//		if (eventContainer.selectedIndex == 0) {
//			for (var i = 0; i < eventContainer.options.length; i++) {
//				var option = eventContainer.options[i];
//				
//				if (option.value.length > 0) {
//					eventContainer.selectedIndex = i;
//					break;
//				}
//			}
//		}
	
	eventContainer.style.display = "block";
}

Sports.UpdateContainer = function(sportID) {
	
	// Force redraw of bottom graphic or IE will not move this accordingly.	
	if (Utils.isMSIE) {
		var bottom = $('sportsDropDownSub-' + sportID).getElement(".leftNavSubMenuBottom");
		var style = bottom.getStyle("bottom").toInt();
		
		bottom.setStyle("bottom", (style + 1) + "px");	
		bottom.setStyle("bottom", style + "px");
	}
}

Sports.UpdateLink = function(select) {
	if (select.listType == "children") {
		//var sportLink = $("sportLink-" + select.SportID);
		//sportLink.href = "Javascript:void(0);";
		
		if (select.options[select.selectedIndex].value == "futures") {
			window.location = Sports.WebsiteURL + "odds/futures-betting.aspx?sportid=" + select.SportID;
		}
		
	} else if (select.listType == "events") {
		//var sportLink = $("sportLink-" + select.MainSportID);
		//sportLink.href = "Javascript:void(0);";
		
		if (select.options[select.selectedIndex].value == "futures") {
			window.location = Sports.WebsiteURL + "odds/futures-betting.aspx?sportid=" + select.SportID;
			
		} else if (select.options[select.selectedIndex].value == "summary") {
			window.location = Sports.WebsiteURL + "odds/odds-summary.aspx?sportid=" + select.SportID;
			
		} else {
			window.location = Sports.WebsiteURL + "odds/odds-comparison.aspx?eventid=" + select.options[select.selectedIndex].value;
		}
	}
}
	
Sports.ShowDropDown = function(sportID) {
	var sub = $('sportsDropDownSub-' + sportID);
	var marginTop = sub.getStyle("margin-top").toInt();
	var height = sub.getStyle("height").toInt();
	
	// Hide.
	if (marginTop == 0) {
		var effect = new Fx.Morph(sub, {duration: 120, transition: Fx.Transitions.Sine.easeOut });
        effect.start({ "margin-top": [0, -height] });
   
	// Show.     
	} else {
		var effect = new Fx.Morph(sub, {duration: 120, transition: Fx.Transitions.Sine.easeOut });
        effect.start({ "margin-top": [-height, 0] });
	}
}




// ## ODDS BUBBLE

	OddBubble = {};

	OddBubble.ShowOdds = function() {
		var oddsButton = $('oddsButtons');
		var odds = $('panel-ODDS');
		var forums = $('panel-FORUMS');

		oddsButton.addClass("oddsTabsOdds");
		oddsButton.removeClass("oddsTabsForums");

		odds.setStyle("display", "block");
		forums.setStyle("display", "none");

		$('currentTab').value = 1;
		Utils.AdjustTableCellBackground('panel-ODDS');
	}

	OddBubble.ShowForums = function() {
		var oddsButton = $('oddsButtons');
		var odds = $('panel-ODDS');
		var forums = $('panel-FORUMS');

		oddsButton.removeClass("oddsTabsOdds");
		oddsButton.addClass("oddsTabsForums");

		odds.setStyle("display", "none");
		forums.setStyle("display", "block");

		$('currentTab').value = 2;
		Utils.AdjustTableCellBackground('panel-FORUMS');
	}

	OddBubble.OnMouseOverOdds = function(e, caller) {
		var bubble = $('oddBubble');

		if (caller == null) { return; }
		var details = caller.data;

		if (details != null) {
			Utils.SetupBubble(caller, bubble);

			var sportsBook = details["SportsBook"];
			var competitor = details["CompetitorName"];
			var odds = details["Odds"];
			var url = details["OddURL"];
			var dateTime = details["OddUpdate"];
			var comments = details["Comments"];

			var dateLinkText = null;

			if (details["IsBestOdd"] == "1") {
				odds += " <span class=\"bestOdds\">(Best Odds)</span>";
			}

			$('bubbleTitle').innerHTML = sportsBook;
			$('bubbleSubTitle').innerHTML = competitor;
			$('bubbleHeader').innerHTML = odds;

			if (dateTime != null && dateTime.trim().length > 0) {
				$('bubbleDateTime').innerHTML = dateTime;
				$('bubbleDateTime').setStyle("display", "block");
			} else {
				$('bubbleDateTime').setStyle("display", "none");
			}

			if (dateLinkText != null && dateLinkText.trim().length > 0) {
				$('bubbleLink').innerHTML = dateLinkText;
				$('bubbleLink').setStyle("display", "block");
			} else {
				$('bubbleLink').setStyle("display", "none");
			}

			if (comments != null && comments.trim().length > 0) {
				$('bubbleComments').innerHTML = comments;
				$('bubbleComments').setStyle("display", "block");
			} else {
				$('bubbleComments').setStyle("display", "none");
			}

			bubble.setStyle("display", "block");
		}
	}


// ## ERROR BUBBLE


	ErrorBubble.ShowError = function(event, text) {
		var e = new Event(event);
		var bubble = $('errorBubble');
		var caller = Utils.isMSIE ? $(e.relatedTarget) : $(e.target);

		if (caller.init != true) {
			caller.addEvent("mousemove", function(e) { ErrorBubble.MouseMove(e); });
			caller.addEvent("mouseout", function(e) { ErrorBubble.MouseOut(e); });
			caller.init = true;
		}

		$("errorDetails").innerHTML = text;
		bubble.setStyle("display", "block");
	}

	ErrorBubble.MouseOut = function() {
		$('errorBubble').setStyle("display", "none");
	}

	ErrorBubble.MouseMove = function(e) {
		var bubble = $('errorBubble');
		var top = e.page.y + 5;
		var left = e.page.x + 5;

		bubble.setStyle("top", top + "px");
		bubble.setStyle("left", left + "px");
	}