var s_account = '';

var Omniture = {};

Omniture.PageLoad = {
  isWrapperPage: false,
  detectWrapper: function() {
    if (window.wrapperTarget !== undefined) {
      Omniture.PageLoad.isWrapperPage = true;
    }
  },
  attachScriptTag: function(fname) {
    var scriptTag = document.createElement('script');
    scriptTag.setAttribute('src', '/includes/' + fname);
    document.body.appendChild(scriptTag);
  },
  customParams: {},
  setCustomParam: function(name, value) {
    this.customParams[name] = value;
  },
  setCustomParams: function(params) {
    this.customParams = params;
  },
  setPageVars: function(pageVars) {
    this.pageVars = pageVars;
  },
  getPageVars: function() {
    return this.pageVars;
  },
  getPageVar: function(key) {
    return this.pageVars[key];
  },
  mkPageLoadCall: function() {
    var newRepeat = Omniture.Util.getNewRepeat();
    var pageVars = this.pageVars; //pageVars should have been set in a preprocess block for this domain/section
    var p = pageVars.pageName.split(':'); //['us', 'channel', 'something']
    if (p.length >= 3) {
      s.prop1 = pageVars.channel + ':' + p[2];
    }
    s.events = pageVars.events;
    s.pageName = pageVars.pageName;
    s.channel = pageVars.channel;
    s.hier1 = pageVars.pageName;
    s.prop10 = newRepeat;
    s.prop34 = pageVars.geo;
    s.eVar12 = pageVars.geo;
    s.eVar28 = newRepeat;
    s.eVar30 = pageVars.pageName;
    for (var key in this.customParams) {
      s[key] = this.customParams[key];
    }
    var s_code = s.t();
    if (s_code) document.write(s_code);
  },
  parseTargetPath: function(path) {
    var targetPath = path.split('?')[0]; 
    var pathArray = targetPath.split('/');
    var out = pathArray.pop();
    return out;
  },
  mkWrapperCall: function() {
    var baseName = this.parseTargetPath(wrapperTarget);
    if (baseName == "r")
      baseName = this.parseTargetPath(wrapperTargetHTML);
    s.eVar6 = baseName;
    s.events = 'event4';
    var s_code = s.tl();
    if (s_code) document.write(s_code);
  },
  callOmniture: function() {
    //called right after 'process' hooks
    if (this.isWrapperPage) {
      this.mkWrapperCall();
    } else {
      this.mkPageLoadCall();
    }
  }
};

Omniture.SharedConfigs = {
  'HomepageV2': {
    'index.html': {
      '_preprocess': function() {
        Omniture.Campaigns.HomepageV2.attachListeners();
      }
    }
  }
};

Omniture.SharedConfigs['WWW'] = {
  '_preprocess': function() {
    Omniture.SiteSections.WWW.preprocess();
  },
  '_postprocess': function() {
    Omniture.SiteSections.WWW.postprocess();
  },
  '*': {
    'forms': {
      '_preprocess': function() {
        Omniture.SiteSections.Forms.setupParameters();
      }
    },
    'company': {
      'events': {
        'techtalk': {
          '_preprocess': Omniture.PageLoad.detectWrapper
        }
      },
      'news': {
        'articles': {
          '_preprocess': Omniture.PageLoad.detectWrapper
        }
      }
    },
    'communities': {
      'tech-ontap': {
        '_preprocess': Omniture.PageLoad.detectWrapper
      },
      '_preprocess': function() {
        Omniture.Listeners.Blogs.preprocess();
      }
    },
    'library': {
      '*': {
        '_preprocess': Omniture.PageLoad.detectWrapper
      },
      '_postprocess': function() {
        Omniture.Listeners.Library.attachListeners();
      }
    },
    'media': {
      '_preprocess': Omniture.PageLoad.detectWrapper
    },
    'error': {
      '_process': function() {
        Omniture.SiteSections.WWWError.process();
      }
    }
  },
  'in': Omniture.SharedConfigs.HomepageV2,
  'uk': Omniture.SharedConfigs.HomepageV2,
  'jp': Omniture.SharedConfigs.HomepageV2,
  'au': Omniture.SharedConfigs.HomepageV2,
  'de': Omniture.SharedConfigs.HomepageV2,
  'us': {
    'index.html': {
      '_preprocess': function() {
        Omniture.Campaigns.HomepageV2.attachListeners();
      }
    },
    'campaigns': {
      'brand': {
        'and': {
          '_preprocess': function() {
            Omniture.Campaigns.And.attachListeners();
          }
        }
      }
    },
    'company': {
      'leadership': {
        'storage-efficiency': {
          '_preprocess': function() {
            Omniture.Campaigns.SE.attachListeners();
          }
        }
      }
    }
  }
};

