/*
 * Copyright (C) 2007 The 1st Mile, Inc. All rights reserved.
 */

Array.prototype.indexOf = function(v, n) {
    n = (n == null) ? 0 : n;
    var m = this.length;
    for (var i = n; i < m; i++)
        if (this[i] == v)
            return i;
    return -1;
};

[].indexOf = function(v, n) {
    n = (n == null) ? 0 : n;
    var m = this.length;
    for (var i = n; i < m; i++)
        if (this[i] == v)
            return i;
    return -1;
};

function findPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}
;

function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}
;


var globalStatusMessageDialog;

/**
 * Displays a message box and optionally triggers an action.
 * @param title
 * @param content
 * @param contextObject Optional, for positioning the box under. Default is at 250px.
 * @param button1Text Optional. Default is 'Close'.
 * @param button1Action Optional. Function object which is invoked after the default closing of the box.
 * @param button2Text Optional. If not supplied, the second button is not displayed.
 * @param button2Action Optional. Function object which is invoked after the default closing of the box.
 */
function showStatusMessage(title, content, button1Text, button1Action, button2Text, button2Action, showFeedbackButton, width, hideExclaim, onHideCallBack) {
    if (globalStatusMessageDialog) {
        globalStatusMessageDialog.hide();
    }

    if (width == null) {
        width = 500;
    }

    var conf = {
        x: 200,
        y: 250,
        width: width + "px",
        constraintoviewport: true,
        modal:true,
        draggable:false,
        close: false};

    document.getElementById('statusMsgPlaceHolder').style.display = '';
    var dialog = new YAHOO.widget.SimpleDialog("statusMsgPlaceHolder", conf);

    dialog.onHideCallBack = onHideCallBack;

    dialog.header = document.getElementById("statusMsgPlaceHolderHeader");
    if (!isFacebook) {
        dialog.header.style.width = width - 60;
    }
    dialog.body = document.getElementById("statusMsgPlaceHolderBody");
    dialog.footer = document.getElementById("statusMsgPlaceHolderFooter");

    dialog.setHeader(title);
    dialog.setBody(content);

    var buttons = new Array();
    var button1 = new Object();
    if (button1Text != null) {
        button1.text = button1Text;
    } else {
        button1.text = ResourceBundle.getString("close");
    }

    if (button1Action != null) {
        button1.handler = function() {
            this.hide();
            button1Action(dialog);
        };
    } else {
        button1.handler = dialog.hide;
    }

    buttons.push(button1);

    if (button2Text != null) {
        var button2 = new Object();
        button2.text = button2Text;

        if (button2Action != null) {
            button2.handler = function() {
                this.hide();
                button2Action();
            };
        } else {
            button2.handler = dialog.hide;
        }

        buttons.push(button2);
    }

    if (showFeedbackButton) {
        var feedbackButton = new Object();
        feedbackButton.text = ResourceBundle.getString("feedback");
        feedbackButton.handler = function() {
            this.hide();
            feedback();
        };

        buttons.push(feedbackButton);
    }

    dialog.cfg.subscribeToConfigEvent("buttons", configButtons, dialog, true);

    dialog.cfg.queueProperty("buttons", buttons);
    setTimeout(function() {
        dialog.render(document.body);
        if (!isOpenSocial) {
            dialog.center();
        }
        dialog.show();

        globalStatusMessageDialog = dialog;
    }, 100);   
}

function hideStatusMessage() {
    if (globalStatusMessageDialog) {
        globalStatusMessageDialog.hide();
        if (globalStatusMessageDialog.onHideCallBack != null) {
            globalStatusMessageDialog.onHideCallBack(globalStatusMessageDialog);
        }
    }
}

var popUpDialogs = [];

function openMainPopup(id, conf, focusLast) {
    if (popUpDialogs[id]) {
        popUpDialogs[id].hide();
    }

    // Default placement, to prevent jitter
    conf.x = 200;
    conf.y = 200;

    // Prevent title from being outside the window
    conf.constraintoviewport = true;

    document.getElementById(id).style.display = '';
    var popUpDialog = new YAHOO.widget.Dialog(id, conf);
    popUpDialog.render(document.body);
    if (!isOpenSocial) {
        popUpDialog.center();
    }
    if (isFacebook) {
        popUpDialog.cfg.setProperty("y", 350);
    }
    popUpDialog.show();
    if (focusLast) {
        popUpDialog.focusLast();
    }

    popUpDialogs.push(popUpDialog);
}

function closeMainPopup(keepDialog) {
    if (popUpDialogs.length == 0) {
        return;
    }

    var popupDialog = popUpDialogs.pop();
    if (popupDialog) {
        // this is a workaround, for the case we have iframe in the dialog. in this case the focus never come back to the main window. so we take the focus back before closing hte dialog.
        if (document.getElementById("destPickerInput1") != null) {
            // we set the focus to the main top AC
            document.getElementById("destPickerInput1").focus();
        }
        popupDialog.hide();
        if(!keepDialog){
            // we keep the dialog in casse we are going to use it more than once. otherwie we lose the dom content
            popupDialog.destroy();
        }else{
            // just hide the content
            popupDialog.element.style.display = "none";
        }
        popupDialog = null;
    }
}


/**
 * Overrides the Yahoo method for using our dtyle of buttons.
 * See container.js, YAHOO.widget.Dialog.prototype.configButtons.
 */
function configButtons(type, args, obj) {
    var buttons = args[0];
    this.buttonSpan = document.createElement("div");
    //this.buttonSpan.className = "button-group";

    for (var b = 0; b < buttons.length; b++) {
        var button = buttons[b];

        var htmlButton = document.createElement("span");
        if (isFacebook) {
            htmlButton.innerHTML = '<input type="button" name="blue_btn" class="blue_btn" value="' + button.text + '">';
        } else {
            var btnColor;
            if (isOpenSocial) {
                btnColor = 'blue';
            } else {
                btnColor = 'greeni';
            }
            htmlButton.innerHTML = '<table border="0" cellpadding="0" cellspacing="0" style="cursor:pointer; display:inline;">' +
                                   '<tbody><tr>' +
                                   '<td style="width:3px"><img src="' + imageBaseUrl + 'images/btn_' + btnColor + '_left.gif"></td>' +
                                   '<td class="btn_greeni"><a class="btn_greeni">' + button.text + '</a></td>' +
                                   '<td style="width:3px"><img src="' + imageBaseUrl + 'images/btn_' + btnColor + '_right.gif"></td>' +
                                   '</tr></tbody>' +
                                   '</table>&nbsp;';
        }

        if (button.isDefault) {
            //htmlButton.className = "default";
            this.defaultHtmlButton = htmlButton;
        }

        YAHOO.util.Event.addListener(htmlButton, "click", button.handler, this, true);

        this.buttonSpan.appendChild(htmlButton);
        button.htmlButton = htmlButton;

        if (b == 0) {
            this.firstButton = button.htmlButton;
        }

        if (b == (buttons.length - 1)) {
            this.lastButton = button.htmlButton;
        }
    }

    this.setFooter(this.buttonSpan);

    this.cfg.refireEvent("iframe");
    this.cfg.refireEvent("underlay");
}

/*
function showFeedbackDialog() {
    var conf = {
        width: '600px',
        height: '400px',
        fixedcenter:true,
        modal:true,
        draggable:true,
        close: true,
        zIndex: 100
    };

    document.getElementById('feedback').style.display = '';
    var dialog = new YAHOO.widget.SimpleDialog('feedback', conf);
    document.getElementById("feedackInDialog").value = 'true';
    dialog.setHeader('Feedback');
    dialog.render();
    dialog.show();
}
*/

function placeElement(ele, contextElement, xOffset, yOffset) {
    if (ele == null) {
        return;
    }

    if (contextElement == null) {
        return;
    }

    var newX = findPosX(contextElement);
    var newY = findPosY(contextElement);

    newX += xOffset;
    newY += yOffset;

    ele.style.display = '';
    ele.style.left = newX + 'px';
    ele.style.top = newY + 'px';
}
;

function isHomepageView() {
    return !isMainView();
}
;

function isMainView() {
    return document.getElementById('mainContentDiv');
}
;

