﻿/**
* Global variables
*/
var topStatsDisplay = "";
var absolutePath = "";

/**
* Document load event handler
*/
jQuery(document).ready(function() {

	// Initialise the pager object if there is one
	if (typeof (pagerObj) != "undefined" && pagerObj != null) {
		initializePager(pagerObj);
	}

	jQuery(".DataBoxHeader").click(function() { jQuery(this).siblings(".DataBoxContent").toggle(); });

	DisplayPlayerInfoHover();
});

/**
* Invokes a WS with JSON data.
*
* @param wsUrl              URL of the web service
* @param dataCallback       callback function to obtain the data to pass to the web service
* @param beforeSendCallback callback function that is invoked before the WS request is sent
* @param successCallback    callback function for a successful WS request
*/
function invokeJsonWS(wsUrl, dataCallback, beforeSendCallback, successCallback) {
	jQuery.ajax({
		type: "POST",
		url: wsUrl,
		data: dataCallback(),
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		beforeSend: beforeSendCallback,
		success: successCallback,
		error: function(request, message, errorThrown) { if (request.status != 0) { alert("An error has occurred. Error type: " + errorThrown + " : " + message); } }
	});
}

/**
* Invokes a web service that returns the control rendered on the server . The control to be rendered is specified in the
* data passed to the web service, and the local rendering is driven by the <c>onSuccess</c> callback method.
*
* @param jsonData              callback function to obtain the rendering parameters
* @param beforeRenderCallback  callback function that is invoked before the rendering starts
* @param successCallback       callback function that is invoked when the rendering completes
*/
function RenderControl(jsonData, beforeRenderCallback, successCallback) {
	var wsUrl =
		(typeof statsServiceUrl !== "undefined")
			? statsServiceUrl
			: subPath + "/StatsService.asmx/RenderControl";
	invokeJsonWS(wsUrl, jsonData, beforeRenderCallback, successCallback);
}

/**
* Initialise the pager, setting its properties and assigning event handlers.
*
* @param pagerObj  the pager object to initialise
*/
function initializePager(pagerObj) {
	var template = jQuery("#hdnTemplate").val();

	if (typeof (template) == "undefined" || template == null)
		template = "Page {0} of {1} ({2} items)";

	jQuery("#PagerSummary").html(format(template, [pagerObj.CurrentPage + 1, pagerObj.NumberOfPages, pagerObj.NumberOfResults]));
	if (pagerObj.NumberOfPages > 1) {
		jQuery("#slider-range-max").slider("destroy");
		jQuery("#slider-range-max > div").remove();
		jQuery("#slider-range-max").slider({
			range: "max",
			min: 1,
			max: pagerObj.NumberOfPages,
			value: pagerObj.CurrentPage + 1,
			slide: function(event, element) { jQuery("#PagerSummary").html(format(template, [pagerObj.CurrentPage + 1, pagerObj.NumberOfPages, pagerObj.NumberOfResults])); },
			change: function(event, element) { Search(pagerObj.ControlToPage, false, element.value - 1, pagerObj.NumberOfResults); }
		});
		jQuery(".Pager").show();
	} else {
		jQuery(".Pager").hide();
	}
}

/*
* This method gets the next page from the search results.
*/
function GetNextPage() {
	if (pagerObj.NextPage >= pagerObj.NumberOfPages) {
		return;
	}
	Search(pagerObj.ControlToPage, false, pagerObj.NextPage, pagerObj.NumberOfResults, pagerObj.DataParameters);
}

/*
* This method gets the previous page from the search results.
*/
function GetPreviousPage() {
	if (pagerObj.PreviousPage < 0) {
		return;
	}
	Search(pagerObj.ControlToPage, false, pagerObj.PreviousPage, pagerObj.NumberOfResults, pagerObj.DataParameters);
}