Omniture.Config = {
  'dev.www.netapp.com': Omniture.SharedConfigs.WWW,
  'stage.www.netapp.com': Omniture.SharedConfigs.WWW,
  'www.netapp.com': Omniture.SharedConfigs.WWW,
  'investors.netapp.com': {
    '_preprocess': function() {
      Omniture.SiteSections.Investors.preprocess();
    }
  },
  'seek.netapp.com': {
    '_preprocess': function() {
      Omniture.SiteSections.Search.preprocess();
    },
    '_process': function() {
      Omniture.SiteSections.Search.process();
    }
  },
  'communities.netapp.com': {
    '_preprocess': function() {
      Omniture.SiteSections.Communities.preprocess();
    }
  },
  'careers.netapp.com': {
    '_preprocess': function() {
      Omniture.SiteSections.Careers.preprocess();
    }
  },
  'livechat.boldchat.com': {
    '_preprocess': function() {
      Omniture.SiteSections.Chat.preprocess();
    }
  }
};

Omniture.System = {
  findMatches: function(c, depth) {
    var out = [];
    if (depth === undefined) depth = 0;
    var currPathNode = this.pathArray[depth];
    var wildcardMatch = c['*'];
    var exactMatch = c[currPathNode];
    var matchList = [wildcardMatch, exactMatch];
    for (var i = 0; i < matchList.length; i++) {
      var match = matchList[i];
      if (!match) continue;
      out[out.length] = match;
      var matches = this.findMatches(match, depth+1);
      out = out.concat(matches);
    }
    return out;
  },
  getConfigNodes: function() {
    var domain = window.location.hostname;
    var path = window.location.pathname;
    var partialPathArray = path.split('/');
    var len = partialPathArray.length;
    if (partialPathArray[len-1] == '') {
      partialPathArray[len-1] = 'index.html';
    }
    len = partialPathArray.length;
    var compactArray = [];
    for (var i = 0; i < len; i++) {
      var cell = partialPathArray[i];
      if (cell != undefined && cell.length > 0)
        compactArray.push(cell);
    }
    this.pathArray = [domain].concat(compactArray);
    return this.findMatches(Omniture.Config);
  },
  callHooks: function(hookName) {
    for (var i = 0; i < this.matches.length; i++) {
      var match = this.matches[i];
      var fcn = match[hookName];
      if (fcn) fcn();
    }
  },
  preProcess: function() {
    this.matches = this.getConfigNodes();
    this.callHooks('_preprocess');
  },
  process: function() {
    this.callHooks('_process');
    Omniture.PageLoad.callOmniture();
  },
  postProcess: function() {
    this.callHooks('_postprocess');
  }
};

Omniture.Util = {
  isLive: function() {
    var domain = window.location.hostname;
    if ((domain == "dev.www.netapp.com") || (domain == "stage.www.netapp.com")) {
      return false;
    } else {
      return true;
    }
  },
  getGeo: function() {
    return window.location.pathname.substring(1, 3);
  },
  getPageName: function() {
    return window.location.pathname.substring(1).split('/').join(':');
  },
  getNormalizedPageName: function() {
    var path = window.location.pathname;
    var pathArray = path.split('/');
    var last = pathArray.pop(); 
    if (last == '') {
      pathArray.push('index');
    } else {
      var base = last.split('.')[0];
      pathArray.push(base);
    }
    var out = pathArray.join(':');
    return out.substring(1); //remove the leading :
  },
  getNewRepeat: function() {
    return s.getNewRepeat();
  },
  setCookie: function(key, value, exp) {
    var cookieStr = escape(key) + "=" + escape(value) + (exp ? "; exp=" + exp.toGMTString() : "") + "; path=/";
    document.cookie = cookieStr;
  },
  getCookie: function(key) {
    if (document.cookie.length == 0) return;
    var start = document.cookie.indexOf(key + "=");
    if (start != -1) {
      var valStart = start + key.length + 1;
      var end = document.cookie.indexOf(";", valStart);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(valStart, end));
    }
  },
  setDebug: function(val) {
    this.debugOn = val;
  },
  isDebugOn: function() {
    return this.debugOn;
  },
  log: function(thing) {
    if (this.isDebugOn() && window.console) console.log(thing);
  },
  strip: function(s) {
    var out = s;
    if (out.stripTags) { // sometimes Prototype isn't available
      out = out.replace(/</g, ' <');
      out = out.stripTags();
    }
    out = out.replace(/\s+/g, ' ');
    out = out.replace(/^\s+|\s+$/g, '');
    return out;
  },
  getQueryParams: function() {
    var qs = window.location.search.substring(1); //remove the leading '?'
    var pairs = qs.split('&');
    var out = {};
    for (var i = 0; i < pairs.length; i++) {
      var nvArray = pairs[i].split('=');
      var name = nvArray[0];
      var value = nvArray[1];
      out[name] = value; //no need to handle multiple values for now
    }
    return out;
  }
};