function initAutoComplete(inputEleId, containerEleId, queryURL, inputIDEleId, onSelectCallBackFn, showIcons, initValue, showAddYourOwn) {
    var oACDS = new YAHOO.widget.DS_XHR(queryURL, ["\n", "\t"]);
    oACDS.responseType = YAHOO.widget.DS_XHR.prototype.TYPE_FLAT;
    oACDS.maxCacheEntries = 60;
    oACDS.queryMatchContains = true;

    if (initValue != null) {
        document.getElementById(inputEleId).value = initValue;
    }

    // Instantiate first auto complete
    var myAutoComp = new YAHOO.widget.AutoComplete(inputEleId, containerEleId, oACDS);
    // make sure myAutoComp is local
    myAutoComp.queryDelay = 0.5;
    // seconds before sending the request
    myAutoComp.forceSelection = true;
    myAutoComp.autoHighlight = false;
    myAutoComp.typeAhead = false;
    myAutoComp.animVert = false;
    myAutoComp.minQueryLength = 2;
    //myAutoComp.animSpeed = 0.5;
    myAutoComp.maxResultsDisplayed = 40;

    // this solves the IE problem with selet box under the div
    myAutoComp.useIFrame = true;

    myAutoComp.inputIDEleId = inputIDEleId;
    myAutoComp.onSelectCallBackFn = onSelectCallBackFn;
    myAutoComp.showIcons = showIcons;
    myAutoComp.addCustomField = showAddYourOwn;

    myAutoComp.textboxKeyEvent.subscribe(myOnTextboxKey);
    myAutoComp.textboxBlurEvent.subscribe(myOnTextboxBlur);
    myAutoComp.itemSelectEvent.subscribe(myOnItemSelect);
    myAutoComp.textboxFocusEvent.subscribe(myOnTextboxFocus);

    function setInpuIdSelection(oAutoComp, value, data) {
        if (oAutoComp.inputIDEleId != null) {
            var idEle = document.getElementById(oAutoComp.inputIDEleId);
            if (idEle != null) {
                idEle.value = value;
            }
        }
        if (oAutoComp.onSelectCallBackFn) {
            if (value != null && data != null) {
                oAutoComp.onSelectCallBackFn(value, data);
            }
        }
    }
    ;

    myAutoComp.formatResult = function(oResultItem, sQuery) {
        var sKey = oResultItem[0];
        //var sName = oResultItem[1];
        //var aMarkup = [sKey];
        var aMarkup = ["<span style='color: #3B5296'>",
                sKey,
                "</span>"
                ];

        // in case there are no results we return one item with no id and no name
        if (oResultItem[1] == '') {
            aMarkup = [ResourceBundle.getString("noMatchFound")];
        } else {
            var index = sKey.search(new RegExp("\\b" + sQuery, "i"));
            if (index < 0) {
                index = 0;
            }
            var head = sKey.substring(0, index);
            var match = sKey.substring(index, index + sQuery.length);
            var tail = sKey.substring(index + sQuery.length);
            var image = "";
            if (this.showIcons) {
                image = "<image src='" + imageBaseUrl + getItemIcon(oResultItem[2]) + "'/>&nbsp;";
            }

            aMarkup = ["<div style='color: #3B5296'>",
                    image,
                    head,
                    "<span style='font-weight:bold'>",
                    match,
                    "</span>",
                    tail,
                    "</div>"];
        }

        return (aMarkup.join(""));
    };

    myAutoComp.formatCustomFieldResult = function(oResultItem, sQuery) {
        if (!this.addCustomField) {
            return "";
        }
        var image = "<image src='" + imageBaseUrl + "images/ic_plus.gif'/>&nbsp;";
        var aMarkup = ["<div style='padding-left:15px; padding-top:8px; color: #3B5296' onclick='createEntity()'>",
                image,
                ResourceBundle.getString("addNewPlace"),
                "</div>"];

        return (aMarkup.join(""));
    };

    myAutoComp.clearValues = function(cleanValue) {
        this.dataSource.flushCache();
        if (cleanValue) {
            if (this.inputIDEleId != null) {
                var idEle = document.getElementById(this.inputIDEleId);
                idEle.value = "";
            }
            var textInput = document.getElementById(inputEleId);
            textInput.value = "";
        }
    };

    function myOnItemSelect(sType, aArgs) {
        var oAutoComp = aArgs[0];
        var oItem = aArgs[1];
        if (oItem._oResultData != null) {
            setInpuIdSelection(oAutoComp, oItem._oResultData[1], oItem._oResultData);
        }
    }
    ;

    function myOnTextboxKey(sType, aArgs) {
        var oAutoComp = aArgs[0];
        // mark selection false when there is some manuall modification
        setInpuIdSelection(oAutoComp, "", null);
    }
    ;

    function myOnTextboxBlur(sType, aArgs) {
        var oAutoComp = aArgs[0];
        if (!oAutoComp._bItemSelected) {
            // clear the selection
            setInpuIdSelection(oAutoComp, "", null);
        }
    }
    ;

    function myOnTextboxFocus(sType, aArgs) {
        var textInput = document.getElementById(inputEleId);
        if (textInput.value == initValue) {
            textInput.value = "";
        }
    }
    ;

    return myAutoComp;
}
;

function openDetailsWindow(url, width, height) {
    var windowParams = 'location=no, menubar=no, toolbar=no, scrollbars=yes, resizable=yes, top=0, left=';
    var name = 'details';

    if (width) {
        windowParams = (window.screen.width - width) + ', width=' + width;
        name = name + '_' + width;
    } else {
        windowParams = windowParams + (window.screen.width - 800) + ', width=800';
    }
    if (height != null) {
        windowParams = windowParams + ', height=' + height;
        name = name + '_' + height;
    }

    window.open(url, name, windowParams);
}
;


// calendar start ----------------------------------------------------------------------------
function initCalendar(containerId, dateInputId, dateImageId) {
    var currentDate = new Date();
    var inputField = document.getElementById(dateInputId);

    // since this control requilr a global variable . I am using the eval to define a unique one. above is the streight forward, but it is not taking care of multiple callander at the same time
    var calVarName = "cal_" + currentDate.getTime();
    // define the variable as global. var name and 1st argument must be the same name.
    eval(calVarName + "= new YAHOO.widget.CalendarGroup('" + calVarName + "', containerId); ");
    // define a local var to make it easy to programm.
    eval("var cal =" + calVarName);

    cal.renderCellDefault = function(workingDate, cell) {
        cell.innerHTML = '<a>' + this.buildDayLabel(workingDate) + "</a>";
    };

    cal.onSelect = function() {
        inputField.value = date2String2(this.getSelectedDates()[0]);
        if (inputField.onchange) {
            inputField.onchange(inputField);
        }

        hideCal();
    };

    cal.selectEvent.subscribe(cal.onSelect, cal, true);

    var dateImage = document.getElementById(dateImageId);
    YAHOO.util.Event.addListener(dateImage, "click", showCal);

    function showCal(e) {
        var date;
        if (inputField.value == null || inputField.value == '') {
            date = currentDate;
        } else {
            date = string2Date(inputField.value);
            if (isNaN(date)) {
                date = currentDate;
            }
        }

        var monthyear = date2String2(date, 'MM/yyyy');
        var selectedDate = date2String2(date);
        cal.cfg.queueProperty("pagedate", monthyear, false);
        cal.cfg.queueProperty("selected", selectedDate, false);
        cal.cfg.fireQueue();
        cal.render();

        document.getElementById(containerId).style.display = 'block';
        YAHOO.util.Event.addListener(document, "click", clickTest);
    }
    ;

    function hideCal(e) {
        document.getElementById(containerId).style.display = 'none';
        YAHOO.util.Event.removeListener(document, "click", clickTest);
    }
    ;

    function clickTest(e) {
        var targ = (e.target) ? e.target : e.srcElement;
        if (targ == document.getElementById(containerId) || YAHOO.util.Dom.isAncestor(containerId, targ))
            return;
        if (targ == document.getElementById(dateImageId) || YAHOO.util.Dom.isAncestor(dateImageId, targ))
            return;

        hideCal();
    }

    return cal;
}
;
// calendar end ----------------------------------------------------------------------------