/*
* This method is executed by the 'Search' button in the Search Competition screen
*/
function Search(controlName, newSearch, pageNo, numberOfResults, DataParameters) {
	var CurrentSeason =
		($("*[id$='cbCurrentSeasonOnly']").size() <= 0)
			? true
			: GetControlValue("*[id$='cbCurrentSeasonOnly']");

	var getDataMethod = function() {
		var jdataObj = "{'jdata': \"{'ControlName':'" + controlName + "'," +
				"'CompetitionSearchData': {" +
			    "'CompetitionArea':'" + GetControlValue("*[id$='ddlArea']") + "'," +
		        "'CompetitionName':'" + GetControlValue("*[id$='txtCompetitionName']") + "'," +
		        "'PageRequest':'true'," +
		        "'CompetitionType':'" + GetControlValue("*[id$='ddlType']") +
				"','CurrentSeasonOnly':'" + CurrentSeason + "'}," +
				"'ClubSearchData': {" +
		        "'ClubName':'" + GetControlValue("*[id$='txtClubName']") + "'," +
		        "'CurrentSeasonOnly':'" + CurrentSeason + "'," +
		        "'CompetitionID':'" + GetControlValue("*[id$='ddlCompetition']") + "'}," +
				((DataParameters)
					? ("'DataParameters': {" +
				       "'ClubID':'" + DataParameters.ClubID + "'," +
				       "'GroupSetID':'" + DataParameters.GroupSetID + "'," +
			           "'TeamID':'" + DataParameters.TeamID + "'},")
					: "") +
		        "'PlayerSearchData': {" +
		        "'PlayerName':'" + GetControlValue("*[id$='txtPlayerName']") + "'," +
		        "'ClubID':'" + GetControlValue("*[id$='ddlClubs']") + "'}," +
		        "'DisciplineSearchData': {" +
				"'CaseId':'" + GetControlValue("*[id$='hfdCaseId']") + "'," +
				"'PlayerName':'" + GetControlValue("*[id$='_tsPlayerName']") + "'," +
		        "'ClubName':'" + GetControlValue("*[id$='_tsClubName']") + "'," +
		        "'HearingFromDate':'" + GetControlValue("*[id$='_dpFromDate']") + "'," +
				"'HearingToDate':'" + GetControlValue("*[id$='_dpToDate']") + "'}," +
		        "'CurrentPage':'" + ((typeof (pageNo) != 'undefined' && pageNo != null && pageNo != '') ? pageNo : "0") + "'," +
				"'NumberOfResults':'" + ((typeof (numberOfResults) != 'undefined' && numberOfResults != null && numberOfResults != '') ? numberOfResults : "0") + "'}\"}";
		return jdataObj;
	}

	var onBeforeSend = function() {
		//Reveal the 'Please wait' image
		$('#SearchResults').html("<div id='Spinner' class='Spinner'></div>");
		return true;
	}

	var onSuccess = function(rdata) {
		//Load the returned data into the container
		$('#SearchResults').html(rdata);

		//Handle the case when no results are returned
		//There is always at least one div element rendered that contain the viewstate hidden input elmenet
		if ($('#SearchResults').children().length == 1)
			$('#SearchResults').html("<div style='color:#fff; text-align:center;'>No results. <br />Please try to refine your search terms.</div>");

		if (typeof (pagerObj) != "undefined" && pagerObj != null) {
			initializePager(pagerObj);
		}
		
		$('body').height('100%');
	}

	RenderControl(getDataMethod, onBeforeSend, onSuccess);
}

/*
* This method is executed by the 'Clear' button in the Search Competition screen
*/
function ClearSearch(controlName) {
	$("input[type='text']").val('');
	$("input[type='checkbox']").each(function() { this.checked = true; });
	$('select').val('');
	Search(controlName, true);
}

/*
* This method retrieves data from an input element based on its id as formed by a jQuery selector
*/


