function set_modals() {
    var f = $find('mdlMessageBox')
    if (f) { f.add_shown(hideloading); f._isIE6 ? f._foregroundElement.style.position = 'fixed' : f._foregroundElement.style.position = 'absolute'; }
    f = $find('mdlPopupLogin')
    if (f) { f.add_shown(hideloading); f._isIE6 ? f._foregroundElement.style.position = 'fixed' : f._foregroundElement.style.position = 'absolute'; }
    f = $find('mdlResetPass')
    if (f) { f.add_shown(hideloading); f._isIE6 ? f._foregroundElement.style.position = 'fixed' : f._foregroundElement.style.position = 'absolute'; }
    f = $find('mdlPopupBid')
    if (f) { f.add_shown(hideloading); f._isIE6 ? f._foregroundElement.style.position = 'fixed' : f._foregroundElement.style.position = 'absolute'; }
    f = $find('mdlOffer')
    if (f) { f.add_shown(hideloading); f._isIE6 ? f._foregroundElement.style.position = 'fixed' : f._foregroundElement.style.position = 'absolute'; }
    f = $find('mdlPopupApprove');
    if (f) { f.add_shown(hideloading); f._isIE6 ? f._foregroundElement.style.position = 'fixed' : f._foregroundElement.style.position = 'absolute'; }
    f = $find('mdlRprt')
    if (f) { f.add_shown(hideloading); f._isIE6 ? f._foregroundElement.style.position = 'fixed' : f._foregroundElement.style.position = 'absolute'; }
    f = $find('mdlWelcome')
    if (f) f.add_shown(hideloading);
}

function switchToEditMode(infoPanelId, editPanelId, editButtonId) {
    var infoPanel = $get(infoPanelId);
    var editPanel = $get(editPanelId);
    var editButton = $get(editButtonId);

    if (infoPanel)
        infoPanel.style.display = "none";
    if (editPanel)
        editPanel.style.display = "block";
    if (editButton)
        editButton.style.display = "none";
}

function HideMessShowResPass() {
    $find('mdlMessageBox').hide();
    $find('mdlResetPass').show();
}
function set_submitbtn_style(obj, id) {
    if (obj.checked) {
        var el = document.getElementById(id);
        el.disabled = false;
        el.className = "btn-global btn-sumbit";
    }
    else {
        var el = document.getElementById(id);
        el.disabled = true;
        el.className = "btn-global btn-sumbit-unac";
    }
}


function countdown_lst(endDateId, currentDateId, itemIdControlId, itemId) {
    var endDateControl = $get(endDateId);
    var currentDateControl = $get(currentDateId);
    var itemIdControl = $get(itemIdControlId);
    // Script may keep working even after page already has refreshed. In this case
    // we should make sure the target control is still there. We verify this by
    // checking the value of hidden field with itemId

    if (endDateControl && currentDateControl && itemIdControl &&
        endDateControl.value != "" && itemIdControl.value == itemId) {
        var endDate = new Date(endDateControl.value);
        var now = new Date();
        if (endDate <= now) {
            currentDateControl.innerHTML = "Ended";
        }
        else {
            var millis = endDate.getTime() - now.getTime() - now.getTimezoneOffset() * 60 * 1000;
            var seconds = Math.floor(millis / 1000);
            var minutes = Math.floor(seconds / 60);
            var hours = Math.floor(minutes / 60);
            var days = Math.floor(hours / 24);
            var months = Math.floor(days / 30);

            if (months > 0) {
                currentDateControl.innerHTML = months + "mon " + days % 30 + "d";
            }
            else {
                var timeString = "";
                if (days > 0) {
                    timeString = timeString + days + "d ";
                }
                if (hours > 0) {
                    timeString = timeString + hours % 24 + "h ";
                }
                if (minutes > 0) {
                    timeString = timeString + (minutes % 60 < 10 ? "0" : "") + minutes % 60 + "m ";
                }
                timeString = timeString + (seconds % 60 < 10 ? "0" : "") + seconds % 60 + "s";

                currentDateControl.innerHTML = timeString;
            }
        }

        setTimeout(function () { countdown_lst(endDateId, currentDateId, itemIdControlId, itemId) }, 1000);
    }

}

function timeleftprogress(el_f, new_time) {

    var l = Math.floor(Math.sqrt(new_time / 10) + 2 > 294 ? 294 : Math.sqrt(new_time / 10) + 2);
    el_f.style.width = l + "px";

    if (new_time < 10 * 60)
        el_f.style.backgroundColor = "#d41919";
    else if (new_time < 1 * 60 * 60)
        el_f.style.backgroundColor = "#b48c0a";
    else
        el_f.style.backgroundColor = "#4b724a";
}

