// GLOBAL PAGE VARIABLES ------------------------------------------------------
var monthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var statusNames = ["Quotation","Waitlisted","Provisional","Confirmed","Cancelled"];
var monthvals = [];
var calendar_window = "";
var cellValueClicked_flag = false;
var mouseDown_flag = false;
var rooms = 0;
var startCell = [];
var endCell = [];
var start_date = "";
var end_date = "";
var firstWizardCall = true;
var screenWidth		= screen.availWidth;
var screenHeight	= screen.availHeight;
var changedFilter	= false;			// Flag to indicate filter criteria changed
var lowest_selection = 999;
var response = 0;								// User response (Y/N) to overbooking continue (continue_yn.htm)
var selectedString;
var first_page_load = true;
var changed_date = "";
var selected_cells_array = [];	// Calendar array to hold array of cells selected
var selected_cells_ids = [];		// Calendar array to hold array of cells selected
var selected_cells_string = "";
var selected_data = "";					// Holds selected data from occupancy calendar
var display_data = "";					// Holds a version of selected calendar cells that is human readable
var email_data = [];						// Holds array containing itinerary for email form
var enabledFunctions = ["Back","Forward","Refresh","Print","Calendar","Internet","Home","Help"];
var enabledButtons = ["Back","Forward","Refresh","Print","Calendar","Internet","Home","Help","NewWindow"];
var haveItinerary = false;
var propNo = -1;
var showOccupancyCalendar = false;
var showEmailWizard = false;
var showPrincipalWizard = false;
var showProvisionals = false;
var calendarAgentPop = true;
var filterOccCalByAgent = false;
var agentFilterName = "All Agents";

// Calendar Styles ------------------------------------------------------------
var calSelected				= "g1Cg";
var calSelectedEmpty	= "g1Cg";
var calAvailable			= "g1C";
var calFull						= "g1Cb";
var calOverbooked			= "overbooking";
var calWeekend				= "wk";
var calWeekendEmpty		= "wkEndNoBorder";
var calClick					= "g1Cg";
var calClickOver			= "g1Cgd";
var calEmpty					= "g1C";
var calBlocked				= "blockNoBorder";
var canSeePastDates		= false;

function newInit() {
	initTop();

	if ( mainWindowPage != "quick_search" ) {
		id("year").focus();
	}

	if ( !publicPage ) {
		enableButtons(enabledButtons);
	}

	// Initialise the wizard itinerary on the availability calendar and alert the 
	// user if session expired
	if ( mainWindowPage == "availability_calendar" || publicPage ) {
		if ( rv_split_items != "" ) {
			openPopup("reservation.php?684+" + rv_split_items,350,470);
		}
		
		frameLoad();
		
		if ( alertUserVal == "1" ) {
			alertUser();
		}
		
		var agent_name 	= id("agent_name");
		var agentPop 		= id("agentPop");
		
		if ( agent_name.value == "Direct" ) {
			agentPop.style.display = "none";
		}
	}
	
	//Reset variables
	selectedPropertyNames = "";

	// Generate the calendar
	initCalendar();
	
	// Get info for print_header
	var loggedUser	= id("user");
	var server 			= id("server");
	var genDate 		= id("genDate");	
	var the_date 		= new Date();
	var the_day 		= the_date.getDate();
	var the_month 	= the_date.getMonth();
	var the_year 		= the_date.getFullYear();

	loggedUser.innerHTML 	= FirstName + " " + LastName;
	server.innerHTML 			= Domain;
	genDate.innerHTML 		= genDateVal;

	/* ----------- COMMENTED FOR SOME REASON ------------------------------------
	if ( publicPage == true ) {
		
		// Set location drop down
		var serverSelect 		= id("serverSelect");
		var flag 						= id("flag");
		var hostName 				= parent.location.hostname;
		var hostNameArray 	= hostName.split(".");
		var serverLocation	= hostNameArray[1];

		// Setup the URL links in the country drop-downs to take the user to the 
		// correct client on the web
		if ( hostNameArray.length > 2 ) {
			// init top has already removed 2...
			serverSelect[0].value = SAServer;
			serverSelect[1].value = USServer;
		} else {
			serverSelect[0].value = "";
			serverSelect[1].value = SAServer;
			serverSelect[2].value = USServer;
		}

		// If we are !localhost then remove "local" option else set local option 
		// and flag
		if ( hostNameArray.length > 2 ) {
			switch ( serverLocation ) {
				case "us":
					serverSelect.selectedIndex = 1;
					flagSrc = "images/top_usaflag.gif";
					flagwidth = "16";
					flagheight = "12";
				break;
				
				case "eu":
					serverSelect.selectedIndex = 2;
					flagSrc = "images/top_euflag.gif";
					flagwidth = "16";
					flagheight = "12";
				break;

				case "za":
					serverSelect.selectedIndex = 0;
					flagSrc = "images/top_saflag.gif";
					flagwidth = "16";
					flagheight = "12";
				break;
				
				default:
					serverSelect.selectedIndex = 0;
					flagSrc = "images/top_saflag.gif";
					flagwidth = "16";
					flagheight = "12";
				}
			} else {
				serverSelect.selectedIndex = 0;
				flagSrc = "images/top_localflag.gif";
				flagwidth = "16";
				flagheight = "14";
			}
	
		flag.src = flagSrc;
		flag.width = flagwidth;
		flag.height = flagheight;
	}
	-------------------------------------------------------------------------- */
}