function GetControlValue(controlID) {
	var ctrl = $(controlID);
	if (typeof (ctrl) != 'undefined' && ctrl != null) {
		if (ctrl.is("input[type='checkbox']"))
			return ctrl.attr("checked");
		else {
			var value = ctrl.val();
			if (value != null && value != 'null') {
				value = value.replace(/'/g, "&quot;");
				return value;
			}
		}
	}
	return '';
}

/*
* This method retrieves Player general Informations
*/

function GetPlayerInfo(PlayerID, controlName, idControlDest) {
	var getDataMethod = function() {
		var jdataObj = "{'jdata': \"{'ControlName':'" + controlName + "'," +
				"'PlayerInfoData': {" +
		        "'PlayerID':'" + PlayerID + "'}"
		        + "" + absolutePath + "}\"}";
		return jdataObj;
	}

	var onBeforeSend = function() {
		//Reveal the 'Please wait' image
		$("#" + idControlDest).html("<div id='Spinner' style='padding: 90px 50px; width: 219px; height:25px;'><div class='Spinner'  style='margin:0 auto;'/></div>");
		return true;
	}

	var onSuccess = function(rdata) {
		//Load the returned data into the container
		$("#" + idControlDest).html(rdata);
	}

	RenderControl(getDataMethod, onBeforeSend, onSuccess);
}

/**
* [Obsolete]
* This method retrieves a query string parameter by it's name
*/
function getQueryStringValueByKey(link, key) {
	return ExtractParameterValueFromUrl(key, link);
}

function ExtractParameterValueFromUrl(key, url) {
	if (!url || !key) return null;

	var queryString = url.substring(url.indexOf("?") + 1, url.length);
	var keyValuePairs = queryString ? queryString.split("&") : [];

	for (var i = 0; i < keyValuePairs.length; i++) {
		var currentKey = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf("="));
		var currentValue = keyValuePairs[i].substring(key.length + 1, keyValuePairs[i].length);
		if (key.toLowerCase() == currentKey.toLowerCase()) {
			return currentValue;
		}
	}

	return null;
}

function DisplayOfficialsFixtures(OfficialID, idControlDest) {
	var getDataMethod = function() {
		var jdataObj = "{'jdata': \"{'ControlName':'OfficialsFixturesList'," +
				"'MatchOfficialInfoData': {" +
		        "'MatchOfficialID':'" + OfficialID + "'}"
		        + "}\"}";
		return jdataObj;
	}

	var onBeforeSend = function() {
		//Reveal the 'Please wait' image
		$("#" + idControlDest).html("<div id='Spinner' class='Spinner' style='margin:109px 90px'></div>");

		$("#" + idControlDest).html("<div id='Spinner' style='padding: 131px 90px;  margin:0 auto; width: auto; height:25px;'><div class='Spinner'  style='margin:0 auto;'/></div>");
		return true;
	}

	var onSuccess = function(rdata) {
		//Load the returned data into the container
		$("#" + idControlDest).html(rdata);
	}

	RenderControl(getDataMethod, onBeforeSend, onSuccess);
}

//Display the official games by team inside "OfficialsGamesByTeam" user control
function DisplayOfficialsGamesByTeam(OfficialID, idControlDest) {
	var getDataMethod = function() {
		var jdataObj = "{'jdata': \"{'ControlName':'OfficialsGamesByTeam'," +
				"'MatchOfficialInfoData': {" +
		        "'MatchOfficialID':'" + OfficialID + "'}"
		        + "}\"}";
		return jdataObj;
	}

	var onBeforeSend = function() {
		$("#" + idControlDest).html("<div id='Spinner' style='padding: 131px 90px;  margin:0 auto; width: auto; height:25px;'><div class='Spinner'  style='margin:0 auto;'/></div>");
		return true;
	}

	var onSuccess = function(rdata) {
		//Load the returned data into the container
		$("#" + idControlDest).html(rdata);
	}

	RenderControl(getDataMethod, onBeforeSend, onSuccess);
}

function GetMatchOfficialsInfos(OfficialID, controlName, idControlDest) {
	var getDataMethod = function() {
		var jdataObj = "{'jdata': \"{'ControlName':'" + controlName + "'," +
				"'MatchOfficialInfoData': {" +
		        "'MatchOfficialID':'" + OfficialID + "'}"
		        + "}\"}";
		return jdataObj;
	}

	var onBeforeSend = function() {
		//Reveal the 'Please wait' image
		$("#" + idControlDest).html("<div id='Spinner' style=' margin:0 auto; padding-top:90px; width:auto; height:25px;'><div class='Spinner'  style='margin:0 auto;'/></div>");
		return true;
	}

	var onSuccess = function(rdata) {
		//Load the returned data into the container
		$("#" + idControlDest).html(rdata);
	}

	RenderControl(getDataMethod, onBeforeSend, onSuccess);
}

