//$Id: whereWhen.js,v 1.13 2009/12/02 14:00:40 clinton Exp $
/* Javascript functions for Where When page */

/* initialize variables */
var arrayVillageSelected    = new Array();
var arrayTimeSelected       = new Array();
var arrayTimePeriods        = new Array('1week', 'midweek', 'weekend', 'specialEvent');
var timePeriodNames         = new Array("Week", "Weekend", "Midweek", "Special");
var arrayVillageNames       = new Array("whinfellForest", "longleatForest", "sherwoodForest", "elvedenForest");
var warningsArray           = new Array();
var showPleaseSelect        = "no";

var villageNames           = new Array("Whinfell", "Elveden", "Sherwood", "Longleat");
var excludeDates = new Array("2009-12-181week", "2009-12-21midweek", "2009-12-25weekend", "2009-12-251week", "2009-12-28midweek", "2010-01-01weekend", "2010-01-011week", "2010-12-171week", "2010-12-20midweek", "2010-12-24weekend", "2010-12-241week", "2010-12-27midweek", "2010-12-31weekend", "2010-12-311week", "2011-04-291week");
// add event handler to call initializePage()
addEvent(window, 'load', initializePage);

// reset the warning messages
function warningsReset(warningType) {
  switch (warningType) {
	case "villages":
		for (var i = 0; i < villageNames.length; i++) {
			changeColor("villageWarning" + villageNames[i], "#000");
		}
		break;

	case "lengthStay":
		for (var i = 0; i < timePeriodNames.length; i++) {
			changeColor("lengthStayWarning" + timePeriodNames[i], "#000");
		}
		break;
      
	case "special":
		for (var i = 0; i < timePeriodNames.length; i++) {
			changeColor("lengthStayWarning" + timePeriodNames[i], "#000");
    }
    break;
    
	case "dates":
		hide("warningDatesText"); 
		break;
  }          
}    

function hideCalendar(calltype) {
	document.getElementById('popupCalendar').style.visibility= "hidden";
	if (calltype == "dates"){
		warningsReset("dates");
	}
}
    
function initializePage() {  
  // Change display to none for calendar icon and the standard month and date selects.
  // Also hide submit form image link and display standard submit button.
  if ($('arrDate') == null) return; // If no arrDate, then we are an error page.
  var arrDate = document.getElementById('arrDate').value;
  display('calendarIcon');
  hide('selectMonth');
  hide('selectDate');
  makeVisible('whereWhenFormImageSubmit');
  hide('whereWhenFormSubmit');
  resetCalendar();

  //document.whereWhenForm.reset();
  for (var i = 0; i < arrayVillageNames.length; i++) {
    villageSelected(arrayVillageNames[i]);    
  }

  var holidayPeriod = "1week";
  for (var i = 0; i < arrayTimePeriods.length; i++) {
    if ((document.getElementById(arrayTimePeriods[i]+'ID') != null) && (document.getElementById(arrayTimePeriods[i]+'ID').checked)) {
      timeSelected(arrayTimePeriods[i]+'ID');
      if (arrayTimePeriods[i] != 'specialEvent') adjustSelectMonth(thisMonth + 1, thisYear, 'yes');
      holidayPeriod = arrayTimePeriods[i];         
    }
  }
    
    
  if ((holidayPeriod != 'specialEvent') && (arrDate != "")) {
    var d = null;
    if (arrDate.substr(4,2) == "00") d = createDate(arrDate.substring(0,4)+"01");
    else d = createDate(arrDate);
    var selectedMonth = padToWidth((d.getMonth()+1), 2, '0', 'R') + " " + d.getFullYear();
    setDropDown(document.getElementById('dd_selectMonth'), selectedMonth);
    adjustSelectDate();
    if (arrDate.substr(4,2) != "00")
      setDropDown(document.getElementById('dd_selectDate'), arrDate.substr(4,2));
  }
}

/* change village div background when selected or deselected */
function villageSelected(item) {
  //showSelects();
  warningsReset('villages');
  if (document.getElementById(item).checked == false) {
    changeBg(item + "Div", "#fff");
  } else {
    changeBg(item + "Div", "#dde2a6");
  }
}


