// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// some custom methods
Element.addMethods({
  //create mouseenter and mouseleave events (these don't bubble, like mouseover/mouseout)
  onmouseenter: function(element,observer) {
      element = $(element);
      element.observe('mouseover',function(evt,currentTarget) {
          var relatedTarget = $(evt.relatedTarget || evt.fromElement);
          if(relatedTarget && relatedTarget!=currentTarget &&  relatedTarget.childOf(currentTarget)==false ) {
              observer();
          }else{
            observer();
          }
      }.bindAsEventListener({},element));
      return element;
  }, onmouseleave: function(element,observer) {
      element = $(element);
      element.observe('mouseout',function(evt,currentTarget) {
          var relatedTarget = $(evt.relatedTarget || evt.toElement);
          try{
            if(relatedTarget!=currentTarget && relatedTarget.childOf(currentTarget)==false ) {
                observer();
            }
          }catch(err){
	  //
          }
      }.bindAsEventListener({},element));
      return element;
  }
});

//convenient log method - outputs to firebug console
function log(msg, type){
  var prefix = 'LOG: ';
  switch(type){
    case 'i': prefix = 'INFO: '
    break;
    case 'w' : prefix = 'WARNING: '
    break;
    default : prefix = 'LOG: ' 
  }
  try{
    if(console.log){
      console.log(prefix + msg)
    }else if(window.console){
      window.console.log(prefix + msg)
    }else{
      try{console.log(prefix + msg)}catch(err){}
    }
  }catch(e){
  }
}

//set cookie with value, to expire in n days
function set_cookie(name,value,days){
  var today = new Date(); today.setTime(today.getTime());
  var cookie_expires = new Date(today.getTime() + (1000 * 60 * 60 * 24));
  document.cookie = name + '=' + value + '; expires=' + cookie_expires.toGMTString() + ';path=/';
}

function updateActiveThumbnail(frame, video_id){
  var token = $('token').innerHTML.replace(/<\/?[^>]*(>|$)/g,'');
  var duration = parseFloat($('video_duration').innerHTML.replace(/<\/?[^>]*(>|$)/g,''));
  if(frame <= duration){
    new Ajax.Updater("thumbnail_edit_examples","/videos/generate_thumb",{parameters: {authenticity_token:encodeURIComponent(token), "frame_num":frame, id:video_id}});
  }
}

