﻿
//------------------------------------------------------------------

var rowHighlight = true // turn on row highlights
var colHighlight = true // turn off row highlights
var lastRowToHighlight;
var lastRowAvailForHighlight;

function getElement(el) {
  var tagList = new Object
  for (var i = 1; i < arguments.length; i++)
    tagList[arguments[i]] = true
  while ((el!=null) && (tagList[el.tagName]==null))
    el = el.parentElement
  return el
}

function MouseOverHighlight(sRowID,which) 
{
	if (sRowID != '')
	{
		var row = document.getElementById(sRowID);

		if(row != null)
			if (which)
			{
				row.className = "rover"
			}
			else
				if (row == lastRowToHighlight)
					row.className = "rowchecked"
				else
					row.className = ""
	}
}

function clickHighlight(sRowID) 
{
	if (sRowID != '')
	{
		var row = document.getElementById(sRowID);
		if(row != null)
			if (lastRowToHighlight == null)
			{
				lastRowToHighlight = row
				row.className = "rowchecked"
			}
			else
			{
				var Oldrow = lastRowToHighlight;
				Oldrow.className = ""
				lastRowToHighlight = row;
			}
	}
}

function ltrim(s1){
	if(s1 != null)
		return s1.replace( /^\s*/, "" )
}
function rtrim(s2){
	if(s2 != null)
		return s2.replace( /\s*$/, "" );
}
function trim(s3){return rtrim(ltrim(s3)); }


function clickPaymentHistory(sRowID) 
{
	if (sRowID != '')
	{
		var row = document.getElementById(sRowID);		
		var bHighLight = false;
		if(row != null)
			if (lastRowToHighlight == null)
			{
				lastRowToHighlight = row
				row.className = "rowchecked"
				bHighLight = true;
			}
			else
			{
				var Oldrow = lastRowToHighlight;
				Oldrow.className = ""
				if(lastRowToHighlight != row)
				{
					bHighLight=true;					
					lastRowToHighlight = row;
				}
				else
					lastRowToHighlight = null;
			}
			if (bHighLight)
			{
				document.getElementById("InvAmtRecvd").value = document.getElementById("PA" + sRowID).innerHTML;
				document.getElementById("InvPayDate").value = ltrim (rtrim(document.getElementById("PD" + sRowID).innerHTML));
				document.getElementById("LodgementNum").value = document.getElementById("LN" + sRowID).innerHTML;
				document.getElementById("Notes").value = document.getElementById("NO" + sRowID).innerHTML;
		
				var oMethod = document.getElementById("method");
   				var sStr1,sStr2;
				for (var nSelectLoop=0;nSelectLoop< oMethod.length;nSelectLoop++)
				{
					sStr1 = ltrim(rtrim(document.getElementById("PM" + sRowID).innerHTML));
					sStr2 = ltrim(rtrim(oMethod.options[nSelectLoop].text));
					if(sStr1.toUpperCase() == sStr2.toUpperCase())
						oMethod.selectedIndex = nSelectLoop;
				}				
				document.getElementById("HiddenPaymentID").value = sRowID;
				
			}
			else
			{		
				document.getElementById("InvAmtRecvd").value = "";
				document.getElementById("InvPayDate").value = "";
				document.getElementById("LodgementNum").value = "";
				document.getElementById("Notes").value = "";
		
				var oMethod = document.getElementById("method").selectedIndex = 0;
			}
	}
}


	function fnCheckboxSearch(sSearch){
		fnRedirectUpdatedQueryString("salesbook2.asp","Search",sSearch);
	}
	
	function fnSelectCompetition(){
		var oCompetition = document.getElementById("competitions")
		fnRedirectUpdatedQueryString("salesbook2.asp","compid",oCompetition.options[oCompetition.selectedIndex].id);
	}
	
	function fnSelectCompetitionLocation(){
		var oLocation = document.getElementById("CompetitionLocation")
		fnRedirectUpdatedQueryString("todaysfixtures.asp","CompetitionLocationID",oLocation.options[oLocation.selectedIndex].value);
	}
	function fnSelectCompetitionAssociation(){
		var oAssociation = document.getElementById("CompetitionAssociation")
		fnRedirectUpdatedQueryString("todaysfixtures.asp","CompetitionAssociationID",oAssociation.options[oAssociation.selectedIndex].value);
	}

	function fnChangeFixtureDate() {
	    var oFixtureDate = document.getElementById("FixtureDate")
	    fnRedirectUpdatedQueryString("todaysfixtures.asp", "FixtureDate", oFixtureDate.value);
	}

	function fnPopupCalendar(sSource)
{
	var nWinHeight = 150;
	var nWinWidth = 180;
	var sUrl;
	var vResult;
	var sFullDateString;
	var nMonth;
	sUrl = "GenericCalendar.htm"

	fnReturnCoords(document.getElementById(sSource));

	if (screen.availWidth < nXCoord + nWinWidth)
	{
		nXCoord = screen.availWidth - nWinWidth
	}
	if (screen.availHeight < nYCoord + nWinHeight)
		nYCoord = screen.availHeight - nWinHeight

	vResult = showModalDialog(sUrl,null,"dialogHeight:" + nWinHeight + "px;,dialogWidth:" + nWinWidth + "px;status:no;resizable:no;help:no;dialogLeft:" + nXCoord + "px;dialogTop:" + nYCoord + "px")
	 if (vResult != null)
	{
		sFullDateString =	vResult[0] + " " + vResult[1] + " " + vResult[2];

		 switch  (vResult[1])
		 {
			case "January":
				nMonth = 1;
			case "February":
				nMonth = 2;
			case "March":
				nMonth = 3;
			case "April":
				nMonth = 4;
			case "May":
				nMonth = 5;
			case "June":
				nMonth = 6;
			case "July":
				nMonth = 7;
			case "August":
				nMonth = 8;
			case "September":
				nMonth = 9;
			case "October":
				nMonth = 10;
			case "November":
				nMonth = 11;
			case "December":
				nMonth = 12;
		 }
		 var vDate = new Date(sFullDateString);

		if(vResult != null)
			document.getElementById(sSource).value = sFullDateString;

	}
	else sFullDateString = "";
}

	var nXCoord,nYCoord;
	function msieversion()
	{
      var ua = window.navigator.userAgent
      var msie = ua.indexOf ( "MSIE " )
      if ( msie > 0 )
         return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
      else
       return 0
	}

	function fnReturnCoords(oObject)
	{
		var scLeft,scTop;

		if ( msieversion() >= 5 )
		{
			scLeft = window.screenLeft
//or simply, screenLeft
			scTop = window.screenTop
		}
//or simply, screenTop
	   else if ( msieversion() == 4 )
		{
			scLeft = window.event.screenX - window.event.clientX
			scTop = window.event.screenY - window.event.clientY
		}
		nXCoord = null;
		nYCoord = null;
		while(oObject.offsetParent != null)
		{
			nXCoord = nXCoord + oObject.offsetLeft;
			nYCoord = nYCoord + oObject.offsetTop;
			oObject = oObject.offsetParent;
		}
		nXCoord = nXCoord + oObject.offsetLeft + scLeft;
		nYCoord = nYCoord + oObject.offsetTop + scTop;
	}

	function fnToday(sSource){
		var sDate = new Date();
		var sMonthname;
		 switch  (sDate.getMonth())
		 {
			case 0:
				sMonthname = "Jan";
			case 1:
				sMonthname = "Feb";
			case 2:
				sMonthname = "Mar";
			case 3:
				sMonthname = "Apr";
			case 4:
				sMonthname = "May";
			case 5:
				sMonthname = "Jun";
			case 6:
				sMonthname = "Jul";
			case 7:
				sMonthname = "Aug";
			case 8:
				sMonthname = "Sep";
			case 9:
				sMonthname = "Oct";
			case 10:
				sMonthname = "Nov";
			case 11:
				sMonthname = "Dec";
		 }

		document.getElementById(sSource).value = sDate.getDate() + '/' + (sDate.getMonth() + 1) + '/' + sDate.getFullYear();
	}
 	function fnPopupPrinterFriendly()
	{
		var sUrl;
		var result;
		sUrl = "salesbookPrintformat.asp" + document.location.search;
		window.open(sUrl,"","scrollbars=yes,resizable=yes,menubar=yes,width=1028,height=768")
	}

	function fnPayFullAmt()
	{
		document.getElementById("InvAmtRecvd").value = document.getElementById("AmountDue").innerHTML;
		
	}
	
	function fnDeleteInvoice()
	{
		document.getElementById("HiddenDelete").value = 1
	}

