// JavaScript Document

var sessionsArray;
			

function checkIfDaysMatch(timestamp1, timestamp2){
	if(timestamp1.getFullYear() != timestamp2.getFullYear()) {
		return false;
	} else {
		if(timestamp1.getMonth() != timestamp2.getMonth()) {
			return false;
		} else {
			if(timestamp1.getDate() != timestamp2.getDate()) {
				return false;
			} else {
				return true;
			}
		}
	}
}
			
			
function getSessions() {
/*
	var loadingPanel = 
		new YAHOO.widget.Panel("wait",  
			{ width:"240px", 
			  fixedcenter:true, 
			  close:false, 
			  draggable:false, 
			  zindex:4,
			  modal:true,
			  visible:false
			} 
		);

	loadingPanel.setHeader("Loading Studio Schedule, please wait...");
	loadingPanel.setBody('<img src="http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif" />');
	loadingPanel.render(document.body);
	loadingPanel.show();
*/
	//oldPage = currentPage
	//currentPage = "book"
	// Get Studio Info
	//clientsArray = new Array();
	//client = new Object
	
	TEMPsessionsArray = new Array();
	TEMPtotalPendingInvoicesArray = new Array
	TEMPtodaysSessionsArray = new Array
	TEMPupdateActualSessionsArray = new Array
	TEMPupcomingSessionsArray = new Array
	var sUrl = "/includes/XML_studio_sessions.php"
	var loadState = "firstLoad"
	var div = document.getElementById('main_content');
	function getVal(theData,theTag) {
		if(theData.getElementsByTagName(theTag)[0] && theData.getElementsByTagName(theTag)[0].firstChild && theData.getElementsByTagName(theTag)[0].firstChild.nodeValue) {
				//alert(theData.getElementsByTagName(theTag)[0].length)
			return theData.getElementsByTagName(theTag)[0].firstChild.nodeValue;
		} else {
			return "";
		}
	}
	var handleSuccess = function(o){
		if(o.responseText !== undefined){
			if(o.responseXML == null) {
				return;
			}
			var root = o.responseXML.documentElement;
			//studio_id = root.getElementsByTagName("studio_id")[0].firstChild.nodeValue;
			//studioName = root.getElementsByTagName("studio_name")[0].firstChild.nodeValue;
			//studioLogo = root.getElementsByTagName("studio_logo")[0].firstChild.nodeValue;
			//room_id = root.getElementsByTagName("room_id")[0].firstChild.nodeValue;
			//alert(studioName)
			
			
			sessionStats = new Object;
			sessionStats.confirmed = new Array();
			sessionStats.rescheduled = new Array();
			sessionStats.declined = new Array();
			sessionStats.pending = new Array();
			sessionStats.pendingMissed = new Array();
			sessionStats.canceled = new Array();
			var sessionCount = 0
			var sessionConfirmedCount = 0
			var sessionRescheduledCount = 0
			var sessionDeclinedCount = 0
			var sessionPendingCount = 0
			var sessionPendingMissedCount = 0
			var sessionCanceledCount = 0
			var phoneNumberCount = 0
			var allSessions = root.getElementsByTagName("session");
			
			
			// Sessions
			var upcomingSessionsCount = 0
			var todaysSessionsCount = 0
			var updateActualSessionsCount = 0
			var sessionRequestsCount = 0
			var loopTest = 0
			sessionRequestsArray = new Array();
			now = new Date
			for(var i=0; i < allSessions.length; i++) {
				var tempObj = new Object
				//tempObj.session_id = getVal(allSessions[i],"session_id")
				//tempObj.user_id = getVal(allSessions[i],"user_id")
				//tempObj.client_id = getVal(allSessions[i],"client_id")
				tempObj.confirmation_status = getVal(allSessions[i],"confirmation_status")
				tempObj.studio = getVal(allSessions[i],"studio")
				//tempObj.start_timestamp = getVal(allSessions[i],"start_timestamp")
				//tempObj.end_timestamp = getVal(allSessions[i],"end_timestamp")
				
				var startTimestamp = new Date
				startTimestamp.setTime(getVal(allSessions[i],"start_timestamp")*1000);
				tempObj.startTimestamp = startTimestamp
				
				var endTimestamp = new Date
				endTimestamp.setTime(getVal(allSessions[i],"end_timestamp")*1000);
				tempObj.endTimestamp = endTimestamp
				
				var actualStartTimestamp = new Date
				actualStartTimestamp.setTime(getVal(allSessions[i],"actual_start_timestamp")*1000);
				tempObj.actualStartTimestamp = actualStartTimestamp
				
				var actualEndTimestamp = new Date
				actualEndTimestamp.setTime(getVal(allSessions[i],"actual_end_timestamp")*1000);
				tempObj.actualEndTimestamp = actualEndTimestamp
				
				
				TEMPsessionsArray[i] = tempObj;
				
				
				//if(loopTest<1) {
				//	alert(now)
				//	loopTest++
				//}
				
				if(TEMPsessionsArray[i].confirmation_status == "rescheduled") {
					//alert(TEMPsessionsArray[i].confirmation_status)
				}
				//alert('here')
				switch(TEMPsessionsArray[i].confirmation_status) {
					case "confirmed":
						sessionStats.confirmed[sessionConfirmedCount] = TEMPsessionsArray[i]
						sessionConfirmedCount++
						if(checkIfDaysMatch(now, TEMPsessionsArray[i].startTimestamp)) {
							TEMPtodaysSessionsArray[todaysSessionsCount] = TEMPsessionsArray[i]
							//alert('hi')
							todaysSessionsCount++
							
						} else {
							if(TEMPsessionsArray[i].startTimestamp>now) {
								TEMPupcomingSessionsArray[upcomingSessionsCount] = TEMPsessionsArray[i]
								//alert('hi')
								upcomingSessionsCount++
							}
						}
							
						if(TEMPsessionsArray[i].endTimestamp < now && (TEMPsessionsArray[i].actualStartTimestamp.getTime() == 0 || TEMPsessionsArray[i].actualEndTimestamp.getTime() == 0)) {
							TEMPupdateActualSessionsArray[updateActualSessionsCount] = TEMPsessionsArray[i]
							//alert('hi')
							updateActualSessionsCount++
						}
							
						break;
					case "rescheduled":
						sessionStats.rescheduled[sessionRescheduledCount] = TEMPsessionsArray[i]
						//alert(TEMPsessionsArray[i].confirmation_status+'hi')
						//alert(sessionRescheduledCount)
						sessionRescheduledCount++
						break;
					case "declined":
						sessionStats.declined[sessionDeclinedCount] = TEMPsessionsArray[i]
						if(sessionDeclinedCount == 0) {
							//alert('hey')
						}
						sessionDeclinedCount++
						break;
					case "pending":
						if(TEMPsessionsArray[i].endTimestamp<now) { // In the past
							sessionStats.pendingMissed[sessionPendingMissedCount] = TEMPsessionsArray[i]
							sessionPendingMissedCount++
						} else { // pending
							sessionStats.pending[sessionPendingCount] = TEMPsessionsArray[i]
							sessionPendingCount++
							sessionRequestsArray[sessionRequestsCount] = TEMPsessionsArray[i]
							//alert('hi')
							sessionRequestsCount++
						}
						break;
					case "canceled":
						sessionStats.canceled[sessionCanceledCount] = TEMPsessionsArray[i]
						sessionCanceledCount++
						break;
				}
				//alert('there')
			}
		}
		
		//clientsArray = TEMPclientsArray
		sessionsArray = TEMPsessionsArray
		//sessionDetailsArray = TEMPsessionDetailsArray
		//sessionRemindersArray = TEMPsessionRemindersArray
		//invoicesArray = TEMPinvoicesArray
		//paymentsArray = TEMPpaymentsArray
		//discountsArray = TEMPdiscountsArray
		//phoneNumbersArray = TEMPphoneNumbersArray
		//songsArray = TEMPsongsArray
		todaysSessionsArray = TEMPtodaysSessionsArray
		updateActualSessionsArray = TEMPupdateActualSessionsArray
		//totalPendingInvoicesArray = TEMPtotalPendingInvoicesArray
		upcomingSessionsArray = TEMPupcomingSessionsArray
		//document.getElementById('main_content').innerHTML = "Ready"
		lastUpdate = new Date
		//loadingPanel.hide();
		
		//var page = YAHOO.util.History.getCurrentState("page");
		//var id = YAHOO.util.History.getCurrentState("id");
		//var tab = YAHOO.util.History.getCurrentState("tab");
		//alert(id)
		if(loadState == "firstLoad") {
			loadState = "loaded"
			renderCal();
			//loadBookingForm()
			/*
			if(page == "client") {
				//alert("hello"+id)
				//if(lastGotClient != id) {
				getClientInfo(id)
				tabView.set('activeIndex', tab);
				//}
			} else {
				if(page == "session") {
					//alert("hello"+id)
					//if(lastGotClient != id) {
					getSessionInfo(id)
					sessionTabs.set('activeIndex', tab);
					//}
				} else {
					loadMainPage()
				}
			}
			*/
		} else {
			/*
			if(currentPage == "main") {
				loadMainPage()
			}
			*/
		}
		//alert(lastUpdate)
		//content.style.visibility = "visible";

	}
	
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			div.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
			div.innerHTML += "<li>HTTP status: " + o.status + "</li>";
			div.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
		}
	}
	
	var callback =
	{
	  success: handleSuccess,
	  failure: handleFailure,
	  argument: { foo:"foo", bar:"bar" }
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
}


