﻿var currentOverlayId = '';
var gBrokerAbortSuggestionSearch = false;
$(document).ready(function () {
    $("form").submit(function () {
        $('input[title!=""], textarea[title!=""]').each(function () {
            if ($(this).val() === $(this).attr("title")) {
                $(this).val("");
            }
        });
    });

    //Setup object gallery
    $(".gallery-section .heading ul a").click(function (e) {
        e.preventDefault();
        showGalleryTabs(this);
    });

    var defaultTab = $(".gallery-section .heading a").first();
    showGalleryTabs(defaultTab);

    //Setup location suggestion for quick search
    if (gLocationSearchInputId) {
        var locationSearchInput = $("#" + gLocationSearchInputId);
        var searchBoxElement = locationSearchInput[0];

        locationSearchInput.focus(function (e) {
            locationFocus(e, this);
        });
        locationSearchInput.keydown(function (e) {
            locationOnKeyDown(e);
        });
        locationSearchInput.keypress(function (e) {
            locationOnKeyPress(e);
        });
        locationSearchInput.keyup(function (e) {
            var id = this.id;
            locationOnKeyUp(e, id);
        });
        locationSearchInput.blur(function () {
            if (!gIgnoreLocationBlur)
                hideLocationSuggest();
        });

        $(".quicksearch .submit").click(function (e) {
            e.preventDefault();
            fireLocationSearch(true);
        });
    }

    if (gIgnoreLocationBlur != undefined) {
        $("#LocationSuggestDiv, .quicksearch .submit").mouseover(function () { gIgnoreLocationBlur = true; });
        $("#LocationSuggestDiv, .quicksearch .submit").mouseout(function () { gIgnoreLocationBlur = false; });
    }

    //Setup location suggestion for search page
    if (!(typeof gLocationSearchPageInputId === 'undefined') && gLocationSearchPageInputId) {
        var searchInput = $("#" + gLocationSearchPageInputId);
        var searchBoxElement = searchInput[0];

        searchBoxElement.noHitsDiv = noHitsDiv = $("#SearchBoxLocationSuggestNoHits")[0];

        searchInput.focus(function (e) {
            locationFocus(e, this);
        });
        searchInput.keydown(function (e) {
            locationOnKeyDown(e);
        });
        searchInput.keypress(function (e) {
            locationOnKeyPress(e);
        });
        searchInput.keyup(function (e) {
            var id = this.id;
            locationOnKeyUp(e, id);
        });
        searchInput.blur(function () {
            if (!gIgnoreLocationBlur)
                hideLocationSuggest();
        });
    }

    $(".search-nav .map-area").hide();
    $(".search-nav .map").click(function (event) {
        event.preventDefault();
        $(".search-nav .map-area").toggle();
    });

    //Setup broker javascript
    if (typeof gBrokerSearchInputId != 'undefined' && gBrokerSearchInputId) {
        var brokerSearchInput = $("#" + gBrokerSearchInputId);

        brokerSearchInput.keydown(function (event) {
            return BrokerOnKeyDown(event);
        });

        brokerSearchInput.keyup(function (event) {
            return BrokerOnKeyUp(event, this);
        });

        brokerSearchInput.keypress(function (event) {
            return postbackOnEnter(event, gBrokerSubmitId);
        });
    }

    $("#BrokerSuggestDiv").mouseover(function () {
        gIgnoreBrokerBlur = true;
    });

    $("#BrokerSuggestDiv").mouseout(function () {
        gIgnoreBrokerBlur = false;
    });

    if (typeof gOverlayMapId != 'undefined' && gOverlayMapId) {
        $(".broker-map .a").click(function (event) {
            overlayWhenInLeftSidebar(gOverlayMapId);
        });

        $(".map-checkboxes .a").click(function () {
            overlay(gOverlayMapId);
        });
    }

    $(".fileinputs input[type=file]").each(function () {
        $(this).addClass("hidden");
        var parent = $(this).parent();
        $(parent).append('<div class="btn-bla">Bla</div><input class="fake-field" title="Last opp CV"/>');
        this.load = this.onchange = this.onmouseout = function () {
            var value = $(this).val();
            if (value != "") {
                $(".fake-field", parent).val(value);
            }
        };
    });
      

    $(document).ready(function () { $('.overlay-popup-map').appendTo('body'); });

    //init facebook javascript
    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/nb_NO/all.js#xfbml=1&appId=165358870152402";
        fjs.parentNode.insertBefore(js, fjs);
    } (document, 'script', 'facebook-jssdk'));
});

