function textCounter(field, countfield, maxlimit) 
{
	/*
	* The input parameters are: the field name;
	* field that holds the number of characters remaining;
	* the max. numb. of characters.
	*/

	if (field.value.length > maxlimit) // if the current length is more than allowed
		field.value =field.value.substring(0, maxlimit); // don't allow further input
	else
		countfield.value = maxlimit - field.value.length; // set the display field to remaining number
} 

function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

function SetAllSelect(FormName, FieldName, SelValue)
{
	if(!document.forms[FormName])
		return;
	var objOptions = document.forms[FormName].elements[FieldName];
	if(!objOptions)
		return;
	var countOptions = objOptions.length;

	if(!countOptions)
		objOptions.selected = SelValue;
	else
	{
		for (i=0; i < countOptions; i++) 
		{
	   		objOptions[i].selected = SelValue;
	  	} 
	}
}

function ToggleQuestionOptions(value, rowid)
{
	var myrow = document.getElementById(rowid);

	if(value == 'text' || value == 'largetext')
	{
		myrow.disabled = true;
	}
	else
	{
		myrow.disabled = false;
	}
}
							

function ToggleCB(myDiv, FormName, myId)
{
	var myCB = document.forms[FormName].elements[myId];
/*	if(myDiv.id == 'plrSelected')
	{
		myDiv.id = ''	
	}
	else
	{
		myDiv.id = 'plrSelected'
	}*/

	if(myCB.checked)
	{
		myCB.checked = false 
	} 
	else 
	{
		myCB.checked = true
	}
}

function ValTitlePhoto()
{
	var FormName = 'gphotos';
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements;
	
	if(!objCheckBoxes)
		return;
	
	var countCheckBoxes = objCheckBoxes.length;
	// set the check value for all check boxes
	var j = 0;
	
	for(var i = 0; i < countCheckBoxes; i++)
	{
		if(objCheckBoxes[i].checked != "")
			j++;
	}
	
	if(j == 0)
		alert('Please Select an photo to be set as the title photo by ticking the checkbox next to that photo');
	else if(j > 1)
		alert('Please only select one photo to be set as the title photo');
	else
	{
		document.forms[FormName].adminpost.value = 'settitlephoto'; 
		document.forms[FormName].submit();
	}
}

function ValEnrolment() {

    var enClass     = document.enrolForm.clId
    var Email         = document.enrolForm.Email
    var Email2        = document.enrolForm.Email2
    var FirstName    = document.enrolForm.FirstName
    var HomePhone    = document.enrolForm.HomePhone
    var Mobile        = document.enrolForm.Mobile
    var SubmitMe    = true

    if(isBlank(enClass.value))
    {
        alert("Please Choose a Class to enrol in")
        SubmitMe = false    
    }
    
    if(isBlank(FirstName.value))
    {
        alert("Please Enter your child's first name")
        SubmitMe = false    
    }
    
    if(isBlank(Mobile.value) & isBlank(HomePhone.value))
    {
        alert("Please make sure either a Mobile Phone or Homephone is entered in so that we can contact you")
        SubmitMe = false
    }

    if(SubmitMe)
    {
        document.enrolForm.submit()
    }
}


function ValDeleteSeasonAttach()
{
	var FormName = 'attachform';
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements;
	
	if(!objCheckBoxes)
		return;
	
	var countCheckBoxes = objCheckBoxes.length;
	// set the check value for all check boxes
	var j = 0;
	
	for(var i = 0; i < countCheckBoxes; i++)
	{
		if(objCheckBoxes[i].checked != "")
			j++;
	}
	
	if(j == 0)
		alert('Please Select an attachment to delete by selecting the checkbox next to that file');
	else
	{
		if(j>1)
			var cont = confirm('Are you sure you want to delete these Attachments?');			
		else		
			var cont = confirm('Are you sure you want to delete this Attachment?');	

		if(cont)
			document.forms[FormName].submit();
	}
}

function EditNewsAttach($newsId)
{
	var cont = confirm('Would you like to save any changes you made to the article (if any)? (click Cancel for No)');
	
	if(cont)
	{
		document.forms.newsform.action='admin.php?adCat=news&aa=nwsAttach&nwsId=' + $newsId;
		ValNewsForm();
	}
	else
		document.location.href='admin.php?adCat=news&aa=nwsAttach&nwsId=' + $newsId;
}

