var msg;
var flightCalendar;
var carCalendar;
var fromSuggest;
var toSuggest;

Event.observe(window, 'load', initializeMsgBox, false);

function initializeMsgBox() {
	// ### GLASS + MESSAGE BOX
	var glassOptions = {
		color: '#003366',
		opacity: 0.5
	}
	var glass = new Gibbon.Glass(glassOptions);

	msg = new Gibbon.MessageBox('MsgBox', glass);	
}

function searching() {
	progress = 0;
	progressbar();
	msg.show();
}

//Event.observe(window, 'beforeunload', progressbar, false);
var progress = 0;
var progressAnimId = 0;
function progressbar() {
	progressAnimId = window.setTimeout('progressbar()', 200);
	progress += 8;
	if (progress > 400) progress = 0;
	Element.setStyle('progress', { width: (progress+'px') });
}

function cancelSearch() {
	if (document.all) {
		document.execCommand("Stop");
	} else {
		window.stop();
	}
	msg.hide();	
	window.clearTimeout(progressAnimId);
}

function initGibbonCalendar() {
	// ### CALENDAR
	var now = new Gibbon.Date();
	flightCalendar = new Gibbon.Calendar(now.getYear(), now.getMonth(), {
		id: 'flightCalendar',
		range: {
			start: new Gibbon.Date(2006, 1, 1), 
			stop: new Gibbon.Date(2010, 1, 1)
		}
	});	
	flightCalendar.dateChangedEvent = function(date) {
		var prefix = date.index == 0 ? 'departure' : 'return';
		$(prefix+'Month').value = date.date.getYear() + '-' + date.date.getMonth(true);
		$(prefix+'Day').value = date.date.getDay();
	}
}

function initializeFlightForm() {
	// ### FIELD FUNCTIONS
	Gibbon.Form.autoSelectText('fromCity');
	Gibbon.Form.autoSelectText('toCity');
	Gibbon.Form.blockEnter('fromCity');
	Gibbon.Form.blockEnter('toCity');



	// ### AUTOCOMPLETE
	/*
	fromSuggest = new TextSuggest('fromCity', '/cityAjaxSearch.do', { 
		matchAnywhere      : true,
		ignoreCase         : true,
		selectionColor     : '#336699',
		createHiddenInput  : false,
		hiddenInput        : 'fIA'        
	});
	
	toSuggest = new TextSuggest('toCity', '/cityAjaxSearch.do', { 
		matchAnywhere      : true,
		ignoreCase         : true,
		selectionColor     : '#336699',
		createHiddenInput  : false,
		hiddenInput        : 'tIA'    
	});
	*/
	
	// ### TOGGLE CHILDREN AGES
	toggleChildAges();	
}

function updateFlightCalendar(index) {
	var prefix = index == 0 ? 'departure' : 'return';
	var yearMonth = $(prefix+'Month').value.split('-');
	var year = parseInt(yearMonth[0], 10);
	var month = parseInt(yearMonth[1], 10);
	var day = parseInt($(prefix+'Day').value, 10);	
	if (!isNaN(year) && !isNaN(month) && !isNaN(day)) {
		flightCalendar.setDate(year, month, day, true, false, false);
	}
}

function initializeCarForm() {
	// ### FIELD FUNCTIONS
	Gibbon.Form.autoSelectText('pickupCity');
	Gibbon.Form.autoSelectText('dropoffCity');
	Gibbon.Form.blockEnter('pickupCity');
	Gibbon.Form.blockEnter('dropoffCity');

	// ### CALENDAR
	/*
	var now = new Gibbon.Date();	
	carCalendar = new Gibbon.Calendar(now.getYear(), now.getMonth(), {
		id: 'carCalendar',
		range: {
			start: new Gibbon.Date(2006, 1, 1), 
			stop: new Gibbon.Date(2010, 1, 1)
		}
	});		
	carCalendar.dateChangedEvent = function(date) {
		var prefix = date.index == 0 ? 'pickup' : 'dropoff';
		$(prefix+'Month').value = date.date.getYear() + "-" + date.date.getMonth(true);
		$(prefix+'Day').value = date.date.getDay();
	}	

	// ### AUTOCOMPLETE
	pickupSuggest = new TextSuggest('pickupCity', '/cityAjaxSearch.do', { 
		matchAnywhere      : true,
		ignoreCase         : true,
		selectionColor     : '#336699',
		createHiddenInput  : false,
		hiddenInput        : 'puIA'        
	});
	dropoffSuggest = new TextSuggest('dropoffCity', '/cityAjaxSearch.do', { 
		matchAnywhere      : true,
		ignoreCase         : true,
		selectionColor     : '#336699',
		createHiddenInput  : false,
		hiddenInput        : 'doIA'    
	});
	*/
}

function updateCarCalendar(index) {
	var prefix = index == 0 ? 'pickup' : 'dropoff';
	var yearMonth = $(prefix+'Month').value.split('-');
	var year = parseInt(yearMonth[0], 10);
	var month = parseInt(yearMonth[1], 10);
	var day = parseInt($(prefix+'Day').value, 10);	
	if (!isNaN(year) && !isNaN(month) && !isNaN(day)) {
		carCalendar.setDate(year, month, day, true, false, false);
	}
}

