window.jn = {
  "ieResize": function(f){
    var ieresize = {
      "width": 0,
      "isResizing": null
    };
    
    function resizeOnce() {
      if ( $.browser.msie ) {
        if ( ! ieresize.fired ) {
          ieresize.fired = true;
        }
        else {
          var version = parseInt( $.browser.version, 10 );
          ieresize.fired = false;
          if ( version < 7 ) {
            return false;
          }
          else if ( version < 9 ) {
            //a vertical resize is fired once, an horizontal resize twice
            var width = $( window ).width();
            if ( width != ieresize.width ) {
              ieresize.width = width;
              return false;
            }
          }
        }
      }

      return true;
    }

    return function( e ) {
      if ( resizeOnce() ) {
        return f.apply(this, [e]);
      }
    }
  },
  "ticker": function(sel, options){
    var o = $.extend({
      "delay": 10000,
      "fx": "fade"
    }, options||{});
    
    $(sel).cycle(o);
  },
  "hero": function(sel, options){
    var o = $.extend({
      "delay": 10000,
      "fx": "fade",
      "pause": true
    }, options||{});
    
    if(o.pager){
      o = $.extend({
        "pauseOnPagerHover": true,
        "pagerAnchorBuilder": function(i,ele){
          // ele is the silde
          $a = $('<a href="#">'+i+'</a>');
          if(i == 0){
            $a.addClass('jn-first');
          } else if(i == (this.elements.length-1)){
            $a.addClass('jn-last');
          }
          return $a;
        }
      }, o);
    }
    
    $(sel).cycle(o);
  },
  "banner": function(sel, options){
    
    function positionButtons(c, state){
       var bimg = $('.jn-banner-image', c.get(1));
       if(bimg.length > 0){
         var pos = bimg.offset();
         // this is relative to the parent container, but since all our containers are the same size
         // its what we want to position the buttons
         var dim = {h: bimg.innerHeight(), w: bimg.innerWidth()};
         var nextDim =  {h: c.buttonNext.outerHeight(), w: c.buttonNext.outerWidth()};
         var prevDim = {h: c.buttonPrev.outerHeight(), w: c.buttonPrev.outerWidth()};
         var pleft = pos.left;
         var nleft = (pos.left+dim.w)-parseInt(bimg.css('margin-right'));
         c.buttonPrev.css({
           left: pleft
         });
         c.buttonNext.css({
           left: nleft
         });
       }
    }
 
    function onInit(c, state){
      
      positionButtons(c, state);
    }

    function onReload(c){
      if($.browser.msie){
        var t = setTimeout(function(){
          positionButtons(c, 'reload');
          clearTimeout(t);
        }, 200);
      } else {
        positionButtons(c, 'reload');
      }
    }
    
    function onSetup(c){
      // remove the time out based resize workaround and replace it with out ieResize closure
      $(window).unbind('resize.jcarousel', $.jcarousel.funcResize).bind('resize.jcarousel', jn.ieResize(function(e){
        c.reload();
      }));
    }
    
    o = $.extend({
      visible: 1,
      scroll: 1,
      wrap: "both",
      auto: 5000,
      initCallback: onInit,
      reloadCallback: onReload,
      setupCallback: onSetup
    }, options||{});
    
    $('.jn-banner-content', sel).jcarousel(o);
  },
  "positionArrow": function(subnav, navitem){
    var $subnav = $(subnav);
    var $navitem = $(navitem);
    var lft = Math.ceil($navitem.outerWidth(true)/2);
    if($.browser.msie){
      var pos = (parseInt($subnav.css('background-position-x'))-11);
      $subnav.css('background-position-x', (lft-11)+'px');
    } else {
      var pos = $subnav.css('background-position').split(' ');
      pos[0] = (lft-11)+'px'; // 11 is 0.5*backgroundImage.height
      $subnav.css('background-position', pos.join(' '));
    }
  },
 "dropdown": function(sel){

    var menu = $(sel);
    var login = menu.find('.jn-dropdown-login');
	var iama = menu.find('#whatami');
	var user = menu.find('#global-login-form-user_id');
	var pwd = menu.find('#global-login-form-password');   
	     
    menu.find('.jn-dropdown-subnav-content').each(function(){
      var $this = $(this);
	  
      if($('.jn-nav', $this).length > 1){
        $this.addClass('jn-nav-double');
      }
      var $subnav = $this.parent();
     
      var $anchor = $subnav.siblings('a');
      var $navitem = $subnav.parent('li.jn-nav-item');
      if($navitem.length > 0){
        jn.positionArrow($subnav, $navitem);
      }
      
    });
    
     function doOver(){
       if(document.activeElement != iama[0] && (document.activeElement != user[0]) && 
	   	  document.activeElement != pwd[0]){
         	login.hide();
       }
       $(this).toggleClass('jn-nav-over');
     }
  
    function doOut(){
	  if(document.activeElement != iama[0] && (document.activeElement != user[0]) && 
	   	  document.activeElement != pwd[0]){
          login.hide();
      }
      $(this).toggleClass('jn-nav-over');
    }
    
    menu.find('.jn-nav-item').hover(doOver, doOut);
  },
  'login': function(sel, options){
    var o = $.extend({}, options||{});
    var container = $(sel);
    var dropdown = container.find('.jn-dropdown-login');
    jn.positionArrow(dropdown, container);
    
    var form = dropdown.find('form:first');
    var labels =  form.find('label.jn-infield"').each(function(){
      $(this).parent().css('position', 'relative');
      $(this).css({
          position: 'absolute',
          'top':2,
          left: 5
      });
    }).inFieldLabels();
    
    dropdown.hide();
    var linkSel = o.invoker||"> a:first";
    var linkbtn = container.find(linkSel);
    
    
    function shadow(field, shadow){
      var input = $(field);
      var ssel = shadow||"[name=s"+input.attr('name')+']';
      var sinput = input.siblings(ssel);
      
      input.blur(function(){
        sinput.val(input.val());
      });
    }
    
    form.find('.jn-sfield').each(function(){ shadow(this); });
    
    function toggleMenu(e){
      e.preventDefault();
      dropdown.toggle();
      linkbtn.toggleClass('jn-dropdown-login-active');
      form.focus();
    }
    
    linkbtn.click(toggleMenu);
    dropdown.click(function(e){
      var isActive = $(this).has(document.activeElement);
      if(!isActive || (isActive && !$(document.activeElement).is(':input'))){
        linkbtn.click();
      } 
    });
    
  },
  'accordion': function(sel, options) {
    
    var _jaDefaults = {
      header: '> li > a:first-child',
      collapsible: true,
      autoHeight: false,
      navigation: true,
      active: false,
      icons: {header: 'ui-icon-triangle-1-s', headerSelected: 'ui-icon-triangle-1-n'}
    };
    
    if(options){
      options.ui = $.extend(_jaDefaults, options.ui||{});
    }
    else {
      var options = {'ui': _jaDefaults };
    }
    
    _init($(sel), options).accordion(options.ui);
    
    
    function _findActiveMenu(selector, context){
      // selector is the selector used to find
      // the menu using the anchor as a context
      // within the contextElement passed to the
      // outer function
      
      // we need to test agains botht he full uri as well as the pathname
      // order is significant - href shoudl come first since its the most
      // unique
      var locations = [window.location.href, window.location.pathname];
      var match = $(), i=0;
      while(match.length < 1 && i < 2){
        match = context.find('a[href="'+locations[i]+'"]');
        ++i;
      }
      
      return $(selector, match);
    }
    
    function _getMenuStates(menuSelector, activeItemSelector, contextElement){
      var states = {
        'active': null,
        'inactive': null,
        'all': $(menuSelector, contextElement)
      };
      
      
      states.active = _findActiveMenu(activeItemSelector, states.all.parent());
      states.inactive = states.all.not(states.active);
      
      return states;
    }
    
    function _init(container, options){
      
      return container;
      
      // the following code is deprecated 
      
      var o = $.extend({
        'activeClass': 'jn-active',
        'defaultClass': 'jn-default',
        'menuSelector': '.jn-nav',
        'menuTargetDepth': 3
      }, options||{});
      
      var stateSelector = o.menuTargetDepth && o.menuTargetDepth > 0 
        ? new Array(3).join(o.menuSelector+' ')
        : o.menuSelector;
        
      if(!o.activeSelector){
        o.activeSelector = '+'+o.menuSelector;
      }
      
      var menus = _getMenuStates(stateSelector, o.activeSelector, container);

      if(menus.active.length > 0){
        menus.active.addClass(o.defaultClass);
      }

      menus.active.toggleClass(o.activeClass);
      menus.inactive.hide();

      menus.all.each(function(){
        var $this = $(this);
        $this.parent().data('jnAccordion.menu', $this);
      });
      menus.all.parent().click(function(e){
        var $this = $(this);
        var $menu = $this.data('jnAccordion.menu');
        if(!$menu.hasClass(o.activeClass)){
          $menu.slideDown(150, function(){
            menus.all.filter('.'+o.activeClass).toggleClass(o.activeClass);
            menus.all.not($menu).slideUp();
            $(this).toggleClass(o.activeClass);
          });
        } else {
          // reset
          menus.all.not('.'+o.defaultClass).slideUp();
          menus.all.filter('.'+o.defaultClass).slideDown();
        }
      });
      
      return container;
    }
  },
  'activeHilightNav': function(sel, options){
    var o = $.extend({
      'selAnchor': '.jn-nav-item > a:first',
      'selItem': 'li.jn-nav-item',
      'activeClass': 'jn-active'
    }, options||{});
    
    var $nav = $(sel);
    var active = $nav.find(o.selItem+'.'+o.activeClass);
    if(active.length < 1){
      $nav.find(o.selAnchor).each(function(){
        var $this = $(this);
        if(_isActive($this)){
          $this.closet(o.selItem).addClass(o.activeClass);
        }
      });
    }
    
    
    function _isActive(anchor){
      var locations = [window.location.href, window.location.pathname];
      var active = false;
      $.each(locations, function(k,v){
        //if(active == false && anchor.is('a[href="'+v+'"]')){
        if(active == false && anchor.attr('href').test(new RegExp('^.*'+v+'$'))){
          active = true;
        }
      });
      
      return active;
    }
  },
  'viddler': function(method, params, options){
    var o = $.extend({
      'url': '/ajaxproxy.php',
      'dataType': 'json',
      'type': 'post',
      'success': function(data){  },
      'error': function(xhr, status){  }
    }, options||{});
    
    o.data = {
      "method": method,
      "params": params||{}
    };
    
    return $.ajax(o);
  },
  "videoLibrary": function(sel, options){
    var container = $(sel);
    
    function VideoWidget(sel, options){
      var video = this;
      
      // options
      this.options = $.extend({
        "videoUrl": window.location.pathname+'?video_id='+'%VIDEO_ID%',
        "loadingElement": '<span>Loading...</span>',
        "viddlerUser": 'antcunningham'
      }, options||{});
      
      // Tabs object
      this.Tabs = {
        "widget": null,
        "fetchState": 0,
        "fetchResult": null,
        "xhr": null,
        "selectTab": function(e, ui){
          var $panel = $(ui.panel);
          if(!video.Carousel.instances[$panel.attr('id')] && $panel.has('.jcarousel-container').length < 1){
            video.Tabs.fetchTab(ui.tab, ui.panel);
          } 
        },
        "showTab": function(e, ui){
          if(video.Tabs.fetchState == 1){
            $(ui.panel).append($(video.options.loadingElement).addClass('loading'));
          } 
        },
        "init": function(e, ui){
          var tabs = $(e.target);
          var selected = tabs.find('.ui-tabs-selected');
          var panel = tabs.find(selected.find('a').attr('href'));
          panel.append($(video.options.loadingElement).addClass('loading'));
          video.Tabs.fetchTab(selected, panel);
          
        },
        "noResults": function(elem){
          var $elem = $(elem);
          var loading = $elem.children('.loading');
          function showNoResult(){
            $('<h4>No Results.</h4>').css('text-align', 'center').hide().appendTo($elem).fadeIn('slow');
          }
          if(loading.length > 0){
            loading.fadeOut('slow', showNoResult);
          } else {
            showNoResult();
          }
        },
        "fetchTab": function(tab, panel){
          var tag = $(tab).text().replace(' ','').toUpperCase();
          var params = {'user': video.options.viddlerUser, 'per_page': 100};
          
          if(tag.toLowerCase() != 'all'){
            params.tags = tag;
          }
          var $panel = $(panel).data('jn.viddler.params', params);
          
          function handleError(xhr, status){
            video.Tabs.fetchState = 0;
            video.Tabs.fetchResult = {'error': {'message': status}};   
          }

          function handleSuccess(data){
           video.Tabs.fetchState = 0;
           video.Tabs.fetchResult = data;
           if($.isEmptyObject(data.list_result.video_list)){
             video.Tabs.noResults(this);
           } else {
             video.Carousel.createInstance(video.Carousel.getMarkup(data).appendTo(this));
           }
           
          }

          if(video.Tabs.xhr && video.Tabs.fetchState == 1){
            // terminate current request
            video.Tabs.xhr.abort();
            video.Tabs.fetchState = 0;
          }

          video.Tabs.fetchState = 1;
          
          var opts = { success: handleSuccess, error: handleError, context: $panel};
          if(video.options.repositoryUrl){
            opts.url = video.options.repositoryUrl
          }
          
          video.Tabs.xhr = jn.viddler(
            'viddler.videos.getByUser', 
            params,
            opts
          );
        }
      };
      
      this.Tabs.widget = $(sel).tabs({
        select: video.Tabs.selectTab,
        show: video.Tabs.showTab,
        create: video.Tabs.init
      });
      
      // Carousel object
      this.Carousel = {
        "instances": [],
        "lastPage": 0,
        "loadItem": function(carousel, state){
          // implement for video pagination
        },
        "getMarkup": function(data){
          var elem = $('<div class="jn-video-carousel jcarousel-skin-jeffnat"><ul></ul></div>');
          var list = elem.find('ul:first');
          $.each(data.list_result.video_list, function(i,videoData){
            list.append(video.Carousel.createItem(videoData));
          });
          return elem;
        },
        "addItem": function(carousel, first, last, data){
          // implement for video pagination
        },
        "init": function(carousel, state){
          if(state == 'init'){
            var loading = carousel.container.parents('.ui-tabs-panel').children('.loading');
            var mask = carousel.container.parents('.jn-video-carousel-mask');
            
            video.Carousel.lastPage++;
            
            if(loading.length > 0){
              loading.fadeOut('slow', function(){
                mask.hide().removeClass('jn-hidden').fadeIn('slow');
              });
            } else {
              carousel.container.removeClass('jn-hidden');
            }
          }
        },
        "createInstance": function(elem, tag, options){
          var $elem = $(elem).wrap('<div class="jn-video-carousel-mask jn-hidden"></div>');
          var $panel = $elem.parents('.ui-tabs-panel');
          
          var o = $.extend({
            size: $elem.find('> ul li').length,
            scroll: 6,
            wrap: "both",
            auto: 5000,
            fallbackDimension: 143,
            //itemLoadCallback: video.Carousel.loadItem, implement for video pagination
            //itemAddCallback: video.Carousel.addItem, implement for video pagination
            initCallback: video.Carousel.init
          }, options||{});
          
          video.Carousel.instances[$panel.attr('id')] = $(elem).jcarousel(o).data('jn.viddler.tag', tag);
        },
        "createItem": function(itemData){
          var rsec = new String(itemData.length%60);
          var rmin = new String((itemData.length - rsec)/60);
          var runtime = rmin+':'+(rsec.length < 2 ? '0'+rsec : rsec);
          var url;
          if(video.options.videoUrl){
            url = video.options.videoUrl;
            url = url.replace('%VIDEO_ID%', itemData.id);
          } else {
            url = '#';
          }
          return $('<li class="jn-video-item"></li>').attr('id', 'jn-video-'+itemData.id).append(
            $('<img src="'+itemData.thumbnail_url+'" width="117" class="jn-video-thumbnail"/>')
          ).append(
            $('<h5 class="jn-video-title">'+itemData.title+'</h5>')
          ).append(
            $('<a class="jn-video-link">Watch Now</a>').attr('href', url)
          ).append(
            $('<span class="jn-video-runtime">'+runtime+'</span>')
          ).click(function(e){
            window.location.href = url;
          });
        }
      };
    }
    
    var videoWidget = new VideoWidget(container, options);
    return container.data('jn.videoLibrary', videoWidget);
  }
};