function ValDeleteNewsAttach()
{
	var FormName = 'attachform';
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements;
	
	if(!objCheckBoxes)
		return;
	
	var countCheckBoxes = objCheckBoxes.length;
	// set the check value for all check boxes
	var j = 0;
	
	for(var i = 0; i < countCheckBoxes; i++)
	{
		if(objCheckBoxes[i].checked != "")
			j++;
	}
	
	if(j == 0)
		alert('Please Select an attachment to delete by selecting the checkbox next to that file');
	else
	{
		if(j>1)
			var cont = confirm('Are you sure you want to delete these Attachments?');			
		else		
			var cont = confirm('Are you sure you want to delete this Attachment?');	

		if(cont)
			document.forms[FormName].submit();
	}
}

function ValPhotoLinkPlayers(matchplayer)
{
	var FormName = 'frmLinkPlayer';
	if(!document.forms[FormName])
		return;

	if(matchplayer == true)
		$( 'gpPlrId' ).value = $( 'gpPlrIdMatch' ).value
	else
		$( 'gpPlrId' ).value = $( 'gpPlrIdFull' ).value

	if($( 'gpPlrId' ).value == '')
	{
		alert('Please choose a player to link to the photo');
		return;
	}

	document.forms[FormName].submit();
}


function ConfirmDel(myItem,frmToSubmit,frmVar,myVal)
{
	var cont = confirm('Are you sure you want to delete ' + myItem);
	
	if(cont)
	{
		document.forms[frmToSubmit].elements[frmVar].value = myVal
		document.forms[frmToSubmit].submit();
	}
}

function ConfirmDelGet(myItem,myUrl)
{
	var cont = confirm('Are you sure you want to delete ' + myItem);
	
	if(cont)
	{
		document.location.href = myUrl;
	}
}

function isBlank(s) {
	var len = s.length
	var i
	
	for (i=0; i < len; ++i) {
		if(s.charAt(i) != " ") return false
	}
	return true
}

function ValCreateUser() {

	var userName 	= document.frmUser.cuName
	var pword 		= document.frmUser.cuPword
	var player		= document.frmUser.cuPlayerId
	var SubmitMe	= true

	if(isBlank(player.value))
	{
		alert("Please Choose a player")
		SubmitMe = false	
	}
	
	if(isBlank(userName.value))
	{
		alert("Please enter a UserName to determine the user by")
		SubmitMe = false
	}

	if(isBlank(pword.value))
	{
		alert("Please enter a Password for the user")
		SubmitMe = false
	}

	if(SubmitMe)
	{
		document.frmUser.submit()
	}
}

function ValCreateMailList() {

	var mlName 		= document.createML.mlName
	var mlDesc		= document.createML.mlDesc
	var filter  	= /^([a-zA-Z0-9_\.\-])+$/;
	var SubmitMe	= true
	
	if(isBlank(mlName.value))
	{
		alert("You must enter a Mailing list name!!")
		SubmitMe = false
	}
	else
	{
		if(filter.test(mlName.value))
			SubmitMe = true
		else
		{
			alert('Mail list name failed validation. Please ensure that the mailing list name does not contain any special characters. Spaces are not allowed either. Valid characters are a-z, 0-9 period (.), underscore (_) and hyphen (-)')
			SubmitMe = false
		}
	}

	if(isBlank(mlDesc.value))
	{
		alert('Please enter a mailing list description')
		SubmitMe = false
	}

	if(SubmitMe)
	{
		document.createML.submit()
	}
}

function ValLogin() {

	var userName 	= document.loginForm.usrName
	var pword 		= document.loginForm.usrPass
	var SubmitMe	= true
	
	if(isBlank(userName.value))
	{
		alert("You must enter a UserName!!")
		SubmitMe = false
	}

	if(isBlank(pword.value))
	{
		alert("You must enter a Password!!")
		SubmitMe = false
	}

	if(SubmitMe)
	{
		document.loginForm.submit()
	}
}

function ValPlrUpload() {

	var xlFile 		= document.plrUpForm.plrExcel
	var SubmitMe	= true
	
	if(isBlank(xlFile.value))
	{
		alert("Please choose an excel file to upload")
		SubmitMe = false
	}

	if(SubmitMe)
	{
		document.plrUpForm.submit()
	}
}


function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
   myfield.form.submit();
   return false;
   }
else
   return true;
}


var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
	return true
}

