function checkElement(elm,checkElementValue){
	if(elm != null && elm != '' && elm != 'undefined') {
		if(checkElementValue == true) {
			if(checkElmValue(elm) == true){
				return true;	
			}
			return false;
		}
		return true;
	} else {
		return false;
	}	
}

function checkElmValue(elm){
	if(!elm) return;	
	if(elm.value != '' && elm.value != 'undefined' && elm.value != null){
		return true;
	}
	alert(elm.id + ' cannot be blank!');
	return false;
}

function toggle(link,parent,divToOpen,lastVisible,action) {
	if (action != null) { 
		if(action() == false) {
			return;
		}
	}
	var divToOpen = document.getElementById(divToOpen);
	var lastVisible = document.getElementById(lastVisible);
	var parent = document.getElementById(parent);
	var lastBlockId;

		for(var i =0; i<parent.childNodes.length; i++) {
			if(parent.childNodes[i].nodeName == 'DIV') {
				if(lastVisible == null) {
					if(parent.childNodes[i].style.display == 'block') {
						lastBlockId = parent.childNodes[i].id;
					}
				}
				parent.childNodes[i].style.display = 'none';
			}
		}
		divToOpen.style.display = 'block';
	
	if(link != null) {
		link.onclick = function(){toggle(link,parent.id,divToOpen.id,lastBlockId,action)}
	}
	return;
}

function checkForm(f) {
	if(f.elements['name'].value == null || f.elements['name'].value == '' || f.elements['name'].value == 'undefined'){
		alert('Pleae fill in your name!');
		return false;
	}
	if(f.elements['email'].value == null || f.elements['email'].value == '' || f.elements['email'].value == 'undefined') {
		alert('Please fill in your email address!');
		return false;
	}	
	if( checkEmail(f.elements['email']) != false) {
			if(jcap() == true) {
				f.submit();
				return true;
			}
		}
	return false;
}

function isEmailAddress (string) {
  var addressPattern =
    /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
  return addressPattern.test(string);
}

function checkEmail (field) {
  if (!isEmailAddress(field.value)) {
    alert('Please enter correct email address!');
    field.focus();
    field.select();
 	return (false);
  }
}

function setClassName(elm,className){	
	if(elm != undefined){
		elm.className = className;
	}
}

function displayGalleryImageInPopupDiv(imgId,imgSrc,width, height) {
	
	var html = '<img src="'+imgSrc+'" border="0" />';
	html += '<div style="padding:5px; background:#FFFFFF;font-weight:bold;text-align:right;">'+
	'<span style="cursor:pointer;background:red;color:white" onClick="closePopupDiv('+imgId+')">&nbsp;close&nbsp;</span></div>';
	var div = drawCenteredPopup(imgId,width,height+20,html);
	div.style.border = 2+'px solid #5288B5';
	div.style.background = 'white';
	div.style.padding = '0.9em';
	div.style.zIndex = 99999999999999999999;	
}
function closePopupDiv(id){
	var elm = document.getElementById(id);
	elm.style.display = 'none';
	elm.style.visibility = 'hidden';
}

function drawCenteredPopup(id,width,height,html) {  
	if (!document.getElementById(id)) {
    	var newNode = document.createElement("div");
    	newNode.setAttribute("id", id);
    	newNode.setAttribute("class", "Div");
    	newNode.setAttribute("style", "visibility: hidden");
    	newNode.setAttribute("style", "display: none");
    	document.body.appendChild(newNode);
	}
	
  	var popupDiv = document.getElementById(id);

	popupWidth = (width =='auto') ? popupDiv.offsetWidth  : width ;
	popupHeight = (height == 'auto') ? popupDiv.offsetHeight : height;
	var innerW = window.innerWidth;
	var innerH = window.innerHeight;
	
	if (document.all) {
		innerW = document.body.clientWidth;
		innerH = document.body.clientHeight;
	}

  	popupDiv.style.position = "absolute";
  	popupDiv.style.width = popupWidth;
  	popupDiv.style.height = popupHeight+'px';
  	var x = (innerW / 2) - (popupWidth / 2);
  	var y = (innerH / 2) - (popupHeight / 2); 
	  	           
  	popupDiv.style.left = x + "px";
  	popupDiv.style.top = y + "px";
  	popupDiv.style.visibility = (popupDiv.style.visibility == "visible" ? "hidden" : "visible"); //hid /vis
  	popupDiv.style.display = (popupDiv.style.display == "block" ? "none" : "block"); //none /block
  	//popupDiv.style.border = 1+'px solid black';
   	//popupDiv.style.opacity=  '.9'; //mozilla
	//popupDiv.style.filter = 'alpha(opacity=90)'; //IE
  	popupDiv.style.zIndex = 1000;
  	popupDiv.innerHTML = html;
	
 	return popupDiv;
}

