// Global vars for popup
var popupContainer;
var popupInner;
var popupHeader;
var popupShadow;

function checkpage(){
  alert('yes')
}

/*
    Uses the cQ styled popup template for displaying a message
*/
function niceAlert(width,height,message,title){
  showPopup(width,height,'<!--POPUP_MESSAGE-->'+message,title.toLowerCase());
}

function validatePayment(formObj,buttonObj,credit){
  if(!formObj.confirm_terms.checked){
    niceAlert(300,150,'You must confirm acceptance of the standard terms and conditions before making a booking.','there was a problem...');
    return;
  }
  buttonObj.disabled = true;
  
  if(credit){
    var c = confirm('The sum of £' + formObj.totalamount.value + ' will be deducted from you available credit. This amount will also be due through your usual payment terms.\n\nIf you are not aware of your payment terms, you should press Cancel and call a member of our team on 0845 402 5000.\n\nClick OK to confirm.');
    if(!c){
      buttonObj.disabled = false;
      return;
    }
  }
  formObj.submit();
}

/*
    Creates and shows a new popup Div
    @param width The width of the popup in pixels
    @param height The height of the popup in pixels
    @param url The url that should be loaded in the popup
    @param title The title of the popup (shown in header)
*/
function showPopup(width,height,url,title){
  if(popupContainer){ closePopup(); }
  
  var scrollTop = document.body.scrollTop;
  if (scrollTop == 0){
    if (window.pageYOffset){
      scrollTop = window.pageYOffset;
    } else {
      scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
    }
  }

  width = parseInt(width);
  height = parseInt(height);
  var left = (document.body.clientWidth / 2) - (width / 2);
  //var top = (document.body.clientHeight / 2) - height;
  var top = (getWindowHeight() / 2) - (height / 2);
  top += scrollTop;
  
  // Create Popup container
  var p = document.createElement("div");
  p.style.width = width + 'px';
  p.style.height = height + 'px';
  p.style.top = top + 'px';
  p.style.left = left + 'px';
  p.id = 'popupDiv';
  
  // Create Popup shadow
  var s = document.createElement("div");
  s.style.width = width + 'px';
  s.style.height = height + 'px';
  s.style.top = (top+5) + 'px';
  s.style.left = (left+5) + 'px';
  s.id = 'popupShadowDiv';
  
  // Create inner (body container)
  var i = document.createElement("div");
  i.style.width = (width-22) + 'px';
  i.style.height = (height-41) + 'px';
  i.style.left = '5px';
  i.style.top = '24px';
  i.className = 'inner';  
  
  // Create header
  var h = document.createElement("div");
  h.style.width = (width-4) + 'px';
  h.className = 'header';
  h.innerHTML = '&nbsp;::&nbsp; ' + title;
  
  // Create close button
  var c = document.createElement("img");
  c.src = '/images/close_button.jpg';
  c.style.position = 'absolute';
  c.style.top = '2px';
  c.style.left = (width - 20) + 'px';
  c.style.cursor = 'pointer';
  c.title = 'Close';
  c.onclick = function(){closePopup();};
  
  // Append objects
  document.body.appendChild(p);
  document.body.appendChild(s);
  p.appendChild(i);
  p.appendChild(h);
  p.appendChild(c);
  
  // Set to global vars
  popupContainer = p;
  popupInner = i;
  popupHeader = h;
  popupShadow = s;
  
  // Hide the page scroll bars
  // Disabled as it moves the page over - more annoying than it's worth
  //document.getElementsByTagName('body')[0].style.overflow = 'hidden';
  //document.getElementsByTagName('html')[0].style.overflow = 'hidden';
  
  // Load the content of the given URL
  popupLoad(url);
}

/*
    Close the current popup
*/
function closePopup(){
  try{
    document.body.removeChild(popupContainer);
    document.body.removeChild(popupShadow);
    popupContainer = null;
    popupInner = null;
    popupHeader = null;
    popupShadow = null;
    
    // Show the page scroll bars
    document.getElementsByTagName('body')[0].style.overflow = 'auto';
    document.getElementsByTagName('html')[0].style.overflow = 'auto';
  } catch(e){}
}