function initCalendar() {
	// Set monthvals array to array of months to correspond to array of days
	monthvals[0] = months[0];
	monthindex = 0;
	for ( i = 1; i <= 19; i++ ) {
		if ( days[i] < days[i-1] ) {
			monthindex = 1;
		}
		monthvals[i] = months[monthindex];
	}
	monthvals[20] = months[monthindex];
	
	// Set the date drop down
	if ( months[0] < 1 ) {
		months[0] = 1;
	}

	if ( days[0] < 1 ) {
		days[0] = 1;
	}

	if ( years[0] < "1995" ) {
		years[0] = "1995";
	}

	var currentMonth 	= months[0];
	var currentYear 	= years[0];
	var currentDay 		= days[0];

	id("select_day").selectedIndex = currentDay;
	id("select_month").selectedIndex = currentMonth;
	id("year").value = currentYear;

	// Do this in PHP with Sessions
	Set_Cookie("mainWindowPage",mainWindowPage);
}

function showHideBrowser() {
	id("getBrowser").style.display = "none";
}

function mouseOverFunction(e,event_obj) {
	var targ = getEventTarget(e);

	if ( mouseDown_flag ) {
		if ( parseInt(targ.innerHTML) == 0 && mainWindowPage == "occupancy_calendar" ) {
			var temp_var = targ.id;
			var split_temp = temp_var.split(":");
			var temp_var1 = targ.name;
			var split_temp1 = temp_var1.split(":");
			
			endCell[0] 			= split_temp1[0];	// Accomm type ID
			endCell[1] 			= split_temp[0];	// day
			endCell[2] 			= split_temp[1];	// month
			rooms 					= true;
			mouseDown_flag 	= false;
			getValues();
		}
	}

	if ( mouseDown_flag ) {
		var split_temp1 = targ.id.split(":");
		
		if ( split_temp1[0] != startCell[0] ) {
			resetSelection();
			mouseDown_flag = false;
			openMessage("Please select on only one row within the calendar cells","a");
			return 0;
		}

		var extraClass = "";
		if(targ.className.toString().match(/allocationIndicator/)) {
			extraClass = " allocationIndicator";
		}
		if ( mainWindowPage == "availability_calendar" ) {
			if ( parseInt(targ.getAttribute("darkness")) == 0 ) {
				targ.className = calClick + extraClass;
				targ.setAttribute("darkness",parseInt(targ.getAttribute("darkness")) + 1);
			} else {
				targ.className = calClickOver + extraClass;
				targ.setAttribute("darkness",parseInt(targ.getAttribute("darkness")) + 1);
			}
		} else {
			if ( targ.className != calClick ) {
				targ.className = calClick + extraClass;
			} else {
				targ.className = calClickOver + extraClass;
			}
		}
		
		selected_cells_array[selected_cells_array.length] = targ;
		selected_cells_ids[selected_cells_ids.length] 		= targ.id;

		if ( parseInt(targ.innerHTML) < lowest_selection ) {
			lowest_selection = parseInt(targ.innerHTML);
		}
	}
}