// some more general ----------------------------------------------------------------------------
var _hrLocaleDate = {
    Months:[ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    Days:[ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
    StartDay: 0 //Sunday
};

function date2String2(date, format) {
    return date2String(date.getFullYear(), date.getMonth(), date.getDate(), format);
}
;

function date2String(iYear, iMonth, iDay, format) {
    if (! format) {
        format = defaultDateFormat;
    }

    var sValue = '';
    //Sorry for IE5.0 Users, doesnt support the replace function
    if (navigator.userAgent.toLowerCase().indexOf('msie 5.0') != -1) {
        sValue = iMonth + '/' + iDay + '/' + iYear;
    } else {
        sValue = format.replace(/(yyyy|yy|MMMM|MMM|MM|M|dddd|ddd|dd|d)/g,
                function($1) {
                    switch ($1) {
                        case 'yyyy':     return iYear;
                        case 'yy':         return ('' + iYear).substr(2, 4);
                        case 'MMMM':     return _hrLocaleDate.Months[iMonth];
                        case 'MMM':      return _hrLocaleDate.Months[iMonth + 12];
                        case 'MM':      return (iMonth < 9) ? '0' + (iMonth + 1) : iMonth + 1;
                        case 'M':        return iMonth + 1;
                        case 'dddd':     return _hrLocaleDate.Days[new Date(iYear, iMonth, iDay).getDay()];
                        case 'ddd':     return _hrLocaleDate.Days[new Date(iYear, iMonth, iDay).getDay() + 7];
                        case 'dd':       return (iDay < 10) ? '0' + iDay : iDay;
                        case 'd':       return iDay;
                    }
                });
    }
    return sValue;
}
;

// Special thanks to Matt Kruse <matt@mattkruse.com> (http://www.mattkruse.com/) for writing the original script
// Convert a Date String => Date Object, depending on sFormat
function string2Date(sValue, sFormat) {
    var oDate = new Date("");
    if (!sValue) {
        return oDate;
    }

    if (! sFormat) {
        sFormat = defaultDateFormat;
    }

    var iValue = 0;
    var iFormat = 0;
    var cChar,sToken;

    var sYear = oDate.getFullYear() + '';
    var sMonth = oDate.getMonth() + 1 + '';
    var sDate = oDate.getDate() + '';

    while (iFormat < sFormat.length) {
        cChar = sFormat.charAt(iFormat);
        sToken = '';
        while ((sFormat.charAt(iFormat) == cChar) && (iFormat < sFormat.length)) sToken += sFormat.charAt(iFormat++);

        if (sToken == 'yyyy' || sToken == 'yy') {
            sYear = _datepicker_getInt(sValue, iValue, sToken.length, sToken.length);
            if (sYear == null) sYear = oDate.getFullYear() + '';
            iValue += sYear.length;
            if (sYear.length == 2) {
                iYear = parseInt(sYear, 10);
                sYear = 2000 + iYear;
            }
        } else if (sToken == 'MMMM' || sToken == 'MMM') {
            for (var i = 0; i < _hrLocaleDate.Months.length; i++) {
                if (sValue.substring(iValue, iValue + _hrLocaleDate.Months[i].length).toLowerCase() == _hrLocaleDate.Months[i].toLowerCase()) {
                    if (sToken == 'MMMM' || ( sToken == 'MMM' && i > 11 )) {
                        sMonth = (i > 11) ? i - 11 : i + 1;
                        iValue += _hrLocaleDate.Months[i].length;
                        break;
                    }
                }
            }
        } else if (sToken == 'ddd' || sToken == 'dddd') {
            for (var i = 0; i < _hrLocaleDate.Days.length; i++) {
                if (sValue.substring(iValue, iValue + _hrLocaleDate.Days[i].length).toLowerCase() == _hrLocaleDate.Days[i].toLowerCase()) {
                    iValue += _hrLocaleDate.Days[i].length;
                    break;
                }
            }
        } else if (sToken == 'MM' || sToken == 'M') {
            sMonth = _datepicker_getInt(sValue, iValue, sToken.length, 2);
            if (sMonth == null) sMonth = oDate.getMonth() + 1 + '';
            iValue += sMonth.length;

        } else if (sToken == 'dd' || sToken == 'd') {
            sDate = _datepicker_getInt(sValue, iValue, sToken.length, 2);
            if (sDate == null) sDate = oDate.getDate() + '';
            iValue += sDate.length;
        }
        else {
            if (sValue.substring(iValue, iValue + sToken.length) != sToken) {
            }
            else iValue += sToken.length;
        }
    }
    return new Date(sYear, sMonth - 1, parseInt(sDate, 10));
}
;

var _oIntPattern = /^[-\d]{1,}$/;
//Helper function sees if the value is a Int
function _datepicker_getInt(sValue, i, iMin, iMax) {

    for (var j = iMin; j >= iMax; j--) {
        var sToken = sValue.substring(i, i + j);
        if (_oIntPattern.test(sToken)) return sToken;
    }
    return null;
}
;

function xmlEscape(xml) {
    return xml.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
;

function getMainContentTripId() {
    var tripRoot = document.getElementById("iti_tree_root");
    if (tripRoot == null) {
        return null;
    }

    return bpc.xpath('string(@tripId)', tripRoot);
}
;

function onMainScrollChange() {
    setLastTripScroll();
}
;

function bestFitScroll() {
    if (!restoreLastTripScroll()) {
        window.scrollTo(0, 0);
    }
}
;

var tripScrollPos_lastTripId;
var tripScrollPos_scrollPos;
var tripScrollPos_block = false;
// the block means that if we leave the trip, the next time we com eback it will clock the set till we call restore first

function setLastTripScroll() {
    var activeTripId = getMainContentTripId();
    if (tripScrollPos_block)
        return;
    if (activeTripId != null) {
        tripScrollPos_lastTripId = activeTripId;
        if (isIE()) {
            tripScrollPos_scrollPos = document.body.scrollTop;
        } else {
            tripScrollPos_scrollPos = window.pageYOffset;
        }

    } else {
        tripScrollPos_block = true;
    }
}
;

function restoreLastTripScroll() {
    var activeTripId = getMainContentTripId();
    if ("" + activeTripId == "" + tripScrollPos_lastTripId) {
        window.scrollTo(0, tripScrollPos_scrollPos);
        tripScrollPos_block = false;
        return true;
    }
    tripScrollPos_block = false;
    return false;
};

function isIE() {
    return (navigator.appName == "Microsoft Internet Explorer");
};

function get_firstchildNode(node)
{
    var x = node.firstChild;
    while (x.nodeType != 1)
    {
        x = x.nextSibling;
    }
    return x;
};

function get_nextSiblingNode(node)
{
    var x = node.nextSibling;
    while (x && x.nodeType != 1)
    {
        x = x.nextSibling;
    }
    return x;
};

function get_previosSiblingNode(node)
{
    var x = node.previousSibling;
    while (x && x.nodeType != 1)
    {
        x = x.previousSibling;
    }
    return x;
};

function get_lastchild(n)
{
    var x = n.lastChild;
    while (x.nodeType != 1)
    {
        x = x.previousSibling;
    }
    return x;
}

function initAjaxAnywhere(aa, trivial) {
    // Custom field
    aa.caller = null;

    aa.getGlobalScriptsDeclarationsList = function(script) {
        return this.globalFunctionNames;
    };

    aa.handlePrevousRequestAborted = function() {
        if (debug) {
            showStatusMessage("Debugging Warning", "Previous AJAX request dropped: " + this.prevCaller +
                                                   ". New request: " + this.caller);
        }

        if (! trivial) {
            makeAjaxCall(baseUrl + "log.do?level=warn&message=Previous AJAX request dropped: " + this.prevCaller +
                         "; new request: " + this.caller, null, "log", true);
        }
    };

    aa.handleWrongContentType = function(contentType) {
        if (debug) {
            showStatusMessage("Debugging Warning", "Wrong content-type: " + contentType + "; caller: " + this.caller);
        }

        if (! trivial) {
            makeAjaxCall(baseUrl + "log.do?level=warn&message=Wrong content-type: " + encodeURIComponent(contentType) +
                         "; caller: " + this.caller, null, "log", true);
        }
    };

    aa.handleException = function(type, details) {
        if (debug) {
            showStatusMessage("Debugging Warning", "Server-side exception occurred: " + type + ". Details: " +
                                                   details + "; caller: " + this.caller);
        }

        if (! trivial) {
            makeAjaxCall(baseUrl + "log.do?message=Server-side exception occurred: " + encodeURIComponent(type) +
                            ". Details: " + encodeURIComponent(details) + "; caller: " + this.caller,
                            null, "log", true);
        }
    };

    aa.handleHttpErrorCode = function(code, responseText) {
        if (! trivial) {
            showStatusMessage(ResourceBundle.getString("oops"), ResourceBundle.getString("networkIssue"));
            handleError("AJAX request failed: " + this.caller + "; error code: " + code + "; response: " + responseText, true);
            hideLoadingMessage();
        }
    };

    aa.onBeforeResponseProcessing = function() {
        // Clear the previous handler
        if (typeof onAjaxPageLoad == 'function') {
            onAjaxPageLoad = null;
        }

        setStartResponseTime(); //make sure we set the start time

        // reset the array that holds the js segment index to execute.
        ajaxJsSegmentsIndex[this.id] = new Array();

        if (! trivial) {
            showLoadingMessage();
        }
    };

    aa.onAfterResponseProcessing = function() {
        if (typeof onAjaxPageLoad == 'function') {
            onAjaxPageLoad();
        }

        if (this.mask) {
            this.mask.hideMask();
            this.mask = null;
        }
    };

    aa.showLoadingMessage = function() {
        if (! trivial) {
            showLoadingMessage();
        }
    };

    aa.hideLoadingMessage = function() {
        // we already take care of it later.
    };
}

// Initialize the default instance
initAjaxAnywhere(ajaxAnywhere);

function getAjaxAnywhere(id, trivial) {
    if (! id) {
        // Use default instance
        return ajaxAnywhere;
    }

    var aa = AjaxAnywhere.findInstance(id);
    if (aa) {
        return aa;
    }

    aa = new AjaxAnywhere();
    aa.id = id;
    aa.bindById();
    initAjaxAnywhere(aa, trivial);
    return aa;
}

function makeAjaxCall(url, zonesToRefresh, id, trivial, sync) {
    if (unloading) {
        return;
    }

    onStartAjaxCall(url);

    var aa = getAjaxAnywhere(id, trivial);

    // Custom fields
    aa.prevCaller = aa.caller;
    aa.caller = encodeURIComponent(url);

    if (sync) {
        buildMask(aa);
    }

    if (! trivial) {
        aa.caller += "; stack: " + getStackTrace();
    }

    // clear the functionames before request
    aa.globalFunctionNames = [];

    try {
        aa.getAJAX(url, zonesToRefresh);
    } catch (e) {
        handleException(e, trivial);
    }

    resetPing();

    if (! trivial) {
        try {
            // Google analytics
            urchinTracker(encodeURIComponent(url));
        } catch(e) {
            handleException(e, true);
        }
    }
}

function handleException(e, debugOnly) {
    handleError(e.name + ": " + e.description + "; " + e.message, debugOnly);

    if (debug) {
        throw e;
    }
}

function handleError(debugMessage, debugOnly, nonDebugMessage) {
    var message = null;
    if (debug) {
        message = debugMessage;
    } else if (nonDebugMessage != null) {
        message = nonDebugMessage;
    } else if (! debugOnly) {
        message = ResourceBundle.getString("thisDidntWork");
    }

    if (message) {
        showStatusMessage(ResourceBundle.getString("oops"), message, null, null, null, null, true);
    }

    makeAjaxCall(baseUrl + "log.do?message=" + encodeURIComponent(debugMessage) + "; stack: " + getStackTrace() + (debugOnly? "&level=warn" : ""), null, "log", true);
}

/**
 * Adds the given function to the page scope.
 * Call this for functions contained in ajax-retrieved script blocks.
 */
function declareFunction(aaInstanceId, functionName) {
    var globalFunctionNames = AjaxAnywhere.findInstance(aaInstanceId).globalFunctionNames;
    globalFunctionNames[globalFunctionNames.length] = functionName;
}

function buildMask(aa) {
    if (aa.mask) {
        return;
    }
    
    aa.mask = new YAHOO.widget.Panel("maskPanel", {modal: true});
    aa.mask.buildMask();
    aa.mask.showMask();
}

function validateForm(formName) {
    var form = document[formName];
    if (form.className.indexOf("validate") < 0) {
        return true;
    }

    return FIC_checkForm(form, true);
}

function submitAjaxForm(formName, onSubmitHandler, id, extraAnalyticsParam) {
    if (unloading) {
        return;
    }

    if (! validateForm(formName)) {
        return;
    }

    var aa = getAjaxAnywhere(id);
    aa.formName = formName;

    var form = aa.findForm();
    var action = form.attributes["action"].nodeValue;

    if (form.className.indexOf("async") < 0) {
        buildMask(aa);
    }

    // Custom fields
    aa.prevCaller = aa.caller;
    aa.caller = encodeURIComponent(action) + "; stack: " + getStackTrace();

    onStartAjaxCall(formName);

    aa.onRequestSent = function() {
        try {
            // Google analytics
            var url = action.substring(action.lastIndexOf("/") + 1);

            if (extraAnalyticsParam != null) {
                url += "?" + extraAnalyticsParam;
            }

            urchinTracker(encodeURIComponent(url));
        } catch(e) {
            handleException(e, true);
        }

        if (onSubmitHandler) {
            onSubmitHandler();
        }
    };

    // clear the functionames before request
    aa.globalFunctionNames = [];
    aa.getGlobalScriptsDeclarationsList = function() {
        return this.globalFunctionNames;
    };

    try {
        aa.submitAJAX();
    } catch (e) {
        handleException(e);
    }

    resetPing();

    // Cleanup
    aa.onRequestSent = function() {
    };
}
;

function submitForm(formName) {
    if (! validateForm(formName)) {
        return;
    }

    document[formName].submit();
}
;

function showHide(id) {
    var el;
    if ("string" !== typeof id) {
        el = id;
    } else {
        el = document.getElementById(id)
    }

    var style = el.style;
    if (style.display == "none") {
        style.display = "";
    } else {
        style.display = "none";
    }
}
;

function clearInitialValue(field) {
    if (field.value == field.defaultValue) {
        field.value = '';
    }
}
;

function restoreInitialValue(field) {
    if (field.value == '') {
        field.value = field.defaultValue;
    }
}
;

function purgeMemory(element) {
    var atrributes = element.attributes;
    if (atrributes) {
        var length = atrributes.length;
        for (var i = 0; i < length; i += 1) {
            var name = atrributes[i].name;
            if (typeof atrributes[i] === 'function') {
                element[name] = null;
            }
        }
    }

    var children = element.childNodes;
    if (children) {
        var length = children.length;
        for (var i = 0; i < length; i += 1) {
            purgeMemory(children[i]);
        }
    }
}
;

function onWindowResize() {
    if (typeof repositionGlobalMap !== 'undefined')
        repositionGlobalMap();
}
;

// this function is called when initiated as an ajax call
function onStartAjaxCall(url) {
    setStartAjaxCallTime(url);
}

// this function is called only when full page starts rendering. (non-ajax)
function onStartPageRender(showLoadMessage) {
    if (showLoadMessage) {
        showLoadingMessage();
    }
    setStartResponseTime();
}

// this function is called only when we start the js part both ajax and non-ajax
function onStartPageLoadJS(showLoadMessage) {
    if (showLoadMessage) {
        showLoadingMessage();
    }
    setStartJSResponseTime();
}

// this function is called at teh end of the page rending both ajax and non-ajax
function onEndPageRender() {
    hideLoadingMessage();
    setEndResponseTime();
}

var perfAjaxSendTimeStamp = 0;
var perfStartResponseTimeStamp = 0;
var perfStartJSResponseTimeStamp = 0;
var perfLastURL;
//var perfAjaxURL;
function setStartAjaxCallTime(url) {
    if (typeof isPerformanceDebug !== 'undefined' && isPerformanceDebug) {
        perfAjaxSendTimeStamp = new Date().getTime();
        perfLastURL = url;
    }
}
;

function setStartResponseTime() {
    if (typeof isPerformanceDebug !== 'undefined' && isPerformanceDebug) {
        perfStartResponseTimeStamp = new Date().getTime();
    }
}
;

function setStartJSResponseTime() {
    if (typeof isPerformanceDebug !== 'undefined' && isPerformanceDebug) {
        perfStartJSResponseTimeStamp = new Date().getTime();
    }
}
;

function setEndResponseTime() {
    if (typeof isPerformanceDebug !== 'undefined' && isPerformanceDebug) {
        var perfEndResponseTimeStamp = new Date().getTime();
        var debugDiv = document.getElementById("performanceTraceDiv");
        var out = perfLastURL + "<br/> net + ser : " + (perfStartResponseTimeStamp - perfAjaxSendTimeStamp) + " ms <br/>";
        out += " js : " + (perfEndResponseTimeStamp - perfStartJSResponseTimeStamp) + "ms <br/> rendering : " + (perfEndResponseTimeStamp - perfStartResponseTimeStamp) + " ms <br/>------------------<br/>";
        debugDiv.innerHTML = debugDiv.innerHTML + out;
    }
}
;

function clearDebugTrace() {
    if (typeof isPerformanceDebug !== 'undefined' && isPerformanceDebug) {
        document.getElementById('performanceTraceDiv').innerHTML = '';
    }
}
;

function getKeyCode(event) {
    if (window.event) {
        return window.event.keyCode;
    }

    if (event) {
        return event.which;
    }

    return null;
}

function noEnter(event) {
    return getKeyCode(event) != 13;
}

function submitOnEnter(form, event) {
    if (getKeyCode(event) == 13) {
        submitForm(form.name);
        return false;
    }

    return true;
}

function submitAjaxOnEnter(form, event, onSubmitHandler, extraAnalyticsParam) {
    if (getKeyCode(event) == 13) {
        var formName = form.name;
        submitAjaxForm(formName, onSubmitHandler, null, extraAnalyticsParam);
        return false;
    }

    return true;
}

function getURLfromForm(ele) {
    if (!ele) {
        return "";
    }

    var searchParam = ele.action + "?";
    var formElements = ele.elements;
    for (var i = 0; i < formElements.length; i++) {
        if (i > 0) {
            searchParam += "&";
        }
        if (formElements[i].name) {
            searchParam += formElements[i].name;
            searchParam += "=";
            var formEleValue = escape(formElements[i].value);
            // this is a local fix for to allow spaces in the search. so we don't need %20. need to find a better solution here (one day;)
            formEleValue = formEleValue.replace(/%20/g, " ");
            searchParam += formEleValue;
        }
    }

    return searchParam;
}

function setFormHistory(formEle) {
    setHistory(getURLfromForm(formEle));
}

// this is a fix for the history comp with iframes. when the inner iframe is refreshed the default history is reloadede.
var blockReloadHistoryOnce = false;

var blockReloadHistory = false;
function setHistory(historyPath) {
    // itzik: temporary disabled
    /*blockReloadHistory = true;
    setTimeout("blockReloadHistory = false;", 500);
    //alert("navigate: " + historyPath);
    YAHOO.util.History.navigate("tripwiser", historyPath);*/
}

function setHistory2(section, url) {
    setHistory("section=" + section + "&url=" + url);
}

function setDummyHistory() {
    var currentSection = YAHOO.util.History.getCurrentState("tripwiser");
    if (YAHOO.util.History.getQueryStringParameter("section", currentSection) == "dummy") {
        // do nothing
        return;
    }

    setHistory("section=dummy");
}

function reloadHistory(historyPath) {
    //    if(blockReloadHistoryOnce){
    //        blockReloadHistoryOnce = false;
    //        return;
    //    }

    if (!blockReloadHistory) {
        //alert("reloadHistory: " + historyPath);
        historyPath = decodeURIComponent(historyPath);
        //historyPath = xmlEscape(historyPath);
        /*if(historyPath.indexOf("section=dummy") >=0 ){
            // this is an indication that we got to a dummy node in the hash. meening we need to go back with the browser.
            window.history.back();
            return;
        } */
        // make the call to load the back url
        var url = parseSection(historyPath);
        if (url.indexOf('?') > 0) {
            url += "&noHistory";
            // make sure the response does not added to the history
        } else {
            url += "?noHistory";
            // make sure the response does not added to the history
        }

        makeAjaxCall(url, 'mainPage');
        //location.replace(url);
    }
}

function backHistory(historyPath) {
    window.history.back();
}

function forwardHistory(historyPath) {
    window.history.forward();
}

function parseSection(historyPath) {
    return historyPath.substring(historyPath.indexOf('url=') + 4);
}

function cleanUserPasswordFileds() {
    if (document.getElementById('loginUserField') != null) {
        document.getElementById('loginUserField').value = '';
        document.getElementById('loginPasswordField').value = '';
    }

    if (document.getElementById('registrationPasswordField') != null) {
        document.getElementById('registrationPasswordField').value = '';
        document.getElementById('registrationUserField').value = '';
    }
}

function showLoadingMessage() {
    document.getElementById("loading").style.display = "";
}

function hideLoadingMessage() {
    document.getElementById("loading").style.display = "none";
}

function onPageScroll() {
    repositionItemDetailDiv(null, true);
}


/* url builder -------------------- */

function getTripSearchUrl(additionalParams) {
    var action;
    if (seoUrlMode) {
        action = "trip_plans";
    } else {
        action = "search_trip_res.do";
    }
    return action + '?' + (additionalParams != null ? additionalParams : "");
}

function getSearchUrl(type, day, referenceEntityId) {
    var searchSeoUrl = {
        site: 'destination_finder',
        activity: 'things_to_do_finder',
        restaurant: 'restaurant_finder',
        hotel: 'hotel_finder'
    };

    var url;
    if (seoUrlMode) {
        url = searchSeoUrl[type];
    } else {
        url = "search_generic.do";
    }

    url += '?type=' + type;

    if (day != null) {
        url += '&day=' + day;
    }

    if (referenceEntityId != null) {
        url += '&refEntityId=' + referenceEntityId;
    }

    /*
    if (keywords) {
        url += "&s_key=" + keywords;
    }
    */

    return url;
}
;

function trimString(sInString) {
    sInString = sInString.replace(/^\s+/g, "");
    // strip leading
    return sInString.replace(/\s+$/g, "");
    // strip trailing
}
/* end url builder -------------------- */

/* start string resources -------------------- */
var ResourceBundle = {};
ResourceBundle.getString = function(key) {
    var value = jsResources[key];
    if (value == null) {
        return key;
    }
    return value;
}

ResourceBundle.formatString = function(key) {
    var value = jsResources[key];
    if (value == null) {
        return key;
    }

    for (var i = 1; i <= arguments.length; i++)
    {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        value = value.replace(re, arguments[i]);
    }
    return value;
}

/* end string resources -------------------- */


function toggleElements(id1, id2) {
    var ele1 = document.getElementById(id1);
    var ele2 = document.getElementById(id2);
    if (ele1 != null) {
        if (ele1.style.display == "") {
            ele1.style.display = "none";
        } else {
            ele1.style.display = "";
        }
    }

    if (ele2 != null) {
        if (ele2.style.display == "") {
            ele2.style.display = "none";
        } else {
            ele2.style.display = "";
        }
    }
}

// This function returns the name of a given function. It does this by
// converting the function to a string, then using a regular expression
// to extract the function name from the resulting code.
function funcName(f) {
    var s = f.toString().match(/function (\w+)\(/);
    if ((s == null) || (s.length == 0)) {
        return "anonymous";
    }

    return s[1];
}

// This function returns a string that contains a "stack trace."
function getStackTrace() {
    var res = "\n";

    try {
        // Loop through the stack of functions, using the caller property of
        // one arguments object to refer to the next arguments object on the
        // stack.
        for (var f = getStackTrace.caller; f != null; f = f.caller) {
            // Add the name of the current function to the return value.
            res += funcName(f) + "(";

            for (var i = 0; i < f.arguments.length; i++) {
                res += f.arguments[i] + ", ";
            }

            res += ")\n";

            // Because of a bug in Navigator 4.0, we need this line to break.
            // a.caller will equal a rather than null when we reach the end
            // of the stack. The following line works around this.
            if (f.caller == f) {
                break;
            }

            if (res.length > 1000) {
                // Handle weird loops in the stack
                break;
            }
        }
    } catch(e) {

    }

    return encodeURIComponent(res);
}

function reloadPage() {
    try {
        window.top.location.reload();
    } catch (e) {
        if (isFacebook) {
            window.top.location = facebookCanvasPageUrl;
        } else {
            window.location.reload();
        }
    }
}

function toggleFacebookBox(link, boxId, hideCallback, showCallback) {
    var boxStyle = document.getElementById(boxId).style;
    if (boxStyle.display == "") {
        boxStyle.display = "none";
        link.className = "title_blue_11_close";
        link.parentNode.className = "title_close";

        if (hideCallback) {
            hideCallback();
        }
    } else {
        boxStyle.display = "";
        link.className = "title_blue_11_open";
        link.parentNode.className = "title_open";

        if (showCallback) {
            showCallback();
        }
    }
}

function reportAnalyticsImpl(page) {
    try {
        if (typeof urchinTracker != "function") {
            // Try again later
            return reportAnalytics(page);
        }

        urchinTracker(encodeURIComponent(page));
    } catch (e) {
        handleException(e, true);
    }
}

function reportAnalytics(page) {
    // Avoid delaying page load for this
    setTimeout(function() {reportAnalyticsImpl(page)}, 1000);
}

function pingServer() {
    makeAjaxCall(baseUrl + "keep_alive.do", null, "keepAlive", true);
}

var pingTimerId = null;
function setupPing() {
    // Every 10 min
    pingTimerId = setInterval(pingServer, 600000);
}

function resetPing() {
    if (pingTimerId) {
        clearInterval(pingTimerId);
    }

    setupPing();
}

function getForwardParams(forward) {
    if (isFacebook) {
        return 'fb_' + forward + '&mainLayout=fb_layout';
    }
    return forward;
}

function feedback() {
    if (isFacebook) {
        window.top.location = "http://www.facebook.com/apps/application.php?api_key=" + facebookApiKey + "#reviews";
    } else {
        makeAjaxCall(baseUrl + 'forward.do?forward=feedback');
    }
}

function openMeebo()
{
    var openWindow = window.open("", "tripwiser_help", "height=370, width=270,toolbar=no,scrollbars=" + scroll + ",menubar=no");
    if (openWindow.document.getElementById("tripwiser_meebo") == null) {
        openWindow.document.write("<HTML><TITLE>TripWiser chat</TITLE>");
        openWindow.document.write("<BODY");
        // this is zikziv
        /*openWindow.document.write("<div id=\"tripwiser_meebo\"><embed src=\"http://widget.meebo.com/mm.swf?BnNXxwcBFP\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"250\" height=\"350\"></embed>");*/
        // thsi is tripwiser
        openWindow.document.write("<div id=\"tripwiser_meebo\"><embed src=\"http://widget.meebo.com/mm.swf?NjquqyvvFi\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"250\" height=\"350\"></embed>");
        openWindow.document.write("</BODY>");
        openWindow.document.write("</HTML>");
    }

    openWindow.focus();
}

function validateUSDate(strValue) {
    var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
    //check to see if in correct format
    if (!objRegExp.test(strValue))
        return false; //doesn't match pattern, bad date

    var arrayDate = strValue.split('/');
    var monthfield = arrayDate[0]
    var dayfield = arrayDate[1]
    var yearfield = arrayDate[2]
    var dayobj = new Date(yearfield, monthfield - 1, dayfield)
    if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
        return false;
    }

    return true;
}

function cleanUp() {
    if (typeof GUnload == "function") {
        GUnload();
    }
}

function method_closure(object, method, opt_argArray) {
    return function() {
        return method.apply(object, opt_argArray);
    }
}

function buildAddressStr(street, city, state, country) {
    var address = new Array();
    if (street != null) {
        address.push(street);
    }

    if (city != null) {
        address.push(city);
    }

    if (state != null) {
        address.push(state);
    }

    if (country != null) {
        address.push(country);
    }

    return address.join(", ");
}

function FormatFloat(pFloat, pDp) {
    var m = Math.pow(10, pDp);
    return parseInt(pFloat * m, 10) / m;
}

function showMaxVideo(caption, bigVideo, smallVideoContainer, isDialog) {
    if (!isDialog && smallVideoContainer != null) {
        // reset the small just in case it is running
        var containerParent = smallVideoContainer.parentNode;
        var removedObject = containerParent.removeChild(smallVideoContainer);
        containerParent.appendChild(removedObject);
    }

    //bigVideo.style.display = "";
    showStatusMessage(caption != null ? caption : "video", bigVideo.innerHTML, ResourceBundle.getString("close"), onCloseVideo, null, null, null, 520, true, onCloseVideo);
}

function onCloseVideo(dialog) {
    // need to stop the video if it is running
    dialog.setBody("");
}

function browseEntity(nodeId, nodeType, name, logOperationSource) {
    var seoText = encodeURIComponent(name.replace(/, | \/ | |\//g, "_"));
    var url;
    if (nodeType == "theme") {
        url = "trip_theme-" + seoText + "?tid=" + nodeId;
    } else {
        var action;
        switch (nodeType) {
            case "activity":
                action = "trip_thing_to_do-";
                break;

            case "site":
                action = "trip_destination-";
                break;

            case "hotel":
                action = "trip_hotel-";
                break;

            case "restaurant":
                action = "trip_restaurant-";
                break;
        }

        url = action + seoText + "?itiNodeId=" + nodeId + "&eType=" + nodeType;
    }
    if (logOperationSource != null) {
        url += "&log_operation_source=" + logOperationSource;
    }

    goToUrl(url);
}

// ---- ratings general functions -----------------------------------
function updateRatingStars(baseId, rating) {
    for (var i = 1; i <= 5; i++) {
        var image;
        if (rating < i) {
            image = "star_off.gif";
        } else {
            image = "star_on.gif";
        }

        document.getElementById(baseId + "_" + i).src = imageBaseUrl + "images/" + image;
    }
}

function initRatingEvents(baseId, rating) {
    for (var i = 1; i <= 5; i++) {
        var image = document.getElementById(baseId + "_" + i);
        if (image == null) {
            // Try later
            setTimeout(function() {
                initRatingEvents(baseId, rating);
            }, 10);
            return;
        }

        image.onmouseout = function() {
            if (rating != null) {
                updateRatingStars(baseId, rating);
            } else {
                updateRatingStars(baseId, document.getElementById('editRating').value);
            }
        };
    }
}

function setRatingField(rating) {
    document.getElementById('editRating').value = rating;
}

function setRating(rating) {
    setRatingField(rating);
    updateRatingStars("dialog", rating);
}

// ---- end ratings general functions -----------------------------------

function editPlace(cellId, userPlaceId, viewUserId, rating, contextId, isVisited, contentPage, signUpSource, tripId) {
    var url = "pl_edit_place.do?cell_id=" + cellId;

    if (rating != null) {
        url += "&rating=" + rating;
    }

    if (isVisited != null) {
        url += "&isVisited=" + isVisited;
    }

    if (userPlaceId != null) {
        url += "&user_place_id=" + userPlaceId;
    }

    if (viewUserId != null) {
        url += "&view_user_id=" + viewUserId;
    }

    if (contextId != null && contextId.length > 0) {
        url += "&context_id=" + contextId;
    }

    if (contentPage) {
        url += "&content_page=true";
    }

    if (signUpSource) {
        url += "&sign_up_src=" + signUpSource;
    }

    if (tripId != null) {
        url += "&TripId=" + tripId;
    }

    makeAjaxCall(baseUrl + url + "&login_req=true&refresh_on_login=true");
}

function showMoreDesc() {
    document.getElementById('shortDescSpanId').style.display = 'none';
    document.getElementById('longDescSpanId').style.display = '';
    document.getElementById('moreDescId').style.display = 'none';
    document.getElementById('lessDescId').style.display = '';
}

function showLessDesc() {
    document.getElementById('shortDescSpanId').style.display = '';
    document.getElementById('longDescSpanId').style.display = 'none';
    document.getElementById('moreDescId').style.display = '';
    document.getElementById('lessDescId').style.display = 'none';
    goToUrl("#");
}

function printTrip(tripId) {
    window.open("trip_printable_ver.do?TripId=" + tripId, "tripWiserPrintWindow");
}
/*for video dialogs*/
function showEditVideosDlg(cellId, userPlaceId, isEditMode, command, needSignUp) {
    var url = "pl_edit_video.do?cell_id=" + cellId;
    if (userPlaceId != null) {
        url += "&user_place_id=" + userPlaceId;
    }
    if (isEditMode != null && !isEditMode) {
        url += "&edit_mode=false";
    } else {
        url += "&edit_mode=true";
    }
    if (command != null) {
        url += "&command=" + command;
    }

    if (needSignUp) {
        url += "&login_req&refresh_on_login&sign_up_src=add_video";
    }

    makeAjaxCall(url);
}

function formCheckAll(id, check) {
    var checkboxes = document.getElementById(id).getElementsByTagName("input");
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = check;
    }
}

function showEditPhotosDlg(cellId, userPlaceId, isEditMode, command, needSignUp) {
    var url = "pl_edit_photo.do?cell_id=" + cellId;
    if (userPlaceId != null) {
        url += "&user_place_id=" + userPlaceId;
    }
    if (isEditMode != null && !isEditMode) {
        url += "&edit_mode=false";
    } else {
        url += "&edit_mode=true";
    }
    if (command != null) {
        url += "&command=" + command;
    }
    if (needSignUp) {
        url += "&login_req&refresh_on_login&sign_up_src=add_photo";
    }

    makeAjaxCall(url);
}

/*Start TopPlacesManager - manages the top places selection*/
function TopPlacesManager(destinationList, destinationIds, addedPlacesWidth) {
    this.destinations = [];
    this.destinationList = document.getElementById(destinationList);
    this.destinationIds = document.getElementById(destinationIds);
    this.addedPlacesWidth = addedPlacesWidth;
    return this;
}

TopPlacesManager.prototype.addDestination = function(destId, destName, type, managerName, showDelete) {
    if (destId == null || destId == "" || this.destinations.length == 5) {
        return;
    }

    for (var i = 0; i < this.destinations.length; i++) {
        if (this.destinations[i].head == destId) {
            return;
        }
    }

    this.destinations.push({head: destId, tail: destName});
    this.updateDestinationIds();

    this.destinationList.appendChild(this.getDestItem(destId, destName, "destination", showDelete, type, managerName));
}

TopPlacesManager.prototype.getDestItem = function(destId, name, baseId, showDelete, type, managerName) {
    var icon = imageBaseUrl + getItemIcon(type);
    var destination = document.createElement("div");
    destination.id = baseId + destId;
    var width = this.addedPlacesWidth != null ? this.addedPlacesWidth : (isFacebook ? 120 : 280);
    var innerHtml = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"width:100%\"><tbody>" +
                    "<tr><td nowrap=\"true\">" +
                    "<div style=\"float: left\">" +
                    "<img src=\"" + icon + "\"/>&nbsp;" +
                    "</div>" +
                    "<div class=\"box_item\" style=\"width:" + width + "px; float: left\">" +
                    "<div class=\"tooltip textOverflow\" style=\"white-space: nowrap;width:" + width + "px;\" tooltipTitle=\"" + name + "\"> " +
                    "" + name + "</div>\n" +
                    "</div></td>";
    if (showDelete) {
        innerHtml += "<td class=\"box_tr\"><a onclick='" + managerName + ".deleteDestination(\"" + destId + "\");' style='cursor: pointer;'>" +
                     "<img src='" + imageBaseUrl + "images/icon_smallx.gif' width='7' height='8' alt='remove destination' border='0'/></a></td>";
    }
    innerHtml += "</tr></tbody></table>";

    destination.innerHTML = innerHtml;
    return destination;
}

TopPlacesManager.prototype.updateDestinationIds = function() {
    var destinationIds = "";
    for (var i = 0; i < this.destinations.length; i++) {
        destinationIds += this.destinations[i].head + "_";
    }

    this.destinationIds.value = destinationIds;
}

TopPlacesManager.prototype.deleteDestination = function(destId) {
    var newDestinations = [];
    for (var i = 0; i < this.destinations.length; i++) {
        if (this.destinations[i].head != destId) {
            newDestinations.push(this.destinations[i]);
        }
    }

    this.destinations = newDestinations;
    this.updateDestinationIds();
    this.destinationList.removeChild(document.getElementById("destination" + destId));
}

TopPlacesManager.prototype.clear = function() {
    this.destinations = [];
    this.destinationIds = "";
    this.destinationList.innerHTML = "";
}



/*Start SelectionManager*/
function SelectionManager(/*array of ids*/itemIds, onAddItemCallBack, onDeleteItemCallBack) {
    this.itemIds = itemIds != null ? itemIds : [];
    this.onAddItemCallBack = onAddItemCallBack;
    this.onDeleteItemCallBack = onDeleteItemCallBack;
    return this;
}

SelectionManager.prototype.addItem = function(itemId, itemAdditionalInfo) {
    for (var i = 0; i < this.itemIds.length; i++) {
        if (this.itemIds[i].head == itemId) {
            return;
        }
    }

    this.itemIds.push({head: itemId, tail: itemAdditionalInfo});

    if (this.onAddItemCallBack != null) {
        this.onAddItemCallBack(itemId, this.itemIds, itemAdditionalInfo);
    }
}

SelectionManager.prototype.getItems = function() {
    return this.itemIds;
}

SelectionManager.prototype.getItemsAsString = function() {
    var itemIdsStr = "";
    for (var i = 0; i < this.itemIds.length; i++) {
        itemIdsStr += this.itemIds[i].head + ";";
    }
    return itemIdsStr;
}

SelectionManager.prototype.findItem = function(itemId) {
    for (var i = 0; i < this.itemIds.length; i++) {
        if (this.itemIds[i].head == itemId) {
            return true;
        }
    }

    return false;
}

SelectionManager.prototype.deleteItem = function(itemId) {
    var newItems = [];
    var deletedItem = null;
    for (var i = 0; i < this.itemIds.length; i++) {
        if (this.itemIds[i].head != itemId) {
            newItems.push(this.itemIds[i]);
        } else {
            deletedItem = this.itemIds[i];
        }
    }

    this.itemIds = newItems;

    if (deletedItem != null) {
        if (this.onDeleteItemCallBack != null) {
            this.onDeleteItemCallBack(deletedItem.head, this.itemIds, deletedItem.tail);
        }
    }
}

SelectionManager.prototype.clear = function() {
    this.itemIds = [];
}

SelectionManager.prototype.refresh = function() {
    // this send evens on add item for each element
    for (var i = 0; i < this.itemIds.length; i++) {
        if (this.onAddItemCallBack != null) {
            this.onAddItemCallBack(this.itemIds[i].head, this.itemIds, this.itemIds[i].tail);
        }
    }
}

// this event is comming from the SelectionManager
function onSearchAddItemCallback(lisItemId, allItems, itemAdditionalInfo) {
    // hide the default item
    document.getElementById("searchSelectedItems_default").style.display = "none";
    document.getElementById("searchSelectedItems_text").innerHTML = allItems.length + (allItems.length == 1? " item" : " items") + " selected:" ;

    var selectedItemsDiv = document.getElementById("searchSelectedItems");
    var newItemDiv = document.createElement("div");
    newItemDiv.id = "searchSelectedEle_" + lisItemId;
    newItemDiv.innerHTML = "<div style=\"border-top:solid 1px white; padding-top:2px\"><img alt=\"remove item from list\" src=\"images/ic_remove.gif\" onclick=\"genSearchSelectionManage.deleteItem('"+lisItemId+"')\"/>&nbsp;<b>"+itemAdditionalInfo.name+"</b></div>";

    selectedItemsDiv.appendChild(newItemDiv);
    setBoxSelection(lisItemId, true, true);
}
// this event is comming from the SelectionManager
function onSearchDeleteItemCallback(lisItemId, allItems, itemAdditionalInfo) {
    if (allItems.length == 0) {
        document.getElementById("searchSelectedItems_default").style.display = "";
    }
    document.getElementById("searchSelectedItems_text").innerHTML = allItems.length + (allItems.length == 1? " item" : " items") + " selected:" ;

    var entry = document.getElementById("searchSelectedEle_" + lisItemId);
    entry.parentNode.removeChild(entry);
    setBoxSelection(lisItemId, false, true);
}

// this event is comming from the box itself
function onSelectableBoxMouseOut(lisItemId) {
    setBoxSelection(lisItemId, genSearchSelectionManage.findItem(lisItemId), false);
}
// this event is comming from the box itself
function onSelectableBoxMouseOver(lisItemId) {
    setBoxSelection(lisItemId, true, false);
}
// this event is comming from the box itself
function onSelectableBoxClick(lisItemId, name, type) {
    if (genSearchSelectionManage.findItem(lisItemId)) {
        genSearchSelectionManage.deleteItem(lisItemId);
        setBoxSelection(lisItemId, false, true);
    } else {
        genSearchSelectionManage.addItem(lisItemId, {"name": name, "type":type});
        setBoxSelection(lisItemId, true, true);
    }
}
// utility function to set the right style in the box.
function setBoxSelection(lisItemId, select, updateIcon) {
    var id = "box_" + lisItemId;
    var boxTable = document.getElementById(id + "_table");

    if (boxTable == null) {
        return;
    }

    boxTable.className = select ? "boxborder_selected" : "boxborder";

    if (updateIcon) {
        if (select) {
            document.getElementById(id + "_img").src = "images/ic_remove.gif";
        } else {
            document.getElementById(id + "_img").src = "images/ic_add.gif";
        }
    }
}


//-------------------- compatibility -----------------------------------
function showCompatQustion(index, fieldValue, baseUrl, isDev) {
    if (fieldValue != null) {
        if (fieldValue.length == 0) {
            showStatusMessage(ResourceBundle.getString("travelCompatibilityQuiz"), ResourceBundle.getString("mustSelectDestination"));
            return;
        }
    }
    if (index < 9) {
        document.getElementById('question' + (index - 1)).style.display = 'none';
        document.getElementById('question' + index).style.display = '';
        document.getElementById('stepNumber').innerHTML = index;
        onPageChange();
    } else if (index == 9) {
        submitAjaxForm('compatibilityForm');
    }
}

function getSelecteRadio(radioArray) {
    for (var i = 0; i < radioArray.length; i++) {
        if (radioArray[i].checked) {
            return radioArray[i].value;
        }
    }
    return ""
}

function changeCompatibilityQuestionPhoto(imgBaseUrl, question, index) {
    document.getElementById('category_image' + question).src = imgBaseUrl + 'images/compatibility/' + question + '_' + index + '.jpg';
}

function changeCompatibilityQuestionPhotoFromSpan(imgBaseUrl, question, index, paramName) {
    document.getElementById(paramName + index).checked = true;
    changeCompatibilityQuestionPhoto(imgBaseUrl, question, index);
}


function getCompatAcSelectedValue(paramName) {
    return document.getElementById(paramName).value;
}

function getCompatAcRbQSelectedValue(paramName, numberOfFields) {
    for (var i = 0; i < numberOfFields; i++) {
        if (document.getElementById(paramName + i).checked) {
            return document.getElementById(paramName + i).value;
        }
    }
    return document.getElementById(paramName + "ACrb").value;
}

function selectCompatAcCheck(paramName) {
    document.getElementById(paramName).checked = true;
}

function selectCompatRb(paramName, index) {
    document.getElementById(paramName + index).checked = true;
}

function getItemIcon(type){
    if(type== "site"){
        return "images/site_16x16.gif";
    }else if(type == "restaurant"){
        return "images/resta_16x16.gif";
    }else if(type == "hotel"){
        return "images/hotel_16x16.gif";
    }else if(type == "theme"){
        return "images/theme_16x16.gif";
    }else {
        return "images/active_16x16.gif";
    }
}

function onPageChange() {
    var adIframe = document.getElementById("adIframe");
    if (adIframe != null) {
        adIframe.src = adIframe.src;
    }
}

function changeCompatResPageMode(mode) {
    document.getElementById("mode" + mode).style.display = '';
    document.getElementById("mode" + mode + "table").style.display = '';
    document.getElementById("mode" + mode + "title").style.display = '';
    if (mode == 1) {
        document.getElementById("mode2").style.display = 'none';
        document.getElementById("mode2table").style.display = 'none';
        document.getElementById("mode2title").style.display = 'none';
    } else {
        document.getElementById("mode1").style.display = 'none';
        document.getElementById("mode1table").style.display = 'none';
        document.getElementById("mode1title").style.display = 'none';
    }

    onPageChange();
}

function showCompatibility(roundPercent, userIndx, userIdBeg, realPercent, numberOfFriends) {
    for (var i = 100; i >= 0; i -= 20) {
        document.getElementById("resTitle" + i).style.backgroundColor = '#FFFFFF';
    }
    for (var i = 100; i >= 0; i -= 20) {
        document.getElementById('percent' + i).innerHTML = '';
    }
    document.getElementById("resTitle" + roundPercent).style.backgroundColor = '#FEF886';
    document.getElementById('percent' + roundPercent).innerHTML = realPercent + '% - ';
    selectCompatUser(userIndx, userIdBeg, numberOfFriends);
}

function selectCompatUser(userIndx, userIdBeg, numberOfFriends) {
    for (var i = 0; i < numberOfFriends; i++) {
        document.getElementById("user" + userIdBeg + i).style.border = '#FFFFFF solid 3px';
    }
    if (userIndx != null) {
        document.getElementById("user" + userIdBeg + userIndx).style.border = '#FAF519 solid 3px';
    }

    onPageChange();
}

function showCompatCollage(roundPercent, userIndx, userIdBeg, realPercent, numberOfFriends, externalId) {
    hideMyCollageSpanShowOther(true);
    fillOsUserName(externalId, 'nameSpan', false, true);
    document.getElementById('collage').style.display = 'none';
    for (var i = 0; i < numberOfFriends; i++) {
        document.getElementById('collage' + i).style.display = 'none';
    }
    document.getElementById('collage' + userIndx).style.display = '';
    selectCompatUser(userIndx, userIdBeg, numberOfFriends);
}

function viewSpecialMyCompatCollage(who, externalId) {
    if (who == 'my') {
        hideMyCollageSpanShowOther(false);
        document.getElementById('ownResultButton').style.display = 'none';
        document.getElementById('hisResultButton').style.display = '';
        document.getElementById('collage0').style.display = '';
        document.getElementById('collage').style.display = 'none';
    } else {
        hideMyCollageSpanShowOther(true);
        fillOsUserName(externalId, 'nameSpan', false, true);
        document.getElementById('ownResultButton').style.display = '';
        document.getElementById('hisResultButton').style.display = 'none';
        document.getElementById('collage0').style.display = 'none';
        document.getElementById('collage').style.display = '';
    }
}

function viewMyCompatCollage(numberOfFriends) {
    hideMyCollageSpanShowOther(false);
    document.getElementById('collage').style.display = '';
    for (var i = 0; i < numberOfFriends; i++) {
        document.getElementById('collage' + i).style.display = 'none';
    }
    selectCompatUser(null, "showCompatCollage", numberOfFriends);
}

/* Quizzes: Start */
function changeQuizQuestionPhoto(question, source, title) {
    document.getElementById('answer_image' + question).src = source;
    document.getElementById('answer_image' + question).title = title;
}

function changeQuizQuestionPhotoFromSpan(question, source, title,paramName, index) {
    document.getElementById(paramName + index).checked= true;
    changeQuizQuestionPhoto(question, source, title);
}

function showQuizQustion(index, fieldValue) {
    if (fieldValue != null) {
        if (fieldValue.length == 0) {
            showStatusMessage(ResourceBundle.getString("travelQuiz"), ResourceBundle.getString("mustSelectDestination"));
            return;
        }
    }
    if (index < 6) {
        document.getElementById('question' + (index - 1)).style.display = 'none';
        document.getElementById('question' + index).style.display = '';
        document.getElementById('stepNumber').innerHTML = index;
        onPageChange();
    } else if (index == 6) {
        submitAjaxForm('quizForm');
    }
}

function showQuizPage(showPage, hidePage) {
    document.getElementById('completedQuizes' + showPage).style.display =  '';
    document.getElementById('completedQuizes' + hidePage).style.display = 'none';
}

function selectQuiz(quizIndx, quizUrl, numberOfQuizzes) {
    for (var i = 0; i < numberOfQuizzes; i++) {
        document.getElementById("quiz" + i).style.border = '#FFFFFF solid 3px';
    }
    document.getElementById("quiz" + quizIndx).style.border = '#FAF519 solid 3px';
    makeAjaxCall(baseUrl + quizUrl, 'quizPane');
    onPageChange();
}

function selectQuizUser(userIndx, userIdBeg, numberOfFriends) {
    for (var i = 0; i < numberOfFriends; i++) {
        document.getElementById("user" + userIdBeg + i).style.border = '#FFFFFF solid 3px';
    }
    if (userIndx != null) {
        document.getElementById("user" + userIdBeg + userIndx).style.border = '#FAF519 solid 3px';
    }

    onPageChange();
}

function showQuizResults(roundPercent, userIndx, userIdBeg, realPercent, numberOfFriends, externalId) {
    // collage
    hideMyCollageSpanShowOther(userIndx!=numberOfFriends);
    fillOsUserName(externalId, 'nameSpan', false, true);
    document.getElementById('collage').style.display = 'none';
    for (var i = 0; i < numberOfFriends; i++) {
        document.getElementById('collage' + i).style.display = 'none';
    }
    document.getElementById('collage' + userIndx).style.display = '';

    // match
    hideMatchPhotos();
    document.getElementById("matchRes" + roundPercent).style.display = '';

    if (realPercent < 50) {
        fillOsUserName(externalId, 'lowMatchResName', false, false);
        document.getElementById("lowMatchRes").style.display = '';
        document.getElementById("hiMatchRes").style.display = 'none';
    } else {
        fillOsUserName(externalId, 'hiMatchResName', false, false);
        document.getElementById("matchPercent").innerHTML = realPercent;
        document.getElementById("hiMatchRes").style.display = '';
        document.getElementById("lowMatchRes").style.display = 'none';
    }

    selectQuizUser(userIndx, userIdBeg, numberOfFriends);
}

function hideMatchPhotos() {
    for (var i = 100; i >= 0; i -= 20) {
        document.getElementById("matchRes" + i).style.display = 'none';
    }
}

function viewMyQuizCollage(numberOfFriends) {
    hideMyCollageSpanShowOther(false);
    document.getElementById('collage').style.display = '';
    for (var i = 0; i <numberOfFriends; i++) {
        document.getElementById('collage' + i).style.display = 'none';
    }

    document.getElementById("hiMatchRes").style.display = 'none';
    document.getElementById("lowMatchRes").style.display = 'none';
    hideMatchPhotos();
    selectQuizUser(null, "showQuizResults", numberOfFriends);
}

function hideMyCollageSpanShowOther(hideMine) {
    document.getElementById('myNameSpan').style.display = hideMine ? 'none' : '';
    document.getElementById('otherNameSpan').style.display = hideMine ? '' : 'none';
}


/* Quizzes: End */


function getInviteFriendsUrl(){
    return "forward.do?forward=generic_page&mainContent=invite_form";
}

function inviteFriendForm(view_user_id) {
    makeAjaxCall("forward.do?forward=invite_friend_form&view_user_id=" + view_user_id);
}


// reload results of user page (after filtering)
function reloadResults(isAjax, isMapMode, tagValue, pageNumber, setProfile) {
    if (isMapMode != null) {
        document.getElementById("placeListFilterForm_view").value = isMapMode ? "map" : "list";
    }

    if (tagValue != null) {
        document.getElementById("placeListFilterForm_tag").value = tagValue;
    }

    if (pageNumber != null) {
        document.getElementById("placeListFilterForm_pageNumber").value = pageNumber;
    }

    if (setProfile) {
        document.getElementById("placeListFilterForm_set_profile").value = "true";
    }

    submitAjaxForm("placeListFilterForm", null, "userPlaceList");
}

function editUserTags(userId, mode){
    makeAjaxCall(baseUrl +  'forward.do?forward=edit_user_profile_tags&user_id=' + userId + '&up_page_mode=' + mode);
}

function goToUrl(url) {
    /*
    var a = document.createElement("a");
    if (!a.click) {
    */
        // only IE has this (at the moment);
        window.location = url;
    /*
        return;
    }

    a.setAttribute("href", url);
    a.style.display = "none";
    document.body.appendChild(a);
    a.click();
    */
}