/*
    Loads a URL within the current popup
*/
function popupLoad(url){
   if(url.indexOf('<!--POPUP_MESSAGE-->') != -1){
     popupInner.innerHTML = url;
     return;
   }

  // Set popup to loading state
  popupLoading();
  
  var rnd = Math.random();
	var http = getXmlHttpObject();
  var appendChar = '&';
  if(url.indexOf('?') == -1){
    appendChar = '?';
  }
	try{
		http.open('GET',url + appendChar + 'rnd=' + rnd);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
				if(response.indexOf("<!--SUCCESS-->") != -1){
          try {
            popupInner.innerHTML = response;
          } catch(e){
          }
				} else if(response.indexOf("<!--REDIRECT-->") != -1) {
          var sPos = response.indexOf('<!--REDIRECT-->');
          var ePos = response.indexOf('<!--/REDIRECT-->');
          if(sPos == -1 || ePos == -1){
            return '';
          }
          sPos = sPos + 15;
          loadUrl(response.substring(sPos,ePos));
				} else {
        }
			}	
		}
		http.send(null);
	} catch (e){
	}
}

function loadUrl(url){
  window.location = url;
}

function launchAvailability(building){
  building = building + '';
  if(building.length < 1){ building = 'All Buildings'; }
  var url = '/online-booking/ajax/availability?building='+building;
  showPopup(350,350,url,'check availability');
}

/*
    Sets the title of the current popup
    @param newTitle the new title for the popup
*/
function popupSetTitle(newTitle){
  popupHeader.innerHTML = '&nbsp;::&nbsp; ' + newTitle;
}

/*
    Put current popup into a 'Loading' state
*/
function popupLoading(){
  var left = ((parseInt(popupInner.style.width) / 2) - 16) + 'px';
  var top = ((parseInt(popupInner.style.height) / 2) - 16) + 'px';
  var style = "position:absolute;width:32px;height:32px;left:"+left+";top:"+top+";";
  popupInner.innerHTML = "<img src=\"/online-booking/loading.gif\" title=\"loading\" style=\"" + style + "\" />";
}

function updateETA(obj){
  var rnd = Math.random();
	var http = getXmlHttpObject();
  var eta = obj.options[obj.selectedIndex].value;
	try{
		http.open('GET','/online-booking/portal/ajax/updateETA?eta=' + eta + '&rnd=' + rnd);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				return;
			}	
		}
		http.send(null);
	} catch (e){
	}
}

/*
    Launches availability check
*/
function checkAvailability(formObj){
  var url = formParamsToUri(document.getElementsByName(formObj)[0],'/online-booking/ajax/availabilityPreCheck');
  showPopup(350,250,url,'checking availability...');
}

/*
    Loads page for changing (and creating) the billing customer
*/
function changeBillingCustomer(){
  showPopup(350,250,'/online-booking/portal/ajax/changeBillingCustomer','change billing customer');
}

/*
    Selects a billing customer for the reservation (both on the page and the session)
    @param customerId The id of the guest to add
    @param customerName The name of the guest to add
*/
function selectBillingCustomer(customerId,customerName){
  // Checks if guest already exists for reservation
  if(!document.getElementById('billingCustomer')){
    closePopup();
    return;
  }
  
	var rnd = Math.random();
	var http = getXmlHttpObject();
	try{
		http.open('GET','/online-booking/portal/ajax/selectBillingCustomer?billingcustomer=' + customerId + '&rnd=' + rnd);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
				if(response == "1"){
          try {
            document.getElementById('billingCustomer').innerHTML = customerName;
          } catch(e){
          }
				} else {
				}
			}	
		}
		http.send(null);
	} catch (e){
	}
  
  closePopup();
}

/*
    Loads page for creating a new guest
*/
function createNewBillingCustomer(){
  popupLoad('/online-booking/portal/ajax/createBillingCustomer');
  popupSetTitle('change billing customer - create new');
}


