

/*********************************************************************************************
  Grid formatters
*********************************************************************************************/

function dateFormatter(date)
{
	if (date == "") return "";
	if (date == "0000-00-00T00:00:00") return "";
	
	var nullTime = new RegExp("T00:00:00", "i");
		
	if (date.search(nullTime) > -1)
	  return dojo.date.locale.format(dojo.date.stamp.fromISOString(date), {datePattern: "MMMM d, y", selector: "date"});
    else
      return dojo.date.locale.format(dojo.date.stamp.fromISOString(date), {datePattern: "MMMM d, y", timePattern: "hh:mm a"});
    
}

function dateFormatter2(date)
{
	if (date == "") return "";
	if (date.search(/0000-00-00T00:00:00/ig) > -1) return "";
	
    return dojo.date.locale.format(dojo.date.stamp.fromISOString(date), {datePattern: "MMMM d, y", selector: "date"});  
}

function timeFormatter(date)
{
	if (date == "") return "";
	
	var nullTime = new RegExp("T00:00:00", "i");	
	if (date.search(nullTime) > -1) return "";
			
    return dojo.date.locale.format(dojo.date.stamp.fromISOString(date), {timePattern: "hh:mm a", selector: "time"});  
}

function floatFormatter(numb)
{
  //return dojo.number.format(dojo.number.parse(numb, {places:0}), {pattern:"000.00"});
  return dojo.number.format(parseFloat(numb), {pattern:"000.00"});
}



  var eventCalStore;
  var eventCalGrid;
  var eventCalLayout = [
                      {
                        name: "Date",
                        formatter: dateFormatter2,
                        width: "10em",
                        field: "startdate"
                      },
                      {
                        name: "Start Time",
                        formatter: timeFormatter,
                        width: "7em",
                        field: "startdate"
                      },
                      {
                        name: "End Time",
                        formatter: timeFormatter,
                        width: "7em",
                        field: "enddate"
                      },
                      {
                        name: "What",
                        width: "23em",
                        field: "descrip"
                      },
                      {
                        name: "Where",
                        width: "23em",
                        field: "location"
                      }
  ];


  function indexInit()
  {
    //dojo.connect(dojo.byId("gridSearchBox"), "onkeyup", eventCalFetchForText);

    eventCalStore = new dojo.data.ItemFileReadStore({ url: "dataproviders/get-event-cal.php?year=2010", clearOnClose: true });

    eventCalGrid = new dojox.grid.DataGrid({
                query: { id: "*" },
                store: eventCalStore,
                structure: eventCalLayout,
                autoWidth: true,
                autoHeight:true,
                rowsPerPage: 20
                    }, "eventCalGridNode");

    eventCalGrid.startup();

}

function eventCalFetchForText()
{

  //include multiple search options, like: starts with, ends with, anywhere in string, etc.
  var searchTermStartsWith = dojo.byId("gridSearchBox").value + "*";
  var searchTermEndsWith = "*" + dojo.byId("gridSearchBox").value;
  var searchTermAnyMatch = "*" + dojo.byId("gridSearchBox").value + "*";

  eventCalGrid.setQuery({descrip:searchTermAnyMatch}, {ignoreCase: true});
}






function doHover(ref, imgFile)
{
  ref.src = "images/" +  imgFile + "_u.png";
}

function doHoverOut(ref, imgFile)
{
  ref.src = "images/" +  imgFile + ".png";
}


function showTab(idx, pageCount, pagePrefix, tabPrefix, showFn)
{
	for (i = 0; i < pageCount; i++)
	{
	  document.getElementById(tabPrefix + i).className = "PropertyTab";
	  document.getElementById(pagePrefix + i).style.display = "none";
	}
	
	document.getElementById(tabPrefix + idx).className = "PropertyTabSelected";
	document.getElementById(pagePrefix + idx).style.display = "block";
	
	//dijit.byId(pagePrefix).selectChild( dijit.byId(pagePrefix + idx) );
//	dojo.byId(pagePrefix).style.height = dojo.byId(pagePrefix + idx).offsetHeight + "px";

    
    if (showFn) showFn();

		
}




/************************************************************************************************
  Contact
************************************************************************************************/

function contactInit()
{
    
}



/************************************************************************************************
  People
************************************************************************************************/
function peopleInit()
{
  showTab(0, 5, 'jobDescripPages', 'jobDescripTabs');
  
}



/************************************************************************************************
  About
************************************************************************************************/
function aboutInit()
{


}






