﻿var navSects = [];
var navSectStrings = [];
var navSectIcons = [];
var navCats = [];
var navSectLink = [];
var sectCount;
var megaLaunched = false;
$(function () {

    setWorkspacePadding();
    $('.colBlock').each(function () {
        if ($(this).height() < 2) $(this).hide();
    });

    $('.toplink').click(function () {
        return false;
    });

    var thisUrl = document.location.href;
    thisUrl = (thisUrl.indexOf("/sites/") > 0) ? thisUrl.split('/')[5] : thisUrl.split('/')[3];
    configureSectionBranding(thisUrl.toLowerCase()); //implement section branding from url
    $('.lnkRow').sameHeights();
    $('.menu-horizontal  .menu-item-text ').each(function () {

        $(this).html($(this).text().replace("+", "&amp;"));

    });

    $('a.static > span >  .menu-item-text,  .menu-horizontal > ul.root > li > span > span > .menu-item-text ').each(function () {
        var str = $(this).text();
        var pos = str.lastIndexOf(' ');
        if ($(this).width() > 100 && pos > 0) str = str.substring(0, pos + 1) + "<br />" + str.substring(pos + 1); //add a line break if the link is too wide
        $(this).html(str);
        if ($(this).height() > 33) str = str.replace(/(<([^>]+)>)/ig, ""); //remove the line break if the link consequently becomes too tall
        $(this).html(str);

    });

    $('#lnkHomeUpper').attr('href', rootUrl);
    $('#homecel a').attr("href", rootUrl);
    var theSearchBox = $('#searchBoxOuter td.ms-sbcell input');
    var defaultSearchText = "Search this site";
    var preferredSearchText = "Search the Port of Seattle";

    theSearchBox.val(preferredSearchText);   //replace the text initially

    theSearchBox.blur(function () { //replace the text when the search box loses focus and no value entered
        if ($(this).val().indexOf(defaultSearchText) > -1)
            $(this).val(preferredSearchText);

    });


    $('#soc-news').attr('href', rootUrl + "Newsroom/Pages/default.aspx");
    $('#soc-twit').attr('href', rootUrl + "Newsroom/Pages/default.aspx?newsTarget=twitter");
    $('#soc-fb').attr('href', rootUrl + "Newsroom/Pages/default.aspx?newsTarget=fb");
    $('#soc-yout').attr('href', rootUrl + "Newsroom/Pages/default.aspx?newsTarget=youtube");
    $('#lnk-signup').attr('href', "http://eepurl.com/gDBVb");
    $('#lnk-questions').attr('href', rootUrl + "About/Contact/Pages/Contact-the-Port.aspx");

    if ($(".tabViewer").size() > 0) $(".tabViewer ul.ulTV").idTabs();

    $('.answer').hide();
    $('a.question').prepend('<span class="farrow"></span>');
    $('a.question').click(function () {
        $(this).next().toggle(150);
        $(this).toggleClass("aactive");
        return false;
    });

    if (navigator.appVersion.indexOf("Mac") != -1) $('.menu-horizontal .menu-item-text').addClass('macAdjust');
    

});

ExecuteOrDelayUntilScriptLoaded(getTopMenuSections, "sp.js");


function printObject(o) {
    var output = '';
    for (property in o) {
        output += property + ': ' + o[property] + '; ';
    }
    if (output.indexOf('responseText:') > -1) output = output.split('responseText:')[1];
    alert(output);

}