//------------------------------------------------------------------	
	function fnUpdateQueryString(sQueryParam,sQueryValue)
	{			
		var sQueryString = document.location.search;
		
		var sQueryStringLength = sQueryString.length;
		var sQueryParamArray = sQueryParam.split("*");
		var sQueryValueArray = sQueryValue.split("*");
		var sQueryValue = "";
		var sHashValue=""; // hash value must be passed as the last param in the sQueryValue - appended to this value using a #
		var nHashIndex; // position in string of #		
	
		for (var nArrayLoop=0;nArrayLoop <sQueryParamArray.length;nArrayLoop++)
		{
			var sQueryParamFlag =  sQueryParamArray[nArrayLoop] + "=";
			var sQueryParamFlagLength = sQueryParamFlag.length;
		
			//Finds the index of the (sQueryParam + "=") from the start of the string
			var sQueryParamIndex = sQueryString.indexOf(sQueryParamFlag);	
	
			//Finds the index of the ampersand to the right of (sQueryParamArray[nArrayLoop] + "=")
			var sAmpersand = sQueryString.indexOf("&",sQueryParamIndex); 
			var sRightOfChangedValue = ""
			
			//Finds the index of the # to the right of (sQueryValueArray[nArrayLoop])
			var nHashIndex = sQueryValueArray[nArrayLoop].indexOf("#",sQueryValueArray[nArrayLoop]); 
			if (nHashIndex != -1)
			{
				sHashValue = sQueryValueArray[nArrayLoop].substring(nHashIndex+1,sQueryValueArray[nArrayLoop].length);
				sQueryValue = sQueryValueArray[nArrayLoop].substring(0,nHashIndex);
			}
			else
				sQueryValue = sQueryValueArray[nArrayLoop];

			// If there is an '&' after the QueryParam then this the string right of the QueryParam 
			// otherwise there is nothing right of the Query Param
			if (sAmpersand > sQueryParamIndex)	
				sRightOfChangedValue =  sQueryString.substring(sAmpersand,sQueryStringLength);
		
			var sChangedValue = sQueryParamArray[nArrayLoop] + "=" + sQueryValue;
			var sLeftOfChangedValue = sQueryString.substring(0,sQueryParamIndex);
			
			if(sQueryString == "")
				if (sQueryValue != "")
					sQueryParamArray[nArrayLoop] = "?" + sQueryParamArray[nArrayLoop] + "=" + sQueryValue;
				else
					sQueryParamArray[nArrayLoop] = "";
			else
				if(sQueryParamIndex == -1)	// sQueryParamArray[nArrayLoop] does not exist in QueryString - thus Append it to existing QueryString
					sQueryParamArray[nArrayLoop] = sQueryString + "&" + sChangedValue;
				else
					if(sQueryValueArray[nArrayLoop] !="")
						sQueryParamArray[nArrayLoop] = sLeftOfChangedValue + sChangedValue + sRightOfChangedValue;
					else
					{						
						if(sAmpersand != -1) //if there is an & to the right of the queryParam - recalculate right of queryParam excluding '&'
							sRightOfChangedValue =  sQueryString.substring(sAmpersand + 1,sQueryStringLength); //Removes the first & after the removed sQueryValue[...]						
						else
						{
							if(sLeftOfChangedValue.indexOf("&",sLeftOfChangedValue.length-1) != -1) //if there is a & at the end of the string 
								sLeftOfChangedValue = sLeftOfChangedValue.substring(0,sLeftOfChangedValue.length-1);			// then remove it ( - shorten the string to cut it out)
						}
						sQueryParamArray[nArrayLoop] = sLeftOfChangedValue + sRightOfChangedValue;   // if the sQueryValue[...] is blank then remove the existing sQueryParam[...] and value from the queryString
					}
			sQueryString = sQueryParamArray[nArrayLoop];			
			sQueryStringLength = sQueryString.length;
		}
		if (sHashValue != "")
			sQueryString += "#" + sHashValue;
		return sQueryString;
	}

	function fnRedirectUpdatedQueryString(sURL,sQueryParam,sQueryValue) {

		if(sURL == "")
			if( document.location.pathname == "/")
				sURL = "/default.asp";		
			else
				sURL = document.location.pathname;
				
        document.location.href = sURL + fnUpdateQueryString(sQueryParam,sQueryValue);
	}
	
    function ajaxManager()
	{
    var args = ajaxManager.arguments;
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
          {
              xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
          }
        catch (e)
          {
              try
                {
                    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
              catch (e)
                {
                    alert("Your browser does not support AJAX!");
                    return false;
                }
              }
    }
	switch (args[0])
		{
		case "load_page":
			if (xmlHttp)
				{
					if(args[3] != "false") // asynchronous(true) - default or synchronous(false)
					{
						xmlHttp.onreadystatechange = function()
						{	
							document.getElementsByTagName("body")[0].style.cursor="wait";
							if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
								{
								document.getElementsByTagName("body")[0].style.cursor="default";
								if(args[2])
									{
										el = document.getElementById(args[2]);
										el.innerHTML = xmlHttp.responseText;				
									}
								}
						}
						xmlHttp.open("GET",args[1]+"&sid=" + Math.random(),true);
						xmlHttp.send(null);
					}
					else
					{
						xmlHttp.open("GET",args[1]+"&sid=" + Math.random(),false);		//Check if asynchronous(true) - default or synchronous(false)
						xmlHttp.send(null);
						if(args[2])
							el = document.getElementById(args[2]);	
							if (el != null)
								el.innerHTML = xmlHttp.responseText;							
					}
				}
			break;
case "fnAddNewTeamContacts":
    if (xmlHttp) {
        xmlHttp.onreadystatechange = function() {
            document.getElementsByTagName("body")[0].style.cursor = "wait";
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                document.getElementsByTagName("body")[0].style.cursor = "default";
                if (args[3]) {
                    el = document.getElementById(args[3]);
                    el.innerHTML = xmlHttp.responseText;
                    //	el.style.display="block";										
                }
                if (args[2] >= 0)
                    ajaxManager(
									'fnAddNewTeamContacts',
									'NewTeamContactsAJAX.asp?Contact='
									+ document.getElementById("ContactsSelect").options[args[2]].innerHTML
									+ "&Email=" + document.getElementById("NewTeamEmailSelect").options[args[2]].innerHTML
									+ "&Mobile=" + document.getElementById("NewTeamMobileSelect").options[args[2]].innerHTML
									+ "&NewTeamID=" + document.getElementById("NewTeamID").value + '&ClientTypeID=1',
									args[2] - 1
									);
                else
                    fnRedirectUpdatedQueryString('payment.asp', 'TeamID*ClientTypeID', document.getElementById("NewTeamID").value + '*1');
            }
        }
        xmlHttp.open("GET", args[1] + "&sid=" + Math.random(), true);
        xmlHttp.send(null);
    }
    break;
		}
	}

	function fnReturnSelection(elementID){
		var oElement = document.getElementById(elementID);		
		return oElement.options[oElement.selectedIndex].value;
	}

	function fnHide(elementID){
		var oElement = document.getElementById(elementID)
		oElement.style.display="none";
	}

	function fnShow(elementID){
		var oElement = document.getElementById(elementID)
		oElement.style.display="block";
	}

	var LastPopupSelected;

	function fnShowPopup(){
		var tempX = 0;
		var tempY = 0;
		var offset = 30;
		var elementBaseCoord;
		var sPopup;
		var e;
		var nLeft;
		var nTop;
		var sPosition;
		var args = fnShowPopup.arguments;				
		var oElement = document.getElementById("StaticPopup");
		var oFullScreen = document.getElementById("fullscreen");
	
		sPopup = args[0];
		if (args[1])
			e = args[1];
		
		if (args[2])
		{
			nLeft = args[2];
			offset = nLeft;
		}
		else
			nLeft = 0;
		
		if(args[3])
			nTop = args[3];
		else
			nTop = 0
			
		if(args[4])
			sPosition = args[4];
		else
			sPosition = 0;		// 0 is relative positioning, 1 is absolute postioning - default is relative
			
		if(LastPopupSelected != null)
			LastPopupSelected.style.display="none";
		LastPopupSelected = oElement;	

		oElement.style.display="block";

		if(e)
		{
			// For non mozilla browsers
			if (document.all) {
			  tempX = event.clientX + document.body.scrollLeft;
			  tempY = event.clientY + document.body.scrollTop;
			} 
			else // For mozilla browsers
			{
			  tempX = e.pageX;
			  tempY = e.pageY;
			}
		}
		tempX -= oFullScreen.offsetLeft;
		tempY -= oFullScreen.offsetTop;
		
		if (tempX < 0){tempX = 0}
		if (tempY < 0){tempY = 0}		
		if (sPosition == 1)	
		{
	        if (nTop < 0){nTop = 0}
		    if (nLeft < 0){nLeft = 0}
			oElement.style.top  = (nTop - document.body.scrollTop) + 'px';
			oElement.style.left = (nLeft - document.body.scrollLeft) + 'px';
		}
		else	
		{
//		    alert("tempY:" + tempY + " nTop:" + nTop + " document.body.scrollLeft:" + document.body.scrollLeft);
			oElement.style.top  = (tempY + nTop - document.body.scrollTop) + 'px';
			oElement.style.left = (tempX + offset - document.body.scrollLeft) + 'px';
		}
		
		if(sPopup != "")
			oElement.innerHTML = "<span>" + sPopup + "</span>";
		elementBaseCoord = tempY + offset + oElement.offsetHeight;
	};

	function fnClosePopup(){
		var oElement = document.getElementById("StaticPopup");
	    oElement.style.display="none";
	};	

	function fnShowAddToSquadPopup(sTeamID,sRRobinID,oEvent){
		var Top = document.getElementById("Scorers" + sRRobinID).offsetTop + document.getElementById("header").offsetHeight;
		//OffsetTop of 'Scorers + sRRobinId is only to top of ContentBody Div, need to add height of header too (Chose to leave out gap between ContentBody and Content)
		var Left = 550;
		fnShowPopup('',oEvent,Left,Top,1);
		ajaxManager(
					'load_page',
					'AddToSquadAJAX.asp?TeamID=' + sTeamID + '&RRobinID=' + sRRobinID,
					'StaticPopup');		
	}
	
	function fnValidateNewPlayer(sRRobinID,sTeamID){
		var sPlayerName = document.getElementById('playername').value;
		var sEmail = document.getElementById('Email').value;
		var sMobile = document.getElementById('Mobile').value;
		var sPlayerPositionID = document.getElementById('PlayerPosition');
		if (sPlayerName.value != "" && sPlayerPositionID.selectedIndex != 0)
		{	
			ajaxManager(
					'load_page',
					'AddToSquadAJAX.asp?RRobinID=' + sRRobinID + '&TeamID=' + sTeamID + '&playername='+ sPlayerName + '&Email='+ sEmail + '&Mobile='+ sMobile + '&PositionID=' + fnReturnSelection('PlayerPosition'),
					'SquadContainer'
						);
			fnClosePopup();
		}
	}
	function ReturnQueryStringValue(sQueryStringParam)
	{
		var sQueryString = document.location.search;
		var sQueryStringValue;
		sQueryString = sQueryString.substring(1,sQueryString.length);					//Removes the leading '?'
		var sQueryParamIndex = sQueryString.indexOf(sQueryStringParam);					//Finds the start of sQueryStringParam
		if (sQueryParamIndex != -1)
		{
			sQueryString = sQueryString.substring(sQueryParamIndex,sQueryString.length);	//sQueryString now starts at sQueryStringParam
			sQueryParamIndex = sQueryString.indexOf("&");									//Finds the trailing '&' - if any
			if (sQueryParamIndex != -1)
				sQueryString = sQueryString.substring(0,sQueryParamIndex);					//sQueryString now starts at sQueryStringParam and 
																							//finishes after it's value						
			sQueryParamIndex = sQueryString.indexOf("=");									//Finds the indexof '=' 
			if (sQueryParamIndex != -1)														//If '=' exists then...
				sQueryStringValue = sQueryString.substring(sQueryParamIndex + 1 ,sQueryString.length);	//Returns value of sQueryStringParam
			else
				sQueryStringValue = "";
		}							
		else						
			sQueryStringValue = "";															//	sQueryStringParam doesn't exist		
																
		return(sQueryStringValue);
	}

					
	function fnIsElementPopulated(sElementID)
	{
		var oElement = document.getElementById(sElementID);
		if (oElement)
		{
			if	(oElement.value != "")
					return true;
				else
					return false; 
		}
		else
			return false;
	}
						
	function fnValidate(sElementID,e)
	{
		var bValidate = false;	//	if bValidate is false then don't validate (this prevents validation occuring after each element has lost focus.)
								//	New Teams should only be validated when the 'Save Registration details' button is pressed.
								//	Existing teams can validate after each element has lost focus - this is because all these elements will be
								//	populated from a previous time when the team registered.		
								
		var sErrorMessage = "";
		var sQueryString ="";
		var sQueryStringValue;
		var sTeamID = ReturnQueryStringValue('TeamID');
		
		if(sTeamID !="")		//Existing team.
			bValidate = true;
		else
			if(sElementID == 'NewTeamSave')			//New Team, but 'Save Registration details' button called validation function
				bValidate = true;
														//Otherwise bValidate remains at false and function is exited.
		
		if(bValidate)
		{
			var registrationElements= new Array(8);
			registrationElements[0]="NameOfTeam";
			registrationElements[1]="UserName";				
			registrationElements[2]="Password";
			registrationElements[3]="KitColours";
			registrationElements[4]="Invoicee";
			registrationElements[5]="BillingAddress";
			registrationElements[6]="marketingMedia";
			registrationElements[7]="othermedia";
				
			var registrationLabels= new Array(8);
			registrationLabels[0]="Team name";
			registrationLabels[1]="UserName";				
			registrationLabels[2]="Password";				
			registrationLabels[3]="Kit Colours";
			registrationLabels[4]="Invoicee";
			registrationLabels[5]="Billing Address";
			registrationLabels[6]="Where did you first hear about us?";
			registrationLabels[7]="The other means of hearing about us";

			for (var x=0; x<8; x++)
			{
				sQueryStringValue = document.getElementById(registrationElements[x]).value;
				sQueryStringValue= sQueryStringValue.replace("&","%26");	//Replaces any instance of '&' with it's hex equivalent 
																			//prevents bugs when stripping querystring to individual values.						
				if(sQueryString == "")
					sQueryString = "?" + registrationElements[x] + "=" + sQueryStringValue
				else
					sQueryString += "&" + registrationElements[x] + "=" + sQueryStringValue
				
				if(x == 6)
				{
					if(sQueryStringValue == 0)
						sErrorMessage += "<label class='ErrorMessage'>" + registrationLabels[x] + "</label>";						
				}
				else
				{
					if(x == 7)
					{
						if(document.getElementById(registrationElements[6]).value == 9)	//Checks to see if marketing media is 'OTHER' - if so then check description of other entered
						{
							if(!(fnIsElementPopulated(registrationElements[x])))
								sErrorMessage += "<label class='ErrorMessage'>" + registrationLabels[x] + "</label>";						
						}
					}
					else
					{
						if(!(fnIsElementPopulated(registrationElements[x])))
							sErrorMessage += "<label class='ErrorMessage'>" + registrationLabels[x] + "</label>";						
					}
				}

			} 				
			//If some of the team info is missing for the NEW team
			if(sErrorMessage != "")	
				sErrorMessage = "<label class='ErrorAlert'>Error: Information missing for</label>" + sErrorMessage;
				
			//Checks to see if Team Name is unique.
			if(document.getElementById("UniqueTeamID").value == 0 && document.getElementById("UniqueTeamID").value != "" && document.getElementById("NameOfTeam").value != "")	
				sErrorMessage += "<label class='ErrorAlert'>Error: Team name not unique</label><label class='ErrorMessage'>Please enter a different Team name</label>";
			
			if(document.getElementById("UniqueLoginID").value != "")	//Will be blank when validating after Teamname Change	
			{
			//Checks to see if Login is unique.
			if(document.getElementById("UniqueLoginID").value == 0 && document.getElementById("UserName").value != ""  && document.getElementById("Password").value != "" )	
				sErrorMessage += "<label class='ErrorAlert'>Error: Password not unique</label><label class='ErrorMessage'>Please enter a different Password</label>";
            }
			sErrorMessage += fnValidateContacts(e);			//New Team - Validate Contacts		
			if(sErrorMessage != "")						//if error message is not blank then data is missing - popup error message!!!
				if(sElementID == 'NewTeamSave')
					fnShowPopup(sErrorMessage,e,650,390,1);
				else
					fnShowPopup(sErrorMessage,e,400,70,1);
			else
			{
				fnClosePopup(); 
				//update Team registration here using AJAX
				if(sTeamID !="")						
				{
					sQueryString = sQueryString + "&TeamID=" + sTeamID;
					ajaxManager(
						'load_page',
						'RegistrationDetailsAJAX.asp' + sQueryString
						);												
				}
				else							
				{
					var oContactsSelect = document.getElementById("ContactsSelect");
					var nContacts = oContactsSelect.options.length -1;
					ajaxManager(
							'fnAddNewTeamContacts',
							'RegistrationDetailsAJAX.asp' + sQueryString + "&competitionid=" + document.getElementById("hiddenNewTeamCompetitionID").value + "&divisiondetailsid=" + document.getElementById("hiddendivision").value + '&ClientTypeID=1',
							nContacts,'newTeamSection'								
							);
				}
			}									
		}
	}
	
	function fnValidateClientRegistration(sElementID,e)
    {
	    var oClientName = document.getElementById("txtInputContact");
	    var oClientMobile = document.getElementById("txtInputPhone");
	    var oClientEmail = document.getElementById("txtInputEmail");
	    var oClientInvoicee = document.getElementById("Invoicee");
	    var oClientBillingAddress = document.getElementById("BillingAddress");
		var oLocation = document.getElementById("CompetitionLocation");
		var sErrorMessage = "";
		var sClientName, sClientMobile, sClientEmail,sClientInvoicee,sClientBillingAddress, nLocationID

		var bValid = false;	//	if bValid is false then don't validate (this prevents validation occuring after each element has lost focus.)
								//	New Registration should only be validated when the 'Save Registration details' button is pressed.
								//	Existing Registrations can validate after each element has lost focus - this is because all these elements will be
								//	populated from a previous time when the team registered.		
								
		var sClientID = ReturnQueryStringValue('TeamID');
		
		
		fnClosePopup();
		if(sClientID !="")		//Existing registration.
			bValid = true;
		else
			if(sElementID == 'NewClientSave')			//New registration, but 'Save Registration details' button called validation function
				bValid = true;
												    //Otherwise bValidate remains at false and function is exited.
	    if (bValid)			
        {
		    if(oClientName.value == "")
		    {
		        bValid = false;		 
		        sErrorMessage += "<label class='ErrorAlert'>Error: Name missing</label><label class='ErrorMessage'>Please enter your name</label>";
		    }
		    else
		        sClientName = oClientName.value;
		    if (!(isMobile(oClientMobile.value)))
            {
		        bValid = false;		 
		        sErrorMessage += "<label class='ErrorAlert'>Error: Mobile number invalid</label><label class='ErrorMessage'>Format should be: [ 08nnnnnnnn ] e.g. 0862233444</label>";
	        }		
	        else
	            sClientMobile = oClientMobile.value;
		    if (!(isEmail(oClientEmail.value)))
            {
		        bValid = false;		 
		        sErrorMessage += "<label class='ErrorAlert'>Error: Email address invalid</label><label class='ErrorMessage'>Format should be: [ name ] @ [ company ] . [ com, ie, .co.uk etc ] e.g. webmaster@astro.ie</label>";
	        }
	        else
	            sClientEmail = oClientEmail.value;
		    if(oClientInvoicee.value == "")
		    {
		        bValid = false;		 
		        sErrorMessage += "<label class='ErrorAlert'>Error: Invoicee missing</label><label class='ErrorMessage'>Please enter the invoicee</label>";
		    }
		    else
		        sClientInvoicee = oClientInvoicee.value;
		    if(oClientBillingAddress.value == "")
		    {
		        bValid = false;		 
		        sErrorMessage += "<label class='ErrorAlert'>Error: Billing address missing</label><label class='ErrorMessage'>Please enter the billing address</label>";
		    }
		    else
		        sClientBillingAddress = oClientBillingAddress.value;
			if(oLocation.selectedIndex == -1 || oLocation.selectedIndex == 0)
			{
				bValid = false;
		        sErrorMessage += "<label class='ErrorAlert'>Error: Location missing</label><label class='ErrorMessage'>Please enter the location you are based in</label>";				
			}
			else
				nLocationID = oLocation.value; 

		    if(sErrorMessage != "")						//if error message is not blank then data is missing - popup error message!!!
	            fnShowPopup(sErrorMessage,e,450,100,1);
	        else  
	        {  
	            if(sClientID != "")
	                ajaxManager('load_page','ClientRegistrationAJAX.asp?clientID=' + sClientID + '&ClientName=' + sClientName + "&ClientMobile=" + sClientMobile + "&ClientEmail=" + sClientEmail + "&ClientInvoicee=" + sClientInvoicee + "&ClientBillingAddress=" + sClientBillingAddress + '&LocationID=' + nLocationID,'newTeamSection');												
                else
	                ajaxManager('load_page','ClientRegistrationAJAX.asp?ClientName=' + sClientName + "&ClientMobile=" + sClientMobile + "&ClientEmail=" + sClientEmail + "&ClientInvoicee=" + sClientInvoicee + "&ClientBillingAddress=" + sClientBillingAddress + '&LocationID=' + nLocationID ,'CustomerDetails');						
			}   
	    }
    }		

					
    function fnValidateLMS(e, lms_id)
    {
        var oLMSAstroTeam = document.getElementById("AstroTeam");
	    var oLMSName = document.getElementById("LMSName");
	    var oLMSMobile = document.getElementById("LMSMobile");
	    var oLMSEmail = document.getElementById("LMSEmail");
	    var bValid = true;
		var sErrorMessage = "";
		var sLMSName, sLMSAstroTeamID, sLMSMobile, sLMSEmail
		if(oLMSName.value == "")
		{
		    bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Team name missing</label><label class='ErrorMessage'>Please enter a valid Team name</label>";
		}
		else
		    sLMSName = oLMSName.value;
		if(oLMSAstroTeam.options[oLMSAstroTeam.selectedIndex].value == "")
		{
		    bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Astro Team missing</label><label class='ErrorMessage'>Please choose the Astro Team you play for</label>";
		}
		else
		    sLMSAstroTeamID = oLMSAstroTeam.options[oLMSAstroTeam.selectedIndex].value;
		if (!(isMobile(oLMSMobile.value)))
        {
		    bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Mobile number invalid</label><label class='ErrorMessage'>Format should be: [ 08nnnnnnnn ] e.g. 0862233444</label>";
	    }		
	    else
	        sLMSMobile = oLMSMobile.value;
		if (!(isEmail(oLMSEmail.value)))
        {
		    bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Email address invalid</label><label class='ErrorMessage'>Format should be: [ name ] @ [ company ] . [ com, ie, .co.uk etc ] e.g. webmaster@astro.ie</label>";
	    }
	    else
	        sLMSEmail = oLMSEmail.value;
	    if (!(bValid))			
	        fnShowPopup(sErrorMessage,e,450,0,1);
	    else  
	    {  
        	ajaxManager('load_page','LMSregistrationAJAX.asp?LMS_ID=' + lms_id + '&LMSName=' + sLMSName + "&LMSAstroTeamID=" + sLMSAstroTeamID + "&LMSMobile=" + sLMSMobile + "&sLMSEmail=" + sLMSEmail,'LMSRegistrationForm','false');												
	        document.getElementById("LMSRegistrationForm").submit();
	    }   
    }		
    
    function fnValidateExistingLMSLogin(e){
        var oEmail = document.getElementById("Email");
        var oContactID = document.getElementById("ContactID");
        var bValid = true;
		
        bValid = fnValidateEmail(oEmail.value,e);  
        if (fnIsElementPopulated('ContactID'))
			bValid = isDigit(oContactID.value);
		else
			bValid = false;        
        if(bValid)
        {
            ajaxManager('load_page','LMSListingsAJAX.asp?ContactID=' + oContactID.value + "&Email=" + oEmail.value + "&LMSAction=login",'LMSLoginForm','false');												            
        }
        else
            fnShowPopup('<label class="ErrorAlert">Error: ID field must be populated with a number</label>',e,350,90,1);
			
    }
    function fnValidateLMSPick()
    {
        var oForm = document.getElementById("LMSFixturesPickForm");
        var nTeamID, nRRobinID;
        var oLMS_ID = document.getElementById("hiddenLMS_ID");
        
        for (i=0;i<oForm.myradio.length;i++)
            if (oForm.myradio[i].checked==true)
            {
                nTeamID = oForm.myradio[i].value;
                nRRobinID = oForm.myradio[i].parentNode.parentNode.id;
                fnHide("LMSFixturesPick");
                ajaxManager('load_page','LMSEditFixturesAJAX.asp?LMSid=' + oLMS_ID.value + "&LMSRRobinID=" + nRRobinID + "&LMSTeamID=" + nTeamID + "&LMSAction=pick");												            
	            fnClosePopup();   
            }
    }

    function fnValidateKeepMePosted(e)
    {
	    var oKMPName = document.getElementById("KeepMePostedName");
	    var oKMPMobile = document.getElementById("KeepMePostedMobile");
	    var oKMPEmail = document.getElementById("KeepMePostedEmail");
		var oKMPLocation = document.getElementById("CompetitionLocation");
	    var bValid = true;
		var sErrorMessage = "";
		
		if(oKMPName.value == "")
		{
		    bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Name missing</label><label class='ErrorMessage'>Please enter your Name</label>";
		}

		if(rtrim(ltrim(oKMPMobile.value)) != '')
			if (!(isMobile(oKMPMobile.value)))
			{
				bValid = false;		 
				sErrorMessage += "<label class='ErrorAlert'>Error: Mobile number invalid</label><label class='ErrorMessage'>Format should be: [ 08nnnnnnnn ] e.g. 0862233444</label>";
			}		
		if (!(isEmail(oKMPEmail.value)))
        {
		    bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Email address invalid</label><label class='ErrorMessage'>Format should be: [ name ] @ [ company ] . [ com, ie, .co.uk etc ] e.g. webmaster@astro.ie</label>";
	    }
		if(oKMPLocation.options[oKMPLocation.selectedIndex].value == 0)	//Nothing selected
		{
			bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Location Missing</label><label class='ErrorMessage'>Please enter the location you are based in</label>";
		}
	    if (!(bValid))			
		{
			fnShowPopup(sErrorMessage,e,450,0,1);
			return false;
		}
	    else  
			return true;
    }		
	
	    function fnValidateFreeAgent(e)
    {
	    var oFreeAgentName = document.getElementById("FreeAgentName");
	    var oFreeAgentMobile = document.getElementById("FreeAgentMobile");
	    var oFreeAgentEmail = document.getElementById("FreeAgentEmail");
	    var oFreeAgentGender = document.getElementById("Gender");
		var oFreeAgentLocation = document.getElementById("CompetitionLocation");
	    var bValid = true;
		var sErrorMessage = "";
		
		if(oFreeAgentName.value == "")
		{
		    bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Name missing</label><label class='ErrorMessage'>Please enter your Name</label>";
		}
		if(oFreeAgentMobile.value != '')
			if (!(isMobile(oFreeAgentMobile.value)))
			{
				bValid = false;		 
				sErrorMessage += "<label class='ErrorAlert'>Error: Mobile number invalid</label><label class='ErrorMessage'>Format should be: [ 08nnnnnnnn ] e.g. 0862233444</label>";
			}		
		if (!(isEmail(oFreeAgentEmail.value)))
        {
		    bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Email address invalid</label><label class='ErrorMessage'>Format should be: [ name ] @ [ company ] . [ com, ie, .co.uk etc ] e.g. webmaster@astro.ie</label>";
	    }
		if(oFreeAgentGender.options[oFreeAgentGender.selectedIndex].value == 0)	//Nothing selected
		{
			bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Gender Missing</label><label class='ErrorMessage'>Please enter your Gender</label>";
		}
		
		if(oFreeAgentLocation.options[oFreeAgentLocation.selectedIndex].value == 0)	//Nothing selected
		{
			bValid = false;		 
		    sErrorMessage += "<label class='ErrorAlert'>Error: Location Missing</label><label class='ErrorMessage'>Please enter the location you are based in</label>";
		}
	    if (!(bValid))
		{
	        fnShowPopup(sErrorMessage,e,450,0,1);
			return false;
		}
	    else  
			return true;
    }		


	function fnShowLMSPickPopup(sLMS_ID){
		fnShowPopup('',null,300,150,1);
		ajaxManager('load_page','LMSEditFixturesAJAX.asp?LMSid=' + sLMS_ID,'StaticPopup');
	}
	
	
	function fnCheckIfUniqueTeamName(){
		var oElement = document.getElementById('NameOfTeam');
		ajaxManager('load_page','UniqueTeamNameAJAX.asp?TeamName=' + oElement.value,'UniqueTeamName','false');
	}										

	function fnCheckIfUniqueLogin(){
		var oUserName = document.getElementById('UserName');
		var oPassword = document.getElementById('Password');
		if(oUserName.value != "" && oPassword.value != "")
		ajaxManager('load_page','UniqueLoginAJAX.asp?UserName=' + oUserName.value + "&Password=" + oPassword.value,'UniqueLogin');
	}										
	function fnCheckIfUniqueClientLogin(){
		var oUserName = document.getElementById('UserName');
		var oPassword = document.getElementById('Password');
		if(oUserName.innerHTML != "" && oPassword.value != "")
		ajaxManager('load_page','UniqueLoginAJAX.asp?UserName=' + oUserName.innerHTML + "&Password=" + oPassword.value,'UniqueLogin');
	}										

	function fnPopulateContactFields(oSelect)
	{
		var sTeamID = ReturnQueryStringValue('TeamID');				// if sTeamID is not blank then it's an existing team.

		var oContactInput = document.getElementById("txtInputContact");
		var oEmailInput = document.getElementById("txtInputEmail");
		var oMobileInput = document.getElementById("txtInputPhone");

		if(sTeamID !="")
		{
			var sRowNum = oSelect.options[oSelect.selectedIndex].value;
			var sContactID = oSelect.options[oSelect.selectedIndex].id;		
			var sContact = oSelect.options[oSelect.selectedIndex].text;
			var oEmail = document.getElementById("Email" + sRowNum);
			var oMobile = document.getElementById("Mobile" + sRowNum);

			oContactInput.value = rtrim(ltrim(sContact));
			oEmailInput.value = rtrim(ltrim(oEmail.value));
			oMobileInput.value = rtrim(ltrim(oMobile.value));
		}
		else
		{
			var sContact = oSelect.options[oSelect.selectedIndex].text;
			var oEmail = document.getElementById("NewTeamEmailSelect");
			var oMobile = document.getElementById("NewTeamMobileSelect");

			oContactInput.value = rtrim(ltrim(sContact));
			oEmailInput.value = rtrim(ltrim(oEmail.options[oSelect.selectedIndex].text));
			oMobileInput.value = rtrim(ltrim(oMobile.options[oSelect.selectedIndex].text));
		}
	}
					
	function fnReplaceWhiteSpaces(str){
		var regExp = /\s+/g;				// \s whitespace \g all instances
		return str.replace(regExp,',');		// replaces all instances of whitespaces with a comma.
	}				
	function isEmail(str)
	{
		 var regXEmail = /^\w+([.-.']\w+)*\@[A-Za-z0-9]+([.-][A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
		 return regXEmail.test(str);
	}
	function isMobile(str)
	{
        var regXMobile = /(08[3-8][0-9]{7})$/;     //Tests for Irish mobile numbers (BUG - Will allow an extra digit for Irish mobiles)
		return regXMobile.test(str);
	}
	function isDigit(str)
	{
        var regX = /[0-9]/;     //Tests for digits only.
		return regX.test(str);
	}

	function fnValidateContactName(str,e){
		if (str == "")
		{
			document.getElementById("ContactNameError").innerHTML="Error: Contact Name missing";
			return false;
		}
		else
		{
			document.getElementById("ContactNameError").innerHTML="";
			return true;
		}
	}		
	function fnValidateEmail(str,e){
		if (!(isEmail(str)) && (str != ""))
		{
			document.getElementById("EmailError").innerHTML="ERROR: Invalid Email<br/><sup>- Format should be: [ name ] @ [ company ] . [ com, ie, .co.uk etc ] e.g. webmaster@astro.ie</sup>";
			return false;
		}
		else
		{
			document.getElementById("EmailError").innerHTML="";
			//If validating contacts in fixtures.asp - then it's via the popup 'Add new Player to Squad' - so we don't want to close this popup	
			return true;
		}
	}		

	function fnValidateMobile(str,e){
		if (!(isMobile(str)) && (str != ""))
		{
			document.getElementById("MobileError").innerHTML="ERROR: Invalid Mobile number<br/><sup>Format should be: [ 08nnnnnnnn ] e.g. 0862233444</sup>";
			return false;
		}
		else
		{
			document.getElementById("MobileError").innerHTML="";
			return true;
		}
	}
						
	function fnValidateContacts(e)
	{
	    var nContactsLoop;
	    var nMinContacts;
		var sErrorMessage = "";
		var sInvalidEmailMessage = "";
		var sInvalidMobileMessage = "";
		var sTeamID = ReturnQueryStringValue('TeamID'); 			// if sTeamID is not blank then it's an existing team.
		
		var sCompetitionAssociationID = ReturnQueryStringValue('CompetitionAssociationID'); //If CompetitionAssociationID = 13 then it's tennis (only check for min 1 contact instead of 3

		if (sCompetitionAssociationID == 13)
		    nMinContacts = 1
		else    
		    nMinContacts = 3
		
		if(sTeamID != "")
		{
			nContactsLoop=0;
			do
			{
				nContactsLoop +=1;
				
				if (!(fnIsElementPopulated("Contact" + nContactsLoop)))		//If Contactname doesn't exist or is empty
				    if (nContactsLoop <= nMinContacts)									//Only display error message if contacts are less than 1 for Tennis, 3 for other sports
				        sErrorMessage = "<label class='ErrorAlert'>Error: Contact Details missing</label><label class='ErrorMessage'>Please enter a minimum of " + nMinContacts + " unique contacts</label>";	
					else
						break;												// if there are at least 3 contacts then exit - validation sufficient!!!
				if (!(fnIsElementPopulated("Email" + nContactsLoop)))		//If Email doesn't exist or is empty
				    if (nContactsLoop <= nMinContacts)
					    sErrorMessage = "<label class='ErrorAlert'>Error: Contact Details missing</label><label class='ErrorMessage'>Please enter a minimum of " + nMinContacts + " unique contacts</label>";
					else
						break;
				else
				{
					var oEmail = document.getElementById("Email" + nContactsLoop);
					if (!(isEmail(oEmail.value)))
						if(sInvalidEmailMessage != '')
							sInvalidEmailMessage += ',' + ' Contact ' + nContactsLoop;
						else
							sInvalidEmailMessage += ' Contact ' + nContactsLoop;
				}
				if (!(fnIsElementPopulated("Mobile" + nContactsLoop)))		//If Mobile doesn't exist or is empty
				    if (nContactsLoop <= nMinContacts)
				        sErrorMessage = "<label class='ErrorAlert'>Error: Contact Details missing</label><label class='ErrorMessage'>Please enter a minimum of " + nMinContacts + " unique contacts</label>";
					else
						break;
				else
				{
					var oMobile = document.getElementById("Mobile" + nContactsLoop);
					if(!(isMobile(oMobile.value)))
						if(sInvalidMobileMessage != '')
							sInvalidMobileMessage += ',' + ' Contact ' + nContactsLoop;
						else
							sInvalidMobileMessage += ' Contact ' + nContactsLoop;
				}
			}
			while(fnIsElementPopulated("Contact" + nContactsLoop))
			if( sInvalidEmailMessage != "")
			{
				sInvalidEmailMessage = "<label class='ErrorAlert'>Error: Invalid Email for" + sInvalidEmailMessage + ".</label><label class='ErrorMessage'>Format should be: [ name ] @ [ company ] . [ com, ie, .co.uk etc ] </label>e.g. webmaster@astro.ie"
				sErrorMessage += sInvalidEmailMessage;
			}
			if( sInvalidMobileMessage != "")
			{
				sInvalidMobileMessage = "<label class='ErrorAlert'>Error: Invalid Mobile number for" + sInvalidMobileMessage + ".</label><label class='ErrorMessage'>Format should be: [ 08nnnnnnnn ]</label>e.g. 0862233444"
				sErrorMessage += sInvalidMobileMessage;
			}
								
		}
		else
		{
			var nContactsCount =0;
			var nNumContacts = document.getElementById("ContactsSelect").length;
			if (nNumContacts < nMinContacts)
			    sErrorMessage = "<label class='ErrorAlert'>Error: Contact Details missing</label><label class='ErrorMessage'>Please enter a minimum of " + nMinContacts + " unique contacts</label>";	
			else
				{
					do
					{
						if(document.getElementById("NewTeamEmailSelect").options[nContactsCount].text == "")
						    sErrorMessage = "<label class='ErrorAlert'>Error: Contact Details missing</label><label class='ErrorMessage'>Please enter a minimum of " + nMinContacts + " unique contacts</label>";	
						if(document.getElementById("NewTeamMobileSelect").options[nContactsCount].text == "")
						    sErrorMessage = "<label class='ErrorAlert'>Error: Contact Details missing</label><label class='ErrorMessage'>Please enter a minimum of " + nMinContacts + " unique contacts</label>";	
						nContactsCount +=1;
					}
					while ((nContactsCount < nNumContacts) && (sErrorMessage =""));
				}			
		}
		return sErrorMessage;

}	
	 
	 function fnLuhnCheck(nNumber){ 
        var i, sum, weight;
        sum = 0;
        for(i=0;i<nNumber.length - 1;i++)
        {
            weight = nNumber.substr(nNumber.length - (i+2),1)*(2-(i%2));
            sum += ((weight <10)?weight:(weight-9));
        }
        if (parseInt(nNumber.substr(nNumber.length -1)) == ((10-sum%10)%10))
            return true;
        else
            return false;
    }
    
    function isCVNnumber(str)
	{
		 var regXNumber = /[0-9]{3}/;
		 var bResult = regXNumber.test(str);
		 if(bResult)
		    return bResult;
		 else
		    return false;
	}					
	function isValidCardholder(str){
	    var regXCardholder = /[A-Za-z0-9]\s/;
		var bResult = regXCardholder.test(str);
		 if(bResult)
		    return bResult;
		 else
		    return false;
	}
	
	function fnValidatePaymentInfo(sAccount){
	    var cardnumber = document.getElementById("cardnumber").value;
	    var cardholder = document.getElementById("cardholder").value;
	    var expMonth = document.getElementById("ExpMonth");
	    var expMonthValue = expMonth.options[expMonth.selectedIndex].id;
	    var expYear = document.getElementById("ExpYear");
	    var expYearValue = expYear.options[expYear.selectedIndex].id;
	    var expDate = new Date();
	    var currentDate = new Date();
        var currentDateValue = new Date();
	    var bValid = true;
	    var bErrorMessage = "<label class='ErrorAlert'>Error</label>";
	    
	    var oForm = document.getElementById("sslForm")
	    
	    expDate.setFullYear(expYearValue,expMonthValue - 1,1);
	    currentDateValue = currentDate.setFullYear(currentDate.getFullYear(),currentDate.getMonth(),1);
	    if(!(fnLuhnCheck(cardnumber)))
	    {
	        bValid = false;
	        bErrorMessage += "<p>Incorrect Card number</p>"
	    }
        if (sAccount == "CREDIT")
        {    
	        var cvn = document.getElementById("cvn").value;
    	    if(!(isCVNnumber(cvn)))
	        {   
	            bValid = false;
	            bErrorMessage += "<p>Incorrect Security Code</p>"
	        }
	     }
	    if(currentDateValue > expDate)
	    {   
	        bValid = false;
	        bErrorMessage += "<p>Expiry Date must be in the future</p>"
	    }
	    if(!(isValidCardholder(cardholder)))
	    {   
	        bValid = false;
	        bErrorMessage += "<p>Cardholder's name must be at least 2 words</p>"
	    }
	    
	    if (!bValid)
	        fnShowPopup(bErrorMessage,null,400,20,1);
	    else
	        document.getElementById("sslForm").submit();   
	 
	}
	
	
	function fnEditNewTeamContact(sAction)
	{
		var oContactInput = document.getElementById("txtInputContact");
		var oEmailInput = document.getElementById("txtInputEmail");
		var oMobileInput = document.getElementById("txtInputPhone");

		var oContactsSelect = document.getElementById("ContactsSelect");
		var oEmailSelect = document.getElementById("NewTeamEmailSelect");
		var oMobileSelect = document.getElementById("NewTeamMobileSelect");
		var nOptionIndex;
		
		if (sAction=="Add")
		{
			nOptionIndex = oContactsSelect.options.length;	// this returns the number of elements in the select - the index is zero based, so this number is the index of the new element.
			oContactsSelect.options[nOptionIndex]=new Option(oContactInput.value,nOptionIndex+1);	//First Option param is Text displayed in element, second param is value
			oEmailSelect.options[nOptionIndex]=new Option(oEmailInput.value,nOptionIndex+1);	
			oMobileSelect.options[nOptionIndex]=new Option(oMobileInput.value,nOptionIndex+1);	
		}
		if (sAction=="Edit")
		{
			nOptionIndex = oContactsSelect.selectedIndex;	
			oContactsSelect.options[nOptionIndex].text = oContactInput.value;	
			oEmailSelect.options[nOptionIndex].text = oEmailInput.value;	
			oMobileSelect.options[nOptionIndex].text = oMobileInput.value;	
		}
		if (sAction=="Delete")
		{
			nOptionIndex = oContactsSelect.selectedIndex;
			oContactsSelect.options[nOptionIndex]= null;	
			oEmailSelect.options[nOptionIndex] = null;	
			oMobileSelect.options[nOptionIndex] = null;	
		}	

		oContactInput.value = "";		//Clears input fields after contacts have been edited.
		oEmailInput.value = "";
		oMobileInput.value = "";
	}

	function fnUpdateDBContacts()
	{
		var args = fnUpdateDBContacts.arguments;
		var oContactsSelect = document.getElementById("ContactsSelect");
		var oContactInput = document.getElementById("txtInputContact");
		var oEmailInput = document.getElementById("txtInputEmail");
		var oMobileInput = document.getElementById("txtInputPhone");
		var oSelectedContactID = document.getElementById("hiddenSelectedContact");
	
		var bValid=false;
		var sCompetitionAssociationID = ReturnQueryStringValue('CompetitionAssociationID'); 			// if sCompetitionAssociationID = 13 then it's tennis, only check if there is at least 1 contact instead of 3

		var nMinContacts;

		if (sCompetitionAssociationID == 13)
		    nMinContacts = 1
		else
		    nMinContacts = 3
		
		
		var sTeamID = ReturnQueryStringValue('TeamID');				// if sTeamID is not blank then it's an existing team.
																	// args[0] is the event argument			
		if(fnValidateContactName(oContactInput.value,args[0]))		// If contact name is not blank then check email otherwise popup error message for contact name
			if(fnValidateEmail(oEmailInput.value,args[0]))			//If email is valid then check mobile - otherwise popup error message for email.
				if(fnValidateMobile(oMobileInput.value,args[0]))		// if mobile is valid then both email and mobile are valid - ready to update database.
					bValid= true;
		
		if(bValid)
		{
			switch (args[1])
			{
			case "0":			
				if(sTeamID != "")
					ajaxManager(	//Add to Database						
							'load_page',
							'RegistrationDetailsAJAX.asp?TeamID=' + sTeamID + '&ContactName=' + oContactInput.value + '&Email=' + oEmailInput.value + '&Mobile=' + oMobileInput.value + '&Action=Add',
							'Contacts'
								);
				else
					fnEditNewTeamContact("Add");
				break;
			case "1":			//Edit to Database
				if(sTeamID != "")
					ajaxManager(
							'load_page',
							'RegistrationDetailsAJAX.asp?TeamID=' + sTeamID + '&ContactID='+ oContactsSelect.options[oContactsSelect.selectedIndex].id + '&ContactName=' + oContactInput.value + '&Email=' + oEmailInput.value + '&Mobile=' + oMobileInput.value + '&Action=Edit',
							'Contacts'
								);
				else
					fnEditNewTeamContact("Edit");
				break;
			case "2":			//Delete from Database
			    if (oContactsSelect.options.length >= nMinContacts + 1 )	//Checks to see if there are more than 1 contact for tennis, 3 for other sports - if so proceed with 'delete'
					if(sTeamID != "")
						ajaxManager(
								'load_page',
								'RegistrationDetailsAJAX.asp?TeamID=' + sTeamID + '&ContactID='+ oContactsSelect.options[oContactsSelect.selectedIndex].id + '&Action=Delete',
								'Contacts'
									);
					else
						fnEditNewTeamContact("Delete");
				else
					fnShowPopup('<label class="ErrorAlert">Unable to Delete</label><label class="ErrorMessage">A minimum of ' + nMinContacts + ' contacts required</label>',args[0],450,175,1);
				break;
			}
		}
	}

	function fnPostCompetitionID(CompetitionID,CompetitionLocationID){
		var oElement = document.getElementById("hiddencompetition");
		oElement.value = CompetitionID;
		oCompetitionForm = document.getElementById("competitionForm")
		oCompetitionForm.action = "competitions.asp" + fnUpdateQueryString("CompetitionLocationID",CompetitionLocationID);
		oCompetitionForm.submit();
	}
	
	function fnPostSignUp(sUrl){
		var oForm = document.getElementById("signupForm")
		oForm.action = sUrl + document.location.search;
		oForm.submit();
	}
	function fnPostTeamSummary(sQueryString,sTeamSummaryID){
		var oForm = document.getElementById("TeamSummaryForm")
		var oElement = document.getElementById("TSummaryID")
		oElement.value = sTeamSummaryID;
		oForm.action = "TeamSummary.asp" + sQueryString;
		oForm.submit();
	}
	function fnGotoNewCompetitions(sCompetitionID,sCompetitionLocationID){
		if(ReturnQueryStringValue('TeamID') != "")
			fnPostCompetitionID(sCompetitionID,sCompetitionLocationID);
		else
			fnRedirectUpdatedQueryString("competitions.asp","CompetitionID*CompetitionLocationID",sCompetitionID + "*" + sCompetitionLocationID);
	}

	function fnPostGlobalinfo(){
		var args = fnPostGlobalinfo.arguments;				

/*
	args[0] is competitionid
	args[1] is locationid
	args[2] is divisiondetailsid
	args[3] is destination
	args[4] is teamsummaryID -- Optional
	
*/
		var oCompetition = document.getElementById("globalcompetitionid");
		var oLocation = document.getElementById("globalcompetitionlocationid");
		var oDivision = document.getElementById("globaldivisiondetailsid");
		
		var oForm = document.getElementById("globalinfoForm");
		
		if (args[4])
		{
			var oTeamSummaryID = document.getElementById("TSummaryID");
			oTeamSummaryID.value = args[4];
		}	
		
		oCompetition.value = args[0];
		oLocation.value = args[1];
		oDivision.value = args[2];
		oForm.action = args[3] + document.location.search;
		oForm.submit();	
	}

	function fnViewDivisionInfo(competitionid,locationid,divisiondetailsid,destination){
		if(ReturnQueryStringValue('TeamID') != "")
			fnPostGlobalinfo(competitionid,locationid,divisiondetailsid,destination)
		else
			fnRedirectUpdatedQueryString(destination,"CompetitionID*CompetitionLocationID*DivisionDetailsID",competitionid + "*" + locationid + "*" + divisiondetailsid);
	    document.getElementById("LeagueMenu").style.display= "none";
	}
	
	function fnLeagueMenu(sCompetitionAssociationID,sCompetitionLocationID)
	{
	    ajaxManager('load_page','LeagueMenuAJAX.asp?CompetitionAssociationID=' + sCompetitionAssociationID + '&CompetitionLocationID=' + sCompetitionLocationID,'LeagueCompetitions');
	}
	
	function fnShowLeagueMenu(){
	    document.getElementById('LeagueMenu').style.display="block";
	}
	function fnHideLeagueMenu(){
	    document.getElementById('LeagueMenu').style.display="none";
	}
    function fnShowTermsPopup(){
        var oTerms = document.getElementById("termsData");
        var sTerms = oTerms.innerHTML;
        fnShowPopup(sTerms,null,0,150);
    }
	
	function fnShowMarketingMediaPopup(){
		var oMarketingMedia = document.getElementById("MarketingMediaPopup");
        var sMarketingMedia = oMarketingMedia.innerHTML;
        fnShowPopup(sMarketingMedia,null,200,350);

	}
    function fnPaymentMethodEnabled(){
        var oTermsCheck = document.getElementById("termsCheck");
        var len = document.paymentmethodform.RadioPaymentType.length;
        if(oTermsCheck.checked)
            for (i = 0; i <len; i++) 
                document.paymentmethodform.RadioPaymentType[i].disabled=false;
        else
        {
            for (i = 0; i <len; i++) 
                document.paymentmethodform.RadioPaymentType[i].disabled=true;
            document.getElementById("secureServerBtn").style.display = "none";
        }
    }
    
	function fnProceedToSecurePayment(sAction){
        var oTermsCheck = document.getElementById("termsCheck");
		if (sAction=="true")
			if(oTermsCheck.checked)
				document.getElementById("secureServerBtn").style.display = "block";
			else
				document.getElementById("secureServerBtn").style.display = "none";
		else		
			document.getElementById("secureServerBtn").style.display = "none";	//if not true then remove button from display.
    }
	
	function fnAddtoBasket(nMerchandiseID,nPrice,nVatRate,bSizingExists)
	{
		var selectQuantity = document.getElementById("selectQuantity");
		if(bSizingExists == 1)
		{
			var selectSize = document.getElementById("selectSize");
			ajaxManager('load_page','BasketAJAX.asp?MerchandiseID=' + nMerchandiseID + 
						'&SizeID=' + selectSize.options[selectSize.selectedIndex].value + 
						'&quantity=' + selectQuantity.options[selectQuantity.selectedIndex].value + 
						'&Price=' + nPrice +
						'&VatRate=' + nVatRate +
						'&action=add','BasketList');
		}
		else
			ajaxManager('load_page','BasketAJAX.asp?MerchandiseID=' + nMerchandiseID + 
						'&SizeID=0' + 
						'&quantity=' + selectQuantity.options[selectQuantity.selectedIndex].value + 
						'&Price=' + nPrice +
						'&VatRate=' + nVatRate +
						'&action=add','BasketList');
	}
	
	function fnAlterBasket(teamid,merchandiseID,sizeID,quantity)
	{
		if(quantity == 0)
			ajaxManager('load_page','BasketAJAX.asp?TeamID=' + teamid + '&MerchandiseID=' + merchandiseID + '&SizeID=' + sizeID + '&quantity=' + quantity + '&action=delete','MerchandiseTable','false');
		else	
			ajaxManager('load_page','BasketAJAX.asp?TeamID=' + teamid + '&MerchandiseID=' + merchandiseID + '&SizeID=' + sizeID + '&quantity=' + quantity + '&action=edit','MerchandiseTable','false');

		fnUpdateDueTotal(teamid);	
	} 
	
	
	
	

	function fnUpdateDueTotal(nTeamID)
	{
		var nInvoicedAstroFeesDue, nNonInvoicedRefTotal, nHiddenInvoicedAstroAmt, nHiddenInvoicedRefAmt
		var oTotalPayable = document.getElementById("totalPayable");
		var oNonInvoicedAstroFeesDue = document.getElementById("NonInvoicedAstroFeesDue");
		var oNonInvoicedRefTotal = document.getElementById("NonInvoicedRefTotal");
		var oHiddenInvoicedAstroAmt = document.getElementById("HiddenInvoicedAstroAmt");
		var oHiddenInvoicedRefAmt = document.getElementById("HiddenInvoicedRefAmt");
		
		if(oNonInvoicedAstroFeesDue == null)
			nInvoicedAstroFeesDue = 0;
		else
			nInvoicedAstroFeesDue = parseFloat(oNonInvoicedAstroFeesDue.innerHTML);
		if(oNonInvoicedRefTotal == null)
			nNonInvoicedRefTotal = 0;
		else
			nNonInvoicedRefTotal = parseFloat(oNonInvoicedRefTotal.innerHTML);
		if(oHiddenInvoicedAstroAmt == null)
			nHiddenInvoicedAstroAmt = 0;
		else
			nHiddenInvoicedAstroAmt = parseFloat(oHiddenInvoicedAstroAmt.value);
		if(oHiddenInvoicedRefAmt == null)
			nHiddenInvoicedRefAmt = 0;
		else
			nHiddenInvoicedRefAmt = parseFloat(oHiddenInvoicedRefAmt.value);
		
		
		var nNonMerchandiseFees = nInvoicedAstroFeesDue + nNonInvoicedRefTotal + nHiddenInvoicedAstroAmt + nHiddenInvoicedRefAmt;

		ajaxManager('load_page','BasketAJAX.asp?TeamID=' + nTeamID + '&NonMerchandiseFees=' + nNonMerchandiseFees +'&action=UpdateTotal','totalPayable','false');

	}
	

	function getCardType(sCard)
	{
		var sDiscount,sAstroAmount,sRefAmount;
		switch (sCard)
		{
		case 'DEBIT':			    
			if(document.getElementById("NonInvoicedAstroFeesDue")!= null) //If there is a non-invoiced competition then the 'discount' field exists
			{
			//Deduct 10 Euro off amount if paying by debit card.
				document.getElementById("discount").innerHTML = "8.81";
				document.getElementById("subtotal").innerHTML = (document.getElementById("cost").innerHTML - document.getElementById("discount").innerHTML).toFixed(2);
				document.getElementById("vatamount").innerHTML = (document.getElementById("subtotal").innerHTML * (document.getElementById("vatRate").value)/100).toFixed(2);
				document.getElementById("NonInvoicedAstroTotal").innerHTML = (parseFloat(document.getElementById("subtotal").innerHTML) + parseFloat(document.getElementById("vatamount").innerHTML)).toFixed(2);
				document.getElementById("NonInvoicedAstroFeesDue").innerHTML = (parseFloat(document.getElementById("subtotal").innerHTML) + parseFloat(document.getElementById("vatamount").innerHTML)).toFixed(2);
				document.getElementById("AUTO_SETTLE_FLAG").value ="1";
				document.getElementById("ACCOUNT").value ="DEBIT";							
				sDiscount =8.81;
				document.getElementById("secureServerBtn").style.display = "block";
			}
			else                 					    
				sDiscount =0;
			document.getElementById("AUTO_SETTLE_FLAG").value ="1";
			document.getElementById("ACCOUNT").value ="DEBIT";							
			document.getElementById("secureServerBtn").style.display = "block";
			break;
		case 'CREDIT':
			if(document.getElementById("NonInvoicedAstroFeesDue")!= null) //If there is a non-invoiced competition then the 'discount' field exists
			{
				document.getElementById("discount").innerHTML = "0.00";
				document.getElementById("subtotal").innerHTML = document.getElementById("cost").innerHTML;
				document.getElementById("vatamount").innerHTML = (document.getElementById("subtotal").innerHTML * (document.getElementById("vatRate").value)/100).toFixed(2);
				document.getElementById("NonInvoicedAstroTotal").innerHTML = (parseFloat(document.getElementById("subtotal").innerHTML) + parseFloat(document.getElementById("vatamount").innerHTML)).toFixed(2);
				document.getElementById("NonInvoicedAstroFeesDue").innerHTML = (parseFloat(document.getElementById("subtotal").innerHTML) + parseFloat(document.getElementById("vatamount").innerHTML)).toFixed(2);
			}
			document.getElementById("AUTO_SETTLE_FLAG").value ="1";
			document.getElementById("ACCOUNT").value ="CREDIT";
			sDiscount =0;
			document.getElementById("secureServerBtn").style.display = "block";
			break;
		case 'CHEQUE':
			if(document.getElementById("NonInvoicedAstroFeesDue")!= null) //If there is a non-invoiced competition then the 'discount' field exists
			{
				document.getElementById("discount").innerHTML = "0.00";
				document.getElementById("subtotal").innerHTML = document.getElementById("cost").innerHTML;
				document.getElementById("vatamount").innerHTML = (document.getElementById("subtotal").innerHTML * (document.getElementById("vatRate").value)/100).toFixed(2);
				document.getElementById("NonInvoicedAstroTotal").innerHTML = (parseFloat(document.getElementById("subtotal").innerHTML) + parseFloat(document.getElementById("vatamount").innerHTML)).toFixed(2);
				document.getElementById("NonInvoicedAstroFeesDue").innerHTML = (parseFloat(document.getElementById("subtotal").innerHTML) + parseFloat(document.getElementById("vatamount").innerHTML)).toFixed(2);
			}   
			document.getElementById("AUTO_SETTLE_FLAG").value ="0";
			document.getElementById("ACCOUNT").value ="CHEQUE";
			sDiscount =0;
			document.getElementById("secureServerBtn").style.display = "none";
			break;
		}
		if(document.getElementById("NonInvoicedAstroFeesDue")!= null) //If there is a non-invoiced competition then the 'discount' field exists
			sAstroAmount = parseFloat(document.getElementById("HiddenInvoicedAstroAmt").value) + parseFloat(document.getElementById("NonInvoicedAstroFeesDue").innerHTML);
		else
			sAstroAmount = parseFloat(document.getElementById("HiddenInvoicedAstroAmt").value);

		if(document.getElementById("NonInvoicedRefFeesDue")!= null) 
			sRefAmount = parseFloat(document.getElementById("HiddenInvoicedRefAmt").value) + parseFloat(document.getElementById("NonInvoicedRefFeesDue").innerHTML);
		else
			sRefAmount = parseFloat(document.getElementById("HiddenInvoicedRefAmt").value) 


		if(document.getElementById("HiddenMerchandiseAmt") != null)
			document.getElementById("totalAstroPayable").innerHTML = (parseFloat(document.getElementById("HiddenMerchandiseAmt").value) + parseFloat(sAstroAmount)).toFixed(2);
		else
			document.getElementById("totalAstroPayable").innerHTML = (parseFloat(sAstroAmount) - parseFloat(document.getElementById("hiddenAstroTopUpCredit").value)/100).toFixed(2);
		document.getElementById("totalRefPayable").innerHTML = (parseFloat(sRefAmount) - parseFloat(document.getElementById("hiddenRefTopUpCredit").value)/100).toFixed(2);

		ajaxManager("load_page","paymenthistoryAJAX.asp?AstroFeesAmount=" + sAstroAmount + "&RefereeFeesAmount=" + sRefAmount + "&Discount=" + sDiscount,"hashcalc");
	}
	
	function fnGotoNewsArticle(nNewsID){
		var oForm = document.getElementById("newsArticlesForm")
		var oElement = document.getElementById("hiddenNewsID")
		oElement.value = nNewsID;
/*		if(document.location.search == "")
			oForm.action = "news.asp";
		else	
		{
			oForm.action = "news.asp" + document.location.search;
		}
*/		oForm.submit();
	}

	function fnGenerateLink(sPage){
		var sUrl;
		var sQuerystring = document.location.search;
		
		if(sQuerystring !="")
			sUrl = sPage + sQuerystring;
		else
			sUrl = sPage;
		document.location.href= sUrl;
		return (document.location.href);
	}
	
	function fnReturnPopupData(nPopup){
	
		var sUrl;
		
		    sUrl = "<a id='Close' class='imgclose' href='javascript:fnHide(&quot;StaticPopup&quot;);'><img src='images/close.gif' alt='Close Window'/></a>";
			if(nPopup == 1)
			{
				if(document.location.search == "")
					sUrl+= "<a id='kitStorePopup' href='shoplist.asp'><img src='images/Visitall4sport.gif'/></a>";
				else	
					sUrl+= "<a  id='kitStorePopup' href='shoplist.asp" + document.location.search + "'><img src='images/kitstoresplash.gif'/></a>";
			}
			if(nPopup == 2)
					sUrl+= "<br/><h3>Note: This page is for new customers only</h3><h3>Existing customers - please use the login facility on the left.</h3>";
		return sUrl;	
	}
	
		function fnSelectAll()
	{
		var ob = document.getElementById("Players");
	 	for (var i = 0; i < ob.options.length; i++) 
			ob.options[ i ].selected=!(ob.options[ i ].selected);
	}

	function fnUseEmailTemplates()
	{
		var oTemplate = document.getElementById("EmailTemplate");
		var oMailSubject = document.getElementById("subject");
		var oMailMessage = document.getElementById("messageContent");
		
		oMailSubject.value = oTemplate.options[oTemplate.selectedIndex].innerHTML;
		oMailMessage.value = oTemplate.options[oTemplate.selectedIndex].value;
		tinyMCE.activeEditor.setContent(oTemplate.options[oTemplate.selectedIndex].value, {format : 'raw'});

	}
	
	function fnSaveEmailTemplate(sTeamID)
	{
		var oTemplate = document.getElementById("EmailTemplate");
		var oMailSubject = document.getElementById("subject");
		var nEmailTemplateID;
	
		if(oTemplate.selectedIndex == -1)
			nEmailTemplateID = ""
		else
			nEmailTemplateID = oTemplate.options[oTemplate.selectedIndex].id;

		ajaxManager('load_page','EmailTemplatesAJAX.asp?Teamid=' + sTeamID + '&EmailTemplateID=' + nEmailTemplateID + "&Subject=" + oMailSubject.value + "&Message=" + tinyMCE.activeEditor.getContent() + '&Action=Save','templateContainer');
	}	
	
	function fnDeleteEmailTemplate(sTeamID)
	{
		var oTemplate = document.getElementById("EmailTemplate");
		var nEmailTemplateID = oTemplate.options[oTemplate.selectedIndex].id;
		
		ajaxManager('load_page','EmailTemplatesAJAX.asp?Teamid=' + sTeamID + '&EmailTemplateID=' + nEmailTemplateID + '&Action=Delete','templateContainer');
	}	
	
	
	function fnUseSMSTemplates()
	{
		var oTemplate = document.getElementById("smsTemplate");
		var oSubject = document.getElementById("subject");		
		var oMessage = document.getElementById("messageContent");
		
		oSubject.value = oTemplate.options[oTemplate.selectedIndex].innerHTML;
		oMessage.value = oTemplate.options[oTemplate.selectedIndex].value;
	}
	
	function fnSaveSMSTemplate(sTeamID)
	{
		var oTemplate = document.getElementById("smsTemplate");
		var oSubject = document.getElementById("subject");
		var oMessage = document.getElementById("messageContent");		
		var nSMSTemplateID; 
	
		if(oTemplate.selectedIndex == -1)
			nSMSTemplateID = ""
		else
			nSMSTemplateID = oTemplate.options[oTemplate.selectedIndex].id;
	
		ajaxManager('load_page','smsTemplatesAJAX.asp?Teamid=' + sTeamID + '&smsTemplateID=' + nSMSTemplateID + "&Subject=" + oSubject.value + "&Message=" + oMessage.value + '&Action=Save','templateContainer');
	}	
	
	function fnDeleteSMSTemplate(sTeamID)
	{
		var oTemplate = document.getElementById("smsTemplate");
		var nSMSTemplateID = oTemplate.options[oTemplate.selectedIndex].id;
		
		ajaxManager('load_page','smsTemplatesAJAX.asp?Teamid=' + sTeamID + '&smsTemplateID=' + nSMSTemplateID + '&Action=Delete','templateContainer');
	}	

	function fnSelectPhotoFolder(){
		var oFolderDirectory = document.getElementById("UploadDirectory")
		var oExistingDirectory = document.getElementById("photoFolders")
		
		if(oExistingDirectory.options[oExistingDirectory.selectedIndex].value >0)
			oFolderDirectory.value = oExistingDirectory.options[oExistingDirectory.selectedIndex].innerHTML;
	}
	
	function fnDisplayThumbnails(nTeamID,nFolderID){
		fnHide("StaticPopup");	//Ensures that any existing popup (Edit photo) is closed before displaying new thumbnails
		ajaxManager(
					'load_page',
					'EditPhotoAJAX.asp?TeamID='+ nTeamID + '&FolderID=' + nFolderID + '&Action=Display',
					'thumbnailscroller');		
	}
	
	function fnPopulateFreeAgents(sEmail){
		ajaxManager(
			'load_page',
			'FreeAgentsAJAX.asp?Email='+ sEmail,
			'FreeAgentSelections');		
	}
	function fnPopulateKeepMePosted(sEmail,sTeamID,sClientTypeID){
		ajaxManager(
			'load_page',
			'KeepMePostedAJAX.asp?Email='+ sEmail + '&TeamID=' + sTeamID + '&ClienTTypeID=' + sClientTypeID,
			'KeepMePostedSelections');		
	}

	function fnPopulateClientRegistration(sEmail){
		ajaxManager(
			'load_page',
			'ClientDetailsAJAX.asp?Email='+ sEmail,
			'CustomerDetails');		
	}
	

	function fnEditPhoto(nTeamID,nFolderID,sPhotoName,sPhotoExtension,oEvent){
//	fnShowPopup('',null,150,50,1);
	ajaxManager(
				'load_page',
				'EditPhotoAJAX.asp?TeamID='+ nTeamID + '&FolderID=' + nFolderID  + '&Action=Popup&PhotoName=' + sPhotoName + '&Extension=' + sPhotoExtension,
				'EditPhoto');		
	}
	function fnUpdatePhoto(nTeamID,nFolderID,sPhotoName,sPhotoExtension){
	
		var oPhotoDescription = document.getElementById("PhotoDescription");
		var oDeletePhoto = document.getElementById("DeletePhoto");

		fnHide("StaticPopup");	//Ensures that any existing popup (Edit photo) is closed before displaying new thumbnails

		if(oDeletePhoto.checked==true)
			ajaxManager(
				'load_page',
				'EditPhotoAJAX.asp?TeamID='+ nTeamID + '&FolderID=' + nFolderID  + '&Action=Delete&PhotoName=' + sPhotoName + '&Extension=' + sPhotoExtension,
				'thumbnailscroller');		
		else
			ajaxManager(
				'load_page',
				'EditPhotoAJAX.asp?TeamID='+ nTeamID + '&FolderID=' + nFolderID  + '&Action=Update&PhotoName=' + sPhotoName + '&Caption=' + oPhotoDescription.value,
				'thumbnailscroller');		

	}

	function fnReturnFalse()
	{
	}
	
	
    function fnShowContactDetailsValidationPopup(e){
        var oTerms = document.getElementById("ContactDetailsValidation");
        var sTerms = oTerms.innerHTML;
        fnShowPopup(sTerms,e,150,300,1);
    }

	function fnValidateContactPassword(nCorrectContactID,sForm){
		var oContactMessage = document.getElementById("ContactPasswordMessage");	//Gets element that will display Contact Details login message.
		var oEnteredContactID = document.getElementById("ContactID"); // The Contact ID entered by the user - requires validation with ajax function below.
		
		if(nCorrectContactID != oEnteredContactID.value)
		{
			oContactMessage.style.display="block";
			oContactMessage.style.color="red";
			oContactMessage.innerHTML = "Error: Password is incorrect<br/>- Please click on the 'Mail me my password' to receive a new email with the password information"	
		}
		else
		    document.getElementById(sForm).submit();
	}

	function fnMailContactDetails(sSubject,sEmail){
		ajaxManager('load_page','MailContactPasswordAJAX.asp?Subject='+ sSubject + '&Email=' + sEmail,'ContactPasswordMessage');		
	}

	function fnMailTeamLoginDetails(sEmail){
		ajaxManager('load_page','MailTeamPasswordAJAX.asp?Subject=Team Login Details&Email=' + sEmail,'ContactPasswordMessage');		

	}

	function transform(s)
	{
			var hex=''
			var i
			for (i=0; i<s.length; i++)
			{
			
			// for debugging:
			// alert('Hex values are:' + hexfromdec( s.charCodeAt(i) ));
			// break;
					
			hex += '%'+hexfromdec( s.charCodeAt(i) )
	
		}
			return hex
	}
// ------------ begin conversion routine ----------
// these are the functions that actually convert
// from decimal ascii to hexidecimal ascii code

	function hexfromdec(num) 
	{
			if (num > 65535) { return ("err!") }
			first = Math.round(num/4096 - .5);
			temp1 = num - first * 4096;
			second = Math.round(temp1/256 -.5);
			temp2 = temp1 - second * 256;
			third = Math.round(temp2/16 - .5);
			fourth = temp2 - third * 16;
			return (""+getletter(third)+getletter(fourth));
	}

	function getletter(num) 
	{
			if (num < 10) {
					return num;
			}
			else {
				if (num == 10) { return "A" }
				if (num == 11) { return "B" }
				if (num == 12) { return "C" }
				if (num == 13) { return "D" }
				if (num == 14) { return "E" }
				if (num == 15) { return "F" }
			}
	}


	function fnSendSMS(sTeamID,sCompetitionID)
	{
		var oSource = document.getElementById("smsFrom");
		var oDestination = document.getElementById("Players");
		var oMessage = document.getElementById("messageContent");
		
		var sSource =  oSource.options[oSource.selectedIndex].value;
		var sMessage = oMessage.value;
		
		sMessage = transform(sMessage); //Converts ASCII to HEX (allows '&' and other symbols to be passed without error)
		
		if (oMessage.value.length >0)
		{
			for (var nLoop=0; nLoop<oDestination.options.length; nLoop++)
			{
				if (oDestination.options[nLoop].selected==true)
				{
					sDestination = oDestination.options[nLoop].value;
					ajaxManager('load_page','smsAJAX.asp?TeamID=' + sTeamID +'&CompetitionID=' + sCompetitionID + '&smsSource=' + sSource + '&smsDestination=' + sDestination + '&smsMessage=' + sMessage,'smsResponse');	
				}
			}
		}
		else
			alert("Message area is blank - sms will not be sent.");
	}
	
	function fnCheckCharCount()
	{
		var smsChars = document.getElementById('smsChars');
		var oMessageContent	= document.getElementById("messageContent");
		var sString = oMessageContent.value;
		if(oMessageContent.value.length >= 135)
			oMessageContent.value = sString.substring(0,135);
		smsChars.innerHTML = 'Characters Left: ' + (135 - oMessageContent.value.length);
	}
	
	function fnFreeAgentsCheck(sTeamID,sCompetitionID)
	{
		var nPositionsCount = document.getElementById("positionsCount").value;
		var sURL="?TeamID=" + sTeamID + "&CompetitionID=" + sCompetitionID + "&PositionCount=" + nPositionsCount;
		
		for(var nLoop=1;nLoop<=nPositionsCount;nLoop++)
			{
				if(document.getElementById(nLoop) != null)
					if(document.getElementById(nLoop).checked!=true)
						sURL += '&Position' + nLoop + '=' + document.getElementById(nLoop).value;
			}
		ajaxManager('load_page','FreeAgentsAvailabilityAJAX.asp' + sURL,'FreeAgentsAvailability');		
	}
	
	function fnDisplayTopupData(nOption)
	{
		var oTopUp1 = document.getElementById("manageMyteamContainer");
		var oTopUp2= document.getElementById("TeamOrganiserTopUp");

		if (nOption == 1)
		{
			oTopUp1.style.display="block";
			oTopUp2.style.display="none";
		}
		if (nOption == 2)
		{
			oTopUp1.style.display="none";
			oTopUp2.style.display="block";			
		}	
	}

	function fnUpdateTopUpMessage(nOption)
	{
		var oMessageContent = document.getElementById("messageContent");
	
		if (nOption == 1)
			oMessageContent.innerHTML ="Hi, Please click on the link below to pay your subscription for our team in the next astro.ie league.";
		if (nOption == 2)
			oMessageContent.innerHTML ="Hi, Please click on the link below to pay your subscription for our team for merchandise from astro.ie";
	}


	function fnShowOtherMedia()
	{
		var oMarketingMedia = document.getElementById("marketingMedia");
		var oOtherMedia = document.getElementById("othermedia");
	
		if( oMarketingMedia.options[oMarketingMedia.selectedIndex].value == 9)
			oOtherMedia.style.display="block"
		else
			oOtherMedia.style.display="none"
	
	}
	
	function fnUpdateTeamsMediaMarketing(sTeamID)
	{
		var oMarketingMedia = document.getElementById("marketingMedia");
		var oOtherMedia = document.getElementById("othermedia");
		var nMarketingMediaID = oMarketingMedia.options[oMarketingMedia.selectedIndex].value;
		var sOtherMedia = oOtherMedia.value; 

		if( nMarketingMediaID == 9)
			oOtherMedia.style.display="block"
		else
			oOtherMedia.style.display="none"


		if( nMarketingMediaID != 0)	// 0 - Blank option
			ajaxManager('load_page','MarketingMediaAJAX.asp?TeamID=' + sTeamID + '&MarketingMediaID=' + nMarketingMediaID + '&OtherMedia=' + sOtherMedia,'MarketingMediaResponse');						
	}
	
	
	
	
	
	function fnChangeDivision(nCompetition,nTeamID,nNewDivision){
				ajaxManager('load_page','ChangeTeamsDivisionAJAX.asp?CompetitionID=' + nCompetition + '&TeamID=' + nTeamID + '&NewDivision=' + nNewDivision);	
				window.location.href = "signedup.asp?CompetitionID=" + nCompetition
	}

	function fnDivisionSplit(nCompetition, nTeamID, nNewDivision) {
	    ajaxManager('load_page', 'ChangeTeamsDivisionAJAX.asp?CompetitionID=' + nCompetition + '&TeamID=' + nTeamID + '&NewDivision=' + nNewDivision);
	}
	
	function fnAutoLogin(sEmail,sRedirectPage)
	{
			document.location.href= "ClientAutoLoginRedirect.asp?Email=" + sEmail + "&RedirectPage=" + sRedirectPage;	
	}
	
	function fnReturnCurrentPage(){
		var sPath = window.location.pathname;
		//var sPage = sPath.substring(sPath.lastIndexOf('\\') + 1);
		var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
		return sPage;			
	}
	function fnCalcTopUpRatio(sTeamID,sTopUpType){
		var oTopUpAmount = document.getElementById("TOPUP_AMT");
		
		if(sTopUpType == "")	//Means that this function was called by a Team Organiser and not a player - ie - page wasn't accessed by a email link.
		{
			if(document.TopUpTypeForm.TopUpType[0].checked)		
					ajaxManager('load_page','TopUpPaymentRatioAJAX.asp?TeamID=' + sTeamID + '&Amount=' + oTopUpAmount.value + "&SplitPayments=true" ,'TopupRatio',"false");		// League and Ref Top Up Payment
				else
					ajaxManager('load_page','TopUpPaymentRatioAJAX.asp?TeamID=' + sTeamID + '&Amount=' + oTopUpAmount.value + "&SplitPayments=false" ,'TopupRatio',"false");	// Non League Top Up Payment - don't split money (all goes to ASTRO)	
		}
		else
		{
			if (sTopUpType == "league")	
				ajaxManager('load_page','TopUpPaymentRatioAJAX.asp?TeamID=' + sTeamID + '&Amount=' + oTopUpAmount.value + "&SplitPayments=true" ,'TopupRatio',"false");		// League and Ref Top Up Payment
			if (sTopUpType == "merchandise")	
					ajaxManager('load_page','TopUpPaymentRatioAJAX.asp?TeamID=' + sTeamID + '&Amount=' + oTopUpAmount.value + "&SplitPayments=false" ,'TopupRatio',"false");	// Non League Top Up Payment - don't split money (all goes to ASTRO)	
		}
		fnProceedToSecurePayment("true");
	}
	
	function fnReturnTwitterStatus(){
		ajaxManager('load_page','http://asltweets:nomads@twitter.com/statuses/user_timeline.xml?status=testing','twitter');		// League and Ref 
	}
	
	
	function twitterCallback2(twitters) {
	 alert(twitters.length);		
	  var statusHTML = [];
	  for (var i=0; i<twitters.length; i++){
		var username = twitters[i].user.screen_name;
		 alert(username);		
		var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
		  return '<a href="'+url+'">'+url+'</a>';
		}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
		  return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
		});
		statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
	  }
	  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
	}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