function listDivisionsForSeason(seasonId){
	var playerSearchDiv = document.getElementById('playerSearchDiv');
	if(playerSearchDiv) playerSearchDiv.style.display = 'none';
	if(!seasonId || seasonId == 0){
		return;
	}
	var params = '&seasonId='+seasonId;
	var submitTo = 'actions.php?action=list_divisions_for_season'+params;
	http("GET",submitTo,listDivisionsForSeasonResp,params);
}

function listDivisionsForSeasonResp(res){
	if(!res) return;
	if(res.error){
		alert(res.error);
		return;
	}
	var divsionSelectBox = document.getElementById('divisionId');
	divsionSelectBox.options.length = 1;
	if(!res.divisionList) return;
	for(var i=0; i<res.divisionList.length;i++){
		var optn = document.createElement("OPTION");
		optn.text = res.divisionList[i].divisionName;
		optn.value = res.divisionList[i].divisionId;
		divsionSelectBox.options.add(optn);		
	}
	hide('listPlayersForTeam');
	hide('playerSearchDiv');
}

function listTeamsForDivision(divisionId){
	var playerSearchDiv = document.getElementById('playerSearchDiv');
	if (playerSearchDiv) playerSearchDiv.style.display = 'none';
	if(!divisionId || divisionId == 0) return;
	var seasonId = document.getElementById('seasonId');
	if(!seasonId || seasonId == 0) return;
	var params = '&divisionId='+divisionId+'&seasonId='+seasonId.value;
	var submitTo = 'actions.php?action=list_teams_for_season'+params;
	http("GET",submitTo,listTeamsForDivisionResp,params);
}

function listTeamsForDivisionResp(res){
	if(!res) return;
	if(res.error){
		alert(res.error);s
		return;
	}
	var teamsSelectBox = document.getElementById('teamId');
	teamsSelectBox.options.length = 1;
	if(!res.teamList) return;
	for(var i=0; i<res.teamList.length;i++){
		var optn = document.createElement("OPTION");
		optn.text = res.teamList[i].teamName;
		optn.value = res.teamList[i].teamId;
		teamsSelectBox.options.add(optn);		
	}	
}

function listHomeAndAwayTeamsForDivision(divisionId){
	if(!divisionId || divisionId == 0) return;
	var seasonId = document.getElementById('seasonId');
	if(!seasonId || seasonId == 0) return;
	var params = '&divisionId='+divisionId+'&seasonId='+seasonId.value;
	var submitTo = 'actions.php?action=list_teams_for_season'+params;
	http("GET",submitTo,listHomeAndAwayTeamsForDivisionResp,params);
}

function listHomeAndAwayTeamsForDivisionResp(res){
	if(!res) return;
	if(res.error){
		alert(res.error);
		return;
	}

	var teamSelectBoxes = new Array('homeTeamId','awayTeamId');
	for (var j = 0; j < teamSelectBoxes.length; j++) {
		var teamsSelectBox = document.getElementById(teamSelectBoxes[j]);
		teamsSelectBox.options.length = 1;
		if (!res.teamList) 
			return;
		for (var i = 0; i < res.teamList.length; i++) {
			var optn = document.createElement("OPTION");
			optn.text = res.teamList[i].teamName;
			optn.value = res.teamList[i].teamId;
			teamsSelectBox.options.add(optn);
		}
	}
}

function viewPlayersForTeamBySeason(teamId,seasonId,divisionId){
	if(!teamId || !seasonId || !divisionId) {
		alert("ERROR! Unknown teamId, seasonId or divisionId");
		return;
	}
	var params = '&teamId='+teamId+'&seasonId='+seasonId+'&divisionId='+divisionId;
	var submitTo = 'actions.php?action=list_players_team_season'+params;
	http("GET",submitTo,viewPlayersForTeamBySeasonResp,params);
}