function configureSectionBranding(topSub) {

    switch (topSub) {
        case "pages":
            $(".bannerBox").hide();
            $(".sp-topnav").hide();
        case "sea-tac":
            $('li#linkTravel a.toplink').addClass("subActive");
            setBanner("sea-tac.jpg");
            $('a#lnkTopSection').html("Sea-Tac Home").attr("href", rootUrl + topSub);
            break;
        case "cruise":
            $('li#linkTravel a.toplink').addClass("subActive");
            setBanner("cruise.jpg");
            $('a#lnkTopSection').html("Cruise Home").attr("href", rootUrl + topSub);
            break;
        case "attractions-resources":
            $('li#linkTravel a.toplink').addClass("subActive");
            setBanner("attractions.jpg");
            $('a#lnkTopSection').html("Attractions Home").attr("href", rootUrl + topSub);
            break;
        case "marinas":
            $('li#linkTravel a.toplink').addClass("subActive");
            setBanner("marinas.jpg");
            $('a#lnkTopSection').html("Marinas Home").attr("href", rootUrl + topSub);
            break;
        case "parks-public-access":
            $('li#linkTravel a.toplink').addClass("subActive");
            setBanner("parks.jpg");
            $('a#lnkTopSection').html("Parks Home").attr("href", rootUrl + topSub);
            break;
        case "cargo":
            $('li#linkBus a.toplink').addClass("subActive");
            setBanner("cargo.jpg");
            $('a#lnkTopSection').html("Cargo Home").attr("href", rootUrl + topSub);
            break;
        case "business":
            $('li#linkBus a.toplink').addClass("subActive");
            setBanner("business.jpg");
            $('a#lnkTopSection').html("Business Home").attr("href", rootUrl + topSub);
            break;
        case "commercial-marine":
            $('li#linkBus a.toplink').addClass("subActive");
            setBanner("commercial-marine.jpg");
            $('a#lnkTopSection').html("Commercial Marine Home").attr("href", rootUrl + topSub);
            break;
        case "about":
            $('li#linkAbout a.toplink').addClass("subActive");
            setBanner("about.jpg");
            $('a#lnkTopSection').html("About Home").attr("href", rootUrl + topSub);
            break;
        case "environmental":
            $('li#linkAbout a.toplink').addClass("subActive");
            setBanner("environmental.jpg");
            $('a#lnkTopSection').html("Environmental Home").attr("href", rootUrl + topSub);
            break;
        case "newsroom":
            $('li#linkAbout a.toplink').addClass("subActive");
            setBanner("newsroom.jpg");
            $('a#lnkTopSection').html("Newsroom Home").attr("href", rootUrl + topSub);
            break;
        case "jobs":
            $('li#linkAbout a.toplink').addClass("subActive");
            setBanner("jobs.jpg");
            $('a#lnkTopSection').html("Jobs Home").attr("href", rootUrl + topSub);
            break;
        case "supporting-our-community":
            $('li#linkAbout a.toplink').addClass("subActive");
            setBanner("supporting.jpg");
            $('a#lnkTopSection').html("Supporting Our Community Home").attr("href", rootUrl + topSub);
            break;
        case "employee-services":
            $('li#linkAbout a.toplink').addClass("subActive");
            setBanner("employee-services.jpg");
            $('a#lnkTopSection').html("Employee Services Home").attr("href", rootUrl + topSub);
            break;

        default:
            $('a#lnkTopSection').addClass("hidden");
            $('.bannerBox').addClass("hidden");
    }

    if ($.browser.mozilla) $('#lnkTopSection').addClass("ffFix");

}

//}

function setBanner(bName) {
    $('.bannerBox').css("background-image", "url('" + rootUrl + "banners/" + bName + "')");
}

//set top padding of the workspace to the height of the ribbon
function setTopPadding() {
    var wrkElem = document.getElementById('s4-workspace');
    var ribHeight = document.getElementById('s4-ribbonrow').offsetHeight;
    if (window.location.search.match("[?&]IsDlg=1")) {
        //margin works better for dialogs b/c of scrollbars
        wrkElem.style.marginTop = ribHeight + 'px';
        wrkElem.style.paddingTop = '0px';
    }
    else {
        //padding works better for the main window
        wrkElem.style.paddingTop = ribHeight + 'px';
    }
}
// bind top padding reset to ribbon resize event so that the page always lays out correctly.


function setWorkspacePadding() {
    if (inEditMode) { $('body').addClass("inEMode"); $('#s4-workspace').addClass("inEMode"); }
    else { $('#s4-workspace').addClass("notEditMode"); $('#s4-ribbonrow').addClass("notEditMode"); ExecuteOrDelayUntilScriptLoaded(function () { SP.UI.Workspace.add_resized(setTopPadding); }, "init.js"); }
}

