// additional line
// DESCRIPTION AND CHANGE LOG
// n-search-common1.js - functions needed to set up (new) search form
//   * 070214 major rework, combined n-common & common-newgui & n-from-memory  & n-common-group & n-hideshow & date-fields, renamed functions, removed redundant code

// function ta - external functions
// function ta_childrenChange(formNumber) - [..] reacts to search form children count changes
// function ta_closeLayer(iFrameId,layerId) - [layers_kohde] closes dynamic iframe layer
// function ta_fillInStoredValuesEmDestination(containsMiddle, onlyMiddle) - [include-body-tag] sets date and traveller and room fields for both search and group forms
// function ta_getValue(selectField) - [em_destination,n-date-picker,this] returns field value or selected option value
// function ta_groupChange(saveElement, formNumber) - [..] validates group and changes room options arrays (count and settling) if needed
// function ta_hideLayer(layer) - [include_nlimited_group_layers,search_criteria_stripe] hides layer using MM_showHideLayers
// function ta_openLayer(iFrameId,layerId,url) - [transport_x] opens dynamic iframe layer
// function ta_roomChange(formNumber) - [search_criteria_nall] reacts to search form room count changes
// function ta_saveAreaValue() - [search-criteria-nall,n-include-accommodation-menu,search-criteria-nlimited] saves ts_area, ts_dest (and ts_accommodation) and handles destination menu
// function ta_saveCurrent(formNumber) - [search-criteria-nlimited,..] saves traveller counts, room count and settling to cookies
// function ta_saveDepStationValue() - [include-dep-station-selection] saves ts_dep_stations into cookies with brand
// function ta_saveIataValue() - [search_criteria_nflights] saves ts_iata into cookies with brand
// function ta_saveValue(element) - [search_criteria_nall] stores element value into cookies, supports multiple different field types
// function ta_searchBodyOnLoadForTwo(containsMiddleFormValue, onlyMiddleFomrvalue) - [em_destination_group, em_destionation, search_criteria_stripe] EM spesific call, which sets up boolean values which tell if page contains more than one search tool. Calls ta_searchBodyOnLoad()
// function ta_searchBodyOnLoad() - [search_criteria_nall,search_criteria_ncampaign,search_criteria_nflights,search-criteria-nlimited] sets initial values to search form and makes selections according to info stored in cookies,  extensivity of search body on load is controlled with a number of flags
// function ta_setA_day(selectElement, justSet) - [n-include-date-field-start] updates B day according to A day change and if ta_latest_in_use defined then also B day&month
// function ta_setA_month(selectElement, justSet) - [n-include-date-field-start] updates A day according to A month change and if ta_latest_in_use defined then also B day&month
// function ta_setB_day(selectElement, justSet) - [n-include-date-field-end] validates A day/month after B day change
// function ta_setB_month(selectElement, justSet) - [n-include-date-field-end] validates A day/month after B month change
// function ta_setEarly(elementDay, elementMY, YYYYMMDD) - [n-date-picker] parses YYYYMMDD input and uses ta_setA_month and ta_setA_day to update date fields accordingly
// function ta_setLatest(elementDay, elementMY, YYYYMMDD) - [n-date-picker] set B daymonth
// function ta_setLengthOption(selectedName, form) - [search-criteria-nlimited,nbrocure] sets hidden lenght option variable to true from form drop down menu (in other words this simulates old search form/extended search form when we are using new more compact or restricted forms)
// function ta_updateDependent(prefix, from, to) - [search-criteria-nall,search-criteria-nlimited,nbrochure] updates destination list according to selected area, or accommodation list according to selected destination
// function ta_reset_form(form) - [search_criteria_nall,search_criteria_nflights] resets search form to default values
// function ta_updateCalendar(varPrefix, form.depStation, form.out_dep_date, calendar div) - used on nbrochure for dynamic calendar generation, requires ta_search_window_diffs to be set


// function _tad - internal date functions
// function _tad_getDay(dayFromBeginning) - [this] returns day part from dayFromBeginning index
// function _tad_getDayFromBeginning(dayIndex, monthIndex) - [this] returns dayFromBeginning index compared to base date ie. how many days is this after base date
// function _tad_getMonth(dayFromBeginning) - [this] returns month part from dayFromBeginning index
// function _tad_formatDate(day, month, year) - [this] returs date in D.M.YYYY format
// function _tad_formatDate(dayFromBeginning) - [this] returs date in D.M.YYYY format
// function _tad_getWeekdayPointer(monthIndex) - [this] returns weekday index for 1st of given month
// function _tad_renderDateFields() - [this] updates date fields according to intrinsic date variables in search and group forms
// function _tad_updateDaysAOptions(form) - [this] rebuilds A day options array to show correct day abbreviations
// function _tad_updateDaysBOptions(form) - [this] rebuilds B day options array to show correct day abbreviations
// function _tad_updateMonthAOptions(form) - [this] selects ta_month_a index of month A options array and deselects other items
// function _tad_updateMonthBOptions(form) - [this] selects ta_month_b index of month B options array and deselects other items
// function _tad_setDateValue(elementDay, elementMY, dateText, earliest) - [this] sets given date to given day and month-year elements. Supports YYYYMMDD and DD formats (Months unchanged on DD).

// function _tam - internal memory functions
// function _tam_GetCookie(name) - [this] gets sub value for key from cookie
// function _tam_fillAccValue() - [this] checks javascript support and fills branded ts_accommodation
// function _tam_fillAreaValue() - [this] checks javascript support and fills branded ts_area
// function _tam_fillDepStationVal() - [this] checks javascript support and fills branded ts_dep_station
// function _tam_fillDestValue() - [this] checks javascript support and fills branded ts_dest
// function _tam_fillIataValue() - [this] fills branded ts_iata
// function _tam_fillSavedValues() - [this] fill rest of saved values (star, env, price and attributes)
// function _tam_fillDynamicRoomStructure() [this] builds room structure inner html
// function _tam_fillGroupValues() - [this] fills person fields, updates room max counts accordingly and selects chosen room count (for each form)
// function _tam_fillLengthOption() - [this] fills length options
// function _tam_fillInStoredDateFields() - [this] retrieves ta_day_a,ta_month_a from cookies from specific keys
// function _tam_fillWithBrandByValue(element, onlyParam) - [this] sets field with branded value, in case of selects compares values
// function _tam_getAbsoluteCookie(name) - [this] gets master cookie containing all key->value pairs
// function _tam_removeCookie(name) - [this] removes sub key from cookie
// function _tam_saveDateValues() - [this] saves ta_day_a,ta_month_a,ta_day_b,ta_month_b to cookies with specific keys
// function _tam_saveWithBrandByValue(element) - [this] finds element value and sets brand+elementname->value to cookie, in case of select elements, actual value is stored
// function _tam_setAbsoluteCookie(name, value) - [this] sets master cookie containing all key->value pairs to relevant paths
// function _tam_setCookie(name, value) - [this] sets sub key-value into cookie
// function _tam_getParam(name) - [this] get parameter value from query

// function _tao - internal other functions, utility functions
// function _tao_LTrim(strValue) - [this] trims spaces from left
// function _tao_RTrim(strValue) - [this] trims spaces from right
// function _tao_Trim(strValue) - [this] trims from both sides
// function _tao_empty(selectField) - [this] empties given select input field
// function _tao_flagInitialized() - [this] sets initialized flag to true, used to recognize if form was initialized correctly
// function _tao_getIndexFromSelect(selectElement) - [this] returns index for given select form element or -1 if not chosen
// function _tao_getFullElementName(element) - [this] returns element full name

// function _tau - internal update functions
// function _tau_buildDynamicRoomChoiceArea(cbCtrl, roomChoices) - [this] builds room settling selection HTML
// function _tau_checkForUpdate(formNumber) - [this] compares form values to those internally kept and flags room or settling updates
// function _tau_checkGroupValidity(formNumber) - [this] checks traveller total counts and alerts if needed
// function _tau_genRoomRows(firstRoom, secondRoom, thirdRoom, checked, formNumber) - [this] builds individua room HTML
// function _tau_getChildCount(formNumber) - [em_destination,this] updates total count according to sum counts
// function _tau_getChoiceRowCloseTag() - [this] returns some HTML element
// function _tau_getChoiceRowOpenTag() - [this] returns some HTML element
// function _tau_refreshFormHolder() - [this] initializes layer names and page structure to internal variables
// function _tau_revertChildCounts(formNumber) - [this] reverts (some) saved values to child fields
// function _tau_setChildrenCounts(formNumber) - [this] updates children sub count according to the total count
// function _tau_setupDateFields() - [this] builds search and group date fields and fetches selections from cookies
// function _tau_updateRSIfNeeded(formNumber) - [this] updates room counts options and room settling options if needed
// function _tau_updateRooms(aCtrl, rmCtrl) - [this] updates room counts array according to chosen adult count
// function _tau_updateRoomsList(adCnt1, cdCnt1, rmCnt1, sectionId, formNumber) - [this] builds different room settlings for different groups
// function _tau_updateSettling(sectionId,formNumber) - [this] updates settlings for given form id
// function _tau_set_selected(select, index) - [this] updates selected index on select (form input) if select exists and index is different. Also calls onchange() for select.
// function _tau_set_checked(checkbox, checked) - [this] updates checked on checkbox if checked value is different. Also calls onchange() for checkbox.
// function _tau_set_text(text, value) - [this] updates value on text field if field value is different. Also calls onchange() for text field.
// function _tau_binSearch(arr, value) - [this] binary search, array must be in natural order

// weekdays for day lists
var ta_day_names = new Array(" (ma)", " (ti)", " (ke)", " (to)", " (pe)", " (la)", " (su)");

