// Javascript functions for Option Bar

// Ajax script to establish connection with server ------------------------------------------------------------------------->

<!--
function ajaxObject(url) {           // This is the object constructor   
	var that=this;                        // A workaround for some javascript idiosyncrocies   
	this.updating = false;                // Set to true if this object is already working on a request  
	this.callback = function () {}        // A post-processing call -- a stub you overwrite.   
	this.update = function(passData) {    // Initiates the server call.      
		if (that.updating==true) { return false; }    // Abort if we're already processing a call.      
	that.updating=true;              // Set the updating flag.      
	var AJAX = null;                  // Initialize the AJAX variable.      
	if (window.XMLHttpRequest) {      // Are we working with mozilla?         
		AJAX=new XMLHttpRequest();        //  Yes -- this is mozilla.      
	} else {                          // Not Mozilla, must be IE         
		AJAX=new ActiveXObject("Microsoft.XMLHTTP");                //  Wheee, ActiveX, how do we format c: again?     
	}                                                              // End setup Ajax.      
	if (AJAX==null) {                                              // If we couldn't initialize Ajax...         
	return false;                                                // Return false (WARNING - SAME AS ALREADY PROCESSING!)      
	} else {         
	AJAX.onreadystatechange = function() {                      // When the browser has the request info..            
		if (AJAX.readyState==4) {                                //   see if the complete flag is set.               
		that.updating=false;                                  //   Set the updating flag to false so we can do a new request
		that.callback(AJAX.responseText,AJAX.status);         //   Pass respons and status to callback.               
		delete AJAX;                                          //   delete the AJAX object since it's done.           
		}                                                        // End Ajax readystate check.         
	}                                                           // End create post-process fucntion block.         
	var timestamp = new Date();                                 // Get a new date (this will make the url unique)         
	var uri=urlCall+'?'+passData+'&timestamp='+(timestamp*1);   // Append date to url (so the browser doesn't cache the call)  
    AJAX.open("GET", uri, true);                                // Open the url this object was set-up with.         
	AJAX.send(null);                                            // Send the request.         
	return true;                                                // Everything went a-ok.      
	}                                                           // End Ajax setup aok if/else block                   
	}         														// This area set up on constructor calls.   
var urlCall = url;                                                // Remember the url associated with this object.
}  																// End AjaxObject

// End of Ajax Object Build Script
// ------------------------------------------------------------------------------------------------------------------------------->


// Ajax object to show number of cruises a search will produce ------------------------------------------------------------------->

var cruiseFeed = new ajaxObject("http://www.bawaycruises.com/ajax/availableCruises.php"); 	   // Create object
cruiseFeed.callback = function (responseText, responseStatus) {       // What to do with the data   
displayCruiseFeed(responseText, responseStatus);                            // Your function here
} 	

function displayCruiseFeed(responseText, responseStatus) {   
	if (responseStatus==200) { 
		var numCruisesFound = responseText; // Get the response text     
		document.getElementById("foundCruises").innerHTML="This search would return <span class='big'>"+numCruisesFound+"</span> Cruises";
	} else {      
		document.getElementById("foundCruises").innerHTML='Failed to get the feed you requested';   
	}
}	// End in-line function

function getCruiseInfo() {                                
var searchDate = document.cruiseSearch.dataArea0.value;
var retDate = document.cruiseSearch.dataArea1.value;
var searchDuration = document.cruiseSearch.cruiseDuration.value;
var searchBudget = document.cruiseSearch.budget.value;
var searchArea = document.cruiseSearch.cruiseArea.value;
var searchType = document.cruiseSearch.cruiseType.value;
var searchLine = document.cruiseSearch.cruiseLine.value;
var searchShip = document.cruiseSearch.cruiseShip.value;
	// Encode the Ampersands found in cruise Areas otherwise it won't return a value
	function encodedData(strInput) {
		return strInput.replace(/&/g, '_ampersand');
	}
searchArea = encodedData(searchArea);
cruiseFeed.update("searchDate="+searchDate+"&retDate="+retDate+"&searchDuration="+searchDuration+"&searchBudget="+searchBudget+"&searchArea="+searchArea+"&searchType="+searchType+"&searchLine="+searchLine+"&searchShip="+searchShip); 
}

// End of ajax to show number of cruises a search will produce
// ------------------------------------------------------------------------------------------------------------------------------->

// Ajax object to dynamically change ships for those of selected cruise line ----------------------------------------------------->


var shipFeed = new ajaxObject("http://www.bawaycruises.com/ajax/shipListings.php"); 	   			// Create object
shipFeed.callback = function (responseText, responseStatus) {       	// What to do with the data   
displayShipFeed(responseText, responseStatus);                            // Your function here
} 	

function displayShipFeed(responseText, responseStatus) {   
	if (responseStatus==200) { 
			function addOption(selectbox,text,value )
				{
				var optn = document.createElement("OPTION");
				optn.text = text;
				optn.value = value;
				selectbox.options.add(optn);
				}
				
			// Remove existing options from Ship List
			document.cruiseSearch.cruiseShip.options.length=0;
			var shipNames = new Array();
			shipNames = responseText.split("&&");
			for (i=0; i<shipNames.length; i++) {
			if (shipNames[i] != "")
			addOption(document.cruiseSearch.cruiseShip, shipNames[i], shipNames[i]);
			getCruiseInfo();
			} // end of for
		} else {      
		alert("Could not update shiplines in form!<br>Please notify webmaster.");
		}
}	// End in-line function