function createBillingCustomerAdd(formObj){
  var url = formParamsToUri(formObj,'/online-booking/portal/ajax/createBillingCustomerAdd');
  var failUrl = formParamsToUri(formObj,'/online-booking/portal/ajax/createBillingCustomer');
  
  popupLoading();
  var appendChar = '&';
  if(url.indexOf('?') == -1){
    appendChar = '?';
  }
  var rnd = Math.random();
	var http = getXmlHttpObject();
	try{
		http.open('GET',url + appendChar + 'rnd=' + rnd);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
				if(response == "1"){
          try {
             popupLoad('/online-booking/portal/ajax/changeBillingCustomer?message=Customer+added+successfully.');
          } catch(e){
          }
				} else {
					popupLoad(failUrl + '&message=' + getMessage(response));
				}
			}	
		}
		http.send(null);
	} catch (e){
	}
}

/*
    Loads page for creating a new guest
*/
function createNewGuest(){
  popupLoad('/online-booking/portal/ajax/createGuest');
  popupSetTitle('add guest - create new');
}


function createGuestAdd(formObj){
  var url = formParamsToUri(formObj,'/online-booking/portal/ajax/createGuestAdd');
  var failUrl = formParamsToUri(formObj,'/online-booking/portal/ajax/createGuest');
  
  popupLoading();
  var appendChar = '&';
  if(url.indexOf('?') == -1){
    appendChar = '?';
  }
  var rnd = Math.random();
	var http = getXmlHttpObject();
	try{
		http.open('GET',url + appendChar + 'rnd=' + rnd);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
				if(response == "1"){
          try {
             popupLoad('/online-booking/portal/ajax/addGuest?message=Guest+added+successfully.');
          } catch(e){
          }
				} else {
					popupLoad(failUrl + '&message=' + getMessage(response));
				}
			}	
		}
		http.send(null);
	} catch (e){
	}
}

function getMessage(response){
  var sPos = response.indexOf('<!--MESSAGE-->');
  var ePos = response.indexOf('<!--/MESSAGE-->');
  if(sPos == -1 || ePos == -1){
    return '';
  }
  sPos = sPos + 14;
  return response.substring(sPos,ePos);
}

/*
  Displays edit customer popup
*/
function editCustomer(customerId,customerType){ 
  showPopup(350,250,'/online-booking/portal/ajax/editCustomer?customer='+customerId+'&customerType='+customerType,'edit customer');
}

function editCustomerSave(formObj,customerType){
  var url = formParamsToUri(formObj,'/online-booking/portal/ajax/editCustomerSave');
  var failUrl = formParamsToUri(formObj,'/online-booking/portal/ajax/editCustomer');
  
  popupLoading();
  var appendChar = '&';
  if(url.indexOf('?') == -1){
    appendChar = '?';
  }
  var rnd = Math.random();
	var http = getXmlHttpObject();
	try{
		http.open('GET',url + appendChar + 'rnd=' + rnd);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
				if(response == "1"){
          try {
             switch(customerType){
               case 'Guest':
                 popupLoad('/online-booking/portal/ajax/addGuest?message=Guest+has+been+amended.'); break;
               case 'Billing Customer':
                 popupLoad('/online-booking/portal/ajax/changeBillingCustomer?message=Customer+has+been+amended.'); break;
             }
          } catch(e){
          }
				} else {
					popupLoad(failUrl + '&message=' + getMessage(response));
				}
			}	
		}
		http.send(null);
	} catch (e){
	}
}

/*
    Adds a guest to the reservation (both on the page and the session)
    @param guestId The id of the guest to add
    @param guestName The name of the guest to add
*/
function selectGuest(guestId,guestName){
  // Checks if guest already exists for reservation
  if(document.getElementById('guest_' + guestId)){
    closePopup();
    return;
  }
  
	var rnd = Math.random();
	var http = getXmlHttpObject();
	try{
		http.open('GET','/online-booking/portal/ajax/selectGuest?guest=' + guestId + '&rnd=' + rnd);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
				if(response == "1"){
          try {
            var newGuest = document.createElement('div');
            newGuest.id = 'guest_' + guestId;
            newGuest.innerHTML = guestName + '&nbsp;&nbsp;[<a class="jsLink" onclick="removeGuest(\'' + guestId + '\');">remove</a>]<br />';
            document.getElementById('guests').appendChild(newGuest);
          } catch(e){
          }
				} else {
				}
			}	
		}
		http.send(null);
	} catch (e){
	}
  
  closePopup();
}

