var tmpUserDate; // Stores date user selected and needs to be global

var DIC = {

	defaultEvent : "click",
	prefix : "dic", 				// Element ID's that want to be used in this need to be prefixed with dic
	arrivalFldID : "dic-arrival",	// ID of arrival input fld
	departFldID : "dic-depart",		// ID of departure input fld
	highlightA : "dic-highlightA", 	// ID For highlight span around arrival input fld
	highlightD : "dic-highlightD", 	// ID For highlight span around depart input fld
	currHighlight : "arrival",		// Default highlight should be arrival date fld
	arrivalDate: '',
	departDate : '',
	unitID : null,					// Unit ID for current calendar
	checkin : null,					// units checkin day
	dataSource : null,				// Used for rate feature. Source we get data from (Escapia, ISI, etc)
 
	init : function (){
		if(document.getElementById){
			this.focusElements = getElementsByIDName(document, "*", "dic");
			//this.applyEvents();
			//this.useMSFilter = typeof this.overlay.style.filter != "undefined";
			this.unitID = document.getElementById('UID').value;
			this.checkin = document.getElementById('DOW').value;
			if(document.getElementById('dataSource')){
				this.dataSource = document.getElementById('dataSource').value;
			}

			// This section added to prefill arrival and departure if avail search done on initial query.html search

			if(document.getElementById('initArrival')){
				if(document.getElementById('initArrival').value != ''){
					this.fillInputFld(document.getElementById('initArrival').value);
				}
				if(document.getElementById('initDepart').value != ''){
					this.fillInputFld(document.getElementById('initDepart').value);
				}
			}
		}




	},



	addEvent : function (oObject, strEvent, oFunction, bCapture){
		if(oObject){
			if(oObject.addEventListener){ // Firefox and standard browsers
				oObject.addEventListener(strEvent, oFunction, bCapture);
			}
			else if(window.attachEvent){ // IE
				oObject.attachEvent(("on" + strEvent), oFunction)
			}
		}
	},

	/* NOT USED CURRENTLY
	applyEvents : function (){
		var oElm;
		switch(this.defaultEvent){
			case "click":
				for(var i=0; i<this.focusElements.length; i++){
					oElm = this.focusElements[i];
					//oElm.onclick = alert("clicked:"+this.focusElements[i].id);
				}
			break;
			case "mouseover":
				for(var i=0; i<this.focusElements.length; i++){
					oElm = this.focusElements[i];
					oElm.onmouseover = DIC.mouseOverElm;
					oElm.onmouseout = DIC.mouseOutElm;
				}
			break;
		}

	},

	getEventTarget : function(e){
		var e = e || window.event; 
		var targ = e.target || e.srcElement;
		if (targ.nodeType == 3) { // defeat Safari bug 
			targ = targ.parentNode; 
		} 
		return targ; 
	},

	*/

	processEventClick : function(oEvent){

		//alert("Clicked Something");

		var oEvent = (typeof oEvent != "undefined")? oEvent : event;
		if(oEvent.target){
			var theTarget = oEvent.target.id;
		}else if (oEvent.srcElement){
			var theTarget = oEvent.srcElement.id;
		}

		//alert(theTarget);

		var oRegExp = new RegExp("(^)" + DIC.prefix + "(-|$)");
		if(oRegExp.test(theTarget)){
			//alert("addEvent:"+oEvent);
			var selectedDate = theTarget.replace(/dic\-/g, "");
			//alert("Target:"+selectedDate);

			// If user simply clicked on input fld highlight what they clicked on and do nothing else for now
			if(selectedDate == 'arrival' || selectedDate == 'depart'){
				this.selectInputFld(selectedDate);
			}else{
				this.fillInputFld(selectedDate);
			}
			

			if(oEvent.preventDefault) {
				oEvent.preventDefault();
			} else {
				oEvent.returnValue = false; // IE branch
			}
			
		}else if(theTarget == 'rateSubmitButton'){
			//alert(theTarget);
			this.getRates();			

		}else if(theTarget == 'resetdates'){

			this.resetDates();

			if(oEvent.preventDefault) {
				oEvent.preventDefault();
			} else {
				oEvent.returnValue = false; // IE branch
			}
		}else if(theTarget == 'calSubmitButton'){
			if(document.getElementById('calSubmitButton').disabled == false){
				this.enableFormValues();
			}
		
		}
	},

	processEventKey : function(oEvent){
		var oEvent = (typeof oEvent != "undefined")? oEvent : event;
		//alert(oEvent.keyCode);	
		if(oEvent.keyCode == 9){
			if(oEvent.target){
				var theTarget = oEvent.target.id;
			}else if (oEvent.srcElement){
				var theTarget = oEvent.srcElement.id;
			}

			var oRegExp = new RegExp("(^)" + DIC.prefix + "(-|$)");
			if(oRegExp.test(theTarget)){
				//alert("addEvent:"+oEvent);
				var selectedDate = theTarget.replace(/dic\-/g, "");
				//alert("Target:"+selectedDate);

				// If user used tab key to move we need to track that as well
				if(selectedDate == 'arrival' || selectedDate == 'depart'){ // keycode of 9 = tab
					//switch(selectedDate){ // Reverse the logic here so logic in selectInputFld function stays the same.
					//	case "arrival":
					//		outSelectedDate = 'depart';
					//	break;
					//	case "depart":
					//		outSelectedDate = 'arrival';
					//	break;
					//}
					if(this.selectInputFld(selectedDate) == 1){
						if(oEvent.preventDefault) {
							oEvent.preventDefault();
						} else {
							oEvent.returnValue = false; // IE branch
						}
					}
				}
			}
		}
	},

	resetDates : function(){

		this.arrivalDate = '';
		this.departDate = '';

		//alert(this.focusElements[this.arrivalFldID].value);
		this.focusElements[this.arrivalFldID].value = '';
		this.focusElements[this.departFldID].value = '';
		this.focusElements[this.highlightD].className = 'highlight disabled';
		this.focusElements[this.highlightA].className = 'highlight enabled';
		this.currHighlight = 'arrival';	

		document.getElementById('calSubmitButton').disabled=true;

		var currCalMonth = this.getStartCalMonth();
		displayCalendar(currCalMonth[0],currCalMonth[1],this.unitID,this.checkin,this.arrivalDate,this.departDate);
		//document.getElementById('calSubmitButton').value="Select Arrival";



	},

	enableFormValues : function(){

		document.getElementById('dic-arrival').disabled=false;
		document.getElementById('dic-depart').disabled=false;


	},

	selectInputFld : function(selectedFld){
		switch(selectedFld){
			case "arrival":
				this.focusElements[this.highlightD].className = 'highlight disabled';
				this.focusElements[this.highlightA].className = 'highlight enabled';
				this.currHighlight = 'arrival';
			break;
			case "depart":
				this.focusElements[this.highlightA].className = 'highlight disabled';
				this.focusElements[this.highlightD].className = 'highlight enabled';
				if(this.focusElements[this.arrivalFldID].value == ''){
					this.focusElements[this.arrivalFldID].focus();
					tmpErrMessage = "The arrival date selected is invalid.";
					initMessage(tmpErrMessage,'BA');

					return 1;

				}else{
					this.currHighlight = 'depart';
				}
			break;
		}

	},

	fillInputFld : function(selectedDate){

		this.unitID = document.getElementById('UID').value;
		this.checkin = document.getElementById('DOW').value;

		switch(this.currHighlight){
			case "arrival":
				this.arrivalDate = selectedDate;
				this.departDate = '';
				this.focusElements[this.arrivalFldID].value = selectedDate;
				this.focusElements[this.departFldID].value = '';
				this.focusElements[this.highlightA].className = 'highlight disabled';
				this.focusElements[this.highlightD].className = 'highlight enabled';
				//this.focusElements["calrates"].innerHTML = '&nbsp;';
				//alert("Insert into Arrival");
				this.currHighlight = 'depart';
				var currCalMonth = this.getStartCalMonth();
				
				displayCalendar(currCalMonth[0],currCalMonth[1],this.unitID,this.checkin,this.arrivalDate,this.departDate);
				
				//alert("month: "+currCalMonth[0]+ " Year: "+currCalMonth[1]);
					
			break;
			case "depart":
				this.departDate = selectedDate;
				this.focusElements[this.departFldID].value = selectedDate;
				this.focusElements[this.highlightD].className = 'highlight disabled';
				this.focusElements[this.highlightA].className = 'highlight enabled';
				this.currHighlight = 'arrival';
				var currCalMonth = this.getStartCalMonth();
					
				displayCalendar(currCalMonth[0],currCalMonth[1],this.unitID,this.checkin,this.arrivalDate,this.departDate);
				//alert("Insert into Depart");
					
			break;
		}
	},

	// Determine the starting calendar month to show after selecting an arrival/depart date
	getStartCalMonth : function() {
		// recalibrate focusElements since user may have change months showing
		this.focusElements = getElementsByIDName(document, "*", "dic");
		var checkRegExp = new RegExp("^("+DIC.prefix+"-)\\d{1,2}/\\d{4}");
		for(keyTest in this.focusElements){

			if(checkRegExp.test(keyTest)){
				var monthYr = keyTest.replace(DIC.prefix+"-",'');
				var startCalMonth = monthYr.split('/');
				//alert("StartMonth: "+monthYr);
				return startCalMonth;
				break;
			}
	
		}

	},

	// Send the AJAX request for Rates for the arrival and departure date user entered
	getRates : function(){
		// Check that we have an arrival and depart date
		if(this.arrivalDate == ''){
			document.getElementById("calrates").innerHTML = "Please enter a valid arrival date.";
		}else if(this.departDate == ''){
			document.getElementById("calrates").innerHTML = "Please enter a valid departure date.";
		}else{
			// dates are there but may be invalid. Might need to address this at some point
			displayRates(this.arrivalDate, this.departDate, this.unitID, this.dataSource);
		}


	},


	closeSession : function (oEvent){
		this.removeEvent(window, "load", function(){DIC.init();}, false);
		//this.removeEvent(window, "scroll", function(){FaT.setOverlaySize();}, false);
		//this.removeEvent(window, "resize", function(){FaT.setOverlaySize();}, false);

		DIC = null;
		delete DIC;
	},

	removeEvent : function (oObject, strEvent, oFunction, bCapture){
		if(oObject){
			if(oObject.removeEventListener){
				oObject.removeEventListener(strEvent, oFunction, false);
			} else if(window.detachEvent){
				oObject.detachEvent(("on" + strEvent), oFunction)
			}
		}
	}

}