function GetMatchOfficialGames(OfficialID, idControlDest) {
	if (OfficialID.length > 0) {
		if ($("#" + idControlDest).css("display") == "none") {
			$("#" + idControlDest).slideToggle("slow");
		}
		DisplayOfficialsFixtures(OfficialID, idControlDest);
		return false;
	}
	return false;
}

function GetMatchOfficialGamesByTeam(OfficialID, idControlDest) {
	if (OfficialID.length > 0) {
		if ($("#" + idControlDest).css("display") == "none") {
			$("#" + idControlDest).slideToggle("slow");
		}
		DisplayOfficialsGamesByTeam(OfficialID, idControlDest);
		return false;
	}
	return false;
}

//displays the profile for player, can be extended for officials easily later. //todo : extend for Others
function DisplayPlayerInfoHover() {
	$(".PlayerHoverProfile").hover(function() {//PlayersList_Name
		var link = $(this).attr("href");
		var playerID = getQueryStringValueByKey(link, "playerID");
		var CompID = getQueryStringValueByKey(link, "CompID");
		var offset = $(this).offset();
		var marginLeft = 100;

		if (playerID.length > 0) {
			GetPlayerInfo(playerID, 'PlayerProfile', 'divPlayerInfos');
		}

		var divPlayerInfos = $('#divPlayerInfos');

		if (divPlayerInfos.length <= 0) {
			$('body').append("<div id='divPlayerInfos' class='playerProfile' style='display: none; background-color: #e0e0e0; width:296px'></div>");
		}

		var popupPositionTop = offset.top - $("#divPlayerInfos").outerHeight(),
			scrollPositionTop = $(window).scrollTop();

		if (popupPositionTop - scrollPositionTop < 0) {
			popupPositionTop = offset.top + $(this).outerHeight() + 10;
		}

		$('#divPlayerInfos').css("top", popupPositionTop + "px")
											.css("left", offset.left + marginLeft + "px")
											.stop()
											.fadeIn(500, function() { $(this).css("opacity", 1) })
											;
	},
					function() {
						$('#divPlayerInfos')
											.stop()
											.css("opacity", 1)
											.fadeOut(800);

					});

	$('#divPlayerInfos').hover(
							function() {
								$(this).stop()
										.fadeIn(500, function() { $(this).css("opacity", 1); })
							},
							 function() {
							 	$(this).stop()
								.fadeOut(800);
							 }
							 );
}

/*
* This method retrieves Player general Informations
*/

function GetTopStatsItem(GroupSetID, TeamID, TopStatItemName, idControlDest) {

	// TopStatsDisplay can be set by the client page to render specific prefences to that page.

	var getDataMethod = function() {
		var jdataObj = "{'jdata': \"{'ControlName':'TopStatsItemControl'," +
				topStatsDisplay +
				"'TopStatsInfoData': {" +
				"'TopStatItemName':'" + TopStatItemName + "'," +
				"'TeamID':'" + TeamID + "'," +
			    "'GroupSetID':'" + GroupSetID + "'}"
		        + "}\"}";
		return jdataObj;
	}

	var onBeforeSend = function() {
		$("#" + idControlDest).html("<div id='Spinner' style=' margin:0 auto; padding-top:90px; width:auto; height:25px;'><div class='Spinner'  style='margin:0 auto;'/></div>");
		return true;
	}

	var onSuccess = function(rdata) {
		//Load the returned data into the container

		rdata = rdata.toString().replace('id="__VIEWSTATE"', 'id="VIEWSTATE2"');
		rdata = rdata.toString().replace('name="__VIEWSTATE"', 'name="VIEWSTATE2"');

		$("#" + idControlDest).html(rdata);

		$("#VIEWSTATE2").remove();
	}

	RenderControl(getDataMethod, onBeforeSend, onSuccess);
}