showGalleryTabs = function (link) {
    if (link != null) {

        var id = $(link).attr("href");
        $(".gallery-section .gallery").hide();
        $(".gallery-section .heading ul a").parent().removeClass("active");
        $(".gallery-section .heading .link").hide();
        if (!(typeof id === 'undefined')) {
            var morelinkclass = id.replace("#", "#more");
            $(morelinkclass).show();
        }
        $(id).show();
        $(link).parent().addClass("active");
    }
};
// ---------------
// Hides all windowed controls in browsers that
// can't display layers on top of them.
// ---------------
function hideWindowedControls() {
    if ((BrowserDetect.browser == 'Explorer') && (BrowserDetect.version < 7)) {
        // Hides all listboxes
        for (var i = 0; i < document.getElementsByTagName('select').length; i++) {
            document.getElementsByTagName('select')[i].style.visibility = 'hidden';
        }
    }
}

// ---------------
// Shows all windowed controls.
// ---------------
function showWindowedControls() {
    if ((BrowserDetect.browser) == 'Explorer' && (BrowserDetect.version < 7)) {
        // Show all listboxes
        for (var i = 0; i < document.getElementsByTagName('select').length; i++) {
            document.getElementsByTagName('select')[i].style.visibility = 'visible';
        }
    }
}

// ------------------------------------------------------------
// Returns the y coordinate of the specified object
// ------------------------------------------------------------
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    else if (obj.clientTop) {
        curtop += obj.clientTop;
    }
    return curtop;
}

// ------------------------------------------------------------
// Returns the x coordinate of the specified object
// ------------------------------------------------------------
function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    }
    else if (obj.clientLeft) {
        curleft += obj.clientLeft;
    }
    return curleft;
}

var gCounter = 0;

// ---------------
// Opens a dialog. The first parameter should be the dialog name.
// ---------------
function openDialog() {
    gCounter = gCounter + 1;
    var dialogName = arguments[0];
    var dialog = document.getElementById('DialogContainer');
    var hiddenField = document.getElementById(gDialogHiddenFieldId);

    try {
        if (dialogName == "TipFriend") {
            s.prop9 = "Tipsa van";
        }
        if (dialogName == "ObjectIntrestRegistration") {
            s.prop9 = "Anmal intresse";
        }
    } catch (err) { }
    if (dialog && hiddenField) {
        dialog.className = 'Dialog ' + dialogName;
        hiddenField.value = '';
        // Make a delimited string with the dialogname and parameters
        for (var i = 0; i < arguments.length; i++) {
            hiddenField.value += arguments[i];
            if (i + 1 < arguments.length) hiddenField.value += '|';
        }

        __doPostBack(gDialogHiddenFieldId, '');

        hideWindowedControls();
        showDialogBackground();
    }
}

// ---------------
// Positions the dialog layer in the center of the screen.
// ---------------
function positionDialog() {
    var dialog = document.getElementById('DialogContainer');
    if (dialog) {
        var viewSize = getViewportSize();
        var scrollSize = getScrollOffset();
        dialog.style.display = 'block';


        // Center window on screen
        dialog.style.left = (scrollSize.x + (viewSize.width - dialog.clientWidth) / 2) + 'px';

        var marginTop = dialog.clientHeight > viewSize.height ? ((viewSize.height - dialog.clientHeight) / 2) : 100;
        var top = (scrollSize.y + ((viewSize.height - dialog.clientHeight) / 2) - marginTop);
        if (top > scrollSize.y)
            dialog.style.top = top + 'px';
        else
            dialog.style.top = scrollSize.y + 'px';
    }
}

