﻿/*
JAVASCRIPT FOR ALL PAGES. ANY JAVASCRIPT NEEDED FOR SPECIFIC
MASTER PAGES SHOULD GO IN THEIR APPROPRIATE js FILE.
*/

var ks = "";
var domain = "http://sf01dev:81/";

$(document).ready(function () {
    //document.title = $('span.ms-pagetitle').html();

    // VERTICALLY ALIGN FUNCTION. Just call $('X').vAlign();
    (function ($) {
        $.fn.vAlign = function () {
            return this.each(function (i) {
                var ah = $(this).height();
                var ph = $(this).parent().height();
                var mh = (ph - ah) / 2;
                $(this).css('margin-top', mh);
            });
        };
    })(jQuery);

    $('#MycogenLogo').click(function () {
        window.location = '/';
    });

    $('#Main_SignInButton').click(function () {
        alert('This would redirect you to sign in.');
    });

    $('#Nav_Searchbox').click(function () {
        if ($(this).val() == 'Search') {
            $(this).val('');
        }
    });
    $('#Nav_Searchbox').blur(function () {
        if ($('#Nav_Searchbox').val() == '') {
            $('#Nav_Searchbox').val('Search');
        }
    });
    
    $('#Nav_SearchBox_Button').bind('click', function () {
        DoSearch();
    });

    $('#Nav_Searchbox').keydown(function (e) {
        if (e.keyCode == 13) {
            DoSearch();
        }
    });

    /* MAIN NAV HOVERS */
    $('#Nav_Menu_GrainCorn').hover(function () {
        $(this).attr('src', '/SiteAssets/images/Navigation/Main/GrainCorn_hover.gif');
    }, function () {
        if (window.location.pathname.toLowerCase().indexOf("grain_corn") > -1)
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/GrainCorn_hover.gif');
        else
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/GrainCorn.gif');
    });

    $('#Nav_Menu_SilageSpecific').hover(function () {
        $(this).attr('src', '/SiteAssets/images/Navigation/Main/Silage-Specific_hover.gif');
    }, function () {
        if (window.location.pathname.toLowerCase().indexOf("silage-specific") > -1)
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Silage-Specific_hover.gif');
        else
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Silage-Specific.gif');
    });

    $('#Nav_Menu_Soybeans').hover(function () {
        $(this).attr('src', '/SiteAssets/images/Navigation/Main/Soybeans_hover.gif');
    }, function () {
        if (window.location.pathname.toLowerCase().indexOf("soybeans") > -1)
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Soybeans_hover.gif');
        else
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Soybeans.gif');
    });

    $('#Nav_Menu_Sunflowers').hover(function () {
        $(this).attr('src', '/SiteAssets/images/Navigation/Main/Sunflowers_hover.gif');
    }, function () {
        if (window.location.pathname.toLowerCase().indexOf("sunflowers") > -1)
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Sunflowers_hover.gif');
        else
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Sunflowers.gif');
    });

    $('#Nav_Menu_Canola').hover(function () {
        $(this).attr('src', '/SiteAssets/images/Navigation/Main/Canola_hover.gif');
    }, function () {
        if (window.location.pathname.toLowerCase().indexOf("canola") > -1)
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Canola_hover.gif');
        else
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Canola.gif');
    });

    $('#Nav_Menu_Alfalfa').hover(function () {
        $(this).attr('src', '/SiteAssets/images/Navigation/Main/Alfalfa_hover.gif');
    }, function () {
        if (window.location.pathname.toLowerCase().indexOf("alfalfa") > -1)
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Alfalfa_hover.gif');
        else
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Alfalfa.gif');
    });

    $('#Nav_Menu_Sorgum').hover(function () {
        $(this).attr('src', '/SiteAssets/images/Navigation/Main/Sorgum_hover.gif');
    }, function () {
        if (window.location.pathname.toLowerCase().indexOf("sorghum") > -1)
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Sorgum_hover.gif');
        else
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Sorgum.gif');
    });

    $('#Nav_Menu_Agronomy').hover(function () {
        $(this).attr('src', '/SiteAssets/images/Navigation/Main/Agronomy_hover.gif');
    }, function () {
        if (window.location.pathname.toLowerCase().indexOf("agronomy") > -1)
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Agronomy_hover.gif');
        else
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/Agronomy.gif');
    });

    $('#Nav_Menu_MySelections').hover(function () {
        $(this).attr('src', '/SiteAssets/images/Navigation/Main/MySelections_hover.gif');
    }, function () {
        if (window.location.pathname.toLowerCase().indexOf("my_selections") > -1)
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/MySelections_hover.gif');
        else
            $(this).attr('src', '/SiteAssets/images/Navigation/Main/MySelections.gif');
    });

    if (window.location.pathname.toLowerCase().indexOf("grain_corn/") > -1)
        $('#Nav_Menu_GrainCorn').attr('src', '/SiteAssets/images/Navigation/Main/GrainCorn_hover.gif');

    if (window.location.pathname.toLowerCase().indexOf("silage-specific/") > -1)
        $('#Nav_Menu_SilageSpecific').attr('src', '/SiteAssets/images/Navigation/Main/Silage-Specific_hover.gif');

    if (window.location.pathname.toLowerCase().indexOf("soybeans/") > -1)
        $('#Nav_Menu_Soybeans').attr('src', '/SiteAssets/images/Navigation/Main/Soybeans_hover.gif');

    if (window.location.pathname.toLowerCase().indexOf("sunflowers/") > -1)
        $('#Nav_Menu_Sunflowers').attr('src', '/SiteAssets/images/Navigation/Main/Sunflowers_hover.gif');

    if (window.location.pathname.toLowerCase().indexOf("canola/") > -1)
        $('#Nav_Menu_Canola').attr('src', '/SiteAssets/images/Navigation/Main/Canola_hover.gif');

    if (window.location.pathname.toLowerCase().indexOf("alfalfa/") > -1)
        $('#Nav_Menu_Alfalfa').attr('src', '/SiteAssets/images/Navigation/Main/Alfalfa_hover.gif');

    if (window.location.pathname.toLowerCase().indexOf("sorghum/") > -1)
        $('#Nav_Menu_Sorgum').attr('src', '/SiteAssets/images/Navigation/Main/Sorgum_hover.gif');

    if (window.location.pathname.toLowerCase().indexOf("agronomy/") > -1)
        $('#Nav_Menu_Agronomy').attr('src', '/SiteAssets/images/Navigation/Main/Agronomy_hover.gif');

    if (window.location.pathname.toLowerCase().indexOf("my_selections/") > -1)
        $('#Nav_Menu_MySelections').attr('src', '/SiteAssets/images/Navigation/Main/MySelections_hover.gif');

    // this targets the Sub1 navigation, which is plain text populated from the Top Link Nav bar. We're checking the URL and styling the li
    $(document).ready(function () {
        var Menu = document.getElementById("zz4_TopNavigationMenuV4");

        if (Menu == null) {
            Menu = document.getElementById("zz10_TopNavigationMenuV4"); //zz10 seems to show up in Ie7 only?
            var zzVer = "zz10_TopNavigationMenuV4";
        }
        else
            var zzVer = "zz4_TopNavigationMenuV4";

        if (Menu != null) //only get the elements if menu exists, otherwise we'll end up with a JS error
            var counter = Menu.getElementsByTagName("li").length;

        if (Menu != null && counter != null) //check for nulls again to verify counter doesn't end up null
        {
            for (i = 1; i <= counter; i++) {
                var text = $("ul.root li:nth-child(" + i + ") a span span").html().toLowerCase().replace(" ", "%20"); //replace the blank space with %20 to match url

                $("#" + zzVer + " ul.root li:nth-child(" + i + ") a").removeClass("selected"); //remove the selected class if an 'a' has it

                if (window.location.pathname.toLowerCase().indexOf(text) > -1)
                    $("#" + zzVer + " ul.root li:nth-child(" + i + ") a").addClass("selected"); //if this is our current page, add the selected class
            }
        }
    });





    // this adds a click event to the button in the upper right hand corner of the ribbon to close it
    // we do a redirect so sharepoint can detect there's no ribbon, and adjust the heights of the content appropriately
    $('#CloseRibbon').bind('click', function () {
        HideRibbon();
    });

    // check to see if the developer dashboard should be shown. in order for this to work, the dashboard
    // needs to be turned on via an stsadm command or powershell script
    if (getParameterByName('ddb') == 1)
        $('#DeveloperDashboard').show();
    else
        $('#DeveloperDashboard').hide();

    // this looks for a keystroke pattern of ctrl+shift+r to show the ribbon
    // we do a redirect, as opposed to just toggling on the ribbon, so sharepoint can detect there's no ribbon,
    // and adjust the heights of the content appropriately.
    // we detect the F5 key (116) so that the refresh can work.
    

    $(document).keydown(function (e) {
        if (e.keyCode == 17) { ks = "a"; return false; }
        if (e.keyCode == 16) { if (ks == "a") { ks = ks + "b"; return false; } }
        if (e.keyCode == 82) {
            if (ks == "ab") {
            
                ks = "";

/*                if (getParameterByName('ribn') == 1)
                window.location = window.location.pathname + "?ribn=0";
                else
                window.location = window.location.pathname + "?ribn=1";*/

                if ($('#s4-ribbonrow').css('display') == "none")
                    ShowRibbon();
                else
                    HideRibbon();

                return false;
            }
        }
        return true;
    });

    //Handle Modal Content
    if (getParameterByName('IsDlg') == 1) {
        $('#Main_Container').hide();
        $('#ModalContent').show();
        $('#Main_Content').appendTo('#ModalContent');
        $('#ModalContent').css('width', $('#s4-workspace').width() - 40);
        $('#s4-ribbonrow').css('display', 'none');
    }

    //QueryToTurnOnRibbon();
    //Ribbon Handeling On Page Load:
    if (getParameterByName('ribn') != '')
        QueryToTurnOnRibbon();
    else
        GetRibbonCookie();

    //Handle Print View
    if (getParameterByName('IsPrint') == 1) {
        $('#PrintLaunch').hide();
        print();
    }
});