DIC.addEvent(window, "load", function(){DIC.init();}, false);
DIC.addEvent(document, "click", function(oEvent){DIC.processEventClick(oEvent);}, false);
DIC.addEvent(document, "keyup", function(oEvent){DIC.processEventKey(oEvent);}, false);

DIC.addEvent(window, "unload", function(){DIC.closeSession();}, false);


// For showing message returned from Ajax calls after user select a date on calendar
function initMessage(messageTxt,errType){
	//alert(messageTxt+" Error Type: "+errType);
	if(messageTxt != '' && errType != ''){
		
		if(errType == 'MESS'){ // not an error so show non red text
			document.getElementById('errMessageBox').className = 'nonErrMessageBox enabled2';
			document.getElementById('errMessageTxt').className = 'nonErrMessageTxt';
		}else{
			document.getElementById('errMessageBox').className = 'errMessageBox enabled2';
			document.getElementById('errMessageTxt').className = 'errMessageTxt';
		}
			
		document.getElementById('errMessageTxt').innerHTML = messageTxt;
	}

	switch(errType){ // Bad arrival date selected
		case "BA":
			DIC.currHighlight = 'arrival';
			DIC.focusElements[DIC.highlightD].className = 'highlight disabled';
			DIC.focusElements[DIC.highlightA].className = 'highlight enabled';
			DIC.arrivalDate = '';
		break;
		case "BABD":
			DIC.currHighlight = 'arrival';
			DIC.focusElements[DIC.highlightD].className = 'highlight disabled';
			DIC.focusElements[DIC.highlightA].className = 'highlight enabled';
			DIC.arrivalDate = '';
			DIC.departDate = '';
		break;
		case "BD":
			DIC.currHighlight = 'depart';
			DIC.focusElements[DIC.highlightD].className = 'highlight enabled';
			DIC.focusElements[DIC.highlightA].className = 'highlight disabled';
			DIC.departDate = '';
		break;

		default:
			if(DIC.arrivalDate != '' && DIC.departDate != ''){
				document.getElementById('calSubmitButton').disabled=false;
				//document.getElementById('calSubmitButton').value="Book It";
			}else{
				document.getElementById('calSubmitButton').disabled=true;
			}
	}	
}