// ---------------
// Returns the size of the viewport.
// ---------------
function getViewportSize() {
    size = {};
    if (window.innerHeight) {
        size.width = window.innerWidth;
        size.height = window.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        size.width = document.documentElement.clientWidth;
        size.height = document.documentElement.clientHeight;
    }
    else if (document.body) {
        size.width = document.body.clientWidth;
        size.height = document.body.clientHeight;
    }
    return size;
}

// ---------------
// Returns the scroll offset
// ---------------
function getScrollOffset() {
    scrollOffset = {};
    if (window.pageYOffset)// all except Explorer
    {
        scrollOffset.x = window.pageXOffset;
        scrollOffset.y = window.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
    {
        scrollOffset.x = document.documentElement.scrollLeft;
        scrollOffset.y = document.documentElement.scrollTop;
    }
    else if (document.body) // all other Explorers
    {
        scrollOffset.x = document.body.scrollLeft;
        scrollOffset.y = document.body.scrollTop;
    }
    return scrollOffset;
}

// ---------------
// Closes the dialog-layer.
// ---------------
function closeDialog() {
    gCounter = gCounter - 1;
    var dialog = document.getElementById('DialogContainer');
    var hiddenField = document.getElementById(gDialogHiddenFieldId);
    if (dialog && hiddenField) {
        dialog.style.display = 'none';
        hiddenField.value = '';
        __doPostBack(gDialogHiddenFieldId, '');

        hideDialogBackground();
        showWindowedControls();
    }
    var helpDialog = document.getElementById('DialogHelpContainer');

    if (helpDialog) {
        var helphiddenField = document.getElementById(gHelpDialogHiddenFieldId);
        helpDialog.style.display = 'none';
        helphiddenField.value = '';
        __doPostBack(gHelpDialogHiddenFieldId, '');
    }

}

// ---------------
// Creates a semi-transparent div and places it over the entire screen.
// ---------------
function showDialogBackground() {
    var bgDiv = document.getElementById('DialogBG');
    if (bgDiv) {
        var height = document.body.clientHeight + 40;
        bgDiv.style.height = height + 'px';
        bgDiv.style.display = 'block';

        // IE6 and below needs a special class
        if ((BrowserDetect.browser == 'Explorer') && (BrowserDetect.version < 7)) {
            bgDiv.className = 'DialogBGIE6';
        }
    }
}

// ---------------
// Hides the semi-transparent div
// ---------------
function hideDialogBackground() {
    var bgDiv = document.getElementById('DialogBG');
    if (bgDiv) {
        bgDiv.style.display = 'none';
    }
}

//Cookiehandler (used by the iPhone popup)
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
}

function postbackOnEnter(evt, controlId) {
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;
    // If enter is pressed -> do a postback
    if (keyCode == 13) {
        __doPostBack(controlId, '');
        gBrokerAbortSuggestionSearch = true;
        return true;
    }
    else {
        return true;
    }
}

// ------------------------------------------------------------
// Handler for keyup in the Broker search field
// ------------------------------------------------------------
function BrokerOnKeyUp(evt, BrokerSearch) {
    var keyCode = evt.keyCode;
    if (BrokerSearch && (keyCode != 38) && (keyCode != 40) && (keyCode != 13)) // up and down
    {
        var val = BrokerSearch.value;
        if (val != '') {
            if (val.length > 1) {
                fireBrokerSuggestRequest(val, BrokerSearch.id);
            }
        }
        else {
            hideBrokerSuggest();
        }
    }
    else {
        ToggleLoader(false);
    }
    return true;
}

