// JavaScript Document

function vs_dateClicked(y, m, d) {
	document.location.href = "../home/?d=" + y + "/" + m + "/" + d;
}

// JavaScript Document
var gDAY_LIST = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var gAjaxContactList;
var gIntervals = new Array();
var gSuggestSelected = new Array();

function ee_submitEvent() {
	if(trim($F('tit')) == '') {
		ee_alertError("Event title cannot be blank");
		return false;
	} else if(trim($F('dates')) == '') {
		ee_alertError("Event must occur on at least one date");
		return false;		
	} else if(trim($F('sta')) == '') {
		ee_alertError("Event must have a start time");
		return false;		
	} else if(trim($F('end')) == '') {
		ee_alertError("Event must have a end time");
		return false;		
	}	
	
	document.eventform.submit();
}

function ee_insertTime(from, target) {
	$(target).value = from.options[from.selectedIndex].value;
	from.selectedIndex = 0;
	from.blur();
	
	if(target == 'sta') {
		ee_startTimeChanged();
	}	else if(target == 'end') {
		ee_endTimeChanged();
	}
}

function ee_timeFieldsChanged() {
	ee_updateDuration();
}

function ee_startTimeChanged() {
	if(!verifyTimeFormat($('sta'))) {
		ee_alertError("INVALID TIME FORMAT");
		$('sta').value = '';
		return;
	}
	
	forceTimeFormat($('sta'));
	
	if($F('end') == '')	{
		var newHour = getHours($F('sta')) + 1;
		if(newHour == 24)	{
			newHour = 0;
		}
		
		var newMinutes = getMinutes($F('sta'));
		$('end').value = padNumber(newHour) + ":" + padNumber(newMinutes);
	}
	
	$('tes').value = addTime(getHours($F('sta')), getMinutes($F('sta')), 0, -30);
	ee_updateDuration();	
}

function ee_endTimeChanged() {
	if(!verifyTimeFormat($('end'))) {
		ee_alertError("INVALID TIME FORMAT");
		$('end').value = '';
		return;
	}
	
	forceTimeFormat($('end'));
	ee_updateDuration();	
}

function ee_durationChanged() {	
	var durSplit = $F('dur').split(" ");
	var dur = durSplit[0];	
	if(!isNaN(dur))	{
		if($F('sta') != '') {
			if(dur > 1440) {
				dur = 1440;
			}
			$('end').value = addTime(getHours($F('sta')), getMinutes($F('sta')), 0, dur);		
		}			
		$('dur').value = dur + " minutes";
	}	else {
		ee_alertError("INVALID ENTRY");
		$('dur').value = '';
		ee_updateDuration();
	}	
}

function ee_alertError(message) {
	alert(message);
}

function ee_testTimeChanged() {
	
	
}

// calculates and displays the duration of an event based on the values
// in the start-time and end-time fields
function ee_updateDuration() {
	if($F('sta') != '' && $F('end') != '') {
		var diff = timeDiff($F('sta'), $F('end'));
		if(diff >= 0)	{
			$('dur').value = diff + " minutes";
		}	else {
			$('dur').value = '';			
		}
	} else {
		$('dur').value = '';
	}
}

function ee_extraFieldCheck(from, checkbox) {
	from.value = trim(from.value);	
	if(from.value != "") {
		$(checkbox).checked = true;
	}	else {
		$(checkbox).checked = false;
	}
}

// find out how many minutes there are between two times
function timeDiff(time1, time2) {
	var hourDiff = getHours(time2) - getHours(time1);
	var minutesDiff = getMinutes(time2) - getMinutes(time1);	
	while(minutesDiff < 0) {
		minutesDiff += 60;
		hourDiff--;
	}	
	var total = (hourDiff * 60) + minutesDiff;	
	return total;
}

// takes a time in hours and minutes and adds hours and minutes to it
// returns hh:ss time string
function addTime(hours, minutes, addHours, addMin) {
	var m = new Number(minutes);
	var h = new Number(hours);	
	var ma = new Number(addMin);
	var ha = new Number(addHours);	
	m += ma;
	h += ha;		
	while(m >= 60) {
		m -= 60;
		h++;
	}	
	while(m < 0) {
		m += 60;
		h--;
	}	
	while(h < 0) {
		h += 24;
	}	
	while(h > 24) {
		h -= 24;
	}	
	var returnTime = padNumber(h) + ":" + padNumber(m);
	return (returnTime);	
}