function ValResetPword()
{
	var pword1		= document.frmResetPass.pword1.value
	var pword2		= document.frmResetPass.pword2.value	
	var SubmitMe	= true
	
	SubmitMe =	ValPassword(pword1, pword2)

	if (SubmitMe)
	{
		document.frmResetPass.submit()
	}

}

function ValPassword(pword1, pword2) {
	
	if(pword1 != pword2)
	{
		alert ("Please make sure the passwords entered are the same")
		return false
	}
	
	if(pword1.length < 6)
	{
		alert ("Passwords must be at least 6 chars long")
		return false
	}
	
	return true
}

// Original JavaScript code by Chirp Internet: www.chirp.com.au 
// Please acknowledge use of this code by including this header. 
function checkTime(field) { 
    var errorMsg = ""; // regular expression to match required time format 
    re = /^(\d{1,2}):(\d{2})(:00)?([ap]m)?$/; 
    
    if(field.value != '') { 
        if(regs = field.value.match(re)) { 
            if(regs[4]) { 
                // 12-hour time format with am/pm 
                if(regs[1] < 1 || regs[1] > 12) { 
                    errorMsg = "Invalid value for hours: " + regs[1]; 
                } 
            } 
            else { 
                // 24-hour time format 
                if(regs[1] > 23) { 
                    errorMsg = "Invalid value for hours: " + regs[1]; 
                } 
            } 
            
            if(!errorMsg && regs[2] > 59) { 
                errorMsg = "Invalid value for minutes: " + regs[2]; 
            } 
        } 
        else { 
            errorMsg = "Invalid time format: " + field.value; 
        } 
    } 
    
    if(errorMsg != "") { 
        alert(errorMsg); 
        field.focus(); 
        return false; 
    } 
    
    return true; 
}

function ValEventForm() {

    var evfilter    = document.eventform.evFilter
	var subject 	= document.eventform.evName
	var mydate 		= document.eventform.evDate	
	var message		= document.eventform.evDesc
	var SubmitMe	= true
	
    if(isBlank(subject.value))
    {
        alert("You must enter an Event Name")
        SubmitMe = false
    }
    
	if(isBlank(mydate.value))
	{
		alert("You must enter a date")
		SubmitMe = false
	}
	else
	{
		if(!isDate(mydate.value))
			SubmitMe = false
	}
    
    if(!checkTime(document.eventform.evTime)) SubmitMe = false;

	if(SubmitMe)
	{
		document.forms.eventform.onsubmit();
		document.eventform.submit();
	}
}

function ValCalDateForm() {

    var evfilter    = document.eventform.evFilter  
    var subject 	= document.eventform.evName
	var mydate 		= document.eventform.evDate	
	var SubmitMe	= true
	
    if(isBlank(subject.value))
	{
		alert("You must enter an Calendar Date Title")
		SubmitMe = false
	}

	if(isBlank(mydate.value))
	{
		alert("You must enter a date")
		SubmitMe = false
	}
	else
	{
		if(!isDate(mydate.value))
			SubmitMe = false
	}
    
    if(!checkTime(document.eventform.evTime)) SubmitMe = false;

	if(SubmitMe)
	{
		document.eventform.submit();
	}
}

function UpdateTimeField(TimeGroupName)
{
    var myHour  = $('#' + TimeGroupName + 'Hour').val();
    var myMin   = $('#' + TimeGroupName + 'Minute').val();
    var myAMPM  = $('#' + TimeGroupName + 'AMPM').val();
    
    if(myAMPM == 'PM' && myHour != '12') 
        myHour = eval(myHour) + 12;
    else if(myAMPM == 'AM' && myHour == '12')
        myHour = '00';
    
    $('#' + TimeGroupName ).val(myHour + ':' + myMin);
}

function ValNewsForm() {

	var subject 	= document.newsform.nwsSubject
//	var mydate 		= document.newsform.nwsDate
	var message		= document.newsform.nwsMessage
	var SubmitMe	= true
	
	if(isBlank(subject.value))
	{
		alert("You must enter a subject")
		SubmitMe = false
	}

/*	if(isBlank(mydate.value))
	{
		alert("You must enter a date")
		SubmitMe = false
	}
	else
	{
		if(!isDate(mydate.value))
			SubmitMe = false
	}
*/
	if(isBlank(message.value))
	{
		alert("You must enter a message")
		SubmitMe = false
	}	

	if(SubmitMe)
	{
		document.forms.newsform.onsubmit();	
		document.newsform.submit();
	}
}

