var telepix_listtool_momlogic;
(function($) {
  telepix_listtool_momlogic = function(container_id, title, ad_refresh, ad_selector, interstitials, interstitial_interval, 
                                    jumps, adzone, offsite_omniture_pagename, onsite_omniture_pagename, 
                                    offsite_omniture_variable, onsite_omniture_variable) {
    var t = this;
    
    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.adzone = adzone;
    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.index = 0;
    t.last_offset = 0;
    t.array = Array();
    t.sections_shown = 0;
    t.interstitials_shown = 0;
    t.embedding_sites = ['www.momlogic.com', 'momlogic.com', 'photos.momlogic.com'];
    t.ad_url = 'http://apps.telepixtv.com/ads/300x250interstitial.php?site=momlogic&' + 'adsize=300x250&tile=1&adzone=' + t.adzone;

    t.log = function(msg) {
      if ( (typeof console != 'undefined') && (typeof console.log != 'undefined') )
        console.log(msg);
    }

    /* PUBLIC API */
    t.version = function() {
      return 2.0;
    }
    
    t.load = function() {
      t.omniture_variable_name = (t.onsite() ? onsite_omniture_variable : offsite_omniture_variable)
      t.onsite() ? t.showSection(t.getIndexByAnchor(), false) : t.showSection(0);
      
      //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) {
      t.array.push([id, src, mn, body, credit, heading, alt_tag, next_heading, byline, section_permaslug]);
    };
    
    t.next = function() { t.navigate(1); };
    t.prev = function() { t.navigate(-1); };
    /* END PUBLIC API */    

    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 */) {
      var refresh = (arguments[1]) ? 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) {
      for(i in t.blocks) {
        (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.getIndexByAnchor = function() {
      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_url);
    };

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

    //###CRZ - store section arrays as hashes instead from the beginning
    //###CRZ - these names match Stencil#dom_placeholders array, not DRY
    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
          };
          break;
        case 'lt-jumps':
          return {
            heading: '(jump page)',
            body: '',
            count: t.array.length,
            byline: '',
            'photo-credit': '',
            index: '(jump page)'
          };
          break;
        case 'lt-interstitials':
          return {
            heading: '(interstitial ad)',
            body: '',
            count: t.array.length,
            byline: '',
            'photo-credit': '',
            index: '(interstitial ad)'
          };
          break;
      }
    }

    t.refreshOmniture = function() {
      //CRZ - seems to be a lag when the variable gets defined, so look for t.omniture_variable_name on every refresh until found
      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.sect_elem_for('image').attr('src', sect[1]);
      t.sect_elem_for('image').attr('alt', sect[6]);
      t.sect_elem_for('heading').html(sect[5]);
      t.sect_elem_for('body').html(sect[3]);
      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.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 e = elem;
      var dde = document.documentElement;
      var b = document.body; var w = window;

      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);