
//globals
var g_events = new Array();
var g_currentCalendarEventDiv;
var g_currentCalendarEventId;
var g_divWidth = 0;
var g_divHeight = 80;
var g_loadEvents = true;
var g_dateBox = 'date';
var preload = new Image();preload.src = 'images/10-1.gif';


function initCalendar() {
	if (!document.getElementById('calendar')) {
		return;
	}
	placeCalendar();
	resize_divs();
	
	//default to true
	loadEventsIntoCalendar();
	document.getElementById('loadingImgDiv').style.display = 'none';
}

function toggleEventLoading(toggle){
	g_loadEvents = toggle;
}


	//	Change the width of the divs (day boxes in the calendar) according to the screensize.
function resize_divs(minWidth,screenWidth,minHeight) {
		//default to 50
		minWidth = minWidth || 80;
		g_divHeight = minHeight || 80;

		//note this also allocates 30% space for the calendar toolbox
		screenWidth = screenWidth || parseInt((document.body.clientWidth-286)-250);

		//grab the style element
		var style = document.getElementById('calendarStyle');
		
		var divWidth = parseInt(screenWidth / 7);
		if (divWidth <= minWidth){
			divWidth = minWidth;
		}
		g_divWidth = divWidth;
		
		
		
		
		//var width = new RegExp("width:[^\f\r\n]+px", "gi");
		//the new style (contains the newly calculated width)
		var replacedText = ".calendar .highlighted {cursor:pointer;border:1px dotted black;height:"+g_divHeight+"px;width:"+divWidth+"px;font-weight:bold; text-decoration:none; background:#A0CFEC;} .calendar .holder {cursor:pointer;border:1px solid black;height:"+g_divHeight+"px;width:"+divWidth+"px}"

		var parent = style.parentNode;
		parent.removeChild(style);
		//create new style element
		var ss = document.createElement('STYLE');
		ss.setAttribute('id','calendarStyle');
		parent.appendChild(ss);
	
		if (ss.styleSheet) {   // internet explorer
		    ss.styleSheet.cssText = replacedText;
			
		} else {                // firefox + else
			ss.appendChild(document.createTextNode(replacedText));			
		}
	}
	
	//load the events into the calendar


function loadEventsIntoCalendar(month,day,year) {
	var queryDate ='';
	var url ='jsonevents.php';
	
	if(typeof month!="undefined")
	 if(typeof year!="undefined")
	 if(typeof day!="undefined"){
		queryDate= year+"-"+month+"-"+day;
	}
	
	
	if (queryDate != '')
		url='jsonevents.php?date='+queryDate;
	try {
		req = new XMLHttpRequest(); /* e.g. Firefox */
	} catch(e) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
			/* some versions IE */
		} catch (e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
				/* some versions IE */
			} catch (E) {
			req = false;
			}
		}
	}
	req.open("POST",url,true);
	
	//the ajax target will return an array of event objects
	req.onreadystatechange = function() {
		if(req.readyState == 4) {
			if(req.status == 200) {
			
				//evaluate the array object
				var JSONarray=eval(req.responseText);
				g_events = JSONarray;
				for (var i = 0; i < g_events.length;i++){
					var e = g_events[i];
					//add the event to the calendar
					var day = getPartOfDate(g_events[i].eventdate,'day');
					var holder = document.getElementById('holder'+day);
					
					//hide if we have more than 5 events
					var hide ="";

					if (holder.getElementsByTagName('div').length >= 5) {
						holder.style.overflowY='scroll';
						holder.style.scrollbarFaceColor='#f0f0f0';
						holder.style.scrollbarShadowColor='#f0f0f0';
						holder.style.scrollbarHighlightColor='#626775';
						holder.style.scrollbar3dLightColor='#f0f0f0';
						holder.style.scrollbarTrackColor='#f0f0f0';
					}
										
					var calendarEventType = 'calendarEvent';
					if (g_events[i].uploaded==0) {
						calendarEventType='calendarSavedEvent';
					}
										
					//display the event on the calendar, with a bit of formatting.
					holder.innerHTML += "<"+"div title=\""+ g_events[i].eventname +"\""+ hide +" onclick='selectCalendarEvent(this,"+i+")' class='"+ calendarEventType +"' id='calendarEventDiv"+ g_events[i].eventid +"'>" +shortenName(g_events[i].eventname) + " ("+ g_events[i].eventid +")<"+"/div>";
					
				}
				//hide the loading animation
				document.getElementById('loadingImgDiv').style.display = 'none';				
				//show the calendar
				 document.getElementById('calendarContainer').style.visibility='visible';
				 
				 
				 //highlight the current day
				currentDate = getCurrentDate();
				s(parseInt(currentDate[0]),currentDate[1],currentDate[2]);
				g_currentCalendarEventId=-1;
				
				
				

			}
		}
	};

	req.send(null);
	
}