// hide selects. This is called when a special event is chosen from the special event select element
function hideSelects() {
  warningsReset('special');
  
  /* Change all radio input div backgrounds to white */
  for (var i = 0; i < 3; i++){ // Exept special events
		changeBg(arrayTimePeriods[i], "#fff");
	}
  
  hide('whenHeader');
  hide('arrivalDateSelects');
  // uncheck all radio inputs
  document.getElementById('1weekID').checked = false;
  document.getElementById('midweekID').checked = false;
  document.getElementById('weekendID').checked = false;
  

  // Clear select date and month values 
  document.getElementById('dd_selectDate').value = "";
  document.getElementById('dd_selectMonth').value = "";
  
  // select special events radio button
  document.getElementById('specialEventID').checked = true;
  document.getElementById('specialEvents_dd').options[0].text = 'Please Select';
}

function showSelects() {
  display('whenHeader');
  display('arrivalDateSelects');
  if (document.getElementById('specialEvents_dd') != null)
    document.getElementById('specialEvents_dd').options[0].text = '-';
  //document.getElementById('specialEvents_dd').options[0].selected = true;
}

function timeSelected(time) {
  warningsReset('lengthStay');
  // in case calendar is open, hide it so the correct possible arrival dates will be set
  hideCalendar();

  /* Change all radio input div backgrounds to white */
  for (var i = 0; i < 4; i++) {
    changeBg(arrayTimePeriods[i], "#fff");
  }
  // set background
  changeBg(time.substring(0, time.length -2), "#dde2a6");

  if (time == "1weekID") {
    showSelects();
    for (var i = 0; i < excludeDates.length; i++) {
      if (excludeDates[i].substr(10,5) == "1week") {
        excludeDate = excludeDates[i].substr(0,10);
        cal.addDisabledDates(excludeDate, excludeDate);
      }
    }
    cal.setDisabledWeekDays(0,2,3,4,6);
    display('calendarIcon');    
  } else if (time == "midweekID") {
    showSelects();
    for (var i = 0; i < excludeDates.length; i++) {
      if (excludeDates[i].substr(10,7) == "midweek") {
        excludeDate = excludeDates[i].substr(0,10);
        cal.addDisabledDates(excludeDate, excludeDate);
      }
    }
    cal.setDisabledWeekDays(0,2,3,4,5,6);
    display('calendarIcon');    
  } else if (time == "weekendID") {
    showSelects();  
    for (var i = 0; i < excludeDates.length; i++) {
      if (excludeDates[i].substr(10,7) == "weekend") {
        excludeDate = excludeDates[i].substr(0,10);
        cal.addDisabledDates(excludeDate, excludeDate);
      }
    }
    cal.setDisabledWeekDays(0,1,2,3,4,6);
    display('calendarIcon');        
  } else if (time == "specialEventID") {
    hideSelects(); 
  }
  adjustSelectDate(time);
}
    
// function to create the month drop down for bookings
function selectMonth(monthCount) {
	document.write("<select onchange=\"adjustSelectDate();\" onfocus=\"hideCalendar();\" name=\"dd_selectMonth\" id=\"dd_selectMonth\" class=\"dropDownWW\">");
	monthValue      = thisMonth;
  yearValue       = thisYear;

  if (monthCount == null) monthCount = 11;
  
  document.write("<option value=\"\">Select month</option>");
  // loop to create option values for the current month and the next 9 months
	for (var i = 1; i < monthCount; i++) {
    value = padToWidth(monthValue + 1, 2, '0', 'R') + " " + yearValue;
        
    // write the option value
		document.write("<option value=\"" + value + "\">" + monthNames[monthValue] + " " + yearValue + "</option>");
		
    monthValue++;
    // if december change month to jan and increment year
    if (monthValue == 12)	{
			monthValue	= 0;
			yearValue	= yearValue + 1;
		}
	}
	document.write("</select>");
}
    
