/**
 * @class RTW.UTIL
 * @parent RTW
 * @author Malcolm Clark
 *
 * Sitewide Round the world experts utility functions
 *
 * __Author:__ Malcolm Clark<br />
 * __Modified By:__ $LastChangedBy: campm $<br />
 * __Copyright:__ Copyright Flight Centre Ltd. All Rights Reserved.<br />
 * __Version:__ $Revision: 6923 $<br />
 * __Last Modified:__ $Date: 2011-04-18 11:03:12 +1000 (Mon, 18 Apr 2011) $
 *
 * ###Requires
 *
 * * RTW.UTIL
 */

;RTW.UTIL =
{
    /* Name of class */
    name: 'RTW.UTIL',
	monthDays: {"Jan": 31, "Feb": 28, "Mar": 31, "Apr": 30, "May": 31, "Jun": 30, "Jul": 31, "Aug": 31, "Sep": 30, "Oct": 31, "Nov": 30, "Dec": 31},
	
	$_GET: null,

    /* Initialise function, executes FCL.UTIL.handleErrors on the RTW.UTIL object */
    init: function()
    {

        this.toolTipHint();  /* yuin: JS function for "What's this?" tooltip on About Us page: Travel Butler tab (link not used anymore - to exclude from file) */

		// if ( document.location.search === "" ) { //If we have no parameters because the page is a redirect use the pathname and replace the first & with a ?
		// 	var params = document.location.pathname.replace(/&/, '?');
		// 	params = params.substr( params.indexOf('?'), params.length );
		// 	this.$_GET = RTW.UTIL.getQueryParams(params);
		// } else { // We have a proper url
		// 	this.$_GET = RTW.UTIL.getQueryParams(document.location.search);
		// }

		/*--- 15/12/11(YE) | To fix condition where there is no queries ------------------------*/
		if (document.location.search) { // If query string exists
			this.$_GET = RTW.UTIL.getQueryParams(document.location.search);
		} else if (document.location.pathname.match(/&/)) { // if query string exists but in '&' form, replace it with '?'
			var params = document.location.pathname.replace(/&/, '?');
			params = params.substr( params.indexOf('?'), params.length );
			this.$_GET = RTW.UTIL.getQueryParams(params);
		}
		/*--- end of 15/12/11(YE) | To fix condition where there is no queries ------------------------*/
    },
	
	/* Common Form Functions */
	disableDates: function() {
		if ( $("#departureMonth").attr("disabled") || $("#dontKnowDates").is(':checked')) {
			$("#departureMonth").removeAttr("disabled");
			$("#departureDay").removeAttr("disabled");
			$("#returnMonth").removeAttr("disabled");
			$("#returnDay").removeAttr("disabled");
			
			$("#departDate").html("");
			$("#returnDate").html("");
			
			
		} else { 
			$("#departureMonth").attr("disabled", "disabled");
			$("#departureDay").attr("disabled", "disabled");
			$("#returnMonth").attr("disabled", "disabled");
			$("#returnDay").attr("disabled", "disabled");
			
			$("#departDate").html("Disabled");
			$("#returnDate").html("Disabled");
			
		}
	},
	
	/* Validation check for the round the world date fields on the journey planner. They use 3 separate inputs so we can't use the normal flight centre validation code */
	checkDates: function() {
		
		/* Write the dates into hidden fields to make it easier to use them in other areas and in the GIMP email */
		if (! $("#dontKnowDates").is(':checked')){
			var departureDate = $("#departureDay").val() + "/" + $("#departureMonth").val();
			var returnDate = $("#returnDay").val() + "/" + $("#returnMonth").val();
			
			$("#departureDate").val(departureDate);
			$("#returnDate").val(returnDate);
		
		
		/* Validate the dates so that they make sense */
		/*--- 15/12/11(YE) | to fix the following validating date function ---------------------------*/
		var dateToday = new Date();
// console.log('This month selected'+$("#departureMonth").val());
// console.log('This day selected'+$("#departureDay").val());
// console.log('This month'+dateToday.getMonth());
// console.log('This day'+dateToday.getDate());
		if ( $("#departureMonth").val() <= (dateToday.getMonth()+1) && $("#departureDay").val() <= dateToday.getDate() ) { alert("Please Choose a Departure Date greater than Today");return false; }
		/*--- end of 15/12/11(YE) | to fix the following validating date function ---------------------------*/
		// if ( $("#departureMonth").attr("selectedIndex") === 0 && $("#departureDay").attr("selectedIndex") === 0 ) { alert("Please Choose a Departure Date greater than Today");return false; }
		else if ( $("#departureMonth").attr("selectedIndex") > $("#returnMonth").attr("selectedIndex") ||
				( $("#departureMonth").attr("selectedIndex") == $("#returnMonth").attr("selectedIndex") && $("#departureDay").attr("selectedIndex") >= $("#returnDay").attr("selectedIndex") ) ) 
				{ alert("Please Choose a Return Date greater than your Departure Date");return false; }
		}
		return true;
	},
	
	/* Function to sort any query parameters into an array for use throughout the site */
	getQueryParams: function(qs) {
		// Jan (02/02/2012) to eliminate query params handling the contact form
		if(qs == "?call" || qs=="?appointment" || qs=="?email") { return; }

		qs = qs.split("+").join(" ");
		var params = {},
			tokens,
			re = /[?&]?([^=]+)=([^&]*)/g;
		while (tokens == re.exec(qs)) {
			params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
		}

		return params;
	},

	/* yuin: JS function for "What's this?" tooltip on About Us page: Travel Butler tab */
	toolTipHint:function(){
		$("#travel_ref_info").hover(function(){$("#travel_reference_info").show(100);},function(){$("#travel_reference_info").hide(100);});
	}
};
RTW.UTIL.init();

