var CNHI = function(){

  var User;
  var Animator;
  var Gopher;
  var Processor;
  var Enhancer;
  var Headlines;
  var Display;
  var WelcomeWagon;
  var IPhone;
  var Lumberjack;
  var CurrentState;
  var StateManager;
  var Connections;
  var Dispatcher;
  var Functions;
  var PublicFunctions;
  var PremiumAds;
  var PremiumAds_max;

  var conf;

  function init(config) {
    conf = {
      more_text : config.more_text || '&hellip; more &raquo;',
      language : config.language || 'Friendly',
      logging : config.logging || false,
      AJAX_param : '/stripped',
      start_query : '?start=',
      section_mapping : config.mapping,
      siteid : config.siteid,
      tld : config.tld,
      root : config.siteurl,
      initial_section : {id: config.initial_section},
      url_delimiter : '/',
      l18n : {
        Friendly : {
          error      : 'Uh oh! Error!',
          logger_on  : 'I\'m a lumberjack and I\'m ok.',
          logger_off : 'I work all night. I sleep all day'
        }
      }
    };
    Connections = {
       loading_headlines : null,
       loading_story : null,
       user_speed : null,
       user_font_size : null,
       user_advanced_features : null,
       display_headlines : null,
       animate_body : null,
       search_close : null,
       search_mouse : null,
       search_key : null,
       search_section : null,
       hide_search_results : null,
       user_zip : null,
       header_open : null,
       header_close : null,
       section_header : null,
       navigation_show_submenus : null,
       navigation_links : [],
       select_header_inputs : [],
       related_links : [],
       navigation_hide_submenus : [],
       headlines_show_icons : [],
       headlines_hide_icons : [],
       headlines_load_story : []
    };
    Lumberjack = new lumberjack();
    User = new user();
    PremiumAds = new premium_ads();
    PremiumAds.init();
    if(User.get_pref('advanced_features') !== '0') {
      CurrentState = new state();
      StateManager = new state_manager();
    }
    Gopher = new gopher();
    Enhancer = new enhancer();
    Processor = new processor();
    Animator = new animator();
    Headlines = new headlines();
    Display = new display();
    IPhone = new iphone();
    WelcomeWagon = new welcome_wagon();
    Dispatcher = {
      'nav' : dojo.subscribe('section', Headlines, 'update_headlines'),
      'display' : dojo.subscribe('story', Display, 'update_story'),
      'body' : dojo.subscribe('section', Processor, 'body')
    };
    if(User.get_pref('advanced_features') === '1') {
      Dispatcher['state_story'] = dojo.subscribe('story', StateManager, 'update_story');
      Dispatcher['state_section'] = dojo.subscribe('section', StateManager, 'update_section');
      WelcomeWagon.redirect();
    }
    IPhone.hide_url_bar();
    Enhancer.init();
    Processor.init();
    //dojo.back.setInitialState(CurrentState);
  }
  
  function iphone() {
    this.hide_url_bar = function() {
      Lumberjack.log('IPhone.hide_url_bar');
      if((dojo.isSafari && (navigator.userAgent.indexOf('iPhone') > 0)) || (dojo.isSafari && (navigator.userAgent.indexOf('iPod') > 0))) {
        window.scrollTo(0, 1);
      }
    };
  }
  
  function welcome_wagon() {
    this.redirect = function() {
    /*
      Lumberjack.log('WelcomeWagon.redirect');
      alert(User.get_pref('advanced_features'));
      if(User.get_pref('advanced_features') === '1') {
        if(window.location.href !== conf.root) {
          var here = window.location.href;
          here = here.replace(conf.root + conf.url_delimiter, conf.root + '#');
          window.location.replace(here);
        }
        if(window.location.hash !== '') {
          var hash = window.location.hash.substr(1);
          if(hash.indexOf(conf.url_delimiter) !== -1) {
            hash = unescape(hash);
            hash = hash.split(conf.url_delimiter);
            var section = {};
            section.id = hash[0];
            section.title = conf.section_mapping[section.id].title;
            var story = conf.root + conf.url_delimiter + section.id + conf.url_delimiter + hash.slice(1).join(conf.url_delimiter);
          }else{
            section = {};
            section.id = hash;
            section.title = conf.section_mapping[section.id].title;
          }
          if(section){
            CurrentState.previous_section = conf.initial_section;
            CurrentState.initial_section = section;
            CurrentState.section = section;
            Headlines.update_headlines(CurrentState.initial_section);
            Processor.body(CurrentState.initial_section);
          }
          if(story){
            CurrentState.story = story;
            Display.update_story(CurrentState.story);
          }
        }else{
          CurrentState.section = conf.initial_section;
          CurrentState.initial_section = conf.initial_section;
          CurrentState.previous_section = conf.initial_section;
        }
      }
    */
    };
  }
  
  function user() {
    this.prefs = [];
    this.get_pref = function(pref) {
      //Lumberjack.log('User.get_pref('+pref+')');
      if(this.prefs[pref]) {
        return this.prefs[pref];
      }else if(dojo.cookie(pref) !== undefined){
        return dojo.cookie(pref);
      }else{
        return false;
      }
    };
    this.set_pref = function(pref,value) {
      //Lumberjack.log('User.set_pref('+pref+','+value+')');
      this.prefs[pref] = value;
      dojo.cookie(pref,value,{expires:30,path : '/'});
    };
    this.del_pref = function(pref) {
      //Lumberjack.log('User.del_pref('+pref+')');
      delete this.prefs[pref];
      dojo.cookie(setting,null,{expires: -1});
    };
    this.throttle = function(duration) {
      //Lumberjack.log('User.throttle('+duration+')');
      var speed = this.get_pref('speed');
      if(speed){
        if(speed > 0){
          duration = duration / speed;
        }else{
          duration = 10;
        }
      }
      return duration;
    };
  }
  function animator() {
    this.fadeIn = function(target) {
      Lumberjack.log('Animator.fadeIn('+target+')');
      return dojo.fadeIn(
        {
          node: target,
          duration: User.throttle(500), 
          easing:dojo.fx.easing.easeOut
        }
      );
    };
    this.fadeOut = function(target) {
      Lumberjack.log('Animator.fadeOut('+target+')');
      return dojo.fadeOut(
        {
          node: target,
          duration: User.throttle(500), 
          easing:dojo.fx.easing.easeOut
        }
      );
    };
    this.wipeOut = function(target) {
      Lumberjack.log('Animator.wipeOut('+target+')');
      return dojo.fx.wipeOut(
        {
          node: target,
          duration: User.throttle(1000), 
          easing:dojo.fx.easing.easeOut
        }
      );
    };
    this.wipeIn = function(target) {
      Lumberjack.log('Animator.wipeIn('+target+')');
      return dojo.fx.wipeIn(
        {
          node: target,
          duration: User.throttle(1000), 
          easing:dojo.fx.easing.easeOut
        }
      );
    };
    this.scrollPage = function(target) {
      Lumberjack.log('Animator.scrollPage('+target+')');
      return dojox.fx.smoothScroll(
        {
          node: target, 
          win: window, 
          duration:User.throttle(2000), 
          easing:dojo.fx.easing.easeOut
        }
      );
    };
    this.scrollToTop = this.scrollPage(dojo.byId('skip'));
    this.hideDisplay = this.wipeOut(dojo.byId('display'));
    this.showDisplay = this.wipeIn(dojo.byId('display'));
  }
  function gopher() {
    this.settings = function(url,callback) {
      return {
        url: url,
        load: callback,
        timeout: 15000,
        error: err
      };
    };
    this.loadPage = function(page,callback) {
      Lumberjack.log('Gopher.loadPage('+page+','+callback+')');
      dojo.xhrGet(this.settings(conf.root + conf.url_delimiter + page,callback));
    };
    this.getHeadlines = function(section,start,callback) {
      Lumberjack.log('Gopher.getHeadlines('+section+','+start+','+callback+')');
      if(start) {
        start = conf.start_query + start;
      }else{
        start = '';
      }
      var loading = Animator.fadeIn('loading_indicator');
      Connections.loading_headlines = dojo.connect(loading,'onEnd',function(){
        var fetch = dojo.xhrGet(Gopher.settings(conf.section_mapping[section.id].url + conf.AJAX_param + start,callback));
        fetch.addCallback(function(){
          Animator.fadeOut('loading_indicator').play(500);
        });
      });
      loading.play();
    };
    this.getStory = function(story,callback) {
      Lumberjack.log('Gopher.getStory('+story+','+callback+')');
      var loading = Animator.fadeIn('loading_indicator');
      Connections.loading_story = dojo.connect(loading,'onEnd',function(){
        var fetch = dojo.xhrGet(Gopher.settings(story,callback));
        fetch.addCallback(function(){
          Animator.fadeOut('loading_indicator').play(500);
        });
      });
      loading.play();
    };
  }
  function enhancer() {
    this.init = function() {
      Lumberjack.log('Enhancer.init');
      //Gopher.loadPage('user_controls.html',this.display_controls);
      //Gopher.loadPage('search_form.html',this.display_search);
      //this.loading_graphic();
    };
    this.display_weather = function(weather) {
      Lumberjack.log('Enhancer.display_weather');
      //var target = dojo.byId('weather');
      //target.innerHTML = weather;
    };
    this.display_controls = function(controls) {
      Lumberjack.log('Enhancer.display_controls');
      var panel = dojo.byId('control_panel');
      panel.innerHTML = controls;
      var speed = dojo.byId('speed');
      var font_size = dojo.byId('font_size');
      var advanced = dojo.byId('advanced_features');
      speed.selectedIndex = User.get_pref('speed');
      advanced.selectedIndex = User.get_pref('advanced_features');
      font_size.selectedIndex = User.get_pref('font_size');
      dojo.query('#body').addClass('user_size_' + User.get_pref('font_size'));
      Connections.user_speed = dojo.connect(speed,'onchange',function(){
        User.set_pref('speed',this.value);
      });
      Connections.user_advanced_features = dojo.connect(advanced,'onchange',function(){
        User.set_pref('advanced_features',this.value);
        window.location.reload(true);
      });
      Connections.user_font_size = dojo.connect(font_size,'onchange',function(){
        User.set_pref('font_size',this.value);
        dojo.query('#body').removeClass('user_size_0');
        dojo.query('#body').removeClass('user_size_1');
        dojo.query('#body').removeClass('user_size_2');
        dojo.query('#body').removeClass('user_size_3');
        dojo.query('#body').addClass('user_size_' + User.get_pref('font_size'));
      });
      if(User.get_pref('zipcode')) {
        dojo.byId('user_zip').value = User.get_pref('zipcode');
      }
      Connections.user_zip = dojo.connect(dojo.byId('user_zip_form'),'onsubmit',function(e) {
        e.preventDefault();
        User.set_pref('zipcode',dojo.byId('user_zip').value);
        /*
         * This bit would make each field in the search bar at the top
         * briefly highlight, in sequence
         
        var delay = 0;
        dojo.query('#header input.query').forEach(function(input){
          dojo.animateProperty(
            {
              node: input, 
              duration:750,
              properties:
              {
                color:
                {
                  start:'#fff'
                }
              }
            }
          ).play(delay);
          delay += 250;
        });
      */
      });
    };
    this.display_search = function(search) {
      Lumberjack.log('Enhancer.display_search');
      var target = dojo.byId('search_form');
      target.innerHTML = search;
      Processor.search();
    };
    this.loading_graphic = function() {
      Lumberjack.log('Enhancer.loading_graphic');
      var content = dojo.byId('content');
      var indicator = document.createElement('div');
      dojo.attr(indicator,'id','loading_indicator');
      dojo.style(indicator,'opacity','0');
      content.appendChild(indicator);
    };
  }
  function headlines() {
    this.update_headlines = function(section) {
      Lumberjack.log('Headlines.update_headlines('+section+')');
      if((section.id != CurrentState.section.id) || section.start) {
        Gopher.getHeadlines(section,section.start,this.display_headlines);
      }
      Animator.hideDisplay.play();
    };
    this.display_headlines = function(headlines) {
      Lumberjack.log('Headlines.display_headlines');
      var list = dojo.byId('headlines_wrap');
      var wipeOut = Animator.wipeOut(list);
      Connections.display_headlines = dojo.connect(wipeOut,'onEnd',function(){
        list.innerHTML = headlines;
        Processor.headline_list();
        Animator.wipeIn(list).play();
      });
      wipeOut.play();
    };
  }
  function display() {
    this.update_story = function(story) {
      Lumberjack.log('Display.update_story('+story+')');
      if(story) {
        Gopher.getStory(story,this.display_story);
      }
    };
    this.display_story = function(story) {
      Lumberjack.log('Display.display_story');
      IPhone.hide_url_bar();
      var dis = dojo.byId('display');
      dis.innerHTML = story;
      Processor.story_body();
      Processor.related_content();
      dojo.fx.chain([
        Animator.scrollToTop,
        Animator.showDisplay
      ]).play();
    };
  }
  function processor() {
    this.init = function(){
      Lumberjack.log('Processor.init');
      this.navigation();
      this.header();
      this.slideshow();
      this.story_body();
      if(User.get_pref('advanced_features') === '1') {
        this.section_header();
        this.body();
        this.features();
        this.headline_list();
      }
      this.related_content();
      this.breaking_news();
      this.big_story();
      this.featured_stories();
      //this.footer();
    };
    this.big_story = function() {
      Lumberjack.log('Processor.big_story');
      if(dojo.byId('big_story')) {
        var stories = dojo.query("#big_story li");
        if(stories.length > 1) {
          var big = new dojox.widget.Roller({delay:15000},"big_story");
          dojo.connect(big.domNode, "onmouseenter", big, "stop");
          dojo.connect(big.domNode, "onmouseleave", big, "start");
        }
        if(stories.length == 0) {
          dojo.destroy(dojo.byId('big_story'));
        }
      }
    };
    this.breaking_news = function() {
      Lumberjack.log('Processor.breaking_news');
      if(dojo.byId('breaking_news')) {
        var breaking = new dojox.widget.Roller({delay:5000},"breaking_news_roller");
        dojo.connect(breaking.domNode, "onmouseenter", breaking, "stop");
        dojo.connect(breaking.domNode, "onmouseleave", breaking, "start");
      }
    };
    this.featured_stories = function() {
      Lumberjack.log('Processor.featured_stories');
      var featured = dojo.byId('featured_stories');
      if(featured) {
        dojo.attr(featured, 'dojoType', 'dojox.layout.ScrollPane');
        dojo.attr(featured, 'orientation', 'horizontal');
        dojo.parser.parse(dojo.byId('highlights'));
      }
    };
    this.slideshow = function() {
      Lumberjack.log('Processor.slideshow');
      var gallery = dojo.byId('gallery');
      if(gallery){
        var photos = dojo.query('.slideshow li a');
        /*
        dojo.forEach(photos,function(a){
          dojo.attr(a, 'href', dojo.attr(a,'imgsrc'));
          dojo.attr(a, 'dojoType', 'dojox.image.Lightbox');
          dojo.attr(a, 'group', 'slideshow');
        });
        */
        dojo.parser.parse(dojo.byId('gallery'));
        var itemNameMap = {imageThumbAttr: "thumb", imageLargeAttr: "large"};
        var request = {query: {}, count : 20};
         dijit.byId('gallery1').setDataStore(imageItemStore, request, itemNameMap);
      }
      var widget = dojo.byId('widget_latest_photos');
      if(widget) {
        dojo.parser.parse(dojo.byId('widget_latest_photos'));
        var request = {query: {}, count : 20};
        var itemNameMap = {imageThumbAttr: "thumb", imageLargeAttr: "large"};
        dijit.byId('latest_photos').setDataStore(imageItemStore, request, itemNameMap);
      }
    };
    this.body = function(section) {
      Lumberjack.log('Processor.body('+section+')');
      if(!section) {
        section = CurrentState.section;
      }
      if(section.id != CurrentState.previous_section.id) {
        var body = dojo.query('#wrap');
        var section_header = dojo.byId('section_header');
        var animation = Animator.fadeOut('section_header');
        Connections.animate_body = dojo.connect(animation,'onEnd',function(){
          section_header.innerHTML = '';
          var new_header = document.createElement('a');
          dojo.attr(new_header,'href',conf.root + conf.url_delimiter + section.id);
          new_header.innerHTML = section.title;
          section_header.appendChild(new_header);
          Processor.section_header();
          body.removeClass(CurrentState.previous_section.id);
          body.addClass(section.id);
          Animator.fadeIn('section_header').play();
        });
        animation.play();
      }
    };
    this.search = function() {
      Lumberjack.log('Processor.search');
      var form = dojo.byId('search');
      var search = dojo.byId('search_phrase');
      var closed_x = -500;
      var open_x = 0;
         
      dojo.attr(form,{'state' : 'closed'});
      
      this.show_search = function(e) {
        Lumberjack.log('Processor.search.show_search');
        var form_state = dojo.attr(form,'state');
        var tabbing = false;
        var caller = 'mouse';
        var maybeFocus = function() {
           if(tabbing) {
             search.focus();
           }
        };
        if(e.type == 'keypress') {
          caller = 'key';
          keyCode = e.keyChar || e.keyCode;
          if(keyCode == dojo.keys.TAB && form_state == 'closed') {
            tabbing = true;
            e.preventDefault();
          }
        }

        if((form_state == 'closed' && caller == 'mouse') || (form_state == 'closed' && tabbing)) {
          dojo.animateProperty(
            {
              node: form, 
              duration:User.throttle(500),
              properties:
              {
                right:
                {
                  start:closed_x,
                  end: open_x,
                  units:'px'
                }
              },
              onEnd: maybeFocus
            }
          ).play();
          dojo.attr(form,{'state' : 'open'});
          dojo.attr(search,{'tabindex' : '1'});
        }
      };
      this.hide_search = function() {
        Lumberjack.log('Processor.search.hide_search');
        if(dojo.attr(form,'state') == 'open') { 
          dojo.animateProperty({ node: form, duration:User.throttle(500),
            properties: {
              right: { start:open_x, end: closed_x, units:'px' }
            }
            }).play();
          dojo.attr(form,{'state' : 'closed'});
          dojo.attr(search,{'tabindex':'-1'});
        }
      };
      this.search_section = function() {
        Lumberjack.log('Processor.search.search_section');
        var sections = dojo.byId('search_section');
        //dojo.byId('ss1').value = conf.root + '/' + sections.value;
        dojo.byId('ss1').value = 'http://enidnews.com/' + sections.value;
      };
      this.hide_search_results = function() {
        var results = dojo.byId('search_results');
        Animator.wipeOut(results);
      };
      Connections.hide_search_results = dojo.connect(dojo.byId('search_results'),'onclick',this.hide_search_results);
      Connections.search_section = dojo.connect(dojo.byId('search_section'),'onchange',this.search_section);
      Connections.search_key = dojo.connect(document,'onkeypress',this.show_search);
      Connections.search_mouse = dojo.connect(form,'onmouseenter',this.show_search);
      Connections.search_close = dojo.connect(dojo.byId('close_search'),'onclick',this.hide_search);
    };
    this.header = function() {
      Lumberjack.log('Processor.header');
      var head = dojo.byId('header');
/*       var wrap = dojo.byId('wrap');
      
      var open_height = 60;
      var closed_height = 60; // put back to 30 to animate

      var play_open = function() {
        Lumberjack.log('Processor.header.play_open');
        if(dojo.style(head,'height') == closed_height) {
          dojo.animateProperty(
            { 
              node: head, 
              duration:User.throttle(1000),
              properties:
              {
                height:
                {
                  start:closed_height,
                  end: open_height,
                  units:'px'
                }
              }
            }
          ).play();
        }
      };
      var play_close = function() {
        Lumberjack.log('Processor.header.play_close');
        if(dojo.style(head,'height') == open_height) {
          dojo.animateProperty(
            {
              node: head,
              duration:User.throttle(1000),
              properties:
              {
                height:
                { 
                  start:open_height, 
                  end: closed_height, 
                  units:'px'
                }
              }
            }
          ).play(500);
        }
      };*/
      dojo.query('#header input.query').forEach(function(input){
        Connections.select_header_inputs.push(
          dojo.connect(input,'onfocus',function(e) {
          this.select();
        }));
      });
      /*
      Connections.header_open = dojo.connect(dojo.byId('header'),'onmouseenter', play_open);
      Connections.header_close = dojo.connect(dojo.byId('header'),'onmouseleave', play_close);
      dojo.attr(head,{'state' : 'closed'}); 
      */
    };
    this.section_header = function() {
      Lumberjack.log('Processor.section_header');
      Connections.section_header = dojo.query('#section_header a').connect('onclick',function(e) {
        e.preventDefault();
        dojo.publish('section',[CurrentState.section]);
      });
    };
    this.navigation = function() {
      Lumberjack.log('Processor.navigation');
      var submenus = dojo.query('div#navigation ul ul');  
      var hide_submenu = function(sub) {
        var submenu_active = false;
        var subs = dojo.query('li a', sub);
        dojo.forEach(subs,function(submenu){
          if(dojo.hasClass(submenu,'current_section')) {
            submenu_active = true;
          }
        });
        if(!submenu_active) {
          dojo.fx.wipeOut({node: sub,duration: User.throttle(500)}).play();
        }
      };
      if(User.get_pref('advanced_features') === '1') {
        if(CurrentState.section.id != CurrentState.previous_section.id) {
          var items = dojo.query('div#navigation a');
          dojo.forEach(items,function(item){
            dojo.removeClass(item,'current_section');
            if(dojo.attr(item,'class') == CurrentState.section.id) {
              dojo.addClass(item,'current_section');          
            }
          });
        }
      } 
      Connections.navigation_show_submenus = dojo.connect(dojo.byId('navigation'),'onmouseleave', function(e){
        dojo.forEach(submenus,function(sub){hide_submenu(sub);});
      });
      if(User.get_pref('advanced_features') === '1') {
        dojo.query('div#navigation a').forEach(function(a){
          Connections.navigation_links.push(
            dojo.connect(a,'onclick',function(e) {
              e.preventDefault();
              var section = {};
              dojo.query('div#navigation a').removeClass('current_section');
              section.id = (dojo.attr(this, 'class').replace(' parent_section',''));
              section.title = conf.section_mapping[section.id].title;
              dojo.publish('section', [section]);
              dojo.query(this).addClass('current_section');
            }));
        });
      }
      dojo.forEach(submenus,function(sub){
        hide_submenu(sub);
        Connections.navigation_hide_submenus.push(
          dojo.connect(sub.parentNode,'onmouseenter', function(e) {
          dojo.fx.wipeIn({node: sub,duration: User.throttle(500)}).play();
        }));
      });
      dojo.query('#navigation a.external').attr('target','_blank')
    };
    this.headline_list = function() {
      Lumberjack.log('Processor.headline_list');
      /*
       ******** This animates the story headlines meta data ************
      dojo.query('dl#headline_list dd ul li p.meta').forEach(function(em){
        dojo.fx.wipeOut({node: em,duration: 0}).play();
      });
      dojo.query('dl#headline_list dd ul li').forEach(function(li){
        Connections.headlines_show_icons.push(
         dojo.connect(li,'onmouseenter',function(e) {
          var icons = dojo.query('p.meta',this);
          if(icons[0]) {
            dojo.fx.wipeIn({node: icons[0],duration: User.throttle(500)}).play();
          }
        }));
        Connections.headlines_hide_icons.push(
          dojo.connect(li,'onmouseleave',function(e) {
            var icons = dojo.query('p.meta',this);
            if(icons[0]){
             dojo.fx.wipeOut({node: icons[0],duration: User.throttle(500)}).play();
            }
          }));
      });
      */
      dojo.query('#headline_list dd ul li a').forEach(function(a){
        Connections.headlines_load_story.push(
          dojo.connect(a,'onclick',function(e) {
            e.preventDefault();
            var section = {};
            var rel = dojo.attr(this,'rel');
            var url = dojo.attr(this,'href');
            var story = url + conf.AJAX_param;
            section.id = dojo.attr(this, 'class');
            section.title = conf.section_mapping[section.id].title;
            if(rel == 'next') {
              section.start = url.split('start=')[1];
              story = null;
            }
            dojo.publish('section',[section]);
            dojo.publish('story',[story]);
        })); 
      });
    };
    this.features = function() {
      dojo.query('#features a[rel=article]').forEach(function(a){
        Connections.headlines_load_story.push(
          dojo.connect(a,'onclick',function(e) {
            e.preventDefault();
            var section = {};
            var url = dojo.attr(this,'href');
            var story = url + conf.AJAX_param;
            section.id = dojo.attr(this, 'class');
            section.title = conf.section_mapping[section.id].title;
            dojo.publish('section',[section]);
            dojo.publish('story',[story]);
        })); 
      });
      dojo.query('#features a[rel=section]').forEach(function(a){
        Connections.headlines_load_story.push(
          dojo.connect(a,'onclick',function(e) {
            e.preventDefault();
            var section = {};
            var url = dojo.attr(this,'href');
            section.id = dojo.attr(this, 'class');
            section.title = conf.section_mapping[section.id].title;
            dojo.publish('section',[section]);
        })); 
      });
    };
    this.related_content = function() {
      Lumberjack.log('Processor.related_content');
      var photos = dojo.query('.related_photos a');
      dojo.forEach(photos,function(a){
        dojo.attr(a, 'href', dojo.attr(a,'imgsrc'));
        dojo.attr(a, 'dojoType', 'dojox.image.Lightbox');
        dojo.attr(a, 'group', 'related_photos');
      });
      dojo.parser.parse(dojo.byId('display'));
      dojo.parser.parse(dojo.byId('features'));
      /*
      dojo.query('ul.related_links li a').forEach(function(a){
        Connections.related_links.push(
          dojo.connect(a,'onclick',function(e) {
            e.preventDefault();
            var section = {};
            section.id = dojo.attr(this, 'class');
            section.title = conf.section_mapping[section.id].title;
            dojo.publish('section',[section]);
            dojo.publish('story',[dojo.attr(this,'href') + conf.AJAX_param]);
        }));
      });
      */
    };
    this.story_body = function() {
      Lumberjack.log('Processor.story_body');
/*       var story = dojo.byId('story_body'); */
      var pull_quotes = dojo.query('#story_body span.pull_quote');
      dojo.forEach(pull_quotes, function(quote){
        var text = quote.innerHTML;
        var box = document.createElement('div');
        dojo.attr(box, 'class', 'pull_quote');
        var source = quote.parentNode;
        box.innerHTML = text;
        source.appendChild(box);
      });
    };
    this.footer = function() {
      Lumberjack.log('Processor.footer');
      var sitemap = dojo.byId('site_map');
      dojo.query('a',sitemap).forEach(function(a){
        Connections.footer_sitemap.push(
          dojo.connect(a,'onclick',function(e) {
            e.preventDefault();
            var section = {};
            section.id = (dojo.attr(this, 'class'));
            section.title = conf.section_mapping[section.id].title;
            dojo.publish('section', [section]);
        }));
      });
    };
  }
  function state_manager() {
    this.update_section = function(section,log){
      Lumberjack.log('StateManager.update_section('+section+','+log+')');
      var previous_section = CurrentState.section || {id:'homepage',title:'Homepage'};
      CurrentState = new state();
      CurrentState.section = section;
      CurrentState.previous_section = previous_section;
      CurrentState.changeUrl = this.bookmark(section.id);
      if(log !== false) {
        this.deploy(CurrentState);
      }
    };
    this.update_story = function(story,log){
      Lumberjack.log('StateManager.update_story('+story+','+log+')');
      if(story) {
        var section = CurrentState.section;
        var cleaned_story_url = story.replace(conf.root + conf.url_delimiter + section.id,'');
        var previous_section = CurrentState.previous_section || {id:'homepage',title:'Homepage'};
        CurrentState = new state();
        CurrentState.story = cleaned_story_url;
        CurrentState.section = section;
        CurrentState.previous_section = previous_section;
        CurrentState.changeUrl = this.bookmark(section.id,cleaned_story_url);
        if(log !== false) {
          this.deploy(CurrentState);
        }
      }
    };
    this.bookmark = function(sectionid,story) {
      var bookmark = sectionid + (story ? story : '');
      return bookmark;
    };
    this.deploy = function(CurrentState) {
      dojo.back.addToHistory(CurrentState);
    };
  }
  function state(){
    this.back = function() {
      if(this.story) {
        dojo.publish('story', [conf.root + conf.url_delimiter + this.section.id + conf.url_delimiter + this.story,false]);    
      }
      if(this.section) {
        dojo.publish('section', [this.section,false]);
      }
    };
    this.forward = function() {
      if(this.story) {
        dojo.publish('story', [this.story]);    
      }
      if(this.section) {
        dojo.publish('section', [this.section]);
      }
    };
  }
  function lumberjack() {
    this.on = function() {
      conf.logging = true;
      if(console) {
        console.log(l18n('logger_on'));
      }
    };
    this.off = function() {
      conf.logging = false;
      if(console) {
        console.log(l18n('logger_off'));
      }
    };
    this.log = function(log) {
      if(conf.logging) {
        if(console) {
          console.log(log);
        }
      }
    };
  }
  function err(error) {
    if(console) {
      console.error(l18n('error') + ' : ', error);
    }
  }
  function l18n(out) {
    return conf.l18n[conf.language][out] || out;
  }
  function premium_ads(ads) {
    this.init = function() {
      var premium_target = dojo.byId('premium_text_ads');
      if (conf.siteid.search(/^(heraldbulletin|andovertownsman|carriagetownenews|derrynews|eagletribune|gloucestertimes|hgazette|newburyportnews|paulsvalleydailydemocrat|recordeagle|salemnews|tribdem)$/) != -1) {
        PremiumAds_max = 25;
      }else{
        PremiumAds_max = 3000;
      }
    };
    this.build = function(json) {
      var premium_target = dojo.byId('premium_text_ads');
      if(premium_target) {
        var panels = document.createElement('div');
        var selected_panel = Math.floor(Math.random()*json.premiumTextAds.length);
        dojo.attr(panels,'dojoType','dijit.layout.AccordionContainer');
        dojo.attr(panels,'id','premium_ads');
        dojo.attr(panels,'duration',User.throttle(1000));
        dojo.forEach(json.premiumTextAds,function(category,index){
          if(category.ads.length > 0) {
            var ads = Functions.array.shuffle(category.ads);
            var pane = document.createElement('div');
            dojo.attr(pane,'dojoType','dijit.layout.AccordionPane');
            if(selected_panel === index) {
              dojo.attr(pane,'selected','true');
            }
            dojo.attr(pane,'title',category.title);
            var count = 0;
            dojo.forEach(ads,function(copy){
              if (count < PremiumAds_max) {
          var ad = document.createElement('div');
          var link = document.createElement('a');
          dojo.attr(link,'href',copy.url);
          dojo.attr(ad,'class','premium_ad');
          ad.innerHTML = copy.text + '&nbsp;<strong>&hellip;more&nbsp;&raquo;</strong>';
          link.appendChild(ad);
          pane.appendChild(link);
              }
              count++;
            });
            panels.appendChild(pane);
            premium_target.appendChild(panels);
          }
        });
        dojo.parser.parse(dojo.byId('premium_text_ads'));
      }
    };
  }

  Functions = {
    array : {
      shuffle : function(v){
        for(var j, x, i = v.length; i; j = parseInt(Math.random() * i,10), x = v[--i], v[i] = v[j], v[j] = x){}
        return v;
      }
    }
  };

  PublicFunctions = {
    /*
        public API to CNHI module
        call these like:
        CNHI.API.grid.on()
        or
        CNHI.API.logger.off()
        this will allow us to add functions 
        other pages, scripts, and possibly papers can call
    */
    grid : {
      on : function() {
        dojo.query('#body').addClass('grid');
      },
      off : function() {
        dojo.query('#body').removeClass('grid');
      }
    },
    checkInput : function(f,v) {
      if(dojo.byId(f).value != v) {
        return true;
      }else{
        dojo.byId(f).value = '';
        alert('Please enter a term to search for.');
        dojo.byId(f).focus();
        return false;
      }
    },
    logger : {
      on : function() {
        Lumberjack.on();
      },
      off : function() {
        Lumberjack.off();
      }
    },
    state : function() {
      //console.dir(CurrentState);
    },
    pta : function(ads) {
      PremiumAds.build(ads);
    },
    widgets : {
      rss : function(feed) {
        //console.log('I recieved: ' + feed);
      }
    },
    google : {
      submit_search : function () {
       document.searchform.sbi.value=document.searchform.stext.value;
       document.searchform.submit()
      }
    },
    poll : {
      displayResults : function(url) {
        dojo.xhrGet({
            url: url + '/results',
            load: function(response, ioArgs){
               CNHI.API.poll.createChart(response.rows);
            },
            error: function(response, ioArgs){
               /* Handle Error appropriately here */
               return response;
            },
            handleAs: "json"
        });
        return false;
      },
      submitVote : function(url, form_id) {
          dojo.xhrPost({
              url: url + '/vote',
              form: dojo.byId(form_id),
              load: function(response, ioArgs){
                  if (response.success) {
                      CNHI.API.poll.displayResults(url);
                  } else {
                      dojo.byId('poll-questions').innerHTML =
                          "Couldn't submit your vote. Please try again later.";
                      return response;
                  }
              },
              error: function(response, ioArgs){
                  /* Handle Error appropriately here */
                  return response;
              },
              handleAs: "json"
          });
      },
      createChart : function(data) {
        dojo.byId('poll-questions').innerHTML = '';
        var chartData = [];
        dojo.forEach(data,
            function (item, index, array) {
               var tooltip = item.option + ' (' + item.count + ' votes' + ')';
               chartData.push({
                   y: item.count,
                   stroke: "gray",
                   tooltip: tooltip,
                   legend: tooltip
                   });
            }
        );
        var pollChart = new dojox.charting.Chart2D("poll-questions");
        pollChart.setTheme(dojox.charting.themes.MiamiNice);
        pollChart.addPlot("default", {
            type: "Pie",
            font: "normal normal 11pt Tahoma",
            fontColor: "black",
            labelOffset: 30,
            radius: 80,
            precision: 0
        });
        pollChart.addSeries("default", chartData);
        var anim_a = new dojox.charting.action2d.MoveSlice(pollChart, "default");
        var anim_b = new dojox.charting.action2d.Highlight(pollChart, "default");
        var anim_c = new dojox.charting.action2d.Tooltip(pollChart, "default");
        pollChart.render();
        var pollLegend = new dojox.charting.widget.Legend({
            chart: pollChart,
            horizontal: false
        }, "poll-legend");
      }
    }
  };
  /*
    return public-facing handles to internal functions
  */
  return {
    init:init,
    API:PublicFunctions
  };
}();
function emailobscure(emailname, emaildomain) {
  window.location.replace('mailto:'+emailname+'@'+emaildomain);
}
