dojo.require("esri.arcgisonline.map.main");
dojo.require("esri.arcgisonline.sharing.util");
dojo.require("esri.arcgisonline.sharing.dijit.Gallery");
dojo.require("esri.arcgisonline.sharing.geow.Account");
dojo.require("esri.arcgisonline.sharing.dijit.HelpManager");
dojo.require("dojo.date.locale");
dojo.require("dojox.widget.Rotator");
dojo.require("dojox.widget.rotator.Controller");
dojo.require("dojox.widget.rotator.Fade");
dojo.require("dojo.cookie");

var page = {};

dojo.mixin(page, {
  labels: null,
  loadLabels: function() {
    this.labels = dojo.i18n.getLocalization("esri", "arcgisonline").common;
    dojo.mixin(this.labels, dojo.i18n.getLocalization("esri", "arcgisonline").homePage);
    
    dojo.attr("viewerLink", "innerHTML", this.labels.viewerLink);
    dojo.attr("viewerDescription", "innerHTML", this.labels.viewerDescription);
    dojo.attr("signUpLink", "innerHTML", this.labels.signUpLink);
    dojo.attr("signUpDescription", "innerHTML", this.labels.signUpDescription);
    dojo.attr("featuredVideosLink", "innerHTML", this.labels.featuredVideosLink);
    dojo.attr("featuredVideosDescription", "innerHTML", this.labels.featuredVideosDescription);
    dojo.attr("lnkExplore", "innerHTML", this.labels.explorerLink);
    dojo.attr("pExplore", "innerHTML", this.labels.explorerDescription);
    dojo.attr("headerH1Tag", "innerHTML", this.labels.ArcGISOnline);
  }
});

dojo.addOnLoad(init);

var gallery;
var feeds = [];
var currentFeed;
var panelRotator = {};
var featuredMaps = {};
var allSSL = false;
var isOrg = false;
var isSingleTenant = false;
var settings;

function init() {
  esri.i18nBundle = dojo.i18n.getLocalization("esri", "arcgisonline");
  page.loadLabels();

  // load help links
  var helpMgr = esri.arcgisonline.sharing.dijit.HelpManager.prototype.statics.getInstance();
  dojo.connect(helpMgr, "onLoad", dojo.hitch(this, function() {
    dojo.byId("featuredVideosLink").href = helpMgr.getHelpUrl("120000461");
  }));

  // determine portal tenancy
  isSingleTenant = (esriGeowConfig.isMultiTenant !== undefined && esriGeowConfig.isMultiTenant !== null && esriGeowConfig.isMultiTenant === false);
  
  // configure organization mode if single-tenant
  var user = esri.arcgisonline.sharing.util.getUser();
  if(isSingleTenant || (user && user.accountId)) {
    isOrg = true;
    // remove the header
    var ht = dojo.byId("headerTitle");
    if(ht){
      ht.parentNode.removeChild(ht);
    }
  }
  
  // load settings, then load page
  esri.arcgisonline.sharing.geow.Account.getSelf(dojo.hitch(this, initPage), dojo.hitch(this, initPage));
}

function overrideSettings(result) {
  // save the settings
  settings = result;
  
  // determine if this is an organization
  if(settings.id && settings.id.length > 0) {
    isOrg = true;
    // remove the header
    var ht = dojo.byId("headerTitle");
    if(ht) {
      ht.parentNode.removeChild(ht);
    }
  }
  
  // set allSSL
  if(result.allSSL) {
    allSSL = result.allSSL;
  }
  
  // override portalName and portalHostname
  if(result.portalName) {
    esriGeowConfig.portalName = result.portalName;
  }
  if(result.portalHostname) {
    esriGeowConfig.portalHostname = result.portalHostname;
  }
  
  // override portalHeaderImage
  if(result.portalHeaderImage) {
    esriGeowConfig.portalHeaderImage = result.portalHeaderImage;
  }
  
  // override homePageFeaturedContent and homePageFeaturedContentCount
  if(result.homePageFeaturedContent) {
    esriGeowConfig.homePageFeaturedContent = result.homePageFeaturedContent;
  } else {
    // by default the home page doesn't show featured content for an organization,
    // unless the organization selects a group to display
    if(isOrg) {
      esriGeowConfig.homePageFeaturedContent = null;
    }
  }
  if(result.homePageFeaturedContentCount) {
    esriGeowConfig.homePageFeaturedContentCount = result.homePageFeaturedContentCount;
  }
  
  // override rotatorPanels
  if(result.rotatorPanels) {
    esriGeowConfig.rotatorPanels = result.rotatorPanels;
  } else {
    // default rotatorPanels
    if(isOrg) {
      esriGeowConfig.rotatorPanels = null;
    }
  }
  
  // override showHomePageDescription
  var showDesc = result.showHomePageDescription;
  // if the showHomePageDescription value is set, use it, otherwise default to false
  if(showDesc !== undefined && showDesc !== null) {
    esriGeowConfig.showHomePageDescription = result.showHomePageDescription;
  } else {
    esriGeowConfig.showHomePageDescription = false;
  }
}