function fnADRotatorWrapper(url,count){
	
		var sURL;
		ajaxManager('load_page',url+'?Count=' + count,'AdRotatorWrapper');
		if(count == 0)
			count += 1;
		else
			count = 0;
		sURL = "fnADRotatorWrapper('" + url + "'," + count + ")";
		setTimeout(sURL, 10000);
	}

function fnGalleryRotatorWrapper(url){
	
		var sURL;
		var FolderID =document.getElementById("lastFolderID").value;
		ajaxManager('load_page',url+'?FolderID=' + FolderID,'squareImage');
		sURL = "fnGalleryRotatorWrapper('" + url + "')";
		setTimeout(sURL, 40000);
	}
	
function fnDisplayTwitter(nCompetitionLocationID,nCompetitionAssociationID){
		
		var sTwitterList;
	
		switch(nCompetitionAssociationID)
		{
			case 1:
				switch(nCompetitionLocationID)
				{
					case 1: sTwitterList = 'dublinsoccer'
					break;
					case 4: sTwitterList = 'corksoccer'
					break;
					case 5: sTwitterList = 'galwaysoccer'
					break;
					case 11: sTwitterList = 'limericksoccer'
					break;
					default: sTwitterList = 'astrogeneric'
				}
			break;
			case 5:
				switch(nCompetitionLocationID)
				{
					case 1: sTwitterList = 'dublintagrugby'
					break;
					case 4: sTwitterList = 'corktagrugby'
					break;
					default: sTwitterList = 'astrogeneric'
				}
			break;		
			default: sTwitterList = 'astrogeneric'				
		}
		
		new TWTR.Widget({
		  version: 2,
		  type: 'list',
		  rpp: 30,
		  interval: 6000,
		  width: 186,
		  height: 100,
		  theme: {
			shell: {
			  background: '#29aae3',
			  color: '#1985b5'
			},
			tweets: {
			  background: '#083a81',
			  color: '#fff',
			  links: '#f7ee25'
			}
		  },
		  features: {
			scrollbar: false,
			loop: true,
			live: true,
			hashtags: true,
			timestamp: true,
			avatars: false,
			behavior: 'default'
		  }
		}).render().setList('asltweets', sTwitterList).start();
	}	
	
	
	