function pluralCheck(singular_word, plural_word, number) {
	//alert('hi')
	if(number == 1) {
		return singular_word;
	} else {
		return plural_word;
	}
}

function handleSelect(type,args,obj) {
	var dates = args[0];
	var date = dates[0];
	var year = date[0], month = date[1], day = date[2];

	var selected = args[0];
	var selDate = this.toDate(selected[0]);
	//getSchedule(selDate.getTime()/1000)
	var sessionCount = 0
	var foundSessionID = 0
	var foundSessions = new Array
	for(i=0; i<sessionsArray.length; i++) {
		//if(sessionsArray[i].client_id == session.client.client_id) {
			var calDateTime = 
				(selDate.getMonth()+1) + '/' + selDate.getDate() + '/' + selDate.getFullYear()
			var sessionDateTime =
				(sessionsArray[i].startTimestamp.getMonth()+1) + '/' + sessionsArray[i].startTimestamp.getDate() + '/' + sessionsArray[i].startTimestamp.getFullYear()
			if(calDateTime == sessionDateTime) {
				//alert(selDate)
				//foundSessionID = session.client.sessions[i].session_id
				foundSessions[sessionCount] = sessionsArray[i]
				sessionCount++
				//break;
			}
		//}
	}
	
	var sessionCalDateDisplay = (foundSessions[0].startTimestamp.getMonth()+1) + '/' + foundSessions[0].startTimestamp.getDate() + '/' + foundSessions[0].startTimestamp.getFullYear()
	
	now = new Date
	var had_have = "had"
	//alert(now+" "+foundSessions[0].startTimestamp)
	if((now)<foundSessions[0].startTimestamp) {
		had_have = "have"
	}
	
	foundSessionsDisplay = 
		"You "+had_have+" "+foundSessions.length+" "+pluralCheck('session', 'sessions', foundSessions.length)+" on "+sessionCalDateDisplay+"<br /><br />"
	for(i=0; i<foundSessions.length; i++) {
		confirmationStatus = ""
		if(foundSessions[i].confirmation_status != "confirmed") {
			confirmationStatus = " ("+foundSessions[i].confirmation_status+")"
		}
		if(foundSessions[i].actualStartTimestamp.getTime() != 0 && foundSessions[i].actualEndTimestamp.getTime() != 0) {
			foundSessionsDisplay += 
				"<a href='#' style='color:blue;' onclick='multipleOnDay.hide(); return false;'>"+sessionsArray[i].studio+": "+displayTime(foundSessions[i].actualStartTimestamp)+" - "+displayTime(foundSessions[i].actualEndTimestamp)+confirmationStatus+"</a><br />"
		} else {
			foundSessionsDisplay += 
				"<a href='#' style='color:blue;' onclick='multipleOnDay.hide(); return false;'>"+sessionsArray[i].studio+": "+displayTime(foundSessions[i].startTimestamp)+" - "+displayTime(foundSessions[i].endTimestamp)+confirmationStatus+"</a><br />"
		}
	}
	multipleOnDay = new YAHOO.widget.Panel("panel2"+Math.floor(Math.random()*11000), { 
															width:"350px", 
															constraintoviewport:true,
															  fixedcenter:true, 
															  close:true, 
															  draggable:true, 
															  zindex:4,
															  modal:false,
															  visible:true
															} );
	multipleOnDay.setHeader("Session Info");
	multipleOnDay.setBody(foundSessionsDisplay);
	//YAHOO.example.container.panel2.setFooter("End of Panel #2");
	multipleOnDay.render("doc");
	
	//alert('hi')
	//multipleOnDay.show();
	var txtDate1 = document.getElementById("date1");
				//alert(this);
	//txtDate1.innerHTML = "Schedule for <b>"+dateToLocaleString(selDate, this)+"</b>";
	fullDateDisplay = dateToLocaleString(selDate, this);
	dayOfTheWeek = dateTodDayOfTheWeek(selDate, this);

	//alert('hi')
}

