var mode;   // Mode of Main frame (new,edit,display)

// Status Bar Text : START ----------------------------------------------------
var wait = 80;       //sleep time until next letter (milliseconds);
var HideArray = ['select_day'];
var message = [];
		message[0] = "For best printing results...          ";
		message[1] = "Set orientation to Landscape...                     ";

var msgs = 1;
var curmsg = 0;
var a = 0;
var b = 0;
var counter = 0;
var timerID = "";
var running = false;
// Status Bar Text : END ------------------------------------------------------

var wizCalIds = [];
var loadingAvailability = "0";
var delItemId = "";
var delAction = "";

// Initialisation Code
window.focus();

function closeMemoOpt(){
	applyTrans(0);
	id("memoOpt").style.zIndex = "1";
	id("memoOpt").style.display = "none";
	if (mainWindowPage == "availability_calendar" ) 
		reloadPage();
}

function calendarCell(oRow,calendarRow) {
	oCell = oRow.insertCell();
	propertyName = calendarRow[1];
	propertyName = escape(propertyName);

	var cellValue = parseInt(calendarRow[i+4],10);
	var asterisk 	= calendarRow[i+4].indexOf("*");

	if (cellValue > 0) {
  	oCell.className = calAvailable;
	} else {
  	oCell.className = calOverbooked;
	}

	oCell.name = calendarRow[0] + ":" + propertyName + ":" + calendarRow[2] + ":" + cellValue;		// Property ID:Property Name:Accomm Type:Cell value
  oCell.id = 	calendarRow[0] + ":" + monthvals[i] + ":" + days[i];                         			// Property ID:month:day

	// DO NOT show cell value if CeilingNum is set to 1
  if (CeilingNum == 1) {
		cellValue = "";
	}
  
	if (asterisk > 0) {
		cellValue = cellValue + "*";
	} else {
		cellValue = cellValue + "&nbsp;"
	};

	oCell.innerHTML = cellValue;

	for (k = 0; k <= weekends.length; k++) {
		var weekend_date = weekends[k];
    
		weekend_date = "a" + weekend_date;
    weekend_date = weekend_date.substr(7);
    
		if (weekend_date == (days[i])) {
			oCell.className = calWeekendEmpty;
		}
	}
	
	selectedDay = id("select_day").options[id("select_day").selectedIndex].value;
	
	if (days[i] == selectedDay) {
		// oCell.className = calSelected;
  }
  
	if (parseInt(calendarRow[i+4],10) <= 0) {
		oCell.className = calOverbooked;
	}
  
	oCell.align 				= "center";
  oCell.UNSELECTABLE 	= "on";
  oCell.width 				= "20";
  oCell.onmousedown 	= mouseDown;
  oCell.onmouseup 		= mouseUp;
  oCell.onmouseover 	= mouseOverFunction;
}

//////////////////////////////////////////////////////////
// Generate the calendar footer buttons (go wizard etc. //
//////////////////////////////////////////////////////////
function generateFooterButtons(){
	oRow = id("calendarFooter");
	oRow.id = "footerRow";

	var booking = "<td><table onclick=\"openPopup('calendar_booking_info.php',400,325,false,160)\" width=\"90\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"outDk\"><tr><td width=\"26\" height=\"15\" align=\"center\" valign=\"middle\"><img src=\"images/button_bkginfo.gif\"></td><td width=\"58\" align=\"left\" valign=\"middle\" class=\"txts\">Booking Info</td></tr></table></td><td width=\"8\"></td>";
	var contact = "<td width=\"93\"><table onclick=\"openPopup('email_form.php?email_address='+PrincipalEmail,578,342)\" width=\"75\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"outDk\"><tr><td width=\"21\" height=\"15\" align=\"center\" valign=\"middle\"><img src=\"images/button_email.gif\"></td><td width=\"88\" align=\"left\" valign=\"middle\" class=\"txts\">Contact Us</td></tr></table></td></tr></table></td>";
	var viewItin = "<td align=\"right\"><table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"outLt\"><tr><td width=\"8\">&nbsp;&nbsp;</td><td height=\"25\"><table onClick=\"isItinerary()\" width=\"85\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"outDk\" onMouseOver=\"overlib('- Click and drag over the accommodation type for the required reservation dates.<br>- Add additional reservation items by following the same procedure.<br>- Click the email request button to email your (no obligation) itinerary request.<br>- Hover over this button if you would like to see a summary of the item/s selected.',BELOW,OFFSETY,-135,WIDTH,200)\" onMouseOut=\"nd()\"><tr><td width=\"20\" height=\"15\" align=\"center\" valign=\"middle\"><img src=\"images/button_itinerary.gif\"></td><td align=\"left\" valign=\"middle\" class=\"txts\">View Itinerary </td></tr></table></td>";
	var clearItin = "<td width\"8\">&nbsp;&nbsp;</td><td><table onclick=\"clearItinerary()\" width=\"90\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"outDk\" onMouseOver=\"overlib('Click here to clear your itinerary. Only available once an itinerary has been started',BELOW,OFFSETY,-50,WIDTH,150)\" onMouseOut=\"nd()\"><tr><td width=\"22\" height=\"15\" align=\"center\" valign=\"middle\"><img src=\"images/button_itinclear.gif\"></td><td id=\"clearItinerary\" width=\"66\" align=\"left\" valign=\"middle\" class=\"txts\">Clear Itinerary </td></tr></table></td>";

	if (showPrincipalWizard) {
		var wiz = "<td width\"8\">&nbsp;&nbsp;</td><td><table onclick=\"openWizard()\" width=\"116\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"outDk\" onMouseOver=\"overlib('Click here to create a reservation request. Only available once an itinerary has been started.',BELOW,OFFSETY,-60,WIDTH,150)\" onMouseOut=\"nd()\"><tr> <td width=\"20\" height=\"15\" align=\"center\" valign=\"middle\"><img src=\"images/button_createres.gif\"></td><td id=\"openWizard\" width=\"94\" align=\"left\" valign=\"middle\" class=\"txtsg\">Create Reserveation </td></tr></table></td><td width=\"8\">&nbsp;&nbsp;</td>";
	} else {
		var wiz = "";
	}

	if (showEmailWizard) {
		var emailRes = "<td width\"8\">&nbsp;&nbsp;</td><td><table onclick=\"openEmailForm()\" width=\"146\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"outDk\" onMouseOver=\"overlib('Click here to email your reservation request. Only available once an itinerary has been started.',BELOW,OFFSETY,-60,WIDTH,150)\" onMouseOut=\"nd()\"><tr><td width=\"20\" height=\"15\" align=\"center\" valign=\"middle\"><img src=\"images/button_email.gif\"></td><td id=\"openWizard\" width=\"124\" align=\"left\" valign=\"middle\" class=\"txtsg\">E-mail Reservation Request</td></tr></table></td><td width=\"8\">&nbsp;&nbsp;</td></tr></table>";
	} else {
		var emailRes = "";
	}
  
	var footerButtons = booking + contact + clearItin;
}