/************************************************************************************************
   best times
************************************************************************************************/



function doPoolTimesShow()
{
	bestTimesGrid2.render();
}


  var bestTimesStore;
  var bestTimesGrid;
  
  var bestTimesStore2;
  var bestTimesGrid;
  
  
  var bestTimesLayout = [
                      {
                        name: "First Name",
                        width: "8em",
                        field: "firstname"
                      },
                      {
                        name: "Last Name",
                        width: "10em",
                        field: "lastname"
                      },
                      {
                        name: "Age Group",
                        width: "7em",
                        field: "agegroupname"
                      },
                      {
                        name: "Gender",
                        width: "7em",
                        field: "gendername"
                      },
                      {
                        name: "Distance",
                        width: "7em",
                        field: "racedistance"
                      },
                      {
                        name: "Style",
                        width: "7em",
                        field: "racetypename"
                      },
                      {
                        name: "Year",
                        width: "7em",
                        field: "year"
                      },
                      {
                        name: "Time (sec)",
                        width: "7em",
                        field: "timesec"
                      }
                     ];


   var bestTimesLayout2 = [
                      {
                        name: "Record Holder",
                        width: "12em",
                        field: "Record Holder"
                      },
                      {
                        name: "Age group",
                        width: "6em",
                        field: "Age group"
                      },
                      {
                        name: "Gender",
                        width: "6em",
                        field: "Gender"
                      },
                      {
                        name: "Distance",
                        width: "6em",
                        field: "Distance"
                      },
                      {
                        name: "Style",
                        width: "8em",
                        field: "Style"
                      },                      
                      {
                        name: "Year",
                        width: "5em",
                        field: "Year"
                      },
                      {
                        name: "Tie",
                        width: "3em",
                        field: "Tie"
                      },
                      {
                        name: "Time",
                        width: "6em",
                        field: "Time"
                      }
                     ];
  
  
  function bestTimesInit()
  {
  
     bestTimesStore = new dojo.data.ItemFileReadStore({ url: "dataproviders/get-team-best-times.php" }); 
     bestTimesStore2 = new dojo.data.ItemFileReadStore({ url: "pool_records.json" });
  
     //team best times
     bestTimesGrid = new dojox.grid.DataGrid({
				query: { id: "*" },
				store: bestTimesStore,
				structure: bestTimesLayout,
				autoWidth:true,
				style:"height:27em;"				
			}, "bestTimesGridNode");
		
		bestTimesGrid.startup();
			
		
        //pool best times	
        bestTimesGrid2 = new dojox.grid.DataGrid({
				query: { id: "*" },
				store: bestTimesStore2,
				structure: bestTimesLayout2,
				autoWidth:true,
				style:"height:27em;"
			}, "bestTimesGridNode2");
			
		bestTimesGrid2.startup();
			
		showTab(0, 2, 'bestTimesPages', 'bestTimesTabs');

    }
    
    



/*****************************  helper signup functions    ***********************************/

var signupDataStore;
var signupGrid = null;

var signupLayout = [
                      {
                        name: "Person",
                        width: "11em",
                        field: "person_name"
                      },
                      {
                        name: "Last Name",
                        width: "11em",
                        field: "lastname"
                      },
                      {
                        name: "Position",
                        width: "12em",
                        field: "position"
                      },
                      {
                        name: "Opponent",
                        width: "9em",
                        field: "opp_name"
                      },
                      {
                        name: "Meet Date",
                        width: "15em",
                        field: "meetdate",
                        formatter:formatDate_DateAndTime
                      },
					 {
                        name: "Shift",
                        width: "4em",
                        field: "shift"
                      }
							 ];



function doSearchBoxKeyUp(e)
{
  if (dojo.byId("signupSearchBox").value == "")
  {
    dojo.byId("signupContent").style.display = "block";
	 dojo.byId("signupTablecontainer").style.display = "none";
	 return;
  }
  else
  {
    dojo.byId("signupContent").style.display = "none";
	 dojo.byId("signupTablecontainer").style.display = "block";
  }
  
  
  var searchTermStartsWith = dojo.byId("signupSearchBox").value + "*";  
  var searchTermEndsWith = "*" + dojo.byId("signupSearchBox").value;
  var searchTermAnyMatch = "*" + dojo.byId("signupSearchBox").value + "*";  

  var searchTermStartsWith = "person_name:" + searchTermStartsWith + " OR " + "lastname:" + searchTermStartsWith;  
  var searchTermEndsWith = "person_name:" + searchTermEndsWith + " OR " + "lastname:" + searchTermEndsWith;
  var searchTermAnyMatch = "person_name:" + searchTermAnyMatch + " OR " + "lastname:" + searchTermAnyMatch;

 // alert(searchTermAnyMatch);

  signupGrid.setQuery({complexQuery: searchTermAnyMatch}, {ignoreCase: true});
}