// form info holders
var ta_cur_adults = new Array(-2,-2);
var ta_cur_w_children = new Array(-1,-1);
var ta_cur_c_2 = new Array(-1,-1);
var ta_cur_cg1 = new Array(-1,-1);
var ta_cur_cg2 = new Array(-1,-1);
var ta_cur_cg3 = new Array(-1,-1);
var ta_cur_cg4 = new Array(-1,-1);
var ta_cur_length = new Array(-1,-1);
var ta_cur_totalCh = new Array(-1,-1);
var ta_cur_rooms = new Array(-1,-1);
var ta_cur_setting = new Array(-1,-1);

var ta_upd_rooms = false;
var ta_upd_settling = false;

// element id or name holders
var page_forms = new Array();
var room_containers = new Array('room_layer_options_top', 'room_layer_options');
var room_layers = new Array('room-layer-top', 'room-layer-middle');
var child_layers = new Array('lapset-layer-top','lapset-layer-middle');

function ta_searchBodyOnLoad() {
    ta_searchBodyOnLoadImpl(true,false,false);
}

function ta_searchBodyOnLoadImpl(containsSearchForm, containsMiddleForm, containsRightForm) {
    // initialize form arrays to know which forms to update
    _tau_refreshFormHolder(containsSearchForm, containsMiddleForm, containsRightForm);

    if(!page_forms || page_forms.length == 0)
        return; // no need to do anything more

    if(document.searchForm) {
        // set dep station
        _tam_fillDepStationVal();
    }

    if (ta_adaEn) {
        // build area menu
        ta_updateDependent('Ar',null,document.searchForm.ts_area);
        // set area id
        _tam_fillAreaValue();
        // build dest menu
        ta_updateDependent('De',document.searchForm.ts_area,document.searchForm.ts_dest);
        // set dest id
        _tam_fillDestValue();
        if (ta_accEn) {
            // build acc menu
            ta_updateDependent('Ac',document.searchForm.ts_dest,document.searchForm.ts_accommodation);
            _tam_fillAccValue();
        }
    }
    if (ta_iataEn) {
        _tam_fillIataValue();
    }

    if (ta_dateFieldsEn && document.searchForm) {
        // build date menu
        _tau_setupDateFields();
        ta_updateDependent('Mo',null,document.searchForm.ts_out_earliest_my);
        // set date fields
        _tam_fillInStoredDateFields();
        // build calendar
        ta_updateCalendar('OdsMoDa', document.searchForm.ts_dep_station, document.searchForm.ts_out_earliest_my, 'calendar_table');
    }

    // fill per value
    _tam_fillGroupValues();
    // build length menu
    if(document.searchForm) {
        ta_updateDependent('Le',null,document.searchForm.ts_length);
    }
    // fill length options
    _tam_fillLengthOption();
    // fill rest
    _tam_fillSavedValues();

    // set up dynamic room structure
    if (containsMiddleForm || containsRightForm) {
        _tam_fillDynamicRoomStructure(true);
    } else {
        _tam_fillDynamicRoomStructure(false);
    }

    initialized = true; //enable search
    _tao_flagInitialized();
    ta_saveCurrent(0);
    enableButton();
    return;
}

function enableButton() {
    var button = document.getElementById("ts_searchButton");
    if(button) {
        button.innerHTML = '<img border="0" alt="ok" src="/tripsearch/'+nresources+'/images/buttons/hae.gif"/>';
        searchEnabled = true;
        button = document.getElementById("ts_searchButton2");
        if(button)
            button.innerHTML = '<img border="0" alt="ok" src="/tripsearch/'+nresources+'/images/buttons/hae.gif"/>';
    }
}

function disableButton() {
    var button = document.getElementById("ts_searchButton");
    if(button) {
        button.innerHTML = '<img border="0" alt="ok" src="/tripsearch/'+nresources+'/images/buttons/hae_disabled.gif"/>';
        searchEnabled = false;
        button = document.getElementById("ts_searchButton2");
        if(button)
            button.innerHTML = '<img border="0" alt="ok" src="/tripsearch/'+nresources+'/images/buttons/hae_disabled.gif"/>';
    }
}

// ensures that rooms options array has enought rooms
function _tau_updateRoomCountMax() {
    _tau_checkGroupValidity(0);
    _tau_updateRooms(page_forms[0].ts_adults, page_forms[0].ts_ch_2, page_forms[0].ts_room_count, page_forms[0].ts_room_combinations, null);
}

// method which parses the dynamic innerhtml of new gui room structure, be it in a layer or embedded into the search tool
// The functions are designed to work on brochure pages where there are more than one search form on page, the number 0 points
// to the first form, which is always on any page which contains search form. Index number 1 will point to the brochure page
// "middle form" which is used to set up the group structure.
function _tam_fillDynamicRoomStructure(containsMiddleForm) {
    _tau_updateSettling(room_containers[0], 0);
    if(containsMiddleForm) {
       _tau_updateSettling(room_containers[1], 1);
    }
    for (var i=0;i<page_forms.length;i++) {
        _tam_saveWithBrandByValue(page_forms[i].ts_room_combinations);
    }
}

function _tao_flagInitialized() {
    if(document.searchForm.initialized) {
        document.searchForm.initialized.value = "true";
    }
}

function ta_updateDependent(prefix, from, to) {
    if(!to || !to.options || !eval("window." + prefix + "Nkaikki"))
        return;
    var selValues = new Array(); // array of selected values
    if(!from || !from.options || from.selectedIndex == -1 || from.options[from.selectedIndex].value == "kaikki") {
        selValues.push("kaikki");
    } else if(from.type == "select-one") {
        selValues.push(from.options[from.selectedIndex].value);
    } else {
        for(var i = 0 ; i < from.options.length ; i++) {
            if(from.options[i].selected)
                selValues.push(from.options[i].value);
        }
    }

    if(selValues.length > 0) {
        var names, values;
        // values for selected
        if(selValues.length == 1) {
            // Only one selected, ids are optional
            names = eval(prefix + "N" + selValues[0]);
            values = eval("window." + prefix + "I" + selValues[0]);
            if(!values || (values.length == 0 && names.length != 0)) {
                values = new Array();
                for(var i = 0 ; i < names.length ; i++) {
                    values.push(i.toString());
                }
            }
        } else {
            // Multi select
            names = new Array();
            values = new Array();
            for(var i = 0 ; i < selValues.length ; i++) {
                names = names.concat(eval(prefix + "N" + selValues[i]));
                values = values.concat(eval(prefix + "I" + selValues[i]));
            }
        }

        // filter
        var depStationSelect = document.searchForm.ts_dep_station;
        var selectedDepStation = (depStationSelect && depStationSelect.selectedIndex != -1) ? depStationSelect.options[depStationSelect.selectedIndex].value : "kaikki";
        var validValues = eval("window.Ods" + prefix + "I" + selectedDepStation);
        if(validValues) {
            var newNames = new Array();
            var newValues = new Array();
            for(var i = 0 ; i < values.length; i++) {
                var value = values[i];
                if(_tau_binSearch(validValues, value) >= 0) {
                    newNames.push(names[i]);
                    newValues.push(value);
                }
                //for(j = 0 ; j < validValues.length; j++) {
                //    if(value == validValues[j]) {
                //        newNames.push(names[i]);
                //        newValues.push(value);
                //        break;
                //    }
                //}
            }
            names = newNames;
            values = newValues;
        }

        // add fixed
        var fixedNames = eval("window." + prefix + "Nfixed");
        if(fixedNames && fixedNames.length > 0)
            names = fixedNames.concat(names);
        var fixedValues = eval("window." + prefix + "Ifixed");
        if(fixedValues && fixedValues.length > 0)
            values = fixedValues.concat(values);

        var newLength = values.length;
        var oldLength = to.options.length;

        _tao_empty(to);

        for(var i = 0; i < newLength; i++) {
            var name = names[i];
            value = values[i];
            var newOption = new Option(name,value,false,false);
            to.options[i] = newOption;
        }
        if(from && from.selectedIndex != -1)
            to.selectedIndex = 0;
    }
}

function ta_saveDepStationValue() {
    _tam_saveWithBrandByValue(document.searchForm.ts_dep_station);
}

function ta_saveAreaValue() {
    _tam_saveWithBrandByValue(document.searchForm.ts_area);
    _tam_saveWithBrandByValue(document.searchForm.ts_dest);
    if (ta_accEn) {
        _tam_saveWithBrandByValue(document.searchForm.ts_accommodation);
    }
}

function ta_saveIataValue() {
    _tam_saveWithBrandByValue(document.searchForm.ts_iata);
}

function ta_saveValue(element) {
    _tam_saveWithBrandByValue(element);
}

function _tam_fillDepStationVal() {
    _tam_fillWithBrandByValue(document.searchForm.ts_dep_station);
}

function _tam_fillAreaValue() {
    _tam_fillWithBrandByValue(document.searchForm.ts_area);
}

function _tam_fillIataValue() {
    _tam_fillWithBrandByValue(document.searchForm.ts_iata);
}

function _tam_fillDestValue() {
    _tam_fillWithBrandByValue(document.searchForm.ts_dest);
}

function _tam_fillAccValue() {
    _tam_fillWithBrandByValue(document.searchForm.ts_accommodation);
}

function _tam_fillSavedValues() {
    // fill star values
    _tam_fillWithBrandByValue(document.searchForm.ts_one_two_stars);
    _tam_fillWithBrandByValue(document.searchForm.ts_three_stars);
    _tam_fillWithBrandByValue(document.searchForm.ts_four_stars);
    _tam_fillWithBrandByValue(document.searchForm.ts_five_stars);
    // fill environment values
    _tam_fillWithBrandByValue(document.searchForm.ts_one_envr);
    _tam_fillWithBrandByValue(document.searchForm.ts_two_envr);
    _tam_fillWithBrandByValue(document.searchForm.ts_three_envr);
    // fill price
    _tam_fillWithBrandByValue(document.searchForm.ts_max_price);
    // acc and dest attributes
    var elements = document.searchForm.elements;
    var len = elements.length;
    for(var i = 0 ; i < len ; i++) {
        var element = elements[i];
        if(element.type == "checkbox") {
            var nameStart = element.name.substring(0, 5);
            if((nameStart == "tade_") || (nameStart == "taac_"))
                _tam_fillWithBrandByValue(element);
        }
    }
}