function getTopMenuSections() {
    megaLaunched = true;
    getFooterLinks();
    //var clientContext = SP.ClientContext.get_current();
    var clientContext = new SP.ClientContext(rootUrl);
    var myList = clientContext.get_web().get_lists().getByTitle('Top Navigation Sections'); //actual list name here

    var camlQuery = new SP.CamlQuery();
    //camlQuery.set_viewXml(''); //caml statement 
    //New Caml statement, sorting by the section, then the order.
    camlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name=\"Section\" Ascending=\"False\" /><FieldRef Name=\"Order0\" Ascending=\"True\" /></OrderBy></Query></View>");

    this.collListItem = myList.getItems(camlQuery);

    clientContext.load(collListItem, 'Include(Title, icon, SectionLink)');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onSectQuerySucceeded), Function.createDelegate(this, this.onSectQueryFailed));
}

function onSectQuerySucceeded(sender, args) {

    var listItemEnumerator = collListItem.getEnumerator();
    var i = 0;
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();

        navSects[i] = oListItem.get_item('Title');
        navSectIcons[i] = oListItem.get_item('icon');
        if (navSectIcons[i] != null) if (navSectIcons[i].toString().indexOf(".") < 0) navSectIcons[i] += ".png";
        navCats[i] = navSects[i].substring(0, navSects[i].indexOf(":"));
        navSectLink[i] = oListItem.get_item('SectionLink');
        if (navSectLink[i] == null)  navSectLink[i] = "#"; else  navSectLink[i] = (navSectLink[i].indexOf("http") < 0) ? rootUrl + navSectLink[i] : navSectLink[i];


        i++;
    }
    sectCount = i;
    var j = 0;
    for (i = 0; i < sectCount; i++) {
        if (navSects[i].toString().indexOf(": Footer") > -1) navSectStrings[i] = '<div class="clear"></div><div class="ddCallout"><ul><li>';
        else { navSectStrings[i] = '<ul class="lnklogo' + j + '"><li><a class="headLnk" href="' + navSectLink[i] + '">' + navSects[i].substring(navSects[i].indexOf(": ") + 1) + '</a></li>'; j++; }
    }

    loadTopMenuEcm();
}

function onSectQueryFailed(sender, args) { }