function roundedImages(content,colour) {
 var content = document.getElementById(content);
 var imgs = content.getElementsByTagName('img');
 
 for (var i = 0; i < imgs.length; i++) {         // start loop 

   var wrapper = document.createElement('div');  // Create the outer-most div (wrapper)
   wrapper.className = 'wrapper';                // Give it a classname - wrapper
   wrapper.style.width = imgs[i].width+'px';     // give wrapper the same width as the current img
   var original = imgs[i];                       // take the next image  
   /* Swap out the original img with our wrapper div (we'll put it back later) */
   if(original.parentNode.tagName.toUpperCase()=='A') original = original.parentNode; // if you link the image this will help the script find the right parent wrapper
   original.parentNode.replaceChild(wrapper, original);
   // IE crash fix - c/o Joshua Paine - http://fairsky.us/home


   /* Create the four other inner nodes and give them classnames */
   var tl = document.createElement('div');
   tl.className = 'tl'+ colour;
   var br = document.createElement('div');
   br.className = 'br'+ colour;
   var tr = document.createElement('div');
   tr.className = 'tr'+ colour;
   var bl = document.createElement('div');
   bl.className = 'bl'+ colour;
   /* Glue the nodes back inside the wrapper */
   wrapper.appendChild(tl);
   wrapper.appendChild(tr);
   wrapper.appendChild(bl);
   wrapper.appendChild(br);
   /* And glue the img back in after the DIVs */
   
   wrapper.appendChild(original);
 }
}