function getShipLine(CL) {
var cruiseLine = CL.value;
shipFeed.update("cruiseLine="+cruiseLine);
}

// End of ajax to dynamically populate ship dropdowns
// ------------------------------------------------------------------------------------------------------------------------------->

// Ajax object to return itinerary details for booking form ----------------------------------------------------->


var itinFeed = new ajaxObject("../ajax/itineraryListing.php"); 	   			// Create object
itinFeed.callback = function (responseText, responseStatus) {       	// What to do with the data   
displayItinFeed(responseText, responseStatus);                            // Your function here
} 	

function displayItinFeed(responseText, responseStatus) {   
	if (responseStatus==200) { 
		var results = new Array(); // Get the response text - there is more than 1 item this time so we need to put into an array
		results = responseText.split("abc");
		document.getElementById("cruiseDetails").innerHTML=results[0];	
		document.getElementById("cruiseNumDisplay").innerHTML=results[1];
		document.getElementById("thisCruiseID").value=results[2];
		document.getElementById("thisCruiseItin").value=results[3];
		document.getElementById("dataArea0").value=results[4];
		document.getElementById("dataArea1").value=results[5];
		} else {      
		alert("Could not return Cruise Itinerary! <br>Please notify webmaster.");
		}
}	// End in-line function

function getItinerary(itin, cruiseNum) {
	if (cruiseNum != "") {
		var cruiseNum = cruiseNum;
	} else {
	var cruiseNum = itin.elements["cruiseNumber"].value;
	}
if (itinFeed.update("cruiseNum="+cruiseNum)) return false;
}

// End of ajax to return itinerary details for Booking Form
// ------------------------------------------------------------------------------------------------------------------------------->

// Ajax object to return newsletter signup confirmation ----------------------------------------------------->


var newsFeed = new ajaxObject("http://www.bawaycruises.com/ajax/newsletterConfirm.php"); 	   			// Create object
newsFeed.callback = function (responseText, responseStatus) {       	// What to do with the data   
displayNewsFeed(responseText, responseStatus);                            // Your function here
} 	

function displayNewsFeed(responseText, responseStatus) {   
	if (responseStatus==200) { 
		var results = new Array(); // Get the response text - there is more than 1 item this time so we need to put into an array
		results = responseText.split("abc");
		if (results[0] == "TRUE") {
				document.getElementById("newsletter").innerHTML="<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td width='2%'>&nbsp;</td><td width='98%' class='cruiseOffers'>Newsletter SignUp Complete<br /><br />Thank you "+results[1]+" your details have been added to receive our newsletter. You will receive a confirmation email shortly.</td></tr><tr></table>";
			} else {
			document.getElementById("newsletter").innerHTML="<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td width='2%'>&nbsp;</td><td width='98%' class='cruiseOffers'>Newsletter SignUp Failure! <br /><br />There was a problem with the details you supplied us. Please refresh the page and enter them again insuring your email address is correct.</td></tr><tr></table>";	
			}
		} else {      
		alert("Could not complete Newsletter SignUp! <br>Please notify webmaster.");
		}
}	// End in-line function

function checkNews() {
	// Sort out the variables from the form
	var fName = document.forms["newsletterconfirm"].elements["newsFName"].value;
	var lName = document.forms["newsletterconfirm"].elements["newsLName"].value;
	var email = document.forms["newsletterconfirm"].elements["newsEmail"].value;
	var confirmEmail = document.forms["newsletterconfirm"].elements["confirmEmail"].value;
newsFeed.update("fName="+fName+"&lName="+lName+"&email="+email+"&confirmEmail="+confirmEmail);
}

// End of ajax to return newsletterSignUp Confirmation
// ------------------------------------------------------------------------------------------------------------------------------->


//-->

//Hides and Shows the option bar and it's various options screens ---------------------------------------------------------------->

function checkLineStatus() {
if (document.cruiseSearch.cruiseLine.value == "Any") {
alert("Please select your cruise line first");
document.cruiseSearch.cruiseShip.selectedIndex = 0;
document.cruiseSearch.cruiseShip.options[0].selected = true;
return;
}
getCruiseInfo();
}