// looks at user input and determines if it can be deciphered as a hh:mm time
function verifyTimeFormat(targetObject) {
	if(targetObject.value != '') 	{
		var timeSplit = targetObject.value.split(":");	
		if(timeSplit.length == 1 && between(timeSplit[0], 0, 23))	{		
			targetObject.value = targetObject.value + ":00";
			return true; 
		}	else if(timeSplit.length == 2 && !isNaN(timeSplit[0]) && !isNaN(timeSplit[1])) {		
			if(between(timeSplit[0], 0, 23) && between(timeSplit[1], 0, 60)) {			
				targetObject.value = timeSplit[0] + ":" + timeSplit[1];			
				return true;		
			}	else {			
				return false;
			}
		}	else {		
			return false;
		}
	} else {
		return true;
	}
}

// takes user input for a time and pads zeroes resulting in fixed length hh:mm string
function forceTimeFormat(targetObject) {
	if(targetObject.value != '') {
		var minutes = getMinutes(targetObject.value);
		var hours = getHours(targetObject.value);		
		if(hours < 10) {
			targetObject.value = "0" + hours;
		} else {
			targetObject.value = hours;
		}
		
		if(minutes < 10) {
			targetObject.value += ":0" + minutes;
		}	else {
			targetObject.value += ":" + minutes;
		}
	}
}

// is a value between a min and max value (inclusive)
function between(value, minVal, maxVal) {	
	return (value >= minVal) && (value <= maxVal);
}

// extract the minutes value from a propertly formatted (hh:mm) time string
function getMinutes(time) {
	var timeSplit = time.split(":");	
	if(timeSplit.length != 2)
	  return null;	
	var val = new Number(timeSplit[1]);	
	return val;
}

// extract the hour value from a propertly formatted (hh:mm) time string
function getHours(time) {		
	var timeSplit = time.split(":");		
	if(timeSplit.length != 2)
	  return null;
	var val = new Number(timeSplit[0]);	
	return val;
}

// get the key code value from an event object
function ee_getKeycode(e) {
    if(document.layers)
        return e.which;
    else if(document.all)
        return event.keyCode;
    else if(document.getElementById)
        return e.keyCode;
    return 0;
}

// called when keyup event is fired on the client search field
function ee_keyupSugClient(e) {	
	ee_suggest('sugClient', e);
}

// called when keyup event is fired on the contact search field
function ee_keyupSugContact(e) {	
	ee_suggest('sugContact', e);
}

// when the user leaves a suggest search field, you want to start a timer
// to hide suggestions after 500ms
function ee_suggestBlur(fieldName) {
	$(fieldName + "Search").value = '';
	ee_startHideTimer(fieldName);
}

// if suggest search field is focused -- clear any existing timers that might exist
// to prevent suggestions from suddenly disappearing
function ee_suggestFocus(fieldName) {
	clearInterval(gIntervals[fieldName]);
}

// stores interval id and starts 500ms timer
function ee_startHideTimer(fieldName) {
	gIntervals[fieldName] = setInterval('ee_hideSuggestNow(\"' + fieldName + '\")', 500);
}

// called when timer has expired, and hides suggestions
function ee_hideSuggestNow(fieldName) {
	$(fieldName).style.display = 'none';
	clearInterval(gIntervals[fieldName]);
}

// general function to handle looking for contact suggestions for various
// fields that use suggestions (client, contact, speaker)
function ee_suggest(field, e) {	
	var key = ee_getKeycode(e)	
	
	switch (key) {
		case 27: // escape					
			$(field + "Search").value = ''; 
			break;
		case 38: // up arrow
			ee_handleUp(field);
			return;
			break;
		case 40: // down arrow
			ee_handleDown(field);
			return;
			break;			
	}
	
	var value = $F(field + "Search");
	
	if(value == '') { 
		$(field).style.display = 'none'; 
		return; 
	}	
	
	$(field).style.display = '';
	var url = '../ajax/fetchpeople.cfm?f=' + field + '&s=' + value;
	gAjaxContactList = new Ajax.Updater(field, url, {asynchronous:true, onComplete:ee_receivedSuggestList, field:field});
}

function ee_receivedSuggestList(originalRequest) {
	//ee_suggestMouseOver($(originalRequest.field).childNodes[gSuggestSelected[field]]);
}

