//------------------------------------------------------------------------------------------
//	Standard scripting to be made available in the <head> block of every content page.
//------------------------------------------------------------------------------------------

//	"Constants"
var FORM_APPLY = 'apply';
var FORM_SHOW = 'show';

function getElement(id)
{
	var e = null;
	if(e = document.getElementById(id))
		return e;
	e = document.getElementsByName(id);
	return (e.length == 1 ? e[0] : null);
}

// Return value of given element name/id. Trim by default.
function getValue(id, bNoTrim)
{
	return bNoTrim ? getElement(id).value : trim(getElement(id).value);
}

function cancelPage()
{
	if(self.opener)
		self.close();
	else
		if(self.backURL != '')
			self.location.replace(self.backURL);
		else
			closePage();
}

function closePage()
{
	if(self.opener)
		self.close();
	else
		showHomePage();
/*	{
		document.write(top.blankPage());
		document.close();				       
		top.setContentTitle('');
	}*/
}

function showPage(url, backURL)
{
	var urlParms = '';
	if(!backURL || backURL == '')
		backURL = getPathName(document.URL);
	// '&parm=value' parameters
	for(var i = 2; i < arguments.length; ++i)
		urlParms += (arguments[i]);

	self.location.href = url + '?formstate=show' + '&back=' + backURL + urlParms;
}

// Submit a form as result of explicit call from onclick event.
function submitFormExplicit()
{
	return submitFormData(false, arguments);
}
// Submit a form as result of onsubmit event of submit button.
function submitForm()
{
	return submitFormData(true, arguments);
}

//	Submit a Form.
//	1st parameter is boolean: true indicates is result of form.onsubmit event (ie from a submit button); false 
//	indicates is explicit call as result of onclick event of non-submit button.
//	2nd parameter is array of arguments passed on to us from intermediate submitPage or submitForm function.
//	Elements in this array are optional, can be in any order and are;
//  - validation function
//  - true/false boolean; do/do not perform validation
//  - any number of '&urlparm=value'  querystring parameters
function submitFormData(bSubmitEvent, args )
{
	var validateFunc = null;
	var bValidate = true;
	var urlParms= '';
	var bBackParm = false;
	var bFormStateParm = false;
	var form = document.getElementsByTagName('form')[0];

	document.body.style.cursor = 'wait';

	// Function arguments
	for(var i = 0; i < args.length; ++i)
	{
		if(typeof(args[i]) == 'function')
			validateFunc = args[i]; 
		else if(typeof(args[i]) == 'boolean')
			bValidate = args[i]; 
		else
		{
			urlParms += (args[i]);
			// Below we would usually add &back url parms. Note if explicitly passed, in which case we won't add it.
			if(args[i].slice(0, 5).toLowerCase() == '&back')
				bBackParm = true;
		}
	}

	// Validate
	if(bValidate && validateFunc)
	{
		window.status = 'Validating page ...';
		if(!validateFunc())
		{
			document.body.style.cursor = 'auto';
			window.status = '';
			return false;
		}
	}

	// Submit
	window.status = 'Submitting page ...';

	document.body.style.cursor = 'auto';

	window.status = '';
	
	form.action = self.location.pathname + '?formstate=apply';
	if(!bBackParm && self.backURL)
		form.action += '&back=' + encodeURL(self.backURL);
	form.action += urlParms;
	form.method = 'post';
		
	if(!bSubmitEvent)
		form.submit();
	return true;
}

function showHomePage()
{
	self.location.href = 'info_page.asp?pagetype=1';
//	frames['content'].location.replace('info_page.asp?pagetype=1');
//	top.showHomePage();
}

function disablePage()
{
	self.disabledNodes = new Array();
	for(var i = 0, nodes = document.getElementsByTagName('*'); i < nodes.length ; ++i)
	{
		var tagName = nodes[i].tagName.toLowerCase();
		if(tagName.match(/^input$|^select$|^checkbox$|^password$/))
		{
			nodes[i].disabled = true;
			self.disabledNodes[self.disabledNodes.length] = nodes[i];
		}
	}
}
function enablePage()
{
	if(self.disabledNodes)
		for(var i =0; i < self.disabledNodes.length; ++i)
			self.disabledNodes[i].disabled = false;
	self.disabledNodes = null;
}
function disableCommandButtons()
{
	for(var i = 0, nodes = document.getElementsByTagName('INPUT'); i < nodes.length ; ++i)
		if(nodes[i].type == 'button')
			nodes[i].disabled = true;
}
function enableCommandButtons()
{
	for(var i = 0, nodes = document.getElementsByTagName('INPUT'); i < nodes.length ; ++i)
		if(nodes[i].type == 'button')
			nodes[i].disabled = false;
}