function hideDiv() { 
if (document.getElementById) { // DOM3 = IE5, NS6  
document.getElementById('searchOptions').style.display = 'none';
document.getElementById('newsletter').style.display = 'none'; 
document.getElementById('basicSearch').style.display = 'none'; 
} 
else { 
if (document.layers) { // Netscape 4 
document.searchOptions.display = 'none';
document.newsletter.display = 'none';
document.basicSearch.display = 'none';
} 
else { // IE 4 
document.all.searchOptions.style.display = 'none'; 
document.all.newsletter.style.display = 'none';
document.all.basicSearch.style.display = 'none'; 

} 
}  
}
function showDiv() { 
if (document.getElementById) { // DOM3 = IE5, NS6 
document.getElementById('cruiseDetails').style.display = 'block';
document.getElementById('cruiseItin').style.display = 'none'; 
document.getElementById('cruisePrices').style.display = 'none'; 
document.getElementById('cruiseShip').style.display = 'none'; 
} 
else { 
if (document.layers) { // Netscape 4 
document.cruiseDetails.display = 'block'; 
document.cruiseItin.display = 'none';
document.cruisePrices.display = 'none';
document.cruiseShip.display = 'none'; 
} 
else { // IE 4 
document.all.cruiseDetails.style.display = 'block';
document.all.cruiseItin.style.display = 'none';
document.all.cruisePrices.style.display = 'none';
document.all.cruiseShip.style.display = 'none';
} 
} 
} 

function changeDiv(myDiv) { 
var hide1 = '';
var hide2 = '';
var hide3 = '';
// Work out which div to show and which ones to hide
if (myDiv == 'cruiseDetails') {
	hide1 = 'cruiseItin';
	hide2 = 'cruisePrices';
	hide3 = 'cruiseShip';
} else if (myDiv == 'cruiseItin') {
	hide1 = 'cruiseDetails';
	hide2 = 'cruisePrices';
	hide3 = 'cruiseShip';
} else if (myDiv == 'cruisePrices') {
	hide1 = 'cruiseDetails';
	hide2 = 'cruiseItin';
	hide3 = 'cruiseShip';
} else {
	hide1 = 'cruiseDetails';
	hide2 = 'cruiseItin';
	hide3 = 'cruisePrices';
}

if (document.getElementById) { // DOM3 = IE5, NS6 
document.getElementById(myDiv).style.display = 'block';
document.getElementById(hide1).style.display = 'none';
document.getElementById(hide2).style.display = 'none';
document.getElementById(hide3).style.display = 'none';
} 
else { 
if (document.layers) { // Netscape 4 
alert("Your browser appears to be too old to support this site"); 
} 
else { // IE 4 
alert("Your browser appears to be too old to support this site"); 
} 
} 
}

//End of Hide and show options bar
//-------------------------------------------------------------------------------------------------------------------------->

//Newsletter SignUp -------------------------------------------------------------------------------------------------------->

function formCheck(formobj){
	//1) Enter name of mandatory fields
	var fieldRequired = Array("newsFName", "newsLName", "newsEmail");
	//2) Enter field description to appear in the dialog box
	var fieldDescription = Array("First Name", "Last Name", "Email Address");
	//3) Enter dialog message
	var alertMsg = "The following fields were not completed:\n";
	
	var l_Msg = alertMsg.length;
	
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "select-multiple":
				if (obj.selectedIndex == -1){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "text":
			case "textarea":
				if (obj.value == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			default:
				if (obj.value == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
			}
		}
	}
	
	var str=formobj.elements["newsEmail"].value;
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str)) {
		if (alertMsg.length == l_Msg){
			return true;
		}else{
			alert(alertMsg);
			return false;
		}
	} else {
	alert("Please input a valid email address!");
	}
	return false;
}
function confirmEmail() {
	
	var v0 = document.newsletter.newsFName.value;
	var v1 = document.newsletter.newsLName.value;
	var v2 = document.newsletter.newsEmail.value;
	document.getElementById("newsletter").innerHTML="<form name='newsletterconfirm' method='post' action='javascript:checkNews()' style='margin-bottom:0px'><table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td width='2%'>&nbsp;</td><td width='98%' class='cruiseOffers'>Please confirm your email address:</td></tr><tr><td width='2%'><input name='newsFName' type='hidden' id='newsFName' value='"+v0+"' /><input name='newsLName' type='hidden' id='newsLName' value='"+v1+"' /><input name='newsEmail' type='hidden' id='newsEmail' value='"+v2+"' /></td><td width='98%' class='cruiseOffers'><input name='confirmEmail' type='text' class='cruiseOffers' id='confirmEmail' /></td></tr><tr><td>&nbsp;</td><td class='cruiseOffers'><input name='newsconfirm' type='image' value='submit' src='http://www.bawaycruises.com/images/signUpOff.gif' alt='Newsletter Sign Up' id='newsconfirm' onmouseover='this.src=\"http://www.bawaycruises.com/images/signUpOn.gif\"' onmouseout='this.src=\"http://www.bawaycruises.com/images/signUpOff.gif\"' /></td></tr></table></form>";
} 

function passengerForms() {
	
	var counter = 0;

function moreFields() {
	counter++;
	var newFields = document.getElementById('passengers').cloneNode(true);
	newFields.id = '';
	newFields.style.display = 'block';
	var newField = newFields.childNodes;
	for (var i=0;i<newField.length;i++) {
		var theName = newField[i].name
		alert(theName);
		if (theName)
			newField[i].setAttribute('name',theName + counter);
	}
	var insertHere = document.getElementById('passengerwrite');
	insertHere.parentNode.insertBefore(newFields,insertHere);
}
moreFields();		
}


<!--
function MM_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.id; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
} }
//-->

