
function init() {

	if($('date1')) {
				var d1 = $('date1');
		d1.DateChooser = new DateChooser();

		// Check if the browser has fully loaded the DateChooser object, and supports it.
		if (!d1.DateChooser.display) {
			return false;
		}

		d1.DateChooser.setCloseTime(0);
		d1.DateChooser.setXOffset(10);
		d1.DateChooser.setYOffset(20);
		d1.DateChooser.setUpdateFunction(Functiond1);
		$('datein1').onclick = d1.DateChooser.display;
	}
	
	if($('date2')) {
		var d2 = $('date2');
		d2.DateChooser = new DateChooser();

		// Check if the browser has fully loaded the DateChooser object, and supports it.
		if (!d2.DateChooser.display) {
			return false;
		}
	
		d2.DateChooser.setCloseTime(0);
		d2.DateChooser.setXOffset(10);
		d2.DateChooser.setYOffset(20);
		d2.DateChooser.setUpdateFunction(Functiond2);
		$('datein2').onclick = d2.DateChooser.display;
	}
}

function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; return emailPattern.test(elementValue); }

function isDate(datee) {
	
	temparray = datee.split("-");
		
	if(temparray.length != 3) {
		
		return false;
		
	} else {
		
		tempdate = new Date();
		year = tempdate.getFullYear();
		
		
		//year validation
		if(temparray[0] < year || temparray[0] >= (year+5)) {
			return false;
		}
		
		//month validation
		if(temparray[1].length != 2 || temparray[1] < 01 || temparray[1] > 12) {
			return false;
		}
		
		//date validation
		if(temparray[2].length != 2 || temparray[2] < 01 || temparray[2] > 31) {
			return false;
		}
		
		return true;
		
	}
}

function Functiond1(objDate) {
	// objDate is a plain old Date object, with the getPHPDate() property added on.
	$('datein1').value = objDate.getPHPDate('Y-m-d');
	return true;
}

function Functiond2(objDate) {
	// objDate is a plain old Date object, with the getPHPDate() property added on.
	$('datein2').value = objDate.getPHPDate('Y-m-d');
	return true;
}

searchOptions = 0;

function showSearchOptions() {
	if(searchOptions == 0) {
		document.getElementById('searchOptions').style.display = 'block';
		searchOptions = 1;
	} else if (searchOptions == 1) {
		document.getElementById('searchOptions').style.display = 'none';
		searchOptions = 0;
	}
}

//test for numeric value
function IsNumeric(strString) {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++) {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1) {
         blnResult = false;
         }
      }
   return blnResult;
}

// bookings

//IE sucks big time!
if (navigator.appName == "Microsoft Internet Explorer") {

	var displayType = 'block';
} else {

	var displayType = 'table-row';
} 

