// Content: js ancillary dashboard
// Content: js ancillary dashboard
// --------------------------------------------------------------------------------------------
//
// Set dates in correct format
//
// --------------------------------------------------------------------------------------------
function selectDate (addDays, dateFormat) {

	var now = new Date();
	var start = new Date(now.getTime() + addDays * 3600 * 24 * 1000);
	var year = start.getFullYear();
	var month = start.getMonth()+1;
	var day = start.getDate();
	if (dateFormat == 1) {
		return day + "/" + month + "/" +  year;
	}else{
		return month + "/" + day + "/" +  year;
	}
}


// --------------------------------------------------------------------------------------------
//
// AncillarySearch component
//
// --------------------------------------------------------------------------------------------
function AncillarySearch () {

	this.browser = this.getBrowser();
	this.addStylesheets();

	this.submitForm = 'hotels-searchform';
	
	//Get the check-in and check-out dates set correctly
	//
	this.ancInDateHotel	 = selectDate(0,1);
	this.ancInDateCar 	 = selectDate(0,1);
	this.ancInDateCarPark  = selectDate(0,1);
	this.ancInDateTransport  = selectDate(0,1);

	//
	this.ancOutDateHotel	  = selectDate(7,1)
	this.ancOutDateCar 	  = selectDate(14,1);
	this.ancOutDateCarPark 	  = selectDate(7,1);
	this.ancOutDateTransport 	  = selectDate(7,1);
	
	//set min date (current day) and max date (current day +2 years)
	//
	this.maxDate = selectDate(800,0);
	this.minDate = selectDate(0,0);
	this.dateFormat	= "dd/mm/yyyy"
	this.days = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
	this.months =['January', 'February', 'March', 'April', 'May',  'June', 'July', 'August', 'September', 'October', 'November', 'December'];
	this.monthsShort= ['En', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ag', 'Sept', 'Oct', 'Nov', 'Dic'];

	//creating the autocompleters for destinations in hotel/car
	this.autoCompleteHotelDestination = new AutoCompl('/travel/ec_es/static/xml/ancillary/hotels_es.xml', 'myInputHotel', 'myContainerHotel', 'Hotel');
	this.autoCompleteCarDestination   = new AutoCompl('/travel/ec_es/static/xml/ancillary/cars_es.xml', 'myInputCar', 'myContainerCar', 'Car');
	this.autoCompleteCarParkDestination= new AutoCompl('/travel/ec_es/static/xml/ancillary/parking_es.xml', 'myInputCarPark', 'myContainerCarPark', 'CarPark');
	this.autoCompleteTransportDestination = new AutoCompl('/travel/ec_es/static/xml/ancillary/transportation_es.xml', 'myInputTransport', 'myContainerTransport', 'Transport');


	//setting the form to display
	YAHOO.util.Dom.get('hotel').checked = 'checked';

	this.ancHotel = YAHOO.util.Dom.get('hotel');
	this.ancHotelDestLabel = YAHOO.util.Dom.get('myInputHotel').value ;
	YAHOO.util.Event.addListener(this.ancHotel, 'click', this.showAncillary,'hotels-searchform', this, true);

	this.ancCar = YAHOO.util.Dom.get('car');
	this.ancCarDestLabel = YAHOO.util.Dom.get('myInputCar').value ;
	YAHOO.util.Event.addListener(this.ancCar, 'click', this.showAncillary,'cars-searchform', this, true);

	this.ancCarParking = YAHOO.util.Dom.get('carpark');
	this.ancCarParkDestLabel = YAHOO.util.Dom.get('myInputCarPark').value ; 
	YAHOO.util.Event.addListener(this.ancCarParking, 'click', this.showAncillary,'parking-searchform', this, true);
	
	this.ancTransport = YAHOO.util.Dom.get('transport');
	this.ancTransportDestLabel = YAHOO.util.Dom.get('myInputTransport').value ; 
	YAHOO.util.Event.addListener(this.ancTransport, 'click', this.showAncillary,'transport-searchform', this, true);

	
	//setting the submit button
	this.submitButton = YAHOO.util.Dom.get('anc-search-submit');
	YAHOO.util.Event.addListener(this.submitButton, 'click', this.doSubmitData, this, true);	

	//setting the date fields
	this.AncillaryDaterHotel 	= new AncillaryDater('hotel', this.dateFormat, this.ancInDateHotel, this.ancOutDateHotel, this.minDate, this.maxDate, this.months, this.days);
	this.AncillaryDaterCar		= new AncillaryDater('car', this.dateFormat, this.ancInDateCar, this.ancOutDateCar, this.minDate, this.maxDate, this.months, this.days);
	this.AncillaryDaterCarPark          = new AncillaryDater('carpark', this.dateFormat, this.ancInDateCarPark, this.ancOutDateCarPark, this.minDate, this.maxDate, this.months, this.days);
	this.AncillaryDaterTransport        = new AncillaryDater('transport', this.dateFormat, this.ancInDateTransport, this.ancOutDateTransport, this.minDate, this.maxDate, this.months, this.days);


}

AncillarySearch.prototype.addStylesheets = function () {
	var host = document.location.protocol+'//'+document.domain+(document.location.port ? ':'+document.location.port : '');
	var publication = 'ec_es';
	var aCssURLs = [
		host+'/travel/'+publication+'/static/css/ancillary.css'
		];
		
	if ( is_ie6 )
	{
		aCssURLs[aCssURLs.length] = host+'/travel/'+publication+'/static/css/ancillary_ie6.css';
	}
	else if ( is_ie7 )
	{
		aCssURLs[aCssURLs.length] = host+'/travel/'+publication+'/static/css/ancillary_ie7.css';
	}
	YAHOO.util.Get.css(aCssURLs);
}

AncillarySearch.prototype.getBrowser = function () {
	var ua = navigator.userAgent.toLowerCase();
	if (ua.indexOf('opera')!=-1) { // Opera (check first in case of spoof)
		return 'opera';
	} else if (ua.indexOf('msie 7')!=-1) { // IE7
		return 'ie7';
	} else if (ua.indexOf('msie 6') !=-1) { // IE6
		return 'ie6';
	} else if (ua.indexOf('msie') !=-1) { // IE5.5
		return 'ie55';
	} else if (ua.indexOf('safari')!=-1) { // Safari (check before Gecko because it includes "like Gecko")
		return 'safari';
	} else if (ua.indexOf('gecko') != -1) { // Gecko
		return 'gecko';
	} else {
		return false;
	}
}

AncillarySearch.prototype.doSubmitData = function (e) {

	switch(this.submitForm ){
	  case "hotels-searchform":
		document.forms[this.submitForm].For.value = "City," + document.forms[this.submitForm].elements["anc-destination-place"].value;
		indateArray = document.forms[this.submitForm].elements["hotel-check-in-date"].value.split("/");
		outdateArray = document.forms[this.submitForm].elements["hotel-check-out-date"].value.split("/");
		document.forms[this.submitForm].DateRange.value = indateArray[2] + "-" + indateArray[1] + "-" + indateArray[0]+","+outdateArray[2] + "-" + outdateArray[1] + "-" + outdateArray[0];
		break;
	  case "cars-searchform":
		document.forms[this.submitForm].PickUpLocation.value = "AirportCity," + document.forms[this.submitForm].elements["anc-destination-place"].value;
		indateArray = document.forms[this.submitForm].elements["car-check-in-date"].value.split("/");
		outdateArray = document.forms[this.submitForm].elements["car-check-out-date"].value.split("/");
		document.forms[this.submitForm].DateTimeRange.value = indateArray[2] + "-" + indateArray[1] + "-" + indateArray[0]+"T" +document.getElementById("anc-check-in-time").value + ","+outdateArray[2] + "-" + outdateArray[1] + "-" + outdateArray[0] + "T"+ document.getElementById("anc-check-out-time").value;
		break;
	case "parking-searchform":
		document.forms[this.submitForm].For.value = "City," + document.forms[this.submitForm].elements["anc-destination-place"].value;
		indateArray = document.forms[this.submitForm].elements["carpark-check-in-date"].value.split("/");
		outdateArray = document.forms[this.submitForm].elements["carpark-check-out-date"].value.split("/");
		document.forms[this.submitForm].DateRange.value = indateArray[2] + "-" + indateArray[1] + "-" + indateArray[0]+","+outdateArray[2] + "-" + outdateArray[1] + "-" + outdateArray[0];
		break;
	case "transport-searchform":
		document.forms[this.submitForm].For.value = "City," + document.forms[this.submitForm].elements["anc-destination-place"].value;
		indateArray = document.forms[this.submitForm].elements["transport-check-in-date"].value.split("/");
		outdateArray = document.forms[this.submitForm].elements["transport-check-out-date"].value.split("/");
		document.forms[this.submitForm].DateRange.value = indateArray[2] + "-" + indateArray[1] + "-" + indateArray[0]+","+outdateArray[2] + "-" + outdateArray[1] + "-" + outdateArray[0];
		break;



	  default:;
	
	}

	document.forms[this.submitForm].submit();
}


AncillarySearch.prototype.hideAncillaries = function () {
	YAHOO.util.Dom.get('hotels-searchform').style.display= 'none';
	YAHOO.util.Dom.get('cars-searchform').style.display = 'none';
	YAHOO.util.Dom.get('parking-searchform').style.display = 'none';
	YAHOO.util.Dom.get('transport-searchform').style.display = 'none';
}

AncillarySearch.prototype.showAncillary = function (e, parm) {
	//hide all the ancillary forms
	this.hideAncillaries();
	//display the selected ancillary form
	YAHOO.util.Dom.get(parm).style.display = '';
		
	if (parm == "cars-searchform"){
		YAHOO.util.Dom.get('anc-logo').style.display = '';
		YAHOO.util.Dom.get('tt-header').style.backgroundPosition = '0 -60px' ;
   		YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('car-check-in-date'), 'error'); 
   		YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('car-check-out-date'), 'error');       		
   		YAHOO.util.Dom.get('car-check-in-date').value   = this.ancInDateCar;
   		YAHOO.util.Dom.get('car-check-out-date').value = this.ancOutDateCar;
   		YAHOO.util.Dom.get('myInputCar').value = this.ancCarDestLabel.valueOf();
   		this.submitForm = 'cars-searchform';
	}else{
		YAHOO.util.Dom.get('anc-logo').style.display = 'none';	
		switch (parm) 
		{ 
			case "hotels-searchform" : 
		      		YAHOO.util.Dom.get('tt-header').style.backgroundPosition = '0 0px' ;
		      		YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('hotel-check-in-date'), 'error'); 
		      		YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('hotel-check-out-date'), 'error');       		
		      		YAHOO.util.Dom.get('hotel-check-in-date').value  = this.ancInDateHotel;
		      		YAHOO.util.Dom.get('hotel-check-out-date').value = this.ancOutDateHotel;
		      		YAHOO.util.Dom.get('myInputHotel').value = this.ancHotelDestLabel.valueOf();
		      		this.submitForm = 'hotels-searchform';
		      		break;

			case "parking-searchform" : 
				
				YAHOO.util.Dom.get('tt-header').style.backgroundPosition = '0 0px' ;
		      		YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('carpark-check-in-date'), 'error'); 
		      		YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('carpark-check-out-date'), 'error');       		
		      		YAHOO.util.Dom.get('carpark-check-in-date').value  = this.ancInDateCarPark;
		      		YAHOO.util.Dom.get('carpark-check-out-date').value = this.ancOutDateCarPark;
		      		YAHOO.util.Dom.get('myInputCarPark').value = this.ancCarParkDestLabel.valueOf();
		      		this.submitForm = 'parking-searchform';
		      		break;		      		
			
			case "transport-searchform" : 
				
				YAHOO.util.Dom.get('tt-header').style.backgroundPosition = '0 0px' ;
		      		YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('transport-check-in-date'), 'error'); 
		      		YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('transport-check-out-date'), 'error');       		
		      		YAHOO.util.Dom.get('transport-check-in-date').value  = this.ancInDateTransport;
		      		YAHOO.util.Dom.get('transport-check-out-date').value = this.ancOutDateTransport;
		      		YAHOO.util.Dom.get('myInputTransport').value = this.ancTransportDestLabel.valueOf();
		      		this.submitForm = 'transport-searchform';
		      		break;
		  }

	}
}
 
