/*
################################################################################
#  Copyright (c) 2001 EDS. All Rights reserved.
################################################################################
#
#  NAME OF FILE:      		hzilib.js
#
################################################################################
*
*/


var mapWindow;
function openMapWindow(zonAction, mapWidth, mapHeight) {
    var prop = "menubar=no,status=no,resizable=yes,scrollbars=yes";
    openCustomMapWindow(zonAction, mapWidth, mapHeight, prop);
}

function openCustomMapWindow(zonAction, mapWidth, mapHeight, properties) {
    var winWidth = parseInt(mapWidth) + 50;
    var winHeight = parseInt(mapHeight) + 80;

    var prop = "width=" + winWidth.toString() + ",height=" + winHeight.toString();
    if (properties && properties.length > 0) {
        prop = prop + "," + properties;
    }

    mapWindow = window.open(getPopupLink(zonAction), "_NEW", prop);
    mapWindow.focus();
}

function popup(mylink, windowname, width, height) {
    if (!window.focus)
        return true;

    window.open(getPopupLink(mylink), windowname, (width != null && height != null ? 'width=' + width + ',height=' + height : "") + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes');
    return false;
}

function stopEventPropagation(event) {
    if (!event) var event = window.event;

    event.cancelBubble = true;
    if (event.stopPropagation) {
        event.stopPropagation();
    }
}

function popupAndStopPropagation(mylink, windowname, width, height, event) {
    if (!window.focus)
        return true;

    window.open(getPopupLink(mylink), windowname, (width != null && height != null ? 'width=' + width + ',height=' + height : "") + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes');
    stopEventPropagation(event);
    return false;
}

function popupAndStopPropagationWithFocus(mylink, windowname, width, height, event) {
   mapWindow=  window.open(getPopupLink(mylink), windowname, (width != null && height != null ? 'width=' + width + ',height=' + height : "") + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes');
   mapWindow.focus();
   stopEventPropagation(event);
   return false;
}


function getPopupLink(mylink){
    var href;

    if (typeof(mylink) == 'string')
        href = mylink;
    else
        href = mylink.href;

    //add popup param
    href = href + (href.indexOf("?") > 0 ? "&" : "?") + "isPopupAction=true";

    return href;
}

function isWholeNum(sValue)
{
    sIntValue = new String(parseInt(sValue));

    if (isNaN(sValue) || sIntValue.length != sValue.length) {
        return 0;
    }
    return 1;
}

/* Following function is used when checking if a submit button was already clicked once, in order to avoid
   double form submission.
*/
var submitButtonClicked = false;
function doCheckSubmission() {
    if (submitButtonClicked == false) {
        submitButtonClicked = true;
        return true;
    } else { //true - button was already was clicked; disable any other submition
        return false;
    }
}

function addPreSavedToMessageToHotel(message) {
    var messageToHotel = document.getElementById('messageToHotel').value;
    var messageToAdd = document.getElementById('msgToHotelSelection');

    if (messageToAdd.selectedIndex != 0) {
        if (messageToHotel != '') {
            messageToHotel += ". ";
        }
        messageToHotel += messageToAdd.options[messageToAdd.selectedIndex].text;
    }
    if (messageToHotel.length > 912) {
        alert(message);
    } else {
        document.getElementById('messageToHotel').value = messageToHotel;
    }
}

function addPreSavedToMessageToTravelers(message) {
    var messageToTravellers = document.getElementById('msgToTravellers').value;
    var messageToAdd = document.getElementById('msgToTravellersSelection');

    if (messageToAdd.selectedIndex != 0) {
        if (messageToTravellers != '') {
            messageToTravellers += " ";
        }
        messageToTravellers += messageToAdd.options[messageToAdd.selectedIndex].text;
    }
    if (messageToTravellers.length > 200) {
        alert(message);
    } else {
        document.getElementById('msgToTravellers').value = messageToTravellers;
    }
}

function daysBetween(date1, date2) {
    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24
    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()
    // Calculate the difference in milliseconds
    var difference_ms = date2_ms - date1_ms
    // Convert back to days and return
    return Math.round(difference_ms / ONE_DAY)
}

function indexOf(arr, value) {
    for (i = 0; i < arr.lenght; i++) {
        if (arr[i].value == value) {
            return i;
        }
    }
    return - 1;
}

//dates dropdowns related code
function HZICalendar(day, month, year) {
    var maxDay = 31;
    var minDay = 1;
    var maxMonth = 12;
    var minMonth = 1;
    var maxYear = 9999;
    var minYear = 1000;
    if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
        maxDay = 30;
    } else if (month == 2) {
        if ((year % 4 == 0) && ((year % 100 != 0)) || (year % 400 == 0)) {
            maxDay = 29;
        } else {
            maxDay = 28;
        }
    }
    if (day < minDay) {
        this.day = minDay;
    } else if (day > maxDay) {
        this.day = maxDay;
    } else {
        this.day = day;
    }
    if (month < minMonth) {
        this.month = minMonth;
    } else if (month > maxMonth) {
        this.month = maxMonth;
    } else {
        this.month = month;
    }
    if (year < minYear) {
        this.year = minYear;
    } else if (year > maxYear) {
        this.year = maxYear;
    } else {
        this.year = year;
    }
}

/*
 * This method adjustes the indate select fields to the nearest corect date and the outdate to be next to indate.
 */
function populateDateFields(form, inDateElement, outDateElement, userDateFormat) {
    populateDateFieldsWithVariableNumberOfDays(form, inDateElement, outDateElement, userDateFormat, 1);
}

/*
 * This method adjustes the indate select fields to the nearest corect date and the outdate to be next to indate.
 */
function populateDateFieldsWithAdjustment(form, inDateElement, outDateElement, userDateFormat) {
    var inDateFromForm = form.elements[inDateElement].value;
    var numericExpression = /^[0-9]{6}$/;
    if (inDateFromForm.match(numericExpression)) {
        //change outDate after in date only if the inDate is a valid date
        populateDateFieldsWithVariableNumberOfDays(form, inDateElement, outDateElement, userDateFormat, numberOfDays);
    }
}

/*
 * This method sets the out date to the indate + 1 and reset the number of days to 1
 */
function populateDateFieldsWithAdjustmentAndUpdateNumberOfDays(form, inDateElement, outDateElement, userDateFormat, nrOfDays) {
   var inDateFromForm = form.elements[inDateElement].value;
    var numericExpression = /^[0-9]{6}$/;
    if (inDateFromForm.match(numericExpression)) {
        //change outDate after in date only if the inDate is a valid date
        populateDateFieldsWithVariableNumberOfDays(form, inDateElement, outDateElement, userDateFormat, 1);
        form.elements[nrOfDays].value = 1;
    }
}

/*
 * This method adjustes the outdate to the corect date when adding a nr of days to the in date. validation of parameters is done
 */
function populateDateFieldsWithVariableNumberOfDaysWithAdjustment(form, inDateElement, outDateElement, userDateFormat, nrOfDays){
    var inDateFromForm = form.elements[inDateElement].value;
    var numericExpression = /[0-9]$/;
    var dateNumericExpression = /^[0-9]{6}$/;
    if (inDateFromForm.match(dateNumericExpression) && nrOfDays.match(numericExpression)) {
        //change outDate after in date only if the inDate  is a valid date and nrOfDays is a number
        populateDateFieldsWithVariableNumberOfDays(form, inDateElement, outDateElement, userDateFormat, nrOfDays);
    }
}

function getDateFromString(stringDate, userDateFormat){
    var dayStart, dayEnd, monthStart, monthEnd, yearStart, yearEnd;

    dayStart = userDateFormat.indexOf("d");
    dayEnd = userDateFormat.lastIndexOf("d") + 1;
    monthStart = userDateFormat.indexOf("M");
    monthEnd = userDateFormat.lastIndexOf("M") + 1;
    yearStart = userDateFormat.indexOf("y");
    yearEnd = userDateFormat.lastIndexOf("y") + 1;
    var dateMonthAsNumber = parseInt(stringDate.substring(monthStart, monthEnd), 10) - 1;

    var date = new Date(1970, 0, 1);
    date.setYear(stringDate.substring(yearStart, yearEnd));
    date.setMonth(dateMonthAsNumber.toString());
    date.setDate(stringDate.substring(dayStart, dayEnd));

    return date;
}

/*
 *  This method populates the numberOf days between two valid dates
 */
function populateNumberOfNightsBetweenDates(form, inDateElement, outDateElement, userDateFormat, nrOfDays){
    var inDateFromForm = form.elements[inDateElement].value;
    var outDateFromForm = form.elements[outDateElement].value;
    var dateNumericExpression = /^[0-9]{6}$/;

    if (inDateFromForm.match(dateNumericExpression)) {  //correct inDate date format
        var inDate = getDateFromString(inDateFromForm, userDateFormat);
        var outDate = getDateFromString(outDateFromForm, userDateFormat);

        if (inDate <= outDate){ //if out date is after in date then calculate the correct nr of nights value
            form.elements[nrOfDays].value = daysBetween(inDate, outDate);
        }
    }
}

/*
 * This method is used to construct the correct inDate and outDate for the date fields input.
 */
function populateDateFieldsWithVariableNumberOfDays(form, inDateElement, outDateElement, userDateFormat, nrOfDays) {
    var inDateFromForm = form.elements[inDateElement].value;
    var inDateElementAsString, outDateElementAsString;

    var dayStart, dayEnd, monthStart, monthEnd, yearStart, yearEnd;
    var numberOfDateFormat = getNumberOfDateFormat(userDateFormat);

    dayStart = userDateFormat.indexOf("d");
    dayEnd = userDateFormat.lastIndexOf("d") + 1;
    monthStart = userDateFormat.indexOf("M");
    monthEnd = userDateFormat.lastIndexOf("M") + 1;
    yearStart = userDateFormat.indexOf("y");
    yearEnd = userDateFormat.lastIndexOf("y") + 1;
    var inDateMonthAsNumber = parseInt(inDateFromForm.substring(monthStart, monthEnd), 10) - 1;

    var inDate = new Date(1970, 0, 1);
    inDate.setYear(inDateFromForm.substring(yearStart, yearEnd));
    inDate.setMonth(inDateMonthAsNumber.toString());
    inDate.setDate(inDateFromForm.substring(dayStart, dayEnd));

    var outDate = new Date(1970, 0, 1);
    outDate.setYear(inDate.getYear());
    outDate.setMonth(inDate.getMonth());
    outDate.setDate(inDate.getDate() + parseInt(nrOfDays));

    var inDateYear, inDateMonth, inDateDay, outDateYear, outDateMonth, outDateDay;
    inDateYear = "" + inDate.getYear();
    if (inDateYear.length == 1) {
        inDateYear = "0" + inDateYear;
    }

    inDateMonth = "" + (inDate.getMonth() + 1);
    if (inDateMonth.length == 1) {
        inDateMonth = "0" + inDateMonth;
    }

    inDateDay = "" + inDate.getDate();
    if (inDateDay.length == 1) {
        inDateDay = "0" + inDateDay;
    }

    outDateYear = "" + outDate.getYear();
    if (outDateYear.length == 1) {
        outDateYear = "0" + outDateYear;
    }

    outDateMonth = "" + (outDate.getMonth() + 1);
    if (outDateMonth.length == 1) {
        outDateMonth = "0" + outDateMonth;
    }

    outDateDay = "" + outDate.getDate();
    if (outDateDay.length == 1) {
        outDateDay = "0" + outDateDay;
    }
    
    switch (numberOfDateFormat) {
        case 0: // ddMMyy format
            inDateElementAsString = inDateDay + inDateMonth + inDateYear;
            outDateElementAsString = outDateDay + outDateMonth + outDateYear;
            break;
        case 1: // MMddyy format
            inDateElementAsString = inDateMonth + inDateDay + inDateYear;
            outDateElementAsString = outDateMonth + outDateDay + outDateYear;
            break;
        case 2: // yyMMdd format
            inDateElementAsString = inDateYear + inDateMonth + inDateDay;
            outDateElementAsString = outDateYear + outDateMonth + outDateDay;
            break;
    }

    form.elements[inDateElement].value = inDateElementAsString;
    form.elements[outDateElement].value = outDateElementAsString;
}

var numberOfDays = 1;
//end of dates dropdowns related code

//calendar
function showCalendar(obj, dateFormat, fromHotelSearchPage) {	
    if (self.gfPop) {
        var numberOfDateFormat = getNumberOfDateFormat(dateFormat);
      
        gfPop.setFromHotelSearchPage(fromHotelSearchPage);
        	
        gfPop.showPopCalendar(dateFormat, numberOfDateFormat, obj);
    }
    return false;
}

function showCalendarForDropdowns(day, month, year, dateFormat) {	
    var range = [[parseInt(year.options[0].value), 1, 1], [parseInt(year.options[year.options.length - 1].value), 12, 31]];
    var numberOfDateFormat = getNumberOfDateFormat(dateFormat);

    if (self.gfPop) {
        gfPop.showPopCalendarForDropdowns(dateFormat, numberOfDateFormat, day, month, year, range);
    }
    return false;
}

/* This method gets the right parameter for the user selected date format for showing the calendar
 * based on the selected date format by the user.
 *
 */
function getNumberOfDateFormat(dateFormat) {
    var numberOfDateFormat = 0;
    var dayStart, monthStart, yearStart;
    //determine the positions of "dd", "MM" and "YY" strings
    //maybe some error checking and message should be used; get *End also and if dayEnd != dayStart + 1
    dayStart = dateFormat.indexOf("d");
    monthStart = dateFormat.indexOf("M");
    yearStart = dateFormat.indexOf("y");

    //check to order in which "dd", "MM" and "yy" appear
    if (dayStart < monthStart && monthStart < yearStart) {
        numberOfDateFormat = 0; // ddMMyy format
    } else if (monthStart < dayStart && dayStart < yearStart) {
        numberOfDateFormat = 1; // MMddyy format
    } else if (yearStart < monthStart && monthStart < dayStart) {
        numberOfDateFormat = 2; // yyMMdd format
    } // else use the default value of 0 = ddMMyy format (see variable declaration)

    return numberOfDateFormat;
}

/* This method retreives a form base on it's name. First is searchses by id xhtml fashion then html.
 * @author George Cojocariu
 */
function formGet(formIdentifier) {
    //xhtml
    var form = document.getElementById(formIdentifier);
    //try by name
    if (form == null) {
        //html
        form = document.forms.namedItem(formIdentifier);
    }
    return form;
}

/* This method submits the specified form. It is intended to be called from an event from a html tag. If the form is not
 * found it returns false thus submition will not occur.
 * @author George Cojocariu
 */
function formSubmit(formIdentifier) {
    var result = true;
    var form = formGet(formIdentifier);

    if (form == null) {
        result = false;

    } else {
        form.submit();
    }

    return result;
}

/* This method submits the specified form with the specified action. It is intended to be called from an event from a
 * html tag. If the form is not found it returns false thus submition will not occur.
 * @author George Cojocariu
 */
function formSubmitAction(formIdentifier, action) {
    var result = true;
    var form = formGet(formIdentifier);

    if (form == null) {
        result = false;

    } else {
        form.action = action;
        if (form.onsubmit != null){
            form.onsubmit();
        }
        form.submit();
    }

    return result;
}

/* This method sets the attribute parameter with the value of the attributeValue and submits the specified form.
 * It is intended to be called from an event from a html tag. If the form is not found it returns false thus submition will not occur.
 * @author George Cojocariu
 */
function formSubmitAttributeAction(formIdentifier, attribute, attributeValue) {
    var result = true;
    var form = formGet(formIdentifier);

    if (form == null) {
        result = false;

    } else {
        form.elements[attribute].value = attributeValue;
        form.submit();
    }

    return result;
}

function formSubmitRedirectActionWithConfirmation(formIdentifier, confirmFunction, yesAction, noAction, isYesSubmit, isNoSubmit) {
    
	if (confirmFunction()) {
		//yesAction should be invoked
		
		if (isYesSubmit) {
			formSubmitAction(formIdentifier, yesAction);
		} else {
			window.location.href = yesAction;  
		}
    } else {
    	//noAction should be invoked
    	if (isNoSubmit) {
			formSubmitAction(formIdentifier, noAction);
		} else {
			window.location.href = noAction;  
		}
    }
}


/* This method submits the specified form with the specified action if user confirmed the displayed message. It is
 * intended to be called from an event from a html tag. If the form is not found it returns false thus submition will
 * not occur.
 * @author George Cojocariu
 */
function messageConfirmFormSubmitAction(message, formIdentifier, action) {
    var result = true;
    if (confirm(message)) {
        var form = formGet(formIdentifier);
        if (form != null) {
            form.action = action;
            form.submit();
        } else {
            result = false;
        }
    }
    return result;
}

/* This method submits the specified form with the specified action if specified confirm function returned true. It is
 * intended to be called from an event from a html tag. If the form is not found the submition will
 * not occur.
 */
function functionConfirmFormSubmitAction(confirmFunction, formIdentifier, action) {
    if (confirmFunction()) {
        var form = formGet(formIdentifier);
        if (form != null) {
            form.action = action;
            form.submit();
        }
    }
}

/*
* This method returns true if the given event is the enter key press.
*/
function checkEnterPressed(event) {
    var NS4 = (document.layers) ? true : false;
    var code = 0;
    var enterPressed = false;

    if (NS4)
        code = event.which;
    else
        code = event.keyCode;

    if (code == 13) {
        enterPressed = true;
    }

    return enterPressed;
}

/**
 * Executes the given javascript function if the enter button is pressed.
 * 
 * @param event the javascript event
 * @param executeFunction the javascript function that should be executed if the enter button is pressed
 */
function executeIfEnterPressed(event, executeFunction){
	if (checkEnterPressed(event)){
		executeFunction();
		return false;
	} else {
		return true;
	}
}

/* This method submits the specified form with the specified action. It is intended to be called from an event from a
 * html tag. If the form is not found it returns false thus submition will not occur.
 * @author George Cojocariu
 */
function formSubmitActionOnEnter(formIdentifier, event, action) {
    var result = true;

    if (checkEnterPressed(event)){
        var form = formGet(formIdentifier);

        if (form == null) {
            result = false;

        } else {
            form.action = action;
            form.submit();
        }
    } else {
        result = false;
    }

    return result;
}

/* This method submits the specified form with the specified action if enter is pressed and specified confirm function returned true. It is
 * intended to be called from an event from a html tag. If the form is not found it returns false thus submition will
 * not occur.
 */
function functionConfirmFormSubmitActionOnEnter(confirmFunction, formIdentifier, event, action){
    var result = true;

    if (checkEnterPressed(event) && confirmFunction()){
        var form = formGet(formIdentifier);

        if (form == null) {
            result = false;

        } else {
            form.action = action;
            form.submit();
        }
    } else {
        result = false;
    }

    return result;
}

function showElementById(newObjectId) {
    if (document.getElementById(newObjectId) != null) {
        document.getElementById(newObjectId).style.display = "";
    }
}

function hideElementById(newObjectId) {
    if (document.getElementById(newObjectId) != null) {
        document.getElementById(newObjectId).style.display = "none";
    }
}

function trim(source){
    return source.replace(/\s*$/, "");
}

function showHideElement(element, isShow){
    if (element != null){
        if (isShow){
            element.style.display = "";
        } else {
            element.style.display = "none";
        }
    }
}

/**
 * This method does the following things:
 *  -based on the showSection boolean shows or hides a section identified by sectionId.
 *  -hides the element identified by toHideElementId
 *  -shows the element identified by toShowElementId
 *
 * @param sectionId       A section identifier which should be collapsed/expanded.
 * @param toHideElementId An element identifier that should be hidden when showSection is true.
 * @param toShowElementId An element identifier that should be shown when showSection is true.
 * @param showSection     A boolean that decides when the sectionId should be shown or not
 *                        (true=>section expanded/shown; false=>section collapsed/hidden)
 */
function showHide(sectionId, toHideElementId, toShowElementId, showSection) {
    showHideElement(document.getElementById(sectionId), showSection);

    var toShowElement;
    var toHideElement;

    if (showSection) {
        toHideElement = document.getElementById(toHideElementId);
        toShowElement= document.getElementById(toShowElementId);
    } else {
        toShowElement = document.getElementById(toHideElementId);
        toHideElement= document.getElementById(toShowElementId);
    }

    if (toHideElement) {
        toHideElement.style.display = 'none';
    }

    if (toShowElement) {
        toShowElement.style.display = '';
    }
}

/**
 * Method does the same as method showHide from above; and after that it stops the event propagation
 *
 * @param sectionId       A section identifier which should be collapsed/expanded.
 * @param toHideElementId An element identifier that should be hidden when showSection is true.
 * @param toShowElementId An element identifier that should be shown when showSection is true.
 * @param showSection     A boolean that decides when the sectionId should be shown or not
 *                        (true=>section expanded/shown; false=>section collapsed/hidden)
 * @param event           The event that must be stopped
 */
function showHideAndStopPropagation(sectionId, toHideElementId, toShowElementId, showSection, event) {
    showHide(sectionId, toHideElementId, toShowElementId, showSection);

    stopEventPropagation(event);
    return false;
}

/**
 * Method toogles a section and expandes or copapses it
 * @param section           - section
 * @param sectionExpand     - expanded section
 * @param sectionColapse    - colapsed section
 */
 function toogleSection(section, sectionExpand, sectionColapse){

    var isDisplayedSection = document.getElementById(section).style.display;

    if (isDisplayedSection == "none"){
        showHide(section, sectionExpand, sectionColapse, true);
    } else {
        showHide(section, sectionExpand, sectionColapse, false);
    }
    return false;
}

/**
 * Displays the content container loading indicator.
 */
function showContentContainerLoadingIndicator(){
    document.getElementById("contentContainer").style.visibility = "hidden";
    document.getElementById('loadingIndicatorImage').style.visibility = 'visible';
}

/**
 * Hiddes the content container loading indicator.
 */
function hiddeContentContainerLoadingIndicator(){
    document.getElementById('loadingIndicatorImage').style.visibility = 'hidden';
    document.getElementById("contentContainer").style.visibility = "visible";
}

/**
 * The function selects the first option in the combo who's text starts with the given search text.
 * The string comparison is case insensitive.  
 *
 * @param combo the combo that should be searched
 * @param searchText the search text
 * @param whiteCharacter character that can be found at the begining of the combo values and which is ignored at search
 *         eg. if one of the combo's value is "+Valorinta/Ville", the value should be found when seaching the searchText starting with "v" letter
 */
function findComboOptionByStartingString(combo, searchText, whiteCharacter){
    var foundIndex = -1;
    var currentIndex = 0;
    var optionsList = combo.options;
    var text = searchText.toLowerCase();

    while (currentIndex < optionsList.length && foundIndex == -1){
        if (optionsList[currentIndex].text.toLowerCase().replace(whiteCharacter, "").indexOf(text) == 0) {
            foundIndex = currentIndex;
        }
        currentIndex++;
    }

    if (foundIndex > 0){
        combo.selectedIndex = foundIndex;
    } else {
       combo.selectedIndex = 0;
    }
}

/**
 * The function selects the first option in the combo who's text has a word that starts with the given search text.
 * The string comparison is case insensitive.
 *
 * @param combo the combo that should be searched
 * @param searchText the search text
 * @param highlightMatches indicates if the found matches should be highlighted
 */
function findComboOptionByWord(combo, searchText, highlightMatches){
    var foundIndex = -1;
    var currentIndex = 0;
    var optionsList = combo.options;
    var text = searchText.toLowerCase();

    while (currentIndex < optionsList.length && (foundIndex == -1 || highlightMatches)){
        var words = optionsList[currentIndex].text.toLowerCase().split(" ");

        var hasMatch = false;
        if (text.length > 0){
            for (var i=0; i < words.length; i++){
                if (words[i].indexOf(text) == 0) {
                    foundIndex = (foundIndex == -1 ? currentIndex : foundIndex);
                    hasMatch = true;
                }
            }
        }

        if (highlightMatches){
            if (hasMatch){
                optionsList[currentIndex].style.backgroundColor = "#dfdfe3";
            } else {
                optionsList[currentIndex].style.backgroundColor = "#ffffff";
            }
        }

        currentIndex++;
    }

    if (foundIndex > 0){
        combo.selectedIndex = foundIndex;
    } else {
       combo.selectedIndex = 0;
    }
}

/**
 * The function schedules the given event string to be executed after the given timeout and stores the obtained timeout
 * id in the eventTimeoutId variable. If the eventTimeoutId is greater then 0 it canceles the event with the eventTimeoutId
 * before schedueling the new event to be executed.
 *
 * @param eventString the event function that needs to be scheduled
 * @param timeout the timeout after which the event should be executed
 */
var eventTimeoutId = 0;
function scheduleEvent(eventString, timeout){
    if (eventTimeoutId > 0){
        clearTimeout(eventTimeoutId);
    }

    eventTimeoutId = setTimeout(eventString, timeout);
}

/**
 * This javascript function is called to enable or disable the specified form fields
 *
 * @param fields the form fields list
 * @param isEnabled
 */
function enableDisableFields(fields, isEnabled){
     for (var i = 0; i < fields.length; i++){
        fields[i].disabled = !isEnabled;
    }
}

/**
 * This functions shows the message given as parameter
 *
 * @param message The message to show
 */
function showMessage(message) {
    if (message != null && message.length > 0) {
        alert(message);
    }
}
/**
 * This function dynamically loads the javascript url specified  
 *
 * @param url  
 * @return
 */
function loadScript(url) {
	var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript= document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src = url;
    oHead.appendChild(oScript);
  }

function disableEnterKey(evt) { 
	  var evt = (evt) ? evt : ((event) ? event : null); 
	  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
	  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
} 

/**
 * Adds a track event with the given name. The function should be used to track javascript events.
 * 
 * @param eventName the event name
 */
function trackEvent(eventName){
	if (typeof trackJavascriptEvent == 'function'){
		trackJavascriptEvent(eventName);
	}
}

function toggleDisabled(el) {
    try {
        el.disabled = !el.disabled;
    } catch(E){}

    if (el.childNodes && el.childNodes.length > 0) {
        for (var x = 0; x < el.childNodes.length; x++) {
            toggleDisabled(el.childNodes[x]);
        }
    }
}