// function to create the date drop down for bookings
function selectDate(month, year) {
  warningsReset("dates");
  startDay = 1;
	// if month and/or year is zero then use current month/year 
	if (month == 0)	{
		month       = thisMonth + 1;
		startDay    = thisDay + 1;
	}
	
	if (year == 0) {
		year = thisYear;
	}
	
	monthLength = getMonthLength(month, year);
	
	// if using the current date then subtract the start day from the month length to get remaining number of days
	if (startDay != 1) {
		monthLength = monthLength - (startDay - 1);
	}
  dayNameValue    = dayName + 1;
  textDayName     = dayNames[dayNameValue];
 
	document.write("<select name=\"dd_selectDate\" id=\"dd_selectDate\"  class=\"dropDownWW\" onfocus=\"hideCalendar('dates')\">");		
	document.write("<option value=\"00\">Select day</option>");
	for (var i = 0; i < monthLength; i++) { 
    daySuffix = getDateSuffix(startDay);
        
		document.write("<option value=\"" + padToWidth(startDay,2,'0','R') + "\">" + startDay + daySuffix + " " + textDayName + "</option>");
		startDay = startDay + 1;
    dayNameValue++;
    if (dayNameValue == 7) {
      dayNameValue = 0;
    }
    textDayName = dayNames[dayNameValue];
	}
  if (permitMonthSearch == true)
    document.write("<option value=\"Any day\">Any day</option>");
	document.write("</select>");
}	

// function  to adjust the date select when the month select is changed	
function adjustSelectDate(time) {
  holidayPeriod = "";
  if (time != null) {
    holidayPeriod = time;
  } else  {
    for (var i = 0; i < document.whereWhenForm.lengthStay.length; i++) {
      if (document.whereWhenForm.lengthStay[i].checked) {
        holidayPeriod = document.whereWhenForm.lengthStay[i].value;
      }
    }
  }

  lengthOfStay = holidayPeriod;

  // get month and year value from dd_selectMonth
  monthData		    = document.getElementById('dd_selectMonth').options[document.getElementById('dd_selectMonth').selectedIndex].value;
  splitMonthData	    = monthData.split(" ");
  month			    = splitMonthData[0];
    
	// if there is no monthData then use current month and year
  if (month == null) {
    month == thisMonth;
  }
  year= splitMonthData[1]; 
  if (year == null) {
    year == thisYear;
  }

  monthLength = getMonthLength(month, year);
  
  var minDate = createDate(dateRangeStart);
  var maxDate = createDate(dateRangeEnd);
  if ((month == minDate.getMonth()+1) && (year == minDate.getFullYear())) {
    monthLength = monthLength - (minDate.getDate()-1);
    startDay    = minDate.getDate() ;
  } else if ((month == maxDate.getMonth()+1) && (year == maxDate.getFullYear())) {
    monthLength = maxDate.getDate();
    startDay = 1;
  } else { 
    startDay    = 1;
  }

  // set value for hidden field 'arrDate'. This is used by the pop-up calendar as its start date
  document.getElementById('arrDate').value = year + " " + padToWidth(month, 2,'0','R') + " " + "01"; 

  startDayNameNumber  = dayOfWeek(startDay, month, year);
  
  // get current day month year
  currentDate     = new Date();
  currentYear     = currentDate.getFullYear();
  currentMonth    = currentDate.getMonth() + 1;
  currentDay      = currentDate.getDate();
  j   = 1;
  
  // initialize options
  setOptionsLength('dd_selectDate', 0);
  document.getElementById('dd_selectDate').options[0] = new Option("Please select", "");

	// write select options
  for (var i = 0; i < monthLength; i++) {
    daySuffix           = getDateSuffix(startDay);
    startDayName        = dayNames[startDayNameNumber];
    var optDate = new Date(year, month-1, startDay);
    var optDateStr = formatDate(optDate, 'yyyy-MM-dd') + holidayPeriod;
    if (excludeDates.indexOf(optDateStr) == -1) {
    switch (holidayPeriod) {
		case "1week":
      if ((startDayName == "Monday") || (startDayName == "Friday")) {
        document.getElementById('dd_selectDate').options[j] = new Option(((startDay) + daySuffix ) + " " + startDayName, padToWidth(startDay,2,'0','R'));
        j++;
      }
			break;
                
		case "midweek":
			if (startDayName == "Monday"){
				document.getElementById('dd_selectDate').options[j] = new Option(((startDay) + daySuffix ) + " " + startDayName, padToWidth(startDay,2,'0','R'));
				j++;
			}
			break;
                
		case "weekend":
			if (startDayName == "Friday"){
				document.getElementById('dd_selectDate').options[j] = new Option(((startDay) + daySuffix ) + " " + startDayName, padToWidth(startDay,2,'0','R'));
				j++;
			}
			break;

		case "empty": 
			document.getElementById('dd_selectDate').options[j] = new Option(((startDay) + daySuffix ) + " " + startDayName, padToWidth(startDay,2,'0','R'));
			j++;    
			break;                  
		}
    }
		startDay++;
		startDayNameNumber++;
		if (startDayNameNumber == 7){
			startDayNameNumber = 0;
		}
	}
  
  if (j == 1) {
		document.getElementById('dd_selectDate').options[0] = new Option('Select Day', '');
  } else if (permitMonthSearch == true) {
    document.getElementById('dd_selectDate').options[j] = new Option("Any day", "00");
  }
  
	// add leading zero to month if not 2 digits
	month   = "0".substring(month >= 10) + month;      
	arrivalDate = year + month + "01";
}
  
  
function adjustSelectMonth(month, year, showPleaseSelect) {
  setOptionsLength('dd_selectMonth', 0);

  monthValue  = month -1;
  yearValue   = year;
  if (showPleaseSelect == "yes") {
    document.getElementById('dd_selectMonth').options[0] = new Option("Select month", "");
    j = 1;
    k = 11;
  } else {
    j = 0;
    k = 10;
  }

  var startDate = createDate(dateRangeStart);  
  var endDate = createDate(dateRangeEnd);
  
  var monthCount = (endDate.getFullYear() - startDate.getFullYear())*12 + (endDate.getMonth() - startDate.getMonth());  
  k = j + monthCount+1;

  // loop to create option values for the current month and the next 9 months
  for (var i = j; i < k; i++)  {
    value = padToWidth(monthValue + 1,2,'0','R') + " " + yearValue;

    // write the option value
    document.getElementById('dd_selectMonth').options[i] = new Option(monthNames[monthValue] + " " + yearValue, value);
    
    monthValue++;
    // if december change month to jan and increment year
    if (monthValue == 12) {
			monthValue	= 0;
			yearValue	= yearValue + 1;
    }
    adjustSelectDate();
    firstArrivalDate = true;
  }
}
    
