﻿
var OGJS =
{
    resources: {},
    detectMobileDevice:
        function () {
            if( OGJS.okToPromptTheUserAboutSwitchingToTheMobileSite())
            {
                if( OGJS.isMobileUserAgent === "true" || OGJS.largestScreenDimension() < 650) {
                    OGJS.askUserIfWantsToSwitchToMobileSite();
                }
            }
            else if( OGJS.isMobileUserAgent === "true" || OGJS.largestScreenDimension() < 650) {
                // Just highlight the mobile site, the user is on a small screen device
                $("#header").prepend( "<div id='mobile-site-option'><a href='" + OGJS.mobileSiteUrl + "'>Go to the mobile site</a></div>");
            }
        },
    smallestScreenDimension:
        function () {
            var minDimension = screenWidth = $(window).width();
            var screenHeight = $(window).height();

            if (screenHeight < screenWidth) {
                minDimension = screenHeight;
            }

            return minDimension;
        },
    largestScreenDimension:
        function () {
            var maxDimension = screenWidth = $(window).width();
            var screenHeight = $(window).height();

            if (screenHeight > screenWidth) {
                maxDimension = screenHeight;
            }

            return maxDimension;
        },
    getViewportDimensions:
        function () {
        },
    okToPromptTheUserAboutSwitchingToTheMobileSite:
        function () {
            // There are four possible states indicated by the cookie (is set when the user last used the prompt) :
            //
            //      null    : User hasn't been asked before (or cookie has timed out)
            //      yes     : The user was redirected the mobile site last time
            //      no      : The user was not redirected the mobile site last time
            //      never   : The user decided to be never redirected to the mobile site
            //
            var value = $.cookie('MobileSwitch');
            if (value == null)
            {
                return true;
            }

            return false;
        },

    askUserIfWantsToSwitchToMobileSite:
        function () {
            var prompt = $(
                "<div id='switchToMobileSite'>" +
                    "<h1>Welcome mobile user</h1>" +
                    "<p>Do you want to go to the mobile version of the site?</p>" +
                    "<p class='buttons'><div>" +
                        "<a rel='nofollow' href='#' id='switchToMobileSite_Yes'>Yes please</a>" +
                        "<a rel='nofollow' href='#' id='switchToMobileSite_No'>Not today</a>" +
                        "<a rel='nofollow' href='#' id='switchToMobileSite_NeverAgain'>Never</a>" +
                    "</div></p>" +
                    "<div class='clear'></div>" +
                "</div>");

            $("body").prepend(prompt);

            var zoomLevel = $(window).width() / screen.availWidth;
            var windowWidth = screen.availWidth * zoomLevel;
            var relativePx = (windowWidth / 22);
            var smallRelativePx = (windowWidth / 30);
            var relativePaddingPx = relativePx / 2;
            prompt.css("font-size", relativePx + "px");

            $("#switchToMobileSite").css(
                {
                    "padding": relativePaddingPx + "px",
                    "border-radius": (relativePaddingPx * 1.2) + "px"
                });
            $("#switchToMobileSite h1").css(
                {
                    "padding": relativePaddingPx + "px",
                    "border-radius": relativePaddingPx + "px"
                });
            $("#switchToMobileSite p").css("padding", "0 " + relativePaddingPx + "px " + (relativePaddingPx / 8) + "px");
            $("#switchToMobileSite span").css("padding", relativePaddingPx + "px 0");
            $("#switchToMobileSite a").css(
                {
                    "margin-right": relativePaddingPx + "px",
                    "padding": relativePaddingPx + "px",
                    "border": (relativePaddingPx / 2.5) + "px solid #5ba124",
                    "border-radius": relativePaddingPx + "px"
                });

            $("#switchToMobileSite_No, #switchToMobileSite_NeverAgain").css( "font-size", smallRelativePx + "px");

            //$("body").css("overflow", "hidden");

            $("#switchToMobileSite_Yes").click(
                function (event) {
                    event.preventDefault();
                    //$("body").css("overflow", "auto");
                    $.cookie('MobileSwitch', "yes", { expires: 1000 });

                    if( OGJS.isJobDetailPage === true)
                    {
                        // Add the job query to the mobile url
                        OGJS.mobileSiteUrl += window.location.pathname;
                    }

                    window.location = OGJS.mobileSiteUrl;
                });

            $("#switchToMobileSite_No").click(
                function (event) {
                    event.preventDefault();
                    //$("body").css("overflow", "auto");
                    $("#switchToMobileSite").remove();

                    // I wanted to use a temporary session cookie here so they are asked again next time they reach our site. But
                    // on iphones a session cookie is only cleared when the device is restarted. This is not the essence of a web
                    // browser session, so it's better to have a 1 day timeout instead
                    var tomorrow = new Date();
                    tomorrow.setHours( 0);
                    tomorrow.setMinutes( 0);
                    tomorrow.setSeconds( 1);
                    tomorrow.setDate( tomorrow.getDate() + 1);
                    $.cookie('MobileSwitch', "no", {expires:tomorrow});
                });

            $("#switchToMobileSite_NeverAgain").click(
                function (event) {
                    event.preventDefault();
                    //$("body").css("overflow", "auto");
                    $.cookie('MobileSwitch', "never", { expires: 1000 }); // Permanent cookie
                    $("#switchToMobileSite").remove();
                });
        }
};