function _tam_saveDateValues() {
    _tam_setCookie(ta_brand + "js_var_da", ta_day_a);
    _tam_setCookie(ta_brand + "js_var_db", ta_day_b);
    _tam_setCookie(ta_brand + "js_var_ma", ta_month_a);
    _tam_setCookie(ta_brand + "js_var_mb", ta_month_b);
    _tam_saveWithBrandByValue(document.searchForm.ts_base_month);
    _tam_saveWithBrandByValue(document.searchForm.ts_base_year);
}
function _tam_fillInStoredDateFields() {
    if (document.images) { // only do it in JavaScript 1.1 browsers
        // the order is determined here
        // _use_ the new Number because otherwise IE will handle variables as Strings, not Numbers!
        var temp = _tam_getParam("js_var_da");
        if(!temp)
            temp = _tam_GetCookie(ta_brand + "js_var_da");
        if (temp)
            ta_day_a = parseInt(temp);
        temp = _tam_getParam("js_var_ma");
        if(!temp)
            temp = _tam_GetCookie(ta_brand + "js_var_ma");
        if (temp)
            ta_month_a = parseInt(temp);
        temp = _tam_getParam("js_var_db");
        if(!temp)
            temp = _tam_GetCookie(ta_brand + "js_var_db");
        if (temp)
            ta_day_b =parseInt(temp);
        temp = _tam_getParam("js_var_mb");
        if(!temp)
            temp = _tam_GetCookie(ta_brand + "js_var_mb");
        if (temp)
            ta_month_b = parseInt(temp);
        var savedBaseMonth = _tam_getParam("ts_base_month");
        if(!savedBaseMonth)
            savedBaseMonth = _tam_GetCookie(ta_brand + "ts_base_month");
        var savedBaseYear = _tam_getParam("ts_base_year");
        if(!savedBaseYear)
            savedBaseYear = _tam_GetCookie(ta_brand + "ts_base_year");
        if(savedBaseMonth && savedBaseYear) {
            var currBaseMonth = document.searchForm.ts_base_month.value;
            var currBaseYear = document.searchForm.ts_base_year.value;
            if(currBaseMonth != savedBaseMonth || currBaseYear != savedBaseYear) {
                savedBaseMonth = parseInt(savedBaseMonth);
                savedBaseYear = parseInt(savedBaseYear);
                currBaseMonth = parseInt(currBaseMonth);
                currBaseYear = parseInt(currBaseYear);
                var monthDiff = savedBaseMonth - currBaseMonth + (savedBaseYear - currBaseYear) * 12;
                ta_month_a += monthDiff;
                ta_month_b += monthDiff;
            }
        }
        ta_month_a = Math.max(0, Math.min(ta_month_a, ta_m_len.length - 1));
        ta_month_b = Math.max(0, Math.min(ta_month_b, ta_m_len.length - 1));
        ta_day_a = Math.max(0, Math.min(ta_day_a, ta_m_len[ta_month_a] - 1));
        ta_day_b = Math.max(0, Math.min(ta_day_b, ta_m_len[ta_month_b] - 1));
        _tad_renderDateFields();
        _tam_saveDateValues();
    }
}

function _tam_fillLengthOption() {
    var paramSet = (_tam_getParam("ts_all_lengths") || _tam_getParam("ts_weekend") ||_tam_getParam("ts_fivedays") ||_tam_getParam("ts_week") ||_tam_getParam("ts_two_weeks") ||_tam_getParam("ts_ten_days") ||_tam_getParam("ts_over_two_weeks"));
    for (var i=0;i<page_forms.length;i++) {
        var form = page_forms[i];
        if(form.ts_length) {
            // all length elements are hidden inputs
            if(_tam_fillWithBrandByValue(form.ts_all_lengths, paramSet) && form.ts_all_lengths.value == "true") {
                ta_setLengthOption(form.ts_all_lengths.name);
            } else if(_tam_fillWithBrandByValue(form.ts_weekend, paramSet) && form.ts_weekend.value == "true") {
                ta_setLengthOption(form.ts_weekend.name);
            } else if(_tam_fillWithBrandByValue(form.ts_fivedays, paramSet) && form.ts_fivedays.value == "true") {
                ta_setLengthOption(form.ts_fivedays.name);
            } else if(_tam_fillWithBrandByValue(form.ts_week, paramSet) && form.ts_week.value == "true") {
                ta_setLengthOption(form.ts_week.name);
            } else if(_tam_fillWithBrandByValue(form.ts_two_weeks, paramSet) && form.ts_two_weeks.value == "true") {
                ta_setLengthOption(form.ts_two_weeks.name);
            } else if(_tam_fillWithBrandByValue(form.ts_ten_days, paramSet) && form.ts_ten_days.value == "true") {
                ta_setLengthOption(form.ts_ten_days.name);
            } else if(_tam_fillWithBrandByValue(form.ts_over_two_weeks, paramSet) && form.ts_over_two_weeks.value == "true") {
                ta_setLengthOption(form.ts_over_two_weeks.name);
            } else {
                document.searchForm.ts_length.selectedIndex = 0;
                ta_setLengthOption();
            }
        } else {
            // all length elements are checkboxes
            var set = false;
            set = (_tam_fillWithBrandByValue(form.ts_all_lengths, paramSet) && form.ts_all_lengths.checked) || set;
            set = (_tam_fillWithBrandByValue(form.ts_weekend, paramSet) && form.ts_weekend.checked) || set;
            set = (_tam_fillWithBrandByValue(form.ts_fivedays, paramSet) && form.ts_fivedays.checked) || set;
            set = (_tam_fillWithBrandByValue(form.ts_week, paramSet) && form.ts_week.checked) || set;
            set = (_tam_fillWithBrandByValue(form.ts_two_weeks, paramSet) && form.ts_two_weeks.checked) || set;
            set = (_tam_fillWithBrandByValue(form.ts_ten_days, paramSet) && form.ts_ten_days.checked) || set;
            set = (_tam_fillWithBrandByValue(form.ts_over_two_weeks, paramSet) && form.ts_over_two_weeks.checked) || set;
            if(!set) {
                if(form.ts_all_lengths) {
                    form.ts_all_lengths.checked = true;
                } else if(form.ts_week) {
                    form.ts_week.checked = true;
                } else if(form.ts_two_weeks) {
                    form.ts_two_weeks.checked = true;
                }
            }
        }
    }
}

function ta_setLengthOption(selectedName, form) {
    if(!form)
        form = document.searchForm;
    var lengthOptions = new Array(form.ts_all_lengths,form.ts_weekend,form.ts_fivedays,form.ts_week,form.ts_ten_days,form.ts_two_weeks,form.ts_over_two_weeks);
    if(!selectedName) {
        selectedName = form.ts_length.options[form.ts_length.selectedIndex].value;
    } else {
        for(var i=0 ; i < form.ts_length.options.length ; i++) {
            if(form.ts_length.options[i].value == selectedName) {
                form.ts_length.selectedIndex = i;
                break;
            }
        }
        if(form.ts_length.selectedIndex == -1)
            form.ts_length.selectedIndex = 0;
    }
    for(var i=0;i<lengthOptions.length;++i) {
        var lengthOption = lengthOptions[i];
        if(lengthOption) {
            if(lengthOption.name == selectedName) {
                lengthOption.value = "true";
            } else {
                lengthOption.value = "";
            }
            _tam_saveWithBrandByValue(lengthOption);
        }
    }
}

// fills person fields, updates room max counts accordingly and selects chosen room count (for each form)
function _tam_fillGroupValues() {
    for (var i=0;i<page_forms.length;i++) {
        _tam_fillWithBrandByValue(page_forms[i].ts_adults);
        _tam_fillWithBrandByValue(page_forms[i].ts_ch_2);
        _tam_fillWithBrandByValue(page_forms[i].ts_ch_gr1);
        _tam_fillWithBrandByValue(page_forms[i].ts_ch_gr2);
        _tam_fillWithBrandByValue(page_forms[i].ts_ch_gr3);
        _tam_fillWithBrandByValue(page_forms[i].ts_ch_gr4);
        _tam_fillWithBrandByValue(page_forms[i].children_total);
    }
    if(page_forms[0])
        _tau_checkGroupValidity(0);
    for (var i=0;i<page_forms.length;i++) {
        _tau_updateRooms(page_forms[i].ts_adults, page_forms[i].ts_room_count);
    }
    for (var i=0;i<page_forms.length;i++) {
        _tam_fillWithBrandByValue(page_forms[i].ts_room_count);
    }
}