// handle when down arrow is pressed in a suggest field
function ee_handleDown(field) {
	
	if(gSuggestSelected[field] == null) {
		gSuggestSelected[field] = 0;		
	} else {
		gSuggestSelected[field]++;
	}
	
	var suggestContainer = $(field);
	var maxRowsAvailable = suggestContainer.childNodes.length;	

	if(gSuggestSelected[field] > maxRowsAvailable) {
		gSuggestSelected[field] = maxRowsAvailable;
	}

	for(var i = 0; i < maxRowsAvailable; i++) {
		ee_suggestMouseOut(suggestContainer.childNodes[i]);
	}
	
	ee_suggestMouseOver(suggestContainer.childNodes[gSuggestSelected[field]]);	
}

// general function for suggestion rows to generate rollover effect
function ee_suggestMouseOver(target) {
	target.style.backgroundColor = '#251e93';
	target.style.color = '#fff';
}

// general function for suggestion rows to handle rollOut
function ee_suggestMouseOut(target) {
	target.style.backgroundColor = '';
	target.style.color = '';	
}

function ee_suggestAdd(field, id) {
	if(id == 0) { return; }
	
	$(field).style.display = 'none';
	$(field + 'Search').value = '';

	var updateField = $(field.toLowerCase().substring(3, field.length) + 's');

	var newList = ee_addValueToList(updateField.value, id);
	if(newList != false) {
		updateField.value = newList;
	} else {
		alert(field.substring(3, field.length) + " was already added.");
		return;
	}

	var url = '../ajax/contactdetails.cfm?f=' + field + '&id=' + id;
	var ajaxContactDetails = new Ajax.Updater(field + 'List', url, {insertion:Insertion.Bottom});
}

function ee_suggestReplace(field, id) {
	var url = '../ajax/contactdetails.cfm?div=no&f=' + field + '&id=' + id;
	var ajaxContactReplace = new Ajax.Updater(field + '_e' + id, url);
}

function ee_editContact(id, field) {
	var replaceElement = field + '_e' + id;
	var url = '../ajax/editcontact.cfm?f=' + field + '&id=' + id;
	var ajaxContactEdit = new Ajax.Updater(replaceElement, url);
}

function ee_addNewContact(field) {
	if($(field + '_e0') == null) {
		var url = '../ajax/editcontact.cfm?f=' + field + '&id=new';
		var ajaxContactEdit = new Ajax.Updater(field + "List", url, {insertion:Insertion.Top});
	}
}

function ee_cancelNewContact(field) {
	var node = $(field + '_e0');
	node.parentNode.removeChild(node);
}

function ee_removeName(field, id) {
	var updateField = $(field.toLowerCase().substring(3, field.length) + 's');
	updateField.value = ee_removeValueFromList(updateField.value, id);
	new Effect.Fade($(field + '_e' + id), {duration:0.5, afterFinish:function() { $(field + '_e' + id).parentNode.removeChild(field + '_e' + id); }}); 
}

function ee_saveContact(id, field) {
	var params = '?id=' + id 
	params += '&f=' + field;
	params += '&lastname=' + $(field + '_lastname_' + id).value;
	params += '&firstname=' + $(field + '_firstname_' + id).value;
	params += '&email=' + $(field + '_email_' + id).value;
	params += '&phone=' + $(field + '_phone_' + id).value;
	params += '&title=' + $(field + '_title_' + id).value;
	params += '&credentials=' + $(field + '_credentials_' + id).value;
	params += '&positions=' + $(field + '_positions_' + id).value;
	params += '&middlename=' + $(field + '_middlename_' + id).value;
	var ajaxContactSave = new Ajax.Request('../ajax/savecontact.cfm' + params, {onSuccess:ee_saveContactSuccess, onFailure:ee_saveContactFailed});
}

function ee_saveContactSuccess(originalRequest) {
	var keyPairs = trim(originalRequest.responseText).split('&');
	var response = new Array();	

	for(var i = 0; i < keyPairs.length; i++) {
		keyPairs[i] = keyPairs[i].split('=');
		response[keyPairs[i][0]] = keyPairs[i][1];
	}	

	if(response["success"] == "true") {
		ee_removeName(response["f"], response["id"]);
		ee_suggestAdd(response["f"], response["id"]);	
	} else {
		alert("There was a problem saving the contact information:\n" + response["error"]);
	}
}

function ee_cancelSaveContact(id, field) {
	ee_suggestReplace(field, id);
}


function ee_saveContactFailed(originalRequest) {
	
}