function fnPopulatePayerDetails(){
	
	var oSelect = document.getElementById("teamsContacts");
	var nContactID = oSelect.options[oSelect.selectedIndex].value;
	
	ajaxManager('load_page','PayerDetailsAJAX.asp?ContactID=' + nContactID,'PayerDetails');
	}
	
	
function fnCallRebatesPopup(sInvoice)
{
	var nWinHeight = 400;
	var nWinWidth = 200;
	var sUrl;
	var vResult;
	var sFullDateString;
	var nMonth;
	sUrl = "rebates.asp?InvoiceID=" + sInvoice


	showModalDialog(sUrl,null,"dialogHeight:" + nWinHeight + "px;,dialogWidth:" + nWinWidth + "px;status:no;resizable:no;help:no;dialogLeft:100px;dialogTop:100px")
}
	
function fnSplashRedirect(sUrl)
{
	var sQueryString = location.search;
	window.location = sUrl + sQueryString;
}

function fnPostRecurringPayments(sAction) {
    var oForm = document.getElementById("sslForm")
    var oAction = document.getElementById("PostToRealex")
    oAction.value = sAction;
    oForm.action = "installmentspayer.asp" + document.location.search;
    oForm.submit();
}

function fnValidateNewPayerCard(sAction) {
    var cardnumber = document.getElementById("cardnumber").value;
    var cardholder = document.getElementById("cardholder").value;
    var expMonth = document.getElementById("ExpMonth");
    var expMonthValue = expMonth.options[expMonth.selectedIndex].id;
    var expYear = document.getElementById("ExpYear");
    var expYearValue = expYear.options[expYear.selectedIndex].id;
    var oCardType = document.getElementById("cardtype");
    var sCardType = oCardType.options[oCardType.selectedIndex].value;
 
    var expDate = new Date();
    var currentDate = new Date();
    var currentDateValue = new Date();
    var bValid = true;
    var bErrorMessage = "<label class='ErrorAlert'>Error</label>";


    expDate.setFullYear(expYearValue, expMonthValue - 1, 1);
    currentDateValue = currentDate.setFullYear(currentDate.getFullYear(), currentDate.getMonth(), 1);
    if (!(fnLuhnCheck(cardnumber))) {
        bValid = false;
        bErrorMessage += "<p>Incorrect Card number</p>"
    }
    if (sCardType == "CREDIT") {
        var cvn = document.getElementById("cvn").value;
        if (!(isCVNnumber(cvn))) {
            bValid = false;
            bErrorMessage += "<p>Incorrect Security Code</p>"
        }
    }
    if (currentDateValue > expDate) {
        bValid = false;
        bErrorMessage += "<p>Expiry Date must be in the future</p>"
    }
    if (!(isValidCardholder(cardholder))) {
        bValid = false;
        bErrorMessage += "<p>Cardholder's name must be at least 2 words</p>"
    }

    if (!bValid)
        fnShowPopup(bErrorMessage, null, 400, 20, 1);
    else
        fnPostRecurringPayments(sAction);

}