function showBook(id, tourID, operatorName, type, operatorID) {

	//type knows if the function is being called to enter new bookings or to change the date on an existing one
	if(type == null) {
		type = "new";
	}
	
	if(type == 'new') {
		//we need the current startdate only when we're changing date on an existing booking, so here make it an empty string
		bookingID = "";
	} else if(type == 'change') {
		bookingID = $('bookingID').value;
	}
	
	if($(id).style.display == 'none') {

	
		$(id).style.display = displayType;
				
				
		//if cell is empty, we will load the dates for this tour
		if($(id).cells[0].innerHTML.length <= 6 && $(id).className == "tableRow1") {
			$(id).cells[0].style.background = '#FFFFFF url(/images/bigloader_orange_white.gif)';
			$(id).cells[0].style.backgroundRepeat = 'no-repeat';
			$(id).cells[0].style.backgroundPosition = 'center center'
		} else if($(id).cells[0].innerHTML.length <= 6 && $(id).className == "tableRow2") {
			$(id).cells[0].style.background = '#F2FAFC url(/images/bigloader_orange_blue.gif)';
			$(id).cells[0].style.backgroundRepeat = 'no-repeat';
			$(id).cells[0].style.backgroundPosition = 'center center'
		}
		
		if($(id).cells[0].innerHTML.length <= 6) {
			//appearantly the cell is empty, so let's fill it with some data		
			
			new Ajax('/date/getDates', {
				method: 'post',
				onComplete: function() {
				
					//disable loaders
					if($(id).className == 'tableRow1') {
						$(id).cells[0].style.background = '#FFFFFF';
					} else {
						$(id).cells[0].style.background = '#F2FAFC';
					}
		
					response = eval('(' + this.response.text + ')');
					
					if(response.first == 0) {
					
						if(type == 'new') {//for entering new bookings
						//no dates found
						
							newDiv = document.createElement("div");
							newDiv.className = 'noDatesMessage';
							newDiv.style.display = 'block';
							if(response.second == 'agent') {
								newDiv.innerHTML = "Sorry, it seems there are no available dates for this service. Please <a href=\"/messages/newm/"+operatorID+"\">contact</a> <b>"+operatorName+"</b> for more details.";
							} else if(response.second == 'operator') {
								newDiv.innerHTML = "There are no dates in the system for this itinerary. Before entering bookings, please enter one or more dates for this itinerary.";
							}
						
							$(id).cells[0].style.textAlign = 'center'
							$(id).cells[0].appendChild(newDiv);
							
						} else {//for changing a date on an existing booking
						
							newDiv = document.createElement("div");
							newDiv.className = 'noDatesMessage';
							newDiv.style.display = 'block';
							
							if(response.sec == 0) {
							
								newDiv.innerHTML = "Sorry, start dates can <b>NOT</b> be altered within four weeks before the current start date. If you still want to alter the start date, please <a href=\"/messages/newm/"+operatorID+"\">contact</a> <b>"+operatorName+"</b>.";
							
							} else if(response.sec == 1) {
								
								newDiv.innerHTML = "Sorry, suppliers are only allowed to alter start dates within four weeks before arrival. Until then, only agents are allowed to alter start dates.";
							}
						
							$(id).cells[0].style.textAlign = 'center'
							$(id).cells[0].appendChild(newDiv);
							
							//$('hideLink').innerHTML = "hide message";
						}
						
					} else {
						
						//since we already have first date, we can now build the days in the calendar
						//at first all days should be days off (thats the way nogray calendar wants it)

						ndate = new Date(response.first.y, response.first.m, response.first.d);
						
						d = ndate.getDate();
						m = ndate.getMonth();
						y = ndate.getFullYear();
						
						ndate_plus_1year = new Date();
						ndate_plus_1year.setDate(ndate.getDate()+365);
						
						//need to reset all the global arrays
						days_off.length = 0;
						startdates.length = 0;
						clickevents.length = 0;
						bookings.length = 0;
						datesPlusDetails.length = 0;
																								
						for(x=1; x<=366; x++) {
							
							days_off[x-1] = {date: ndate.getDate(), month: ndate.getMonth(), year: ndate.getFullYear()}
							
							ndate.setDate(ndate.getDate()+1);
						}
												
						//now we do the good dates, plus an array with click events: for every td with a startdate
						for(x=0; x<response.dates.length; x++) {
							
							newDate = new Date(response.dates[x].y, response.dates[x].m, response.dates[x].d);
							
							startdates[x] = {date: newDate.getDate(), month: newDate.getMonth(), year: newDate.getFullYear()}
							
							clickevents[response.dates[x].m+1+"-"+response.dates[x].d+"-"+response.dates[x].y] = {click: function(td, date_str){
									//alert(datesPlusDetails[td.id]['tourID'])
									
									if(typeof(CUSTOMIT) == 'number' && CUSTOMIT == 1) {
									
										if(CUSTOMIT_dates_its[datesPlusDetails[td.id]['tourID']] == datesPlusDetails[td.id]['date']) {
											//already selected date has been clicked, we should remove it											
											for(var i in CUSTOM_dates_its) {
												
												if(CUSTOMIT_dates_its[i].tourID == datesPlusDetails[td.id]['tourID'] && CUSTOMIT_dates_its[i].date == datesPlusDetails[td.id]['date']) {
												
													delete CUSTOMIT_dates_its[i];
												
												}
											}
										
											
										} else {
										
											temp = new Object();
											temp.tourID = datesPlusDetails[td.id]['tourID'];
											temp.date = datesPlusDetails[td.id]['date'];
									
											CUSTOMIT_dates_its.push(temp);
																						
											//CUSTOMIT_dates_its[datesPlusDetails[td.id]['tourID']] = datesPlusDetails[td.id]['date'];
										
										}
									} else {
										
										if(type == 'change') {
										//if script is used for changing a start date, every time a date is clicked, we need to remove
										//present div's
																				
										divs = $$('div.noDatesMessage');
										
										for(x=0; x<divs.length;x++) {
																						
											$(id).cells[0].removeChild(divs[x]);
											
										}
										
										changeDateTo = datesPlusDetails[td.id]['date'];
									}
																		
									if(bookings[td.id]) {
										//same date was clicked again, remove booking
										
										delete bookings[td.id];
										
										//count the number of bookings for this date id
										tourID = datesPlusDetails[td.id]['tourID'];
										
										//counter for bookings for this tourID
										count = 0;
										
										for(var i in bookings) {
											//our date id is likely 18, 19 or 20 characters in length
											if(i.length == 18 || i.length == 19 || i.length == 20) {
												if(bookings[i]['tourID'] == tourID) {
													
													count++;
												}
											}
										}
																			
										if(count == 0) {
											//hide the star
											$('star'+datesPlusDetails[td.id]['tourID']).style.visibility = 'hidden';
											
											if($('confirm'+datesPlusDetails[td.id]['tourID'])) {
												
												$(id).cells[0].removeChild($('confirm'+datesPlusDetails[td.id]['tourID']));
											}
										}
										
										//remove that div saying how many places there are
										$(id).cells[0].removeChild($('seats'+td.id))
										
									} else {
									
										if(type == 'new') {//used by agent tours view to enter new bookings
										
										
											//booking is fresh, let's put in the booking array
											tempArr = new Object();
											tempArr['tourID'] = datesPlusDetails[td.id]['tourID'];
											tempArr['date'] = datesPlusDetails[td.id]['date'];
											tempArr['tr_con'] = id;
											tempArr['places'] = 1;
									
											bookings[td.id] = tempArr;
										
											if($('star'+datesPlusDetails[td.id]['tourID'])) {
												$('star'+datesPlusDetails[td.id]['tourID']).style.visibility = 'visible';
											}
										
											newDiv = document.createElement("div");
											newDiv.style.padding = '0px 0px 15px 0px';
											newDiv.style.textAlign = 'left';
											newDiv.style.width = '95%';
											newDiv.style.margin = "0px auto 10px auto"
											newDiv.className = 'noDatesMessage';
											newDiv.id = 'seats'+td.id;
										
											newDiv_close = document.createElement("div");
											newDiv_close.style.width = '100%';
											newDiv_close.style.height = '15px';
											newDiv_close.style.textAlign = 'right';
										
											newImage = document.createElement('img');
											newImage.src = "/images/close.gif";
											newImage.style.cursor = "pointer";
											newImage.onclick = function() {
												
												if(bookings[td.id].bookings) {
													checkBooking(td.id);
												}
												closeDate(td.id, id);
											}
											
											
										
											newDiv_close.appendChild(newImage);
										
											newDiv.appendChild(newDiv_close);
										
											newSpan = document.createElement("span");
											newSpan.innerHTML = "&nbsp;&nbsp;<b>"+datesPlusDetails[td.id]['date']+"</b>: <b>"+datesPlusDetails[td.id]['places']+"</b> seats available.&nbsp;How many seats would you like to book?&nbsp;&nbsp;&nbsp;";
										
											newDiv.appendChild(newSpan);
									 
											newInput = document.createElement("input");
											newInput.type = 'text';
											newInput.id = "seatsfor_"+td.id;
											newInput.value = "0";
											newInput.style.width = '30px';
											newInput.onfocus = function() {
											
												temp = this.value;
											
												if(this.value != 0) {
													alert('Changing this number will reset all seat data for this date!')
												}
											}
										
											newInput.onchange = function(){
											
												//$('seatslink'+td.id).innerHTML = "Enter customer details"
											}
										
											newInput.onkeyup = function(){
												if(this.value != "" && this.value != 0) {
													$('seatslink'+td.id).style.display = 'inline'
												} else {
													$('seatslink'+td.id).style.display = 'none'
												}
											
												if(temp != 0 && temp != this.value) {
													$('seatslink'+td.id).innerHTML = "Enter customer details";
												}
											}
																				
											newDiv.appendChild(newInput);
										
											newSpan = document.createElement("span");
											newSpan.innerHTML = " seats<br/>&nbsp;&nbsp;";
										
											newDiv.appendChild(newSpan);
										
											newLink = document.createElement("a");
											newLink.href = "javascript:doOverlay('"+td.id+"');"
											newLink.style.display = 'none';
											newLink.id = "seatslink"+td.id
											newLink.innerHTML = "Enter customer details";
										
											newDiv.appendChild(newLink);
										
											$(id).cells[0].appendChild(newDiv);
										
											//move the Confirm Bookings button to the bottom of the div
										
											if($('confirm'+datesPlusDetails[td.id]['tourID'])) {
												tempDiv = $('confirm'+datesPlusDetails[td.id]['tourID']);
											
												$(id).cells[0].removeChild($('confirm'+datesPlusDetails[td.id]['tourID']));
											
												$(id).cells[0].appendChild(tempDiv);
											}
											
										} else if(type == "change") {
										
											//used by agent booking view to change a start date											
											
											newDiv = document.createElement("div");
											newDiv.style.padding = '0px';
											newDiv.style.textAlign = 'left';
											newDiv.style.width = '95%';
											newDiv.style.margin = "0px auto 0px auto"
											newDiv.className = 'noDatesMessage';
											newDiv.id = 'seats'+td.id;
											
											
											newTable = document.createElement("table");
											
											newRow = newTable.insertRow(-1);
											
											cell1 = document.createElement("td");
											
											newSpan = document.createElement("span");
											newSpan.innerHTML = "<b>"+datesPlusDetails[td.id]['date']+"</b>: <b>"+datesPlusDetails[td.id]['places']+"</b> seats available. Change to this date?";
										
											cell1.appendChild(newSpan);
											newRow.appendChild(cell1)
											
											cell2 = document.createElement("td");
											cell2.style.textAlign = 'right';
											cell2.style.width = '175px'
											
											newButton = document.createElement('div');
											newButton.className = 'b';
											newButton.style.display = 'inline-block';
											newButton.style.marginLeft = '100px';
											newButton.style.marginTop = 'auto';
											newButton.style.marginBottom = 'auto'
											newButton.innerHTML = "change";
											newButton.onclick = function() {
												
												changeDate(td.id);
											}
											
											cell2.appendChild(newButton);
											newRow.appendChild(cell2);
											
											newDiv.appendChild(newTable);
											
											$(id).cells[0].appendChild(newDiv);
										}
									}
									}
									
								} //click: function(td, date_str)
							};
							
							//datesPlusDetails contains the dates plus tourID plus places
							tempArr = new Array();
							tempArr['tourID'] = tourID;
							tempArr['places'] = response.dates[x].places
							tempArr['date'] = response.dates[x].y+"-"+(response.dates[x].m+1)+"-"+response.dates[x].d;
							
							datesPlusDetails['cal'+id+'date-'+(response.dates[x].m+1)+"-"+response.dates[x].d+"-"+response.dates[x].y] = tempArr;
												
							//alert('cal'+id+'date-'+(response.dates[x].m+1)+"-"+response.dates[x].d+"-"+response.dates[x].y)
						}
						
						
						//create a div to hold the calendar
						newDiv = document.createElement("div");
						newDiv.id = "cal"+id;
						newDiv.className = 'calendarr'
						
						$(id).cells[0].appendChild(newDiv)
						
						if(type == 'new') {
							var ge_cal = new Calendar("cal"+id, null, {
									startDate:{date:d, month:m, year:y},
									datesOff:days_off,
									forceSelections:startdates,
									inputType:"none",
									idPrefix:'de_cal',
									visible: true,
									numMonths:1,
									endDate:{date:ndate_plus_1year.getDate(), month:ndate_plus_1year.getMonth(), year:ndate_plus_1year.getFullYear()},
									allowWeekendSelection:false,
									tdEvents:clickevents,
									multiSelection:true,
									idPrefix: 'cal'+id
							});
						} else {//we don't want multiSelection
							
							var ge_cal = new Calendar("cal"+id, null, {
									startDate:{date:d, month:m, year:y},
									datesOff:days_off,
									forceSelections:startdates,
									inputType:"none",
									idPrefix:'de_cal',
									visible: true,
									numMonths:1,
									endDate:{date:ndate_plus_1year.getDate(), month:ndate_plus_1year.getMonth(), year:ndate_plus_1year.getFullYear()},
									allowWeekendSelection:false,
									tdEvents:clickevents,
									idPrefix: 'cal'+id
							});
						
						}
							
						
						//we will display a personal details form for every program and ask how many reservations are needed
					}
					
				},
				data: {tourID: tourID, bookingID: bookingID}
			}).request();
		}
		
	} else {
		$(id).style.display = 'none';
	}
}