function mouseDownFunction(e,event_obj) {
	var targ = getEventTarget(e);

	if ( parseInt(targ.innerHTML,10) == 0 && mainWindowPage == "occupancy_calendar" ) {
		return 0;
	}

	if ( mainWindowPage == "availability_calendar" ) {
		if ( id("loadingRow").style.display != "none" || canUseWizard == false ) {
			return 0;
		}
	}

	selected_cells_array.length	= 0;
	selected_cells_ids.length 	= 0;
	selected_cells_array[0]			= targ;
	selected_cells_ids[0]				= targ.id;

	var temp_var 		= targ.id;
	var split_temp 	= temp_var.split(":");
	var temp_var1 	= targ.getAttribute("name");
	var split_temp1	= temp_var1.split(":");

	startCell[0] = split_temp[0];							// Accomm type ID
	startCell[1] = split_temp[2];							// day
	startCell[2] = split_temp[1];							// month
	startCell[3] = unescape(split_temp1[1]);
	startCell[4] = split_temp1[2];

	mouseDown_flag = true;

	var extraClass = "";
	if(targ.className.toString().match(/allocationIndicator/)) {
		extraClass = " allocationIndicator";
	}
	if ( mainWindowPage == "availability_calendar" ) {
		if ( parseInt(targ.getAttribute("darkness")) == 0 ) {
			targ.className = calClick + extraClass;
			targ.setAttribute("darkness",parseInt(targ.getAttribute("darkness")) + 1);
		} else {
			targ.className = calClickOver + extraClass;
			targ.setAttribute("darkness",parseInt(targ.getAttribute("darkness")) + 1);
		}
	} else {
		if ( targ.className != calClick ) {
			targ.className = calClick + extraClass;
		} else {
			targ.className = calClickOver + extraClass;
		}
	}
	lowest_selection = parseInt(targ.innerHTML);
}

function cMouseUp(e,event_obj) {
	var targ = getEventTarget(e);
  
	var temp_var		= targ.id;
	var split_temp	= temp_var.split(":");
	var temp_var1 	= targ.getAttribute("name");
	var split_temp1	= temp_var1.split(":");

	endCell[0] = split_temp[0];	// Accomm type ID
	endCell[1] = split_temp[2];	// day
	endCell[2] = split_temp[1];	// month
	
	if ( id("agentDetailsRow") ) {
		toggleStep2("hide");		
	}
	
	if ( mouseDown_flag == true ) {
		rooms 					= true;
		mouseDown_flag 	= false;
		getValues();
	}
}