// --------------------------------------------------------------------------------------------
//
// AncillaryDater component
//
// --------------------------------------------------------------------------------------------
function AncillaryDater (ancillary, dateFormat, depDate, retDate, minDate, maxDate, months, days) {

	//
	// GENERAL
	// init departuredate
	var depIdIcon = ancillary+'-check-in-date-icon';
	var depIdDate = ancillary+'-check-in-date';
	this.depDateIcon = YAHOO.util.Dom.get(depIdIcon);
	this.depCalendar = new GeneralCalendar (null, YAHOO.util.Dom.get(depIdDate), dateFormat, depDate, minDate, maxDate, months, days);
	YAHOO.util.Event.addListener(this.depDateIcon, "click", this.depCalendar.show, [this.depCalendar, YAHOO.util.Dom.get(depIdDate)], true); 
	
	// init returndate
	var retIdIcon = ancillary+'-check-out-date-icon';
	var retIdDate = ancillary+'-check-out-date';
	this.retDateIcon = YAHOO.util.Dom.get(retIdIcon);
	this.retCalendar = new GeneralCalendar (null, YAHOO.util.Dom.get(retIdDate), dateFormat, retDate, minDate, maxDate, months, days);
	YAHOO.util.Event.addListener(this.retDateIcon, "click", this.retCalendar.show, [this.retCalendar, YAHOO.util.Dom.get(retIdDate)], true); 
	this.depCalendar.cal.selectEvent.subscribe(this.selectdepDate, this, true);
	this.depDateChange = new YAHOO.util.CustomEvent("dateChange", this);

}