function  getPathName(url)
{
	var siteRoot = top.location.pathname.toLowerCase().substr(0,top.location.pathname.toLowerCase().indexOf('default.asp'));
	var from, to;
	if((from = document.URL.indexOf(siteRoot)) == -1)
		from = 0;
	if((to = document.URL.indexOf('?')) == -1)
		to = document.URL.length;
	return document.URL.substring(from,to);
}

/*
 *	Validate given date string.
 * 	If bCCYY set then year portion must be 4 digits, else must be 2.
 *	Month/day values may be 1 or 2-digit.
 *	Separtor may be "/" or "-".
 *  If US locale, format is assumed to be month/day/year, else day/month/year.
 */
function isDate(dateStr, isCCYY) 
{
	var maxDay, bIsDate, date;

	// Create object to pass to parse date routines. 
	date = new Object();
	date.value = dateStr;
	date.isCCYY = isCCYY
	
	// Parse date. Object returns with day, month year properties set.
	if(date.value.indexOf('/') > -1 || date.value.indexOf('-') > -1)
		bIsDate = parseDelimDate(date);
	else
		bIsDate = parsePlainDate(date);
	if(!bIsDate)
		return false;
		
	if(date.year < 100)
	{
		if((date.year + 2000) <= (new Date()).getFullYear())
			date.year += 2000;
		else
			date.year += 1900;
	}
	if(date.month == 2)
		maxDay = (date.year % 4 == 0 && (date.year % 100 != 0 || date.year % 400 == 0)) ? 29 : 28;
	else if (date.month==4 || date.month==6 || date.month==9 || date.month==11)
		maxDay = 30;
	else
		maxDay = 31;

	return(date.month >= 1 && date.month <= 12 && date.day >= 1 && date.day <= maxDay);
}

function parsePlainDate(date)
{
	if(date.value.length != 6 && date.value.length != 8 || 
	   date.isCCYY && date.value.length != 8)
		return false;
		
	if(isUKDateLocale())
	{
		date.day = date.value.slice(0, 2);
		date.month = date.value.slice(2, 4);
	}
	else
	{
		date.day = date.value.slice(2, 4);
		date.month = date.value.slice(0, 2);
	}
	date.year = date.value.slice(4);
	return true;
}

function parseDelimDate(date)
{
	var datePat;
	if(date.isCCYY)
		datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	else
		datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
 
	var matchArray = date.value.match(datePat); // is the format ok?
	if(!matchArray) 
		return false;
	if(isUKDateLocale())
	{
		date.day = parseInt(matchArray[1]);
		date.month = parseInt(matchArray[3]);
	}
	else
	{
		date.day = parseInt(matchArray[3]);
		date.month = parseInt(matchArray[1]);
	}
	date.year = parseInt(matchArray[4]);
	return true;
}

function validTime(time)
{
	var hr = null, mn = null;
	var segs = time.split(/[:. ]/);

	if(segs.length <= 2)
	{
		if(segs.length == 1)
		{
			if(time.length == 2)
			{
				hr = time.substring(0,2); mn = '00';
			}
			else if(time.length == 3)
			{
				hr = '0' + time.substring(0,1);	mn = time.substring(1,3);
			}
			else if(time.length == 4)
			{
				hr = time.substring(0,2); mn = time.substring(2,4);
			}
		}
		else
		{
			hr = segs[0];
			mn = segs[1];
			if(hr == '')
				hr = '00';
			else if(hr.length == 1)
				hr = '0' + hr;
			if(mn == '')
				mn = '00';
			else if(mn.length == 1)
				mn += '0';
		}
	}
	if(!hr || !mn || !isInt(hr) || !isInt(mn) ||
	   parseInt(hr) < 0 || parseInt(hr) > 24 || 
	   parseInt(mn) < 0  || parseInt(mn) > 59)
		return false;
	else
		return(hr + ':' + mn);
}