/* ----------------------------------------------------------------------------
	 Called when next/previous 10 days button pressed 
---------------------------------------------------------------------------- */
function dateRangeChange(action) {

	parent.calendarToggle = false;
	
	temp_date		= get_select_date();
	begin_date	= temp_date;
	begin_date	= "";

	if ( begin_date == "" ) {
		if ( months.length == 1 ) {
			begin_date = years[0] + "-" + months[0] + "-" + days[0];
		} else {
			if ( days[4] > days[0] ) {
				begin_date = years[0] + "-" + months[0] + "-" + days[0];
			} else {
				begin_date = years[0] + "-" + months[0] + "-" + days[0];
			}
		}
	}


	var new_date = begin_date.replace(/-/gi,"/");
	begin_date = new_date;
	var new_date = new Date(begin_date);
    if (action == "next") {
		new_date = DateAdd(new_date,10,0,0);
	} else {
		new_date = DateAdd(new_date,-10,0,0);
	}
	begin_date = new_date.getFullYear() + "-" +(new_date.getMonth()+1) + "-" + new_date.getDate();

	// Check we are not going into the past
	var the_date = new Date();
	var y = the_date.getFullYear();
	var m = the_date.getMonth();
	var d = the_date.getDate();
	var ny = new_date.getFullYear();
	var nm = new_date.getMonth();
	var nd = new_date.getDate();
	if ( ( ny < y || ( nm < m && ny == y ) || ( nd < d && nm == m && ny == y ) ) && mainWindowPage == "availability_calendar" && canSeePastDates == false ) {
		openMessage("Only future dates can be illustrated on this calendar","a",127);
	} else {
		parent.calendar_begin_date = begin_date;
		var first_dash = begin_date.indexOf("-");
		var second_dash = begin_date.indexOf("-",first_dash+1);
		var year = begin_date.substr(0,first_dash);
		var month = begin_date.substring(first_dash+1,second_dash);
		var day = begin_date.substr(second_dash+1,2);
      
		id("select_day").options[day].selected = true;
		id("select_month").options[month].selected = true;
		id("year").value = year;
      
		switch ( mainWindowPage ) {
		default :
			var rateId = id("rateSelect").value;
			var agent_id = id("rv_agent_id").value;
			var contact_id = id("rv_corr_persona_id").value;

			if ( id("allocDiv").style.display == "block" ) {
				allocDropDown = id("allocOptions").options[id("allocOptions").selectedIndex].value;
			} else {
				allocDropDown = "";
			}

			provDis = id("showProvs").disabled;
			provCheck = id("showProvs").status;
				
			window.location = "reservation.php?20+" + begin_date + "+" + selectedProperties + "+" + selectedStatuses + "+" + agent_id + "+" + rateId + "+" + contact_id + "+" + id("commPerc").value + "+" + allocDropDown + "+" + provDis + "+" + provCheck + "+" + selIndex("commDeduct");

			break;

		case "occupancy_calendar":
			window.location = "reservation.php?29+" + begin_date + "+" + selectedProperties + "+" + selectedStatuses + "+++" + agent_id;
			break;
		}
	}
}

/////////////////////////////////////////////////////////////
// Generate property selection popup                       //
// selection criteria                                      //
/////////////////////////////////////////////////////////////
function calendar_propertypop() {
	openPopup('calendar_propertypop.htm',258,300);
}

/////////////////////////////////////////////////////////////
// This function toggles between the two calendars,        //
// Availability and Occupancy                              //
/////////////////////////////////////////////////////////////
function toggleCalendar(goToCalendar) {
   temp_day = id("select_day").options[id("select_day").selectedIndex].value;
   temp_month = id("select_month").options[id("select_month").selectedIndex].value;
   temp_year = id("year").value;
   new_date = temp_year + "-" + temp_month + "-" + temp_day;

   // Added to store new date in URL calendar call format
   changed_date = new_date;

   var new_date = new_date.replace(/-/gi,"/");
   var new_date = new Date(new_date);

   // Check we are not going into the past
   var the_date = new Date();
   var y = the_date.getFullYear();
   var m = the_date.getMonth();
   var d = the_date.getDate();
   var ny = new_date.getFullYear();
   var nm = new_date.getMonth();
   var nd = new_date.getDate();
   if(goToCalendar == "occupancy"){
      window.location="reservation.php?29+"+changed_date+"+"+selectedProperties;
   }else{
      if((ny<y || (nm<m && ny<=y) || (nd<d && nm==m && ny==y)) && mainWindowPage == "occupancy_calendar"){
         changed_date = y+"-"+(m+1)+"-"+d;
      }
      window.location="reservation.php?20+"+changed_date+"+"+selectedProperties;
   }
}

