/**
    $Revision: 1.14 $
**/

function checkBrowserVersion() {
    // var browser=navigator.appName;
    // var b_version = $.browser.version;
    // var version=parseFloat(b_version);
    if (($.browser.msie) && (parseFloat($.browser.version) <= 6)) {
        if (null == $.cookie("browserNotSupportedShown")) {
            $("#alertbar").removeClass("hidden");
            $("#alertbar .close").removeAttr('href');
            $("#alertbar .close").click(function() {
                $("#alertbar").addClass("hidden");
                $.cookie("browserNotSupportedShown", "true", { expires: 90 });
            });
        }
    }
}

function setBookingModuleTabs() {
	var tabs = $(".frameNav > li");
	var frames = $(".frame");
	var header2 = $(".textField > h2");
	$(".frameNav > li > a")
		.each(function(i){
            $(this).click(function() {
				tabs.each(function(i){
					$(this).removeClass("selected");
					
				});
               $(this).parent().addClass("selected");
               
				frames.each(function(){
					$(this).removeClass("visibleFrame");
				});
				$("#frame0" + (i+1)).addClass("visibleFrame");
            });
        });
}

function setMiddlefield() {
	var middlefield = $("#main .middleField");
	$("#f02").click(function() {
		middlefield.addClass("hidden");
		trackOutgoingLink('/tabs/iseatz');
		});
	$("#f03").click(function() {
		middlefield.addClass("hidden");
		trackOutgoingLink('/tabs/check-in');
		});
	$("#f01").click(function() {
		middlefield.removeClass("hidden");
		trackOutgoingLink('/tabs/booker');
		});
}	

// Tracks outgoing links to Google Analytics tracker
function  trackOutgoingLink(url){
	if(urchinTracker){
		if(typeof _uacct != "undefined")
		{
			_uacct = "UA-6461318-1";
			urchinTracker(url);
		}
	}
}

/*******
 ** sf - Functies overgenomen uit destination-listing.js. Rewritten with jQuery **
*******/

function setDestinations(){

	$('li.listingopen').addClass('listingclosed');
	$('a.destination').click(function()
	{
		if($(this).parent().hasClass('listingclosed')){
			$(this).parent().removeClass('listingclosed');
		}
		else if($(this).parent().hasClass('listingopen')) {
			$(this).parent().addClass('listingclosed');
		}
	});
}

function setFaq() {
	$('a.question').click(function() {
		$(this).parent().toggleClass('answerclosed');
	});
}

/*******
** sf - Functies overgenomen uit PostbackOnEnter.js **
*******/
 
// Functie om een simpele postback te geven op een enter in een textbox
// parameter: evt is de keypress event
// parameter: postbackLink is de 'korte' naam/id van de linkbutton die de echte postback veroorzaakt
// typisch gebruik: <asp:TextBox runat="server" ID="PlaatsTextBox" onKeyPress="javascript:PostbackOnEnter(event,'ZoekenLinkButton');" />
 function PostbackOnEnter(evt, postbackLink){
    PostbackOnEnterMetVoorwaarde(evt, postbackLink, true);
}

// Functie om een simpele postback te geven op een enter in een textbox met een voorwaarde om te checken voordat de porstback uitgevoerd wordt
// parameter: evt is de keypress event
// parameter: postbackLink is de 'korte' naam/id van de linkbutton die de echte postback veroorzaakt
// parameter: een functie of expressie die een boolean waarde teruggeeft - als de waarde true is, wordt de postback uitgevoerd, anders niet.
// typisch gebruik: <asp:TextBox runat="server" ID="PlaatsTextBox" onKeyPress="javascript:PostbackOnEnterMetVoorwaarde(event,'ZoekenLinkButton', new function(){if (this.value==null) return false; return true;});" />
function PostbackOnEnterMetVoorwaarde(evt, postbackLink, voorwaardeFunctie){
    evt = (evt) ? evt : event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode==13){
        if (voorwaardeFunctie){
            var postbackButton = getPostbackButton(postbackLink); 
            if (postbackButton){
               __doPostBack(postbackButton,'');
            }
        }
    }
}