var meetCntr = 0;
var meetMark = new Array();
  
function helperSignupInit()
{
    signupDataStore = new dojox.data.AndOrReadStore({ url: "dataproviders/get-helper-positions.php", clearOnClose: true });
    dojo.connect(dojo.byId("signupSearchBox"), "onkeyup", doSearchBoxKeyUp);
  
  //TODO: should change the calls below so the data is just a single call to the json file; use
  //     itemfilereadstore for both
  
    dojo.xhrGet ({url: "dataproviders/get-helper-positions.php",	            
                handleAs: "json", 
                load: gotSignupDetails,
                error: gotHelperSignupError});
					 
					 
   signupGrid = new dojox.grid.DataGrid({
				query: { id: "*" },
				store: signupDataStore,
				structure: signupLayout
			}, "signupContentTable");

			signupGrid.startup();

}

function gotSignupDetails(data, xhr)
{
    var currMeet = -1;
	 var currShift = -1;
	 var isHome = "";
	 var i = 0;
	 var contentTableBody;
	 var contentTable;
	 
	 
	 for (i = 0; i < data.items.length; i++)
	 {
	   if ((currMeet != data.items[i].meet_id) || (currShift != data.items[i].shift))
		{
		   if (contentTable)
			{
			  contentTable.appendChild(contentTableBody.cloneNode(true));	
			  paneContent.appendChild(contentTable.cloneNode(true));
			}
			
			contentTable = document.createElement("table");
		   contentTableBody = document.createElement("tbody");
			dojo.addClass(contentTable, "DataTableTextBlack");
		}
	    
	 
		 if (currMeet != data.items[i].meet_id)
		 {
		   if (paneContent)
			{
			  dojo.byId("signupContent").appendChild(paneContent.cloneNode(true));
			}
			
			var paneContent = document.createElement("div");						
			paneContentId = document.createAttribute("id");
			paneContentId.nodeValue = "pane" + meetCntr;
			paneContent.setAttributeNode(paneContentId);
			paneContent.id = "pane" + meetCntr;
			meetMark[meetCntr] = i;
			meetCntr++;	
			
		 
		   if (parseInt(data.items[i].home) == 1)
			  isHome = "Home";
			else
			  isHome = "Away";

		   meetHeader = document.createElement("h3");
			meetHeaderText = document.createTextNode(data.items[i].opp_name + " - " + formatDate_DateAndTime(data.items[i].meetdate) + " - " + isHome);
			meetHeader.appendChild(meetHeaderText.cloneNode(true));
			dojo.addClass(meetHeader, "DarkText");
			
			paneContent.appendChild(meetHeader.cloneNode(true));
			 
	 	   currMeet = data.items[i].meet_id;
		 }
		 
		 if (currShift != data.items[i].shift)
		 {
		   var shiftHeaderText;
			
			
		   shiftHeader = document.createElement("h4");
			
			if (data.items[i].shift == "")
				shiftHeaderText = document.createTextNode("(available/unavailable)");
		   else
  			   shiftHeaderText = document.createTextNode("Shift " + data.items[i].shift);
				
		   dojo.addClass(shiftHeader, "DarkText");
			shiftHeader.appendChild(shiftHeaderText.cloneNode(true));
			 
			paneContent.appendChild(shiftHeader.cloneNode(true));
			 
	 	   currShift = data.items[i].shift;
					
		 }
		 
		 tRow = document.createElement("tr");
		 tCell0 = document.createElement("td");
		 tCell1 = document.createElement("td");
		 
		 tCell0Text = document.createTextNode(data.items[i].position);
		 tCell1Text = document.createTextNode(data.items[i].person_name + " " + data.items[i].lastname);
		 
		 if (
		     (data.items[i].homeonly == "1") && (data.items[i].home == "0") ||
			  (data.items[i].inshift1 == "0") && (data.items[i].shift == "1") ||
			  (data.items[i].inshift2 == "0") && (data.items[i].shift == "2")
			 )
		 {
		    dojo.addClass(tCell0, "NotApplicableCell");
		    dojo.addClass(tCell1, "NotApplicableCell");
		 }
		 
		 
		 tCell0.appendChild(tCell0Text.cloneNode(true));
		 tCell1.appendChild(tCell1Text.cloneNode(true));
	 	
		 tRow.appendChild(tCell0.cloneNode(true));	 
		 tRow.appendChild(tCell1.cloneNode(true));	        
		 contentTableBody.appendChild(tRow.cloneNode(true));	
		 
		 
		 //close out before exit
		 if (i == (data.items.length - 1))
		 {
		    if (contentTable)
			 {
			    contentTable.appendChild(contentTableBody.cloneNode(true));	
			    paneContent.appendChild(contentTable.cloneNode(true));
			 }
			 
		    if (paneContent)
 	       {
	        dojo.byId("signupContent").appendChild(paneContent.cloneNode(true));			  			  
	       }
	       meetMark[meetCntr] = i;
          meetCntr++;
		 }
	 }
	 
	 
    //did the DOM stuff first up above, now transform into dojo widgets
    for (i = 0; i < meetCntr; i++)
	 {
	    if (parseInt(data.items[meetMark[i]].home) == 1)
			  isHome = "Home";
		 else
			  isHome = "Away";
		 
 	    meetPane = new dijit.TitlePane( {title:data.items[meetMark[i]].opp_name + " - " + formatDate_DateAndTime(data.items[meetMark[i]].meetdate) + " - " + isHome, open:false, style:"color:#232323"}, dojo.byId("pane" + i)); 
	    meetPane.startup(); 
	 }
  
 
  }
  
  function gotHelperSignupError(error)
  {
    alert(error);  
  }
  
  
  function getSponsorImageIdx()
  {
  
  
  }
  
   
  var committeeJsonStore;
  var committeeGrid;

  var committeeLayout = [
                  {
                    name: "lastname",
                    width: "9em",
                    field: "lastname"
                  },
                  {
                    name: "firstname",
                    width: "12em",
                    field: "firstname"
                  },
                  {
                    name: "email",
                    width: "16em",
                    field: "email"
                  },
                  {
                    name: "committee",
                    width: "19em",
                    field: "committee"
                  }
                ];

  function doCommitteeShow()
  {
  	//committeeGrid.setQuery({lastname:"*"}, {ignoreCase: true});
  	committeeGrid.render();
  	
  }
  
  function committee_signup_init()
  {
  	  	
    dojo.connect(dojo.byId("committeeGridSearchBox"), "onkeyup", committeeFetchForText);

    committeeJsonStore = new dojo.data.ItemFileReadStore({ url: "committee_members.json", clearOnClose: true });

    committeeGrid = new dojox.grid.DataGrid({
                query: { lastname: "*" },
                store: committeeJsonStore,
                structure: committeeLayout,
                rowsPerPage: 20
                    }, dojo.byId("committeeGridNode"));

    committeeGrid.startup();
    
    }
    
    
    function committeeFetchForText()
    {

      //include multiple search options, like: starts with, ends with, anywhere in string, etc.
      var searchTermStartsWith = dojo.byId("committeeGridSearchBox").value + "*";
      var searchTermEndsWith = "*" + dojo.byId("committeeGridSearchBox").value;
      var searchTermAnyMatch = "*" + dojo.byId("committeeGridSearchBox").value + "*";

      committeeGrid.setQuery({lastname:searchTermAnyMatch}, {ignoreCase: true});
    }
    
    
    
      
    