Event.observe(window,'load',function(){
  if($("layout_link_buttons")){
    Element.observe('layout_list','click',function(e){
      log("clicked 'list'");
      var videos = $("videos").select('.video');
      videos.each(function(v){ v.removeClassName('layout_grid')});
      videos.each(function(v){ v.addClassName('layout_list')});
      set_cookie('video_view','l',2);
      $('layout_grid').removeClassName('active_layout_link');
      $('layout_list').addClassName('active_layout_link');
    });
    Element.observe('layout_grid','click',function(e){
      log("clicked 'grid'");
      var videos = $("videos").select('.video');
      videos.each(function(v){ v.removeClassName('layout_list')});
      videos.each(function(v){ v.addClassName('layout_grid')});
      set_cookie('video_view','g',2);
      $('layout_list').removeClassName('active_layout_link');
      $('layout_grid').addClassName('active_layout_link');
    });
  }

  if($('asset[active]')){
  Element.observe("asset[active]",'click',function(e){
    var state = $('asset[active]').checked;
  
    if(state==true){
      Form.Element.enable('asset[active_from]');
      Form.Element.enable('asset[active_to]');
    }else{
      Form.Element.disable('asset[active_from]');
      Form.Element.disable('asset[active_to]');
    }
  });}

  //will return a thumbnail for a user on the video edit screen
  if($('thumbnail_frame_render_button')){
    $('thumbnail_frame_render_button').observe('click', function(e){
      var frame = parseFloat($('video_thumbnail_frame').value);
      var duration = parseFloat($('video_duration').innerHTML.replace(/<\/?[^>]*(>|$)/g,''));
      var video_id = $('video_id').innerHTML.replace(/<\/?[^>]*(>|$)/g,'');
      if(frame <= duration){
        updateActiveThumbnail(frame, video_id)
      }
    });
  }
  //will toggle the chosen thumbnail on the video publish screen
  if($('temp_thumbnails')){
  var images = $('temp_thumbnails').select('img');
  images.each(function(i){
    $(i).observe('click',function(e){
      if($(i).hasClassName("active_thumbnail")){
        return false;
      }else{
        $('temp_thumbnails').select('[class="thumbnail active_thumbnail"]').each(function(i){$(i).removeClassName("active_thumbnail")});
        $(i).addClassName("active_thumbnail");
        $('thumbnail_frame').value = $(i).id;
        }
      });
    });
  
    //observe tag clicks
    var available = new Array;
    var current = new Array;
    $('tags_available_active').select('a.tag_available').each(function(t){
      $(t.id).observe('click', function(){addTagToCurrent(t)});
    });
    //observe current tags
    observeCurrent();
  }
  //will remove a selected tag on the video edit/publish screen
  function observeCurrent(){
    $('tags_current_active').select('a.tag_current').each(function(t){
      $(t.id).observe('click', function(){removeTagFromCurrent(t)});
    });
  }
  function addTagToCurrent(tag){
    var current_members = new Array;
    $('tags_current_active').select('a.tag_current').each(function(t){current_members.push(t.id)});

    //if we dont already have this tag, put it in the right place
    if(current_members.indexOf(tag.id)==-1){
      $('tag_ids').value += tag.id +", ";
      $('tags_current_active').insert(build_tag(tag));
    }
    observeCurrent();
  }
  function removeTagFromCurrent(tag){
    var current_members = new Array;
    var current_ids = $('tag_ids').value;
    $('tag_ids').value = current_ids.gsub(tag.id+",","");
    log("UPDATED TAGIDS: " + $('tag_ids').value);

    $('tags_current_active').select('a.tag_current').each(function(t){
      if(tag.id!=t.id){
        current_members.push(build_tag(t));
      }
    });
    $('tags_current_active').replace('<div id="tags_current_active"></div>');
    $('tags_current_active').insert(current_members.join(" "));
    var ccurrent_ids = $('tag_ids').value;
    observeCurrent();
  }
  function build_tag(tag){
    var element = '<a href="javascript:return false;" class="tag_current" id="' + tag.id + '">' + tag.innerHTML + '</a> ';
    return element;
  }

  if($('asset_channel')){
    new Form.Element.EventObserver('asset_channel',function(){
      if($F('asset_channel')>0)
        enable_button();
      else
        disable_button();
    });
  }
  function enable_button(){
    $('btn_publish').value = "Save video & metadata";
    Form.Element.enable('btn_publish');
  }
  function disable_button(){
    $('btn_publish').value = "Select a channel";
    Form.Element.disable('btn_publish');
  }

  if($('starsCont')){
    var ratings = $('starsCont').select('[class="inline star"]');
    var token = $('token').innerHTML.replace(/<\/?[^>]*(>|$)/g,'');
    var video = $('video_id').innerHTML.replace(/<\/?[^>]*(>|$)/g,'');
    ratings.each(function(e){
      var d = e.id;
      $(d).observe('click', function(event){
        var rating = d.split("_")[1];
        log("CLICKED STAR: " + d);
        new Ajax.Request('/videos/rate',{asynchronous:true,evalScripts:true,parameters:{authenticity_token:encodeURIComponent(token),new_rating:rating,video_id:video} });
      });
    });
  }

  // homepage effects
  // the hp_ function name convention means hp_Foo is a home page helper
  if($('featuredContent')){
    $("featuredContentRightBtn").observe('click', function(){
      observe_verButtons('right', 'featuredContent');
    });
    $("featuredContentLeftBtn").observe('click', function(){
      observe_verButtons('left', 'featuredContent');
    });
    $("playlistContentRightBtn").observe('click', function(){
      observe_verButtons('right', 'playlistContent');
    })
    $("playlistContentLeftBtn").observe('click', function(){
      observe_verButtons('left', 'playlistContent');
    })

    function observe_verButtons(direction, label){
      var containerLabel = label+"Carrousel";
      var leftBtnLabel = label+"LeftBtn";
      var rightBtnLabel = label+"RightBtn";
      
      var currentPos = parseFloat($(containerLabel).up().scrollLeft);
      var visibleArea = parseFloat($(containerLabel).up().getWidth());
      var totalWidth = 0;
      var videos = $(containerLabel).select('.video_latest');
      videos.each(function(e){totalWidth+=(getVideoWidth(e))});
      var scrollDistance = getVideoWidth(videos.first()) * 4;
      set_cookie('scroll_width', scrollDistance, 1);

      if(direction=="left"){
        to=currentPos-scrollDistance;
        if(currentPos > 0){
          performSlide('horizontal', $(containerLabel).up().identify(), currentPos, to);
          $(rightBtnLabel).addClassName('vertButtonActive');
          $(rightBtnLabel).removeClassName('vertButtonInactive');
        }else{
          $(rightBtnLabel).addClassName('vertButtonActive');
          $(leftBtnLabel).addClassName('vertButtonInactive');
          $(leftBtnLabel).removeClassName('vertButtonActive');
        }    
        if((currentPos-scrollDistance)<=0){
          $(leftBtnLabel).addClassName('vertButtonInactive');
          $(leftBtnLabel).removeClassName('vertButtonActive');
        }
      }else{
        to=currentPos+scrollDistance;
        if(currentPos < (totalWidth-visibleArea)){
          performSlide('horizontal', $(containerLabel).up().identify(), currentPos, to);
          $(leftBtnLabel).addClassName('vertButtonActive');
          $(leftBtnLabel).removeClassName('vertButtonInactive');
        }else{
          $(rightBtnLabel).addClassName('vertButtonInactive');
          $(rightBtnLabel).removeClassName('vertButtonActive');
          $(leftBtnLabel).addClassName('vertButtonActive');
        }   

        var diff = parseFloat(visibleArea%scrollDistance);
        if((to+scrollDistance+diff)==totalWidth){
          $(rightBtnLabel).addClassName('vertButtonInactive');
          $(rightBtnLabel).removeClassName('vertButtonActive');
        }
        if(((currentPos+scrollDistance)+visibleArea - (visibleArea%scrollDistance))>totalWidth){
          $(rightBtnLabel).addClassName('vertButtonInactive');
          $(rightBtnLabel).removeClassName('vertButtonActive');
        }
      }
    }
	
	function getVideoWidth(node){
		var width = parseFloat(node.getWidth()) + parseFloat(node.getStyle('margin-left')) + parseFloat(node.getStyle('margin-right'));
		return width;
	}
  }

  if($('latestContent')){
	$("latestContentDownBtn").observe('click', function(){
	  observe_buttons('down', 'latestContentUpBtn', 'latestContentDownBtn', 'latestContentCarrousel');
    });
    $("latestContentUpBtn").observe('click', function(){
      observe_buttons('up', 'latestContentUpBtn', 'latestContentDownBtn', 'latestContentCarrousel');
    });
  }
  
  if($('hitsContent')){
	$("hitsContentDownBtn").observe('click', function(){
	  observe_buttons('down', 'hitsContentUpBtn', 'hitsContentDownBtn', 'hitsContentCarrousel');
    });
    $("hitsContentUpBtn").observe('click', function(){
      observe_buttons('up', 'hitsContentUpBtn', 'hitsContentDownBtn', 'hitsContentCarrousel');
    });
  }
  
  if($('relatedContent')){
	$("relatedContentDownBtn").observe('click', function(){
	  observe_buttons('down', 'relatedContentUpBtn', 'relatedContentDownBtn', 'relatedContentCarrousel');
    });
    $("relatedContentUpBtn").observe('click', function(){
      observe_buttons('up', 'relatedContentUpBtn', 'relatedContentDownBtn', 'relatedContentCarrousel');
    });
  }
  
function observe_buttons(direction, upBtn, downBtn, carrousel){
	
  var currentPos = parseFloat($(carrousel).up().scrollTop);
  var visibleArea = parseFloat($(carrousel).up().getHeight());
  var totalHeight = 0;
  var videos = $(carrousel).select('.video_latest');
  videos.each(function(e){totalHeight+=getVideoHeight(e)});
  var scrollDistance = getVideoHeight(videos.first()) * 3;
  set_cookie('scroll_height', scrollDistance, 1);

  if(direction=="up"){
	to=currentPos-scrollDistance;
	if(currentPos > 0){
	  performSlide('vertical', $(carrousel).up().identify(), currentPos, to);
	  $(downBtn).addClassName('horButtonActive');
	  $(downBtn).removeClassName('horButtonInactive');
	}else{
	  $(downBtn).addClassName('horButtonActive');
	  $(upBtn).addClassName('horButtonInactive');
	  $(upBtn).removeClassName('horButtonActive');
	}    
	if((currentPos-scrollDistance)<=0){
	  $(upBtn).addClassName('horButtonInactive');
	  $(upBtn).removeClassName('horButtonActive');
	}
  }else{
	to=currentPos+scrollDistance;
	if(currentPos < (totalHeight-visibleArea)){
	  performSlide('vertical', $(carrousel).up().identify(), currentPos, to);
	  $(upBtn).addClassName('horButtonActive');
	  $(upBtn).removeClassName('horButtonInactive');
	}else{
	  $(downBtn).addClassName('horButtonInactive');
	  $(downBtn).removeClassName('horButtonActive');
	  $(upBtn).addClassName('horButtonActive');
	}   
	
	var diff = parseFloat(visibleArea%scrollDistance);
	if((to+scrollDistance+diff)==totalHeight){
	  $(downBtn).addClassName('horButtonInactive');
	  $(downBtn).removeClassName('horButtonActive');
	}
	if(((currentPos+scrollDistance)+visibleArea)>totalHeight){
	  $(downBtn).addClassName('horButtonInactive');
	  $(downBtn).removeClassName('horButtonActive');
	}
  }
  
  function getVideoHeight(node){
  	var height = parseFloat(node.getHeight()) + parseFloat(node.getStyle('margin-top')) + parseFloat(node.getStyle('margin-bottom'));
	return height;
  } 
  }
});