function showloading() {
    var el = $find('mdlLoadingMsg');
    if (el)
        el.show();
}

function hideloading() {
    var el = $find('mdlLoadingMsg');
    if (el)
        el.hide();
}

function preloadImages() {
    for (i = 0; i < document.styleSheets.length; i++) {
        var ss = document.styleSheets[i];
        if (ss.cssRules) rls = document.styleSheets[i].cssRules;
        else rls = document.styleSheets[i].rules;
        var ph = '';
        if (document.styleSheets[i].href)
            ph = /([\w\W]*\/)[^\/]+$/.exec(document.styleSheets[i].href)[1];
        for (j = 0; j < rls.length; j++) {
            if (rls[j].selectorText != undefined && rls[j].selectorText.indexOf(":hover") != -1) {
                var bgi = rls[j].style.backgroundImage;
                if (!bgi) continue;
                var rs = /^url\(([^)]+)\)$/.exec(bgi);
                if (!rs) continue;
                im = new Image;
                im.src = (ph + rs[1]).replace(/"/g, "");
            }
        }
    }
}


////FilmStrip scripts Start
var photolineTop = 0;
var constPictureHeight = 46;

function moveNext() {
    var photoLineHolder = $get("tblPhotolineHolder");
    photolineTop = pixToInt(photoLineHolder.style.top) - constPictureHeight;

    if (photolineTop + photoLineHolder.offsetHeight < photoLineHolder.parentNode.offsetHeight) {
        photolineTop = photoLineHolder.parentNode.offsetHeight - photoLineHolder.offsetHeight;
    }

    photoLineHolder.style.top = photolineTop + "px";

    controlArrowState(photoLineHolder);
}

function movePrev() {
    var photoLineHolder = $get("tblPhotolineHolder");
    photolineTop = pixToInt(photoLineHolder.style.top) + constPictureHeight;

    if (photolineTop > -constPictureHeight) {
        photolineTop = 0;
    }

    photoLineHolder.style.top = photolineTop + "px";

    controlArrowState(photoLineHolder);
}

function controlArrowState(photoLineHolder) {
    if (photoLineHolder != null) {
        if (photoLineHolder.offsetHeight > photoLineHolder.parentNode.offsetHeight) {
            if (photolineTop + photoLineHolder.offsetHeight <= photoLineHolder.parentNode.offsetHeight) {
                $get("lnkArrowDown").style.display = "none";
                $get("spnArrowDown").style.display = "inherit";
            }
            else {
                $get("lnkArrowDown").style.display = "inherit";
                $get("spnArrowDown").style.display = "none";
            }

            if (photolineTop == 0) {
                $get("lnkArrowUp").style.display = "none";
                $get("spnArrowUp").style.display = "inherit";
            }
            else {
                $get("lnkArrowUp").style.display = "inherit";
                $get("spnArrowUp").style.display = "none";
            }
        }
        else {
            $get("lnkArrowUp").style.display = "none";
            $get("lnkArrowDown").style.display = "none";
            $get("spnArrowUp").style.display = "inherit";
            $get("spnArrowUp").className = "photoline-arrow up-none";
            $get("spnArrowDown").style.display = "inherit";
            $get("spnArrowDown").className = "photoline-arrow down-none";
        }
    }
}

function initGalleryScript() {
    photolineTop = 0;

    controlArrowState($get("tblPhotolineHolder"));
}
////FilmStrip scripts End

function clr_cb(prf, v, sender) {
    for (i = 1; i < 7; i++) {
        var el = document.getElementById(prf + i);
        if (el) el.checked = v;
    }
    if (sender) {
        sender.className = "hidden";
    }
}


////Filters
var prf = 'ctl00_LeftContent_';
var _tleft = ['', '30m', '1h', '2h', '3h', '5h', '8h', '10h', '12h', '1d', '2d', '3d', '5d', '1w', '2w', '']; //16
var _lsize = ['', '2000', '4000', '6000', '8000', '0.25ac', '0.5ac', '0.75ac', '1ac', '1.5ac', '2ac', '2.5ac', '3ac', '']; //14
var _size = ['', '500', '700', '1000', '1200', '1500', '1700', '2000', '2300', '2500', '3000', '3500', '4000', '4500', '5000', '']; //16
var _dist = ['1', '2', '5', '10', '15', '20', '25', '30', '40', '50', '60', '70', '80', '90', '100', '']; //16