/************************************************************************************************
  Swim Meets
************************************************************************************************/
    
function swimMeetsInit()
{
  showTab(0, 4, 'swimMeetPages', 'swimMeetTabs');

}

function formatMeetHome(dataItem)
{
   var resultStr = dataItem + "";
        
   if (dataItem== "1") resultStr = "Home";
   if (dataItem== "0") resultStr = "Away";
   
   return resultStr;
}
    
    
    
    
var meetsJsonStore;
var meetsGrid;
 
var currentSeasonMeetsStore;
var currentSeasonMeetsGrid;
 
function formatTeamName(dataValue, rowIndex) {
    
  var resultStr;

   var item = currentSeasonMeetsGrid.getItem(rowIndex);
    
    if (item) {
       var clubId = currentSeasonMeetsGrid.store.getValue(item, "opp_id");   
       resultStr =  "<a style='color:blue;' target='_blank' href='http://www.tsanc.org/src/club.php?club_id=" + clubId + "'>" + dataValue + "</a>";
        
    } else {
       resultStr = dataValue;   
    }
        
    
    
    return resultStr;
    
}
 
var meetsLayout = [
                      {
                        name: "Opponent",                        
                        width: "10em",
                        field: "name",
                        formatter:formatTeamName
                      },
                      {
                        name: "Meet Date",
                        formatter: dateFormatter,
                        width: "12em",
                        field: "date"
                      },
                      {
                        name: "Oxxford Hunt Score",                        
                        width: "9em",
                        formatter: floatFormatter,
                        field: "oxh_score"
                      },
                      {
                        name: "Opponent Score",
                        width: "9em",
                        formatter: floatFormatter,
                        field: "opp_score"
                      },
                      {
                        name: "Home-Away",
                        width: "9em",
                        field: "home",
                        formatter:formatMeetHome
                      }
  ];
  