function GetRibbonCookie() {
    if ($.cookie != null) {
        var c = $.cookie("RibbonState");
        if (c == "ON")
            ShowRibbon();
        else
            if (c == null || c == "OFF")
                HideRibbon();
    }
}

//function IsAuthenticatedUser() { if (typeof _spUserId == "undefined") { HideRibbon(); } else { ShowRibbon(); } }
function QueryToTurnOnRibbon() { if (getParameterByName('ribn') == "1") { ShowRibbon(); } else { HideRibbon(); } }

function ShowRibbon() {
    //if ($.cookie != null) {
        $('#s4-ribbonrow').show();
        $('#s4-workspace').height($(document).height() - $('#s4-ribbonrow').height() * 2);
      	$.cookie("RibbonState", "ON", { path: "/" });
    //}
}

function HideRibbon() {
    if ($.cookie != null) {
        $('#s4-ribbonrow').hide();
        var newHeight = $(document).height();
        if ($.browser.msie) { newHeight = newHeight - 3; }
        $('#s4-workspace').height(newHeight);
      	$.cookie("RibbonState", "OFF", { path: "/" });
    }
}

function AlertCustom(alertText, timeout) {
    var ScrollTop = $('#s4-workspace').scrollTop();
    $('#CustomAlert').show();
    $('#CustomAlert').html(alertText);
    $('#CustomAlert').animate({ "top": ScrollTop })
    if (timeout != null) {
        if (timeout > 0) {
            $('#CustomAlert').delay(timeout).animate({ "top": "-30" });
        }
    }
}