function toggleDropoff() {
	var dropoffField = $('dropoffField');
	dropoffField.toggle();
	if (dropoffField.visible()) {
		$('dropoffCity').focus();
	}
}

function toggleTransTypes() {
	$('transTypeFields').toggle();
}

function toggleCarTypes() {
	$('carTypeFields').toggle();
}

function toggleChildAges() {
	var children = $('children');
	if (children != null && children.options != null) {
		var count = children.options[children.selectedIndex].value;		
		for (var i = 1; i <= 8; i++) {
			if (count >= i) {
				$('child' + (i-1)).show();
			} else {
				$('child' + (i-1)).hide();
			}
		}
	}
}

function initYUICalendar(fromDate, toDate, elPrefix) {	
	var oCalendarMenu;
	
	var onButtonClick = function () {
		var oCalendar = new YAHOO.widget.CalendarGroup("buttoncalendar", oCalendarMenu.body.id, {            
            mindate:fromDate,
   		 	maxdate:toDate,
   		 	LOCALE_WEEKDAYS:"1char", 
			START_WEEKDAY: 1
        });
        
		oCalendar.cfg.setProperty("MONTHS_LONG",    ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"]); 
		oCalendar.cfg.setProperty("WEEKDAYS_1CHAR", ["S", "M", "T", "O", "T", "F", "L"]);
		oCalendar.cfg.setProperty("DATE_FIELD_DELIMITER", "-");
		oCalendar.cfg.setProperty("MDY_DAY_POSITION", 3); 
		oCalendar.cfg.setProperty("MDY_MONTH_POSITION", 2); 
		oCalendar.cfg.setProperty("MDY_YEAR_POSITION", 1); 
        oCalendar.render();        

        oCalendar.selectEvent.subscribe(function (p_sType, p_aArgs) {
    		if (p_aArgs) {
    			var aDate = p_aArgs[0][0];
    			var dM = (aDate[0]) + "-" + (aDate[1] < 10 ? "0" + aDate[1] : aDate[1]);
    			$(elPrefix + "Month").value = dM;
    			$(elPrefix + "Day").value = aDate[2];
    		}

    		oCalendarMenu.hide();
    	});
             
    //    	var d = $("departureDay").value;
    	//	oCalendar.select($("departureMonth").value + "-" + (d < 10 ? "0" + d : d));	
    

        YAHOO.util.Event.on(oCalendarMenu.element, "keydown", function (p_oEvent) {
    		if (YAHOO.util.Event.getCharCode(p_oEvent) === 27) {
    			oCalendarMenu.hide();
    			this.focus();
    		}
    	}, null, this);
    	        
    	oCalendarMenu.align();

    	this.unsubscribe("click", onButtonClick);
	}

	oCalendarMenu = new YAHOO.widget.Overlay(elPrefix + "Calendarmenu", { visible: false });		
	var oButton = new YAHOO.widget.Button({ 
			type: "menu", 
			id: elPrefix + "Calendarpicker", 
			label: "", 
			menu: oCalendarMenu, 
			container: elPrefix + "Datefields" });

	oButton.on("appendTo", function () {
			oCalendarMenu.setBody("&#32;");
			oCalendarMenu.body.id = elPrefix + "Calendarcontainer";
		});

	oButton.on("click", onButtonClick);
}

var cityAjaxUrl = "/cityAjaxSearch.do?flat=true&";

function createCityAutoComplete(elInput, elHiddenInput, elContainer) {
    // Use an XHRDataSource
    var oDS = new YAHOO.util.XHRDataSource(cityAjaxUrl);
    // Set the responseType
    oDS.responseType = YAHOO.util.XHRDataSource.TYPE_TEXT;
    // Define the schema of the delimited results
    oDS.responseSchema = {
        recordDelim: "\n",
        fieldDelim: "\t",
        fields: ["name", "code"]
    };
    // Enable caching
    oDS.maxCacheEntries = 5;

    // Instantiate the AutoComplete
    var oAC = new YAHOO.widget.AutoComplete(elInput, elContainer, oDS, {
	    queryQuestionMark : false,
	    allowBrowserAutocomplete : false,
	    minQueryLength : 3
	    });
    oAC.resultTypeList = false;
    oAC.useIFrame = true;
    oAC.formatResult = function(data, query, match) {
    	 return '<b>' + data.name + '</b>, ' + data.code;
    };

 	// Define an event handler to populate a hidden form field
    // when an item gets selected
    var myHiddenField = $(elHiddenInput);
    var myHandler = function(sType, aArgs) {
        var myAC = aArgs[0]; // reference back to the AC instance
        var elLI = aArgs[1]; // reference to the selected LI element
        var oData = aArgs[2]; // object literal of selected item's result data
        
        // update hidden form field with the selected item's ID
        myHiddenField.value = oData.code;
    };
    oAC.itemSelectEvent.subscribe(myHandler);
    
    return {
        oDS: oDS,
        oAC: oAC
    };
}