function shortenName(str) {

	//shorten the name based on the divWidth
	var limit = 10;
	
	if (g_divWidth > 0) {
		limit = parseInt(0.04 * g_divWidth);
	}
	
	if (str.length >= limit) {
		return str.substring(0,limit) + " ...";
	}else {
		return str;
	}
}

function deselectCalendarEvent(object) {
	if(g_currentCalendarEventId==-1){
		return;
	}
	if (g_events[g_currentCalendarEventId].uploaded == 1) {
		object.setAttribute('class','calendarEvent');
		object.setAttribute('className','calendarEvent');
	}else {
		object.setAttribute('class','calendarSavedEvent');
		object.setAttribute('className','calendarSavedEvent');
	}
}

function selectCalendarEvent(object,globalEventIndex) {
	//if there's a currently selected event
	if (g_currentCalendarEventDiv) {
		//deselect it
		/*g_currentCalendarEventDiv.setAttribute('class','calendarEvent');
		g_currentCalendarEventDiv.setAttribute('className','calendarEvent');*/
		deselectCalendarEvent(g_currentCalendarEventDiv);
		
		//if you're deselecting the currently selected event, clear the selection
		if(g_currentCalendarEventDiv == object) {
			g_currentCalendarEventDiv = null;
			document.getElementById('selectedDayInfo').innerHTML = ""+ object.parentNode.getElementsByTagName('div').length + " event(s)";
			//document.getElementById('selectedDayInfo').innerHTML = "Nothing Planned";
		//otherwise select the new one
		}else {
			object.setAttribute('class','selectedCalendarEvent');
			object.setAttribute('className','selectedCalendarEvent');
			//display the event info
			var eventid = g_events[globalEventIndex].eventid;
			var selectedDayInfo = document.getElementById('selectedDayInfo');
			selectedDayInfo.innerHTML = "Selected Event:<br><a href='eventdetails.php?id="+eventid +"' target='_new'><img style='width:100px;border:0px' src='crop.php?id="+eventid +"'></a><br>"+g_events[globalEventIndex].eventname; 
			
			if(g_events[globalEventIndex].uploaded == 1) {
				selectedDayInfo.innerHTML += "<br>Edit:<a class='bluelink' href='editevent.php?id="+ eventid + "'>Details</a>|<a class='bluelink' href='editimage.php?id="+ eventid + "'>Image</a>";
			}
			g_currentCalendarEventDiv = object;
			g_currentCalendarEventId = globalEventIndex;
			/*object.setAttribute('class','selectedCalendarEvent');
			object.setAttribute('className','selectedCalendarEvent');
			var eventid = g_events[globalEventIndex].eventid
		
			document.getElementById('selectedDayInfo').innerHTML = "Selected Event:<br><a href='eventdetails.php?id="+eventid +"' target='_new'><img style='width:100px;border:0px' src='crop.php?id="+eventid +"'></a><br>" + g_events[globalEventIndex].eventname+"<br>Edit:<a class='bluelink' href='editevent.php?id="+ eventid + "'>Details</a>|<a class='bluelink' href='editimage.php?id="+ eventid + "'>Image</a>";
			g_currentCalendarEventDiv = object;
			g_currentCalendarEventId = globalEventIndex;*/
		}

	//there isn't one selected, select one
	}else {
		object.setAttribute('class','selectedCalendarEvent');
		object.setAttribute('className','selectedCalendarEvent');
		//display the event info
		var eventid = g_events[globalEventIndex].eventid;
		var selectedDayInfo = document.getElementById('selectedDayInfo');
		selectedDayInfo.innerHTML = "Selected Event:<br><a href='eventdetails.php?id="+eventid +"' target='_new'><img style='width:100px;border:0px' src='crop.php?id="+eventid +"'></a><br>"+g_events[globalEventIndex].eventname; 
		if(g_events[globalEventIndex].uploaded == 1) {
			selectedDayInfo.innerHTML += "<br>Edit:<a class='bluelink' href='editevent.php?id="+ eventid + "'>Details</a>|<a class='bluelink' href='editimage.php?id="+ eventid + "'>Image</a>";
		}
		g_currentCalendarEventDiv = object;
		g_currentCalendarEventId = globalEventIndex;
	}
	
}

