

//just gets a guaranteed unique string, to use for id's etc.
function getUidStr()
{
  return dojox.uuid.generateRandomUuid();
}


/*********************************************************************************************
  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"});  
}


//grays and strikethroughs past dates
function dateFormatterStrikePast(date)
{
	if (date == "") return "";
	if (date.search(/0000-00-00T00:00:00/ig) > -1) return "";
	
	var resultStr = "";
	var d = new Date();
	var dEpoch = d.getTime();
	
	var cellDate = dojo.date.stamp.fromISOString(date);
	var cellDateEpoch = cellDate.getTime();
	
	if (cellDateEpoch >= dEpoch) {
		resultStr =  dojo.date.locale.format(dojo.date.stamp.fromISOString(date), {datePattern: "MMMM d, y", selector: "date"});	
	} else {
		resultStr = "<span style='color:gray;text-decoration: line-through;'>" + dojo.date.locale.format(dojo.date.stamp.fromISOString(date), {datePattern: "MMMM d, y", selector: "date"}) + "</span>";
	}
    
    
    return resultStr;
    
}


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: dateFormatterStrikePast,
                        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"
                      }
  ];

  var newsStore;
  
  function gotNewsItems(items, xhr) {
		var i = 0;
		
		console.log("in gotNewsItems");
		
		if (!items) {
			dojo.create("li", {innerHTML:"(no news to display)"}, "newsList");
			return;
		}
		
		if (items.length <= 0) {
			dojo.create("li", {innerHTML:"(no news to display)"}, "newsList");
			return;
		}
		
		for (i = 0; i < items.length; i++) {
			dojo.create("li", {innerHTML:items[i].description}, "newsList");
		}
	}
  
  function gotNewsItemsError(err) {
	  alert("gotNewsItems Error: " + err);
  }
  
  
  function newsInit() {
	  if (!newsStore) newsStore = dojo.data.ItemFileReadStore({url:"dataproviders/get-news.php", clearOnClose:true});
    
    newsStore.close();
	newsStore.fetch({query:{id:"*"}, onComplete:gotNewsItems, onError:gotNewsItemsError});
    
  }
  
  function impDatesInit() {
	   eventCalStore = new dojo.data.ItemFileReadStore({ url: "dataproviders/get-event-cal.php?year=2011", clearOnClose: true });

    eventCalGrid = new dojox.grid.DataGrid({
                query: { id: "*" },
                store: eventCalStore,
                structure: eventCalLayout,
                autoWidth: true,
                autoHeight:true,
                rowsPerPage: 20
                    }, "eventCalGridNode");

    eventCalGrid.startup();
  }
  
  function indexInit()
  {
    //dojo.connect(dojo.byId("gridSearchBox"), "onkeyup", eventCalFetchForText);
	  
	

   
    
    
    

}

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();

		
}







/************************************************************************************************
  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 teamBestTimesInit() {
	   bestTimesStore = new dojo.data.ItemFileReadStore({ url: "dataproviders/get-team-best-times.php" });  
	   
	   //team best times
     bestTimesGrid = new dojox.grid.DataGrid({
				query: { id: "*" },
				store: bestTimesStore,
				structure: bestTimesLayout,
				autoWidth:true,
				style:"height:27em;"				
			}, "bestTimesGridNode");
		
		bestTimesGrid.startup();
			
   }
   
  function poolBestTimesInit()
  {
  
     
     bestTimesStore2 = new dojo.data.ItemFileReadStore({ url: "pool_records.json" });
  
    
		
        //pool best times	
        bestTimesGrid2 = new dojox.grid.DataGrid({
				query: { id: "*" },
				store: bestTimesStore2,
				structure: bestTimesLayout2,
				autoWidth:true,
				style:"height:27em;"
			}, "bestTimesGridNode2");
			
		bestTimesGrid2.startup();
			
	

    }
    
    



/*****************************  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;

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();

}

var meetSignupContainers = [];
var tblBody = [];

function gotSignupDetails(data, xhr) {

	 var isHome = "";
	 var i = 0;
	 var attachNodeId = "signupContent";
	 
	 if (!data) {
		 dojo.create("div", {innerHTML:"(There is no signup information to show)"}, attachNodeId);
		 return;
	 }
	 
	 if (!(data.items)) {
		 dojo.create("div", {innerHTML:"(There is no signup information to show)"}, attachNodeId);
		 return;
	 }
	 
	 for (i = 0; i < data.items.length; i++)
	 {
		 
		tblId = "table" +  data.items[i].meet_id + data.items[i].shift;
		tblBodyId = "tableBody" +  data.items[i].meet_id + data.items[i].shift;
		titlePaneId = "titlePane" + data.items[i].meet_id;
		
		
		if (parseInt(data.items[i].home) == 1)
			  isHome = "Home";
			else
			  isHome = "Away";
		
		if (!(dijit.byId(titlePaneId))) {

		  meetSignupContainers[data.items[i].meet_id] = new dijit.TitlePane( {id:titlePaneId, title:data.items[i].opp_name + " - " + formatDate_DateAndTime(data.items[i].meetdate) + " - " + isHome, open:false, style:{color:"#232323"}}).placeAt("signupContent");
		  meetSignupContainers[data.items[i].meet_id].startup();
		  
		  dojo.create("h3", {innerHTML:data.items[i].opp_name + " - " + formatDate_DateAndTime(data.items[i].meetdate) + " - " + isHome}, meetSignupContainers[data.items[i].meet_id].containerNode);
		  		  
		}
		
		//if haven't previously encountered this meet/shift combo then create the container for it
		if (!(dojo.byId(tblId))) {
			
			if (data.items[i].shift == "")
				shiftHeader = dojo.create("h4", {innerHTML:"(available/unavailable)"}, meetSignupContainers[data.items[i].meet_id].containerNode);
		    else
			   shiftHeader = dojo.create("h4", {innerHTML:"Shift " + data.items[i].shift}, meetSignupContainers[data.items[i].meet_id].containerNode);

			
			tbl = dojo.create("table", {id:tblId}, meetSignupContainers[data.items[i].meet_id].containerNode);
			tblBody[tblBodyId] = dojo.create("tbody", {id: tblBodyId}, tbl);
		}

		 
		 tRow = dojo.create("tr", {}, tblBody[tblBodyId]);
		 tCell0 = dojo.create("td", {innerHTML:data.items[i].position}, tRow);
		 tCell1 = dojo.create("td", {innerHTML:data.items[i].person_name + " " + data.items[i].lastname}, tRow);

		 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");
		 }

	 }
	
}
  
  function gotHelperSignupError(error)
  {
    alert(error);  
  }
  
  
  function getSponsorImageIdx()
  {
  
  
  }
  
   
  var committeeJsonStore;
  var committeeGrid;

  var committeeLayout = [
                  {
                    name: "Last Name",
                    width: "12em",
                    field: "lastname"
                  },
                  {
                    name: "First Name",
                    width: "25em",
                    field: "parentcontact"
                  },                  
                  {
                    name: "Committee",
                    width: "18em",
                    field: "committeename"
                  }
                ];

  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: "dataproviders/get-family-committees.php?currentyear=true", clearOnClose: true });

    committeeGrid = new dojox.grid.EnhancedGrid({
                query: { lastname: "*" },
                store: committeeJsonStore,
                structure: committeeLayout,
                autoWidth:true,
                autoHeight:false,
                style:{height:"15em"}
                    }, 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');

}

var mapScript;


//would rather pass params into initializeMap fn, but doesn't seem to be a way
var initMapParams = {gblMapLat:null, gblMapLong:null, canvasElementId:"", opponentName:""};

function initializeMap() {
	
    var myLatlng = new google.maps.LatLng(initMapParams.gblMapLat, initMapParams.gblMapLong);
    
    var opts = {
      zoom: 15,
      center: myLatlng,      
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      draggable:true
    };
    
    var meetMap = new google.maps.Map(dojo.byId(initMapParams.canvasElementId), opts);
    
    var _marker = new google.maps.Marker({clickable:true, draggable:false, position:myLatlng, title:initMapParams.opponentName, map:meetMap});
    
  }

var mapLocDlg;
var userCurrentPos = {populated:false, latitude:0, longitude:0, accuracy:0};

function showOppMap(latitude, longitude, oppName) {
	
	var uid = getUidStr();
	
	initMapParams.gblMapLat = latitude;
	initMapParams.gblMapLong = longitude;
	initMapParams.opponentName = oppName;
	
	initMapParams.canvasElementId = "mapCanvas";
	
	

	if (mapLocDlg) {
		mapLocDlg.destroyRecursive(false);
	}

	
	mapLocDlg = new dijit.Dialog({style:{width:"750px", height:"550px"}, title:"Location of " + oppName, id:"swimMeetMapDlgContainerWidget"});
	contDiv = dojo.create("div", {style:{width:"700px", height:"500px"}}, mapLocDlg.containerNode);
	mapLocDlg.show();
	
	var tabCont = new dijit.layout.TabContainer({id:uid + "tabs", style:{}, doLayout:false}, contDiv);
	
	var pg0 = new dijit.layout.ContentPane({id:uid +"page0", title:"Map"});
    pg0.startup();
    tabCont.addChild(pg0);
	
    var pg1 = new dijit.layout.ContentPane({id:uid +"page1", title:"Directions"});
    pg1.startup();
    tabCont.addChild(pg1);
    
    tabCont.startup();
    tabCont.resize();
    tabCont.selectChild(pg0);
    
    
	dojo.create("div", {id:initMapParams.canvasElementId, style:{margin:"1em", width:"650px", height:"475px"}}, pg0.containerNode);

	directionsInfoNode = dojo.create("div", {}, pg1.containerNode);

	
	//TODO: need to figure out how to make this more global to the site, instead of just this fn, so could use elsewhere in the overall site
	if (!mapScript) {
		mapScript = dojo.create("script", {src: "http://maps.google.com/maps/api/js?sensor=false&callback=initializeMap", type:"text/javascript"}, dojo.body());
	} else {
		initializeMap();
	}
	
	var gotDir = function(data, xhr) {
  	     var i = 0;
  	     var j = 0;    	                	    
  	     var detailsStr = "";
  	     var d = new Date();
 	     var uid = d.getTime();
 	     
 	     dojo.create("h4", {style:{color:"#232323"}, innerHTML:"Total " + data.routes[0].legs[0].distance.text + ", " + data.routes[0].legs[0].duration.text}, pg1.containerNode);
 	   

 	     ol = dojo.create("ol", {}, pg1.containerNode);

         for (i = 0; i < data.routes[0].legs[0].steps.length; i++) {
         	li = dojo.create("li", {style:{color:"#232323"}, id:uid + i + "option", innerHTML: data.routes[0].legs[0].steps[i].html_instructions + "; travel " + data.routes[0].legs[0].steps[i].distance.text}, ol);
         }

        };
        
     var gotCurrPos = function(position) {
        	
        	console.log("in gotCurrPos; position = ");
        	console.dir(position);
        	
        	//TODO: could use navigator.geolocation.watchPosition instead of getCurrentPosition, which seems to not succeed on repeated calls
        	//for mobile, would definitely want to use watchPosition; but for desktop like this, not as important.
        	userCurrentPos.latitude  = position.coords.latitude;
        	userCurrentPos.latitude  = position.coords.latitude;
        	userCurrentPos.accuracy = position.coords.accuracy;
        	
        	
        	var _p = position.coords.latitude + "," + position.coords.longitude;
        	
        	directionsInfoNode.innerHTML = "Using your current location as the starting point (starting point accuracy is within " + position.coords.accuracy + " meters)";
        	  
        	
        	dojo.xhrGet({url:"dataproviders/get-meet-directions.php", 
                handleAs:"json",
                content:{origin:_p, dest:latitude + "," + longitude},
                load: gotDir ,
                error: function(err){console.log("xhrget error"); console.dir(err); }});
      	};
      	
      	
      	var useSavedCurrPos = function() {
            directionsInfoNode.innerHTML = "Using your current location as the starting point (starting point accuracy is within " + userCurrentPos.accuracy + " meters)";
        	  
            var _p = userCurrentPos.latitude + "," + userCurrentPos.longitude;
        	
        	dojo.xhrGet({url:"dataproviders/get-meet-directions.php", 
                handleAs:"json",
                content:{origin:_p, dest:latitude + "," + longitude},
                load: gotDir ,
                error: function(err){console.log("xhrget error"); console.dir(err); }});
      	};
      	
      	//if error getting users current location, or geolocation not supported then will default to oxh pool
      	var gotCurrPosErr = function(err) {
      		
      		if (err) {
      		  console.log("gotCurrPos Error " + err.code);
      		  if (err.message) console.log(err.message);
      		}
      		
      		//lat long of the oxh pool
      	    var oxhPoolCoords = "35.774342,-78.820664";
    
      	    
      	  directionsInfoNode.innerHTML = "Using Oxxford Hunt Pool as the starting point";
      	  
      		
      		dojo.xhrGet({url:"dataproviders/get-meet-directions.php", 
                handleAs:"json",
                content:{origin:oxhPoolCoords, dest:latitude + "," + longitude},
                load: gotDir ,
                error: function(err){console.log("xhrget error"); console.dir(err); }});
      		
      	};
        

	  	//try to get the user's current location so we can give directions based on that; if error or user doesn't allow, then oxh pool coords will be the starting point.
	    if (navigator.geolocation) {
	    	
	    	if (userCurrentPos.populated) {
	    		useSavedCurrPos();
	    	} else {
	    		navigator.geolocation.getCurrentPosition(gotCurrPos, gotCurrPosErr, {enableHighAccuracy: true, timeout: 10000, maximumAge:0});	
	    	}
	        
	    	console.log("geolocation supported");
	    } else {
	    	console.log("geolocation not supported");
	    	gotCurrPosErr();
	    }
	    
	 
	 
	 mapLocDlg._position();
	 
}


function formatMeetHome(dataItem, rowIndex)
{
   var resultStr = dataItem + "";
   
   var item = this.grid.getItem(rowIndex);    
   var _lat = this.grid.store.getValue(item, "latitude");
   var _long = this.grid.store.getValue(item, "longitude");
   var oppName = this.grid.store.getValue(item, "name");
        
   if (dataItem== "1") resultStr = "Home";
   
   if (dataItem== "0") {
	   if (_lat != "") {
		    resultStr = "Away <a style='color:blue;'  href='javascript:void(0);' onclick=\"showOppMap(" + _lat + "," + _long + ",'" + oppName  + "');\">map. . .</a>";   
	   } else {
		   resultStr = "Away <span style='color:silver'>(no map available)</span>";
	   }
   }
   
   
   
   return resultStr;
}
    

    
var meetsJsonStore;
var meetsGrid;
 
var currentSeasonMeetsStore;
var currentSeasonMeetsGrid;
 
function formatTeamName(dataValue, rowIndex) {
    
	
	//console.log("in formatTeamName; grid = " + this.grid);
	//console.dir(this);
	
	  var resultStr;

	   var item = this.grid.getItem(rowIndex);
	    
	    if (item) {
	       var clubId = this.grid.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: "15em",
                        field: "date"
                      },
                      {
                        name: "Oxxford Hunt Score",                        
                        width: "11em",
                        formatter: floatFormatter,
                        field: "oxh_score"
                      },
                      {
                        name: "Opponent Score",
                        width: "11em",
                        formatter: floatFormatter,
                        field: "opp_score"
                      },
                      {
                        name: "Home-Away",
                        width: "22em",
                        field: "home",
                        formatter:formatMeetHome
                      }
  ];
  

function currentSeasonInit()
{
    currentSeasonMeetsStore = new dojo.data.ItemFileReadStore({ url: "dataproviders/get-meets.php?usecurrentyear=true", 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.store.close();
      meetsGrid.setQuery({name: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];
  
}




/******************************************************************************************
 *   Contacts
 ******************************************************************************************/
    