function viewPlayersForTeamBySeasonResp(res){
	if(res.error){
		alert(res.error);
		return;		
	}
	var tbl = document.getElementById('listPlayerTable');
	var newRowIndex = emptyTable(tbl,true);	
	var temp ='';
	for(var i=0;i<res.playerList.length;i++){
		tbl.insertRow(newRowIndex);
		tbl.rows[newRowIndex].insertCell(0);
		tbl.rows[newRowIndex].cells[0].vAlign = 'top';
		tbl.rows[newRowIndex].cells[0].innerHTML = res.playerList[i].playerFirstName;
		
		tbl.rows[newRowIndex].insertCell(1);
		tbl.rows[newRowIndex].cells[1].className = '';
		tbl.rows[newRowIndex].cells[1].vAlign = 'top';
		
		if(res.playerList[i].temp == 'Y'){
			temp = '<font color=red> (L)</font>';
		}
		
		tbl.rows[newRowIndex].cells[1].innerHTML = res.playerList[i].playerLastName + temp;
		
		tbl.rows[newRowIndex].insertCell(2);
		tbl.rows[newRowIndex].cells[2].className = '';
		tbl.rows[newRowIndex].cells[2].vAlign = 'top';
		tbl.rows[newRowIndex].cells[2].innerHTML = '<input type="text" size="3" name="playerNumber'+res.playerList[i].playerId+'" id="playerNumber'+res.playerList[i].playerId+'" value="'+res.playerList[i].playerNumber+'" />';
		
		tbl.rows[newRowIndex].insertCell(3);
		tbl.rows[newRowIndex].cells[3].className = '';
		tbl.rows[newRowIndex].cells[3].vAlign = 'top';
		tbl.rows[newRowIndex].cells[3].innerHTML += '<input type="text" name="playerPosition' +i+'" id="playerPosition'+i+'" value="'+res.playerList[i].playerPosition+'"/>';
		
		tbl.rows[newRowIndex].insertCell(4);
		tbl.rows[newRowIndex].cells[4].className = '';
		tbl.rows[newRowIndex].cells[4].vAlign = 'top';
		tbl.rows[newRowIndex].cells[4].innerHTML = res.playerList[i].season;
		tbl.rows[newRowIndex].cells[4].innerHTML += '<input type="hidden" name="playerId'+i+'" id="playerId'+i+'" value="'+res.playerList[i].playerId+'"/>';
		
		newRowIndex++;
	}
	tbl.style.display = 'table';
}

function emptyTable(table,keepHeaderRow) {
	var firstRow = (keepHeaderRow == true) ? 1 : 0;
	if(table.rows.length > 0) {
		for(var j=table.rows.length; j != firstRow; j--) { //!= 1
		table.deleteRow(-1);
		}
	}	
	return table.rows.length;
}