//Jquery Plugin to get updated innerHTML
(function($) {
	var oldHTML = $.fn.html;

	$.fn.formhtml = function() {
		if (arguments.length) return oldHTML.apply(this, arguments);
		$("input,textarea,button", this).each(function() {
			this.setAttribute('value', this.value);
		});
		$(":radio,:checkbox", this).each(function() {
			if (this.checked) this.setAttribute('checked', 'checked');
			else this.removeAttribute('checked');
		});
		$("option", this).each(function() {
			if (this.selected) this.setAttribute('selected', 'selected');
			else this.removeAttribute('selected');
		});
		return oldHTML.apply(this);
	};

	//optional to override real .html() 
	// $.fn.html = $.fn.formhtml;
})(jQuery);


function DisplayDataByGroup(classname, classDdl) {
	/// <summary>Displays Information regarding Control by group</summary> 
	var $ddlGroup = $('.' + classDdl).eq(0);

	$ddlGroup.change(function() {
		$("." + classname).each(function() {
			$(this).fadeOut('1500');
		});

		$("div[name='" + $ddlGroup.val() + "']." + classname).fadeIn('1500');
	});
}

/**
* Form Guide
*/
var FormGuide = (function() {
	var itself = {};
	itself.revealGroup = function(groupId) {
		jQuery(".SingleFormGuide").each(function() { jQuery(this).css("display", "none"); });
		jQuery("div[name=\"" + groupId + "\"].SingleFormGuide").css("display", "block");
	};
	return itself;
} ());



///
///Form Guide
///
function LoadFormGuide() {
	var direction = "+";
	var leftPosition = 100;
	var PositionScrollFG = 0;
	var SizeScrollFG = 100;

	$('#divKOScrollLeft').click(function() {

		ScrollMatchResultIcons(SizeScrollFG, "+", 1000);
	});

	$('#divKOScrollRight').click(function() {
		ScrollMatchResultIcons(SizeScrollFG, "-", 1000);
	});

	$('[id*=ddlResults]').eq(0).change(function() {
		var selectedValue = this.value;

		if (selectedValue == 'Away') {
			$('.AwayResults').css({ 'visibility': 'visible', 'float': 'left' });
			$('.HomeResults').css({ 'visibility': 'hidden', 'float': 'left' });
		}
		else if (selectedValue == 'Home') {
			$('.HomeResults').css({ 'visibility': 'visible', 'float': 'left' });
			$('.AwayResults').css({ 'visibility': 'hidden', 'float': 'left' });
		}
		else {
			$('.MatchResultIcon').css({ 'display': 'block', 'float': 'left' });
			$('.MatchResultIcon').css({ 'visibility': 'visible', 'float': 'left' });
		}
	});

	function CheckScrollsFG() {
		var position = $('.FixturesResultPanel').eq(0).css('left');
		position = position.replace('px', '');
		if (position > 0) $('#divKOScrollLeft').css('display', 'none');

	}

	function ScrollMatchResultIcons(leftPosition, direction, duration) {
		$('.FixturesResultPanel').each(function() {
			$(this).animate({ left: direction + '=' + leftPosition + 'px' }, (duration) ? duration : 1900
			, null)
		});
	}
}

function DisplayScheduleTable(groupSetId, clubId, roundId, placeholder, baseUrl) {
	var dataFunction = function() {
		var json = "{'jdata': \"{'ControlName':'ScheduleControl', " +
		            "'DisplayParameters':{'ShowPreviousFixtures':'true'," +
						               "  'ShowUpcomingFixtures':'false'," +
						               "  'AbsoluteImagePaths':'true'," +
    					               "  'VirtualFolder':'" + baseUrl + "'," +
						               "  'DDLParameter':'RLC'}," +
    			   "'DataParameters': {" +
    		       "'GroupSetID':'" + groupSetId + "'," +
    		       "'ClubID':'" + clubId + "'," +
    		       "'RoundID':'" + roundId + "'}" +
    		       "}\"}";
		return json;
	};

	var onBeforeSend = function() {
		$("#" + placeholder).html("<div id='Spinner' style='padding: 90px 50px; width: 219px; height:25px;'><div class='Spinner'  style='margin:0 auto;'/></div>");
		return true;
	};

	var onSuccess = function(rdata) {
		$("#" + placeholder).html(rdata);
	};

	RenderControl(dataFunction, onBeforeSend, onSuccess);
}