var _fl = ['tl', 'ls', 's', 'd', 'pr', 'gtl', 'cpr', 'ctl', 'bpr', 'btl', 'bipr', 'bitl', 'spr', 'stl', 'jpr', 'jtl', 'ppr', 'ptl', 'tpr', 'ttl'];

function applyAllDistanceFilter() {//debugger;
    var txtbLocation = getFilterControl('tbZip_ftr');

    if (txtbLocation) {
        txtbLocation.value = '';
    }

    set_all('slDs');
}

function set_all(id) {
    var s = $find(id);
    if (s) {
        if (s._handles == 2) {
            s.setValue(0, s._minimum);
            s.setValue(1, s._maximum);
        }
        if (s._handles == 1) {
            s.setValue(0, s._maximum);
        }
        update_flds(s);
    }
}
function update_flds(sender, args) {
    switch (sender._id) {
        case 'slTL': upd(sender, _fl[0], _tleft); break;
        case 'slLS': upd(sender, _fl[1], _lsize); break;
        case 'slS': upd(sender, _fl[2], _size); break;
        case 'slDs': upd(sender, _fl[3], _dist); break;
        case 'slgTL': upd(sender, _fl[5], _tleft); break;
        case 'slcTL': upd(sender, _fl[7], _tleft); break;
        case 'slbTL': upd(sender, _fl[9], _tleft); break;
        case 'slbiTL': upd(sender, _fl[11], _tleft); break;
        case 'slsTL': upd(sender, _fl[13], _tleft); break;
        case 'sljTL': upd(sender, _fl[15], _tleft); break;
        case 'slpTL': upd(sender, _fl[17], _tleft); break;
        case 'sltTL': upd(sender, _fl[19], _tleft); break;
    }
}

function showClean(id, type, revert) {
    var t = "";
    switch (id) {
        case 'slTL': t = _fl[0]; break;
        case 'slLS': t = _fl[1]; break;
        case 'slS': t = _fl[2]; break;
        case 'slDs': t =_fl[3]; break;
        case 'slgTL': t = _fl[5]; break;
        case 'slcTL': t = _fl[7]; break;
        case 'slbTL': t = _fl[9]; break;
        case 'slbiTL': t = _fl[11]; break;
        case 'slsTL': t = _fl[13]; break;
        case 'sljTL': t = _fl[15]; break;
        case 'slpTL': t = _fl[17]; break;
        case 'sltTL': t = _fl[19]; break;
        case 'bth': t = 'bth'; break;
        case 'bd': t = 'bd'; break;
        case 'pst': t = 'pst'; break;
    }
    var lnk = getFilterControl('l_' + t + '_ftr');
    if (!lnk)
        return;
    if (type == "input") {
        var e0 = getFilterControl('t_' + t + '0_ftr');
        var e1 = getFilterControl('t_' + t + '1_ftr');
        if (e0 && e1 && (e0.value != "" || e1.value != ""))
            lnk.className = "visible";
        else
            lnk.className = "hidden";
    }
    else if (type == "check") {
        var visible = false;
        for (i = 1; i < 7; i++) {
            var el = getFilterControl('cb_' + t + '_ftr_' + i);
            if (el) {
                if ((!revert && el.checked) || (!el.checked && revert)) {
                    visible = true;
                    break;
                }
            }
        }
        if (visible)
            lnk.className = "visible";
        else
            lnk.className = "hidden";

    }
}


getUrlEncodedKey = function (key, query) {
    if (!query)
        query = window.location.search;
    var re = new RegExp("[?|&]" + key + "=(.*?)&");
    var matches = re.exec(query + "&");
    if (!matches || matches.length < 2)
        return "";
    return decodeURIComponent(matches[1].replace("+", " "));
}
setUrlEncodedKey = function (key, value, query) {

    query = query || window.location.search;
    var q = query + "&";
    var re = new RegExp("[?|&]" + key + "=.*?&");
    if (!re.test(q))
        q += key + "=" + encodeURI(value);
    else
        q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");
    q = q.trimStart("&").trimEnd("&");
    return q[0] == "?" ? q : q = "?" + q;
}

String.prototype.trimEnd = function (c) {
    if (c)
        return this.replace(new RegExp(c.escapeRegExp() + "*$"), '');
    return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function (c) {
    if (c)
        return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), '');
    return this.replace(/^\s+/, '');
}