function fnSelectBlitzType(nOption){

    var oCompetitionType = document.getElementById("CompetitionType");
    var oStandard = document.getElementById("Standard");
    var oForm = document.getElementById("BlitzCompetitionForm");

    switch(nOption)
    {
    case 1: //Ladies Open
      oCompetitionType.value = 27;
      oStandard.value = 6;
      break;
    case 2://Mens Open
      oCompetitionType.value = 26;
      oStandard.value = 6;
      break;
    case 3://Mens 30+
        oCompetitionType.value = 26;
        oStandard.value = 7;
        break;
    }
    oForm.submit();
}

function fnSelectBlitzCompetition(nCompetitionID, DivisionDetailsID, sTeamID) {
    ajaxManager('load_page', 'NationalBlitzAJAX.asp?CompetitionID=' + nCompetitionID + '&DivisionDetailsID=' + DivisionDetailsID + '&TeamID=' + sTeamID, 'nationalblitzinfo');
}

function fnUpdatePhoneScore(team,score){

    var nRRobinID = document.getElementById("rrobinID").value;
    var nTeam1ID = document.getElementById("team1ID").value;
    var nTeam2ID = document.getElementById("team2ID").value;
    var oTeamScore = document.getElementById("team" + team + "Score");
    var nScore;
    var nTeamID;
    
    if (score > 0) 
    {
        if (oTeamScore.value == "")
            nScore = parseInt(1);
        else 
        {
            nScore = parseInt(oTeamScore.value);
            nScore += parseInt(1);
        }
    }
    else 
    {
        if (oTeamScore.value == 0)
            nScore = "";
        else 
        {
            nScore = parseInt(oTeamScore.value);
            nScore -= parseInt(1);
        }
    }
    oTeamScore.value = nScore;
    
    if (team == '1')
        nTeamID = nTeam1ID;
    else
        nTeamID = nTeam2ID;

        
    ajaxManager('load_page', 'UpdateTodaysScoreAJAX.asp?TeamID=' + nTeamID + '&RRobinID=' + nRRobinID + '&Scored=' + nScore);
}