/**
 * @description Reset form plugin. Can reset whole form, or a certain field type, field, etc.
 * 				Currently used for resetting only checkboxes on product Enquiry form.
 */

$.fn.resetForm = function() {
	return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form') {
			return $(':input',this).resetForm();
		}
		if (type == 'text' || type == 'password' || tag == 'textarea') {
			this.value = '';
		} else if (type == 'checkbox' || type == 'radio') {
			this.checked = false;
		} else if (tag == 'select') {
			this.selectedIndex = -1;
		}
	});
};

/**
 * @description  Adding 2x2 methods to the prototype of Date object in order to facilitate Day and Month names
 *
 */
Date.prototype.getMonthName = function() {
	var m = ['January','February','March','April','May','June','July','August','September','October','November','December'];
	return m[this.getUTCMonth()];
};
Date.prototype.getDayName = function() {
	var d = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
	return d[this.getUTCDay()];
};
Date.prototype.getMonthShortName = function() {
	var m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
	return m[this.getUTCMonth()];
};
Date.prototype.getDayShortName = function() {
	var d = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
	return d[this.getUTCDay()];
};

/**
 * @description Plugin for setting dates. Initialises / updates the date fields. Calculates 1 year ahead
 * 				The formats are "dd" for a day, and "mm/yyyy" for monthYear.
 *				ID convention: the pairs of "monthYear" and "day" IDs should be exactly the same, except for the "monthYear", and "day" part,
 *				e.g.: "myDeparture_monthYear12" <=> "myDeparture_day12"
 */

$.fn.setDates = function() {
	$this = $(this);
	// Private methods & members
	var formatDay = function(day) {
		return (day.length == 1)?"0"+day:day;
	};
		
	// Constructor, public methods
	return {
		initMonthYear: function() {
			$this.empty();
			var dayStart, dayEnd, dayStartSize, dayEndSize;
			var today = new Date();
			var todayYear = today.getUTCFullYear();
			var todayMonth = (today.getUTCMonth()+1)%12;
			var todayDayName = today.getDayShortName();
			var todayMonthName = today.getMonthShortName();
			$this.append("<option value='"+formatDay(todayMonth)+"/"+todayYear+"' selected>"+todayMonthName+" "+todayYear+"</option>");
			for (var i=0; i < 11; i++) {
				var month = (today.getUTCMonth()+i)%12+1;
				var year = (month < today.getUTCMonth()+i)?today.getUTCFullYear()+1:today.getUTCFullYear();
				var newDate = new Date(year,month,2);
				var dayName = newDate.getDayShortName();
				var monthName = newDate.getMonthShortName();
				$this.append("<option value='"+formatDay(newDate.getUTCMonth()+1)+"/"+newDate.getUTCFullYear()+"'>"+monthName+" "+newDate.getUTCFullYear()+"</option>");
			}
			this.updateDays();
		},
		updateDays: function() {
			var today = new Date();
			if ($this && $this.size() > 0) {
				var monthYear = $this.val().match(/(^\d+)\/(\d+)/);
				// Date generated from month / year, will use time 00:00:00, therefore will need either day 2, or add 30 mins, so it defines next day (and the month with it) correctly
				var date = new Date(monthYear[2],monthYear[1]-1,2);
				var firstDay = (date.getUTCMonth() == today.getUTCMonth() && date.getUTCFullYear() == today.getUTCFullYear())?today.getUTCDate():1;
				var lastDay = RTW.UTIL.monthDays[date.getMonthShortName()];
				// Leap year
				if (lastDay == 28 && monthYear[2]%4 === 0 && monthYear[2]%100 !== 0 || monthYear[2]%400 === 0) {
					lastDay += 1;
				}
				var day = $this.attr("id").replace(/monthYear/i,"day");
				if (day && $("#"+day)) {
					$("#"+day).empty();
					for (var i=firstDay; i <= lastDay; i++) {
						$("#"+day).append("<option value='"+i+"'>"+i+"</option>");
					}
				}
			}
		}
	}
 };