AncillaryDater.prototype.selectdepDate = function (e) {
	// update Return calendar
	var selectedDepDate = this.depCalendar.getSelectedDates()[0];
	this.retCalendar.cal.cfg.setProperty("mindate", selectedDepDate); 
	if ((selectedDepDate > this.retCalendar.getSelectedDates()[0])) {
		this.retCalendar.cal.select(selectedDepDate);
	}
	this.depDateChange.fire(selectedDepDate);
}


// --------------------------------------------------------------------------------------------
//
// AutoComplete component
//
// --------------------------------------------------------------------------------------------

//var airportToData = new Array();
var destinationDataHotel = new Array();
var destinationDataCar = new Array();
var destinationDataCarPark = new Array();
var destinationDataTransport = new Array();


function AutoCompl (xmlFile, inputField, containerField, destinationField) {
	this.AncilaryType = destinationField;
	this.inputFld = YAHOO.util.Dom.get(inputField);
	YAHOO.util.Event.addListener(this.inputFld, "focus", function () {if (YAHOO.util.Dom.hasClass(this, 'entered')) {this.select()} else {this.value = ''}}); 
	YAHOO.util.Event.addListener(this.inputFld, "keydown", function () {this.style.color = '#023167'; YAHOO.util.Dom.addClass(this, 'entered')});
	YAHOO.util.Event.addListener(this.inputFld, "keyup", this.updateHiddenField, this, true);
	this.getAirportData(xmlFile);
	switch (this.AncilaryType) 
	{ 
		case "Hotel" : 
			this.ACDS = new YAHOO.widget.DS_JSFunction(this.getToMatchesHotel)
			break; 
		case "Car" : 
			this.ACDS = new YAHOO.widget.DS_JSFunction(this.getToMatchesCar)
			break; 
		case "CarPark" : 
			this.ACDS = new YAHOO.widget.DS_JSFunction(this.getToMatchesCarPark)
			break; 
		case "Transport" : 
			this.ACDS = new YAHOO.widget.DS_JSFunction(this.getToMatchesTransport)
			break; 
		default:			   
	}
	this.myAutoComplete = new YAHOO.widget.AutoComplete(inputField, containerField, this.ACDS);
	this.myAutoComplete.queryDelay = 0; 
	this.myAutoComplete.maxResultsDisplayed = 100;
	this.myAutoComplete.doBeforeExpandContainer = function () {
		var is_ie6 = (is_ie && is_major == 6);
		var is_ie7 = (is_ie && is_major == 7);
		if (is_ie6 || is_ie7) {
				switch (destinationField) 
			{ 
	   			case "Hotel" :
					document.getElementById('anc-return-label').style.visibility = "hidden";
					document.getElementById('hotel-check-out-date').style.visibility = "hidden";
					document.getElementById('hotel-check-out-date-icon').style.visibility = "hidden";
					break;
	   			case "Car" : 
					document.getElementById('anc-car-return-label').style.visibility = "hidden";
					document.getElementById('car-check-out-date').style.visibility = "hidden";
					document.getElementById('car-check-out-date-icon').style.visibility = "hidden";	
					break;
				case "CarPark" : 
					document.getElementById('anc-car-park-return-label').style.visibility = "hidden";
					document.getElementById('carpark-check-out-date').style.visibility = "hidden";
					document.getElementById('carpark-check-out-date-icon').style.visibility = "hidden";	
					break;
				case "Transport" : 
					document.getElementById('anc-transport-return-label').style.visibility = "hidden";
					document.getElementById('transport-check-out-date').style.visibility = "hidden";
					document.getElementById('transport-check-out-date-icon').style.visibility = "hidden";	
					break;

	   			default:
	   		}
		}
		else {};
		return true;
	};
	 
	this.myAutoComplete.containerCollapseEvent.subscribe(test_collapsEvent);


}

