/*
################################################################################
#  Copyright (c) 2001 EDS. All Rights reserved.
################################################################################
#
#  NAME OF FILE:      		hzilib.js
#
################################################################################
*
*/


var mapWindow;
function openMapWindow(zonAction, mapWidth, mapHeight) {

    var winWidth = parseInt(mapWidth) + 50;
    var winHeight = parseInt(mapHeight) + 80;

    var prop = "menubar=no,status=no,resizable=yes,scrollbars=yes,width=" + winWidth.toString() + ",height=" + winHeight.toString();
    mapWindow = window.open(zonAction, "_NEW", prop);
    mapWindow.focus();
}

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(zonAction, "_NEW", prop);
    mapWindow.focus();
}

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) {
    populateDateFieldsWithVariableNumberOfDays(form, inDateElement, outDateElement, userDateFormat, numberOfDays);
}

/*
 * 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() + 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) {
    if (self.gfPop) {
        var numberOfDateFormat = getNumberOfDateFormat(dateFormat);

        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;
        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;
}

/* 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 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;
}

/* 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;
}

function showElementById(newObjectId) {
    document.getElementById(newObjectId).style.display = "";
}

function hideElementById(newObjectId) {
    document.getElementById(newObjectId).style.display = "none";
}

function showHideElement(element, isShow){
    if (element != null){
        if (isShow){
            element.style.display = "";
        } else {
            element.style.display = "none";
        }
    }
}

/**
 * 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";
}

function popup(mylink, windowname, width, height) {
    if (!window.focus)
        return true;

    var href;
    if (typeof(mylink) == 'string')
        href = mylink;
    else
        href = mylink.href;

    window.open(href, windowname, 'width=' + width + ',height=' + height + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes');
    return false;
}

/**
 * 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 confirmMessage(message) {
    if (message != null && message.length > 0) {
        alert(message);
    }
}

/**
 * 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);
	}
}
