/*
Author:Bruno Lenette (info@jean-bruno.com)
Date:07/02/08javascriptFunctions.js
Purpose:Javascript validation
*/

////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to make the over functionality
// jQuery Sortable 
////////////////////////////////////////////////////////////////////////////////////////////////////	
/*$(document).ready(function() {
	$('table.sortable tbody tr').mouseover(function() { 
		$(this).addClass('over');					
	});
	$('table.sortable tbody tr').mouseout(function() { 
		$(this).removeClass('over');					
	});
});		*/

////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to validate url
////////////////////////////////////////////////////////////////////////////////////////////////////	
function validURL(theURL)
{
	//if the url matches our criteria
	if(theURL.match(/http:\/\/[^.]+\.[^.]+\.[^;]+/i))
	{
		//return true
		return true
	}
	else//else if the url is invalid
	{
		//return false
		return false
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to validate email
////////////////////////////////////////////////////////////////////////////////////////////////////	
function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid E-mail Address")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail Address")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid E-mail Address")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid E-mail Address")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid E-mail Address")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid E-mail Address")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid E-mail Address")
		    return false
		 }

 		 return true					
	}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to validate login form
////////////////////////////////////////////////////////////////////////////////////////////////////	
function validateForm()
{
	username	= ''; password = '';
	username	= document.loginForm.userName.value;
	password	= document.loginForm.userPassword.value;
	if (username == '')
	{
		alert ('Please enter a username');
		document.loginForm.userName.focus();
		return false;
	}
	if (password == '')
	{
		alert ('Please enter a password');
		document.loginForm.userPassword.focus();
		return false;
	}
	return true;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to validate users form
////////////////////////////////////////////////////////////////////////////////////////////////////	
function validateUsersForm()
{
	firstName = '';
	lastName = '';
	login = '';
	password = '';
	accessLevel = '';
	emailAddress = '';
	
	firstName	= document.usersForm.name.value;
	lastName	= document.usersForm.surname.value;
	login	= document.usersForm.login.value;
	password	= document.usersForm.password.value;
	accessLevel	= document.usersForm.permissions.value;
	emailAddress = document.usersForm.email.value;
	
	if (firstName == '')
	{
		alert ('Please enter a first name');
		document.usersForm.name.focus();
		return false;
	}
	
	if (lastName == '')
	{
		alert ('Please enter a surname');
		document.usersForm.surname.focus();
		return false;
	}
	
	if (login == '')
	{
		alert ('Please enter a login');
		document.usersForm.login.focus();
		return false;
	}
	
	if (password == '')
	{
		alert ('Please enter a password');
		document.usersForm.password.focus();
		return false;
	}
	
	if (emailAddress == '')
	{
		alert ('Please enter an email address');
		document.usersForm.email.focus();
		return false;
	}
	
	if (echeck(emailAddress)==false){
		document.usersForm.email.focus();
		return false
	}
	
	if (accessLevel == '')
	{
		alert ('Please choose an access level');
		document.usersForm.permissions.focus();
		return false;
	}
	
	return true;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to validate users form
////////////////////////////////////////////////////////////////////////////////////////////////////	
function validateCategoryForm()
{
	categoryName = '';
	categoryName	= document.categoryForm.categoryName.value;
	
	if (categoryName == '')
	{
		alert ('Please enter a category name');
		document.categoryForm.categoryName.focus();
		return false;
	}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to validate users form
////////////////////////////////////////////////////////////////////////////////////////////////////	
function validatesubCategoryForm()
{
	subCategoryName = '';
	subCategoryName	= document.subCategoryForm.subCategoryName.value;
	
	mainCategory = '';
	mainCategory	= document.subCategoryForm.mainTeamCategory.value;
	
	if (subCategoryName == '')
	{
		alert ('Please enter a sub category name');
		document.subCategoryForm.subCategoryName.focus();
		return false;
	}
	
	if (mainCategory == '')
	{
		alert ('Please enter a main category');
		document.subCategoryForm.mainTeamCategory.focus();
		return false;
	}
}


////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to validate venues stadium
////////////////////////////////////////////////////////////////////////////////////////////////////	
function validateVenuesForm()
{
	venueName = '';
	venueName	= document.venuesForm.venueName.value;
	
	if (venueName == '')
	{
		alert ('Please enter a venue name');
		document.venuesForm.venueName.focus();
		return false;
	}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to validate teams
////////////////////////////////////////////////////////////////////////////////////////////////////	
function validateTeamForm()
{
	teamName = '';
	teamName	= document.teamForm.teamName.value;
	
	teamCategory = '';
	teamCategory	= document.teamForm.teamCategory.value;
	
	subCategory = '';
	subCategory	= document.teamForm.subCategory.value;

	teamStadium = '';
	teamStadium	= document.teamForm.teamStadium.value;
	

	if (teamName == '')
	{
		alert ('Please enter a team name');
		document.teamForm.teamName.focus();
		return false;
	}
	
	if (teamCategory == '')
	{
		alert ('Please choose a valid category');
		document.teamForm.teamCategory.focus();
		return false;
	}
	
	if (subCategory == '')
	{
		alert ('Please choose a valid sub category');
		document.teamForm.subCategory.focus();
		return false;
	}
	
	if (teamStadium == '')
	{
		alert ('Please choose a valid stadium');
		document.teamForm.teamStadium.focus();
		return false;
	}

}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to validate teams
////////////////////////////////////////////////////////////////////////////////////////////////////	
function validatePageContentForm()
{
	pageTitle = '';
	pageTitle	= document.pageContentForm.pageTitle.value;
	
	pageContentText = '';

	if (pageTitle == '')
	{
		alert ('Please enter a page title');
		document.pageContentForm.pageTitle.focus();
		return false;
	}
	
	//Get text from editor and pass to hidden text field
	var oEditor = FCKeditorAPI.GetInstance('pageContentText') ; //emailBody is the instance name of the editor. Can be changed.
	contentFromEditor = oEditor.GetHTML();
	if(contentFromEditor == '')
	{
		alert ('Please enter some text for the page content');
		return false;
	}
	
	
}


/*
Function to confirm if user want to delete object
@0bject [object being passed from calling function ]
@id [id of object to be deleted]
@page [page to redirect back]
*/

function confirmDelete(object,id,page)
{
	
	var confirmIt = confirm("Are you sure you want to delete this " + object + "?");
	if( confirmIt == true)
	{
		document.location.href = page + "?id=" + id + "&mode=delete";
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to re-order
////////////////////////////////////////////////////////////////////////////////////////////////////	
function reOrder(newOrder,id,page)
{
	document.location.href = page + "?id=" + id + "&mode=reOrder&newOrder=" + newOrder;
}


/*
	Ajax stuff
*/

function GetXmlHttpObject(handler)
{
    var objXMLHttp=null
    if (window.XMLHttpRequest)
    {
        objXMLHttp=new XMLHttpRequest()
    }
    else if (window.ActiveXObject)
    {
        objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
    }
    return objXMLHttp
}

function stateChanged()
{
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    {
            document.getElementById("txtResult").innerHTML= xmlHttp.responseText;
    }
    else {
            //alert(xmlHttp.status);
    }
}

function stateChanged2()
{
   
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    {
			 document.getElementById("txtResultTeam").innerHTML= xmlHttp.responseText;
    }
    else {
            //alert(xmlHttp.status);
    }
}

// Will populate data based on input
function htmlData(url, qStr,id,subId)
{
	if (url.length==0)
    {
        document.getElementById("txtResult").innerHTML=""; 
        return;
    }
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request");
        return;
    }

    url=url+"?"+qStr+id+"&subId="+subId; 
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("GET",url,true) ;
    xmlHttp.send(null);
}

// Will populate data based on input
function populateTeam(url, qStr,id,tId)
{
	if (url.length==0)
    {
        document.getElementById("txtResultTeam").innerHTML=""; 
        return;
    }
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request");
        return;
    }

    url=url+"?"+qStr+id+"&tId="+tId; 
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange=stateChanged2;
    xmlHttp.open("GET",url,true) ;
    xmlHttp.send(null);
}

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 pos2=dtStr.indexOf(dtCh)
	var pos1=dtStr.indexOf(dtCh,pos2+1)
	var strMonth=dtStr.substring(3,5)	
	var strDay=dtStr.substring(0,2)
	var strYear=dtStr.substring(6,10)	
	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
	}
	
return true
}


/*
Function to check news form
*/

function validateNewsForm()
{
	newsTitle = '';
	newText = '';
	newsDate = '';
	
	newsTitle	= document.newsForm.newsTitle.value;
	newText	= document.newsForm.newsText.value;
	newsDate	= document.newsForm.dateFrom.value;
		
	if (newsTitle == '')
	{
		alert ('Please enter a news title');
		document.newsForm.newsTitle.focus();
		return false;
	}
	
	if (newText == '')
	{
		alert ('Please enter some news');
		document.newsForm.newsText.focus();
		return false;
	}
	
	if (newsDate == '')
	{
		alert ('Please enter a date');
		document.newsForm.dateFrom.focus();
		return false;
	}
	
	if (isDate(newsDate)==false){
		document.newsForm.dateFrom.focus();
		return false;
	}
}


/*
Function to players form
*/

function validatePlayerForm()
{
	category = '';
	subCategory = '';
	teamName = '';
	playerName = '';
	playerProfile = '';
	playerDob = '';
	
	category = document.playerForm.teamCategory.value;
	subCategory = document.playerForm.subCategory.value;
	teamName = document.playerForm.teamName.value;
	playerName = document.playerForm.playerName.value;
	playerDob = document.playerForm.playerDob.value;
		
	if (category == '')
	{
		alert ('Please choose a category');
		document.playerForm.teamCategory.focus();
		return false;
	}
	
	if (subCategory == '')
	{
		alert ('Please choose a sub category');
		document.playerForm.subCategory.focus();
		return false;
	}
	
	if (teamName == '')
	{
		alert ('Please choose team');
		document.playerForm.teamName.focus();
		return false;
	}
	
	if (playerName == '')
	{
		alert ('Please enter a name for the player');
		document.playerForm.playerName.focus();
		return false;
	}
	
	if(playerDob != '')
	{
		if (isDate(playerDob)==false)
		{
			document.playerForm.playerDob.focus();
			return false;
		}
	}	
	
	//Get text from editor and pass to hidden text field
	var oEditor = FCKeditorAPI.GetInstance('playerProfile') ; //emailBody is the instance name of the editor. Can be changed.
	contentFromEditor = oEditor.GetHTML();
	if(contentFromEditor == '')
	{
		alert ('Please enter some text for the profile');
		return false;
	}
	
	
}


/*
Function to check photo gallery form
*/

function validateGalleryForm()
{
	photoEventSelect = '';
	photoThumbnail = '';
	photoLarge = '';
	photoName = '';
	photoEvent = '';
	dateEvent = '';
	actualImage = '';
	actualImage2 = '';
	
	photoEventSelect	= document.galleryForm.photoEventsList.value;
	photoThumbnail	= document.galleryForm.photoThumbnail.value;
	photoLarge	= document.galleryForm.photoLarge.value;
	photoName	= document.galleryForm.photoName.value;
	photoEvent	= document.galleryForm.photoEvent.value;
	dateEvent	= document.galleryForm.dateEvent.value;
	if( document.galleryForm.actualImage)
	{
		actualImage = document.galleryForm.actualImage.value;
		actualImage2 = document.galleryForm.actualImage2.value;
	}
	
		
	/* Check if user has added an event name then by pass validation for select box event */
	if( photoEvent == '')
	{
		if (photoEventSelect == '')
		{
			alert ('Please choose an event from the list or create a new event');
			document.galleryForm.photoEventsList.focus();
			return false;
		}
	}
	
	//If photo event field box is not empty then we make sure the date is available
	if( photoEvent != '')
	{
		if (dateEvent == '')
		{
			alert ('Please insert a date for the event');
			document.galleryForm.dateEvent.focus();
			return false;
		}
		
		if (isDate(dateEvent)==false)
		{
			document.galleryForm.dateEvent.focus();
			return false;
		}
	}
	
	if (photoThumbnail == '' && !(actualImage))
		{
			alert ('A thumbnail image is required');
			document.galleryForm.photoThumbnail.focus();
			return false;
		}
	
	if (photoLarge == '' && !(actualImage2))
		{
			alert ('A large image is required');
			document.galleryForm.photoLarge.focus();
			return false;
		}	
		
	if (photoName == '')
		{
			alert ('A name for the photo is required');
			document.galleryForm.photoName.focus();
			return false;
		}		
	
}

function daysBetween(date1, date2) {

	var yr1=date1.substring(6,10);
	var mm1=date1.substring(3,5) -1;
	var dd1=date1.substring(0,2);
		
	var yr2=date2.substring(6,10);
	var mm2=date2.substring(3,5) -1;
	var dd2=date2.substring(0,2);

	var newDate1 = new Date();
	newDate1.setYear(yr1);
	newDate1.setMonth(mm1);
	newDate1.setDate(dd1);
	
	var newDate2 = new Date();
	newDate2.setYear(yr2);
	newDate2.setMonth(mm2);
	newDate2.setDate(dd2);
	
	if( newDate2 < newDate1 )
	{
		return 1;
	}
	else
	{
		return 0;
	}
	
}



/*
Function to validate seasons
*/

function validateSeasonsForm()
{
	season = '';
	periodStart = '';
	periodEnd = '';
	seasonStart = '';
	seasonEnd = '';
	
	
	season = document.seasonsForm.seasonName.value;
	periodStart = document.seasonsForm.periodStart.value;
	periodEnd = document.seasonsForm.periodEnd.value;
	seasonStart = document.seasonsForm.dateFrom.value;
	seasonEnd = document.seasonsForm.dateTo.value;
		
	//Checks if season name is empty	
	if (season == '')
	{
		alert ('Please put a season name');
		document.seasonsForm.seasonName.focus();
		return false;
	}
	
	/*
	if(periodStart == periodEnd)
	{
		alert ('Period start can\'t be the same as period ends');
		document.seasonsForm.periodStart.focus();
		return false;
	}*/
	
	if(periodStart > periodEnd)
	{
		alert ('Period start can\'t be greater than period ends');
		document.seasonsForm.periodStart.focus();
		return false;
	}
	
	
	if (isDate(seasonStart)==false){
		document.seasonsForm.dateFrom.focus();
		return false;
	}
	
	if (isDate(seasonEnd)==false){
		document.seasonsForm.dateTo.focus();
		return false;
	}
	
	var dayDiff = 0;
    var startDate = seasonStart;
    var endDate = seasonEnd;
    dayDiff = daysBetween(startDate, endDate);
	
	if (dayDiff == 1)
	{
		alert ('The Season end date must be greater than the season start date');
		document.seasonsForm.dateFrom.focus();
		return false;
	}
	
	
}

/*
Function to validate fixtures
*/

function validateFixturesForm()
{
	teamOne = '';
	teamTwo = '';
	stadium = '';
	matchDate = '';
	score1 = '';
	score2 = '';
		
	teamOne = document.fixturesForm.teamOne.value;
	teamTwo = document.fixturesForm.teamTwo.value;
	stadium = document.fixturesForm.stadium.value;
	matchDate = document.fixturesForm.matchDate.value;
	season = document.fixturesForm.season.value;
	
	if(document.fixturesForm.scoreOne)
	{
		score1 = document.fixturesForm.scoreOne.value;
		score2 = document.fixturesForm.scoreTwo.value;
		pageContentText = '';
	}
	
	if(document.fixturesForm.scoreOne == false)
	{
		if (teamOne == '')
		{
			alert ('Please choose team one');
			document.fixturesForm.teamOne.focus();
			return false;
		}
		
		if (teamTwo == '')
		{
			alert ('Please choose team two');
			document.fixturesForm.teamTwo.focus();
			return false;
		}
		
		if (teamOne == teamTwo)
		{
			alert ('Team one must be different to team two');
			document.fixturesForm.teamOne.focus();
			return false;
		}
		
		if (stadium == '')
		{
			alert ('Please choose a venue / stadium');
			document.fixturesForm.stadium.focus();
			return false;
		}
		
		if (matchDate == '')
		{
			alert ('Please provide a date');
			document.fixturesForm.matchDate.focus();
			return false;
		}
		
		if (isDate(matchDate)==false){
			document.fixturesForm.matchDate.focus();
			return false;
		}
		
		
		if (season == '')
		{
			alert ('Please choose a season');
			document.fixturesForm.season.focus();
			return false;
		}
	}
	
	
	if(document.fixturesForm.scoreOne)
	{
		if (score1 == '')
		{
			alert ('Please insert a score  for team 1');
			document.fixturesForm.scoreOne.focus();
			return false;
		}
		
		if (isNaN(score1))
		{
			alert ('Please insert a numerical score  for team 1');
			document.fixturesForm.scoreOne.focus();
			return false;
		}
		
		if (score2 == '')
		{
			alert ('Please insert a score  for team 2');
			document.fixturesForm.scoreTwo.focus();
			return false;
		}
		
		if (isNaN(score2))
		{
			alert ('Please insert a numerical score  for team 2');
			document.fixturesForm.scoreTwo.focus();
			return false;
		}
		
		//Get text from editor and pass to hidden text field
		var oEditor = FCKeditorAPI.GetInstance('matchReport') ; //emailBody is the instance name of the editor. Can be changed.
		contentFromEditor = oEditor.GetHTML();
		if(contentFromEditor == '')
		{
			alert ('Please enter some text for the match report');
			return false;
		}
		
	
	}
	
	
}


/*
Function to contact us page
*/

function validateContactForm()
{
	name = '';
	email = '';
	message = '';
	url = '';
	
		
	name = document.contactForm.visitor.value;
	email = document.contactForm.visitormail.value;
	message = document.contactForm.visitorMessage.value;
	
	if(document.contactForm.visitorurl.value != "")
	{
		url = document.contactForm.visitorurl.value;
	}
	
	if (name == '')
	{
		alert ('Please provide a name');
		document.contactForm.visitor.focus();
		return false;
	}
	
	if (email == '')
	{
		alert ('Please provide an email address');
		document.contactForm.visitormail.focus();
		return false;
	}
		

	if (echeck(email)==false)
	{
			document.contactForm.visitormail.focus();
			return false
	}
	
	if (message == '')
	{
		alert ('Please provide a message');
		document.contactForm.visitorMessage.focus();
		return false;
	}
	
	if(document.contactForm.visitorurl.value != "")
	{
		if(!validURL(url))
		{
			alert("This is not a correct type of url.");
			document.contactForm.visitorurl.focus();
			return false;
		}
	}
	
}	