/*
    Removes a guest from the reservation (both on the page and the session)
    @param guestId The id of the guest to remove
*/
function removeGuest(guestId){
  var tmp = document.getElementById('guest_' + guestId).innerHTML;
  document.getElementById('guest_' + guestId).innerHTML = '<strong>Removing...</strong>';
	var rnd = Math.random();
	var http = getXmlHttpObject();
	try{
		http.open('GET','/online-booking/portal/ajax/removeGuest?guest=' + guestId + '&rnd=' + rnd);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
				if(response == "1"){
          try {
            //alert('Guest removed.');
            document.getElementById('guests').removeChild(document.getElementById('guest_' + guestId));
          } catch(e){
            alert("There was a problem removing the guest");
            document.getElementById('guest_' + guestId).innerHTML = tmp;
          }
				} else {
					alert('There was a problem removing the guest.');	
          document.getElementById('guest_' + guestId).innerHTML = tmp;
				}
			}	
		}
		http.send(null);
	} catch (e){
		alert("There was a problem removing the guest.");
    document.getElementById('guest_' + guestId).innerHTML = tmp;
	}
}


/*
    Search check-outs
*/
function searchCheckOuts(days){
  try{document.getElementById('checkOutsList').innerHTML = loadingDiv();}catch(e){}
	var rnd = Math.random();
	var http = getXmlHttpObject();
  var url = '/online-booking/portal/ajax/checkOuts?days='+days+'&rnd='+rnd;
	try{
		http.open('GET',url);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
        try {
          document.getElementById('checkOutsList').innerHTML = response
        } catch(e){;
          //alert('error');
        }
			}	
		}
		http.send(null);
	} catch (e){
    //alert('error');
	}
}
/*
    Search check-ins
*/
function searchCheckIns(days){
  try{document.getElementById('checkInsList').innerHTML = loadingDiv();}catch(e){}
	var rnd = Math.random();
	var http = getXmlHttpObject();
  var url = '/online-booking/portal/ajax/checkIns?days='+days+'&rnd='+rnd;
	try{
		http.open('GET',url);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
        try {
          document.getElementById('checkInsList').innerHTML = response
        } catch(e){;
          //alert('error');
        }
			}	
		}
		http.send(null);
	} catch (e){
    //alert('error');
	}
}
/*
    Search bookings
*/
function searchBookings(formObj){
  try{document.getElementById('bookingsList').innerHTML = loadingDiv();}catch(e){}
	var rnd = Math.random();
	var http = getXmlHttpObject();
  var url = formParamsToUri(formObj,'/online-booking/portal/ajax/bookings?rnd='+rnd);
	try{
		http.open('GET',url);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
        try {
          document.getElementById('bookingsList').innerHTML = response;
          return;
        } catch(e){;
          return;
        }
			} else if((http.readyState == 4) && (http.state != 200)){
        document.getElementById('bookingsList').innerHTML = '<p>There was a problem with your search, please check your criteria and try again.<p>';
      }      
		}
		http.send(null);
	} catch (e){
    return;
	}
}
/*
    Search invoices
*/
function searchInvoices(formObj){
  try{document.getElementById('invoicesList').innerHTML = loadingDiv();}catch(e){}
	var rnd = Math.random();
	var http = getXmlHttpObject();
  var url = formParamsToUri(formObj,'/online-booking/portal/ajax/invoices?rnd='+rnd);
	try{
		http.open('GET',url);
		//http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = function(){
			if((http.readyState == 4) && (http.status == 200)){
				var response = http.responseText;
        try {
          document.getElementById('invoicesList').innerHTML = response
        } catch(e){;
          alert('error');
        }
			}	else if((http.readyState == 4) && (http.state != 200)){
        document.getElementById('invoicesList').innerHTML = '<p>There was a problem with your search, please check your criteria and try again.<p>';
      } 
		}
		http.send(null);
	} catch (e){
    alert('error');
	}
}


function loadingDiv(){
  return "<div style=\"text-align:center; margin-top:20px; margin-bottom:20px;\"><img src=\"/online-booking/loading.gif\"></div>";
}