function loadTopMenuEcm() {


    var clientContext = new SP.ClientContext(rootUrl);
    var topNav = clientContext.get_web().get_lists().getByTitle('Top Navigation');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('');
    this.collListItem = topNav.getItems(camlQuery);
    clientContext.load(collListItem, 'Include(Title, Section, Link)');
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {

    var topNavTitle = [];
    var topNavSection = [];
    var topNavLink = [];
    var strTravel = '<ul class="ul-dd"><li class="litop bgPng">&nbsp;</li><li class="limid">';
    var strBusiness = strTravel;
    var strAbout = strTravel;
    var listItemInfo = '';

    var listItemEnumerator = collListItem.getEnumerator();
    var enm = 0;
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        topNavTitle[enm] = oListItem.get_item('Title');
        topNavSection[enm] = oListItem.get_item('Section').get_lookupValue();
        topNavLink[enm] = oListItem.get_item('Link');
        if (topNavLink[enm] == null) topNavLink[enm] = "#"; else topNavLink[enm] = (topNavLink[enm].indexOf("http") < 0) ? rootUrl + topNavLink[enm] : topNavLink[enm];

        enm++;
    }
    var linkCount = enm;

    for (i = 0; i < linkCount; i++) {
        if (topNavSection[i].toString().indexOf(": Footer") > -1) navSectStrings[$.inArray(topNavSection[i], navSects)] += '<span class="ddcDiv">|</span><a href="' + topNavLink[i] + '">' + topNavTitle[i] + '</a>';
        else navSectStrings[$.inArray(topNavSection[i], navSects)] += '<li><a href="' + topNavLink[i] + '">' + topNavTitle[i] + '</a></li>';

    }

    for (i = 0; i < sectCount; i++) {
        if (navSects[i].toString().indexOf(": Footer") > -1) navSectStrings[i] += '</li></ul></div>';
        else navSectStrings[i] += '</ul>';

        if (navCats[i] == "Travel") strTravel += navSectStrings[i];
        else if (navCats[i] == "Business") strBusiness += navSectStrings[i];
        else if (navCats[i] == "About") strAbout += navSectStrings[i];
    }

    strTravel += '</li><li class="lifoot bgPng">&nbsp;</li></ul>';
    strBusiness += '</li><li class="lifoot bgPng">&nbsp;</li></ul>';
    strAbout += '</li><li class="lifoot bgPng">&nbsp;</li></ul>';
    $('#linkTravel').append(strTravel);
    $('#linkBus').append(strBusiness);
    $('#linkAbout').append(strAbout);
    var j = 0;
    for (i = 0; i < sectCount; i++) {
        if (navSects[i].toString().indexOf(": Footer") < 0) {
            $('ul.lnklogo' + j).css("background", "url('" + rootUrl + "NavIcons/" + navSectIcons[i] + "') no-repeat");
            j++;
        }

    }


    $('.ddCallout ul li span.ddcDiv:first-child').addClass("hidden");


    $('li.limid').each(function () {
        $(this).children('ul:even').addClass("clearBoth");
    });

    if (($.browser.msie) && ($.browser.version < 7)) {
        $('.menu-horizontal a.dynamic-children span.additional-background').addClass('bgPng');
        $("ul.sf-menu").superfish({
            delay: 0,                            // one second delay on mouseout
            speed: 'fast',                          // faster animation speed 
            autoArrows: false,                           // disable generation of arrow mark-up 
            dropShadows: false                            // disable drop shadows 

        });
        $.ifixpng('/Style%20Library/pos/images/pixel.gif');
        $('img, .bgPng').ifixpng();



        $('.sf-menu > li').hover(
				 function () {
				     $(this).children("a.toplink").css("background-position", "0px -60px");
				 },
				  function () {
				      $(this).children("a.toplink").css("background-position", "0px 0px");
				  }
				);
    }


}

function onQueryFailed(sender, args) { }

function getFooterLinks() {


    var clientContext = new SP.ClientContext(rootUrl);

    var myList = clientContext.get_web().get_lists().getByTitle('FooterLinks'); //actual list name here

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="Active" /><Value Type="Boolean">1</Value></Eq></Where></Query><RowLimit>6</RowLimit></View>');
    this.footerListItem = myList.getItems(camlQuery);

    clientContext.load(footerListItem, 'Include(Title, Link,Active)');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.footerLinkSuccess), Function.createDelegate(this, this.footerLinksFail));
}

function footerLinkSuccess(sender, args) {

    var listItemInfo = '';

    var listItemEnumerator = footerListItem.getEnumerator();
    var strTheLinks = "";

    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var theFooterLink = oListItem.get_item('Link');
        theFooterLink = (theFooterLink.indexOf("http") < 0) ? rootUrl + theFooterLink : theFooterLink;
        strTheLinks += '<li><a href="' + theFooterLink + '">' + oListItem.get_item('Title') + '</a></li><li><span>|</span></li>';

    }

    strTheLinks = strTheLinks.substring(0, strTheLinks.lastIndexOf('<li>'));
    $('#footerLinks').html(strTheLinks);
}

function footerLinksFail(sender, args) { }

$.fn.sameHeights = function () {
    $(this).each(function () {
        var tallest = 0; $(this).children().each(function (i) {
            if (tallest < $(this).height()) {
                tallest = $(this).height();
            }
        }
      ); $(this).children().css({
          'height': tallest
      }
      );
    }
   );
    return this;
};

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null;
}

function dateCorrect(oldString) {
    var result = oldString.split(" ")[0];
    result = result.split("-");
    return result[1] + "/" + result[2] + "/" + result[0];
}

function stripHtml(dirty) {
    return dirty.replace(/(<([^>]+)>)/ig, "");


}