function initOrganization() {
  //hide the bottom panel (Sign-Up, Featured Videos, Start ArcGIS Explorer Online)
  esri.hide(dojo.byId('bottomSection'));
   
   //add Arcgis Explorer Online to second row
   var explorerOnlineLink = (allSSL ? esriGeowConfig.explorerOnline.replace("http:", "https:") : esriGeowConfig.explorerOnline.replace("https:", "http:"));
   //if(settings.urlKey) {
   //  explorerOnlineLink += "?org=" + settings.urlKey;
   //}
   dojo.create("span",{
    innerHTML:'<h2 id="h2Explore">' + 
              '<a id="lnkExplore" class="explorerLink" href="' + explorerOnlineLink + '">' + page.labels.explorerLink + '</a>' +
              '</h2>' + 
              '<p id="pExplore">' + page.labels.explorerDescription + '</p>'
   },dojo.byId('topRow2'));
   
  //add the company name and details to the 'About the organization section'
  //in some cases there may not be an organization description so only display 
  //section if this exists.
  var name = settings.name;
  var description = settings.description;
  var showDesc = esriGeowConfig.showHomePageDescription;
  showDesc = (showDesc !== undefined && showDesc !== null && showDesc === false) ? false : true;

  if(description && description !== "" && showDesc) {
    //display the organization panel
    dojo.byId("orgDetails").innerHTML = description;
    //dojo.byId("orgName").innerHTML = name;
    esri.show(dojo.byId("organizationSection"));
  }
  
  var token = esri.arcgisonline.sharing.util.getToken();
  var tokenParam = (token ? "?token=" + token : "");
  //if rotator panels are defined for the organization display those
  var url = esriGeowConfig.restBaseUrl + "accounts/self/resources/rotatorPanels" +  tokenParam;
  esri.arcgisonline.sharing.util.getJson(url, dojo.hitch(this, function(results){
    createRotator(dojo.fromJson(results));
  }),function(error){
    // no explicit/separate rotator panels defined, check account settings
    if(esriGeowConfig.rotatorPanels) {
      // shorten layout for custom/predefined banners
      dojo.addClass(dojo.byId("matrixLayout"), "matrixLayoutShort");
      dojo.addClass(dojo.byId("details"), "detailsShort");
      
      var tkn = esri.arcgisonline.sharing.util.getToken();
      var panel;
      var rotatorPanels = esriGeowConfig.rotatorPanels;
      for(var i = 0; i < rotatorPanels.length; i++) {
        panel = rotatorPanels[i];
        // adjust for allSSL mode
        if(panel.id) { // if the panel has an id, assume it's been set up through our UI
          panel.innerHTML = (allSSL ? panel.innerHTML.replace("http:", "https:") : panel.innerHTML.replace("https:", "http:"));
        }
        rotatorPanels[i].innerHTML = panel.innerHTML.replace("SECURITY_TOKEN", (tkn ? tkn : ""));
      }
      createRotator(rotatorPanels);
    } else {
      //no rotator panels exist - use image instead
      var displayImage = esriGeowConfig.portalHeaderImage? esriGeowConfig.portalHeaderImage : 'images/organizationSplash.jpg';
      dojo.create("img", {
        id: 'headerImage',
        src: displayImage
      }, dojo.byId('matrixLayout'));
      dojo.addClass(dojo.byId('headerImage'), 'portalImage');
      // build organization thumbnail URL
      //create a div for the logo and text
      var logoDisplay = dojo.create('div',{
        id:'logoDisplay'
      },dojo.byId('matrixLayout'));
      
      var thumbnailUrl = "";
      if(settings && settings.thumbnail) {
        thumbnailUrl = esriGeowConfig.restBaseUrl + "accounts/self/resources/" + settings.thumbnail + tokenParam;
  
        //add the thumbnail image to the organization splash screen
        var thumbnailImage = dojo.create("img", { 
          src: thumbnailUrl,
          alt: name
        },dojo.byId('logoDisplay'));    
      }
      //add the company  name to the organization splash screen
      dojo.create("span",{
        innerHTML: name
      },dojo.byId('logoDisplay'));
      
      // shorten the layout for the default organization banner
      dojo.addClass(dojo.byId("matrixLayout"), "matrixLayoutShort");
      dojo.addClass(dojo.byId("details"), "detailsShort");
    }
  });
}