Omniture.Call = {
  customLink: function(element, params, type) {
    Omniture.Util.log(element);
    Omniture.Util.log(params);
    if (type === undefined) type = 'o';
    var keys = "";
    for (key in params) {
      if (keys.length > 0) keys += ',';
      keys += key;
      s[key] = Omniture.Util.strip(params[key]);
    }
    s.linkTrackVars = keys;
    s.linkTrackEvents = params.events;
    s.tl(element, type);
  }
};

Omniture.Listeners = {
  Library: {
    attachListeners: function() {
      var searchLinkNode = $$('.searchButtonSpanLib a').first();
      searchLinkNode.observe('click', this.mkSearchCallback());
      var formNode = $('searchForm');
      formNode.observe('submit', this.mkSearchCallback());
    },
    mkSearchCallback: function() {
      return function() {
        var keyword = 'library: ' + $F('keywordSearchBox');
        var params = {
          prop42: keyword
        };
        Omniture.Call.customLink({href:document.location.pathname}, params);
      };
    }
  },
  Blogs: {
    preprocess: function() {
      this.attachListeners();
    },
    attachListeners: function() {
      var formNode = $('blogPostSearchForm');
      formNode.observe('submit', this.mkSearchCallback());
      var linkNode = $$('.searchButtonBlogs a').first();
      linkNode.observe('click', this.mkSearchCallback());
    },
    mkSearchCallback: function() {
      return function() {
        var keyword = 'blogs: ' + $F('keywordSearchBox');
        var params = {
          prop42: keyword
        };
        Omniture.Call.customLink({href:document.location.pathname}, params);
      };
    }
  },
  Widgets: {
    attachListeners: function() {
      //this is called in a process callback, so we won't get here if prototype is not available
      var letsGetStartedElements = $$('.letsGetStartedWithBottomBorder');
      var hasLetsGetStarted = letsGetStartedElements.length;
      if (!hasLetsGetStarted) return;
      var emailUsLink = $$('.emailUs a').first();
      emailUsLink.observe('click', this.mkWidgetCallback(emailUsLink.innerHTML));
      var self = this;
      var liveChatImg = $('liveChatImage');
      if (liveChatImg) {
        liveChatImg.observe('click', self.mkWidgetCallback("Chat Initiated"));
      }
      var sideBarLinks = $$('#sideBarLink a'); //Print, Send to Colleague
      sideBarLinks.each(function(linkNode) {
        linkNode.observe('click', self.mkWidgetCallback(linkNode.innerHTML));
      });
      var widgetIcons = $$('#tagItIcons img');
      widgetIcons.each(function(iconNode) {
        var widgetName = iconNode.src.split('/').pop().split('.')[0];
        iconNode.observe('click', self.mkWidgetCallback(widgetName));
      });
    },
    mkWidgetCallback: function(linkText) {
      return function() {
        var params = {
          prop43: linkText,
          eVar43: linkText,
          events: 'event5'
        };
        Omniture.Call.customLink({href:'/' + linkText}, params);
      };
    }
  },
  Spotlight: {
    attachListeners: function() {
      var spotlightContainerNode = $('topBlockRightSpotlight');
      if (!spotlightContainerNode) return;
      var spotlightLinks = $$('#topBlockRightSpotlight a');
      var self = this;
      spotlightLinks.each(function(linkNode) {
        linkNode.observe('click', self.mkCallback(linkNode));
      });
    },
    mkCallback: function(linkNode) {
      return function() {
        var linkText = linkNode.innerHTML;
        var pageName = Omniture.PageLoad.getPageVar('pageName');
        var params = {
          prop8: pageName + '|' + linkText
        };
        Omniture.Call.customLink({href: '/'}, params);
      };
    }
  }
};