function DisplayFixturesList(groupSetId, clubId, teamId, roundId, filteredTeamId, placeholder, baseUrl) {
    var dataFunction = function() {
        var json = "{'jdata': \"{'ControlName':'FixturesControl', " +
		            "'DisplayParameters':{'ShowPreviousFixtures':'true'," +
						               "  'ShowUpcomingFixtures':'false'," +
						               "  'AbsoluteImagePaths':'true'," +
    					               "  'VirtualFolder':'" + baseUrl + "'," +
						               "  'DDLParameter':'RLC'}," +
    			   "'DataParameters': {" +
    		       "'GroupSetID':'" + groupSetId + "'," +
    		       "'ClubID':'" + clubId + "'," +
    		       "'TeamID':'" + teamId + "'," +
    		       "'FilteredTeamID':'" + filteredTeamId + "'," +
    		       "'RoundID':'" + roundId + "'}" +
    		       "}\"}";
        return json;
    };

	var onBeforeSend = function() {
		ContentHelper.setContent(placeholder, "<div id='Spinner' style='padding: 90px 50px; width: 219px; height:25px;'><div class='Spinner'  style='margin:0 auto;'/></div>");
		return true;
	};

	var onSuccess = function(rdata) {
		ContentHelper.setContent(placeholder, rdata);
	};

	RenderControl(dataFunction, onBeforeSend, onSuccess);
}

var ContentHelper = (function() {
	var itself = {};
	itself.setContent = function(elementId, content) {
		var element = jQuery("#" + elementId);
		if (element !== null) {
			element.html(content);
		}
	};
	return itself;
} ());

function format(template, values) {
	var result = template;
	for (var i = 0; i < values.length; i++) {
		var temp = result;
		result = temp.replace("{" + i + "}", values[i]);
	}
	return result;
}


/**
* CompetitionDetails specific code
*/
var CompetitionDetails = (function() {
	var itself = {};
	itself.handleSeasonChanged = function(sender) {
		var url = location.href;
		var matches = url.match(/[?&]CompID=[^&]+/i);
		if (matches !== null && matches.length > 0) {
			var competitionSetIdParameter = matches[0];
			var matches2 = competitionSetIdParameter.match(/=[^&]+/i);
			if (matches2 !== null && matches2.length > 0) {
				var replacement = matches[0].replace(/=[^&]+/gi, "=" + sender.value);
				location.href = url.replace(competitionSetIdParameter, replacement);
			}
		} else {
			location.href = url + (url.indexOf("?") > 0 ? "&CompID=" : "?CompID=") + sender.value;
		}
	};
	return itself;
} ());


/**
* TopStats specific code
*/
var TopStatsBackup = (function () {
	var itself = {};
	itself.handleStatsItemChanged = function(sender, groupSetId, teamId) {
		this.loadStatsItem(groupSetId, teamId, sender.value);
	};
	itself.loadStatsItem = function(groupSetId, teamId, currentStatsItemName) {
		GetTopStatsItem(groupSetId, teamId, currentStatsItemName, "TopStatItemNameContent");
	};
	return itself;
} ());

/**
* LeagueTable specific code
*/
var LeagueTable = (function() {
	var itself = {};
	itself.revealGroup = function(groupId) {
		jQuery(".SingleLeagueTable").each(function() { jQuery(this).css("display", "none"); });
		jQuery("div[name=\"" + groupId + "\"].SingleLeagueTable").css("display", "block");
	}
	return itself;
} ());


/**
* Schedule specific code
*/
var Schedule = (function() {
	var itself = {};
	itself.handleItemSelection = function(groupSetId, clubId, selection, baseUrl) {

		this.refreshScheduleTable(groupSetId, clubId, selection, baseUrl);
	};
	itself.refreshScheduleTable = function(groupSetId, clubId, selection, baseUrl) {
		DisplayScheduleTable(groupSetId, clubId, selection, "divScheduleTable", baseUrl);
	};
	return itself;
} ());