AutoCompl.prototype.getAirportData = function (xmlFile) {
	var callback = { 
		success: this.parseAirportData, 
		failure: this.handleFailure,
		scope: this
	};
	this.airportXMLData = YAHOO.util.Connect.asyncRequest('GET', xmlFile, callback, null);
}
AutoCompl.prototype.parseAirportData = function (o) {
	var airports = o.responseXML.getElementsByTagName('destination');
	var airportRecord;

	for (var i = 0; i < airports.length; i++) {
		airportRecord = new Array();
		airportRecord[0] = airports[i].childNodes[0].nodeValue; //general name

		switch (this.AncilaryType) 
		{ 
		   case "Hotel" : 
			destinationDataHotel[i] = airportRecord;
			break; 
		   case "Car" : 
	   		destinationDataCar[i] = airportRecord;
			break; 
		  case "CarPark" : 
	   		destinationDataCarPark[i] = airportRecord;
			break; 
		  case "Transport" : 
		   	destinationDataTransport[i] = airportRecord;
			break; 
 		   default:
		}
	}


	switch (this.AncilaryType) 
	{ 
		case "Hotel" : 
			destinationDataHotel.sort(initialSortFuncAnc);
			break; 
	  	case "Car" : 
		   	destinationDataCar.sort(initialSortFuncAnc);
		   	break;
		case "CarPark" : 
		   	destinationDataCarPark.sort(initialSortFuncAnc);
		   	break;
		case "Transport" : 
		   	destinationDataTransport.sort(initialSortFuncAnc);
		   	break;

		default:			   
	}

}
AutoCompl.prototype.handleFailure = function () {
}
AutoCompl.prototype.getToMatchesHotel = function (sQuery) {
	sQuery = unescape(sQuery);
	var aResults = [];
	if (sQuery.length < 3) return aResults;
	
	// priority array; defines order to show results: airportcode, airportname, city, state, country
	// var priority = [0,5, 4, 1, 2, 3, 6];
	// only check the general name, the city, the airport name, the airportcode and the group name
	var priority = [0,5, 4, 1, 6];
	var regExp = new RegExp("(.*)(" + sQuery + ")(.*)", "i");

	for (var i = 0; i < destinationDataHotel.length; i++) {
		for (var j = 0; j < destinationDataHotel[i].length; j++) {
			if (regExp.test(destinationDataHotel[i][priority[j]])) {
				aResults.push(destinationDataHotel[i]);
				aResults[aResults.length - 1][8] = j;
				break;
			}
		}
	};

	aResults.sort(acSortFuncAnc);
	return (sortSecLevelAlphabeticAnc(aResults));
}