var contactsStore;

function contactInit()
{
  
}

function gotContacts(items, xhr, attachNodeId) {
	
	
	if (!items) return;
	if (items.length <= 0) return;
	
	var i = 0;
	
	tbl = dojo.create("table", {}, attachNodeId );
	dojo.addClass(tbl, "DataTable");
	
	tblBody = dojo.create("tbody", {}, tbl );
	
	for (i = 0; i < items.length; i++) {
		tr = dojo.create("tr", {}, tblBody);
		td = dojo.create("td", {innerHTML:items[i].firstname + " " + items[i].lastname}, tr);
		td = dojo.create("td", {}, tr);
		a = dojo.create("a", {href:"mailto:" + items[i].email, innerHTML:items[i].email}, td);
		
		td = dojo.create("td", {innerHTML:items[i].role}, tr);
	}
	
}

function getBoardContacts() {	
	
    if (!contactsStore) contactsStore = new dojo.data.ItemFileReadStore({url:"dataproviders/get-contacts.php", clearOnClose:true});
    gotObj = {_attachNodeId: "contactsBoardContainer", doGot: function(items, xhr){ gotContacts(items, xhr, this._attachNodeId); } };
    contactsStore.fetch({query:{category:"board"}, onComplete:dojo.hitch(gotObj, "doGot")});
}


function getCoachContacts() {	
	
    if (!contactsStore) contactsStore = new dojo.data.ItemFileReadStore({url:"dataproviders/get-contacts.php", clearOnClose:true});
    gotObj = {_attachNodeId: "contactsCoachContainer", doGot: function(items, xhr){ gotContacts(items, xhr, this._attachNodeId); } };
    contactsStore.fetch({query:{category:"coach"}, onComplete:dojo.hitch(gotObj, "doGot")});
}