// ------------------------------------------------------------
// Handler for keydown in the Broker search field
// ------------------------------------------------------------
function BrokerOnKeyDown(evt) {
    var keyCode = evt.keyCode;

    if (keyCode == 38) // up
    {
        highlightBrokerSuggestItem('BrokerSuggestItem_' + (gCurrentBrokerSuggestItem - 1));

        // This is to avoid a bug in Safari that fires duplicate events
        if (evt.stopPropagation) {
            evt.stopPropagation();
        }
        return true;
    }
    else if (keyCode == 40) // down
    {
        highlightBrokerSuggestItem('BrokerSuggestItem_' + (gCurrentBrokerSuggestItem + 1));

        // This is to avoid a bug in Safari that fires duplicate events
        if (evt.stopPropagation) {
            evt.stopPropagation();
        }
        return true;
    }
    else if (((keyCode == 13) || (keyCode == 9)) && !gBrokerAbortSuggestionSearch) // enter or tab
    {
        fireBrokerSearch();
        return true;
    }

    return true;
}

// ------------------------------------------------------------
// Handler for keypress in the Broker search field
// ------------------------------------------------------------
function BrokerOnKeyPress(evt) {
    var keyCode = evt.keyCode;
    // This is to prevent postbacks when enter is pressed
    if (keyCode == 13) {
        if (evt.stopPropagation) {
            evt.stopPropagation();
        }
        return false;
    }
}

// ------------------------------------------------------------
// Highlights the suggest item with the specified index
// ------------------------------------------------------------
function highlightBrokerSuggestItem(id) {
    // The currently selected item
    var oldItem = document.getElementById('BrokerSuggestItem_' + gCurrentBrokerSuggestItem);
    // The new item to select
    var newItem = document.getElementById(id);
    if (oldItem && newItem) {
        oldItem.className = 'BrokerSuggestItem';
        newItem.className = 'BrokerSuggestItemSelected';
        gCurrentBrokerSuggestItem = parseInt(id.split('_')[1]);
    }
}

// ------------------------------------------------------------
// Fires suggestion request to the server.
// ------------------------------------------------------------
function fireBrokerSuggestRequest(search, BrokerSearchId) {
    $.ajax({
        type: 'POST',
        url: '/Templates/Facebook/WebServices/SearchBrokers.aspx?method=suggestionredirect&q=' + encodeURI(search),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
            BrokerSuggestCompleted(data, BrokerSearchId);
        }
    });
    ToggleLoader(true);
}

// ------------------------------------------------------------
// Hides the suggest "drop-down"
// ------------------------------------------------------------
function hideBrokerSuggest() {
    var suggestDiv = document.getElementById('BrokerSuggestDiv');
    if (suggestDiv) {
        $(suggestDiv).css('display', 'none');
        gCurrentBrokerSuggestItem = -1;
    }
    var nohitsDiv = document.getElementById('BrokerSuggestNoHits');
    if (nohitsDiv) {
        $(nohitsDiv).css('display', 'none');
        gCurrentBrokerSuggestItem = -1;
    }
}

// ------------------------------------------------------------
// Callback method that is called when a suggestion request is complete
// ------------------------------------------------------------
function BrokerSuggestCompleted(data, BrokerSearchId) {
    if (data) {
        var searchTerm = data.searchterm;
        var hitList = data.result;

        if (searchTerm == document.getElementById(BrokerSearchId).value) {
            if (hitList.length > 0) {
                $('#TextBoxBroker').attr('onkeypress', '');
                updateBrokerSuggest(hitList);
            }
            else {
                hideBrokerSuggest();
                ToggleLoader(false);
                if (isNaN(searchTerm)) {
                    setBrokerSuggestNoHitsVisibility(true);
                }
            }
        }
    }
}

