//fire event observers when the page loads
Event.observe(window,'load', function(){
  observe_social_media_icons();
  observe_video_thumbnails();
  observe_tools();
});

function observe_tools(){
	try {
  	var tools = $('hidden_tools').select('.tool_container');
  }catch(e){
		return;
	}
  tools.each(function(tool){
    var tool_content = tool.select('.tool_content').first()
    if(!tool_content) return;
    var padding = parseFloat(tool.select('.tool_button').first().getStyle('paddingBottom'));
    tool.observe('mouseenter', function(e){
      tool_content.appear({to:0.9, duration:0.2});
      tool.select('.tool_button').first().setStyle({'paddingBottom':(padding+4)+'px'});
    });
    tool.observe('mouseleave', function(e){
      tool_content.fade({duration:0.2});
      tool.select('.tool_button').first().setStyle({'paddingBottom':(padding)+'px'});
    });
  });
}

function observe_video_thumbnails(){
  //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;
  }
}
function observe_social_media_icons(){
  try{var social = $('social_network_icons')}catch(e){}
  
  //observe events over the social networking footer icons
  if(social){
    var icons = social.select('.social_icon');

    //show the hint 'bubbles'
    icons.each(function(i){
      i.observe('mouseenter', function(){
        if(i.hasClassName('active_hint')) return false;
        i.addClassName('active_hint');

        var hint = i.select('.icon_hint_container').first();
        var start_pos = -hint.getHeight()+12;
        
        hint.appear({duration:0.4});
        new Effect.Tween(hint.identify(), start_pos, start_pos-21, {duration:0.2}, function(p){
          hint.setStyle({'top':p.toFixed(0)+'px'});
        })
      })

      //hide 'em using the reverse of the above effects
      i.observe('mouseleave', function(){
        i.removeClassName('active_hint');
        var hint = i.select('.icon_hint_container').first();
        var start_pos = -hint.getHeight()+12;
        
        hint.fade({duration:0.2});
      })
    })
  }
}
function switch_to(child){
	var parent = $(child).up();
	hide_current(child);
}
//helpers
function hide_current(c){
	$(c).up().select('.video_column').each(function(e){
		if(e.getStyle('display')==='block'){
			e.hide();
		}
	})
	$(c).appear();
}
//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(cookie,value,expires){
  //create date
  var today = new Date(); today.setTime(today.getTime());
  var cookie_expires = new Date(today.getTime() + (1000 * 60 * 60 * (24*expires)));

  document.cookie = cookie + "=" + value + ";expires='" + cookie_expires.toGMTString() +"';path=/";
}
//the url will be updated when the user clicks ajax links, ie:
//www.foo.bar/#variable_1=1;variable_2 
//
//the calls to eval() below are to dynamically create RegExp objects with
//the variables passed into their parent functions
function get_url_variable(return_variable){
  var vars = String(document.location).split("#")[1];
  var retval = null;
  if(vars){
    var split_vars = vars.split(";");
    split_vars.each(function(v){
      //vars would be something like foo=bar;biz=boz, this eval'd regex will return
      //the variable (return_variable) passed into the function. so if we got called with
      //'foo', we'd be returning 'bar' here.
      var re = eval("/(^|;)"+return_variable+"=(\\d+)/.exec(vars)");
      if(re && re.length>0){
        retval = re.last();
      }   
    }); 
  }
  return retval;
}
//update the #url variable to a given value
function set_url_variable(set_variable, to){
  var url = String(document.location);
  var vars = url.split("#")[1];
  var set_to = ';' + set_variable + '=' + to; 

  if(vars){
    if(get_url_javascript_variable(set_variable)){
      eval("var new_url = vars.gsub(/(^|;)" + set_variable + "=(\\d+)/, set_to)");
    }else{
      var new_url = vars + ";" + set_variable + "=" + to; 
    }   
    var new_url = document.location = url.split("#")[0] + "#" + new_url;
  }else{
    var new_url = String(document.location).split("#")[0] = url + "#" + set_variable + "=" + to; 
  }
  var set = String(document.location).split("#")[1];
}
//extend Array class so we can get a bool returned from
//expressions like: [1,2,3,4].has_member(4) => true; [1,2].has_member(4) => false
Object.extend(Array.prototype, {
  has_member: function(m){
    if(this.indexOf(m)>=0){
      return true;
    }else{
      return false;
    }
  }
});