$(function () {
    // Sort navigation out by adding class to navbar whgen we are on certain pages.
    var page = window.location.pathname;
    var handler = function () {
        $("#searchterm").attr({ title: $(this).val() });
        $("#searchterm").val('');
    }
    $('ul#menu li a[href=' + page + ']').addClass("active");

    // Clear job search box on focus
    $("#searchterm[value*=" + OGJS.resources.defaultSearchTermText + "]").bind("focus", handler);
    $("#searchterm").focus(function () { $(this).css("color", "#000"); });
    $("#searchterm").blur(function () {
        if ($(this).val() == "" || $(this).val() == OGJS.resources.defaultSearchTermText) {
            if ($(this).attr("title") == "") {
                $(this).val(OGJS.resources.defaultSearchTermText);
                $(this).bind("focus", handler);
            }
            else {
                $(this).val($(this).attr("title"));
            }
        }
        else {
            $(this).unbind("focus", handler);
        }
    });
    $("#search-jobs").click(function () {
        $this = $(this);
        if ($("#searchterm").val() == OGJS.resources.defaultSearchTermText) {
            $("#searchterm").css("color", "red");
            return false;
        }
        return true;
    });

    //    $(".popup").click(function (evt) {
    //        evt.preventDefault();
    //        var $this = $(this);
    //        var url = $this.attr("href") + "?popup=true";
    //        $.colorbox({ href: url, width: "700px", height: "450px" });
    //    });

    //    $(".largepopup").click(function (evt) {
    //        evt.preventDefault();
    //        var $this = $(this);
    //        var url = $this.attr("href") + "?popup=true";
    //        $.colorbox({ href: url, width: "980px", height: "450px" });
    //    });
    $(".popup").fancybox({ 'width': 750, 'height': 450, 'autoDimensions': false, 'scrolling': 'auto' }).click(function (e) { return false; });
    $(".largepopup").fancybox({ 'width': 980, 'height': 450, 'autoDimensions': false, 'scrolling': 'auto' }).click(function (e) { return false; });
    $(".popup-iframe").fancybox({ 'width': 750, 'height': 450, 'autoDimensions': false, 'scrolling': 'auto', 'type': 'iframe' }).click(function (e) { return false; });
    $(".popup-iframe-large").fancybox({ 'width': 980, 'height': 550, 'autoDimensions': false, 'scrolling': 'auto', 'type': 'iframe' }).click(function (e) { return false; });
    /*
    $("#keywords").autocomplete({
    source: "/Jobs/LookupCategories",
    select: function (event, ui) {
    if (ui.length > 0) {
    $("#keywords").val(ui);
    }
    }
    });
    */

    OGJS.detectMobileDevice();
});

function stringify(object, padding, margin) {
    var o = (typeof object == 'object' || typeof object == 'function') && object != null ? object : null;
    var p = typeof padding == 'boolean' && padding ? true : false;
    var m = typeof margin == 'number' && margin > 0 && p ? margin : 0;
    if (o != null) {
        var s = '';
        var a = function (o) { return (typeof o === 'object' && o ? ((typeof o.length === 'number' && !(o.propertyIsEnumerable('length')) && typeof o.splice === 'function') ? true : false) : false); }; //is array?
        for (var v in o) {
            s += typeof o[v] === 'object' ? (o[v] ? (
					(typeof o[v].length === 'number' && !(o[v].propertyIsEnumerable('length')) && typeof o[v].splice === 'function') ?
					(m > 0 ? Array(m).join(' ') : '') + v + ':' + (p ? ' ' : '') + '[' + (p ? '\r\n' : '') + stringify(o[v], p, (m > 0 ? m : 1) + v.length + 4) + (p != true ? '' : '\r\n' + Array((m > 0 ? m : 1) + v.length + 2).join(' ')) + '],' + (p ? '\r\n' : '') :
					(m > 0 ? Array(m).join(' ') : '') + v + ':' + (p ? ' ' : '') + '{' + (p ? '\r\n' : '') + stringify(o[v], p, (m > 0 ? m : 1) + v.length + 4) + (p != true ? '' : '\r\n' + Array((m > 0 ? m : 1) + v.length + 2).join(' ')) + '},' + (p ? '\r\n' : '')
				) : (m > 0 ? Array(m).join(' ') : '') + v + ':' + (p ? ' ' : '') + o[v] + ',' + (p ? '\r\n' : ''))
			: (m > 0 ? Array(m).join(' ') : '') + v + ':' + (p ? ' ' : '') + (typeof o[v] == 'string' ? '\'' + o[v].replace(/\'/g, '\\\'') + '\'' : o[v]) + ',' + (p ? '\r\n' : '');
        };
        o = s.length > 0 && p != true ? s.substring(0, s.length - 1) : (s.length > 2 ? s.substring(0, s.length - 3) : s);
    } else {
        o = object;
    };
    return o;
};

function SetSpeechBubble(controlId, contentHtml) {
    $(controlId).qtip({ content: contentHtml,
        style: { name: 'blue', tip: true, padding: 10, textAlight: 'center', border: { width: 1, radius: 4} }, position: { adjust: { x: 10, y: -20 }, corner: { target: 'leftMiddle', tooltip: 'rightMiddle'} }, show: { when: { event: 'focus'} }, hide: { when: { event: 'blur'} }
    });
}

// Add a flash message from the client side
// flashType : warning|info|error
function addFlashMessage(message, flashType) {
    if (typeof (flashType) == "undefined") {
        flashType = "info";
    }

    $('#flash').removeClass("info error warning");
    $('#flash').toggleClass(flashType);
    $('#flash').hide();
    $('#flash').html(message);
    $('#flash').slideDown('slow');

    $('#flash').click(
        function () {
            $('#flash').slideUp();
        });
}

