function CheckButtons()
{
	var disable_buttons = false;

   var refinebutton=document.getElementById("refinedates");

   //Only build up the image list if the page is fully loaded
   if(refinebutton) {
	   if(document.validimages == null)
	   {
		   var images=document.getElementsByTagName("img");

		   document.validimages = new Array();

		   for(var i=0; i< images.length ; i++)
		   {
			   if(images[i].className == "valid")
			   {
				   document.validimages.push(images[i]);
			   }
		   }
	   }
	   for(var i=0; i< document.validimages.length ; i++)
	   {
		   if(document.validimages[i].valid != true)
		   {
			   disable_buttons=true;
			   break;
		   }
	   }


      refinebutton.disabled = disable_buttons;

	   var createbutton=document.getElementById("createevent_top");
      if(createbutton)createbutton.disabled = disable_buttons;

      var createbutton_bottom=document.getElementById("createevent_bottom");
      if(createbutton_bottom)createbutton_bottom.disabled = disable_buttons;
   }
}

function nonempty(elem)
{
	if(elem.validimage ==null)
	{
		elem.validimage=elem.parentNode.getElementsByTagName("img")[0];
		
		if(elem.validimage == null)return;
	}
	if(elem.value == "")
	{
		if(elem.validimage.valid == true)
		{
			elem.validimage.src="pics/wrong.gif";
			elem.validimage.title="No text has been entered";
			elem.validimage.valid=false;
		}
	}
	else
	{
		if(elem.validimage.valid != true)
		{
			elem.validimage.src="pics/right.gif";
			elem.validimage.title="Text has been entered in this mandatory field";
			elem.validimage.valid=true;
		}
	}
	CheckButtons();
}


//This function works out the earliest date the event is allowed to start on.
//It is the earliest of:
//   1) today according to the client
//   2) today according to the server (if editing a new event)
//   3) date the event was created (according to the server, if we are editing an old event)
//   We allow dates in the past when editing an old event so if a user wants to edit a
//   description they don't have to mess with the dates

function minDate()
{
   var earliestDate = new Date(serverstartdate.getTime()); //2 or 3 whichever is appropriate
   
   var today = new Date();	  //today on the client - so don't use utc

   //We want midnight
   today.setHours(0);
   today.setMinutes(0);
   today.setSeconds(0);
   today.setMilliseconds(0);
   
   if(today < earliestDate) {
      return today;
   }
   return earliestDate;
}

var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var months=new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var monthlengths=new Array(31,28,31,30,31,30,31,31,30,31,30,31);