AutoCompl.prototype.getToMatchesCar = function (sQuery) {
	sQuery = unescape(sQuery);
	var bResults = [];
	if (sQuery.length < 3) return bResults;
	
	// priority array; defines order to show results: airportcode, airportname, city, state, country
	// var priority = [0,5, 4, 1, 2, 3, 6];
	// only check the general name, the city, the airport name, the airportcode and the group name
	var priority = [0,5, 4, 1, 6];
	var regExp = new RegExp("(.*)(" + sQuery + ")(.*)", "i");

	for (var i = 0; i < destinationDataCar.length; i++) {
		for (var j = 0; j < destinationDataCar[i].length; j++) {
			if (regExp.test(destinationDataCar[i][priority[j]])) {
				bResults.push(destinationDataCar[i]);
				bResults[bResults.length - 1][8] = j;
				break;
			}
		}
	};

	bResults.sort(acSortFuncAnc);
	return (sortSecLevelAlphabeticAnc(bResults));
}

AutoCompl.prototype.getToMatchesTransport = function (sQuery) {
	sQuery = unescape(sQuery);
	var bResults = [];
	if (sQuery.length < 3) return bResults;
	
	// priority array; defines order to show results: airportcode, airportname, city, state, country
	// var priority = [0,5, 4, 1, 2, 3, 6];
	// only check the general name, the city, the airport name, the airportcode and the group name
	var priority = [0,5, 4, 1, 6];
	var regExp = new RegExp("(.*)(" + sQuery + ")(.*)", "i");

	for (var i = 0; i < destinationDataTransport.length; i++) {
		for (var j = 0; j < destinationDataTransport[i].length; j++) {
			if (regExp.test(destinationDataTransport[i][priority[j]])) {
				bResults.push(destinationDataTransport[i]);
				bResults[bResults.length - 1][8] = j;
				break;
			}
		}
	};

	bResults.sort(acSortFuncAnc);
	return (sortSecLevelAlphabeticAnc(bResults));
}

