var telepix_listtool_momlogic;
(function($) {
  $.fn.swap = function(b) { 
      if(jQuery(b).length == 0) { return false; }
      
      b = jQuery(b)[0]; 
      var a = this[0]; 
      var t = a.parentNode.insertBefore(document.createTextNode(''), a); 

      b.parentNode.insertBefore(a, b); 
      t.parentNode.insertBefore(b, t); 
      t.parentNode.removeChild(t); 
      return this; 
  };
  
  telepix_listtool_momlogic = function(container_id, title, ad_refresh, ad_selector, interstitials, interstitial_interval, 
                                    jumps, ad_generator_url, offsite_omniture_pagename, onsite_omniture_pagename, 
                                    offsite_omniture_variable, onsite_omniture_variable) {
    var t = this;
    
    t.PreloadWindowSizeAhead = 3;
    t.PreloadWindowSizeBehind = 1;
    t.preloadedSections = [];
    
    t.title = title;
    t.container_id = container_id;
    t.ad_refresh = ad_refresh;
    t.ad_selector = ad_selector;
    t.interstitials = interstitials;
    t.interstitial_interval = interstitial_interval;
    t.jumps = jumps;
    t.ad_generator_url = ad_generator_url;
    t.offsite_omniture_pagename = offsite_omniture_pagename;
    t.onsite_omniture_pagename = onsite_omniture_pagename;
    t.offsite_omniture_variable = offsite_omniture_variable;
    t.onsite_omniture_variable = onsite_omniture_variable;
    t.omniture_variable_name = null;
    
    t.blocks = ['lt-sections', 'lt-jumps', 'lt-interstitials'];
    t.currentBlock = 'lt-sections';
    t.cid = '#' + t.container_id;
    t.root = $(t.cid).parent().parent();
    t.preloadContainer = $(t.cid).siblings('.preload');
    t.index = 0;
    t.last_offset = 0;
    t.sectionCSSElem = null;
    t.array = [];
    t.sections_shown = 0;
    t.interstitials_shown = 0;
    t.embedding_sites = ['www.momlogic.com', 'momlogic.com', 'photos.momlogic.com'];

    t.log = function() {
      
    };

    /* PUBLIC API */
    t.loadInPlace = function(options) {
      var cb_name = options.article + '_' + (options.stencil || '') + '_' + 'listtool_callback';
  
      eval("window." + cb_name + " = function(data) {       \
          $(t.cid).parent().parent().after(data);           \
          setTimeout(function() {                           \
            $(t.cid).parent().parent().remove();            \
          }, 1);                                            \
          delete window." + cb_name + ";                    \
        };                                                  \
      ");

      //### what should n= be?
      $.getJSON(t.article_json_url(options.article, options.stencil) + '?v=2.2&callback=' + cb_name + '&ignored_variable=?');
    };

    t.version = function() {
      return 2.2;
    };
    
    t.load = function() {
      t.omniture_variable_name = (t.onsite() ? onsite_omniture_variable : offsite_omniture_variable);
      t.showSection(t.getIndexFromAnchor(), false);
      
      //CRZ - jquery's toggle is broke-ed
      t.onsite() ? $(t.cid + ' span.lt-onsite').css('display', 'inline') : $(t.cid + ' span.lt-offsite').css('display', 'inline');
      $(t.cid).css('display', 'block');
    };

    t.addSection = function(id, src, mn, body, credit, heading, alt_tag, next_heading, byline, section_permaslug, media_type, css) {
      t.array.push([id, src, mn, body, credit, heading, alt_tag, next_heading, byline, section_permaslug, media_type, css]);
    };
    
    t.next = function() { t.navigate(1); };
    t.prev = function() { t.navigate(-1); };
    /* END PUBLIC API */    

    t.preloadSectionWindow = function(options) {
      options = options || {};
      options = $.extend(
        { windowSizeAhead: options.windowSize || t.PreloadWindowSizeAhead,
          windowSizeBehind: options.windowSize || t.PreloadWindowSizeBehind,
          index: t.index 
        }, options);
      
      if(document.images) {
        t.preloadSection(t.array[options.index]); //load this first.
        
        var i;
        for(i = options.index - options.windowSizeBehind; i < options.index + options.windowSizeAhead + 1; i++) {
          var idx = (i + t.array.length) % t.array.length;
          t.preloadSection(t.array[idx]);
        }
      }
    };
    
    t.isSectionPreloaded = function(sect) {
      return ($.inArray(sect, t.preloadedSections) != -1);
    };
    
    t.preloadSection = function(sect, reload) {
      if(!t.isSectionPreloaded(sect) || reload == true) {
        if(!t.isSectionPreloaded(sect)) {
          t.preloadedSections.push(sect);
        }
        else if(reload == true) {
          t.preloadContainer.find('img[src="' + sect[1] + '"]').remove();
          
        }

        if(sect[10] == 'image') {
                    $('<img/>').attr({
            src: sect[1],
            'class': t.container_id + "-section-image",
            alt: sect[6]
          }).appendTo(t.preloadContainer);
        }
        
        
      }
    }

    t.article_json_url = function(article_id, stencil_id) {
      var url = 'http://' + 'listtool.momlogic.com' + '/sites/' + 'momlogic' + '/lists/' + article_id;
      if(stencil_id) {
        url += '/stencils/' + stencil_id;
      } 
      
      return (url + '.json');
    };

    t.navigate = function(offset) {
      var index_to = t.indexCycle(offset);
      
      if(t.inBlock('lt-interstitials')) {
        if (t.jumpsNext(offset)) { t.showJumps(); }
        else { t.showSection(index_to); }
      }
      else if(t.inBlock('lt-jumps')) {
        if (offset == -t.last_offset) { //if we go back to the page we were on.
          index_to = t.index;
        }
        t.showSection(index_to);
      }
      else {
        if (t.interstitialsNext(offset)) { t.showInterstitial(); }
        else if (t.jumpsNext(offset)) { t.showJumps(); }
        else { t.showSection(index_to); }
      }

      if(t.onsite()) {
        document.location.href = document.location.href.split("#")[0] + '#' + t.array[t.index][9];
      }

      t.last_offset = offset;
    };
    
    t.tog_elem_for = function(prop) { return $(t.cid +' span.' + prop); };
    t.sect_elem_for = function(prop) { return $(t.cid +' .'+ t.container_id + '-section-' + prop); };
    t.elem_for = function(prop) { return $(t.cid +' .'+ t.container_id + '-' + prop); };
    t.cycle = function(num, offset, ceil) { return (((num + offset) % ceil) + ceil) % ceil; };
    t.indexCycle = function(offset) { return t.cycle(t.index, offset, t.array.length); };
      
    t.interstitialsNext = function(offset) {
       var index_to = t.indexCycle(offset);
      
       if (t.interstitials) {
         if ((t.sections_shown - (t.interstitials_shown * t.interstitial_interval)) >= t.interstitial_interval) {
           return true;
         }
         else if (t.index == (t.array.length-1) && (t.interstitials_shown == 0)) {
           return true;
         }
       }       
       return false;
    };
    
    t.jumpsNext = function(offset) {
      if (t.jumps && !t.inBlock('lt-jumps')) {
        if ( (t.index == t.array.length-1) && offset > 0) { return true; }
        else if (t.index == 0 && offset < 0 ) { return true; }
      }
      
      return false;
    };

    t.showInterstitial = function() {
      t.togBlock('lt-interstitials');
      t.refreshInterstitialAd();
      t.refreshAdsAndOmniture();
      t.interstitials_shown++;
    };

    t.showSection = function(index, refresh) {
      refresh = (arguments[1] != null) ? arguments[1] : true;

      t.populate(index);
      t.togBlock('lt-sections');
      
      if (refresh) {
        t.refreshAdsAndOmniture();
      }
      
      t.sections_shown++;
    };
    
    t.showJumps = function() {
      t.togBlock('lt-jumps');
      t.refreshAdsAndOmniture();
      t.populateNextLink();
    };

    t.togBlock = function(block) {
      $.each(t.blocks, function(i, e) {
        (t.blocks[i] == block) ? t.tog_elem_for(t.blocks[i]).show() : t.tog_elem_for(t.blocks[i]).hide();
      });
      
      t.currentBlock = block;
    };
    t.inBlock = function(block) { return t.currentBlock == block; };

    t.getIndexFromAnchor = function() {
      if(!t.onsite()) {
        return 0;
      }
      
      var anchor = document.location.href.split('#')[1];
      var index_to = 0;
 
      $.each(t.array, function(i, val) {
        if (val[9] == anchor) {
          index_to = i; return false;
        }
      });

      return index_to;
    };
  
    t.refreshInterstitialAd = function() {
      t.elem_for('interstitial-ad').attr('src', t.ad_generator_url);
    };

    t.refreshAdsAndOmniture = function() {
      if(t.onsite()) {
        t.refreshSelectedAds();
      }
      t.refreshOmniture();
    };

            t.section_as_object = function() {
      switch(t.currentBlock) {
        case 'lt-sections':
          var s = t.array[t.index];
          return {
            heading: s[5],
            body: s[3],
            count: t.array.length,
            byline: s[8],
            'photo-credit': s[4],
            index: t.index
          };
        case 'lt-jumps':
          return {
            heading: '(jump page)',
            body: '',
            count: t.array.length,
            byline: '',
            'photo-credit': '',
            index: '(jump page)'
          };
        case 'lt-interstitials':
          return {
            heading: '(interstitial ad)',
            body: '',
            count: t.array.length,
            byline: '',
            'photo-credit': '',
            index: '(interstitial ad)'
          };
      }
    };

        t.refreshOmniture = function() {
      try {
        if(typeof t.omniture_variable == "undefined") {
          t.omniture_variable = eval(t.omniture_variable_name);
        }
        if(typeof t.omniture_variable == "object" && typeof t.omniture_variable.t == "function") {      
          if(!t.onsite()) {
            t.omniture_variable.pageName = t.parse(t.offsite_omniture_pagename, {section:t.section_as_object()});
          }
          else {
            if (t.onsite_omniture_pagename != "") {
              t.omniture_variable.pageName = t.parse(t.onsite_omniture_pagename, {section:t.section_as_object()});
            }
          }
          s_code = t.omniture_variable.t();
        }
      }
      catch(e) {
        //t.log("cannot find omniture variable " + t.omniture_variable_name + " to refresh it");
      }
    };

    t.refreshSelectedAds = function() {
      if (t.ad_refresh && t.onsite()) {
        var th = t;
        $(th.ad_selector).each(function() {
          if(th.is_onScreen(this))
            $(this).attr('src', $(this).attr('src'));
        });
      }
    };
    
    t.onsite = function() { 
      var onsite = false;

      $.each(t.embedding_sites, function() {
        if (document.location.host == this) {
          onsite = true;
      }});
      
      return onsite;
    };

    t.populate = function(index_to) {
      t.index = index_to;
      var sect = t.array[index_to];
  
      t.preloadSectionWindow({index: index_to});
  
      var image = t.sect_elem_for('image');
      if(image.size() > 0) {
        switch(sect[10]) { /* media_type */
          case 'image':
            if(image) {
              t.swapPreloadedImageIn(image, sect);
              image.attr('alt', sect[6]);
              image.css('display', 'block');
            }
            break;
          default:
            //image.attr('src', ''); //### this may cause 'aborted' loads in firefox
            image.attr('alt', '');
            image.css('display', 'none');
            break;
        }
      }
      t.sect_elem_for('heading').html(sect[5]);

      if(t.sect_elem_for('body').size() > 0) {
        
          t.sect_elem_for('body').html(sect[3]);
        
      }

      t.loadSectionCSS(sect[11]);

      t.sect_elem_for('photo-credit').html(sect[4]);    
      t.sect_elem_for('byline').html(sect[8]);
      t.sect_elem_for('index').html(index_to+1);

      t.populateNextLink();
    };

    
    t.loadSectionCSS = function(css) {
      if(css == '' && t.sectionCSSElem == null) { return; } //dont create if we dont need to

      var tag = $('<style type="text/css" title="lt-inline-' + t.container_id + '">' + css + '</style>');

      if(t.sectionCSSElem == null) { 
        t.sectionCSSElem = tag.appendTo($('head:first'));
      } else {
        t.sectionCSSElem.replaceWith(tag);
        t.sectionCSSElem = tag;
      }
    };
    
    t.swapPreloadedBodyIn = function(to, sect) {
      var what = t.preloadContainer.find('> span.' + t.container_id + "-" + sect[9]);
      
      $(to).swap(what);
    };

    //Be super robust here as other js code likes to interfere with our DOM.
    t.swapPreloadedImageIn = function(to, sect) {
      var url = sect[1];
      var what = t.findPreloadedImageFor(url);
      
      if (what.length == 0) { //only try this once to avoid infinite loop
        t.preloadSection(sect, true);
        what = t.findPreloadedImageFor(url);
        if(what.length == 0) { //if all else fails, just change the src= attr
          return $(to).attr('src', url);
        }
      }

      $(to).swap(what);
    };
    
    t.findPreloadedImageFor = function(url) {
      return t.preloadContainer.find('> img[src="' + url + '"]');
    };
    
    t.populateNextLink = function() {
      t.sect_elem_for('next-text-link-prefix').html( (!t.jumpsNext(1) && t.index == t.array.length - 1) ? "Back to Beginning" : "Next" );
      t.sect_elem_for('next-text-link-title').html( (t.jumpsNext(1)) ? "Other Lists" : t.array[t.index][7] );
    };

	  //move the window to the top of the article if they've scrolled down below the top and pressed next/prev
    t.reposition = function() {
      if (t.onsite() && window.pageYOffset > $(t.cid)[0].offsetTop) {
        document.location.href = document.location.href.split("#")[0] + '#top-' + t.container_id;
      }
    };
  
    t.is_onScreen = function(elem) {
      var elemXOffset = 0, elemYOffset = 0;
      var pageXOffset = 0, pageYOffset = 0;
      var pageOffset = 0;
      var e = elem;
      var dde = document.documentElement;
      var b = document.body; var w = window;
      var windowWidth = 0, windowHeight = 0;

      do {
        elemXOffset += e.offsetLeft;
        elemYOffset += e.offsetTop;
      }
      while((e = e.offsetParent) && e != null);

      //http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
      if( typeof( w.innerWidth ) == 'number' ) { //Non-IE
        windowWidth = w.innerWidth;
        windowHeight = w.innerHeight;
      } else if( dde && ( dde.clientWidth || dde.clientHeight ) ) {//IE 6+ in 'standards compliant mode'
        windowWidth = dde.clientWidth;
        windowHeight = dde.clientHeight;
      } else if( b && ( b.clientWidth || b.clientHeight ) ) { //IE 4 compatible
        windowWidth = b.clientWidth;
        windowHeight = b.clientHeight;
      }
      if( typeof( w.pageYOffset ) == 'number' ) {//Netscape compliant
        pageYOffset = w.pageYOffset;
        pageXOffset = w.pageXOffset;
      } else if( b && ( b.scrollLeft || b.scrollTop ) ) { //DOM compliant
        pageOffset = b.scrollTop;
        pageXOffset = b.scrollLeft;
      } else if( dde && ( dde.scrollLeft || dde.scrollTop ) ) { //IE6 standards compliant mode
        pageYOffset = dde.scrollTop;
        pageXOffset = dde.scrollLeft;
      }

      if (((pageYOffset < elemYOffset && (pageYOffset + windowHeight) > elemYOffset) ||
           (pageYOffset < (elemYOffset + elem.offsetHeight) && (pageYOffset + windowHeight) > (elemYOffset + elem.offsetHeight))) && 
          ((pageXOffset < elemXOffset && (pageXOffset + windowWidth) > elemXOffset) ||
           (pageXOffset < (elemXOffset + elem.offsetWidth) && (pageXOffset + windowWidth) > (elemXOffset + elem.offsetWidth)))) {
        return true;
      }
      else { 
        return false;
      }
    };
    
    t.parse = function (str, context) {
      return str.replace(/\{([^{}]*)\}/g,
        function (a, b) {
          var o = context;
          $.each(b.split('.'), function(i, item) {
            if(!o[item]) { o = false; return; }
            o = o[item];
          });
          return typeof o === 'string' || typeof o === 'number' ? o : a;
        }
      );
    };
  };
})(jQuery);