function showLoadingAnimation(){
	var loadingImgDiv = document.getElementById('loadingImgDiv');
	loadingImgDiv.style.display='';
	loadingImgDiv.style.border='0px solid black';
	loadingImgDiv.style.position='relative';
	loadingImgDiv.style.top='30%';
	loadingImgDiv.style.textAlign='center';
	//loadingImgDiv.style.marginLeft='-56px';
	
	loadingImgDiv.innerHTML ='';
	var loadingImg = document.createElement('img');
	
	loadingImg.setAttribute('src','images/10-1.gif');
	loadingImgDiv.appendChild(loadingImg);
	loadingImgDiv.appendChild(document.createElement('br'));
	loadingImgDiv.appendChild(document.createTextNode('Loading Events...'));
}


// retrieve an array of the current set date in the date field
// returns Array(month,day,year)
function getCurrentDate(){
 return document.getElementById(g_dateBox).value.split("-");
}

//date string must be in '6-26-2008' format
function getPartOfDate(dateString,part){
	if (dateString == null || part == null) {
		return null;
	}
	var part = part.toLowerCase();
	var splitDate = dateString.split("-");
	if (part == 'month'){
		return splitDate[0];
	}
	else if (part == 'day'){
		return splitDate[1];
	}
	else if (part == 'year'){
		return splitDate[2];
	}
	
}
function deselectCurrentDay(){
 	currentDate = getCurrentDate();
 
 //unhighlight the old one
 	 try{document.getElementById('holder'+currentDate[1]).className='holder';}
	 catch(e){}//incase new month has more days than last
}


// places the date in the "date" input field when calendar is clicked
// and highlights that day on the calendar
function s(month,day,year,event){
deselectCurrentDay();

 
 
 document.getElementById(g_dateBox).value = month+"-"+day+"-"+year;
 var holder =  document.getElementById('holder'+day);
 holder.className='highlighted';

//if this day is empty 
if (event == null){
	event = window.event;
}
if (event != null) {
	var source = event.target;
	if(source == null) {
		//ie
		source=event.srcElement;
	}
	
	//check to see if no source fired at all, aka no event
	if (source ==null) {
		//display the number of events for this day
	 	document.getElementById('selectedDayInfo').innerHTML = ""+ holder.getElementsByTagName('div').length + " event(s)";
		return;
	}
	
	if (source.id == holder.id) {
			if (g_currentCalendarEventDiv) {
				if (g_events[g_currentCalendarEventId].uploaded == 1) {
					g_currentCalendarEventDiv.setAttribute('class','calendarEvent');
					g_currentCalendarEventDiv.setAttribute('className','calendarEvent');
				}else {
					g_currentCalendarEventDiv.setAttribute('class','calendarSavedEvent');
					g_currentCalendarEventDiv.setAttribute('className','calendarSavedEvent');
				}
				//g_currentCalendarEventDiv.className = 'calendarEvent';
			}
		
		 	g_currentCalendarEventDiv = null;
		 	document.getElementById('selectedDayInfo').innerHTML = ""+ holder.getElementsByTagName('div').length + " event(s)";
	}
}
}