/////////////////////////////////////////////////////////////
// This function ensures the date drop downs can only      //
// contain valid values (i.e. Feb 30 not allowed)          //
/////////////////////////////////////////////////////////////
function select_daymonth_changed(){

   dayObject = id("select_day");
   temp_month = id("select_month").selectedIndex;
   temp_year = id("year").value;

   setDayList(dayObject,temp_month,temp_year);

}

/////////////////////////////////////////////////////////////
// Get date from select boxes on calendars                 //
//                                                         //
/////////////////////////////////////////////////////////////
function get_select_date(){
    temp_day = id("select_day").selectedIndex;
    temp_month = id("select_month").selectedIndex;
    temp_year = id("year").value;
    temp_date = temp_year + "-" + temp_month + "-" + temp_day;
    return temp_date;
}

/////////////////////////////////////////////////////////////
// Restrict calendars to years before 2030                 //
//                                                         //
/////////////////////////////////////////////////////////////
function year_changed(){
   changedFilter=true;
   if(parseInt(id("year").value,10) > 2030){
      id("year").value = 2030;
      openMessage("The calendar is restricted to the year 2030","a",120);
   }
   select_daymonth_changed();
}

/* ----------------------------------------------------------------------------
 * Toggle inclusion of provisionals on calendar            
---------------------------------------------------------------------------- */
function showProvs() {
	if ( isProv == "0" ) {
		selectedStatuses = "20:30";
	} else {
		selectedStatuses = "30";
	}
	reloadPage();
}

/////////////////////////////////////////////////////////////
// This function reloads the calendar with the new         //
// selection criteria                                      //
/////////////////////////////////////////////////////////////
function reloadPage() {
	temp_day 		= id("select_day").options[id("select_day").selectedIndex].value;
	temp_month 	= id("select_month").options[id("select_month").selectedIndex].value;
	temp_year		= id("year").value;
   
	if ( isNaN(temp_year) || temp_year.length < 4 ) {
		id("year").focus();
		openMessage("Please enter a valid year");
		return 0;
	}

	if ( temp_year > "2037" ) {
		id("year").focus();
		openMessage("Please enter a year less than 2038");
		return 0;
	}

	// Calculate the exact dates that can't be accessed
	zeroA = "";
	if ( parseInt(temp_month) < 10 ) {
		zeroA = "0";
	}

	zeroB = "";
	if ( parseInt(temp_day) < 10 ) {
		zeroB = "0";
	}

	temp_dates = calDateResLimit.split("-");
	temp_date = temp_dates[0] + temp_dates[1] + temp_dates[2];
	tempB_date = temp_year + zeroA + temp_month + zeroB + temp_day;

	if ( parseInt(tempB_date) > parseInt(temp_date) ) {
		maxCalPopup = "1";
	} else {
		maxCalPopup = "0";
	}

	new_date = temp_year + "-" + zeroA + temp_month + "-" + zeroB + temp_day;

	// Added to store new date in URL calendar call format
	changed_date = new_date;

	var new_date = new_date.replace(/-/gi,"/");
	var new_date = new Date(new_date);

	var the_date 	= new Date();
	var the_day 	= the_date.getDate();
	var the_month = the_date.getMonth()+1;
	var the_year 	= the_date.getFullYear();

	var valid_date = true;

	if ( temp_year < the_year ) {
		valid_date = false;
	}

	if ( (temp_year == the_year) && temp_month < the_month ) {
		valid_date = false;
	}
	
	if ( (temp_year == the_year) && (temp_month == the_month) && (temp_day < the_day) ) {
		valid_date = false;
	}

	// Check we are not going into the past
	var the_date = new Date();
	var y 	= the_date.getFullYear();
	var m 	= the_date.getMonth();
	var d 	= the_date.getDate();
	var ny 	= new_date.getFullYear();
	var nm 	= new_date.getMonth();
	var nd 	= new_date.getDate();

	if ( (ny<y || (nm<m && ny==y) || (nd<d && nm==m && ny==y)) && mainWindowPage == "availability_calendar" && canSeePastDates == false ) {
		openMessage("Please select current or future dates only","a",120);
	} else {
		calendarToggle = false;
		
		if ( mainWindowPage == "availability_calendar" || mainWindowPage == "quick_search") {
			var rateId = id("rateSelect").value;
			var agent_id = id("rv_agent_id").value;
			var contact_id = id("rv_corr_persona_id").value;
			
			if ( id("allocDiv").style.display == "block" ) {
				allocDropDown = id("allocOptions").options[id("allocOptions").selectedIndex].value;
			} else {
				allocDropDown = "";
			}

			provDis = id("showProvs").disabled;
			provCheck = id("showProvs").checked;

			window.location = "reservation.php?20+" + changed_date + "+" + selectedProperties + "+" + selectedStatuses + "+" + agent_id + "+" + rateId + "+" + contact_id + "+" + id("commPerc").value + "+" + allocDropDown + "+" + provDis + "+" + provCheck + "+" + selIndex("commDeduct") + "+" + maxCalPopup;
		} else {
			if ( id("rv_agent_id") ) {
				agent_id = id("rv_agent_id").value;
			}

			if ( selectedStatuses === "" ) {
				openMessage("Please select at least one status");
				//id("showAlloc").checked = true;
				return 0;
			}
			//alert(selectedStatuses);
			window.location = "reservation.php?29+" + changed_date + "+" + selectedProperties + "+" + selectedStatuses + "+++" + agent_id;
		}
	}
}