function isInt(n)
{
	return (!n.match(/[^0123456789]/));
}

function isUKDateLocale()
{
	return (self.LCID != '1033');
}

function encodeURL(urlParm)
{
	var encodedParm = '';
	for(var i = 0; i < urlParm.length; ++i)
	{
		var c = urlParm.charAt(i);
		if(c == '?')
			c = '%3F';
		else if(c == '&')
			c = '%26';
		else if(c == ' ')
			c = '%20%';
		encodedParm += c;
	}
	return encodedParm;
}

/* Trim a string of whitespace, left and right */
function trim(s)
{
	var i=0, from=0, to=0;
	for(i=0; i < s.length; ++i)
	{
		if(s.charAt(i).match(/\S/))
		{
			from = i;
			to = i+1;
			break;
		}
	}
	for(i= s.length-1; i > from; --i)
	{
		if(s.charAt(i).match(/\S/))
		{
			to = i+1;
			break;
		}
	}
	return s.substring(from,to);
}

function toggleDisplay(element, displayType)
{
	if(element.style.display != 'none')
		element.style.display = 'none';
	else
		element.style.display = displayType ? displayType : '';
}

function toggleVisibility(element)
{
	if(element.style.display != 'hidden')
		element.style.display = 'visible';
	else
		element.style.display = 'hidden';
}

function errAlert(msg, field /*, field2, field3 ... */ )
{
	for(i = 1; i < arguments.length; ++ i)
		arguments[i].className = 'error';
	if(msg)
		alert(msg);
	if(arguments.length > 1)
		try{arguments[1].focus();} catch(e){};
	return false;
}

function clrError(field /*, field2, field3 ... */ )
{
	for(i = 0; i < arguments.length; ++i){
		if(arguments[i])
			arguments[i].className = arguments[i].type;
	}
}

function toggleClass(id, classN, state) {
// turn on/off the class within the html object.
	var o = typeof(id)=="string" ? document.getElementById(id) : id;
	
	if (o!=null) {
		if (state && o.className.indexOf(classN)==-1) {
          o.className += ' '+classN;
		} else if (!state) {
		o.className = eval("o.className.replace(/"+classN+"/,'');");
		}
	}
}
// pass date as string in format of dd/mm/yyyy
function getMonthName(szDate,bFull)
{
var szName = '';

var Ar = szDate.split('/');
var nMonthNum  = new Number(Ar[1]); 
	
	switch(nMonthNum.toString())
	{
		case '1':  szName = 'January';	break;
		case '2':  szName = 'February';	break;
		case '3':  szName = 'March';	break;
		case '4':  szName = 'April';	break;
		case '5':  szName = 'May';		break;
		case '6':  szName = 'June';		break;
		case '7':  szName = 'July';		break;
	 	case '8':  szName = 'august';	break;
		case '9':  szName = 'September';break;
		case '10': szName = 'October';	break;
		case '11': szName = 'November';	break;
		case '12': szName = 'December';	break;
	}
	if(bFull == false)
		return szName.substr(0,3);
	else
		return szName;
}
// pass date as string in format of dd/mm/yyyy
function getDayName(szDate,bFull)
{
var szName = '';
var Ar = szDate.split('/');
var dtDate = new Date( Ar[1]  + '/' +  Ar[0] + '/' + Ar[2]);
	switch(parseInt(dtDate.getDay()) )
	{
		case 0:	szName = 'Sunday';		break;
		case 1:	szName = 'Monday';		break;
		case 2:	szName = 'Tuesday';		break;
		case 3:	szName = 'Wednesday';	break;
		case 4:	szName = 'Thursday';	break;
		case 5:	szName = 'Friday';		break;
		case 6:	szName = 'Saturday';	break;
	}

	if(bFull == false)
		return szName.substr(0,3);
	else
		return szName;
}
// return values
// 0 = same
// 1 = dt1 > dt2
// -1 = dt1 < dt2
function dateComp(dt1,dt2)
{
//var arDt1	= dt1.split('/');	//  MGM 18 08 05
//var arDt2 = dt2.split('/');	//  MGM 18 08 05

var arDt1	= dt1.split(/[-\/]/);	//  MGM 18 08 05
var arDt2   = dt2.split(/[-\/]/);	//  MGM 18 08 05

var nDay1   = (arDt1[0] - 0)
var nDay2   = (arDt2[0] - 0)
var nMonth1 = (arDt1[1] - 0)
var nMonth2 = (arDt2[1] - 0)
var nYear1  = (arDt1[2] - 0)
var nYear2  = (arDt2[2] - 0)
var now		= new Date();

	// Convert years to 4-digit
	if(nYear1 < 100)
		if( nYear1 > ((now.year + 1) % 100)) // If greater than this year or next, must be last century
			nYear1 = nYear1 + 1900;
		else
			nYear1 = nYear1 + 2000;
	if(nYear2 < 100)
		if( nYear2 > ((now.year + 1) % 100)) // If greater than this year or next, must be last century
			nYear2 = nYear2 + 1900;
		else
			nYear2 = nYear2 + 2000;
	
//alert(dt1 + '\r' + dt2);
	if( nDay1 == nDay2 && nMonth1 == nMonth2 && nYear1 == nYear2 )
	{
		return 0;			
	}
	else if( ( nYear1 > nYear2 ) 
	      || ( nYear1 == nYear2 && nMonth1 > nMonth2 ) 
	      || ( nYear1 == nYear2 && nMonth1 == nMonth2 && nDay1 > nDay2) )
	{
	   return 1;
	}
	else
	{
		return -1;
	}
}