function displayTime(timestamp){
	hour = timestamp.getHours();
	var tag = "AM";
	if (hour > 12) {
		hour = hour - 12;
		tag = "PM";
	}
	
	if (hour == 12) {
		//hour = hour - 12;
		tag = "PM";
	}
	if (hour == 0) {
		hour = 12;
		//tag = "PM";
	}
			
	var minutes =  "0" + timestamp.getMinutes()
	return hour+":"+minutes.substr(-2,2)+" "+tag
}
function displayTimeSec(timestamp){
	hour = timestamp.getHours();
	var tag = "AM";
	if (hour > 12) {
		hour = hour - 12;
		tag = "PM";
	}
	
	if (hour == 12) {
		//hour = hour - 12;
		tag = "PM";
	}
	if (hour == 0) {
		hour = 12;
		//tag = "PM";
	}
			
	var minutes =  "0" + timestamp.getMinutes()
	var seconds =  "0" + timestamp.getSeconds()
	return hour+":"+minutes.substr(-2,2)+":"+seconds.substr(-2,2)+" "+tag
}
function dateToLocaleString(dt, cal) {
	//alert('hi');
	var wStr = cal.cfg.getProperty("WEEKDAYS_LONG")[dt.getDay()];
	var dStr = dt.getDate();
	var mStr = cal.cfg.getProperty("MONTHS_LONG")[dt.getMonth()];
	var yStr = dt.getFullYear();
	return (mStr + " " + dStr + ", " + yStr);
}
function dateTodDayOfTheWeek(dt, cal) {
	//alert('hi');
	var wStr = cal.cfg.getProperty("WEEKDAYS_LONG")[dt.getDay()];
	var dStr = dt.getDate();
	var mStr = cal.cfg.getProperty("MONTHS_LONG")[dt.getMonth()];
	var yStr = dt.getFullYear();
	return (wStr);
}
/*
function renderCal() {
	//var sessionsArray = new Array
	var calendar = new YAHOO.widget.Calendar("calendarContainer",{navigator:true});
	
	for(i=0; i<sessionsArray.length; i++) {
		//var startTimestamp = monthSessionsArray[i].start_timestamp
		if(sessionsArray[i].confirmation_status == "confirmed") {
			var sessionStartTimestamp = new Date()
			sessionStartTimestamp.setTime(sessionsArray[i].startTimestamp.getTime());
			var sessionDateDisplay = (sessionStartTimestamp.getMonth()+1) + '/' + sessionStartTimestamp.getDate() + '/' + sessionStartTimestamp.getFullYear()
			calendar.addRenderer(sessionDateDisplay, calendar.renderCellStyleHighlight1);
			//alert('hi')
		} else {
			var sessionCalDateDisplay = (sessionsArray[i].startTimestamp.getMonth()+1) + '/' + sessionsArray[i].startTimestamp.getDate() + '/' + sessionsArray[i].startTimestamp.getFullYear()
			//alert(sessionCalDateDisplay)
			calendar.addRenderer(sessionCalDateDisplay, calendar.renderCellStyleHighlight3);
		}
	}
		//alert(sessionDateDisplay)
	//calendar.addRenderer("6/28/2009", calendar.renderCellStyleHighlight2);
	now = new Date
	/*
	if(bookMode == "reschedule") {
		now.setTime(session.startTimestamp)
	}
	*/
	/*
	todaysDateFormatted = (now.getMonth()+1) + "/" + now.getDate() + "/" + now.getFullYear()
	calendar.select(todaysDateFormatted);
	calendar.cfg.setProperty("pagedate", (now.getMonth()+1) + "/" + now.getFullYear());
	//alert(todaysDateFormatted)
	//calendar.cfg.setProperty("mindate", todaysDateFormatted);
	//calendar.doCellMouseOver = function(e, call) {
	//	document.getElementById('fullDateDisplay').innerHTML = 'here';
	//}
	calendar.selectEvent.subscribe(handleSelect, calendar, true);
	calendar.render(); 
	//alert('hello')
	
}
*/