function updateRoom(resItemId,roomList,requestYN,requestReason) {
	openPopup("reservation.php?224+++" + resItemId + "+calendar+" + roomList + "+" + requestYN + "+" + escape(requestReason),320,455);
}

function setRoomId(groupId,roomId,resItemId,requestYN,requestReason) {
	url = "reservation.php?637+" + resItemId + "+7+" + roomId + "+" + requestYN + "+" + escape(requestReason);

	if ( rsBusy == "0" ) {
		id("loadingRow").style.display = "inline";
		rsRequest(url);
		return 1;
	} else {
		openMessage("Please wait for your previous action to complete");
	}
}

function allocCheckbox() {
	var finalStatus = "";
	if ( id("showAlloc").checked ) {
		selectedStatuses += ":" + 15;
	} else {
		statusArray = selectedStatuses.split(":");
		for ( s in statusArray ) {
			if ( statusArray[s] != 15 ) {
				finalStatus += ":" + statusArray[s];
			}
		}
		selectedStatuses = finalStatus;
	}
	reloadPage();
}

var rateDropdownAll = false;

function rateDropdownShow(force) {
	if(id("rateDropdown").className == "" && !force) {
		rateDropdownHide();
	} else {
		aRequestPost("reservation.php?297+"+id("rv_agent_id").value + "+" + (rateDropdownAll?"1":"0"),rateDropdownLoad,[],[]);
	}
}

function rateDropdownHide() {
	id("rateDropdown").className = "collapse";
}


function rateDropdownLoad(result, response) {
	if(result) {
		id("rateDropdown").innerHTML = response;
		id("rateDropdown").className = "";
		id("rateDropdown").style.top = getTop(id("rateSelectLabel")) + id("rateSelectLabel").offsetHeight;
		id("rateDropdown").style.left = getLeft(id("rateSelectLabel"));
	}
}

var confirmRateSelect;
var confirmRateSelectLabel;

function rateDropdownSet(rateId,rateLabel,hasAgent) {
	if(!hasAgent) {
		confirmRateSelect = rateId;
		confirmRateSelectLabel = rateLabel;
		delAction = "rate";
		openConfirm("You have selected a rate type not allocated to the agent / direct contact. Would you like to continue?");
		return;
	}
	id("rateSelect").value = rateId;
	id("rateSelectLabel").value = rateLabel;
	rateDropdownHide();
	selectRate();
}

function rateDropdownToggle() {
	rateDropdownAll = !rateDropdownAll;
	rateDropdownShow(true);
}