String.prototype.escapeRegExp = function () {
    return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
};


function clear_text(t) {
    var e0 = getFilterControl('t_' + t + '0_ftr');
    if (e0) e0.value = "";
    var e1 = getFilterControl('t_' + t + '1_ftr');
    if (e1) e1.value = ""
}

function upd(s, t, a) {
    var e0 = getFilterControl('t_' + t + '0_ftr');
    if (e0) e0.value = a[s._handleData[0].Value];
    var e1 = getFilterControl('t_' + t + '1_ftr');
    if (e1) e1.value = a[s._handleData[1].Value];
}

function getFilterControl(name) {
    var elem = $get(prf + name);
    if (elem != null)
        return elem;
    if ($('[clientId=' + name + ']').length > 0)
        return $('[clientId=' + name + ']')[0];
}

////Reports
function open_rprt() {
    var el = $get('ctl00_MainContent_pnlLongRprt');
    if (el && el.firstChild)
        el.removeChild(el.firstChild);
    el = $get('rprt_loading')
    if (el)
        el.style.display = '';
    el = $find('mdlRprt')
    if (el) {
        el.add_populated(on_rprtpop);
        el.show();
    }
}
function on_rprtpop() {
    var el = $get('rprt_loading')
    if (el) el.style.display = 'none';
    var el = $get('ctl00_MainContent_pnlLongRprt');
    if (el) el.innerHTML = "Select a link above to view detailed report.";
}

//Main page handlers
function getElement(id) {
    var rc = document.getElementById(id);
    if (rc == null) {
        window.location = "Error404.aspx";
        throw ("Element id=" + id + " is not found");
    }

    return rc;
}


// Autoscrolling left menu. Implemenetation
var TIMER_TICK = 50;
var ANIMATION_STEP_COUNT = 20;
var SUB_MENU_OFFSET = 200;
var moveToPosition = 0;
var currentStep = 0;
var direction = 1;
var requestInProgress = false;
var freezeOn = false;
var closestElement = null;

function freeze(on) {
    freezeOn = on;
    if (!freezeOn) {
        handleScroll();
    }
}

function handleScroll() {
    if (helpMenu == undefined) {
        return;
    }

    var pos = Math.max(0, (window.pageYOffset || document.documentElement.scrollTop || 0) - SUB_MENU_OFFSET);

    currentStep = Math.min(ANIMATION_STEP_COUNT, Math.floor(Math.sqrt(Math.abs(pixToInt(helpMenu.style.top) - pos))));
    if (pixToInt(helpMenu.style.top) < pos) {
        direction = -1;
    }
    else {
        direction = 1;
    }

    moveToPosition = pos + direction * currentStep * currentStep;

    if (!requestInProgress) {
        requestInProgress = true;
        setTimeout("scrollMenu()", 500);
    }
}

function pixToInt(value) {
    return value == "" ? 0 : parseInt(value);
}

function scrollMenu() {
    if (currentStep > 0 && !freezeOn) {
        helpMenu.style.top = moveToPosition + "px";

        moveToPosition = moveToPosition - direction * (2 * currentStep - 1);
        currentStep = currentStep - 1;

        setTimeout("scrollMenu()", TIMER_TICK);
    }
    else {
        highlightItem();
    }

    requestInProgress = false;
}

// Front page tab control
var TAB_BUYER_ID = "tabBuyer";
var TAB_SELLER_ID = "tabSeller";
var TAB_AGENT_ID = "tabAgent";

function animateTab(tab, activeTab) {
    // Tab content
    panel = document.getElementById("pnl" + tab.title);

    if (tab == activeTab) {
        tab.style.cursor = "auto";
        tab.src = "images/hwindow/hw-b-" + tab.title.toLowerCase() + "_over.png";
        panel.style.display = "inline";

        document.getElementById("lbArticle").innerHTML = getArticle(tab.title);
    }
    else {
        tab.style.cursor = "pointer";
        tab.src = "images/hwindow/hw-b-" + tab.title + "_" + activeTab.title.substr(0, 1).toLowerCase() + "_acti.png";
        panel.style.display = "none";
    }
}

function getArticle(word) {
    vowels = "eioau";
    if (vowels.indexOf(word.substr(0, 1).toLowerCase()) != -1) {
        return "an";
    }
    else {
        return "a";
    }
}