function fnSelectPitchLocation(oPitchLocation, nCompetitionLocationID) {
    var nPitchCount = document.getElementById("NumPitches").value;
    
    ajaxManager('load_page', 'VenueAJAX.asp?PitchLocationID=' + oPitchLocation.options[oPitchLocation.selectedIndex].value + '&LocationID=' + nCompetitionLocationID + '&PitchCount=' + nPitchCount + '&Action=View', 'AddNewPitch');
}

function fnSaveNewVenue(nCompetitionLocationID) { 
    var sVenue = document.getElementById("Venue").value; 
    var nLongtitude = document.getElementById("Longtitude").value; 
    var nLatitude = document.getElementById("Latitude").value; 
    var sArea = document.getElementById("Area").value; 
    var sShortName = document.getElementById("VenueShortname").value;

    ajaxManager('load_page', 'NewVenueAJAX.asp?Venue=' + sVenue + '&Long=' + nLongtitude + '&Lat=' + nLatitude + '&Area=' + sArea + '&Shortname=' + sShortName + '&LocationID=' + nCompetitionLocationID + '&PitchCount=' + nPitchCount + '&Action=NewVenue', 'AddNewPitch');
    
}

function fnSaveNewDirections(nCompetitionLocationID) {
    var sTitle = document.getElementById("DirectionsTitle").value;
    var sDirections = document.getElementById("NewVenueDirections").value;
    var oPitchLocation = document.getElementById("PitchNameSelector");

    ajaxManager('load_page', 'NewDirectionsAJAX.asp?Title=' + sTitle + '&Directions=' + sDirections + "&PitchLocationID=" + oPitchLocation.options[oPitchLocation.selectedIndex].value + '&LocationID=' + nCompetitionLocationID + '&PitchCount=' + nPitchCount + '&Action=NewDirections', 'Directions');
    
}
function fnPopulatePitchShortname() {
    var oVenueShortname = document.getElementById("VenueShortname");
    var oPitchShortname = document.getElementById("PitchShortName");

    oPitchShortname.value = oVenueShortname.value;
}