function ee_addValueToList(list, value, shouldSort) {
	var currentEntries = list.split(",");
	
	for(var i = 0; i < currentEntries.length; i++) {
		if(value == trim(currentEntries[i])) {
			return false;
		}		
	}
	
	if(list.length != 0) { list += ","; }
	list += value + ',';
	
	if(shouldSort) {		
		var sort_array = list.split(",");
		sort_array.sort();
		list = "";
		for(var i = 0; i < sort_array.length; i++) {
			if(sort_array[i] != '') {
				list += sort_array[i] + ',';
			}
		}
	}

	return list.substring(0, list.length - 1);
}

function ee_removeValueFromList(list, value) {
	var currentEntries = list.split(",");

	var newList = "";

	for(var i = 0; i < currentEntries.length; i++) {
		if(value != currentEntries[i]) {
			newList += currentEntries[i] + ","			
		}
	}
	
	return newList.substring(0, newList.length - 1);
}

function ee_addCredential(target, value) {	
	var newValue = ee_addValueToList($F(target), value);
	if(newValue != false) {
		$(target).value = newValue;
	}
	return false;
}

function ee_refillDateList() {
	var date_list = $('datelist');
	
	while(date_list.length != 0) {
			date_list.options[0] = null;
	}
	
	var dates_array = $F('dates').split(',');
	for(var i = 0; i < dates_array.length; i++) {
		if(dates_array[i] != "") {
			var date_obj = new Date(dates_array[i]);
			var day = getDayAsString(date_obj) + " ";
			date_list.options[date_list.options.length] = new Option(day + getInputFormatDate(date_obj), dates_array[i]);
		}
	}	
}

function ee_fastInsertDate(incoming_date) {	
	$('dates').value = ee_addValueToList($F('dates'), incoming_date, true);	
	ee_refillDateList();
	var date_list = $('datelist');
	
	for(var i = 0; i < date_list.length; i++) {
		if(incoming_date == date_list.options[i].value) {
			date_list.selectedIndex = i;
			return;
		}
	}
}

function ee_fastRemoveDate(incoming_date) {
	$('dates').value = ee_removeValueFromList($F('dates'), incoming_date);
	ee_refillDateList();	
}

function ee_userChangedPhone(field) {	
	field.value = trim(field.value);
	
	while(field.value.match(/[^\d]+/) != null) {
		field.value = field.value.replace(/[^\d]+/, "");	
	}
	
	if(field.value.length == 7)	{
		field.value = "520-" + field.value.substring(0, 3) + "-" + field.value.substring(3, 7);
	}
	else if(field.value.length == 10)	{
		field.value = field.value.substring(0, 3) + "-" + field.value.substring(3, 6) + "-" + field.value.substring(6, 10);
	}
	else if(field.value.length == 4) {
		field.value = "520-626-" + field.value.substring(0, 4);
	}
	else if(field.value.length == 5 && field.value.substring(0, 1) == "1") {
		field.value = "520-621-" + field.value.substring(1, 5);
	}
	else if(field.value.length == 5 && field.value.substring(0, 1) == "6") {
		field.value = "520-626-" + field.value.substring(1, 5);
	}
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " " || ch == "\n" || ch == "\r") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " " || ch == "\n" || ch == "\r") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   /*
   while (retValue.indexOf("  ") != -1) 
   { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   */
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

function getDayAsString(date) {
	return gDAY_LIST[date.getDay()];
}

function getInputFormatDate(dateObject) {
	return padNumber(dateObject.getMonth() + 1) + "/" + padNumber(dateObject.getDate()) + "/" + dateObject.getFullYear();
}

function padNumber(value) {
	if(value < 10) {
	  	return "0" + value;
	}	else {
		return value;
	}	
}

function demoronize(badString)
{	
	// CharCodes of strings to replace	
	badCharCodes = new Array(8220, 8221, 8212, 8217, 8211);
	// Replacement characters
	replacementChars = new Array("\"", "\"", "--", "'", "-");
	
	var goodString = "";
	
	for(var i = 0; i < badString.length; i++)
	{
		var badCharFound = -1;
		for(var j = 0; j < badCharCodes.length; j++)
		{	
			if(badString.charCodeAt(i) == badCharCodes[j])
			{
				badCharFound = j;
				break;
			}
		}
		if(badCharFound == -1)
		{
			goodString += badString.charAt(i);		
		}
		else
		{
			goodString += replacementChars[badCharFound];
		}
	}
	return goodString;
}