//pageContent.js
var myApp = {};

(

function () {
  var stopBubble = function (e) {
      var event = e || window.event;
      if (e.cancelBubble) e.cancelBubble = true;
      else e.stopPropagation();
      return false;
    }

  myApp.layout = {
    hide: function (layoutId) {
      document.getElementById(layoutId).style.display = "none";
    },

    show: function (layoutId) {
      document.getElementById(layoutId).style.display = "block";
    }
  }

  myApp.revolver = new ContentRotator();
  myApp.featured = new FeatureDisplay({
    cssPath: "css/",
    itemClass: "fd_round",
    skin: "zyquest",
    showStatus: false,
    overlayCaption: true,
    absoluteNavLayout: true,
    useBorderedItems: false,
    rotateOptions: {
      interval: 5000,
      animation: {
        easing: "easeOutBack",
        duration: 1000
      }
    },
    autoRotate: true,
    featureOnHover: false,
    featureOnClick: true
  });
  // myApp.morePanel = new SlidePanel({
  //   cssPath: "css/",
  //   top: 85,
  //   label: " ",
  //   openLabel: " ",
  //   skin: "zyquest"
  // });
  myApp.sidePanel = new Sidebar({
    cssPath: "css/",
    skin: "zyquest"
  });
/*myApp.linksPanel = new SlidePanel({
      top: 160,
      label: "links"
    });*/
  myApp.navSlider = new NavSlider({
    cssPath: "css/"
  });

  myApp.content = {
    HEADERNAVLINKS: "header-nav-links",
    SUBNAVLINKS: "sub-nav-links",
    FOOTERNAVLINKS: "footer-nav-links",
    PAGEFOOTER: "pageFooter",
    CONTENT_URI: "lib/layout.topnav.json",

    mPageId: null,
    mSectionId: null,
    mJsonData: null,
    mPageContent: null,
    mRedrawSubNavFlag: false,
    mPageIsCreated: false,
    mTestimonials: null,

    create: function (pageId, defaultSectionId) {
      var sectionId = myApp.content.getSectionIdFromUriHash(defaultSectionId);
      myApp.content.setTopNav(pageId);

      pageId = pageId || "home";
      sectionId = sectionId || "overview";

      if (pageId === "sitemap") {
        // This is the only place that doesn't call setPageContent, which sets the mPageId.  So we need to set it here.
        myApp.content.mPageId = pageId;
        myApp.content.mSectionId = sectionId;

        // sitemap
        myApp.content.generateSiteMap();
      } else {
        // Get all testimonials so we can ramdomly pick some to fill missing rotator items - or 
        // they will be used in testimonials page.    
        if (myApp.content.mTestimonials == null) {
          myApp.content.mTestimonials = myApp.content.getTestimonials(pageId);
        }

        // content from JSON files.
        myApp.content.setPageContent(pageId);
      }

      if ((sectionId !== undefined) && (sectionId != null) && (sectionId != "")) {
        // setSectionContent only sets content if pageId is defined.
        myApp.content.setSectionContent(pageId, sectionId);
      }

      // create the slider over the footer-nav, except for pages that do not have sub-nav links.
      if (pageId !== "sitemap" /* && !(pageId === "home" && sectionId === "main")  */ ) {
        myApp.navSlider.create();
      }

      // setup the page footer.
      myApp.content.setPageFooter();

      var contactsArray = myApp.content.getTopicContacts();

      myApp.sidePanel.render('#content-container');

      myApp.sidePanel.addGroupContent('<a id="siteMap" href="#"><img src="img/sidebar/sidebar-sitemap.png" alt="Sitemap" title="View our Sitemap" /></a>');
      $('#siteMap').click(function (event) {
        $('#' + myApp.sidePanel.id + '_content').empty();
        $('#' + myApp.sidePanel.id + '_content').append(myApp.content.generateSiteMap());
        $('#' + myApp.sidePanel.id + '_content_wrapper').css('top', -146);
        $('#' + myApp.sidePanel.id + '_content_wrapper').toggle();
        $('#' + myApp.sidePanel.id + '_content_carat').show();
        return stopBubble(event);
      });

      for (var i in contactsArray.reverse()) {
        myApp.sidePanel.addGroupContent("<a class='showContactDetails' href='#'><img src='" + contactsArray[i].photoUri + "' width='24px' alt='Request Information' title='Request Information' class='sp_round' /></a>");
      }
      $('.showContactDetails').click(function (event) {
        myApp.content.showSlidePanelContactDetails();
        $('#' + myApp.sidePanel.id + '_content_wrapper').css('top', -185);
        $('#' + myApp.sidePanel.id + '_content_carat').show();
        return stopBubble(event);
      });

      $("#requestInfo").bind("click", function () {
        myApp.content.requestInformation();
      });

      // setup page events
      $("#pageHeader").bind("mouseover", function () {
        myApp.content.setRedrawSubNavFlag(true);
      });
      $("#sub-nav").bind("mouseover", function () {
        myApp.content.setRedrawSubNavFlag(true);
      });
      $(document).keyup(function (e) {
        if (e.which == 13) {
          SlidePanel.prototype.triggerClicked();
          SlidePanel.prototype.triggerClicked();
        }
      });

      $("#content-container").bind("mouseover", function () {
        myApp.content.redrawSubNavByFlagValue(myApp.content.mPageId, "sub-nav-links");
      });
      $(".rotator-page").bind("click", function (e) {
        var id = $(e.target).attr("id");
        var num = id.charAt(id.length - 1) - 0;
        myApp.revolver.focus(num);
      });
      $("#contactUs").bind("click", function () {
        return myApp.content.setSectionContent("about", "team");
      });

      myApp.content.mPageIsCreated = true;
    },

    getSectionIdFromUriHash: function (defaultSectionId) {
      var hash = window.location.hash;
      hash = hash.replace("#", "");
      hashArray = hash.split(".")

      var pageId = "";
      var sectionId = "";
      if (hashArray.length == 2) {
        pageId = hashArray[0];
        sectionId = hashArray[1];
      }

      if (sectionId.length == 0) {
        if ((defaultSectionId === undefined) || (defaultSectionId == null) || (defaultSectionId.length == 0)) {
          defaultSectionId = "";
        }

        sectionId = defaultSectionId;
      }

      return sectionId;
    },

    /*
     * This function should only be called from init, so once per page load.
     */
    generateSiteMap: function () {
      if (myApp.content.mJsonData.links == null) {
        alert("Sitemap was not generated because contents were not loaded from JSON file.");
        return;
      }


      var clickevent = 'SlidePanel.prototype.triggerClicked();SlidePanel.prototype.triggerClicked()';

      var template = "<div class='sitemap-content sb_round'>";
      //template += "<h3 onclick=" + clickevent + ">[Close]</h3>";
      template += '<table class="sitemap-table sb_round" cellpadding="0" border="0" cellspacing="0"><tr>';
      $.each(myApp.content.mJsonData.links, function (key, value) {
        if (value.enabled === "Y") {
          var pageId = value.pageId;
          var navEvent = 'return myApp.content.setSectionContent("' + pageId + '", "overview");';
          template += "<th><a href='" + pageId + ".html' onclick='" + navEvent + "'>" + value.navTitle + "</a></th>"
        }
      });

      template += '</tr><tr>'
      $.each(myApp.content.mJsonData.links, function (key, value) {
        var pageId = value.pageId;
        if (value.enabled === "Y") {
          template += "<td><ul>";
          $.each(value.subNav, function (key, value) {
            //var pageId = value.pageId;
            var subNavEvent = 'myApp.content.setSectionContent("' + pageId + '", "' + value.sectionId + '");';
            template += "<li><a href='" + pageId + ".html#" + pageId + "." + value.sectionId + "' onclick='" + subNavEvent + "'>" + value.title + "</a></li>";
          });
          template += "</td>"
        }
      });
      template += '</ul></tr></table></div>';
      //myApp.morePanel.addToContentPanel(template);
      return template;
      //$( "#content" ).html(template);
    },

    generateContactListItem: function (contacts) {
      // reset the uri
      //parent.location.hash="#" + myApp.content.mPageId + "." + myApp.content.mSectionId;
      // MPS Contacts
      var template = '<ul id="contact-list">'; //<div>";
      $.each(contacts, function (key, value) {
        //var clickevent = 'myApp.layout.hide("slidePanel_expanding_content_more")';
        //var clickevent = 'SlidePanel.prototype.triggerClicked();SlidePanel.prototype.triggerClicked()';
        //var clickevent = '$("#slidePanel_expanding_content_more").hide(50);$("#slidePanel_expanding_content_more").toggleClass("active")';
        // template += "<h3 onclick=" + clickevent + ">[Close]</h3>";
        template += "<li style='list-style: none;'>";

        // thumbnail
        if (value.photoUri == "") {
          value.photoUri = "img/missing_photo.png";
        }

        template += "<div class='thumb'>" + "<img src='" + value.photoUri + "' alt='' title='" + value.displayName + "' width='100' class='rounded_five' />" + "</div>";

        template += '<div><b>' + value.jobTitle + '</b></div>';
        template += '<div><b>' + value.displayName + '</b></div>';
        template += '<div><b>Email:</b> ' + value.email + '</div>';
        template += '<div><b>Voice:</b> ' + value.phone + '</div>';
        if (value.mobile && value.mobile.length > 0) {
          template += '<div><b>Voice:</b> ' + value.mobile + '</div>';
        }
        template += '<div><b>Fax:</b> ' + value.fax + '</div>';

        template += "<div class='contact-types'><a class='contact-type-image' href='mailto:" + value.email + "?subject=Inquiry from ZyQuest website' target='top'><img src='img/icons/email.png' alt='Email' title='Email " + value.displayName + "' /></a>";

        if (value.vCardUri.length > 0) {
          var tooltip = value.vCardTooltip || "vCard";
          template += "<a class='contact-type-image' href='" + value.vCardUri + "' target='top'><img src='img/icons/vcard.png' alt='vCard' title='" + tooltip + "' /></a>";
        }

        if (value.vCardAltUri && value.vCardAltUri.length > 0) {
          var tooltip = value.vCardAltTooltip || "vCard";
          template += "<a class='contact-type-image' href='" + value.vCardAltUri + "' target='top'><img src='img/icons/vcard.png' alt='vCard' title='" + tooltip + "' /></a>"
        }

        if (value.facebookUri.length > 0) {
          template += "<a class='contact-type-image' href='" + value.facebookUri + "' target='top'><img src='img/icons/fb.png' alt='Facebook' title='Follow us on Facebook' /></a>";
        }

        if (value.linkedInUri.length > 0) {
          template += "<a class='contact-type-image' href='" + value.linkedInUri + "' target='top'><img src='img/icons/linkedin.png' alt='LinkedIn' title='Follow " + value.displayName + " on LinkedIn' /></a>";
        }

        if (value.twitterUri.length > 0) {
          template += "<a class='contact-type-image' href='" + value.twitterUri + "' target='top'><img src='img/icons/twitter.png' alt='Twitter' title='Follow " + value.displayName + " on Twitter' /></a>";
        }

        template += "</div>";

        template += '</li>';

      });

      template += '</ul>';

      return template;
    },

    requestInformation: function (contactId) {
      // reset the uri
      parent.location.hash = "#" + myApp.content.mPageId + "." + myApp.content.mSectionId;

      var contactsArray;

      if (contactId) {
        contactsArray = myApp.content.getContactsArray([contactId]);
      } else {
        contactsArray = myApp.content.getTopicContacts();
      }

      if (contactsArray.length > 0) {
        // Add each contact to the contacts layout in the correct location.
        var html = '<ul id="contact-list">';

        for (var contactIndex in contactsArray) {
          html += "<li style='margin-bottom: 25px; list-style: none;'>";
          html += myApp.content.setContactUsItem(contactsArray[contactIndex]);
          html += '</li>';
        }

        html += '</ul>';
        
        var $dialog = $('<div id="basic-modal-content"></div>').html(html)
        
        $dialog.modal({
            minHeight: 100,
            minWidth: 420,
            maxHeight: 320,
            maxWidth: 520,
            overlayClose:true,
            opacity: 70
        });
      }
  }, 

    showSlidePanelContactDetails: function () {
      // reset the uri
      parent.location.hash = "#" + myApp.content.mPageId + "." + myApp.content.mSectionId;

      var contactsArray = myApp.content.getTopicContacts();

      if (contactsArray.length > 0) {
        var html = '<div class="contact-content sb_round">';
        html += '<ul id="contact-list">';

        for (var contactIndex in contactsArray) {
          html += "<li style='list-style: none;'>";
          html += myApp.content.setContactUsItem(contactsArray[contactIndex]);
          html += '</li>';
        }

        html += '</ul>';
        html += '</div>';

        // var liHeight = 170;
        // var options = {
        //     width: $('.contact-content').css('width'),
        //     height: (liHeight * contactsArray.length) + 'px'
        // };
        myApp.sidePanel.addToContentPanel(html);
        // myApp.morePanel.setContentPanelDimens(options);
      }
    },

    getTopicContacts: function () {
      var contacts = new Array();
      var contactsArray = new Array();
      var jsonPageContent = _.detect(myApp.content.mJsonData.links, function (item) {
        return item.pageId == myApp.content.mPageId;
      });
      if ((jsonPageContent !== undefined) || (jsonPageContent != null)) {
        var jsonSectionContent = _.detect(jsonPageContent.subNav, function (item) {
          return item.sectionId == myApp.content.mSectionId;
        });
        if ((jsonSectionContent !== undefined) || (jsonSectionContent != null)) {
          contacts = jsonSectionContent.contacts;
          contactsArray = myApp.content.getContactsArray(contacts);
        } else {
          contactsArray = myApp.content.getContactsArray(contacts);
        }
      }

      return contactsArray;
    },

    getContactsArray: function (contacts) {
      if (contacts.length == 0) {
        contacts = myApp.content.mJsonData.defaultContacts;

        if (contacts.length == 0) {
          alert('There are no default contacts defined in the topnav.json file.');
          return false;
        }
      }

      // now we have contacts, we need to get their details
      var pageContent;
      if ((myApp.content.mPageId == "about") || (myApp.content.mPageId == 'home')) {
        pageContent = myApp.content.mPageContent.sections;
      } else {
        var uri = myApp.content.CONTENT_URI.replace(/topnav/, "about");

        $.ajax({
          url: uri,
          success: function (data) {
            pageContent = data.sections;
          },
          error: function (xhr, status, error) {
            alert("error: " + xhr.status);
          },
          async: false,
          dataType: "json",
          type: "GET"
        });
      }

      // now we have our page content with contact details in it - now get the contacts
      var contactDetails = _.detect(pageContent, function (item) {
        return item.sectionId === "team";
      });

      // now we have our contact details array - find the specific contact(s)
      var contactsArray = new Array();
      for (var i in contacts) {
        var contact = _.detect(contactDetails.contacts, function (item) {
          return item.contactId == contacts[i].contactId || item.contactId === contacts[i];
        });
        if (typeof (contact) === "object") {
          contactsArray.push(contact);
        }
      }

      return contactsArray;
    },

    /*
     * This function should only be called from init, so once per page load.
     */
    setTopNav: function (pageId) {
      $.ajax({
        url: myApp.content.CONTENT_URI,
        success: function (data) {
          myApp.content.mJsonData = data;
          myApp.content.redrawTopNav(pageId);
        },
        error: function (xhr, status, error) {
          alert("error: " + xhr.status);
        },
        async: false,
        dataType: "json",
        type: "GET"
      });
    },

    getOpenings: function () {
      $.ajax({
        url: 'lib/zaajson.json',
        cache: false,
        success: function (data) {
          var html = '<br /><p style="position: relative"><a class="button" href="mailto:resumesgb@zyquest.com?subject=Resume Submission&body=Please attach your resume and send.">General Apply</a><img src="img/pages/careers_opportunities.jpg" style="position: absolute; right: 10px; top: -25px" /></p><br /><div id="openings-table-holder"><table class="openings-table" border="1px solid #CCC">';
          html += '<th colspan="2">Description</th><th>Location</th><th>Type</th><th>Status</th><th colspan="2"></th>';
          for (var object in data.Openings) {
            //TODO - find a way to just pass the data.Openings[object] object
            var clickevent = "myApp.content.createInfoPage('" + data.Openings[object].Title + "', '" + data.Openings[object].Description + "', '" + data.Openings[object].Location;
            clickevent += "', '" + data.Openings[object].Type + "', '" + data.Openings[object].Status + "', '" + data.Openings[object].Email + "', '";
            clickevent += data.Openings[object].OrderNumber + "', '" + data.Openings[object].Duration + "', '" + data.Openings[object].StartDate + "', '" + data.Openings[object].EndDate;
            clickevent += "', '" + escape(data.Openings[object].LongDescription) + "');";

            html += '<tr><td colspan="2">' + data.Openings[object].Title + ' - ' + data.Openings[object].Description + '</td>';
            html += '<td style="width: 200px">' + data.Openings[object].Location + '</td><td style="width: 80px">' + data.Openings[object].Type + '</td><td>' + data.Openings[object].Status + '</td>';
            html += '<td style="width: 90px"><a class="button" onclick="' + clickevent + '" >More Info</a></td>';
            html += '<td><a class="button" href="mailto:' + data.Openings[object].Email + '?subject=Resume Submission - Order Number ' + data.Openings[object].OrderNumber + '&body=Please attach your resume and send.">Apply</a></td></tr>';

          }

          html += '</table></div>';
          $('.child-content').append(html);
        },
        error: function (xhr, status, error) {
          alert("error: " + xhr.status);
        },
        async: true,
        dataType: "json",
        type: "GET"
      });
    },

    createInfoPage: function (title, description, location, type, status, email, ordernumber, duration, startdate, enddate, longdescription) {

      if (startdate !== "") {
        var sd = new Date(startdate);
        startdate = sd.toLocaleDateString();
      }
      if (enddate !== "") {
        var ed = new Date(enddate);
        enddate = ed.toLocaleDateString();
      }

      // %0D%0A = newline
      var infobody = "<a href='mailto:" + email + "?subject=Resume Submission For Order Number " + ordernumber + "&body=Please attach your resume and send.' class='applylink' target='_blank'>Apply</a><br><br>";
      infobody += "Job Order: " + title + " %0D%0A";
      infobody += "Post Description: " + description + " %0D%0A";
      infobody += "Start Date: " + startdate + " %0D%0A";
      infobody += "End Date: " + enddate + " %0D%0A";
      infobody += "Location: " + location + " %0D%0A";
      infobody += "Type: " + type + " %0D%0A";
      infobody += "Status: " + status + " %0D%0A%0D%0A";
      infobody += "Additional Info: " + longdescription + " %0D%0A";
      infobody += "http://www.zyquest.com" + " %0D%0A";
      infobody += "1-800-992-0533" + " %0D%0A";
      infobody += "<br><br><a href='mailto:" + email + "?subject=Resume Submission For Order Number " + ordernumber + "&body=Please attach your resume and send.' class='applylink' target='_blank'>Apply</a>";

      var $dialog = $('<div id="basic-modal-content"></div>').html(unescape(infobody).replace(/(\r\n|\n|\r)/gm, "<br />"));
      
      $dialog.modal({
         minHeight: 100,
         minWidth: 420,
         maxHeight: 400,
         maxWidth: 700,
         overlayClose:true,
         opacity: 70
      });
    },

    setPageContent: function (pageId) {
      var uri = myApp.content.CONTENT_URI.replace(/topnav/, pageId);

      // mPageId is used to refer back to the current page for displaying 
      // the correct subnav menus.  Currently mPageId is only used in 
      // index.html.
      myApp.content.mPageId = pageId;

      // TODO: we will need to determine what template to display and which 
      //       ones to hide.
      //myApp.content.showContentContainer("content-no-left-title");
      $.ajax({
        url: uri,
        success: function (data) {
          myApp.content.mPageContent = data;

          // TODO: this is called twice when the page is initially loaded, once here and once in init.setTopNav.
          myApp.content.redrawTopNav(pageId);
          if (pageId !== undefined) {
            // Commented this out because we no longer wish to display the sub-nav links unless top-nav is being hovered.  The sub-nav links are quick links.  These will only be displayed "full-time" per page in the footer-nav.
            //myApp.content.redrawSubNav(pageId, myApp.content.SUBNAVLINKS);
            myApp.content.redrawSubNav(pageId, myApp.content.FOOTERNAVLINKS);
          }

          // Clear the section content since we have a new page.
          //$("content_no_left_title").html("");
          //$("content_left_title").html("");
          //alert(data.pageId);
        },
        error: function (xhr, status, error) {
          alert("error: " + xhr.status);
        },
        async: false,
        dataType: "json",
        type: "GET"
      });
    },

    redrawTopNav: function (pageId) {
      if (myApp.content.mJsonData.links == null) {
        alert("No links loaded in redrawTopNav.");
        return;
      }

      var navHtml = "";
      $.each(myApp.content.mJsonData.links, function (key, value) {
        if (value.enabled == "Y") {
          navHtml += "<li";
          if ((pageId !== undefined) && (pageId == value.pageId)) {
            navHtml += " class='selected'>";
          } else {
            navHtml += ">"
          }

          //navHtml += "<a href='#' class='nav-link' onClick=\"myApp.content.setPageContent('" + value.pageId + "')\" onMouseOver=\"myApp.content.redrawSubNav('" + value.pageId + "')\" onMouseOut=\"myApp.content.redrawSubNav('" + pageId + "')\">" + value.navTitle + "</a></li>";
          //navHtml += "<a href='it.html' class='nav-link' onClick=\"myApp.content.setPageContent('" + value.pageId + "')\" onMouseOver=\"myApp.content.redrawSubNav('" + value.pageId + "', 'subnav')\">" + value.navTitle + "</a></li>";
          // Ticket #: 671
          // Description: Remove "Home" header link.  Make sub-nav appear when hovering over ZyQuest logo.
          var navUri = value.navUri;
          if (value.navImage == "") {
            if (value.navTitle === "Home") {
              navUri = "about.html";
            }
            navHtml += "<a href='" + navUri + "' class='header-nav-link' onMouseOver=\"myApp.content.redrawSubNav('" + value.pageId + "', '" + myApp.content.SUBNAVLINKS + "')\">" + value.navTitle + "</a></li>";
          } else {
            navHtml += "<a href='" + value.navUri + "' class='header-nav-link' onMouseOver=\"myApp.content.redrawSubNav('" + value.pageId + "', '" + myApp.content.SUBNAVLINKS + "')\"><img src='" + value.navImage + "' alt='ZyQuest' title='Home' /></a></li>";

          }
        }
      });

      $("#" + myApp.content.HEADERNAVLINKS).html(navHtml);
    },

    setSectionContent: function (pageId, sectionId) {
      $('.addthis_container').remove();
      myApp.content.mSectionId = sectionId;

      if ((myApp.content.mPageId == null) || (myApp.content.mPageId === undefined) || (myApp.content.mPageId != pageId)) {
        return true;
      } else {
        myApp.sidePanel.clearGroupContent();
        myApp.sidePanel.addGroupContent('<a id="siteMap" href="#"><img src="img/sidebar/sidebar-sitemap.png" alt="Sitemap" title="View our Sitemap" /></a>');
        $('#siteMap').click(function (event) {
          $('#' + myApp.sidePanel.id + '_content').empty();
          $('#' + myApp.sidePanel.id + '_content').append(myApp.content.generateSiteMap());
          $('#' + myApp.sidePanel.id + '_content_wrapper').css('top', -146);
          $('#' + myApp.sidePanel.id + '_content_wrapper').toggle();
          $('#' + myApp.sidePanel.id + '_content_carat').show();
          return stopBubble(event);
        });

        var contactsArray = myApp.content.getTopicContacts();
        for (var i in contactsArray.reverse()) {
          myApp.sidePanel.addGroupContent("<a class='showContactDetails' href='#'><img src='" + contactsArray[i].photoUri + "' width='24px' alt='Request Information' title='Request Information' class='sp_round' /></a>");
        }

        $('.showContactDetails').click(function (event) {
        myApp.content.showSlidePanelContactDetails();
        $('#' + myApp.sidePanel.id + '_content_wrapper').css('top', -185);
        $('#' + myApp.sidePanel.id + '_content_carat').show();
        return stopBubble(event);
        });

        myApp.featured && myApp.featured.stop();
        parent.location.hash = "#" + pageId + "." + sectionId;

        myApp.content.setPageContent(pageId);

        if (myApp.content.mPageContent == null) {
          alert("No links loaded in setSectionContent.");
          return;
        }

        if (sectionId === "rotator") {
          $("#content").html(myApp.revolver.getMarkup("myApp.revolver"));
        } else if (sectionId === "overview") {
          var overview = _.detect(myApp.content.mPageContent.sections, function (item) {
            return item.sectionId === "overview";
          });
          if (overview.content !== undefined) {

            // If overview.content.items contains > 2 items, then randomly grab a testimonial for the current page and fill the empty ones.
            var numItems = overview.content.items.length;
            if (numItems < 3) {
              var testimonialId = pageId;
              if (testimonialId === "services" || testimonialId === "infrastructure") {
                testimonialId = "careeropportunities";
              }
              var testimonials = _.detect(myApp.content.mTestimonials.pages, function (item) {
                return item.pageId == testimonialId;
              });

              var usedTestimonialArray = new Array();
              for (var i = numItems; i < 4; i++) {
                var randomTestimonialIndex = Math.floor(Math.random() * testimonials.testimonials.length);

                // Was this testimonial used already?
                if (usedTestimonialArray.length > 0) {

                  var found = true;
                  do {
                    for (var n = 0; n < usedTestimonialArray.length; n++) {
                      if (usedTestimonialArray[n] == randomTestimonialIndex) {
                        randomTestimonialIndex = Math.floor(Math.random() * testimonials.testimonials.length);
                        found = true;
                        break;
                      } else {
                        found = false;
                      }
                    }
                  } while (found == true);
                }

                usedTestimonialArray.push(randomTestimonialIndex);
                var testimonial = testimonials.testimonials[randomTestimonialIndex];
                var html = myApp.content.formatTestimonialForRotator(testimonial);
                var item = myApp.featured.getDefaultItem();

                var name = testimonial.source.name ? '<br>' + testimonial.source.name : '';
                var title = testimonial.source.title ? '<br>' + testimonial.source.title : '';
                var company = testimonial.source.company ? '<br>' + testimonial.source.company : '';
                var boxText = 'Testimonial<br/>' + name + title + company;
                item.data = $('<div>').append($.tmpl(item.data, {
                  classes: 'fd-item-html-centered fd_item_dark',
                  content: boxText
                })).remove().html();
                item.feature = $('<div>').append($.tmpl(item.feature, {
                  vertical: 'bottom',
                  horizontal: 'right',
                  title: 'Testimonial',
                  description_text_align: 'description left',
                  description: html
                })).remove().html();
                overview.content.items.push(item);
              }
            }

            myApp.featured.init();
            myApp.featured.setContent(overview.content);
            myApp.featured.render("#content", function (err) {
              // if (err && console) {
              //   console.log(err);
              // }
            });
          }
        } else if ((pageId === "developmentcenter") && (sectionId === "successes")) {
          // we get testimonials from one json file, we need to get rotator items from another.
          var successes = _.detect(myApp.content.mPageContent.sections, function (item) {
            return item.sectionId === "successes";
          });
          if (successes.content === undefined) {
            // If the structure of the json file changes, this may need to change too.  We need this in case there are no items to clone.
            successes.content = {
              'featured': {
                'skin': 'zyquest.developmentcenter',
                'type': 'html',
                'data': html.split(),
                'actionUri': ''
              },
              'useBorderedItems': true,
              'items': successes.content.items
            };
          }

          var content = _.clone(successes.content);
          var data = myApp.content.getTestimonials(pageId);
          var html = myApp.content.formatTestimonialsForContent(pageId, data);

          // changing content by cloning what was there and replacing what was in the featured.data property.
          content.featured.data = html.split();

          myApp.featured.init();
          myApp.featured.setContent(content);
          myApp.featured.render("#content", function (err) {
            if (err && console) {
              console.log(err);
            }
          });
        } else if ((pageId === 'careeropportunities') && (sectionId === 'testimonials')) {
          var data = myApp.content.getTestimonials(pageId);
          if (data != null) {
            var html = myApp.content.formatTestimonialsForContent(pageId, data);
            $("#content").html(html);
          }
        } else if (((pageId === "about") || (pageId === 'home')) && (sectionId === "clients")) {
          var data = _.detect(myApp.content.mPageContent.sections, function (item) {
            return item.sectionId === "clients";
          });
          if (data.content === undefined) {
            data.content = '';
          }
          myApp.featured.init();
          myApp.featured.setContent(data.content);
          myApp.featured.render("#content", function (err) {
            if (err && console) {
              console.log(err);
            }
          });
          var data = myApp.content.getTestimonials(pageId);
          if (data != null) {
            var html = myApp.content.formatTestimonialsForContent(pageId, data);
            $("#sub-content").append(html);
          }
        } else if (((pageId === "about") || (pageId === 'home')) && (sectionId === "affiliations")) {
          var data = _.detect(myApp.content.mPageContent.sections, function (item) {
            return item.sectionId === "affiliations";
          });
          if (data.content === undefined) {
            data.content = '';
          }
          myApp.featured.init();
          myApp.featured.setContent(data.content);
          myApp.featured.render("#content", function (err) {
            if (err && console) {
              console.log(err);
            }
          });
        } else if (((pageId === "about") || (pageId === 'home')) && (sectionId === "partners")) {
          var data = _.detect(myApp.content.mPageContent.sections, function (item) {
            return item.sectionId === "partners";
          });
          if (data.content === undefined) {
            data.content = '';
          }
          myApp.featured.init();
          myApp.featured.setContent(data.content);
          myApp.featured.render("#content", function (err) {
            if (err && console) {
              console.log(err);
            }
          });
        } else if (((pageId === "about") || (pageId === 'home')) && (sectionId === "team")) {
          var jsonData = _.detect(myApp.content.mPageContent.sections, function (item) {
            return item.sectionId == sectionId;
          });

          var html = ['<div>', '<div id="selectedSubNav" class="selectedSubNav">', '</div>', '<div class="addthis_container">', '<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;pubid=ra-4e08db6a49da6eee"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a>', '</div>', '<script type="text/javascript">var addthis_config = {"data_track_clickback":true, "ui_open_windows":true};</script>', '<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4e08db6a49da6eee"></script>', '</div>', '<div class="contacts-content">', '<ul id="contact-list">'].join('\n');


          // Create the layout for the contacts
          var count = 0;
          while (count < jsonData.contacts.length) {
            html += ['<li>', '<div id="contact' + (count++) + '" style="float: left; width: 49%;">', '</div>', '<div id="contact' + (count++) + '" style="float: right; width: 49%;">', '</div>', '</li>'].join('\n');
          }

          html += ['</ul>', '</div>'].join('\n');

          // Add the contacts layout to the page.
          var e = document.getElementById('content');
          e.innerHTML = html;

          // Add subnav title to content (there is another one, search for this text in comments).
          var topnavLink = _.detect(myApp.content.mJsonData.links, function (item) {
            return item.pageId == pageId;
          });
          var subnavLink = _.detect(topnavLink.subNav, function (item) {
            return item.sectionId === sectionId;
          })
          $("#selectedSubNav").html(subnavLink.title);

          // Add each contact to the contacts layout in the correct location.
          for (var contactIndex in jsonData.contacts) {
            html = myApp.content.setContactUsItem(jsonData.contacts[contactIndex]);
            e = document.getElementById('contact' + contactIndex);
            e.innerHTML = html;
          }
        } else {
          $.each(myApp.content.mPageContent.sections, function (key, value) {

            var addThis = ['<div>', '<div id="selectedSubNav" class="selectedSubNav">', '</div>', '<div class="addthis_container">', '<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;pubid=ra-4e08db6a49da6eee"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a>', '</div>',
                                                                  //'<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4e08db6a49da6eee&async=1"></script>'
                                                                                                      '<script type="text/javascript">var addthis_config = {"data_track_clickback":true, "ui_open_windows":true};</script>', '<script type="text/javascript"> eval($.ajax({ url: "http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4e08db6a49da6eee&async=1", cache: "false", dataType: "script", type: "GET" }));  </script>', '</div>'].join('\n');

            if (value.sectionId == sectionId) {
              var jsonTemplate = value.template;
              if ($.isArray(value.template) == true) {
                jsonTemplate = value.template.join('');
              }

              // append the AddThis buttons to the page.
              jsonTemplate = addThis + jsonTemplate;
              //jsonTemplate = jsonTemplate.replace("<div class='child-content'>", addThis);
              jsonTemplate = jsonTemplate.replace(/zyquest(?!\<nr\/>)/gi, 'Zy<span class="q-color">Q</span>uest, Inc.');
              jsonTemplate = jsonTemplate.replace(/\<nr\/>/gi, '');

              //var finalMarkup = $(value.template).tmpl(value.data);
              //var template = '<div id="child-content" class="child-content">' + jsonTemplate + "</div>";
              var finalMarkup = $.tmpl(jsonTemplate, value.data);
              $("#content").html(finalMarkup);

              // Add subnav title to content (there is another one, search for this text in comments).
              var topnavLink = _.detect(myApp.content.mJsonData.links, function (item) {
                return item.pageId == pageId;
              });
              var subnavLink = _.detect(topnavLink.subNav, function (item) {
                return item.sectionId === sectionId;
              })
              $("#selectedSubNav").html(subnavLink.title);

              if ((pageId === "careeropportunities") && (sectionId === "opportunities")) {
                myApp.content.getOpenings();
              }

              return;
            }
          });
        } // end else
      }

      // if the moreButton for testimonials is set, bind a click event to it.  Need to do this here 
      // because the moreButton is defined in some scenarios within this function.
      var moreButton = document.getElementById('moreButton');
      if (moreButton !== undefined) {
        $('#moreButton').bind('click', function () {
          myApp.content.moreTestimonials();
        });
      }

      return false;
    },

    setContactUsItem: function (contact) {

      var photoUri = (contact.photoUri && contact.photoUri.length > 0) ? contact.photoUri : 'img/missing_photo.png';
      var displayName = contact.displayName;
      var jobTitle = contact.jobTitle;
      var jobTitle2 = (contact.jobTitle2 && contact.jobTitle2.length > 0) ? ["<div class='jobTitle'>", contact.jobTitle2, "</div>",].join('\n') : '';

      var email = contact.email;
      var voice = contact.phone;
      var fax = contact.fax;


      var facebookUri = (contact.facebookUri) ? ['<li class="facebook">', '<a href="' + contact.facebookUri + '" target="top">',
                                    //'<img src="img/icons/fb.png" alt="Facebook" title="Follow us on Facebook" />',
                                                      'facebook', '</a>', '</li>'].join('\n') : '';

      var twitterUri = (contact.twitterUri) ? ['<li class="twitter">', '<a href="' + contact.twitterUri + '" target="top">',
                                    //'<img src="img/icons/twitter.png" alt="LinkedIn" title="Follow ' + contact.displayName + ' on Twitter" />',
                                                      'twitter', '</a>', '</li>'].join('\n') : '';

      var linkedInUri = (contact.linkedInUri) ? ['<li class="linkedin">', '<a href="' + contact.linkedInUri + '" target="top">',
                                    //'<img src="img/icons/linkedin.png" alt="LinkedIn" title="Follow ' + contact.displayName + ' on LinkedIn" />',
                                                      'linkedin', '</a>', '</li>'].join('\n') : '';

      var emailUri = (contact.email) ? ['<li class="email">', '<a href="mailto:' + contact.email + '" target="top">',
                                    //'<img src="img/icons/linkedin.png" alt="LinkedIn" title="Follow ' + contact.displayName + ' on LinkedIn" />',
                                                      'email', '</a>', '</li>'].join('\n') : '';

      var vCardToolTip = (contact.vCardToolTip) ? contact.vCardToolTip : 'vCard';
      var vCard = (contact.vCardUri) ? ['<li class="vcard">', '<a href="' + contact.vCardUri + '" target="top">',
                                    //'<img src="img/icons/vcard.png" alt="vCard" title="' + vCardToolTip + '" />',
                                                      'vcard', '</a>', '</li>'].join('\n') : '';

      var vCardAltToolTip = (contact.vCardAltToolTip) ? contact.vCardAltToolTip : 'vCard';
      var vCardAltUri = (contact.vCardAltUri) ? ['<li class="vcard">', '<a href="' + contact.vCardAltUri + '" target="top">',
                                    //'<img src="img/icons/vcard.png" alt="vCard" title="' + vCardAltToolTip + '" />',
                                                      'vcardalt', '</a>', '</li>'].join('\n') : '';

        var html = [
          '<div class="contacts-table">',
            '<img src="' + photoUri + '" class="thumb" style="float:left;margin-right:10px;"/>',
            '<div class="contacts-table">',
		      '<div class="displayName">',
                displayName,
              '</div>',
              '<div class="jobTitle">',
                jobTitle,
              '</div>',
              jobTitle2,
              '<div class="contactDetails contactDetailsSeparator">',
                'Email:&nbsp;' + email + '<br>',
                'Voice:&nbsp;' + voice + '<br>',
//                            "{{if item.mobile}}<div>\n<b>Mobile:</b>&nbsp;${item.mobile}<br/>\n</div>{{/if}}",
                'Fax:&nbsp;' + fax,
                '<ul class="contactTypes">',
                  facebookUri, twitterUri, linkedInUri, emailUri, vCard, vCardAltUri,
                '</ul>',
              '</div>',
			'</div>',
          '</div>',			
        ].join('\n');

      //var e = document.getElementById(elementId);
      //e.innerHTML = html;
      return html;
    },

    getTestimonials: function (pageId) {
      var uri = myApp.content.CONTENT_URI.replace(/topnav/, 'testimonials');

      // mPageId is used to refer back to the current page for displaying 
      // the correct subnav menus.  Currently mPageId is only used in 
      // index.html.
      myApp.content.mPageId = pageId;
      var jsonData = null;

      $.ajax({
        url: uri,
        success: function (data) {
          jsonData = data;
        },
        error: function (xhr, status, error) {
          alert("error: " + xhr.status);
        },
        async: false,
        dataType: "json",
        type: "GET"
      });

      return jsonData;
    },

    moreTestimonials: function (event) {
      myApp.layout.show('hiddenTestimonials');
      myApp.layout.hide('moreButton');
      event && event.preventDefault();
      return false;
    },

    formatTestimonialsForContent: function (pageId, data) {
      var html = '<div class="child-content" id="testimonialContent">';

      var testimonials = _.detect(data.pages, function (item) {
        return item.pageId == pageId;
      });
      var hiddenTestimonialsEnd = '';
      var moreButton = '';
      var testimonialCount = 0;
      for (var i = 0; i < testimonials.testimonials.length; i++) {
        if (testimonialCount++ == 2) {
          html += '<div id="moreButton" class="moreTestimonials">More Testimonials...</div>'
          html += '<div id="hiddenTestimonials" class="hiddenTestimonials";>';
          hiddenTestimonialsEnd = '</div>';
        }

        var testimonial = testimonials.testimonials[i];
        html += '<div class="quote_container">';
        //html += '<div class="quote">&quot;' + testimonial.quote + '&quot;  ' + testimonial.date + '</div>';
        html += '<blockquote><p>' + testimonial.quote + '</p></blockquote>' + testimonial.date;
        html += '<div class="quote-source">&#x270E;</div>';

        var name = '';
        if (testimonial.source.name.length > 0) {
          name = testimonial.source.name;
        }

        if (testimonial.source.title.length > 0) {
          if (name.length > 0) {
            name += ', ';
          }

          name += testimonial.source.title;
        }

        if (name.length > 0) {
          html += '<div>' + name + '</div>';
        }

        if (testimonial.source.company.length > 0) {
          var company = '<div class="quote-source">&nbsp;</div>';
          company += '<div>' + testimonial.source.company + '</div>';
          html += company;
        }

        html += '</div>';
        html += '<center><hr style="width: 75%;" /></center>';
      }

      html += hiddenTestimonialsEnd + '</div>';

      return html;
    },

    formatTestimonialForRotator: function (testimonial) {
      var html = '<p>';
      html += '<div class="quote">&quot;' + testimonial.quote + '&quot;  ' + testimonial.date + '</div>';
      html += '<div class="quote-source">&#x270E;</div>';

      var name = '';
      if (testimonial.source.name.length > 0) {
        name = testimonial.source.name;
      }

      if (testimonial.source.title.length > 0) {
        if (name.length > 0) {
          name += ', ';
        }

        name += testimonial.source.title;
      }

      if (name.length > 0) {
        html += '<div>' + name + '</div>';
      }

      if (testimonial.source.company.length > 0) {
        var company = '<div class="quote-source">&nbsp;</div>';
        company += '<div>' + testimonial.source.company + '</div>';
        html += company;
      }

      html += '</p>';

      return html;
    },

    redrawSubNav: function (pageId, listId) {
      if (myApp.content.mJsonData.links == null) {
        alert("No links loaded in redrawSubNav.");
        return;
      }

      var navHtml = "";
      $.each(myApp.content.mJsonData.links, function (key, value) {
        if ((pageId === undefined) || (pageId == null)) {
          $("#" + myApp.content.SUBNAVLINKS).html("");
          $("#" + myApp.content.FOOTERNAVLINKS).html("");
        } else {
          var fileName = value.navUri;
          if (value.pageId == pageId) {

            $.each(value.subNav, function (key, value) {
              if (value.enabled == "Y") {
                var css = 'sub-nav-link';
                if ((listId == myApp.content.FOOTERNAVLINKS) && (value.sectionId === 'overview')) {
                  css = 'footerNavTopic';
                }

                navHtml += "<li><a class='" + css + "' href='" + fileName + "#" + pageId + "." + value.sectionId + "' onclick=\"return myApp.content.setSectionContent('" + pageId + "', '" + value.sectionId + "')\">" + value.title + "</a></li>";
              }
            });

            $("#" + listId).html(navHtml);

            return;
          }
        }
      });

      // need this check to make sure that we only create the navSlider once.
      if ((myApp.content.mPageIsCreated == true) && (listId == myApp.content.FOOTERNAVLINKS)) {
        myApp.navSlider.create();
      }
    },

    // Called in index.html to redraw the subnav menu when the mouse ventures
    // into the content area.
    redrawSubNavByFlagValue: function (pageId, listId) {
      if (myApp.content.mRedrawSubNavFlag == true) {
        myApp.content.mRedrawSubNavFlag = false;

        // Ticket #: 668
        // Description: Sub-nav area should go blank once mouse leaves top nav area.
        // Comments: (MPS) I'm going to blank the sub-nav area when the mouse enters the content area. Otherwise, users could only view sub-nav links when they hover the topics, but they wouldn't be able to select the sub-nav because it would disappear.
        //myApp.content.redrawSubNav(pageId, listId);
        $("#" + listId).html("");
      }
    },

    setRedrawSubNavFlag: function (redraw) {
      myApp.content.mRedrawSubNavFlag = redraw;
    },

    showContentContainer: function (containerId) {
      if (containerId == "content") {
        $("#content").attr("style", "display: inline");
        $("#content-no-left-title").attr("style", "display: none");
        $("#content-left-title").attr("style", "display: none");
      } else if (containerId == "content-no-left-title") {
        $("#content").attr("style", "display: none");
        $("#content-no-left-title").attr("style", "display: inline");
        $("#content-left-title").attr("style", "display: none");
      } else if (containerId == "content-left-title") {
        $("#content").attr("style", "display: none");
        $("#content-no-left-title").attr("style", "display: none");
        $("#content-left-title").attr("style", "display: inline");
      }
    },

    showRotatorItemDetailDialog: function (pageId, sectionId, rotatorItemId) {
/* var pageContent;
        if(myApp.content.mPageId == pageId) {
          pageContent = myApp.content.mPageContent.sections;
     
        }
        else {
          // todo: add error dialog - this should never happen because the page we are on should already have mPageContent available.
          var uri = myApp.content.CONTENT_URI.replace(/topnav/, "home");

          $.ajax({
              url: uri,
              success: function(data) {
                pageContent = data.sections;
              },
              error: function(xhr, status, error) {
                alert("error: " + xhr.status); 
              },
              async: false,
              dataType: "json",
              type: "GET"
          });
          alert("While trying to show rotator item detail, rotator content was not found.");
          return false;
        }

        // now we have our page content with contact details in it - now get the contacts
        var sectionDetails = _.detect(pageContent, function(item){ return item.sectionId == sectionId;} );
        var rotatorItem = _.detect(sectionDetails.content.items, function(item){ return item.dataId == rotatorItemId;} );

        var $dialog = $('<div class="ui-dialog"></div>')
          .html(rotatorItem.dataDetail.join('\n'))
          .dialog( {
            autoOpen: false, 
            buttons: { 
              "Close": function() { 
                $(this).dialog("close");
              }
            },
            minHeight: 300,
            minWidth: 500,
            maxHeight: 500,
            maxWidth: 800,
            height: 300,
            width: 500,
            modal: true
          });

        $dialog.dialog('open');
    $dialog.scrollTop(0);*/

      return true;
    },

    getImages: function () {
      $.getJSON("lib/layout.topnav.json").success(function (data) {
        myApp.revolver.images = data.images;
        myApp.revolver.spin('rotator-image', 10, 'rotator-page');
      }).error(function (xhr, status, error) {
        alert("error: " + xhr.status);
      });
    },

    getThumbnails: function () {
      $.getJSON("lib/layout.topnav.json").success(function (data) {
        $('#rotator-item-1').css("background-image", "url(" + data.thumbnails[0].imageUri + ")");
        $('#rotator-item-2').css("background-image", "url(" + data.thumbnails[1].imageUri + ")");
        $('#rotator-item-3').css("background-image", "url(" + data.thumbnails[2].imageUri + ")");
      }).error(function (xhr, status, error) {
        alert("error: " + xhr.status);
      });
    },

    setPageFooter: function () {
      if (myApp.content.mJsonData.pageFooter == null) {
        alert("no footer data.");
        return;
      }

      $("#" + myApp.content.PAGEFOOTER).html("<div>" + myApp.content.mJsonData.pageFooter[0].text + "</div>");
    }
  }

  // Can use this to call init by default, or call it from the html page.
  //myApp.content.init();
})();