// navigate the calendar left/right (backward/forward)
function calendarNav(direction){
 switch (direction){
  case "left":{
   if(d.getMonth()=="0"){newMonth=11;newYear=d.getFullYear()-1;}
   else{newMonth=d.getMonth()-1;newYear=d.getFullYear()}
   break;
  }
  case "right":{
   if(d.getMonth()==11){newMonth=0;newYear=d.getFullYear()+1;}
   else{newMonth=d.getMonth()+1;newYear=d.getFullYear();}
   break;
  }
  default:{
   // do nothing. basically, if you manually set the date field
   // you can use calendarNav() with no args to refresh what day
   // is highlighted.
   // this however is only useful if you are in the same month.
   // to display a custom calendar you should really use
   // placeCalendar(month,year,day);
   break;
  }
 }

//check for valid date

var validDate = new Date(newYear,newMonth,parseInt(getCurrentDate()[1]));
newDay = validDate.getDate();

//====================================================================================
//THIS IS WHERE WE HANDLE WHAT HAPPENS AFTER YOU CLICK THE NAV BUTTONS
//====================================================================================
 // refresh the calendar
 //hide the calendar until all items have been loaded
 
 //clear the selectedDay Info
 if (g_loadEvents) {
	 document.getElementById('selectedDayInfo').innerHTML = 'Loading New Month...';
	 document.getElementById('calendarContainer').style.visibility='hidden';
	 showLoadingAnimation();
 }
 placeCalendar(newMonth,newYear);
 

 //load events from the new calendar
 if (g_loadEvents){
 	loadEventsIntoCalendar(newMonth+1,1,newYear); 
 

	//======================================================================================
 	// preserve date highlighting
 	s(newMonth+1,newDay,newYear);
 }
/* currentDate = getCurrentDate();
 if(typeof currentDate[1]!="undefined"){
     s(newMonth+1,currentDate[1],newYear);
   }*/
}



// write/refresh calendar to the calendar div
// all args optnl:
//  month - sets month of calendar; 0=january
//  year - sets year
//  day - highlight a given day

function placeCalendar(month,year,day){
 // main date object
 d=new Date();
 
if ((month == 1) || (month == 3) ||(month == 5) ||(month == 8) ||(month == 10)) {
	if (d.getDate() == 31) {
		d.setDate(1);
	}
}

 // load the date object with provided vars if any
 if(typeof month!="undefined")d.setMonth(month);
 if(typeof year!="undefined")d.setFullYear(year);
 if(typeof day!="undefined"){d.setDate(day);highlightDay=day;}

 // use this copy of the date object for local manipulation
 dx=d;



 // bring date vars to local ones
 month=d.getMonth();
 year=d.getFullYear();
 day=d.getDate();
 // configure months and weeks
// days=new Array('SU','M','TU','W','TH','F','SA');
 days=new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
 months=new Array('January','February','March','April','May','June','July','August','September','October','November','December');
 mlen=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
 if(d.getFullYear()%4==0){mlen[1]=29;} //leapyear

 // calendar start html
 cal="<table class=\"calendar\" border=\"0\" cellpadding=\"2\" cellspacing=\"0\"><tr>";
 cal+="<td class=\"nav\"><a href=\"javascript:{}\" onclick=\"calendarNav(\'left\')\">&lt;&lt;</a></td>";
 cal+="<td colspan=\"5\" class=\"month\">"+months[month]+" "+year+"</td>";
 cal+="<td class=\"nav\"><a href=\"javascript:{}\" onclick=\"calendarNav(\'right\')\">&gt;&gt;</a></td></tr><tr>";
 for(i=0;i<=6;i++){cal+="<td class=\"weekday\" id=\""+days[i]+"\">"+days[i]+"</td>";}
 cal+="</tr><tr>";

 // iterate the days and insert them
 for(i=1;i<=mlen[dx.getMonth()];i++){
  dx.setDate(i);
  iday=dx.getDay();
  
  // starting at appropriate day of the week
  if(i==1){
   for(j=0;j<iday;j++){
    cal+="<td>&nbsp;</td>";
   }
  }
  if((iday==0)&&(i!=1))cal+="<tr>";
  cal+="<td id=\""+i+"\" class=\"day\"><div class='dayofmonth'>"+i+"</div><div class='holder' onclick=\"s("+(month+1)+","+i+","+year+",event);\" id='holder"+ i +"'></div></td>";
  if((iday==6)||(i==days[month]))cal+="</tr>";
 }

 // close the calendar table
 cal+="</table>";

 // write out the calendar to the div
 document.getElementById('calendar').innerHTML=cal;

 // if a day was specified as an argument, highlight it
 if (typeof highlightDay!="undefined"){
 	s(month+1,highlightDay,year);
 }

 // and by default, if there currently is no selected date at all
 // then select the current day
 currentDate = getCurrentDate();
 if (typeof currentDate[1]=="undefined"){
 	s(month+1,day,year);
 }

}