// will return true if date is = to  "30/12/1899" ( vbNullDate
// pass date as string in the format of dd/mm/ccyy

function isDateNull(szDate)
{
	if(szDate == '31/12/1899' || szDate == '30/12/1899' || szDate == '')
		return true;
	else
		return false;

}
function getFixtureDate(szDate)
{
var Ar = szDate.split('/');

	return getDayName(szDate,false) + '&nbsp;' + parseInt(Ar[0]) + '&nbsp;' + getMonthName(szDate,false);

}

// will find the
function encodeEmbeddedBackURL(szUrl)
{
var nPos = new Number();
var rExp = /\?back=/gi;
	// look for ?back=
	nPos = szUrl.search(rExp);
	if(nPos < 0 ) // if not found look for &back=
	{
		rExp = /\&back=/gi;
		nPos = szUrl.search(rExp)
	}
	if(nPos >= 0) // we found it
		return  szUrl.slice(0,nPos + 6) + encodeURL(szUrl.slice(nPos + 6,szUrl.length));
	else
		return  szUrl;
}

function showHelpPage()
{
	this.helpPage = getHelpPage();
	window.open('help/help.asp?helppage=' + this.helpPage, '', 'scrollbars=yes, width=740px')
}

// Get help page, relative to root of current site, based on what's in current content frame.
// eg /afc/lman/create_clubs.asp -> and /test.leaguemanager.biz/create_clubs.asp -> help/create_clubs.asp
function getHelpPage()
{

	var len, helpPage; // contentFrame;

	// MD 041209 Amended as Frames are no longer used.
	//contentFrame = top.frames['content'];

	// Help page name usually follows the content page's name, but this can be overriden
	// by placing an <input type="hidden" id="helppage" value="helppagename"> element in the content page.
	//if(contentFrame.document.getElementById('helppage'))
	//	return contentFrame.document.getElementById('helppage').value;
	if (getElement('helppage'))
		{
		return getElement('helppage').value;
		}
	// Set offset to 1st character of content frame name after site root...
	
	//len = contentFrame.location.pathname.toLowerCase().indexOf(self.rootPath) + self.rootPath.length;
	len = window.location.pathname.toLowerCase().indexOf(self.rootPath) + self.rootPath.length;

	// ... the rest of the pathname is the root-relative name of the current content page
	//helpPage = contentFrame.location.pathname.slice(len);
	helpPage = window.location.pathname.slice(len);
	
	// Just in case things are not as expected, and we have a blank value, replace it with default help page
	if(helpPage == '')
		helpPage = 'default.asp';

	// Append _help to the base file name eg "club_create.asp" becomes "club_create_help.asp".
	helpPage = helpPage.replace(/\.(.+)$/, '_help.$1');
	
	return helpPage;
}