//This function is a mess, tidy it up.
function parseDate(elem, start, norecursion)
{
	var datestring=elem.value;

	if(start)
	{
		document.startdate=null;
		
		if(elem.otherdate==null)
		{
			elem.otherdate=document.getElementById("inenddate");
		}
		
	}
	else
	{
		document.enddate=null;
		
		if(elem.otherdate==null)
		{
			elem.otherdate=document.getElementById("instartdate");
		}
	}
	if(elem.validimage ==null)
	{
		elem.validimage=elem.parentNode.getElementsByTagName("img")[0];
	}
	
	datestring=datestring.replace(/\//g,"-");
	datestring=datestring.replace(/\./g,"-");
	
	elem.value=datestring;
	
	var datepieces=datestring.split("-");
	elem.validimage.valid=false;

	if(datepieces.length == 3)
	{
		var year=parseInt(datepieces[0],10);
		var month=parseInt(datepieces[1],10);
		var day=parseInt(datepieces[2],10);
		
		if((year>2004)&&(year<2100))
		{
			if((month>0)&&(month<13))
			{
				var mlength=monthlengths[month-1];
				
				if((mlength==28)&&(year%4 == 0))
				{
					mlength=29;
				}
				
				if((day>0)&&(day<=mlength))
				{
					var entereddate=new Date();
					entereddate.setTime(Date.UTC(year, month-1, day));	

					if(minDate()<=entereddate)
					{	
						if(start)
						{
							document.startdate=entereddate;
							
							elem.validimage.src="pics/right.gif";
							elem.validimage.valid=true;
							elem.validimage.title="Date Valid";
							
                     setCalendarDate('start',entereddate);
                     
							if(norecursion != true)parseDate(elem.otherdate,false,true);
						}
						else
						{
							if((document.startdate)&&(document.startdate > entereddate))
							{
								elem.validimage.src="pics/wrong.gif";
								elem.validimage.valid=false;
								elem.validimage.title="Date must be after the earliest possible date";
							}
							else
							{
								document.enddate=entereddate;
								elem.validimage.src="pics/right.gif";
								elem.validimage.valid=true;
								elem.validimage.title="Date Valid";
                        
                        setCalendarDate('end',entereddate);
                        
								if(norecursion != true)parseDate(elem.otherdate,true,false);
							}
						}
					}
					else
					{
						elem.validimage.src="pics/wrong.gif";
						elem.validimage.title="Date cannot be in the past";
						elem.validimage.valid=false;
					}
				}
				else
				{
					elem.validimage.src="pics/wrong.gif";
					elem.validimage.title="No valid date has been entered";
					elem.validimage.valid=false;
				}
			}
			else
			{
				if(elem.validimage.valid)elem.validimage.src="pics/wrong.gif";
				elem.validimage.title="No valid month has been entered";
				elem.validimage.valid=false;
			}
		}
		else
		{
			if(elem.validimage.valid)elem.validimage.src="pics/wrong.gif";
			elem.validimage.title="No valid year has been entered";
			elem.validimage.valid=false;
		}
	}
	else
	{
		if(elem.validimage)
		{
			if(elem.validimage.valid)elem.validimage.src="pics/wrong.gif";
			elem.validimage.title="Not a valid date";
			elem.validimage.valid=false;
		}
	}
	CheckButtons();
}


//dodaterefine creates an html table representing valid dates for
//the event dates on the initial select of the user (startdate/enddate/validdays (e.g. only
//saturdays. Internally the valids dates are represented as integers since the "serverdate"
// - the date on which the server thinks the event was created
//
//args:
// showtables = if this is true the table is displayed to the user so s/he can refine
//              the dates manually
//              if this is false the false is generated but hidden so it can be transmitted to
//              the server
// strictlyvalidddays = if this is true (usually), then if only mondays+thursdays are valid and we have a selected fri, that will be deselected.
//                         if this is false (when page is drawn for update events) then that Thursday would be included too
function doDatesRefine(showtable, strictlyvaliddays)
{
	//Delete all rows...
	var tbody=document.getElementById("refinedatestable").tBodies[0];
	
	if(tbody.rows)
	{
		while(tbody.rows.length > 0)
		{
			tbody.deleteRow(0);
		}
	}
	
	if(showtable)
	{
		document.getElementById("suggest_refine").style.display="none";
		document.getElementById("refinedatesdiv").style.display="";
		document.getElementById("createevent_top").style.display="none";
	}
	document.numdates=0;
	
	var currdate=new Date(document.startdate.getTime());
	
	//valid days determines which days (e.g. only saturdays) are valid
	var mon_valid=document.getElementById("mon_valid").checked;
	var tues_valid=document.getElementById("tues_valid").checked;
	var wed_valid=document.getElementById("wed_valid").checked;
	var thurs_valid=document.getElementById("thurs_valid").checked;
	var fri_valid=document.getElementById("fri_valid").checked;
	var sat_valid=document.getElementById("sat_valid").checked;
	var sun_valid=document.getElementById("sun_valid").checked;

	/*Get number of milliseconds since epoch start for the start date*/
	var counter = Date.UTC(document.startdate.getUTCFullYear(),document.startdate.getUTCMonth(),document.startdate.getUTCDate(),0,0,0); 
	
	/*Subtract number of milliseconds for the server start date*/
	counter -= Date.UTC(serverstartdate.getUTCFullYear(),serverstartdate.getUTCMonth(),serverstartdate.getUTCDate(),0,0,0); 
	
	counter = Math.round(counter / 86400000); //Convert milliseconds to days 

	/*Check that the "array" of selecteddates exists as we're about to update it*/
	if(!document.selectedDates)document.selectedDates = new Object();

	while(currdate <= document.enddate)
	{
		var thisvalid=false;
		
		var dayofweek = currdate.getUTCDay();
		switch(dayofweek)
		{
			case 0:
				if(sun_valid)thisvalid=true; break;
			case 1:
				if(mon_valid)thisvalid=true;	break;
			case 2:
				if(tues_valid)thisvalid=true;	break;
			case 3:
				if(wed_valid)thisvalid=true; break;
			case 4:
				if(thurs_valid)thisvalid=true; break;
			case 5:
				if(fri_valid)thisvalid=true; break;
			case 6:
				if(sat_valid)thisvalid=true; break;
		}		
		if(thisvalid == true ||
          (!strictlyvaliddays && document.selectedDates[counter] == 1))
		{
			/* If say this is a Tuesday and Tuesday's have just been added we want */
			/* this date to start ticked                                           */
			if(WasValidDate(dayofweek,currdate) == false) {
				document.selectedDates[counter] = 1;
			}
         
			if(document.numdates < 100)
			{
				addDate(currdate, counter);
			}
			else
			{
				window.alert("Only the first 100 dates will be used.");
				return false;
			}
		}
		else
		{
			/*The weekday is no longer selected so this date is no longer ticked*/
			document.selectedDates[counter] = 0;
		}
		counter++;
		currdate.setUTCDate(currdate.getUTCDate()+1);	
	}

	/* Now update the list of which weekdays (and date-range) are valid*/
	UpdateValidDates();
	
	return false;
}

function addDate(newdate, counter)
{
	var rownode=document.createElement("TR");
	var checkboxcell=document.createElement("TD");
	var datecell=document.createElement("TD");
	
	var cbox=document.createElement("input");
	cbox.type="checkbox";
	cbox.name="indivdate[]";
	cbox.value=counter;
	cbox.onclick=function(event){UpdateSelectedDates(this);}

	/*Does the user want this date*/
	var date_chosen=true;

	if(document.selectedDates && (document.selectedDates[counter] != 1) ){
		date_chosen = false;
	}
	if(date_chosen) {
		cbox.defaultChecked=true; /*Without this line it won't be checked on IE6*/
		cbox.checked=true;
	}
	var datestr=weekday[newdate.getUTCDay()]+" "+newdate.getUTCDate()+" "+months[newdate.getUTCMonth()]+" "+newdate.getUTCFullYear();
	var datenode=document.createTextNode(datestr);
	
	var tbody=document.getElementById("refinedatestable").tBodies[0];
	tbody.appendChild(rownode);
	rownode.appendChild(checkboxcell);
	checkboxcell.appendChild(cbox);
	
	rownode.appendChild(datecell);
	datecell.appendChild(datenode);
	
	document.numdates++;
}

function doCreateEvent()
{
	if(document.numdates == null )
	{
		doDatesRefine(false, true);
		if(document.numdates == 0)
		{
			window.alert("Can't create event as no valid dates were found.");
			return;
		}
	}
	else
	{
		var founddate=false;
		
      var checkbox_cont = document.getElementById('refinedatestable');
		var checkboxesandmore=checkbox_cont.getElementsByTagName("input");
		
		for(var i=0; i< checkboxesandmore.length ; i++)
		{
			if(checkboxesandmore[i].type=="checkbox" && checkboxesandmore[i].checked == true)
			{
				founddate=true;
				break;
			}
		}
		if(founddate == false)
		{
			window.alert("Can't save event details as no valid dates were found.");
			return;
		}
	}
	CheckForm('ajaxform', 'EventDatesDetails', 'outputmsg', 'outputmsg_anchor');
}

function ToggleAllEdit(cbox)
{
	var editpwrow=document.getElementById('editpwrow');
	
	if(editpwrow && cbox.checked)
	{
		editpwrow.style.display="none";
	}
	else
	{
		editpwrow.style.display="";
	}
}

/* This function stores which days (e.g. Tuesday are currently ticked)       */
/* Then when refine days is hit, we can tell whether Tuesdays were already   */
/* selected and we should change whether Tuesday dates are ticked or not.    */
/* On the other hand if Tuesdays are new, we want all Tuesday dates to start */
/* ticked                                                                    */
function UpdateValidDates()
{
	
	if(!document.oldValidDays)document.oldValidDays = new Array();
	document.oldValidDays[0]=document.getElementById("sun_valid").checked;
	document.oldValidDays[1]=document.getElementById("mon_valid").checked;
	document.oldValidDays[2]=document.getElementById("tues_valid").checked;
	document.oldValidDays[3]=document.getElementById("wed_valid").checked;
	document.oldValidDays[4]=document.getElementById("thurs_valid").checked;
	document.oldValidDays[5]=document.getElementById("fri_valid").checked;
	document.oldValidDays[6]=document.getElementById("sat_valid").checked;
	
	document.oldStartDate = document.startdate;
	document.oldEndDate   = document.enddate;
   
}


/* When the checkbox for a date is (un)ticked we update the arrays of ticked dates*/
/* So that if we re-refine the days we can retick the correct dates               */
function UpdateSelectedDates(cbox) 
{
   if(cbox.checked) {
      document.selectedDates[cbox.value]=1;
   } else {
      document.selectedDates[cbox.value]=0;
   }
}

/* Last time that UpdateValidDates() was called, was the date are given a valid*/
/* date                                                                        */
function WasValidDate(dayofweek, currdate) {
	if(!document.oldValidDays || !document.oldValidDays[dayofweek]) {
		return false;
	}
	
	if(currdate < document.oldStartDate) {
		return false;
	}
	
	if(currdate > document.oldEndDate) {
		return false;
	}
	
	return true;
}