/* Code to set up pop-up calendar */
function resetCalendar() {
	// Get today's date
	currentDate     = new Date();
	currentYear     = currentDate.getFullYear();
	currentMonth    = currentDate.getMonth() + 1;
	currentDay      = currentDate.getDate();
	todaysDate = currentYear + "-" + currentMonth + "-" + currentDay;
	cal = new CalendarPopup("popupCalendar");
	cal.addDisabledDates(null,"20"+dateRangeStart.substr(0,2)+"-"+dateRangeStart.substr(2,2)+"-"+dateRangeStart.substr(4,2))
    cal.addDisabledDates("20"+dateRangeEnd.substr(0,2)+"-"+dateRangeEnd.substr(2,2)+"-"+dateRangeEnd.substr(4,2), "2199-12-31");
	cal.setDisabledWeekDays(0,2,3,4,6);  
	cal.setCssPrefix("TEST");
	cal.setReturnFunction("setArrivalDate");
	cal.setMaxDateRange(createDate(dateRangeStart), createDate(dateRangeEnd));
}

/* function for receiving arrival date when pop-up calendar day is selected  this is then written to hidden input field 'chosenArrivalDate' */
function setArrivalDate(year,month,date) {
  // select the correct option in dd_selectMonth
  for (var i = 0; i < document.getElementById('dd_selectMonth').options.length; i++)  {
    if (document.getElementById('dd_selectMonth').options[i].value == padToWidth(month,2,'0','R') + " " + year) {
      document.getElementById('dd_selectMonth').options[i].selected = true;
    } else {
      document.getElementById('dd_selectMonth').options[i].selected = false;
    }
  }

	adjustSelectDate(holidayPeriod);
    
	// select the correct option in dd_selectDate
	for (var i = 0; i < document.getElementById('dd_selectDate').options.length; i++) {
		if (document.getElementById('dd_selectDate').options[i].value ==  padToWidth(date,2,'0','R')) {
			document.getElementById('dd_selectDate').options[i].selected = true;
		}
	}
}