function submitEditGame(f){
	var gameDate = f.elements['gameDate'];
	var gameTimeHrs = f.elements['gameTimeHrs'];
	var gameTimeMins = f.elements['gameTimeMins'];
	var homeTeamId = f.elements['homeTeamId'];
	var awayTeamId = f.elements['awayTeamId'];
	var divisionId = f.elements['divisionId'];
	var seasonId = f.elements['seasonId'];
	var scheduleType = f.elements['scheduleType'];
	var homeScore = f.elements['homeScore'];
	var awayScore = f.elements['awayScore'];
	var gamePlayed = f.elements['gamePlayed']
	var homeTeamPlayerIds = f.elements['homeTeamPlayerIds'];
	var awayTeamPlayerIds = f.elements['awayTeamPlayerIds'];
	
	if(checkElement(gameDate,true) == false){
		return false;
	}
	if(checkElement(gameTimeHrs,true) == false){
		return false;
	}
	if(checkElement(gameTimeMins,true) == false){
		return false;
	}
	if(checkElement(homeTeamId,true) == false){
		return false;
	}
	if(checkElement(awayTeamId,true) == false){
		return false;
	}
	//if(checkElement(divisionId,true) == false){
		//return false;
	//}
	if(checkElement(seasonId,true) == false){
		return false;
	}
	if(checkElement(scheduleType,true) == false){
		return false;
	}
	if( scheduleType.value == 'REGULAR_SEASON' && (homeScore.value != '' || awayScore.value != '') && ( gamePlayed.value == 'N' || gamePlayed.value == '') ) {
		alert('FOR THE REGULAR SEASON ONLY !!! \n\nPlease make sure to set "Game Played" flag to "Y" after entering scores!');
		//return false;
	}
	
	//calculate scores
	var homeTeamPlayerIdsArray = homeTeamPlayerIds.value.split(',');
	var homeTotalScore = 0;
	for(var i=0;i<homeTeamPlayerIdsArray.length;i++){
		var homePlayerScore = f.elements['homePlayerScore' + homeTeamPlayerIdsArray[i]];
		if(homePlayerScore){			
			homeTotalScore += (!isNaN(parseInt(homePlayerScore.value))) ? parseInt(homePlayerScore.value) : parseInt(0);
		}
	}
	var checkScores = document.getElementById('noRosters');

	if(!checkScores || !checkScores.checked){
		var homeScoreVal = (!isNaN(parseInt(homeScore.value))) ? parseInt(homeScore.value) : parseInt(0);
		if(homeScoreVal != homeTotalScore){
			alert('ERROR! Home score does not match total score by players!\n' +
			'Home Score: '+ homeScoreVal +'\nPlayers Total Score: '+ homeTotalScore );
			return false;
		}
		
		var awayTeamPlayerIdsArray = awayTeamPlayerIds.value.split(',');
		var awayTotalScore = 0;
		for(var i=0;i<awayTeamPlayerIdsArray.length;i++){
			var awayPlayerScore = f.elements['awayPlayerScore' + awayTeamPlayerIdsArray[i]];
			
			if(awayPlayerScore){		
				awayTotalScore +=  (!isNaN(parseInt(awayPlayerScore.value))) ? parseInt(awayPlayerScore.value) : parseInt(0);
			}
		}
		var awayScoreVal = (!isNaN(parseInt(awayScore.value))) ? parseInt(awayScore.value) : parseInt(0);
	
		if(awayScoreVal != awayTotalScore){
			alert('ERROR! Away score does not match total score by players!\n' +
			'Away Score: '+ awayScoreVal +'\nPlayers Total Score: '+ awayTotalScore );
			return false;
		}
	}
	
	f.submit();
	return true;
}

function hide(elmId){
	var elm = document.getElementById(elmId);
	if(!elm || elm == null) return;
	elm.style.display = 'none';
}
function show(elmId,displayType){
	var elm = document.getElementById(elmId);
	if(!elm) return;
	if(!displayType) displayType = 'block';
	elm.style.display = displayType;
}

function showGameInfo(elm,gameId){
	var div = document.getElementById('gameInfo'+gameId);	
	if(!div) return;
	div.style.position = 'absolute';
	var x =parseInt(elm.offsetLeft);
 	var y =parseInt(elm.offsetTop) + parseInt(elm.offsetHeight);

  // deal with elements inside tables and such
	var parent = elm;
	// while (parent.offsetParent) {
	parent = parent.offsetParent;
	x += parent.offsetLeft;
    y += parent.offsetTop ;
	//}
	div.style.left = (x - 220) + 'px';
	div.style.top = y  + 'px' ;
	div.style.zIndex = 10000;
	div.style.display = 'block';
}

function hideGameInfo(gameId){
	var div = document.getElementById('gameInfo'+gameId);
	if(!div) return;
	div.style.display = 'none';
}

function addTeamToSeasonAndDivision(){
	var seasonId = document.getElementById('seasonId');
	var divisionId = document.getElementById('divisionId');
	var teamId = document.getElementById('teamId');
	if(seasonId.value == -1 || divisionId.value == -1){
		alert('Please select both Season and Division!');
		return false;
	}
	var params = '&teamId='+teamId.value+'&seasonId='+seasonId.value+'&divisionId='+divisionId.value;
	var submitTo = 'actions.php?action=team_add_to_season_division'+params;
	http("GET",submitTo,addTeamToSeasonAndDivisionResp,params);
}

function addTeamToSeasonAndDivisionResp(res){
	if(res.error){
		alert(res.error);
		return false;
	}
	alert(res.success);
}