function initPage(result, args) {
  // if the settings wasn't an error, override settings
  if(result && !result.code && !result.message) {
    overrideSettings(result);
  }

  //hide the header and modify the display image if portal is set
  //otherwise create rotator panels
  if(!isOrg){
     document.title = esriGeowConfig.portalName || page.labels.arcgis;
     if(esriGeowConfig.portalHeaderImage){
      var ht = dojo.byId("headerTitle");
      if(ht){
        ht.parentNode.removeChild(ht);
      }
      var displayImage = esriGeowConfig.portalHeaderImage;
      dojo.create("img", {
        id: 'headerImage',
        src: displayImage
      }, dojo.byId('matrixLayout'));
      dojo.addClass(dojo.byId('headerImage'), 'portalImage');
    } else{
        createRotator(esriGeowConfig.rotatorPanels);
    }
  } else {
    document.title = settings.name;
  }
  
  var signInUrl = "";
  if (esriGeowConfig.signin.indexOf("http") === -1 ) {
    //relative to baseUrl
    signInUrl = esriGeowConfig.baseUrl + esriGeowConfig.signin;
    if (esriGeowConfig.useSSL !== false) {
      signInUrl = signInUrl.replace('http:', 'https:');
    }
  } else {
    signInUrl = esriGeowConfig.signin;
  }
  dojo.query(".signUpLink").attr("href", signInUrl);
  
  if (!esriGeowConfig.explorerOnline) {
    //remove explorer section and line that divides map and explorer
    dojo.style(dojo.byId("bottom3Grid"), "display", "none");
    dojo.removeClass(dojo.byId("bottomRow2"), "middle");
    dojo.addClass(dojo.byId("bottomRow2"), "last");
    dojo.addClass(dojo.byId("bottom2Grid"),"grid_6");
    dojo.addClass(dojo.byId("bottom1Grid"),"grid_6");
  } else {
    var explorerOnlineLink = (allSSL ? esriGeowConfig.explorerOnline.replace("http:", "https:") : esriGeowConfig.explorerOnline.replace("https:", "http:"));
    dojo.query(".explorerLink").attr("href", explorerOnlineLink);
    //dojo.query(".explorerLink").attr("href", esriGeowConfig.explorerOnline);
  }

  dojo.style('page-border', 'visibility', 'visible');

  //display featured maps in the gallery if no
  //featured maps exist hide the gallery
  if (esriGeowConfig.homePageFeaturedContent) {
    getGroup(esriGeowConfig.homePageFeaturedContent);
  } else {
    //hide the gallery
    esri.hide(dojo.byId('featuredMaps'));
  }

  // init organization specific settings
  if(isOrg) {
    initOrganization();
  } else {
    initGoogleAPI();
  }
}

function createRotator(panels){
  var panelRotator = new dojox.widget.Rotator({
      transition: "dojox.widget.rotator.crossFade",
      duration: 2500,
      panes: panels
  },dojo.byId("imgRotator"));

  var controller = new dojox.widget.rotator.Controller({
     rotator: panelRotator,
     commands:"#"
  },
  dojo.byId("categories"));
  
  // if only one panel is present, hide the rotator controller
  if(panels && panels.length === 1) {
    dojo.style("categories", "display", "none");
  }
}