//Functie om het 'lange' unieke asp.net id op te halen op basis van het 'korte' id dat aan PostbackOnEnter is meegegeven
//NB: dit kan tot problemen leiden als er twee links met hetzelfde 'korte' id op een pagina staan
//Vervolgens worden alle '_' in het id vervangen door '$', want dat wordt bij postback gebruikt  
function getPostbackButton(postbackLink){
    var shortID = postbackLink;
    for (var i=0;i<document.links.length;i++){
        var thisName = document.links[i].id;
        var thisNameEnd = thisName.substring(thisName.length - shortID.length,thisName.length);
        
        //vervang '_' door '$'
        if (thisNameEnd==shortID){
            while (thisName.indexOf("_")>-1){
               thisName = thisName.replace("_","$");
            }
            return thisName;
        }
    }
    
    //return null als niet gevonden
    return null;
}

/*******
** sf - Functies overgenomen uit ShowHideSelectedItems.js - NEEDS TO BE REWRITTEN IN JQuery **
*******/

//Show and hide items of a given tag on the page based on the selected value of a dropdownlist
//param: selectID - the id of the dropdownlist
//param: itemTag - the tagname of items involved
//param: itemGroupName - the value of the 'title' attribute on the items, thus defining the group of items to which 
// the selection applies
function showSelectedItem(selectID, itemTag, itemGroupName){
	showSelectedItemWithExtraAttribute(selectID, itemTag, itemGroupName, null);
} 
//Show and hide items of a given tag on the page based on the selected value of a dropdownlist, and an extra attribute
// the extra attribute needs to be set on the select-element as well as the items to which it applies
function showSelectedItemWithExtraAttribute(selectID, itemTag, itemGroupName, extraAttribute){
	var selectElem = document.getElementById(selectID); 
	if (selectElem!=null){
		var selectedValue = selectElem.options[selectElem.selectedIndex].value;
		var items= document.getElementsByTagName(itemTag);
		for (var index=0; index<items.length; index++){
			if (items[index].getAttribute("title")==itemGroupName){
				items[index].style.display="none";
				if ((items[index].id==selectedValue)||(selectedValue=="all")){
					if (extraAttribute){
						if (items[index].getAttribute(extraAttribute)==selectElem.getAttribute(extraAttribute)){
							items[index].style.display="block";
						}
					}else{
						items[index].style.display="block";
					}
				}
			}
		}
	}
}

/*******
** sf - Functies overgenomen uit TimeTableSelection.js - NEEDS TO BE REWRITTEN IN JQuery **
*******/

//function for the selection of a period via radio buttons for timetables
function periodSelectionChanged(tagName, group, period, selectID){
	var selectElem = document.getElementById(selectID);  
	//retain selection of dropdownlist
	var selectedTextBefore;
	if (selectElem.selectedIndex>-1) selectedTextBefore = selectElem.options[selectElem.selectedIndex].text; 
	//retain first option
	var firstOption = selectElem.options[0];
	selectElem.options.length=0;
	selectElem.options[0]=firstOption; 
	//start index for the rest of the options
	optionIndex=1; 
	//set the chosen period as 'period' attribute on the dropdownlist
	selectElem.setAttribute("period",period); 
	//walk through all elements on the page that apply 
	var items= document.getElementsByTagName(tagName);
	for (var index=0; index<items.length; index++){
		//make sure we only change elements that belong to the given group
		if (items[index].getAttribute("title")==group){
			items[index].style.display="none";
			//make sure we only change elements that belong to the given period
			if (items[index].getAttribute("period")==period){
				var optionText= items[index].getAttribute("continent");
				selectElem.options[optionIndex] = new Option(optionText,"continent_div_"+optionText+"_"+period);
				//reset selection of dropdownlist
				if (optionText==selectedTextBefore) selectElem.options[optionIndex].selected="selected";
				optionIndex++;
				items[index].style.display="block";
			}
		}
	} 
	//apply selected value of dropdownlist
	showSelectedItemWithExtraAttribute(selectID, tagName, group, "period");
}