// for custom form elements
function _tam_saveWithBrandByValue(element) {
    if (!element)   //removed && !element.type 12.11.2003
        return;
    if (document.images) {
        var val = null;
        if ((element.type == "text") || (element.type == "password") || (element.type == "textarea") || (element.type == "radio") || (element.type == "hidden")) {
            val = element.value;
        } else if (element.type == "select-one") {
            if(element.selectedIndex != -1)
                val = element.options[element.selectedIndex].value
        } else if (element.type == "select-multiple") {
            if(element.selectedIndex != -1) {
                val = element.options[element.selectedIndex].value
                for(var i = element.selectedIndex + 1 ; i < element.options.length ; i++)
                    if(element.options[i].selected)
                        val += "_" + element.options[i].value;
            }
        } else if (element.type == "checkbox") {
            val = element.checked;
        } else if (typeof(element) == "object" && element.length > 0) {
            var elements = element;
            for ( var i = 0 ; i < elements.length ; i++) {
                element = elements[i];
                if(element && element.type == "radio" && element.checked)
                    val = element.value;
            }
        }
        _tam_setCookie(ta_brand+element.name,val);
    }
}
// for custom form elements
function _tam_fillWithBrandByValue(element, onlyParam) {
    if(!element)
        return false;
    if (document.images) {
        // this is the one
        var val = _tam_getParam(element.name);
        if(!val) {
            if(onlyParam)
                return false;
            var cookie_name = ta_brand+element.name;
            val = _tam_GetCookie(cookie_name);
            if(!val)
                return false;
        }
        if (element.type == "select-one" || element.type == "select-multiple") {
            var values = val.split("_");
            element.selectedIndex = -1;
            for(var l=0;l < values.length ; l++) {
                for(var k=0;k<element.options.length;k++)
                    if (element.options[k].value == values[l]) {
                        element.options[k].selected=true;
                        if(element.type == "select-one")
                            return true;
                    }
            }
            if(element.selectedIndex == -1) {
                element.selectedIndex = 0;
                return false;
            } else {
                return true;
            }
        } else if (element.type == "checkbox") {
            if (val == "true") {
                element.checked = true;
            } else {
                element.checked = false;
            }
            return true;
        } else if ((element.type == "text") || (element.type == "password") || (element.type == "textarea") || (element.type == "radio") || (element.type == "hidden")) {
            element.value = val;
            return true;
        }
        return false;
    }
}

// DESCRIPTION AND CHANGE LOG
// n-form-memory5.js - functions needed save values to and retrieve values from cookies


function _tam_getAbsoluteCookie(name) {
    var result = null;
    var myCookie = " " + document.cookie + ";";
    // alert(myCookie);
    var searchName = " " + name + "=";
    var startOfCookie = myCookie.indexOf(searchName);
    var endOfCookie;
    if (startOfCookie != -1) {
        startOfCookie += searchName.length; // skip past name of cookie
        endOfCookie = myCookie.indexOf(";", startOfCookie);
        result = myCookie.substring(startOfCookie, endOfCookie);
    }
    return result;
}

function _tam_setAbsoluteCookie(name, value) {
    document.cookie = name + "=" + value + "; PATH=/tripsearch/";
    document.cookie = name + "=" + value + "; PATH=/";
}


function _tam_setCookie(name, value) {

    var escapedValue = "#"+escape(value)+"#";

    if (escapedValue == "##" || escapedValue == "# #" || escapedValue == "#null#") {
        _tam_removeCookie(name);
        return;
    }

    // cookie syntax : memory=/key1/#escape(value1)#/key2/#escape(value2)#; PATH=/tripsearch/
    //                 memory=/key1/#escape(value1)#/key2/#escape(value2)#; PATH=/

    var masterCookie = _tam_getAbsoluteCookie("memory");

    var key = "/"+name+"/";

    if (masterCookie == null) {
        masterCookie = key + escapedValue;
    } else {
        var ind = masterCookie.indexOf(key);
        if (ind != -1) {
            var endInd = masterCookie.indexOf("/",ind + key.length);
            if (endInd != -1) {
                masterCookie = masterCookie.substring(0,ind) + key + escapedValue + masterCookie.substring(endInd);
            } else {
                masterCookie = masterCookie.substring(0,ind) + key + escapedValue;
            }
        } else {
            masterCookie = masterCookie + key + escapedValue;
        }
    }

    _tam_setAbsoluteCookie("memory",masterCookie);
}

function _tam_removeCookie(name) {
    var masterCookie = _tam_getAbsoluteCookie("memory");

    var key = "/"+name+"/";

    if (masterCookie != null) {
        var ind = masterCookie.indexOf(key);
        if (ind != -1) {
            var endInd = masterCookie.indexOf("/",ind + key.length);
            if (endInd != -1) {
                masterCookie = masterCookie.substring(0,ind) + masterCookie.substring(endInd);
            } else {
                masterCookie = masterCookie.substring(0,ind);
            }
            _tam_setAbsoluteCookie("memory",masterCookie);
        }
    }
}

function _tam_GetCookie(name) {
    // cookie syntax : memory=/key1/#escape(value1)#/key2/#escape(value2)#; PATH=/tripsearch/
    //                 memory=/key1/#escape(value1)#/key2/#escape(value2)#; PATH=/
    //                 memory=/key1/#escape(value1)#/key2/#escape(value2)#; PATH=/

    var masterCookie = _tam_getAbsoluteCookie("memory");

    if (masterCookie != null) {
        var key = "/"+name+"/";
        var ind = masterCookie.indexOf(key);
        if (ind != -1) {
            var startInd = ind + key.length;
            var endInd = masterCookie.indexOf("/",startInd);
            var result = null;
            if (endInd != -1) {
                return unescape(masterCookie.substring(startInd+1,endInd-1));
            } else {
                return unescape(masterCookie.substring(startInd+1,masterCookie.length-1));
            }
        }
    }
    return null;
}

function _tam_getParam(name) {
    var queryString = location.search;
    if(!queryString)
        return null;
    var queryString = queryString.substring(1,queryString.length);
    if(queryString.length>0) {
        if(queryString.search(name) == -1)
            return null;
        var arrayPairs = queryString.split("&");
        for(var i=0;i<arrayPairs.length;i++){
            var pair = arrayPairs[i].split("=");
            if (pair[0] == name)
                return pair[1]
        }
    }
    return null;
}

function ta_saveCurrent(formNumber) {
    if(!page_forms[formNumber])
        return;
    var form = page_forms[formNumber];
    ta_cur_adults[formNumber] = form.ts_adults.selectedIndex;
    _tam_saveWithBrandByValue(form.ts_adults);

    if(form.children_total) {
        ta_cur_totalCh[formNumber] = form.children_total.selectedIndex;
        _tam_saveWithBrandByValue(form.children_total);
    }

    if(form.ts_ch_2) {
        ta_cur_c_2[formNumber] = form.ts_ch_2.selectedIndex;
        _tam_saveWithBrandByValue(form.ts_ch_2);
    }

    if(form.ts_ch_gr1) {
        ta_cur_cg1[formNumber] = form.ts_ch_gr1.selectedIndex;
        _tam_saveWithBrandByValue(form.ts_ch_gr1);
    }
    if(form.ts_ch_gr2) {
        ta_cur_cg2[formNumber] = form.ts_ch_gr2.selectedIndex;
        _tam_saveWithBrandByValue(form.ts_ch_gr2);
    }
    if(form.ts_ch_gr3) {
        ta_cur_cg3[formNumber] = form.ts_ch_gr3.selectedIndex;
        _tam_saveWithBrandByValue(form.ts_ch_gr3);
    }
    if(form.ts_ch_gr4) {
        ta_cur_cg4[formNumber] = form.ts_ch_gr4.selectedIndex;
        _tam_saveWithBrandByValue(form.ts_ch_gr4);
    }

    // limited
    if(form.ts_length) {
        ta_cur_length[formNumber] = form.ts_length.selectedIndex;
        _tam_saveWithBrandByValue(form.ts_length);
    }

    if(form.ts_room_count) {
        ta_cur_rooms[formNumber] = form.ts_room_count.selectedIndex;
        _tam_saveWithBrandByValue(form.ts_room_count);
    }
    if(form.ts_room_combinations) {
        _tam_saveWithBrandByValue(form.ts_room_combinations);
    }
}

function ta_reset_form(form) {
    if (document.images && form) {
        // dates
        _tau_set_selected(form.ts_out_earliest_day, ta_1st_search_day);
        _tau_set_selected(form.ts_out_latest_day, ta_1st_search_day);
        _tau_set_selected(form.ts_out_earliest_my, 0);
        _tau_set_selected(form.ts_out_latest_my, 0);
        // lengths
        _tau_set_checked(form.ts_weekend, false);
        _tau_set_checked(form.ts_week, true);
        _tau_set_checked(form.ts_two_weeks, false);
        _tau_set_checked(form.ts_fivedays, false);
        _tau_set_checked(form.ts_ten_days, false);
        _tau_set_checked(form.ts_over_two_weeks, false);
        // attributes (dest & acc)
        if(form.elements) {
            for(var i = 0 ; i < form.elements.length ; i++) {
                var element = form.elements[i];
                if(element.type == "checkbox" && element.name.length > 5) {
                    var nameStart = element.name.substring(0,5);
                    if(nameStart == "tade_" || nameStart == "taac_") {
                        _tau_set_checked(element, false);
                    }
                }
            }
        }
        // out dep station
        _tau_set_selected(form.ts_dep_station, 0);
        // area
        _tau_set_selected(form.ts_area, 0);
        // dest
        _tau_set_selected(form.ts_dest, 0);
        // iata
        _tau_set_selected(form.ts_iata, 0);
        // groups (adults last)
        _tau_set_selected(form.ts_room_count, 0);
        _tau_set_selected(form.ts_ch_2, 0);
        _tau_set_selected(form.ts_ch_gr1, 0);
        _tau_set_selected(form.ts_ch_gr2, 0);
        _tau_set_selected(form.ts_ch_gr3, 0);
        _tau_set_selected(form.ts_ch_gr4, 0);
        _tau_set_selected(form.ts_ch_gr5, 0);
        _tau_set_selected(form.ts_adults, 1);
        // stars and env
        _tau_set_checked(form.ts_one_two_stars, false);
        _tau_set_checked(form.ts_three_stars, false);
        _tau_set_checked(form.ts_four_stars, false);
        _tau_set_checked(form.ts_five_stars, false);
        _tau_set_checked(form.ts_one_envr, false);
        _tau_set_checked(form.ts_two_envr, false);
        _tau_set_checked(form.ts_three_envr, false);
        // acc type
        _tau_set_checked(form.ts_htl, false);
        _tau_set_checked(form.ts_ahtl, false);
        // price
        _tau_set_text(form.ts_max_price, "");
    }
}