function initGoogleAPI() {
  // injects the Google AJAX API and calls initFeed() when loaded
  var script = document.createElement("script");
  script.src = location.protocol + "//www.google.com/jsapi?key=ABQIAAAAmO-VQth3Y6KB46-ZxGr_nBSQ8kgDO2SNhVovJIFNetyD-K9YDhTGHU-P9PYC3aMlIhJ1u_jDcPv_Jw&callback=initFeed";
  script.type = "text/javascript";
  document.getElementsByTagName("head")[0].appendChild(script);
}

function initFeed() {
  // load the feeds functionality
  google.load('feeds', '1', {'callback': LoadDynamicFeed});
}

function LoadDynamicFeed() {
  if(!isOrg){ //don't need feed if its an organization
    var feedURL = "http://feeds.feedburner.com/arcgiscomnewsfeed";
    var feedpointer = new google.feeds.Feed(feedURL);
    feedpointer.setNumEntries(50);
    feedpointer.load(formatFeedCallback);
  }
}

function formatFeedCallback(result) {
  if (!result.error) {
    dojo.forEach(result.feed.entries, function (feed) {
      var feedDate = dojo.date.locale.format(new Date(feed.publishedDate), {
        datePattern: "MMMM dd, yyyy",
        selector: "date"
      });
      var feedContent = "<div><h2 class='ellipsis'><a href='" + feed.link + "'>" + feed.title + "</a></h2></div><div style='padding-bottom:4px;' id='date'>" + feedDate + "</div><div class='feedSnippet'>" + feed.contentSnippet + "</div>";
      feeds.push(feedContent);
    });
    //display the first feed
    currentFeed = 0;

    //dynamically create feed control
    dojo.create('div',{
      id:'feed-control',
      innerHTML:'<div id="feedLeft" style="padding-top:30px">' + 
                  '<img alt="previous" src="images/previous.png" onclick="getPreviousFeed();" />'+
                  '</div><div id="feedRight" style="padding-top:30px">'+
                  '<img alt="next" src="images/next.png" onclick="getNextFeed();"/>'+
                  '</div><div id="feedDisplay">'+
                  '<a href="http://feeds.feedburner.com/arcgiscomnewsfeed" target="_self">'+
                  '<img src="images/rss.jpg" alt="RSS" class="feedRSS" alt="' + page.labels.rssFeed + '" title="' + page.labels.rssFeed + '" />'+
                  '</a><div id="feeds"></div></div>'
    },dojo.byId('topRow2'));
    dojo.byId('feeds').innerHTML = feeds[currentFeed];
  } else {
    return;
  }

}

function getNextFeed() {
  if (currentFeed >= -1 && currentFeed < (feeds.length - 1)) {
    //at first feed increment and display next feed
    currentFeed += 1;
    dojo.byId('feeds').innerHTML = feeds[currentFeed];
  } else {
    currentFeed = -1;
    getNextFeed();
  }

}

function getPreviousFeed() {
  if (currentFeed <= feeds.length && currentFeed > 0) {
    //get the previous page
    currentFeed -= 1;
    dojo.byId('feeds').innerHTML = feeds[currentFeed];
  } else {
    currentFeed = feeds.length;
    getPreviousFeed();
  }
}

function getNextElementSibling(element) {
  if (element.nextElementSibling) {
    return element.nextElementSibling;
  }
  while (element.nextSibling) {
    if (element.nextSibling.nodeType === 1) {
      return element.nextSibling;
    }
    element = element.nextSibling;
  }
}

function getGroup(featuredQuery) {
  var groupQuery = {
    "q": featuredQuery,
    "f": "json"
  };
  
  var token = esri.arcgisonline.sharing.util.getToken();
  if(token) {
    groupQuery.token = token;
  }
  
  esri.request({
    url: esriGeowConfig.restBaseUrl + "community/groups",
    load: getGroupContent,
    callbackParamName: 'callback',
    content: groupQuery,
    error: function () {
      //hide the gallery
      esri.hide(dojo.byId('featuredMaps'));
      console.log("unable to fetch resource info: ", arguments);
    }
  });
}