/* form validation */

function validateWhereWhenForm() {
  villageValidate     = false;
  lengthStayValidate  = false;
  warnings            = false;
  specialEvents       = false;
  
  hide('warningArrivalMonth');
  hide('warningArrivalDate');
  hide('warningSpecialBreak');

  // check if a village has been selected
  for (var i = 0; i < arrayVillageNames.length; i++) {
    if (document.getElementById(arrayVillageNames[i]).checked == true) {
      villageValidate = true; 
    }
  }
    
  if (villageValidate != true) {    
    display('warningVillage');
    for (var i = 0; i < villageNames.length; i++) {
      changeColor("villageWarning" + villageNames[i], "#900");
    }
    warningsArray['villages'] = true;
    warnings = true;
  } else {
    hide('warningVillage'); 
  }
 
  // check that a time period has been selected
  for (var i = 0; i < document.whereWhenForm.lengthStay.length; i++) {
    if (document.whereWhenForm.lengthStay[i].checked == true) {
      lengthStayValidate = true;
    }
  }

  // check special events select
  if (document.getElementById('specialEvents_dd') != null) {
		for (j = 0; j < document.getElementById('specialEvents_dd').length; j++) {
			if (document.getElementById('specialEvents_dd').options[document.getElementById('specialEvents_dd').selectedIndex].value != "-") {
				specialEvents = true;
			}
		}
  }
  // check length of stay has been selected
  if (lengthStayValidate != true) {
    display('warningLengthStay');
    for (var i = 0; i < timePeriodNames.length; i++)  {
      changeColor("lengthStayWarning" + timePeriodNames[i], "#900");
    }
        
    warningsArray['lengthStay'] = true;
    warnings = true;        
  } else {
    hide('warningLengthStay'); 
  }
  // if a special event has not been chosen then check for an arrival month and date
  if (lengthStayValidate == true) {
    if (getRadioSetValue(document.whereWhenForm.lengthStay) == 'specialEvent') {
      if (specialEvents != true) {
        display('warningSpecialBreak');
        warnings = true;
      }
      
    } else {
      // check arrival date has  been selected
         if (document.getElementById('dd_selectDate').value.length == 0)  {
         document.getElementById('warningDatesText').style.display="inline";
         warnings = true;      
         warningsArray['dates'] = true;  
         display('warningArrivalDate');            
         }
      // check arrival month has been selected
      if (document.getElementById('dd_selectMonth').value == "") {
        document.getElementById('warningDatesText').style.display="inline";
        warnings = true;
        warningsArray['dates'] = true;
        display('warningArrivalMonth');
      } else {
        hide('warningArrivalMonth');  
      }
    }
  }
    
  //if there are warnings show the warning message box and highlight the area being warned about. 
  if (warnings == true) {
    display('warningMessages');
    document.getElementById('warningMessages').scrollIntoView(true);
  } else {
    document.whereWhenForm.submit();
    hide('warningMessages');
  }
}

    

// End of file

    
function padToWidth(s, width, padChar, justify) {
  var result = s + "";
  if (padChar == null) padChar = ' ';
  if (justify == null) justify = 'L';
  justify = justify.toUpperCase();
  
  switch (justify) {
	case 'L': 
		while (result.length < width) {
			result = result + "" + padChar;
		} 
		break;
	case 'R': 
		while (result.length < width) {
			result = padChar + "" + result;
		} 
		break;
	case 'C': 
		while (result.length < width) {
			result = padChar + "" + result + "" + padChar;
		} 
		break; 
  }
  return result;
}


function checkSelectedItems() {
  for (i = 0; i < arrayVillageNames.length; i++) {
    if (document.getElementById(arrayVillageNames[i]).checked == true) {
      document.getElementById(arrayVillageNames[i] + "Div").style.background = "#dde2a6";
    }
  }
  for (i = 0; i < arrayTimePeriods.length; i++) {
    if (document.getElementById(arrayTimePeriods[i] + "ID").checked == true) {
      document.getElementById(arrayTimePeriods[i]).style.background = "#dde2a6";
    }
  }
}