function initButtonMessage(bMessage){
	document.getElementById('calSubmitButton').value=bMessage;
}


function getElementsByIDName(oElm, strTagName, strIDName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);

	var arrReturnElements = new Array();
	strIDName = strIDName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^)" + strIDName + "(-|$)");

	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];

		if(oRegExp.test(oElement.id)){
			//alert(oElement.id);	
			//arrReturnElements.push(oElement);
			arrReturnElements[oElement.id] = oElement;
		}	
	}
	return (arrReturnElements)
}

// AJAX FUNCTIONS
function createCalObject_OLD() { 
   var req; 
   if(window.XMLHttpRequest){ 
      // Firefox, Safari, Opera... 
      req = new XMLHttpRequest(); 
   } else if(window.ActiveXObject) { 
      // Internet Explorer 5+ 
      req = new ActiveXObject("Microsoft.XMLHTTP"); 
   } else { 
      alert('Problem creating the XMLHttpRequest object'); 
   } 
   return req; 
} 

function createCalObject()
{
	var xmlHttp;
	try{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e){
		// Internet Explorer
	  	try{
	    	xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	    }
		catch (e){
	   		try{
	  			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		   	}
			catch (e){
			    alert("Your browser does not support AJAX!");
			    return false;
			}
	    }
	}
	return xmlHttp;
}