function _tau_set_selected(select, index) {
    if(select && (select.selectedIndex != index || select.type == "select-multiple")) {
        select.selectedIndex = index;
        if(select.onclick)
            select.onclick();
        if(select.onchange)
            select.onchange();
    }
}

function _tau_set_checked(checkbox, checked) {
    if(checkbox && checkbox.checked != checked) {
        checkbox.checked = checked;
        if(checkbox.onclick)
            checkbox.onclick();
        if(checkbox.onchange)
            checkbox.onchange();
    }
}
function _tau_set_text(text, value) {
    if(text && text.value != value) {
        text.value = value;
        if(text.onclick)
            text.onclick();
        if(text.onchange)
            text.onchange();
    }
}

/////////////
/// GROUPS

function _tau_refreshFormHolder(containsSearchForm, containsMiddleForm, containsRightForm) {
    if (containsMiddleForm && containsRightForm) {
        alert("assertation failed: containsMiddleForm: " + containsMiddleForm + " containsRightForm : " + containsRightForm);
    }
    containsSearchForm = (containsSearchForm && document.searchForm);
    containsMiddleForm = (containsMiddleForm && document.group_form);
    containsRightForm = (containsRightForm && document.group_form);
    if (containsSearchForm && (containsMiddleForm || containsRightForm)) {
        page_forms = new Array(document.searchForm, document.group_form);
        room_containers = new Array('room_layer_options_top', 'room_layer_options');
        if (containsMiddleForm) {
            room_layers = new Array('room-layer-top', 'room-layer-middle');
            child_layers = new Array('lapset-layer-top','lapset-layer-middle');
        } else {
            room_layers = new Array('room-layer-top', 'room-layer-right');
            child_layers = new Array('lapset-layer-top','lapset-layer-right');
        }
    } else if (containsSearchForm) {
        page_forms = new Array(document.searchForm);
        room_containers = new Array('room_layer_options_top');
        room_layers = new Array('room-layer-top');
        child_layers = new Array('lapset-layer-top');
    } else if (containsMiddleForm || containsRightForm) {
        page_forms = new Array(document.group_form);
        room_containers = new Array('room_layer_options');
        if (containsMiddleForm) {
            room_layers = new Array('room-layer-top', 'room-layer-middle');
            child_layers = new Array('lapset-layer-top','lapset-layer-middle');
        } else {
            room_layers = new Array('room-layer-top', 'room-layer-right');
            child_layers = new Array('lapset-layer-top','lapset-layer-right');
        }
    }
}

function ta_childrenChange(formNumber) {
    _tau_setChildrenCounts(formNumber);
    _tau_checkGroupValidity(formNumber);
    if(page_forms[formNumber].roomChoice.selectedIndex > 0) {
        MM_showHideLayers(room_layers[formNumber],'','show');
    }
    else {
        MM_showHideLayers(room_layers[formNumber],'','hide');
    }
    _tau_updateSettling(room_containers[formNumber], formNumber);
    ta_saveCurrent(formNumber);
}

function ta_hideLayer(layer, hidetime) {
    if(hidetime) {
        var remaining = hidetime - new Date().getTime();
        if(remaining > 0) {
            setTimeout("MM_showHideLayers('"+layer+"','','hide')", remaining);
            return;
        }
    }
    MM_showHideLayers(layer,'','hide');
}

function ta_roomChange(formNumber) {
    if(page_forms[formNumber].roomChoice.selectedIndex > -1) {
        ta_saveCurrent(formNumber);
        _tau_updateSettling(room_containers[formNumber], formNumber);
    }
    if(page_forms[formNumber].roomChoice.selectedIndex > 0) {
        MM_showHideLayers(room_layers[formNumber],'','show');
    }
    else {
        MM_showHideLayers(room_layers[formNumber],'','hide');
    }
}

function ta_setA_month(selectElement, justSet) {
    ta_month_a = parseInt(selectElement.options[selectElement.selectedIndex].value);
    ta_force = false;
    var newLength = ta_m_len[ta_month_a];
    if (ta_day_a >= newLength) {
        // new month has fewer days, move pointer to last day of the month
        ta_day_a = newLength-1;
    }
    // make sure first date is before or equal than last date
    if(ta_month_a >= ta_month_b) {
        ta_month_b = ta_month_a;
        if(ta_day_a > ta_day_b) {
            ta_day_b = ta_day_a;
        }
    }
    if(!justSet) {
        _tad_renderDateFields();
        _tam_saveDateValues();
    }
}
function ta_setA_day(selectElement, justSet) {
    ta_day_a = _tao_getIndexFromSelect(selectElement);
    ta_force = false;
    // make sure first date is before or equal than last date
    if(ta_month_a == ta_month_b) {
        if(ta_day_a > ta_day_b) {
            ta_day_b = ta_day_a;
        }
    }
    if(!justSet) {
        _tad_renderDateFields();
        _tam_saveDateValues();
    }
}
function ta_setB_month(selectElement, justSet) {
    ta_month_b = parseInt(selectElement.options[selectElement.selectedIndex].value);
    ta_force = false;
    // make sure first date is before or equal than last date
    if(ta_month_a >= ta_month_b) {
        ta_month_a = ta_month_b;
        if(ta_day_a > ta_day_b) {
            ta_day_a = ta_day_b;
        }
    }
    if(!justSet) {
        _tad_renderDateFields();
        _tam_saveDateValues();
    }
}
function ta_setB_day(selectElement, justSet) {
    ta_day_b = _tao_getIndexFromSelect(selectElement);
    ta_force = false;
    // make sure first date is before or equal than last date
    if(ta_month_a == ta_month_b) {
        if(ta_day_a > ta_day_b) {
            ta_day_a = ta_day_b;
        }
    }
    if(!justSet) {
        _tad_renderDateFields();
        _tam_saveDateValues();
    }
}

/////
//
// day and month index
//

function _tad_getWeekdayPointer(monthIndex) {
    var dayFromBeginning = _tad_getDayFromBeginning(0, monthIndex);
    var index = (dayFromBeginning + ta_1st_day) % 7;
    return index;
}
function _tad_getDayFromBeginning(dayIndex, monthIndex) {
    var dayFromBeginning = 0;
    for (var i = 0; i < monthIndex; i++) {
        dayFromBeginning += ta_m_len[i];
    }
    dayFromBeginning += dayIndex;
    return dayFromBeginning;
}
function _tad_getDay(dayFromBeginning) {
    var month = _tad_getMonth(dayFromBeginning);
    return (dayFromBeginning - _tad_getDayFromBeginning(0, month));
}
function _tad_getMonth(dayFromBeginning) {
    var sumFromBeginning = 0;
    for (var i = 0; i < ta_m_len.length; i++) {
        sumFromBeginning += ta_m_len[i];
        if (dayFromBeginning < sumFromBeginning) {
            // this is the month
            return i;
        }
    }
    // we dont really know, best effort guess
    return ta_m_len.length + Math.floor((dayFromBeginning - sumFromBeginning) / 30);
}

function _tad_formatDate(day, month, year) {
    if(!month) {
        // day is day from beginning
        var monthIdx = _tad_getMonth(day);
        day = _tad_getDay(day);
        var baseMonth = parseInt(document.searchForm.ts_base_month.value);
        var baseYear = parseInt(document.searchForm.ts_base_year.value);
        year = baseYear + Math.floor((baseMonth + monthIdx) / 12);
        month = (baseMonth + monthIdx) % 12;
    }
    // D.M.YYYY format
    return (day + 1) + '.' + (month + 1) + '.' + year;
}

////////
//
// Utils
//
function _tao_getIndexFromSelect(selectElement) {
    for(var k=0;k<selectElement.length;k++) {
        if (selectElement.options[k].selected)
            return k;
    }
    return -1;
}

///////
//
// updates
//
function _tad_updateDaysAOptions(form) {
    if(!form.ts_out_earliest_day)
        return false;
    if(form.ts_out_earliest_day.type != "select-one") {
        form.ts_out_earliest_day.value = ta_day_a;
        return false;
    }

    var newLength = ta_m_len[ta_month_a];
    var oldLength = form.ts_out_earliest_day.options.length;
    var weekdayPointer = _tad_getWeekdayPointer(ta_month_a);

    if (ta_day_a >= newLength) {
        ta_day_a = newLength-1;
    }

    var i = 0;

    for(i = 0; i < newLength; i++) {
        if (weekdayPointer == 7) {
            weekdayPointer = 0;
        }
        form.ts_out_earliest_day.options[i] = new Option(i+1+ta_day_names[weekdayPointer++]);
        form.ts_out_earliest_day.options[i].value = i;
        if (i==ta_day_a) {
            form.ts_out_earliest_day.options[i].selected = true;
        }
    }

    for(i = oldLength - 1; i >= newLength; i--) {
        form.ts_out_earliest_day.options[i] = null;
    }
    return false;
}

function _tad_updateDaysBOptions(form) {
    if(!form.ts_out_latest_day)
        return false;
    if(form.ts_out_latest_day.type != "select-one") {
        form.ts_out_latest_day.value = ta_day_b;
        return false;
    }
    if(ta_month_b < 0)
        ta_month_b = 1;  //check if we have gone over year change.
    var newLength = ta_m_len[ta_month_b];
    var oldLength = form.ts_out_latest_day.options.length;
    var weekdayPointer = _tad_getWeekdayPointer(ta_month_b);

    if (ta_day_b >= newLength) {
        ta_day_b = newLength-1;
    }

    var i = 0;

    for(i = 0; i < newLength; i++) {
        if (weekdayPointer == 7) {
            weekdayPointer = 0;
        }
        form.ts_out_latest_day.options[i] = new Option(i+1+ta_day_names[weekdayPointer++]);
        form.ts_out_latest_day.options[i].value = i;
        if (i==ta_day_b) {
            form.ts_out_latest_day.options[i].selected = true;
        }
    }
    for(i = oldLength - 1; i >= newLength; i--) {
        form.ts_out_latest_day.options[i] = null;
    }
    return false;
}