function currentSeasonInit()
{
    currentSeasonMeetsStore = new dojo.data.ItemFileReadStore({ url: "dataproviders/get-meets.php?year=2010", clearOnClose: true });

    currentSeasonMeetsGrid = new dojox.grid.DataGrid({
                query: { id: "*" },
                store: currentSeasonMeetsStore,
                autoWidth:true,
                autoHeight:true,
                structure: meetsLayout,
                rowsPerPage: 20
                    }, "currentSeasonMeetGridContainer");

    currentSeasonMeetsGrid.startup();

}


  function meetsGridInit()
  {
    dojo.connect(dojo.byId("meetsGridSearchBox"), "onkeyup", meetsGridFetchForText);

    meetsJsonStore = new dojo.data.ItemFileReadStore({ url: "dataproviders/get-meets.php", clearOnClose: true });

    meetsGrid = new dojox.grid.DataGrid({
                query: { id: "*" },
                store: meetsJsonStore,
                structure: meetsLayout,
                autoWidth:true
                    }, "meetsGridNode");

    meetsGrid.startup();

    }
    
    function doMeetGridShow()
    {
    	meetsGrid.render();
    }

    function meetsGridFetchForText()
    {

      //include multiple search options, like: starts with, ends with, anywhere in string, etc.
      var searchTermStartsWith = dojo.byId("meetsGridSearchBox").value + "*";
      var searchTermEndsWith = "*" + dojo.byId("meetsGridSearchBox").value;
      var searchTermAnyMatch = "*" + dojo.byId("meetsGridSearchBox").value + "*";

      meetsGrid.setQuery({oppname:searchTermAnyMatch}, {ignoreCase: true});
    }

    
    
    

/******************************  age group stuff  ************************************/

var ageGroups = new Array();
ageGroups.push("6 and under");
ageGroups.push("7 - 8");
ageGroups.push("9 - 10");
ageGroups.push("11 - 12");
ageGroups.push("13 - 14");
ageGroups.push("15 - 18");



function ageGroupsInit()
{
 // dojo.connect(dojo.byId("btnTmp"), "onclick", doAgeBoxChange);
}


function doAgeBoxChange()
{

  if (dijit.byId("dobBox").attr("value") == null)
  {
    alert("Please enter a valid date of birth");
    dojo.byId("dobBox").focus();
    return;
  }

  //alert(dojo.date.locale.format(dijit.byId("dobBox").attr("value")));
  //alert(dojo.date.stamp.toISOString(dijit.byId("dobBox").attr("value")));

  var cutoffDate = dojo.date.stamp.fromISOString("2009-06-01T00:00:00");
  
  var diff = cutoffDate - dijit.byId("dobBox").attr("value");
  
  var msInDay = 86400000;  
  var diffDays = Math.floor(diff / 86400000);
  var diffYears = Math.floor(diffDays / 365);
  
  
  
  if (diffYears <= 6) group = 0;
  if ((diffYears >= 7) && (diffYears <= 8)) group = 1;
  if ((diffYears >= 9) && (diffYears <= 10)) group = 2;
  if ((diffYears >= 11) && (diffYears <= 12)) group = 3;
  if ((diffYears >= 13) && (diffYears <= 14)) group = 4;
  if ((diffYears >= 15) && (diffYears <= 18)) group = 5;
  
  //alert("Age group is: " + ageGroups[group]);
  
  dojo.byId("results").style.display = "block";
  
  dojo.byId("dobVal").firstChild.nodeValue = dojo.date.locale.format(dijit.byId("dobBox").attr("value"), {datePattern: "MMMM d, y", selector: "date"});
  dojo.byId("ag").firstChild.nodeValue = ageGroups[group];
  
}


    