// ------------------------------------------------------------
// Updates the suggest "drop-down" with new items.
// ------------------------------------------------------------
function updateBrokerSuggest(offices) {
    var suggestDiv = document.getElementById('BrokerSuggestDiv');

    if (suggestDiv) {
        while (suggestDiv.hasChildNodes()) {
            suggestDiv.removeChild(suggestDiv.lastChild);
        }

        var parentDiv = document.createElement("div");

        var html = '';
        for (var i = 0; i < offices.length; i++) {
            var itemDiv = document.createElement('div');
            itemDiv.id = 'BrokerSuggestItem_' + i;
            itemDiv.className = ((i == 0) ? 'BrokerSuggestItemSelected' : 'BrokerSuggestItem');

            if (itemDiv.addEventListener) {
                itemDiv.addEventListener('mouseover', function (e) { highlightBrokerSuggestItem(this.id); }, false);
                itemDiv.addEventListener('click', function (e) { fireBrokerSearch(); }, false);
            }
            else {
                itemDiv.attachEvent('onmouseover', function (e) { highlightBrokerSuggestItem(e.srcElement.id); }, false);
                itemDiv.attachEvent('onclick', function (e) { fireBrokerSearch(); }, false);
            }
            itemDiv.innerHTML = offices[i].name;

            var hidden = document.createElement('input');
            hidden.id = 'BrokerSuggestItemHidden_' + i;
            hidden.type = 'hidden';
            hidden.value = offices[i].name + ';' + offices[i].officeurl;

            itemDiv.appendChild(hidden);
            parentDiv.appendChild(itemDiv);
        }
        suggestDiv.appendChild(parentDiv);

        gCurrentBrokerSuggestItem = 0;

        if ($(suggestDiv).css('display') != 'block') {
            var searchBox = document.getElementById(gBrokerSearchInputId);
            if (searchBox) {
                $(suggestDiv).css('display', 'block');
                suggestDiv.style.top = (findPosY(searchBox) + searchBox.clientHeight + 6) + 'px';
                suggestDiv.style.left = (findPosX(searchBox) - 10) + 'px';
            }
        }

        setBrokerSuggestNoHitsVisibility(false);
        ToggleLoader(false);
    }
}
function ToggleLoader(show) {
    if (show) {
        $('#topAjaxLoader').css('display', 'block');
        $('#bottomAjaxLoader').css('display', 'block');
    }
    else {
        $('#topAjaxLoader').css('display', 'none');
        $('#bottomAjaxLoader').css('display', 'none');
    }
}

// ------------------------------------------------------------
// Hides or shows the "No hits"-message below the search field.
// ------------------------------------------------------------
function setBrokerSuggestNoHitsVisibility(isVisible) {
    $('#BrokerSuggestNoHits').css('display', isVisible ? 'block' : 'none');
}

// ------------------------------------------------------------
// Fires the Broker search request
// ------------------------------------------------------------
function fireBrokerSearch() {
    var suggestItem = document.getElementById('BrokerSuggestItem_' + gCurrentBrokerSuggestItem);
    var searchBox = document.getElementById(gBrokerSearchInputId);

    if (suggestItem) {
        var data = $(suggestItem).find('input').val().split(';');
        if (searchBox)
            searchBox.value = data[0].replace(/<.*?>/g, '');

        if ((data != null) && searchBox && (searchBox.className != 'BrokerSearchInputTip')) {
            hideBrokerSuggest();
            window.location = data[1];
        }
    }
}

// Overlay reposition when in left sidebar
function overlayWhenInLeftSidebar(divid) {
    overlay(divid);

    var scrollTop = document.body.scrollTop;

    if (scrollTop == 0) {
        if (window.pageYOffset)
            scrollTop = window.pageYOffset;
        else
            scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
    }

    var newTop = parseFloat($('#' + divid).css('top').replace('px', '')) + scrollTop;
    $('#' + divid).css('top', newTop + 'px');
    initialize();
}