function _tad_updateMonthAOptions(form) {
    for (var i = 0; i < form.ts_out_earliest_my.options.length; i++) {
        var option = form.ts_out_earliest_my.options[i];
        if(option.value == ta_month_a) {
            option.selected = true;
        }
    }
    if(form.ts_out_earliest_my.selectedIndex == -1 || ta_month_a != form.ts_out_earliest_my.options[form.ts_out_earliest_my.selectedIndex].value) {
        form.ts_out_earliest_my.selectedIndex = 0;
        ta_month_a = parseInt(form.ts_out_earliest_my.options[0].value);
    }
}

function _tad_updateMonthBOptions(form) {
    for (var i = 0; i < form.ts_out_latest_my.options.length; i++) {
        var option = form.ts_out_latest_my.options[i];
        if(option.value == ta_month_b) {
            option.selected = true;
        }
    }
    if(form.ts_out_latest_my.selectedIndex == -1 || ta_month_b != form.ts_out_latest_my.options[form.ts_out_latest_my.selectedIndex].value) {
        form.ts_out_latest_my.selectedIndex = 0;
        ta_month_b = parseInt(form.ts_out_latest_my.options[0].value);
    }
}

function _tad_renderDateFields() {
    if(document.searchForm) {
        _tad_updateMonthAOptions(document.searchForm);
        _tad_updateDaysAOptions(document.searchForm);
        if(document.searchForm.ts_out_latest_my) {
            _tad_updateMonthBOptions(document.searchForm);
            _tad_updateDaysBOptions(document.searchForm);
        }
    }
    if(document.group_form) {
        if(document.group_form.ts_out_earliest_day) {
            _tad_updateMonthAOptions(document.group_form);
            _tad_updateDaysAOptions(document.group_form);
            if(document.group_form.ts_out_latest_my) {
                _tad_updateMonthBOptions(document.group_form);
                _tad_updateDaysBOptions(document.group_form);
            }
        }
    }
}

function _tau_setupDateFields() {
    // init values
    for(var i = 0; i < ta_m_name.length; i++) {
        var earliest_my = document.searchForm.ts_out_earliest_my;
        var latest_my = document.searchForm.ts_out_latest_my;
        earliest_my.options[i] = new Option(ta_m_name[i]);
        earliest_my.options[i].value = i;
        if(latest_my) {
            latest_my.options[i] = new Option(ta_m_name[i]);
            latest_my.options[i].value = i;
        }
        if(document.group_form) {
            earliest_my = document.group_form.ts_out_earliest_my;
            latest_my = document.group_form.ts_out_latest_my;
            if(earliest_my) {
                earliest_my.options[i] = new Option(ta_m_name[i]);
                earliest_my.options[i].value = i;
                if(latest_my) {
                    latest_my.options[i] = new Option(ta_m_name[i]);
                    latest_my.options[i].value = i;
                }
            }
        }
    }
}

function ta_setEarly(elementDay, elementMY, dateText) {
    return _tad_setDateValue(elementDay, elementMY, dateText, ta_setA_day, ta_setA_month);
}

function ta_setLatest(elementDay, elementMY, dateText) {
    return _tad_setDateValue(elementDay, elementMY, dateText, ta_setB_day, ta_setB_month);
}


function _tad_setDateValue(elementDay, elementMY, dateText, setFuncDay, setFuncMY) {
    // dateText must be either in YYYYMMDD or DD format
    dateText = _tao_Trim(dateText);
    if(!dateText || !(dateText.length == 1 || dateText.length == 2 || dateText.length == 8)) {
        alert("Valitsemasi päivä on virheellinen.");
        return false;
    }
    if(dateText.length != 8) {
        // DD
        var day = parseInt(dateText.replace(/^0/, ''));
        var dayIndex = day-1;
        elementDay.options[dayIndex].selected = true;
        setFuncDay(elementDay, true);
    } else {
        // YYYYMMDD
        var year = parseInt(dateText.substring(0,4));
        var month = parseInt(dateText.substring(4,6).replace(/^0/, ''));
        var day = parseInt(dateText.substring(6,8).replace(/^0/, ''));
        var baseMonth = parseInt(document.searchForm.ts_base_month.value);
        var baseYear = parseInt(document.searchForm.ts_base_year.value);
        var dayIndex = day-1;
        var monthIndex = month - baseMonth + (year-baseYear)*12 - 1;

        if (dayIndex < 0 || monthIndex < 0) {
            alert("Valitsemasi päivä on jo mennyt.");
            return false;
        }
        if (elementMY.options.length <= monthIndex || elementDay.options.length+3 <= dayIndex) {
            alert("Valitsemasi päivän matkat eivät ole vielä hakupalvelussa.");
            return false;
        }
        elementMY.options[monthIndex].selected = true;
        elementDay.options[dayIndex].selected = true;
        setFuncMY(elementMY, true);
        setFuncDay(elementDay, true);
    }
    _tam_saveDateValues();
    _tad_renderDateFields();
}



function _tao_Trim(strValue)	{
    return strValue.replace(/^\s+|\s+$/g, '');
}

function _tao_LTrim(strValue) {
    return strValue.replace(/^\s+/, '');
}

function _tao_RTrim(strValue) {
    return strValue.replace(/\s+$/, '');
}

function _tau_updateRooms(aCtrl, rmCtrl) {
    if (!ta_roomsEn)
        return;
    var new_rooms_max = ta_getValue(aCtrl);
    var cur_selectedIndex = rmCtrl.selectedIndex;
    if (new_rooms_max > 3) {
        new_rooms_max = 3;
    }
    if (new_rooms_max != rmCtrl.options.length) {
        _tao_empty(rmCtrl);
        while (rmCtrl.options.length < new_rooms_max) {
            var ind = rmCtrl.options.length;
            var rooms = ind+1;
            rmCtrl.options[ind] = new Option(rooms, rooms, false, false);
        }
        var new_selectedIndex = -1;
        var save = false;
        new_selectedIndex = cur_selectedIndex;
        if (new_selectedIndex >= rmCtrl.options.length) {
            new_selectedIndex = rmCtrl.options.length - 1;
            ta_upd_settling = true;
            save = true;
        } else if (new_selectedIndex == -1) {
            new_selectedIndex = 0;
            ta_upd_settling = true;
        }
        rmCtrl.selectedIndex = new_selectedIndex;
        if (save) {
            _tam_saveWithBrandByValue(rmCtrl);
        }
    }
}

function _tao_empty(selectField){
    while(selectField.length > 0){
        selectField.options[selectField.length - 1] = null;
    }
}

function _tau_updateRSIfNeeded(formNumber) {
    _tau_checkForUpdate(formNumber);
    if (ta_upd_rooms) {
        _tau_updateRooms(page_forms[formNumber].ts_adults, page_forms[formNumber].ts_room_count);
        ta_upd_rooms = false;
    }
    if (ta_settlingEn && ta_upd_settling) {
        _tau_updateSettling(room_containers[formNumber], formNumber);
        ta_upd_settling = false;
    }
    ta_saveCurrent(formNumber);
}

function ta_groupChange(saveElement, formNumber) {
    _tau_checkGroupValidity(formNumber);
    if (ta_roomsEn || ta_settlingEn)
        _tau_updateRSIfNeeded(formNumber);
    ta_saveCurrent(formNumber);
}

function _tau_checkForUpdate(formNumber) {
    if (ta_cur_adults[formNumber] != page_forms[formNumber].ts_adults.selectedIndex) {
        ta_upd_rooms = true;
        ta_upd_settling = true;
    } else if  (ta_cur_c_2[formNumber] != page_forms[formNumber].ts_ch_2.selectedIndex ||
                (page_forms[formNumber].ts_ch_gr1 && ta_cur_cg1[formNumber] != page_forms[formNumber].ts_ch_gr1.selectedIndex) ||
                (page_forms[formNumber].ts_ch_gr2 && ta_cur_cg2[formNumber] != page_forms[formNumber].ts_ch_gr2.selectedIndex) ||
                (page_forms[formNumber].ts_ch_gr3 && ta_cur_cg3[formNumber] != page_forms[formNumber].ts_ch_gr3.selectedIndex) ||
                (page_forms[formNumber].ts_ch_gr4 && ta_cur_cg4[formNumber] != page_forms[formNumber].ts_ch_gr4.selectedIndex)
                ) {
        ta_upd_settling = true;
        ta_upd_rooms = true;
    } else if  (ta_cur_rooms != page_forms[formNumber].ts_room_count.selectedIndex) {
        ta_upd_settling = true;
        ta_upd_rooms = false;
    } else {
        ta_upd_settling = false;
        ta_upd_rooms = false;
    }
}

function _tau_setChildrenCounts(formNumber) {
    var total = page_forms[formNumber].children_total.selectedIndex;
    var totalSet = false;
    if(page_forms[formNumber].ts_ch_gr1) {
        page_forms[formNumber].ts_ch_gr1.selectedIndex = total;
        totalSet = true;
    }
    if(page_forms[formNumber].ts_ch_gr2) {
        if(totalSet) {
            page_forms[formNumber].ts_ch_gr2.selectedIndex = 0;
        } else {
            page_forms[formNumber].ts_ch_gr2.selectedIndex = total;
            totalSet = true;
        }
    }
    if(page_forms[formNumber].ts_ch_gr3) {
        if(totalSet) {
            page_forms[formNumber].ts_ch_gr3.selectedIndex = 0;
        } else {
            page_forms[formNumber].ts_ch_gr3.selectedIndex = total;
            totalSet = true;
        }
    }
    if(page_forms[formNumber].ts_ch_gr4) {
        if(totalSet) {
            page_forms[formNumber].ts_ch_gr4.selectedIndex = 0;
        } else {
            page_forms[formNumber].ts_ch_gr4.selectedIndex = total;
            totalSet = true;
        }
    }
    page_forms[formNumber].ts_ch_2.selectedIndex = 0;
}