AutoCompl.prototype.getToMatchesCarPark = function (sQuery) {
	sQuery = unescape(sQuery);
	var bResults = [];
	if (sQuery.length < 3) return bResults;
	
	// priority array; defines order to show results: airportcode, airportname, city, state, country
	// var priority = [0,5, 4, 1, 2, 3, 6];
	// only check the general name, the city, the airport name, the airportcode and the group name
	var priority = [0,5, 4, 1, 6];
	var regExp = new RegExp("(.*)(" + sQuery + ")(.*)", "i");

	for (var i = 0; i < destinationDataCarPark.length; i++) {
		for (var j = 0; j < destinationDataCarPark[i].length; j++) {
			if (regExp.test(destinationDataCarPark[i][priority[j]])) {
				bResults.push(destinationDataCarPark[i]);
				bResults[bResults.length - 1][8] = j;
				break;
			}
		}
	};

	bResults.sort(acSortFuncAnc);
	return (sortSecLevelAlphabeticAnc(bResults));
}

AutoCompl.prototype.BasicRemote = function() {	
	  
};


function test_collapsEvent () {
	var is_ie6 = (is_ie && is_major == 6);
	var is_ie7 = (is_ie && is_major == 7);
	if (is_ie6 || is_ie7) {
		if (document.getElementById('hotel').checked) { 
			document.getElementById('anc-return-label').style.visibility = "visible";
			document.getElementById('hotel-check-out-date').style.visibility = "visible";
			document.getElementById('hotel-check-out-date-icon').style.visibility = "visible";		
		}
		if (document.getElementById('car').checked) { 
			document.getElementById('anc-car-return-label').style.visibility = "visible";
			document.getElementById('car-check-out-date').style.visibility = "visible";
			document.getElementById('car-check-out-date-icon').style.visibility = "visible";
		}
		if (document.getElementById('carpark').checked) { 
			document.getElementById('anc-car-park-return-label').style.visibility = "visible";
			document.getElementById('carpark-check-out-date').style.visibility = "visible";
			document.getElementById('carpark-check-out-date-icon').style.visibility = "visible";
		}
		if (document.getElementById('transport').checked) { 
			document.getElementById('anc-transport-return-label').style.visibility = "visible";
			document.getElementById('transport-check-out-date').style.visibility = "visible";
			document.getElementById('transport-check-out-date-icon').style.visibility = "visible";
		}
	}
}