function tabClick(sender) {
    animateTab(document.getElementById(TAB_BUYER_ID), sender);
    animateTab(document.getElementById(TAB_SELLER_ID), sender);
    animateTab(document.getElementById(TAB_AGENT_ID), sender);

    return true;
}

// Message box implementation
function isNullOrEmpty(stringValue) {
    return stringValue == null || stringValue == "";
}

function configureButton(button, text) {
    if (!isNullOrEmpty(text)) {
        button.style.display = 'inline';
        button.value = text;
    }
    else {
        button.style.display = 'none';
    }
}

function showMessageBox(id, message, button1Text, button2Text, button3Text) {
    if (isNullOrEmpty(message) == null ||
       (isNullOrEmpty(button1Text) && isNullOrEmpty(button3Text) && isNullOrEmpty(button3Text))) {

        return;
    }

    $find('mdlMessageBox').show();

    $get(jsid_hdnMessageBoxID).value = id;

    $get(jsid_pnlMessageBoxText).innerHTML = message;

    configureButton($get(jsid_btnMessageBox1), button1Text);
    configureButton($get(jsid_btnMessageBox2), button2Text);
    configureButton($get(jsid_btnMessageBox3), button3Text);
}

function updateSubmitState(checkbox, buttonId) {
    button = $get(buttonId);
    if (checkbox.checked) {
        button.disabled = '';
    }
    else {
        button.disabled = 'disabled';
    }
}

function formatTime(time) {
    // Use some common formats or just print as is
    localFormat = new Date("23:15:00").toLocaleTimeString().toLowerCase();
    if (localFormat.indexOf("pm")) {
        // "US" format
        return time.getHours() + (time.getMinutes() > 0 ? ":" + time.getMinutes() : "") + (time.getHours() > 11 ? "pm" : "am");
    }
    else if (localFormat.indexOf("23")) {
        // Assume this is 24-hour format
        return time.getHours() + ":" + time.getMinutes();
    }
    else {
        return time.toLocaleTimeString();
    }
}

function adjustToLocalTime(dateControlId, timeControlId, univTime) {
    dateControl = $get(dateControlId);
    timeControl = $get(timeControlId);

    if (dateControl && timeControl) {
        scheduledOn = new Date(univTime);
        milllis = scheduledOn.getTime() - scheduledOn.getTimezoneOffset() * 60 * 1000;
        scheduledOn.setTime(milllis);

        dateControl.innerHTML = scheduledOn.toLocaleDateString();
        timeControl.innerHTML = formatTime(scheduledOn);
    }
    else {
        throw "date or/and time controls do not exist";
    }
}

/***
* Password to hint switch. This function helps to display translucent hint text in password fields
*/
function switchPassword2Hint(obj) {
    if (obj.type != "password" || obj.value == "") {

        obj.style.display = "none";
        var inputs = obj.parentNode.getElementsByTagName("input");
        for (i = 0; i < inputs.length; i++) {
            if (inputs.item(i).id != obj.id) {
                inputs.item(i).style.display = "";
                if (inputs.item(i).type == "password") {
                    inputs.item(i).focus();
                }
                break;
            }
        }

    }
}


/***
* A set of functions to handle floating hint feature.
*/
function getScreenCordinates(obj) {
    var p = {};
    p.x = obj.offsetLeft;
    p.y = obj.offsetTop;
    while (obj.offsetParent) {
        p.x = p.x + obj.offsetParent.offsetLeft;
        p.y = p.y + obj.offsetParent.offsetTop;
        if (obj == document.getElementsByTagName("body")[0]) {
            break;
        }
        else {
            obj = obj.offsetParent;
        }
    }
    return p;
}

function showFloatingHint(control, text) {
    var hintWindow = $get("pupFloatingHint");
    var hintTextHolder = $get("pnlFloatingHintText");
    if (hintWindow && hintTextHolder) {
        control.parentNode.insertBefore(hintWindow, control);
        hintTextHolder.innerHTML = text;
        hintWindow.style.display = "";

        var p = getScreenCordinates(control);
        hintWindow.style.top = (p.y - 25) + 'px';

        return false;
    }
}

function hideFloatingHint() {
    var hintWindow = $get("pupFloatingHint");
    if (hintWindow) {
        hintWindow.style.display = "none";

        return false;
    }
}


/***
* GMT offset processing helper
*/
function fillInGMTOffset(fieldId) {
    gmtHolder = $get(fieldId);
    if (gmtHolder) {
        gmtHolder.value = new Date().getTimezoneOffset();
    }
}