// Make the XMLHttpRequest object 
var http = createCalObject(); 

function displayCalendar(m,y,u,c,a,d) {
	//alert("month: "+m+" year: "+y+"UID: "+u);
	//var ran_no=(Math.round((Math.random()*9999))); 
	http.open('get', '/vdsCal/getCal.html?m='+m+'&y='+y+'&ID='+u+'&checkin='+c+'&arrival='+a+'&depart='+d);
   	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) { 
      		var response = http.responseText;

      		if(response) { 
				document.getElementById("calrates").innerHTML = '&nbsp;';
				document.getElementById('errMessageBox').className = 'errMessageBox disabled2';
				document.getElementById("vdsCal").innerHTML = http.responseText; 
				eval(document.getElementById('javascript').innerHTML);
      		} 
   		} 
	} 
   	http.send(null); 
}

function displayRates(rArrival, rDepart, unitID, dataSource){

	//alert('/vdsCal/genRates.class.php?arrival='+rArrival+'&depart='+rDepart+'&PID='+unitID+'&DS='+dataSource);
	http.open('get', '/vdsCal/genRates.class.php?arrival='+rArrival+'&depart='+rDepart+'&PID='+unitID+'&DS='+dataSource);
	document.getElementById("calrates").innerHTML = '<br />Calculating <img src="/vdsCal/loading.gif" border="0">';
   	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) { 
      		var response = http.responseText;

      		if(response) { 
				//document.getElementById('errMessageBox').className = 'errMessageBox disabled2';
				document.getElementById("calrates").innerHTML = http.responseText; 
				//initMessage('* Optional fees are included in this rate which can be changed at final contract.','MESS');
				initMessage('* Optional fees included in this rate can be changed at final contract. Balance due will be adjusted on your confirmation/final billing.','MESS');
				//eval(document.getElementById('javascript').innerHTML);
      		} 
   		} 
	} 
   	http.send(null); 


}

// END AJAX SECTION

// Following used for changing month shown via dropdowns
function chgCurrentCal() {
	var month = document.getElementById('month').value;
	var year = document.getElementById('year').value;
	var UID = document.getElementById('UID').value;
	var DOW = document.getElementById('DOW').value;
	var ARRIVAL = document.getElementById('ARRIVAL').value;
	var DEPART = document.getElementById('DEPART').value;

	//alert(month+','+year+','+UID+','+DOW);

	displayCalendar(month,year,UID,DOW,ARRIVAL,DEPART);

	return false;
}