Omniture.SiteSections = {
  Chat: {
    preprocess: function() {
      s_account = 'networkapplnetappcom-us,networkapplglobalexternal';
      var pageVars = {
        pageName: 'us:contact-us:chat:chat',
        channel: 'contact-us',
        geo: 'us',
        events: 'event29'
      };
      Omniture.PageLoad.setPageVars(pageVars);
    }
  },
  Forms: {
    setupParameters: function() {
      var baseName = Omniture.System.pathArray[Omniture.System.pathArray.length-1];
      if (baseName.indexOf("sales-contact") >= 0) {
        if (document.location.search == "?s=y")
          this.setThankYouParams();
        else
          this.setSalesContactParams();
      }
    },
    setSalesContactParams: function() {
      Omniture.PageLoad.setCustomParam('events', 'event29,event78');
      Omniture.PageLoad.setCustomParam('eVar47', 'Sales Inquiry');
    },
    setThankYouParams: function() {
      Omniture.PageLoad.setCustomParam('events', 'event29,event79');
      Omniture.PageLoad.setCustomParam('eVar47', 'Sales Inquiry');
      var geo = Omniture.Util.getGeo();
      Omniture.PageLoad.setCustomParam('pageName', geo + ':thankyou-sales-contact');
    }
  },
  Investors: {
    preprocess: function() {
      s_account = 'networkapplnetappcom-us,networkapplglobalexternal';
      Omniture.PageLoad.setPageVars({
        pageName: 'us:investors:' + this.getBaseName(),
        channel: 'investors',
        events: 'event29',
        geo: 'us'
      });
    },
    getBaseName: function() {
      return window.location.pathname.split('/').pop().split('.')[0] || 'index';
    }
  },
  Communities: {
    preprocess: function() {
      s_account = 'networkapplnetappcom-us,networkapplglobalexternal';
      var pageName = 'us:communities:' + Omniture.Util.getNormalizedPageName();
      var pageVars = {
        pageName: pageName,
        channel: 'communities',
        geo: 'us',
        events: 'event29'
      };
      Omniture.PageLoad.setPageVars(pageVars);
    }
  },
  Careers: {
    preprocess: function() {
      s_account = 'networkapplnetappcom-us,networkapplglobalexternal';
      var path = window.location.pathname;
      var pageName = 'us:careers:' + Omniture.Util.getNormalizedPageName();
      var pageVars = {
        channel: 'careers',
        pageName: pageName,
        geo: 'us',
        events: 'event29'
      };
      Omniture.PageLoad.setPageVars(pageVars);
    }
  },
  Search: {
    preprocess: function() {
      var qParams = Omniture.Util.getQueryParams();
      Omniture.SiteSections.Search.queryParams = qParams;
      var geo = qParams['cc'];
      s_account = 'networkapplnetappcom-' + geo + ',networkapplglobalexternal';
    },
    process: function() {
      var qParams = Omniture.SiteSections.Search.queryParams;
      var geo = qParams['cc'];
      var pageName = geo + ':search';
      var pageVars = {
        pageName: pageName,
        channel: 'search',
        geo: geo
      };
      Omniture.PageLoad.setPageVars(pageVars);
      var startIndex = qParams['st'];
      if (!startIndex) {
        //we get to this block only if this is the first page after a search is performed
        //we don't want to set these variables otherwise
        var searchString = qParams['q'];
        var customParams = {
          events: 'event8',
          prop5: searchString,
          eVar1: searchString
        };
        Omniture.PageLoad.setCustomParams(customParams);
      }
    }
  },
  WWW: {
    preprocess: function() {
      this.setupReportSuite();
      this.calculatePageVars();
    },
    postprocess: function() {
      Omniture.Listeners.Widgets.attachListeners();
      Omniture.Listeners.Spotlight.attachListeners();
    },
    setupReportSuite: function() {
      var geo = Omniture.Util.getGeo();
      var isLive = Omniture.Util.isLive();
      var suffix = isLive ? '' : '-dev';
      s_account = 'networkapplnetappcom-' + geo + suffix + ',networkapplglobalexternal' + suffix;
    },
    calculatePageVars: function() {
      var path = document.location.pathname;
      var pathArray = path.split('/');
      var len = pathArray.length;
      var baseName = pathArray[len-1];
      var geo = pathArray[1];
      var channel = pathArray[2] || 'home';
      var subSection = pathArray.length >= 5 ? pathArray[3] : '';
      var pageName = pathArray.slice(1, len-1).join(':') + ':';
      if (baseName && baseName.length > 0) {
        pageName += baseName.split('.')[0];
      } else if (len == 3) {
        pageName += 'index';
      } else {
        pageName += pathArray[len-2];
      }
      var pageVars = {
        'baseName': baseName,
        'channel': channel,
        'pageName': pageName,
        'geo': geo,
        'events': 'event29'
      };
      Omniture.PageLoad.setPageVars(pageVars);
    }
  },
  WWWError: {
    process: function() {
      var errorURL = s.getQueryParam('errorURL'); 
      Omniture.PageLoad.customParams = {
        pageType: 'errorPage',
        pageName: '404:' + errorURL,
        prop16: errorURL
      };
    }
  }
};