function ValPayment()
{
	var player	 	= document.payform.plrId
	var myDay 		= document.payform.pyDay
	var myMonth		= document.payform.pyMonth
	var myYear		= document.payform.pyYear
	var mydate 		= myDay.value + '/' + myMonth.value + '/' + myYear.value
	var Amount		= document.payform.pyAmount
	var Desc		= document.payform.pyDesc
	var SubmitMe	= true
	
	if(isBlank(player.value))
	{
		alert("You must choose a player")
		SubmitMe = false
	}

	if(isBlank(mydate))
	{
		alert("You must enter a date")
		SubmitMe = false
	}
	else
	{
		if(!isDate(mydate))
			SubmitMe = false
	}

	if(!(isInteger(Amount.value)) || (Amount.value <= 0))
	{
		alert("Please Enter an Amount over $0")
		SubmitMe = false
	}	

	if(isBlank(Desc.value))
	{
		alert("Please Enter a Description")
		SubmitMe = false
	}

	if(SubmitMe)
		document.payform.submit()
}

function ValSelChangePeriod() {

	var myDay 		= document.SelChangePeriod.ssDay
	var myMonth		= document.SelChangePeriod.ssMonth
	var myYear		= document.SelChangePeriod.ssYear
	var mydate 		= myDay.value + '/' + myMonth.value + '/' + myYear.value
	var myDay2 		= document.SelChangePeriod.sfDay
	var myMonth2	= document.SelChangePeriod.sfMonth
	var myYear2		= document.SelChangePeriod.sfYear
	var mydate2		= myDay2.value + '/' + myMonth2.value + '/' + myYear2.value

	var SubmitMe	= true
	
	if(isBlank(mydate))
	{
		alert("You must enter a Selection Start date")
		SubmitMe = false
	}
	else
	{
		if(!isDate(mydate))
			SubmitMe = false
	}

	if(isBlank(mydate2))
	{
		alert("You must enter a Selection Finish date")
		SubmitMe = false
	}
	else
	{
		if(!isDate(mydate2))
			SubmitMe = false
	}
	
	if(mydate > mydate2)
	{
		alert('start date must be before finish date')
	}
	else
	{
		alert('everything cool')
	}

	if(SubmitMe)
	{
//		document.forms.SelChangePeriod.onsubmit();	
		document.SelChangePeriod.submit();
	}
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function ValidEmailAddress(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
}

function ValOnlineRegoForm() {

	var FirstName 	= document.frmonlinerego.orFirstName;
	var LastName	= document.frmonlinerego.orLastName;
	var email		= document.frmonlinerego.orEmail.value;
	var Bday		= document.frmonlinerego.orBday;
	var mphone		= document.frmonlinerego.orMobile;
	var wphone		= document.frmonlinerego.orWorkPhone;
	var hphone		= document.frmonlinerego.orHomePhone;
	var gender		= document.frmonlinerego.orGender; 
	var reason		= '';

	email = trim(email);

	var SubmitMe	= true;
	
	if(isBlank(getCheckedValue(gender)))
	{
		reason = reason + '\n - Please specify your gender';
		SubmitMe = false;
	}

	if(isBlank(FirstName.value) || isBlank(LastName.value))
	{
		reason = reason + '\n - Please ensure both First name and Last name are filled in';
		SubmitMe = false
	}

	if(isBlank(email))
	{
		reason = reason + '\n - Please ensure an email address is filled in';
		SubmitMe = false
	}
	else
	{
		if(!ValidEmailAddress(email))
		{
			reason = reason + '\n - Please check that your email address is correctly entered';
			SubmitMe = false			
		}
	}

	if(isBlank(mphone.value) && isBlank(wphone.value) && isBlank(hphone.value))
	{
		reason = reason + '\n - Please enter at least one Phone contact number';
		SubmitMe = false;
	}

	if(isBlank(Bday.value))
	{
		reason = reason + '\n - Please enter your Date of Birth';
		SubmitMe = false;
	}
	else
	{
		if(!isDate(Bday.value))
		{
			reason = reason + '\n - Please check Date of Birth is in dd/mm/yyyy format';
			SubmitMe = false;
		}
	}

	if(SubmitMe)
	{
		document.frmonlinerego.submit();
	}
	else
	{
		reason = 'Sorry the form has not yet been submitted can you please check the following: ' + reason;
		alert(reason);
	}
}