//this function sets attributes (period and continent) on the timetable elements for filtering
// it gets its information from dissecting the id: "continent_div_" + continent + "_"+ period
function addPeriodAndContinentAttributes(tagName, group){
	var items= document.getElementsByTagName(tagName);
	for (var index=0; index<items.length; index++){
		if (items[index].getAttribute("title")==group){
			var continentAndPeriod = items[index].id.substring(14).split("_");
			var continent = continentAndPeriod[0];
			var period = continentAndPeriod[1];
			
			items[index].setAttribute("continent", continent);
			items[index].setAttribute("period", period);
		}
	}

}

/*******
** sf - Functies overgenomen uit PrintButton.js  and rewritten with JQuery **
*******/
function setPrintButton(){
	$("span.printthispage").attr("title","").html('<a href="javascript:window.print();">' + LABELS['PrintPageLabel'] + '</a>')	
}

function setDefaultValues(){
	$("input[id$='txtSearch']")
		.focus(function(){
			if(this.value == LABELS["SearchTextDefaultValue"]){
				this.value = "";
			}
			else {
				this.select();
			}
		})
		.blur(function(){
			if(!this.value){
				this.value = LABELS["SearchTextDefaultValue"];
			}
		});
	$("input[id$='txtEmail']")
		.focus(function(){
			if(this.value == LABELS["EmailTextLabel"]){
				this.value = "";
			}
			else {
				this.select();
			}
		})
		.blur(function(){
			if(!this.value){
				this.value = LABELS["EmailTextLabel"];
			}
		});	
}