function fnSaveNewPitch() {
    var nCompetitionLocationID = document.getElementById("HiddenCompetitionID").value;
    var nCompetitionTypeID = document.getElementById("HiddenCompetitionTypeID").value;
    var nPitchCount = document.getElementById("NumPitches").value;
    var oPitchLocation = document.getElementById("PitchNameSelector");
    var nPitchName = document.getElementById("PitchName").value;
    var nPitchShortName = document.getElementById("PitchShortName").value;
    
    ajaxManager('load_page', 'NewPitchAJAX.asp?CompetitionTypeID=' + nCompetitionTypeID + '&CompetitionLocationID=' + nCompetitionLocationID + '&PitchCount=' + nPitchCount + "&PitchLocationID=" + oPitchLocation.options[oPitchLocation.selectedIndex].value + '&PitchName=' + nPitchName + "&PitchShortname=" + nPitchShortName, 'PitchAdded');

}

function fnSignUpTennis(nCompetitionID,nDivisionDetailsID) {

        window.location.href="/registeredit.asp?CompetitionLocationID=1&CompetitionAssociationID=13&CompetitionID=" + nCompetitionID + "&DivisionDetailsID=" + nDivisionDetailsID;
    }
    function fnTeamSearch() {
        var oTeamName = document.getElementById("Teamname")

        ajaxManager('load_page', 'TeamDetailsSearchAJAX.asp?Teamname=' + oTeamName.value, 'TeamSearchResults');
    }