var Cookie = {
  set: function(name, value, minutesToExpire) {
    var expire = '';
    if (minutesToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (60000 * parseFloat(minutesToExpire)));
      var expire = '; expires=' + d.toGMTString();
    } else {
      var expire = ''
    }
    path = '; path=/';
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire + path);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled  == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') = '1');
  }
};

;(function($) {

  // After calling this function, $.platform.mac returns a boolean
  function detectPlatform() {
    nua = navigator.userAgent.toLowerCase();
    $.platform = {
      mac: /mac/.test(nua),
      win: /win/.test(nua),
      linux: /linux/.test(nua)
    };
  }
  
  var cache = [];
  function preLoadImages() {
    var args_len = arguments.length;
    for( var i = args_len; i--; ) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
  
  function bookmarkPage(url, title) {
    detectPlatform();
    key_string = $.platform.mac ? 'Command-D' : 'Control-D';
    if ($.browser.msie && window.external) { // IE Favorite
      window.external.AddFavorite(url, title);
    } else if ($.browser.mozilla && window.sidebar) { // Firefox Bookmark
      window.sidebar.addPanel(title, url, "");
    // NB: Opera auto-bookmarking not supported in newest version
    } else {
      alert('Your browser does not support adding bookmarks by script, please add it manually.\n\n(Shortcut: ' + key_string + ')');
    }
  }
  
  function setCarouselContainerWidth(carousel) {
    var videoCount = carousel.find(".video.small").size();
    var videoWidth = carousel.find(".video.small:first").outerWidth() + 3;
    var newWidth = videoCount * videoWidth;
		var loader = carousel.find(".ajax-loader.horizontal");
    if(loader != null) {
      newWidth = newWidth + loader.outerWidth() + 5;
    }
    carousel.find(".container").css('width', newWidth);
  }

  function carouselSort(link) {
    if(!(link.hasClass('active'))) {
      link.siblings("a").removeClass("active");
      link.addClass('active');
      var carousel = link.parent(".options").next('.carousel');
      carousel.animate({scrollLeft: 0}, 300);
      $.ajax({
        type: 'GET',
        url: link.attr('href'),
        dataType: 'script',
        data: 'sort_by=' + link.attr('id'),
        success: function() {
          setCarouselContainerWidth(carousel);
        }
      });
    }
  }
  
  function searchSort(link) {
    if(!(link.hasClass('active'))) {
      link.siblings("a").removeClass("active");
      link.addClass('active');
      $.ajax({
        type: 'GET',
        url: link.attr("href"),
        dataType: 'script'
      });
    }
  }

  function clickTab(tab_link) {
    if(!(tab_link.hasClass('active'))) {
      var tab = tab_link.parent();
      var groups = tab.parent('.tabs').siblings('.groups');
      tab.siblings().removeClass("active");
      tab.addClass("active");
      groups.children('.group').removeClass("active");
      groups.children('.group.'+tab_link.attr("id")).addClass("active");
    }
  }
  
  function animatedScrollTo(element_id, options) {
    var defaults = {speed : 1000};
    var settings = $.extend(defaults, options);
    var offset = $(element_id).offset().top;
    $("html,body").animate({scrollTop: offset}, settings.speed);
  }

  $(document).ready(function() {
  
    // preload all the 'loading' images
    preLoadImages("/../images/loading_more_videos_hz.gif", 
                  "/../images/loading_more_videos_box.gif", 
                  "/../images/loading_more_videos_next.gif", 
                  "/../images/loading_more_videos_prev.gif");
  
    $('.fieldWithErrors').parent().closest("p").hide();

    setCarouselContainerWidth($("#most-recent .carousel"));
    setCarouselContainerWidth($("#other-stories .carousel"));
  
    // Tabs
    $("div.tabs div.tab a").click(function() {
      clickTab($(this));
      return false;
    });

    // Video Rollovers and Buttons
    $(".video a.more-info").live("click", function() {
      $(this).closest('.video').toggleClass('more');
      return false;
    });
    
    $("#share-bar a#bookmark").click(function() {
      bookmarkPage(location.href, document.title);
      return false;
    });

    // Password Idea
    $("a#password_idea_link").click(function () {
      $("#getting_idea").show();
      $("#get_idea").hide();
      $.ajax({
        url: $(this).attr('href'),
        type: "GET",
        success: function(response, textStatus) {
          // response should either be the assignment_id or 'Failure'
          $("#password_idea").html(response);
          $("#getting_idea").hide();
          $("#get_idea").show();
        }
      });
      return false;
    });
  
    $('a.ajax_put_link').live("click",function() {
      $.ajax({
        type: 'PUT',
				data: { _method:'PUT'},
        url: $(this).attr('href'),
        dataType: 'script'
      });
      return false;
    });

    $('.ajax-loader a').live("click", function() {
      // add 'loading' class & set correct background image with CSS
      $(this).addClass('loading');
      var div = $(this).parent();
      var carousel = $(this).closest('.carousel');
      var horizontal = carousel.hasClass('horizontal');
      var featured = carousel.parent('div.videos-box').attr('id') == 'featured';
      $.ajax({
        type: 'GET',
        url: $(this).attr('href'),
        dataType: 'script',
        success: function() {
          div.remove();
          if (horizontal) { setCarouselContainerWidth(carousel); }
          if (featured) { animatedScrollTo("#featured"); }
        }
      });
      return false;
    });
  
    $('.sort-link').live("click", function() {
      carouselSort($(this));
      return false;
    });
  
    $('.search-sort-link').live("click", function() {
      searchSort($(this));
      return false;
    });

    $('#search-pagination a').live("click", function() {
      $.ajax({
        type: 'GET',
        url: $(this).attr("href"),
        dataType: 'script',
        complete: function() { window.scrollTo(0,0); }
      });
      return false;
    });
    
    $('.ajax_put_form').submit(function() {
      $.ajax({
        type: 'PUT',
        url: $(this).attr('action'),
        dataType: 'script',
        data: $(this).serialize()
      });
      return false;
    });

    $('.ajax_get_form').submit(function() {
      $.ajax({
        type: 'GET',
        url: $(this).attr('action'),
        dataType: 'script',
        data: $(this).serialize()
      });
      return false;
    });
  
  });
  
  $.ajaxSetup({
   'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");}
  });

  $(document).ajaxSend(function(event, request, settings) {
    if (typeof(AUTH_TOKEN) == "undefined") return;
    settings.data = settings.data || "";
    settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
  });

  $.fn.delay = function(time,func) {
    this.each(function() { setTimeout(func,time); });
  };
  $.fn.replace = function(o) { return this.after(o).remove(); }; 

})(jQuery);

/* lure */
jQuery.fn.lure = function(text){
  return jQuery(this).each(function(){
    var default_text = text || $(this).addClass('lure').val();
    $(this).data('lure_text', default_text);
    var current_text = $(this).val();
    if (!current_text && default_text || (current_text == text)){
      $(this).val(default_text).addClass("lure");
    }
    var clear_fn = function(){
      if ($(this).val() == default_text){
        $(this).val('').removeClass("lure");
      }
    };
    var show_fn = function(){
      if (!$(this).val()){
        $(this).val(default_text).addClass("lure");
      }
    }
    jQuery(this).click(clear_fn).focus(clear_fn).blur(show_fn);
  });
};

jQuery.fn.lured_val = function(){
  var $input = $(this);
  if ($input.val() == $input.data('lure_text')){
    return "";
  }
  return $input.val();
}

function close_welcome() {
  $('#welcome').effect('blind');
  Cookie.set("visited_home", true);
}

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};