// Was current page opened by a foreign domain
function isForeignOpener()
{
	// If we were opened by another window
	if(self.opener)
	{
		// Evaluate document.domain property
		try {self.opener.document.domain;} catch(e) 
		{
			// Which will trigger an access denied error if it is from a foreign domain.
			return true;
		}
	}
	return false;
}

// Return true if we are an embedded (i)frame in a foreign site
function isForeignParent()
{
	return(top != self);
}

function isPopup()
{
	return(self.opener && !isForeignOpener());
}

// Are "header" elements (header block, menus, ads) enabled?
function isHeaderEnabled()
{
	// Headers disabled in popups and pages embedded in foreign sites.
	return(!isPopup() && !isForeignParent());
}
function isFooterEnabled()
{
	// Headers disabled in popups and pages embedded in foreign sites.
	return(isHeaderEnabled());
}

// to be used with NewRegionDivisionSelect in clsSelectList.vbs
// gets region id from select list
function getSelectedRegionID()
{
	return getValueFromRegionDivisionSelectionList(0);
}
// to be used with NewRegionDivisionSelect in clsSelectList.vbs
// get division id from select list
function getSelectedDivisionID()
{
	return getValueFromRegionDivisionSelectionList(1);
}
// to be used with NewRegionDivisionSelect in clsSelectList.vbs
// get the value string form the region division select list inthe form of "3~4"
// splits it to the region and divison values the returns the required vales
// nType pass 0 for region and 1 for division
function getValueFromRegionDivisionSelectionList(nType)
{
var obj;
	obj = getElement('selRegionDivisionList');
	if(!obj)
		return -99; //control not found return error"
	var selValue = obj.options[obj.selectedIndex].value;
	if(selValue == '')
		return -99; //no value return 99 for error"		
	var Result = selValue.split("~");
	return Result[nType];
}
// to be used with DatesSelectForDaysMatchesScheduled from clsDate
// get value from select list
function getDateFromDatesSelectForDaysMatchesScheduled()
{
var obj;
	obj = getElement('selDatesForDaysMatchesScheduled');
	if(!obj)
		return -99; //control not found return error"	
	return obj.options[obj.selectedIndex].value;
}
function loadNumericSelect(selName,start,end,selected,emptyCellValue)
{
	var selectBox = getElement(selName);
	if(selectBox != null){
		if(emptyCellValue.length > 0){
			addCellToSelect(selectBox,emptyCellValue,'',(emptyCellValue == selected));
		}		
		for(var value = start; value <= end; value++){
			addCellToSelect(selectBox,value,value.toString(),(value == selected));  			
		}
	}
	else{
		alert('Error: loadNumericSelect\n' + selName);
	}
}
function addCellToSelect(obj,value,text,selected){
	var elOptNew = document.createElement('option');
	elOptNew.text = text;
	elOptNew.value = value;
	if(selected)
		elOptNew.selected = true;
	try {
		obj.add(elOptNew, null); // standards compliant; doesn't work in IE
	}catch(ex) {
   		obj.add(elOptNew); // IE only
  	}
}

function togglePrintView(szCallerName){
var obj1;
var obj2;
var objBody;
	objBody = document.getElementsByTagName("body")[0];
	obj2 = getElement('fullPage');
	obj1 = getElement('fullPagePrint');
	if(obj1)	// we are in print mode allready then
	{		
		objBody.innerHTML =  '<div id="fullPage" >' + obj1.innerHTML + '</div>';
		getElement(szCallerName).value = 'Print View';	
	}else{
		
		objBody.innerHTML = '<div id="fullPagePrint" >' + obj2.innerHTML + '</div>';
		getElement(szCallerName).value = 'Normal View';
	}
}

function formatCurrency(sz1){ 	

	if(isNaN(sz1))
		return '';
var sz = new String(sz1);
	var pos = sz.indexOf(".");
	if(pos == -1)
		sz+='.00';
	else{
		if(pos == 0)
			sz = '0' + sz;			
		if(pos != sz.length-3){
			if(sz.length > (pos + 3)){
				sz = sz.substring(0,pos+3);// .length = pos + 3;
			}else{
				if(sz.length == pos +1)
					sz+='00';
				else
					sz+= '0';
			}
		}
	}
	return  sz;
}