function getGroupContent(response) {
  if (!response.results[0]) {
    esri.hide(dojo.byId('featuredMaps'));
    return;
  }
  var i = 0;
  var group = response.results[i]; //group.title, id, etc
  // make sure we pick the correct group if the search returns more than one
  while (response.results.length > (i+1)) {
		if (response.query.indexOf('"'+group.title+'"') > -1 ){
			break;
		} else {
			i++;
			group = response.results[i];
		}
	}
  //set the title 
  dojo.byId('galleryTitle').innerHTML = group.title;
  var query = {
    "q": "group:" + group.id + " -(type:\"Code Attachment\")",
    "f": "json",
    "num": esriGeowConfig.homePageFeaturedContentCount,
    "sortField" : "uploaded",
    "sortOrder": "desc"
  };
  
  var token = esri.arcgisonline.sharing.util.getToken();
  if(token) {
    query.token = token;
  }
  esri.request({
    url: esriGeowConfig.restBaseUrl + "search",
    load: createGallery,
    callbackParamName: 'callback',
    content: query,
    error: function () {
      console.log("unable to fetch resource info: ", arguments);
    }
  });
}

function createGallery(response, args) {
  //create the code gallery when the request to fetch the items is finished.
  //specify the div (gallery) where the gallery will display and the number of
  //items per page.
  var items = response.results;
  gallery = new esri.arcgisonline.sharing.dijit.Gallery({
    nodesPerPage: 4,
    showThumbnailInDetails: false,
    showToolTip: false,
    showPageControls: false,
    //set to false to only show number of nodes on the page, use gallery.nextPage() previousPage() to navigate back and forth
    fadeOutOtherNodes: true,
    noResultsMessage: "<p class='esriItemLinks'><span>" + page.labels.noGalleryItems + "</span></p>"
  }, "gallery");

  gallery.attr("items", items);
  if (esriGeowConfig.isRightToLeft) {
    dojo.connect(dojo.byId("prev"), "onclick", gallery, gallery.nextPage);
    dojo.connect(dojo.byId("next"), "onclick", gallery, gallery.prevPage);
    dojo.removeClass("next", "nextButtonEnabled");
    dojo.addClass("next", "nextButtonDisabled");    
    
  }
  else {
    dojo.connect(dojo.byId("prev"), "onclick", gallery, gallery.prevPage);
    dojo.connect(dojo.byId("next"), "onclick", gallery, gallery.nextPage);
    dojo.removeClass("prev", "prevButtonEnabled");
    dojo.addClass("prev", "prevButtonDisabled");    
    
  }


  dojo.connect(gallery, "onPageChange", function (current) {
    if(!esriGeowConfig.isRightToLeft) {
      if (current === 1) {
        //first page disable previous button
        dojo.removeClass("prev", "prevButtonEnabled");
        dojo.addClass("prev", "prevButtonDisabled");
      } else {
        dojo.removeClass("prev", "prevButtonDisabled");
        dojo.addClass("prev", "prevButtonEnabled");
      }
  
      if (current === gallery.pageCount) {
        //last page disable next button
        dojo.removeClass("next", "nextButtonEnabled");
        dojo.addClass("next", "nextButtonDisabled");
      } else {
        dojo.removeClass("next", "nextButtonDisabled");
        dojo.addClass("next", "nextButtonEnabled");
      }
    }
    else {
      if (current === 1) {
        //first page disable previous button
        dojo.removeClass("next", "nextButtonEnabled");
        dojo.addClass("next", "nextButtonDisabled");
      } else {
        dojo.removeClass("next", "nextButtonDisabled");
        dojo.addClass("next", "nextButtonEnabled");
      }
  
      if (current === gallery.pageCount) {
        //last page disable next button
        dojo.removeClass("prev", "prevButtonEnabled");
        dojo.addClass("prev", "prevuttonDisabled");
      } else {
        dojo.removeClass("prev", "prevButtonDisabled");
        dojo.addClass("prev", "prevButtonEnabled");
      }      
    }

  });
  //override link on thumbnail
  dojo.connect(gallery, "onNodeMouseEnter", function (evt, item) {
    var linkInfo = esri.arcgisonline.sharing.util.getGalleryMainLinkInfo(item);
    if(linkInfo.href && linkInfo.href.toLowerCase().indexOf("javascript") > -1 && item.url) {
      // handle case for Web Mapping Application and Mobile Application types
      if(item.type === "Web Mapping Application" || item.type === "Mobile Application") {
        linkInfo.href = item.url;
      }
    }
    var node = evt.currentTarget;
    dojo.query('a', node).forEach(function (element) {
      dojo.attr(element, 'href', linkInfo.href);
    });
  });
}