Omniture.Campaigns = {
  And: {
    attachListeners: function() {
      var self = this;
      s_account = 'networkapplnetappcom-us'; //per request, set this to a us-only report suite
      var leftNode = $$('.andLeft h3 a').first();
      leftNode.observe('click', this.mkCallback(leftNode, 'event18'));
      var rightNode = $$('.andRight h3 a').first();
      rightNode.observe('click', this.mkCallback(rightNode, 'event19'));
      $$('.regularList a').each(function(linkNode) {
        linkNode.observe('click', self.mkCallback(linkNode, 'event20'));
      });
    },
    mkCallback: function(linkNode, eventId) {
      var self = this;
      return function(e) {
        var params = {
          'events': eventId,
          'eVar38': linkNode.innerHTML,
          'eVar39': self.getType()
        };
        Omniture.Call.customLink(linkNode, params);
      };
    },
    getType: function() {
      var baseName = Omniture.PageLoad.pageVars.baseName;
      var out = baseName.split('.')[0];
      return out;
    }
  },
  SE: {
    attachListeners: function() {
      var self = this;
      $$('#productList a').each(function(linkNode) {
        if (linkNode.innerHTML != "Watch Now") return;
        linkNode.observe('click', self.mkCallback());
      });
    },
    mkCallback: function() {
      return function(event) {
        var linkNode = event.findElement();
        var hrefArray = linkNode.href.split('/');
        var videoName = hrefArray[hrefArray.length-1];
        videoName = videoName.substring(0, videoName.length-2);
        var params = {
          'events': 'event33',
          'eVar2': 'se|' + videoName
        };
        Omniture.Call.customLink(linkNode, params);
      };
    }
  },
  HomepageV2: {
    numbers: {
      'one': 1,
      'two': 2,
      'three': 3,
      'four': 4
    },
    attachListeners: function() {
      var self = this;
      var i = 1;
      $$('#stories a').each(function(linkNode) {
        linkNode.observe('click', self.mkFeaturedCallback(linkNode, i++));
      });
      $('news').observe('click', function(event) {
        var targetNode = event.findElement();
        if (targetNode.tagName != "A") return;
        if (targetNode.parentNode.tagName == "TD") return;
        var linkText = targetNode.innerHTML;
        var tabName = $('news').className.split('-')[1];
        var liNode = targetNode.up('li');
        var ulNode = liNode.parentNode;
        var i = 0;
        var linkPosition = 0;
        ulNode.childElements().each(function(childNode) {
          i++;
          if (childNode == liNode) linkPosition = i;
        });
        var pageNum = self.getPageNum();
        var pagePosition = pageNum + '.' + linkPosition;
        var params = {
          prop20: 'Hotspot: ' + tabName,
          prop25: 'Hotspot: ' + linkText,
          prop35: pagePosition
        };
        Omniture.Call.customLink(targetNode, params);
      });
      $('solutions').observe('click', function(event) {
        var targetNode = event.findElement();
        if (targetNode.tagName != "A") return;
        if (targetNode.parentNode.tagName == "TD") return; //bail out if it's a tab click
        var tabName = self.getTabName();
        var linkName = '';
        if (targetNode.hasClassName('button')) {
          var containerDiv = targetNode.up('div');
          var firstChild = containerDiv.firstDescendant();
          linkName = firstChild.innerHTML;
        } else {
          linkName = targetNode.innerHTML;
        }
        var params = {
          'prop39': tabName,
          'prop41': linkName
        };
        Omniture.Call.customLink(targetNode, params);
      });
    },
    getPageNum: function() {
      var n = 0;
      var out = 1; //default to page 1 if there are no page icons
      $$('#newsPages img').each(function(imgNode) {
        if (imgNode.src.indexOf("-on-") > 0) out = n;
        n++;
      });
      return out;
    },
    mkFeaturedCallback: function(linkNode, linkPosition) {
      return function(e) {
        var containerNode = linkNode.up('div');
        var title = containerNode.down('h3 a').innerHTML;
        var params = {
          eVar48: title
        };
        Omniture.Call.customLink(linkNode, params);
      };
    },
    getTabName: function() {
      var className = $('solutions').className;
      var tabNum = className.split('-')[1];
      var n = this.numbers[tabNum];
      var selector = "#sol-tab-" + n + " a";
      var matches = $$(selector);
      var tab = matches.first();
      return tab.innerHTML;
    }
  }
};

Omniture.System.preProcess();
if (Event && Event.observe) {
  Event.observe(window, 'load', function() {
    Omniture.System.postProcess();
  });
}