function _tau_getChildCount(formNumber) {
    var count = 0;
    if (page_forms[formNumber].ts_ch_gr1)
        count += page_forms[formNumber].ts_ch_gr1.selectedIndex;
    if (page_forms[formNumber].ts_ch_gr2)
        count += page_forms[formNumber].ts_ch_gr2.selectedIndex;
    if (page_forms[formNumber].ts_ch_gr3)
        count += page_forms[formNumber].ts_ch_gr3.selectedIndex;
    if (page_forms[formNumber].ts_ch_gr4)
        count += page_forms[formNumber].ts_ch_gr4.selectedIndex;
    if (page_forms[formNumber].ts_ch_2)
        count += page_forms[formNumber].ts_ch_2.selectedIndex;
    return count;
}

function _tau_revertChildCounts(formNumber) {
    if (page_forms[formNumber].ts_ch_gr1)
        page_forms[formNumber].ts_ch_gr1.selectedIndex = ta_cur_cg1[formNumber];
    if (page_forms[formNumber].ts_ch_gr2)
        page_forms[formNumber].ts_ch_gr2.selectedIndex = ta_cur_cg2[formNumber];
    if (page_forms[formNumber].ts_ch_gr3)
        page_forms[formNumber].ts_ch_gr3.selectedIndex = ta_cur_cg3[formNumber];
    if (page_forms[formNumber].ts_ch_gr4)
        page_forms[formNumber].ts_ch_gr4.selectedIndex = ta_cur_cg4[formNumber];
    if (page_forms[formNumber].ts_ch_2)
        page_forms[formNumber].ts_ch_2.selectedIndex = ta_cur_c_2[formNumber];
}

function _tau_checkGroupValidity(formNumber) {

	var adults = parseInt(ta_getValue(page_forms[formNumber].ts_adults));
	var childCount = _tau_getChildCount(formNumber);

	var personTotal = adults + childCount;
	if(page_forms[formNumber].ts_ch_2) {
        if(adults == 1) {
            page_forms[formNumber].ts_ch_2.options[2] = null;
        }else {
            if(null == page_forms[formNumber].ts_ch_2.options[2]) {
                page_forms[formNumber].ts_ch_2.options[2] = new Option("2", "2",false,false);
            }
        }
    }
    if(personTotal > 6) {
        alert("Henkilöiden lukumäärä enintään 6!");

        if(ta_cur_adults[formNumber] < 0)
            ta_cur_adults[formNumber] = 0;
        if(ta_cur_c_2[formNumber] < 0)
            ta_cur_c_2[formNumber] = 0;
        if(ta_cur_c_2[formNumber] + ta_cur_adults[formNumber] > 6) {
            ta_cur_adults[formNumber] = 2;
            ta_cur_c_2[formNumber] = 0;
        }
        page_forms[formNumber].ts_adults.selectedIndex = ta_cur_adults[formNumber];
        if(page_forms[formNumber].ts_ch_2) {
            page_forms[formNumber].ts_ch_2.selectedIndex = ta_cur_c_2[formNumber];
            _tau_revertChildCounts(formNumber);
        }

        // no need to save
    }
    //if(ta_flightsEn)            // save if flights
    //    ta_saveCurrentGroup();
}

function ta_getValue(selectField) {
    if (selectField) {
        if (!selectField.options) {
            return selectField.value;
        }
        var selected = selectField.selectedIndex;
        if (selected != -1) {
            return selectField.options[selected].value;
        }
    }
    return null;
}

function _tau_updateSettling(sectionId,formNumber) {
    var adults = parseInt(ta_getValue(page_forms[formNumber].ts_adults));
    var rooms = parseInt(ta_getValue(page_forms[formNumber].ts_room_count));
    var child_count_temp = 0;
    if(includeChildren) {
        child_count_temp = _tau_getChildCount(formNumber);
        if(ta_child_total_in_use) {
            page_forms[formNumber].children_total.selectedIndex = child_count_temp;
        }
        if (page_forms[formNumber].ts_ch_2)
            child_count_temp = child_count_temp - page_forms[formNumber].ts_ch_2.selectedIndex;
    }
    _tau_updateRoomsList(adults, child_count_temp, rooms, sectionId, formNumber); //'room_layer_options'
    if(rooms > 1 && page_forms[formNumber].ts_ch_2.selectedIndex) {
        var cbCtrl = document.getElementById(sectionId);
        cbCtrl.innerHTML = cbCtrl.innerHTML + "<br style=\"clear: both;\" />Alle 2-vuotiaiden lasten sijoittamisen voi p&auml;&auml;tt&auml;&auml; paikan p&auml;&auml;ll&auml;";
    }
    return; //opera problem
}

// checks the right room structures and sends them as parameters to _tau_genRoomRows. Adults as tens and children as single numbers
// ie 2 adults and 1 child become 21 room
function _tau_updateRoomsList(adCnt1, cdCnt1, rmCnt1, sectionId, formNumber) {
    var cbCtrl = document.getElementById(sectionId);
	if(cbCtrl == null)
	    return;
    var roomChoices;
    if(rmCnt1 == 1) {
        roomChoices = new Array(_tau_genRoomRows(adCnt1*10+cdCnt1,0,0,true,formNumber));
        _tau_buildDynamicRoomChoiceArea(cbCtrl, roomChoices);
        return;
    }
    switch(adCnt1) {
        case 1:
            roomChoices = new Array(_tau_genRoomRows(10+cdCnt1,0,0,true,formNumber));
            break;
        case 2:
            if(cdCnt1 == 0) {
                roomChoices = new Array(_tau_genRoomRows(10,10,0,true,formNumber));
            } else if(cdCnt1 == 1) {
                roomChoices = new Array(_tau_genRoomRows(11,10,0,true,formNumber));
            } else if(cdCnt1 == 2) {
                roomChoices = new Array(_tau_genRoomRows(11,11,0,true,formNumber), _tau_genRoomRows(12,10,0,false,formNumber));
            } else if(cdCnt1 == 3) {
                roomChoices = new Array(_tau_genRoomRows(12,11,0,true,formNumber), _tau_genRoomRows(13,10,0,false,formNumber));
            } else if(cdCnt1 == 4) {
                roomChoices = new Array(_tau_genRoomRows(12,12,0,true,formNumber), _tau_genRoomRows(14,10,0,false,formNumber), _tau_genRoomRows(13,11,0,false,formNumber));
            }
            break;
        case 3:
            if(cdCnt1 == 0) {
                if(rmCnt1 == 2) {
                    roomChoices = new Array(_tau_genRoomRows(20,10,0,true,formNumber));
                } else if(rmCnt1 == 3) {
                    roomChoices = new Array(_tau_genRoomRows(10,10,10,true,formNumber));
                }
            } else if(cdCnt1 == 1) {
                if(rmCnt1 == 2) {
                    roomChoices = new Array(_tau_genRoomRows(20,11,0,true,formNumber), _tau_genRoomRows(21,10,0,false,formNumber));
                } else if(rmCnt1 == 3) {
                    roomChoices = new Array(_tau_genRoomRows(11,10,10,true,formNumber));
                }
            } else if(cdCnt1 == 2) {
                if(rmCnt1 == 2) {
                    roomChoices = new Array(_tau_genRoomRows(21,11,0,true,formNumber), _tau_genRoomRows(22,10,0,false,formNumber), _tau_genRoomRows(12,20,0,false,formNumber));
                } else if(rmCnt1 == 3) {
                    roomChoices = new Array(_tau_genRoomRows(11,11,10,true,formNumber), _tau_genRoomRows(12,10,10,false,formNumber));
                }
            } else if(cdCnt1 == 3) {
                if(rmCnt1 == 2) {
                    roomChoices = new Array(_tau_genRoomRows(21,12,0,true,formNumber), _tau_genRoomRows(22,11,0,false,formNumber), _tau_genRoomRows(23,10,0,false,formNumber), _tau_genRoomRows(13,20,0,false,formNumber));
                } else if(rmCnt1 == 3) {
                    roomChoices = new Array(_tau_genRoomRows(11,11,11,true,formNumber), _tau_genRoomRows(13,10,10,false,formNumber), _tau_genRoomRows(12,11,10,false,formNumber));
                }
            }
            break;
        case 4:
            if(cdCnt1 == 0) {
                if(rmCnt1 == 2) {
                    roomChoices = new Array(_tau_genRoomRows(20,20,0,true,formNumber), _tau_genRoomRows(30,10,0,false,formNumber));
                } else if(rmCnt1 == 3) {
                    roomChoices = new Array(_tau_genRoomRows(20,10,10,true,formNumber));
                }
            } else if(cdCnt1 == 1){
                if(rmCnt1 == 2) {
                    roomChoices = new Array(_tau_genRoomRows(21,20,0,true,formNumber), _tau_genRoomRows(30,11,0,false,formNumber), _tau_genRoomRows(31,10,0,false,formNumber));
                } else if(rmCnt1 == 3) {
                    roomChoices = new Array(_tau_genRoomRows(20,11,10,true,formNumber), _tau_genRoomRows(21,10,10,false,formNumber));
                }
            } else if(cdCnt1 == 2) {
                if(rmCnt1 == 2) {
                    roomChoices = new Array(_tau_genRoomRows(21,21,0,true,formNumber), _tau_genRoomRows(32,10,0,false,formNumber), _tau_genRoomRows(22,20,0,false,formNumber), _tau_genRoomRows(12,30,0,false,formNumber), _tau_genRoomRows(31,11,0,false,formNumber));
                } else if(rmCnt1 == 3) {
                    roomChoices = new Array(_tau_genRoomRows(20,11,11,true,formNumber), _tau_genRoomRows(22,10,10,false,formNumber), _tau_genRoomRows(21,11,10,false,formNumber), _tau_genRoomRows(20,12,10,false,formNumber));
                }
            }
            break;
        case 5:
            if(cdCnt1 == 0) {
                if(rmCnt1 == 2) {
                    roomChoices = new Array(_tau_genRoomRows(30,20,0,true,formNumber), _tau_genRoomRows(40,10,0,false,formNumber));
                } else if(rmCnt1 == 3) {
                    roomChoices = new Array(_tau_genRoomRows(20,20,10,true,formNumber), _tau_genRoomRows(30,10,10,false,formNumber));
                }
            } else if(cdCnt1 == 1) {
                if(rmCnt1 == 2) {
                    roomChoices = new Array(_tau_genRoomRows(30,21,0,true,formNumber), _tau_genRoomRows(41,10,0,false,formNumber), _tau_genRoomRows(40,11,0,false,formNumber), _tau_genRoomRows(31,20,0,false,formNumber));
                } else if(rmCnt1 == 3) {
                    roomChoices = new Array(_tau_genRoomRows(20,20,11,true,formNumber), _tau_genRoomRows(31,10,10,false,formNumber), _tau_genRoomRows(30,11,10,false,formNumber), _tau_genRoomRows(21,20,10,false,formNumber));
                }
            }
            break;
        case 6:
            if(rmCnt1 == 2) {
                roomChoices = new Array(_tau_genRoomRows(30,30,0,true,formNumber), _tau_genRoomRows(50,10,0,false,formNumber), _tau_genRoomRows(40,20,0,false,formNumber));
            } else if(rmCnt1 == 3) {
                roomChoices = new Array(_tau_genRoomRows(20,20,20,true,formNumber), _tau_genRoomRows(40,10,10,false,formNumber), _tau_genRoomRows(30,20,10,false,formNumber));
            }
            break;
    }  // switch
    _tau_buildDynamicRoomChoiceArea(cbCtrl, roomChoices);
}