/**
* Fixtures specific code
*/
var Fixtures = (function() {
    var itself = {};
    itself.handleItemSelection = function(groupSetId, clubId, teamId, periodsDropDownListId, teamsDropDownListId, fixturesListId, baseUrl) {
        this.refreshFixturesList(groupSetId, clubId, teamsDropDownListId, periodsDropDownListId, teamsDropDownListId, fixturesListId, baseUrl);

    };
    itself.refreshFixturesList = function(groupSetId, clubId, teamId, periodsDropDownListId, teamsDropDownListId, fixturesListId, baseUrl) {
        
        if (typeof (teamsDropDownListId) != "undefined" && teamsDropDownListId != null) {
         
            teamsDropDownList = document.getElementById(teamsDropDownListId);
            var teamIDvalue = teamsDropDownList.value;
        }
        else {
         
            var teamIDvalue = teamId;
        }

        var periodsDropDownList = document.getElementById(periodsDropDownListId);
        DisplayFixturesList(groupSetId, clubId, teamId, periodsDropDownList.value, teamIDvalue, fixturesListId, baseUrl);

    };
    return itself;
} ());

/**
* Language selection specific code
*/
var LanguageSelection = (function() {
	var itself = {};
	itself.handleLanguageSelected = function(languageCode) {
		var url = location.href;
		var matches = url.match(/[?&]lang=[^&]+/i);
		if (matches != null && matches.length > 0) {
			var languageParameter = matches[0];
			var matches2 = languageParameter.match(/=[^&]+/);
			if (matches2 != null && matches2.length > 0) {
				var replacement = matches[0].replace(/=[^&]+/g, "=" + languageCode);
				location.href = url.replace(languageParameter, replacement);
			}
		}
		else {
			location.href = url + (url.indexOf("?") > 0 ? "&lang=" : "?lang=") + languageCode;
		}
	};
	itself.handleLanguageSelectionRequested = function(sender) {
		var divLanguageSelection = document.getElementById("divLanguageSelection");
		if (divLanguageSelection.style.display == "block") {
			divLanguageSelection.style.display = "none";
		} else {
			divLanguageSelection.style.display = "block";
			divLanguageSelection.style.position = "absolute";
			divLanguageSelection.style.float = "right";
			divLanguageSelection.style.top = sender.offsetTop + sender.offsetHeight + 5;
		}
	};
	return itself;
} ());

/**
* Print selection specific code
*/
var PrintSelection = (function() {
    var itself = {};
    /**
    * handler must implement the method execute(mode, data)
    */
    itself.handlePrintSelected = function(selection, handler) {        
        
        var data = selection.split(",");
        handler.execute(data[0], data[1]);
        var divPrintSelection = document.getElementById("divPrintSelection");
        divPrintSelection.style.display = "none";
    };
    itself.handlePrintSelectionRequested = function(sender) {
        var divPrintSelection = document.getElementById("divPrintSelection");
        if (divPrintSelection.style.display === "block") {
            divPrintSelection.style.display = "none";
        } else {
            divPrintSelection.style.display = "block";
            divPrintSelection.style.position = "absolute";
        }
    };
    return itself;
} ());

/**
* Print fixtures specific code
*/
var PrintFixtures = (function() {
    var itself = {};
    /**
    * Must implement an execute(mode, data) method
    */
    
    itself.execute = function(mode, data) {
    
        var url = null;
        if (mode === "TEAM") {
            url = "PrintSchedule.aspx?TeamID=" + data;
        } else if (mode === "COMPETITION") {
            url = "PrintSchedule.aspx?CompID=" + data;
        }
        if (url !== null) {
            if (typeof externalLocation !== "undefined") {
                url = externalLocation + "/" + url;
            }
            var wnd = window.open(url, "__printfixtures");
            if (wnd !== null) {
                wnd.focus();
            }
        }
    };
    return itself;
} ());

//To print the page
function PrintPage() {
	window.print();
	return false;
}