function sortSecLevelAlphabeticAnc (results) {
	var arSorted = new Array();
	var arSub = new Array();
	if (results[0])	var group = results[0][8];

	for (var i = 0; i < results.length; i++) {
		if (results[i][8] == group) {
			arSub[arSub.length] = results[i]
		} else {
			arSub.sort(initialSortFuncAnc);
			arSorted = arSorted.concat(arSub);
			arSub = new Array();
			arSub[arSub.length] = results[i]
			group = results[i][8];
		}
	}
	arSub.sort(initialSortFuncAnc);
	arSorted = arSorted.concat(arSub);
	
	return arSorted;
}
function acSortFuncAnc (a, b) {
	if (parseInt(a[8], 10) >= parseInt(b[8], 10)) return 1;
	if (parseInt(a[8], 10) < parseInt(b[8], 10)) return -1;
	return 0;
}
function initialSortFuncAnc (a, b) {
	if (a[0] >= b[0]) return 1;
	return -1;
}	
// Content: js ancillary dashboard elements
// --------------------------------------------------------------------------------------------
//
// HTMLNode component
//
// --------------------------------------------------------------------------------------------
function HTMLNode(target, type, attributes, innerHtml, className, hrefText) {
	var newNode = target.createElement(type);
	for (var prop in attributes) {
		newNode.setAttribute(prop, attributes[prop]);
	}
	if (type = 'a' && hrefText) newNode.href = hrefText;
	if (className) newNode.className = className;
	if (innerHtml) newNode.innerHTML = innerHtml;
	return newNode;
}

// --------------------------------------------------------------------------------------------
//
// calculate offset
//
// --------------------------------------------------------------------------------------------

function calculateTop(object) {if (object) return object.offsetTop + calculateTop(object.offsetParent); else return 0;}
function calculateLeft(object) {if (object) return object.offsetLeft + calculateLeft(object.offsetParent); else return 0;}