$(document).ready(function() {
    var buttonImage = 'http://cdn.martinair.com/static/img/ic-calendar.png';
    var group = $('input[name$=searchForGroup]:checked').val();
    if (group == "car") {
        $("[id$=plhHotel]").css("display", "none");
        $("[id$=plhCar]").css("display", "block");
    }
    $("input[id$=rdoHotel]").click(function() {
        $("[id$=plhHotel]").css("display", "block");
        $("[id$=plhCar]").css("display", "none");
    });

    $("input[id$='rdoCar']").click(function() {
        $("[id$='plhHotel']").css("display", "none");
        $("[id$='plhCar']").css("display", "block");
    });

    $("input[id$='rdoSame']").click(function() {
        $(".dropofflocation").css("visibility", "hidden").val(null);
    });

    $("input[id$='rdoOther']").click(function() {
        $(".dropofflocation").css("visibility", "visible");
    });

    if (typeof destinations_hotels != 'undefined') {
        $("input[id$='txtDestination']").autocomplete(destinations_hotels);
    }
    if (typeof destinations_cars != 'undefined'){
        $("input[id$='txtPickupLocation']").autocomplete(destinations_cars);
        $("input[id$='txtDropoffLocation']").autocomplete(destinations_cars);
    }
    //$.datepicker.regional.de = {closeText:"schließen",prevText:"&#x3c;zurück",nextText:"Vor&#x3e;",currentText:"heute",monthNames:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],monthNamesShort:["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],dayNames:["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],dayNamesShort:["So","Mo","Di","Mi","Do","Fr","Sa"],dayNamesMin:["So","Mo","Di","Mi","Do","Fr","Sa"],dateFormat:"dd-mm-yy",firstDay:1,isRTL:false};
    //$.datepicker.regional.es = {closeText:"Cerrar",prevText:"&#x3c;Ant",nextText:"Sig&#x3e;",currentText:"Hoy",monthNames:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],monthNamesShort:["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"],dayNames:["Domingo","Lunes","Martes","Mi&eacute;rcoles","Jueves","Viernes","S&aacute;bado"],dayNamesShort:["Dom","Lun","Mar","Mi&eacute;","Juv","Vie","S&aacute;b"],dayNamesMin:["Do","Lu","Ma","Mi","Ju","Vi","S&aacute;"],dateFormat:"dd-mm-yy",firstDay:0,isRTL:false};
    $.datepicker.regional.nl = { closeText: "Sluiten", prevText: "?", nextText: "?", currentText: "Vandaag", monthNames: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"], monthNamesShort: ["jan", "feb", "maa", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"], dayNames: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"], dayNamesShort: ["zon", "maa", "din", "woe", "don", "vri", "zat"], dayNamesMin: ["zo", "ma", "di", "wo", "do", "vr", "za"], dateFormat: "dd-mm-yy", firstDay: 1, isRTL: false };

    //$.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['nl']));

    $('.checkindate').datepicker({
        numberOfMonths: 2,
        showButtonPanel: true,
        showOn: 'both', buttonImage: buttonImage, buttonImageOnly: true, dateFormat: 'dd-mm-yy', minDate: new Date(),
        onSelect: function(dateText, inst) {
            var checkinDate = $('.checkindate').datepicker('getDate');
            var checkoutDate = $('.checkoutdate').datepicker('getDate');
            if (checkinDate > checkoutDate) {
                checkinDate.setDate(checkinDate.getDate() + 1);
                $('.checkoutdate').datepicker('setDate', checkinDate);
            }
        }
    });
    $('.checkoutdate').datepicker({
        numberOfMonths: 2,
        showButtonPanel: true,
        showOn: 'both', buttonImage: buttonImage, buttonImageOnly: true, dateFormat: 'dd-mm-yy', minDate: new Date(),
        onSelect: function(dateText, inst) {
            var checkinDate = $('.checkindate').datepicker('getDate');
            var checkoutDate = $('.checkoutdate').datepicker('getDate');
            if (checkoutDate < checkinDate) {
                checkoutDate.setDate(checkoutDate.getDate() - 1);
                $('.checkindate').datepicker('setDate', checkoutDate);
            }
        }
    });

    $('.pickupdate').datepicker({
        numberOfMonths: 2,
        showButtonPanel: true,
        showOn: 'both', buttonImage: buttonImage, buttonImageOnly: true, dateFormat: 'dd-mm-yy', minDate: new Date(),
        onSelect: function(dateText, inst) {
            var pickupDate = $('.pickupdate').datepicker('getDate');
            var dropoffDate = $('.dropoffdate').datepicker('getDate');
            if (pickupDate > dropoffDate) {
                pickupDate.setDate(pickupDate.getDate() + 1);
                $('.dropoffdate').datepicker('setDate', pickupDate);
            }
        }
    });
    $('.dropoffdate').datepicker({
        numberOfMonths: 2,
        showButtonPanel: true,
        showOn: 'both', buttonImage: buttonImage, buttonImageOnly: true, dateFormat: 'dd-mm-yy', minDate: new Date(),
        onSelect: function(dateText, inst) {
            var pickupDate = $('.pickupdate').datepicker('getDate');
            var dropoffDate = $('.dropoffdate').datepicker('getDate');
            if (dropoffDate < pickupDate) {
                dropoffDate.setDate(dropoffDate.getDate() - 1);
                $('.pickupdate').datepicker('setDate', dropoffDate);
            }
        }
    });
    $('.bookingdate').datepicker({
        numberOfMonths: 2,
        showButtonPanel: true,
        showOn: 'both', buttonImage: buttonImage, buttonImageOnly: true, dateFormat: 'dd-mm-yy', maxDate: new Date()
    });
    $('.departuredate').datepicker({
        numberOfMonths: 2,
        showButtonPanel: true,
        showOn: 'both', buttonImage: buttonImage, buttonImageOnly: true, dateFormat: 'dd-mm-yy'
    });
    /*
    */
    setDefaultValues();
    setBookingModuleTabs();
    setMiddlefield();
    setPrintButton();
    setFaq();
    setDestinations();
    checkBrowserVersion();
	
	if ($("#DestinationContinentSelection").length != 0)
	{
		addPeriodAndContinentAttributes('div','TimeTable');
		periodSelectionChanged('div','TimeTable','period1','DestinationContinentSelection');
	}
}); 