// builds the actual html for use. if restructure_room_choices set true, will allow
// two choices to put onto same row, otherwise closes div for every choice.
// layers should use default, large non-layered areas should use restructured version.
function _tau_buildDynamicRoomChoiceArea(cbCtrl, roomChoices) {

    var counter = 0;
    var temp_html = "";
    for(var i=0 ; i < roomChoices.length ; ++i) {
        if(roomChoices[i].length > 0) {
            // if default mode or if we have handled two after opening div
            if(!restructure_room_choices || counter % 2 == 0) {
                if(counter > 0) {
                    temp_html = temp_html + _tau_getChoiceRowCloseTag();
                }
                temp_html = temp_html + _tau_getChoiceRowOpenTag();
            }
            // put the actual roomChoice code in
            temp_html = temp_html + roomChoices[i];
            ++counter;
         }
    }
    if(window.addRoomStructureText && temp_html.length > 1)
        cbCtrl.innerHTML = "<h2>Huoneisiin sijoittuminen *</h2><br />" + temp_html;
    else
        cbCtrl.innerHTML = temp_html;

}
function _tau_getChoiceRowOpenTag() {
    return "<div class=\"PikahakuBlockCont\">";
}
function _tau_getChoiceRowCloseTag() {
    return "</div>";
}

function _tau_genRoomRows(firstRoom, secondRoom, thirdRoom, checked, formNumber) {

    var html = "";
    if(secondRoom > 0) {
        var roomCounts = new Array([parseInt(firstRoom / 10), firstRoom % 10],[parseInt(secondRoom / 10), secondRoom % 10],[parseInt(thirdRoom / 10), thirdRoom % 10]);
        var value = "";
        for(var i = 0 ; i < 3 ; ++i) {
            if(roomCounts[i][0]>0) {
                if(i > 0)
                    value = value + '_';
                value = value + roomCounts[i][0] + 'A';
            }
            if(roomCounts[i][1]>0) {
                value = value + roomCounts[i][1] + 'L';
            }
        }


        html = "<div class=\"RoomOption\">";
        if(checked) {
            html = html + "<input name=\"ts_room_combinations\" type=\"radio\" value=\""+ value + "\" onchange=\"ta_saveCurrent(" + formNumber + ")\" checked />";
        }
        else {
            html = html + "<input name=\"ts_room_combinations\" type=\"radio\" value=\""+ value + "\" onchange=\"ta_saveCurrent(" + formNumber + ")\" />";
        }
        html = html + "</div>";

        for(var i = 0 ; i < 3 ; ++i) {
            if(roomCounts[i][0]>0) {
                html = html + "<div class=\"room-container\">";
                for(var j = 0 ; j < roomCounts[i][0] ; ++j) {
                    html = html + '<div class="room-person-container">'+
                                  '<img src="'+resourcePrefix + nresources+'images/icons/adult.gif" alt="Aikuinen" title="Aikuinen"/>'+
                                  "</div>";
                }
                for(var j = 0 ; j < roomCounts[i][1] ; ++j) {
                    html = html + '<div class="room-person-container">'+
                                  '<img src="'+resourcePrefix + nresources+'images/icons/child.gif" alt="Lapsi" title="Lapsi"/>'+
                                  "</div>";
                }
                html = html + "</div>";
            }
        }

        if(window.ta_atcom_search) {
                html = html + "<div class=\"clear\"></div>";
        }
    }
    return html;
}

function _tau_binSearch(arr, value) {
    if(!arr || !value)
        return -1;
    var low, high, mid, midVal;
	low = 0;
	high = arr.length-1;
	while (low <= high) {
	    mid = Math.round((low + high)/2);
	    midVal = arr[mid];
	    if (midVal < value)
    		low = mid + 1;
	    else if (midVal > value)
	    	high = mid - 1;
	    else
		    return mid;
	}
	return -(low + 1);
}

// opens dynamic iframe layer
function ta_openLayer(iFrameId,layerId,url) {
    document.getElementById(iFrameId).src = url;
    MM_showHideLayers(layerId,'','show');
}

// closes dynamic iframe layer
function ta_closeLayer(iFrameId,layerId) {
    document.getElementById(iFrameId).src = "";
    MM_showHideLayers(layerId,'','hide');
}

// method for dynamic nbrochure calendar building
function ta_updateCalendar(prefix, depStation, outDepMonth, calendarDivId) {
    var calendarDiv = document.getElementById(calendarDivId);
    if(!calendarDiv)
        return;
    _tad_updateMonthAOptions(document.searchForm); // month option list and ta_month_a maybe be off sync if dep station was changed
    var firstDay = _tad_getWeekdayPointer(ta_month_a);
    var selectedDepstation = (depStation ? depStation.options[depStation.selectedIndex].value : "kaikki");
    var days = eval(prefix + 'I' + selectedDepstation + ta_month_a);
    // change selected day if it isn't possible dep date
    if(_tau_binSearch(days, ta_day_a.toString()) < 0) {
        var newSelectedDay = parseInt(days[0]);
        for(var i=1; i < days.length; i++) {
            var d = parseInt(days[i]);
            if(d < newSelectedDay)
                newSelectedDay = d;
        }
        setEarliestSearchDay(newSelectedDay);
    }
    var calTable = '<table cellpadding="0" cellspacing="0" class="calendar"><thead><tr><th>ma</th><th>ti</th><th>ke</th><th>to</th><th>pe</th><th>la</th><th>su</th></tr></thead><tbody><tr>';
    for(var i=0; i <= 41; ) {
        var curActualDay = i-firstDay;
        var selected = (curActualDay == ta_day_a);
        if(curActualDay < 0 || curActualDay >= ta_m_len[ta_month_a]) {
            calTable = calTable + '<td>&nbsp;</td>';
        } else if(_tau_binSearch(days, curActualDay.toString()) >= 0) {
            calTable = calTable + '<td class="' + (selected ? 'selected' : 'valid') + '"><a href="javascript:setEarliestSearchDay(' + curActualDay + ');';
            calTable = calTable + 'ta_updateCalendar(\'' + prefix + '\',' + _tao_getFullElementName(depStation) + ',' + _tao_getFullElementName(outDepMonth) + ',\'' + calendarDivId + '\');">' + (curActualDay + 1) + '</a></td>';
        } else {
            calTable = calTable + '<td' + (selected ? ' class="selected"' : '') + '>' + (curActualDay + 1) + '</td>';
        }
        i++; // increase here
        if(i % 7 == 0) {
            calTable = calTable + '</tr>';
            if(i < 41)
                calTable = calTable + '<tr>';
        }
    }
    var seletedDayNumber = _tad_getDayFromBeginning(ta_day_a, ta_month_a);
    calTable = calTable + '<tr><td colspan="7">Haetaan matkoja ' + _tad_formatDate(seletedDayNumber + ta_search_window_diffs[0]) + ' - ' + _tad_formatDate(seletedDayNumber + ta_search_window_diffs[1]) + '</td></tr>';
    calTable = calTable + '</tbody></table>';
    calendarDiv.innerHTML = calTable;
}

function setEarliestSearchDay(day) {
    document.searchForm.ts_out_earliest_day.value = day;
    ta_day_a = day;
    _tad_renderDateFields();
    _tam_saveDateValues();
}

function _tao_getFullElementName(element) {
    if(!element)
        return "null";
    var name = element.name;
    while(element.parentNode != null) {
        element = element.parentNode;
        if(element.name)
            name = element.name + "." + name;
    }
    return "document." + name;
}