// --------------------------------------------------------------------------------------------
//
// Ancillary Calendar component
//
// --------------------------------------------------------------------------------------------
function GeneralCalendar (container, inputBox, dateFormat, defaultDate, minDate, maxDate, months, days) {
	if (!container) {
		this.container = new HTMLNode(document, 'div', null, '', 'anc-calendar');
		document.body.appendChild(this.container);
	} else {
		this.container = container;
	}
	this.closeBut = new HTMLNode(document, 'a', {href:'javascript:;'}, 'close', 'close-calendar');
	this.container.appendChild(this.closeBut);
	this.tableContainer = new HTMLNode(document, 'div', {id:'cal' + Math.random()});
	this.container.appendChild(this.tableContainer);
	this.cal = new YAHOO.widget.Calendar('myCal', this.tableContainer.id, {mindate:minDate, maxdate:maxDate});
	this.inputBox = inputBox;
	this.dateFormat = dateFormat;
	this.minDate = minDate;
	this.maxDate = maxDate;
	this.months = months;
	this.days = days;
	this.mover = false;
	this.configDateFormat();
	this.initEvents();
	if (defaultDate) this.cal.select(defaultDate);
}
GeneralCalendar.prototype.configDateFormat = function () {
	this.cal.cfg.setProperty("WEEKDAYS_SHORT", this.days);
	this.cal.cfg.setProperty("MONTHS_LONG", this.months);
	var sDate = this.dateFormat.split('/');
	sDate[0] == 'mm' ? this.mPos = 1 : (sDate[1] == 'mm' ? this.mPos = 2 : this.mPos = 3);
	sDate[0] == 'dd' ? this.dPos = 1 : (sDate[1] == 'dd' ? this.dPos = 2 : this.dPos = 3);
	sDate[0].indexOf('yy') != -1 ? this.yPos = 1 : (sDate[1].indexOf('yy') != -1 ? this.yPos = 2 : this.yPos = 3);
	this.cal.cfg.setProperty("MDY_MONTH_POSITION", this.mPos);
	this.cal.cfg.setProperty("MDY_DAY_POSITION", this.dPos);
	this.cal.cfg.setProperty("MDY_YEAR_POSITION", this.yPos);
	this.cal.cfg.setProperty("START_WEEKDAY", 1);
	this.yearShort = sDate[this.yPos-1].length > 2 ? false : true;
}
GeneralCalendar.prototype.initEvents = function () {
	YAHOO.util.Event.addListener(this.container, "mouseover", this.overCal, this, true); 
	YAHOO.util.Event.addListener(this.container, "mouseout", this.outCal, this, true); 
	YAHOO.util.Event.addListener(this.inputBox, "focus", this.show, [this, this.inputBox], true); 
	YAHOO.util.Event.addListener(this.closeBut, "click", this.close, this, true); 
	YAHOO.util.Event.addListener(this.inputBox, "keydown", this.close, this, true); 
	YAHOO.util.Event.addListener(this.inputBox, "blur", this.checkEnteredDate, this, true); 
	this.cal.selectEvent.subscribe(this.selectDate, this, true);
	this.cal.renderEvent.subscribe(this.updateCalNavigation, this, true);

	this.dateInputError = new YAHOO.util.CustomEvent("dateError", this);
	this.dateNoError = new YAHOO.util.CustomEvent("dateNoError", this);
}
GeneralCalendar.prototype.overCal = function (e) {
	this.mover = true;
}
GeneralCalendar.prototype.outCal = function (e) {
	try {if (isChild(this.container, YAHOO.util.Event.resolveTextNode(YAHOO.util.Event.getRelatedTarget(e)))) return} catch(e) {}
	this.mover = false;
}
GeneralCalendar.prototype.show = function (e, args) {
	var base = args[0];
	var inputBox = args[1];
	
	if (inputBox.disabled) return;
	if (inputBox) inputBox.select();
	if (base.cal.getSelectedDates().length > 0) {
		base.cal.cfg.setProperty("pagedate", (base.cal.getSelectedDates()[0].getMonth() + 1) + '/' + base.cal.getSelectedDates()[0].getFullYear());
	}
	base.cal.render();
	base.container.style.display = 'block';
	YAHOO.util.Dom.setXY(base.container, [calculateLeft(inputBox) - 3, calculateTop(inputBox) + 16]);
}
GeneralCalendar.prototype.close = function (e) {
	this.mover = false;
	this.container.style.display = 'none';
}
GeneralCalendar.prototype.selectDate = function (e, args) {
	var selectedRetDate = args[0][0];
	var selDay = selectedRetDate[2];
	var selMonth = selectedRetDate[1];
	var selYear = selectedRetDate[0];

	selectedDate = selDay + '/' + selMonth + '/' + selYear;
	this.close();
	this.inputBox.value = this.formatDate(selectedDate);
	YAHOO.util.Dom.removeClass(this.inputBox, 'error');
	this.dateNoError.fire(this.inputBox); 
}
GeneralCalendar.prototype.formatDate = function (date) {
	var aDate = date.split('/');
	var aFormattedDate = new Array();
	
	aFormattedDate[this.dPos-1] = aDate[0];
	aFormattedDate[this.mPos-1] = aDate[1];
	aFormattedDate[this.yPos-1] = aDate[2];
	if (this.yearShort) aFormattedDate[this.yPos-1] = aFormattedDate[this.yPos-1].substr(2, 2); // show only last 2 characters of year
	var s = aFormattedDate[0] + '/' + aFormattedDate[1] + '/' + aFormattedDate[2];
	
	return s;
}
GeneralCalendar.prototype.checkEnteredDate = function (e) {
	if (this.mover) return;
	this.close();
	var dateValues = this.inputBox.value.split('/');
	var day = parseInt(dateValues[this.dPos-1], 10);
	var month = parseInt(dateValues[this.mPos-1], 10);
	var year = parseInt(dateValues[this.yPos-1], 10);
	if (this.yearShort) year += 2000;
	var date = new Date(year, month-1, day);
	if ((date.getMonth() + 1) != month) {
		this.dateInputError.fire(this.inputBox); 
		YAHOO.util.Dom.addClass(this.inputBox, 'error');
		return false;
	} else {
		this.dateNoError.fire(this.inputBox);
		YAHOO.util.Dom.removeClass(this.inputBox, 'error');
		this.cal.select(date);
		return true;
	}
}
GeneralCalendar.prototype.getSelectedDates = function () {
	return this.cal.getSelectedDates();
}
GeneralCalendar.prototype.updateCalNavigation = function (e) {
	var mindate = new Date(this.cal.cfg.getProperty("minDate"));
	var maxdate = new Date(this.cal.cfg.getProperty("maxDate"));
	maxdate.setMonth(maxdate.getMonth() - 1);
	if (this.cal.cfg.getProperty("pagedate").getTime() <= mindate.getTime()) {
		YAHOO.util.Dom.getElementsByClassName('calnavleft', 'a', this.cal.oDomContainer)[0].style.display = 'none';
	};
	if (this.cal.cfg.getProperty("pagedate").getTime() > maxdate.getTime()) {
		YAHOO.util.Dom.getElementsByClassName('calnavright', 'a', this.cal.oDomContainer)[0].style.display = 'none';
	};
}