// creates the ability to use jquerys dollar sign assignment
// instead of using $('.selector'), use $j('.selector')
var $j = jQuery.noConflict();


var categoryTools = {
  // create an initializer, which creates event listeners
  init: function() {
    // Category Carousel
    $j('.cl-link').click(function() { categoryTools.categoryCarousel(this); return false; });
    // changes selected category according to url
    this.urlToSlectedState();
    // lazy loading function
    lazyLoad.init($j('img.photo').filter(':hidden'));
  },
  categoryCarousel: function(evt) {
    evt = $j(evt);
    var carousel = $j('.carousel:first');
    // if the current link, ignore
    if (evt.parent().hasClass('selected')) { return false; };
    // Google Analytics
    hcUtils.trackEvent('Category', 'Toggle Top Videos', evt.attr('href').substr(1));
    // remove selected
    $j('.snip-link').removeClass('selected');
    // make current selected
    evt.parent().addClass('selected');
    // takes the link and finds the snippets
    var targetId = evt.attr("href");
    // finds the visible snippets
    var visibleEl = $j('.carousel .cl-unit').filter(':visible');
    // loads the images of the new snippets
    lazyLoad.load($j(targetId).find('img.photo'));
    // get position data
    var newPos = this.getRepositionData(targetId);
    // animations
    $j(visibleEl).effect("slide", {direction:"right", mode:"hide"}, 'fast', function(){
      // move the carousel object.. not the thing inside it. 
      carousel.css({"position":"absolute","z-index":9,"top":newPos+"px"});
      $j(targetId).effect("slide", {direction:"left", mode:"show"}, 'fast');
    });
    window.location.hash = targetId;
  },
  getRepositionData: function(targetId) {
    // variables
    var target = $j(targetId);
    var cont = $j('.layout-d');
    var newPos = {};
    var scroll = $j(window).scrollTop();
    target.ht = parseInt(target.height());
    cont.ht = parseInt(cont.height());
    cont.offTop = Math.round(cont.offset().top);
    // calculations
    if (scroll>cont.offTop) { newPos = scroll-cont.offTop; } else { newPos = 0; };
    if ((scroll-cont.offTop)>(cont.ht-target.ht)) { newPos=cont.ht-target.ht; };
    if (newPos<0) { newPos=0; };
    return newPos;
  },
  urlToSlectedState: function() {
    if (window.location.hash == "") {
      $j('.snip-link:first').addClass('selected').show();
      $j('.carousel .cl-unit:first').removeClass('hide').addClass('selected');
    } else {
      var newPos = this.getRepositionData(window.location.hash);
      $j('.carousel:first').css({"position":"absolute","z-index":9,"top":newPos+"px"});
      $j('a[href$="' + window.location.hash + '"]').parent().addClass('selected').show();
      $j('.carousel ' + window.location.hash).removeClass('hide').addClass('selected');
    }
  }
};  // categoryTools Namespace

var hcUtils = {
  createDraggable: function(url) {
    if (!url) {return false};
    $j('body').after("<img src='"+url+"' id='draggable'/>");
    $j("#draggable").draggable();
    var imgWidth = $j('#draggable').width();
    $j('#draggable').css({'opacity':'0.8','z-index':999,'top':0,'position':'absolute','left':'50%','margin-left':'-'+(imgWidth/2)+'px','width':imgWidth+'px'})
  },
  centerOnElement: function(ele, target) {
    // aligns centers on another element's center
    ele = $j(ele);
    target = $j(target);
    target.css({"left":"0px"});
    ele.offLeft = ele.offset().left+(ele.width()/2);
    target.offLeft = target.offset().left+(target.width()/2);
    var diff = (ele.offLeft - target.offLeft);
    target.css({"left":diff+"px"});
  },
  trackEvent: function(category, action, label, value) {
    try {
      pageTracker._trackEvent(category, action, label, value);
    } catch(err) {}
  },
  headerActions: function() {
    // create dropdowns for category and my acount links
    if ($j('#category-hover-link')) {
      $j('#category-hover-link').hover(
        function() {
          if(this.timer) {
            clearTimeout(this.timer);
          };
          this.timer = setTimeout(function(){ 
            $j('#category-ddm-target').fadeIn('fast', function() {
              hcUtils.trackEvent('Header', 'Dropdown', 'Category');
            });
            hcUtils.centerOnElement("#category-hover-link > img","#category-ddm-target > img"); }, 420);
        },
        function() {
          if(this.timer) {
            clearTimeout(this.timer);
          };
          this.timer = setTimeout(function(){$j('#category-ddm-target').fadeOut('fast');}, 420);
        }
      );
    };
    if ($j('#myaccount-hover-link')) {
      $j('#myaccount-hover-link').hover(
        function() {
          if(this.timer) {
            clearTimeout(this.timer);
          };
          this.timer = setTimeout(function(){ 
            $j('#user-ddm-target').fadeIn('fast', function() {
              hcUtils.trackEvent('Header', 'Dropdown', 'My Account');
            });
            hcUtils.centerOnElement("#myaccount-hover-link > img","#user-ddm-target > img"); }, 420);
        },
        function() {
          if(this.timer) {
            clearTimeout(this.timer);
          };
          this.timer = setTimeout(function(){ $j('#user-ddm-target').fadeOut('fast'); }, 420);
        }
      );
    };    
    //  suckerfish style hover animation..   extend this to use a unique class
    $j("#user-ddm-target li").hover(
      function() {
        $j(this).addClass("hover");
      },
      function() {
        $j(this).removeClass("hover");
      }
    );
  }, // end headerActions
  init: function() {    
    hcUtils.headerActions();
  }  // end init
};
$j(document).ready(function(){ hcUtils.init(); });

// Used on Marker create/edit
MARKER = function() {
  return {
    init: function() {
      MARKER.restrictDelete();
      MARKER.updatePositions();
    },
    updatePositions: function() {
      $j('#markers .marker:visible input.position').each(function(index) {
        $j(this).val(index+1);
      });
    },
    restrictDelete: function() {
      $j('#markers .marker:visible .remove-link:first').hide();
    },
    showHandle: function() {
      if ($j('#markers .marker:visible').length > 1) {
        $j('.handle', this).height(jQuery(this).height()-23);
      } else {
        $j('.handle', this).height(0);
      }
    }
  };
}(); // MARKER namespace


var lazyLoad = {
  init: function(els) {
    lazyLoad.unload(els);
  },
  load: function(els) {
    $j(els).each(function(i, val) {
      if ($j(val).attr("src").length > 0) {return false;};
      var source = $j(val).attr("origin");
      $j(val).attr("src", function() {return source;});
      $j(val).attr("origin", "");
    });
  },
  unload: function(els) {
    $j(els).each(function(i, val) {
      var source = $j(val).attr("src");
      $j(val).attr("origin", function() {return source;});
      $j(val).attr("src", "");
    });
  }
};  // Lazy Load Namespace

(function($){
  var url = "/search/suggest.txt";
  var options = {
    scroll: false,
    resultsClass: "theme-box Round Cirrus ac_results",
    selectFirst: false,
    delay: 125,
    width: 358 + 7 + 7 + 31 + 1, // input width + left padding + right padding + right margin + right border
    cacheLength: 10,
    matchSubset: true,
    matchContains: true
  }
  $(document).ready(function(){
    $(".search-input").autocomplete(url, options);
  });
})(jQuery);