/////////////////////////////////////////////////////////
// Get the number of rooms requested                   //
// - called by mouseUp function (calendars_common.js)  //
/////////////////////////////////////////////////////////
var roomPopup = false;

function getValues() {
	// Generate popup to get number of rooms required
	start 		= selected_cells_ids[0];
	end 			= selected_cells_ids[selected_cells_ids.length-1];
	agentId = AgentID;

	if (userStatusId > "1") {
		agentId = id("rv_agent_id").value;
	}

	roomPopup = openPopup('reservation.php?674+'+start+'+'+end+"++++" + agentId + "+" + id("rateSelect").value,350,350);
	
	setTimeout("validRoomPopup()", 1);
}

function validRoomPopup() {
	if (!roomPopup || roomPopup.closed) {
		resetSelection();
		return;
	}

	if (roomPopup.isLoaded) {
		return;
	}

	setTimeout("validRoomPopup()", 100);
}

function makeItem(url,more) {
	if (rsBusy == "0") {
		id("searchAgentButton").style.visibility 		= "hidden";
		id("searchContactButton").style.visibility 	= "hidden";
		id("commPerc").disabled = true;
		id("commDeduct").disabled = true;
		
		returnAvailability();

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

function processValues(components,split_yn,ovrdRateAmt,roomList,roomRequestYN,roomRequestReason,allocations,itemRate) {
	// If the user does not accept an overbooking then reset selection
  if (wizData == "") {
  	var startCell 	= document.getElementById(selected_cells_ids[0]);
    var startName 	= startCell.getAttribute("name").split(":");
    var startPeriod = startName[5];

		var endCell 		= document.getElementById(selected_cells_ids[selected_cells_ids.length-1]);
		var endName 		= endCell.getAttribute("name").split(":");
		var endPeriod 	= endName[5];
	}

	if (startPeriod != endPeriod){
  	if (blockRateOverLap) {
    	//openMessage("This item overlaps the start of a new period and will be split for each period");
		}
	}

	if(response == "no") {
		resetSelection();
    lowest_selection = 999;
		id("overbooked").value = "false";
		return 0;
	}

	haveItinerary = true;

	// Enable the 'Clear Itinerary' button as soon as we have one
	var clearItinerary 	= id("clearItinerary");
	var openWizard 			= id("openWizard");

	if (loadingAvailability == "1") {
		rooms = loadRooms;
	}

	// Add the selection to the list of cells to be reset on clearing the calendar
	if (wizData == "") {
		for (a = 0; a < selected_cells_ids.length; a++) {
			if (!contains(wizCalIds,selected_cells_ids[a])) {
				wizCalIds[wizCalIds.length] = selected_cells_ids[a];
			}
		}
    
		/* ------------------------------------------------------------------------
		 * Set cookie to save current itinerary 
		 * --------------------------------------------------------------------- */
		// Get current itinerary
    var selected_cells_string = Get_Cookie("selected_cells");
    
		if (selected_cells_string != "") {
			selected_cells_string += "!";
		}
    
		// Get current selection
    for (i = 0; i < selected_cells_ids.length-1; i++) {
			selected_cells_string += selected_cells_ids[i] + "!";
		}
    selected_cells_string += selected_cells_ids[selected_cells_ids.length-1];
    
		var startCell 			= selected_cells_ids[0];
		var startCellArray	= startCell.split(":");
		var endCell 				= selected_cells_ids[selected_cells_ids.length-1];
		var endCellArray 		= endCell.split(":");

		// Check if we cross year boundary on selection
    if (years.length > 1) {
			// Find out the starting year of selection
      if (parseInt(startCellArray[1],10) == 1) {
				var startYear = years[1];
			} else {
				var startYear = years[0];
			}

			// Find out the ending year of selection
			if (parseInt(endCellArray[1],10) == 1) {
				var endYear = years[1];
			} else {
				var endYear = years[0];
			}
		} else {
			var startYear = years[0];
      var endYear 	= years[0];
		}

		start_date 	= startYear + "/" + startCellArray[1] + "/" + startCellArray[2];
		end_date 		= endYear + "/" + endCellArray[1] + "/" + endCellArray[2];

		var temp_start_date = new Date(start_date);
    var temp_end_date = new Date(end_date);
    temp_end_date = DayAdd(temp_end_date,1);

		// Swap dates if user dragged backwards
		if (temp_start_date > temp_end_date) {
			var temp_date = temp_end_date;
			var temp_end_date = temp_start_date;
			var temp_start_date = temp_date;
			var t_start_date = end_date;
			var end_date = start_date;
			var start_date = t_start_date;
		}
	}

	if (loadingAvailability == "0") {
		var rateId = id("rateSelect").value;
		
		if (rateId == " ") {
			rateId = "0";
		}

		agentId = AgentID;
		contactId = 0;

		if (userStatusId > "1") {
			agentId = id("rv_agent_id").value;
      contactId = id("rv_corr_persona_id").value;
		}

		if (id("commPerc") && !id("commPerc").disabled) {
			agentId = agentId + ":" + id("commPerc").value + ":" + selValue("commDeduct");
		}

		more = 0;

		if (submitPath) {
			more = submitPath;
		}

		url = "reservation.php?637+" + wizData + "+2++" + rateId + "+" + agentId + "+" + components + "+" + contactId + "+" + split_yn + "+" + ovrdRateAmt + "+"+more+"+" + roomList + "+" + roomRequestYN + "+" + escape(roomRequestReason) + "+" + allocations + "+" + itemRate;
		wizData = "";

		makeItem(url,more);
		return 1;
	}

	// Reduce calendar cell values by number of rooms booked ---------------------
	if ( !publicPage && !limitOne && !roomingPopup ) {
		for ( i = 0; i < selected_cells_ids.length; i++ ) {
			var cell 			= id(selected_cells_ids[i]);
			var cellValue = cell.innerHTML;
			
			if (cellValue != "" && cellValue != "&nbsp;") {
				var asterisk = cellValue.indexOf("*");
				var currentvalue = parseInt(cellValue,10);
				var newvalue = currentvalue - parseInt(rooms);
				if ( asterisk == -1 ) {
					cell.innerHTML = newvalue;
				} else {
					cell.innerHTML = newvalue + "*";
				}
			} else {
				if (cellValue == "&nbsp;") {
					cell.innerHTML = "&nbsp;";
				} else {
					cell.innerHTML = "";
				}
			}
		}
	}
}

function reloadItin() {
	url = "reservation.php?637++1";
	
	if (rsBusy == "0") {
		id("searchAgentButton").style.visibility = "hidden";
		id("searchContactButton").style.visibility = "hidden";
		id("commPerc").disabled = true;
		id("commDeduct").disabled = true;

		returnAvailability();

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

function isItinerary() {
	if ( selected_data.length == "" ) {
		openInfoPop('info_itinerary.htm',event,300,213,screen.availWidth/2 - 300/2,screen.availHeight/2 - 213/2);
	} else {
		openInfoPop('info_itinerary_details.htm',event,300,203,screen.availWidth/2 - 300/2,screen.availHeight/2 - 213/2);
	}
}

function resetSelection() {
	rooms = "";
	wizData = "";

	if ( mainWindowPage == "quick_search" ) {
		return;
	}
  
	for ( i = 0; i < selected_cells_ids.length; i++ ) {
		var cellId = selected_cells_ids[i];
		var cellPtr = document.getElementById(cellId);
		var cellName = cellPtr.getAttribute("name");
		var cellIdArray = cellId.split(":");
		var cellNameArray = cellName.split(":");
		var cellValue = parseInt(cellNameArray[3]);
    
		for ( j = 0; j < weekends.length; j++ ) {
			weekend_day = "a" + weekends[j];
			if ( parseInt(cellIdArray[2],10) == parseInt(weekend_day.substr(7,2),10) ) {
				weekendday = true;
				break;
			} else {
				weekendday = false;
			}
		}

		var extraClass = "";
		if(cellPtr.className.toString().match(/allocationIndicator/)) {
			extraClass = " allocationIndicator";
		}
		if ( cellPtr.getAttribute("darkness") < 2 ) {
			cellPtr.setAttribute("darkness",parseInt(cellPtr.darkness) - 1);
			if ( cellPtr.getAttribute("ab") == "1" ) {
				cellPtr.className = calBlocked + extraClass;
				cellPtr.darkness = 0;
			} else {
				if ( cellValue <= 0 ) {
					cellPtr.className = calOverbooked + extraClass;
				} else {
					if ( weekendday == true ) {
						cellPtr.className = calWeekendEmpty + extraClass;
					} else {
						cellPtr.className = calAvailable + extraClass;
					}
				}
			}
		} else {
			if ( cellPtr.darkness == "2" ) {
				cellPtr.className = calClick + extraClass;
			}
			cellPtr.darkness = parseInt(cellPtr.darkness) - 1;
		}
	}
	return 0;
}

function openEmailForm() {
	if ( selected_data.length ) {
		var selectedData = selected_data.substr(0,selected_data.length - 1);
    openPopup("reservation.php?184+" + selectedData,638,470);
	} else {
		openMessage("Please first select your itinerary by clicking and dragging over the accommodation dates you would like to reserve, then click the E-mail Booking button",false,150);
	}
}

function openCalendarRules() {
	openPopup('calendar_rules.htm',650,410);
}

function clearItinerary() {
	if ( haveItinerary ) {
		returnAvailability();
		Set_Cookie("selected_cells","");
		selected_cells_array.length = 0;
		selected_cells_ids.length = 0;
		selected_cells_string = "";
		haveItinerary = false;
		removeAvailability();
	}	else	{
		openMessage("Clear Itinerary is only available once an itinerary has been created");
	}
}

function openWizard() {
	if ( haveItinerary ) {
		var res_items = selected_data.substr(0,selected_data.length-1);
    selected_data = "";
    id("selected_properties").value = res_items;
		openPopup("reservation.php?130+1+"+res_items,650,300);
	} else {
		openMessage("You have not made any selections on your calendar. Please click and drag across calendar cells to select dates and camps",false,150);  // parms(height,message)
	}
}

function typew() {
	running = true;
  a = a + 1;
  check();
  window.status = message[curmsg].substring(0, a);
  
	if ( a == message[curmsg].length + 5 ) {
		curmsg = curmsg + 1;
    a = 0;
		b++;
	}

	if ( b == 6 ) {
		stopStatusType();
	}

	if ( curmsg > msgs ) {
		curmsg = 0;
	}
  
	if ( running ) {
		timerID = setTimeout("typew()", 40);
	}
}

function check(){
  if(a <= message[curmsg].length){
    if(message[curmsg].substring(a, a + 1) == ""){
      a = a + 1;
      check();
    }
  }
}

function stopStatusType(){
  clearTimeout(timerID);
   running = false;
}

function logon(){
   typew();
   var pr_user_name = document.getElementById("pr_user_name").value;
   var pr_user_password = document.getElementById("pr_user_password").value;
   if(pr_user_name == "" || pr_user_password == ""){
      openMessage("Please enter a Username and Password");
    }else{
     document.forms[0].submit();
    }
}

function chngPass(){
   openPopup('reservation.php?527',365,380);
}

// Added for public calendar
// Takes user to selected server
function serverGo(){
   parent.window.location.href = id("serverSelect").options[id("serverSelect").selectedIndex].value;
}

function keyDown(e) {
  if(publicPage){
     if(e.keyCode == 13) {
  //     logon();
     }
  }
  if(e.keyCode == 123 && mainWindowPage == "availability_calendar") { // F12
	showQuickDate();
 }
}

function selectRate(){
	if(mainWindowPage == "quick_search") { return; } 
		var rateId = id("rateSelect").value;

   var rateRay = new Array();
   for(a=0;a<rateData.length;a++){
      if(rateData[a] == rateId){
         rateRay = rateData[a+1];
         break;
      }
   }

   var rateEcho = "";
   for(b=0;b<rateRay.length;b++){
      if (b==rateRay.length-1){
         rateEcho = document.getElementById("rateEcho");
         rateEcho.innerHTML = rateRay[b];
         //
         //var temp = rateRay[b].split("(");
         //temp = temp[1].split(")");
         //document.getElementById("resCurr1").innerHTML = temp[0];
         //document.getElementById("resCurr2").innerHTML = temp[0];
         //document.getElementById("resCurr3").innerHTML = temp[0];
         //
         break;
      }
      rateDisplay = document.getElementById("rate"+accommIdList[b]);
      rateDisplay.innerHTML = rateRay[b] + "&nbsp;";
   }
}

function addItinerary(){
	agentId = AgentID;

	if ( userStatusId > "1" ) {
		agentId = id("rv_agent_id").value;
	}

	toggleStep2('hide');
 
	openPopup('reservation.php?674++++++' + agentId + "+" + id("rateSelect").value,350,360);
}

function removeAvailability() {
	if ( mainWindowPage == "quick_search" ) {
		// hide row containing "loading" button -------------------------------------
		id("loadingRow").style.display = "none"
		return;
	}

	loadingAvailability = "1";

	for ( x = 0; x < wizCalData.length; x++ ) {
		for ( y = 0; y < wizCalData[x].length-1; y++ ) {
			var cell = document.getElementById(wizCalData[x][y]);

			if ( !contains(wizCalIds,wizCalData[x][y]) ) {
				wizCalIds[wizCalIds.length] = wizCalData[x][y];
			}

			if ( y == 0 && wizCalData[x].length > 2 ) {
				wizMouseDown(cell);
			} else {
				if ( y == 0 ) {
					wizMouseDown(cell);
				} else {
					wizMouseOverFunction(cell);
				}

				if ( y == wizCalData[x].length-2 ) {
					wizMouseUp(cell);
					loadRooms = wizCalData[x][wizCalData[x].length-1];
					processValues();
				}
			}
		}
	}
	loadingAvailability = "0";

	// Hide row containing "loading" button --------------------------------------
	id("loadingRow").style.display = "none";
}

function returnAvailability(){
	if (mainWindowPage == "quick_search") {
		return;
	}
   
	id("loadingRow").style.display = "none";                              // hide row containing "loading" button
   
	for(a=0;a<selected_cells_ids.length;a++) {
		if(!contains(wizCalIds,selected_cells_ids[a])) {
			wizCalIds[wizCalIds.length] = selected_cells_ids[a];
		}
	}
	cellList = wizCalIds;

	for(i=0;i<cellList.length;i++) {
		var cellId = cellList[i];
		var cellPtr = id(cellId);
		var cellName = cellPtr.getAttribute("name");
      
		var cellIdArray = cellId.split(":");
      
		if (cellIdArray.length < 1) {
			continue;
		}
      
		var cellNameArray = cellName.split(":");
		var cellValue = cellNameArray[3];
		var asterisk2 = cellPtr.innerHTML.indexOf("*");

		if(!publicPage) {
			cellPtr.innerHTML = cellValue;
		}
		if (asterisk2 == "1" && cellValue.indexOf("*") == "0"){
			cellPtr.innerHTML += "*";
		}
		//var selectedDay = calNewPeriodStart;

		for(j=0;j<weekends.length;j++) {
			weekend_day = "a" + weekends[j];
			if(parseInt(cellIdArray[2],10) == parseInt(weekend_day.substr(7,2),10)) {
				weekendday = true;
				break;
			} else {
				weekendday = false;
			}
		}

		cellValue = parseInt(cellValue);

		// is_overbooked ? calOverbooked
		var extraClass = "";
		if(cellPtr.className.toString().match(/allocationIndicator/)) {
			extraClass = " allocationIndicator";
		}
		if(cellPtr.className.toString().match(calClick) || cellPtr.className.toString().match(calClickOver)) {
			if(cellPtr.getAttribute("ab") == "1") {
				cellPtr.className = calBlocked + extraClass;
				cellPtr.innerHTML = "&nbsp;"
				cellPtr.darkness = 0;
			} else {
				if(cellValue <= 0) {
					cellPtr.className = calOverbooked + extraClass;
				} else {
					// is_weekend ? calWeekend
					if(weekendday === true) {
						cellPtr.className = calWeekendEmpty + extraClass;
					} else {
						cellPtr.className = calAvailable + extraClass;
					}
				}
				cellPtr.darkness = 0;
			}
		}
	}
	haveItinerary = false;
	return 0;
}

function wizMouseOverFunction(e) {
	window.status = e.id;
	if(mouseDown_flag) {
		if(parseInt(e.innerHTML) == 0 && mainWindowPage == "occupancy_calendar") {
			var temp_var = window.event.srcElement.id;
			var split_temp = temp_var.split(":");
			var temp_var1 = window.event.srcElement.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 && !roomingPopup ) {
		var split_temp1 = e.id.split(":");

		if ( split_temp1[0] != startCell[0] ) {
			resetSelection();
			mouseDown_flag = false;
			openMessage("Please select on only one row","a");
			return 0;
		}

		var extraClass = "";
		if(e.className.toString().match(/allocationIndicator/)) {
			extraClass = " allocationIndicator";
		}
		if ( parseInt(e.darkness) == 0 ) {
			e.className = calClick + extraClass;
			e.darkness = parseInt(e.darkness) + 1;
		} else {
			e.className = calClickOver + extraClass;
			e.darkness = parseInt(e.darkness) + 1;
		}
		selected_cells_array[selected_cells_array.length]	= e;
		selected_cells_ids[selected_cells_ids.length]			= e.id;

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

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

	selected_cells_array.length = 0;
	selected_cells_ids.length = 0;

	selected_cells_array[0] = e;
	selected_cells_ids[0] = e.id;

	var temp_var = e.id;
	var split_temp = temp_var.split(":");
	var temp_var1 = e.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;

	if ( !roomingPopup ) {
		var extraClass = "";
		if(e.className.toString().match(/allocationIndicator/)) {
			extraClass = " allocationIndicator";
		}
		if ( parseInt(e.darkness) == 0 ) {
			e.className = calClick + extraClass;
			e.darkness = parseInt(e.darkness) + 1;
		} else {
			e.className = calClickOver + extraClass;
			e.darkness = parseInt(e.darkness) + 1;
		}
	}
	lowest_selection = parseInt(e.innerHTML);
}

function wizMouseUp(e) {
   var temp_var = e.id;
   var split_temp = temp_var.split(":");
   var temp_var1 = e.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(mouseDown_flag) {
      rooms = true;
      mouseDown_flag = false;
      if (loadingAvailability == "0"){
         getValues();
      }
   }
}

function contains(a, e) {
   for(j=0;j<a.length;j++)if(a[j]==e)return true;
   return false;
}

function frameLoad() {
   if (canUseWizard) {
      removeAvailability();
	  // **FIX**
      rateDropDown = document.getElementById("rateSelect");
      if (frameRateId != "" && frameRateId != "rateId") {
         for(i=0;i<rateDropDown.length;i++) {
            rateId = rateDropDown.options[i].value;
            if (rateId == frameRateId) {
               rateDropDown.selectedIndex = i;
               rateDropDown.disabled = true;
               //selectRate();
            }
         }
      } else {
         rateDropDown.disabled = false;
      }
      selectRate();
      if (userStatusId > 1) {
         //alert(userStatusId);
         if ((frameAgentId != "" && frameAgentId != gtfAgentId && frameAgentId != "0") || isItinerary == true) {
            id("searchAgentButton").style.visibility = "hidden";
            id("searchContactButton").style.visibility = "hidden";
			 id("commPerc").disabled = true;
			 id("commDeduct").disabled = true;
         }else{
            id("searchAgentButton").style.visibility = "visible";
            id("searchContactButton").style.visibility = "visible";			
			if(id("rv_agent_id").value == "0") {
			 id("commPerc").disabled = true;
			 id("commDeduct").disabled = true;
			} else {
			 id("commPerc").disabled = false;
			 id("commDeduct").disabled = false;
			}
         }
         //AgentDropDown = document.getElementById("rv_agent_id");
         //if (frameAgentId != ""){
         //   for(i=0;i<AgentDropDown.length;i++){
         //      agentId = AgentDropDown.options[i].value;
         //      if (agentId == frameAgentId){
         //         AgentDropDown.selectedIndex = i;
         //         AgentDropDown.disabled = true;
         //      }
         //   }
         //}else{
         //   AgentDropDown.disabled = false;
         //}
      }
   }else{
      id("loadingRow").style.display = "none";
   }
}

function alertUser(){
   openMessage('Session expired, your reservation was deleted.<br>Please start again by creating an item');
}

function delItem(){
   itemId = delItemId;
   returnAvailability();
   rsRequest("reservation.php?637+" + itemId + "+4");
}

function confDelItem(itemId){
   delItemId = itemId;
   delAction = "item";
   openConfirm("Are you sure you want to delete this item?");
}

function confEmptyItin(){
   delAction = "itin";
   openConfirm("Are you sure you want to clear your itinerary?");
}

function processResponse(){
	if (delAction == "item") {
		delItem();
	}
	if (delAction == "itin"){
		emptyItinerary();
	}
	if (delAction == "rate") {
		rateDropdownSet(confirmRateSelect,confirmRateSelectLabel,true);
	}
}

function goDate(date){
   window.location="reservation.php?20+"+date+"+"+selectedProperties+"+"+selectedStatuses;
}

function emptyItinerary(){
   if (isItinerary == "1"){
      returnAvailability();
      rsRequest("reservation.php?637++0");
   }else{
      openMessage("Your itinerary is already empty");
   }
}

function processForm2(){
   if (isItinerary == "1"){
      window.location='reservation.php?639';
   }else{
      openMessage("Please create an item before proceeding");
   }
}

function showItinerary() {
	id("itineraryRows").style.display = "block";	
  id("clearItineraryButton").style.display = "block";
  id("nextStepButton").style.display = "block";
}

function hideItinerary(){
   id("itineraryRows").style.display = "none";
   id("clearItineraryButton").style.display = "none";
   id("nextStepButton").style.display = "none";
   //id("rv_agent_id").value = "0";
   //id("agent_name").value = "Direct";
   //id("rv_corr_persona_id").value = "0";
   //id("contact_name").value = "No Contact";
}

function runConfigAction(url) {
	returnAvailability();
	rsRequest(url);
}

function checkReturn(event) {
	if (event.keyCode == 13) {
		reloadPage();
	}
}

function agentNoteShow() {
	if (id("agent_name").value == "Direct" || userStatusId < 1) {
		id("agentPop").style.visibility = "hidden";
	} else {
		id("agentPop").style.visibility = "visible";
	}
}

function gotoQuick(new_date) {
	var jobId = "20";
  if (mainWindowPage == "availability_calendar") {
		if (new_date == "") {
			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;

			// 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;

			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 jobId = "693";
	} else {
		if (new_date != "") {
			split_date = new_date.split("-");
			temp_day = split_date[2];
			temp_month = split_date[1];
			temp_year = split_date[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)) {
				openMessage("Calendar can only be displayed until " + calDateResLimitNice);
				return 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 rateId = id("rateSelect").value;
	var agent_id = id("rv_agent_id").value;
	var contact_id = id("rv_corr_persona_id").value;

	url = "reservation.php?"+jobId+"+"+changed_date+"+"+"+"+"+"+agent_id+"+"+rateId+"+"+contact_id;
	window.location = url;
}

function accommClick(propertyId, accommId) {
	Set_Cookie("availCalRoomPopup",propertyId + "|" + accommId);

	if ( !accommId ) {
		accommId = "";
	}

	names		= ["propertyId","accommId"];
	values	= [propertyId,accommId];
	date		= id("year").value + "-" + id("select_month").selectedIndex + "-" + id("select_day").selectedIndex;

	id("divLoading").style.display	= "";
	id("divLoading").style.zIndex		= 100;
	centerDivOnPage("divLoading");

	//applyTrans(1);
	// Hide Form elements that show through -------------------------------------
	if ( id("allocOptions") ) {
		id("allocOptions").style.visibility = "hidden";
	}
	
	//setTimeout("tcUpdateWaitText(0);",100);
	aRequestPost("reservation.php?259+1+"+date,roomPopupLoad,names,values);
}

function roomPopupLoad(result, response) {
	//applyTrans(0);

	if ( result ) {
		id("roomPopupDiv").innerHTML = unescape(response);
		id("roomPopupDiv").style.left = getLeft(id("filterArea"));

		if ( mainWindowPage != "quick_search" ) {
			if ( id("agentDetailsRow").style.display != "none" ) {
				id("roomPopupDiv").style.top = 264;
			} else {
				id("roomPopupDiv").style.top = 186;
			}
		} else {
			id("roomPopupDiv").style.top = 340;
		}

		id("roomPopupDiv").style.display	= "";
		id("divLoading").style.display		= "none";
		id("roomPopupDiv").style.zIndex		= 100;
		//applyTrans(1);
	}
}

function closeRoomPopup() {
	Set_Cookie("availCalRoomPopup","");

	if(id("allocOptions")) {
		id("allocOptions").style.visibility = "visible";
	}

	id("roomPopupDiv").style.display = "none";
	id("roomPopupDiv").innerHTML = "";
	applyTrans(0);
}

function toggleAttr() {
	if ( id("attrCol").className == "collapse" ) {
		id("attrCol").className			= "";
		id("calScroll").style.width	= "410px";
		if ( is_ie ) {
			id("calScroll").style.height = id("calScroll").offsetHeight + 17;
		}
		id("btnToggleAttr").value		= ">> Hide Attributes";
	} else {
		id("attrCol").className			= "collapse";
		id("calScroll").style.width	= "590px";
		if ( is_ie ) {
			// We need to reset the days DIV back to it's originial height
			id("calScroll").style.height = id("calScroll").offsetHeight - 17;
		}
		id("btnToggleAttr").value		= "<< Show Attributes";
	}
}

var resNum;
var resCanEdit;

function openRes(oObj,oResNum,oResCanEdit) {
	resNum = oResNum;
	id("resTabDropDownTitle").innerHTML = oResNum;
	resCanEdit = oResCanEdit;
	click();
	if(id("resTabDropDown").style.display != "") {
		id("resTabDropDown").style.display = "";
		id("resTabDropDown").style.left = getLeft(oObj) + oObj.offsetWidth - id("resTabDropDown").offsetWidth + 2;
		id("resTabDropDown").style.top = oObj.offsetHeight + getTop(oObj) + 2;
	} else {
		id("resTabDropDown").style.display = "none";
	}
	event.cancelBubble = true;
}

function click() {
	if(id("resTabDropDown").style.display != "none") {
		id("resTabDropDown").style.display = "none";
	}
	id("itemMenuDiv").style.display = "none";	
}
/*
   if (canEditReservation($wizResId)) {
      $GLOBALS[temp][resDetailJob] = "2";
      $GLOBALS[temp][resNoteJob] = "137";
	   $GLOBALS[temp][resExtraJob] = "610";
      $GLOBALS[temp][resRoomJob] = "216";
      $GLOBALS[temp][resFinancialJob] = "647";
   } else {
      $GLOBALS[temp][resDetailJob] = "0";
      $GLOBALS[temp][resNoteJob] = "138";
	   $GLOBALS[temp][resExtraJob] = "609";
      $GLOBALS[temp][resRoomJob] = "215";
      $GLOBALS[temp][resFinancialJob] = "646";
   }

*/
function gotoReservation(tabName) {
	switch(tabName) {
		case "detail":
			if(resCanEdit) {
				jobId = 2;
			} else {
				jobId = 0;
			}
			break;
		case "notes":
			if(resCanEdit) {
				jobId = 137;
			} else {
				jobId = 138;
			}
			break;
		case "extras":
			if(resCanEdit) {
				jobId = 610;
			} else {
				jobId = 609;
			}
			break;
		case "rooming":
			if(resCanEdit) {
				jobId = 216;
			} else {
				jobId = 215;
			}
			break;	
		case"financial":
			if(resCanEdit) {
				jobId = 647;
			} else {
				jobId = 646;
			}
			break;
		case"comms":
			jobId = "191";
			break;
	}
	window.location = "reservation.php?" + jobId + "+" + resNum;
}


// Added for Availability Report
function gotoAvailabilityReport() {
	var day 	= id("select_day").selectedIndex;
	var month = id("select_month").selectedIndex;
	var year 	= id("year").value;
	
	if ( month < 10 ) {
		month = "0" + month.toString();
	}

	if ( day < 10 ) {
		day = "0" + day.toString();
	}

	fromDate = year + "-" + month + "-" + day;

	if ( id("allocOptions").selectedIndex == 0 ) {
		var showAlloc = true;
	}

	url = new Array(
		"reservation.php?262",
		fromDate,																// 1 fromDate
		"",																			// 2 toDate
		34,																			// 3 number of days
		"fromCal",															// 4 dateType
		selectedProperties,											// 5 Properties filter
		"",																			// 6 Accomm filter
		"",																			// 7 Render option (HTML, PDF, CSV)
		"",																			// 8 filterStatus (for hidin or showing the report filters)
		"",																			// 9 Hide filters button text
		"",																			//10 Show/Hide unit totals
		"",																			//11 Current page (for pagination)
		"",																			//12 Include page breaks
		"",																			//13 Show/hide report parameters
		"",																			//14 Limit Units text
		id("showProvs").status,									//15 Include provisionals
		showAlloc,															//16 Include agent's allocations
		gtfAgentId,															//17 Agent ID
		""																			//18 RandomID that is not defined here for some reason
	);
	window.location = url.join("+");
}

function includeAllocProvs(cID) {
	provs = id("showProvs").checked;
	alloc = parseInt(id("allocOptions").options[id("allocOptions").selectedIndex].value,10);
	
	selectedStatuses = "";

	id("showProvs").disabled = false;

	switch (alloc) {
	case 0 :
		selectedStatuses = "30:15";		
		break;
	case 1 :
		selectedStatuses = "30:15";
		break
	case 2 :
		if ( cID == "alloc" ) {
			selectedStatuses = "15";
			id("showProvs").disabled = true;
		}	else {
			// Reset to default settings --------------------------------------------
			id("allocOptions").selectedIndex = 0;
			selectedStatuses = "30:15";	
		}
		break;
	case 3 :
		selectedStatuses = "30:15";		
		break;
	case 4 :
		if ( cID == "alloc" ) {
			selectedStatuses = "15";
			id("showProvs").disabled = true;
		}	else {
			// Reset to default settings --------------------------------------------
			id("allocOptions").selectedIndex = 0;
			selectedStatuses = "30:15";	
		}
		break;
	}

	if ( provs ) {
		selectedStatuses += ":20";
	}

	reloadPage();

}

function toggleStep2(what) {
	var d = id("agentDetailsSummary");
	
	if ( what == "hide" ) {
		var s = [];
	
		id("agentDetailsRow").style.display = "none";
		id("btnStep2ShowHide").className = "button bExpandVertical";
	
		s[0] = "<strong>Agent:</strong> " + id("agent_name").value;
		s[1] = " <strong>Contact:</strong> " + id("contact_name").value;
		s[2] = " <strong>Commission:</strong> " + id("commPerc").value;
		s[3] = " <strong>Charge:</strong> " + selLabel("commDeduct");
		s[4] = " <strong>Rate:</strong> " + id("rateSelectLabel").value;
	
		d.innerHTML = s.join(";");
	} else {
		id("agentDetailsRow").style.display = "block";
		id("btnStep2ShowHide").className = "button bCollapseVertical";

		d.innerHTML = "&nbsp;";
	}
}

var itemMenuCurrentId = "";
var itemMenuCurrentRoomList = "";
var itemMenuCurrentRoomRequestYN = "";
var itemMenuCurrentRoomReason = "";

function showItemMenu(e,resItemId,allowRoom,allowComp,allowDel, roomList, roomRequestYN, roomReason) {
	if ( !e ) {
		e = window.event;
	}
	stopBubble(e);

	itemMenuCurrentId = resItemId;	
	itemMenuCurrentRoomList = roomList;
	itemMenuCurrentRoomRequestYN = roomRequestYN;
	itemMenuCurrentRoomReason = roomReason;
		

	var posx = 0;
	var posy = 0;
	
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	} else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}

	if(allowRoom) {
		id("itemMenuRoomRow").className = "imgLink";
	} else {
		id("itemMenuRoomRow").className = "collapse";
	}
	if(allowComp) {
		id("itemMenuCompRow").className = "imgLink";
	} else {
		id("itemMenuCompRow").className = "collapse";
	}
	if(allowDel) {
		id("itemMenuDelRow").className = "imgLink";
	} else {
		id("itemMenuDelRow").className = "collapse";
	}

	id("itemMenuDiv").style.display	= "";
	posx -= id("itemMenuDiv").offsetWidth;
	id("itemMenuDiv").style.left			= posx;
	id("itemMenuDiv").style.top			= posy;
}