function performSlide(orientation, divid, from, to, duration){
  if(typeof(duration)=="undefined"){
    var dur = 1;
  }else{ 
    var dur = duration;
  }
  
  if(to < 0) to = 0;
  set_cookie($(divid).up().identify(), to, 1);
  new Effect.Tween(divid, from, to, {duration: dur}, function(p){
    if(orientation=="horizontal"){
      $(divid).scrollLeft = p.toFixed(0);
    }else{
      $(divid).scrollTop = p.toFixed(0);
    }
  });
}

//returns the height of a div with the margin and borders added
//the 'real' height of a node is its style width and the left/right padding/margin
function getRealHeightOf(node){
  var height = 0 ;
  ['height','padding-top','padding-bottom','margin-top','margin-bottom','border-top-width','border-bottom-width'].each(function(s){
    height += parseFloat($(node).getStyle(s)) + 0;
  });
  return height;
}
function checkClassName(theId){
  if( $(theId).up().hasClassName("layout_list")){
    return false;
  }else{
    return true;
    }
}
function showInfo(id){
  if(checkClassName(id)) {
    $(id).setStyle({'display':'none','visibility':'visible'});
    Effect.Appear(id, {'to':0.7, 'duration':0.5});
  }
}
function hideInfo(id){
  document.getElementById(id).style.visibility = 'hidden';
}

function switchFeaturedTo(type){
  var hide = (type=="playlist") ? "playlist" : "highlighted";
  if(hide=="playlist"){
    var show = $('featuredContentPL');
    var hide = $('featuredContent');
  }else{
    var show = $('featuredContent');
    var hide = $('featuredContentPL');
  }
  //new Effect.Parallel([hide.fade(), show.appear()]);
  show.setStyle({'display':'block','visibility':'hidden'});
  hide.hide();
  show.setOpacity(0);
  show.setStyle({'visibility':'visible'});
  show.appear();
  
  set_cookie('featured_column', type, 2);
}

function switchSpotlightTo(type){
  var opts = ["spot_spot","spot_night", "spot_day"];

  switch(type){
    case "day": hide = ["spot_spot", "spot_night"]; break;
    case "night": hide = ["spot_spot", "spot_day"]; break;
    case "spot": hide = ["spot_night", "spot_day"]; break;
  }
  var show = opts.collect(function(i){ if(hide.indexOf(i)===-1) return i}).compact().first();
  hide.each(function(h){$(h).fade({duration:0.2})});
  $(show).appear({duration:0.2, delay:0.2});
  set_cookie(show, type, 1);
}