/* 
	Basic AJAX function that will create an instance of the
	XML HTTP (or browser equivalent) object and return it.
	
	@return XML HTTP object (specific to current browser)
*/
function getXmlHttpObject(){
	var xmlHttp = null;
	try {    
		// Firefox 1.5, Firefox 2, Internet Explorer 7, Konqueror, Opera 8, Opera 9, Safari 
		xmlHttp = new XMLHttpRequest();
	} catch (e) {     
		try {
			// Internet Explorer 5, Internet Explorer 6
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {    
				// Internet Explorer Fallback
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {      
				return false;        
			}
		}
	}
	
	return xmlHttp;
}

/*  converts values of a given form object to a URI string for GET by AJAX (etc)
      @author  Jamie (LMM) and Joseph (LMM too)
      @date  2008/03/07
      @param  formObj  A HTML form object to convert
      @param  uri  The current URI to append the form parameters to (can already contain parameters, or not)
      @return  string  The full URI (built from supplied URI + form parameters) ready for querying
*/
function formParamsToUri(formObj,uri){
  var returnValues = Array();
  var returnNames = Array();
  var index = 0;
  var elementInputs;  
  uri = '' + uri;
  
  // Add all <input> object values
  elementInputs = formObj.getElementsByTagName('input');
  for(var i = 0; i < elementInputs.length; i++){
    if(elementInputs[i].name.length < 1){ continue; } // checks the object has name
    if(elementInputs[i].type == 'checkbox' || elementInputs[i].type == 'radio'){
      if(elementInputs[i].checked != true){ continue; } // only include the checked radio/checkbox inputs
    }
    returnValues[index] = elementInputs[i].value; // add values
    returnNames[index] = elementInputs[i].name;
    index++;
  }
  
  // Add all <textarea> object values
  elementInputs = formObj.getElementsByTagName('textarea');
  for(var i = 0; i < elementInputs.length; i++){
    if(elementInputs[i].name.length < 1){ continue; } // checks the object has name
    returnValues[index] = elementInputs[i].value; // add values
    returnNames[index] = elementInputs[i].name;
    index++;
  }
  
  // Add all the <select>  object values
  elementInputs = formObj.getElementsByTagName('select');
  for(var i = 0; i < elementInputs.length; i++){
    if(elementInputs[i].name.length < 1){ continue; } // checks the object has name
    for(var j = 0; j < elementInputs[i].options.length; j++){ // loop through all select options (required for multiple select objects)
      if(elementInputs[i].options[j].selected){ // check if option is selected
        returnValues[index] = elementInputs[i].options[j].value; // add selected values
        returnNames[index] = elementInputs[i].name;
        index++;
      }
    }
  }
  
  // Build the full URI string
  var firstItem = true;
  for(var key =0; key< returnValues.length;key++){
    // check if the given URI already contains some parameters
    if(firstItem == false){ uri += '&'; } else if(uri.indexOf('?') == -1){ uri += '?'; firstItem = false; } else { uri += '&'; firstItem = false; }
    // replace problematic ASCII characters
    returnValues[key] = returnValues[key].replace('%','%25'); // MUST be first (% character replace)
    returnValues[key] = returnValues[key].replace('?','%3F');
    returnValues[key] = returnValues[key].replace(' ','%20');
    returnValues[key] = returnValues[key].replace('&','%26');
    returnValues[key] = returnValues[key].replace('=','%3D');
    returnValues[key] = returnValues[key].replace(':','%3A');
    // Append values
    uri += returnNames[key] + '=' + returnValues[key];
  }
  
  // Return the full URI
  return uri;        
}

function getWindowHeight(){
  var viewportwidth;
  var viewportheight;
   
  // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
   
  if (typeof window.innerWidth != 'undefined')
  {
        viewportwidth = window.innerWidth,
        viewportheight = window.innerHeight
  }
   
  // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

  else if (typeof document.documentElement != 'undefined'
       && typeof document.documentElement.clientWidth !=
       'undefined' && document.documentElement.clientWidth != 0)
  {
         viewportwidth = document.documentElement.clientWidth,
         viewportheight = document.documentElement.clientHeight
  }
   
   // older versions of IE
   
  else
  {
         viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
         viewportheight = document.getElementsByTagName('body')[0].clientHeight
  }
  return viewportheight;
}