//launch a SharePoint modal dialog
function launchModal(sUrl, iWidth, iHeight) {
    //var options = SP.UI.$create_DialogOptions(); 
    var options = SP.UI.$create_DialogOptions;
    options.url = sUrl;
    options.width = iWidth;
    options.height = iHeight;
    options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
    SP.UI.ModalDialog.showModalDialog(options);
}

function closeWindow(updateMessage) {
    SP.UI.ModalDialog.commonModalDialogClose(updateMessage);
}

// Dialog callback 
function CloseCallback(result, target) {
    if (result != '' && result != '0') {
        messageId = SP.UI.Notify.addNotification(result, false);
    }
}

function launchModalFrame(url, isSharePoint, modalHeight, modalWidth) {
    if (isSharePoint == 'True') {
        if (url == 'login.aspx')
            ExecuteOrDelayUntilScriptLoaded(launchLogin, 'sp.js');
        else
            launchModal(url, modalWidth, modalHeight);
    }
    else {
        //jQuery modal in web test project
        //set iframe src
        document.getElementById('frameModal').src = url;

        //open results dialog
        jQuery('#dialog').dialog('open');
    }
}

function launchLogin() {
    launchModal('/sitepages/login.aspx', 650, 600);
}

function launchProfile() {
    launchModal('/sitepages/login.aspx?action=update', 650, 600);
}

function launchCreateAccount() {
    launchModal('/sitepages/login.aspx?action=create', 650, 600);
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function DoSearch() {
    var searchText = $('#Nav_Searchbox').val();
    window.location = String.format("/SitePages/Search%20Results.aspx?k={0}" + searchText);
    }
