// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var podsMenu = null;
document.onmouseup=function(e) {
  // When user clicks off of the pods menu, hide it
  e = e || event;
  target = Event.element(e);
  if (e != null && target != null && target.id != 'arrow' && target.className != 'arrow')
  {
    if (podsMenu != null)
    {
      Element.hide('pods_iframe');
      Element.hide(podsMenu);
      podsMenu = null;
    }
  }
}
//addLoadEvent(function() {$('pods_iframe').style.display="block"});

function preserveAjaxState(request, element_id)
{
  var field = $('preserve_ajax_state_' + element_id);
  
  if (field != null)
  {
    field.value = request.responseText;
  }  
}

function restoreAjaxState(element_id)
{
  var field = $('preserve_ajax_state_' + element_id);
  
  if (field != null)
  {
    //url = field.value
    //new Ajax.Updater(element_id, url, {asynchronous:true});
    if (field.value != null && field.value != '')
      $(element_id).innerHTML = field.value;
  }
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
function writeIfIE(text,alt)
{
    if (BrowserDetect.browser == 'Explorer') {
        document.writeln(text);
    } else {
        document.writeln(alt);
    }
}

var highlighted_id = 0;

function ShowAddCategoryControl()
{
    add_category = $('add_category');
    add_category.show();
    $('category_title').value = '';
    $('category_title').focus();
}

function CategoryAddComplete()
{
  $('add_category').hide();
}

// Called to display the Add Tag AJAX control
function ShowAddTagControl()
{
    add_category = $('add_tag');
    add_category.show();
    $('tag_title').value = '';
    $('tag_title').focus();
}

// Called to hide the add tag AJAX control
function TagAddComplete()
{
  $('add_tag').hide();
}

function CancelReview(video_poly_id)
{
  FCKeditorAPI = null;
  __FCKeditorNS = null;
  CloseVideoPopout(video_poly_id);
  
  return false;
}

function chooseFramegrab(framegrab_id)
{
  sel = $('framegrab_id').value;
  if (sel != '' && $('framegrab_' + sel)) {
    $('framegrab_' + sel).className = 'pick_framegrab';
  }
  $('framegrab_id').value = framegrab_id;
  $('framegrab_' + framegrab_id).className = 'framegrab_selected';
}

function CloseVideoPopout(video_poly_id)
{
  //new Ajax.Updater('embed_container', '/video/video_object/?poly_id=' + video_poly_id, {asynchronous:true, evalScripts:true}); return false;
  ShowVideoPlayer();
  return false;
}

function HideVideoPlayer()
{
  $('player_container').style.display = 'none';
}
function ShowVideoPlayer()
{
  $('player_container').style.display = 'block';
  $('embed_secondary_container').style.display = 'none';
  $('embed_secondary_container').innerHTML = '';
  $('embed_secondary_container').style.display = 'block';
}

/*
function FlyoutShowYouBox(box_id)
{
  //Effect.BlindDown(box_id);
  $(box_id).style.visibility = "visible";
}

function HideShowYouBox(box_id)
{
  $(box_id).style.visibility = "hidden";
}
*/

function showNextVideos()
{
  new Effect.Move('list', { x: -297, y: 0, transition: Effect.Transitions.sinoidal });
  
  return false;
}
function showPreviousVideos()
{
  new Effect.Move('list', { x: 297, y: 0, transition: Effect.Transitions.sinoidal });
  
  return false;
}

function ShowDialog(url)
{
  
  Dialog.alert({url:url, options: {method: 'get'}}, {windowParameters: {className: "alphacube", width:440}, okLabel: "Cancel"});
  
  return false;
}

function selectImportedVideo(id, url, thumbnail_url, title, description)
{
  /*url_field = Builder.node('input', {type:'text', id: 'url_'+id});
  url_field.value = url;
  $('import_form').appendChild(url_field);
  */
  /*$('import_url').value = url;
  $('import_thumbnail_url').value = thumbnail_url;
  $('import_title').value = title;
  $('import_description').value = description;*/
}

function HideElementsByClass(cls)
{
  elts = getElementsByClass(cls)
  for( var i = 0; i < elts.length; i++ ){
    elts[i].style.visibility = "hidden"
  }
}

function findImages(query, page, script_id, target_id)
{
  if (query)
  {
    start = (page-1)*10;
    $('json_container').src='http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=' + query + '&results=40&start=' + start + '&output=json&callback=handleYahooImageResults' + target_id;
  }
}
function handleYahooImageResults1(json_result)
{
    handleYahooImageResults(json_result, 1)
}
function handleYahooImageResults2(json_result)
{
    handleYahooImageResults(json_result, 2)
}
function handleYahooImageResults3(json_result)
{
    handleYahooImageResults(json_result, 3)
}

function handleYahooImageResults(json_result,target_id)
{
  // Clear the image result container
  $('image_result_container').innerHTML = '';
  
  for(i=0;i<json_result.ResultSet.totalResultsReturned;i++)
  {
    result = json_result.ResultSet.Result[i];
    
    img_node = Builder.node('img', {src:result.Thumbnail.Url, style:'padding:3px;'})

    img_href_node = Builder.node('a', {href:'javascript:imageSelected' + target_id + '(\'' + result.Url + '\')'})
    img_href_node.appendChild(img_node);
    //title_node = Builder.node('p', [result.Title]);
    //img_container_node.appendChild(title_node);
    
    $('image_result_container').appendChild(img_href_node);
  } 
  
  node = $('json_container').parentNode;
  Element.remove('json_container');
  node.appendChild(Builder.node('script', {id:'json_container'}));
  
  // Add next/previous buttons
  //next_href_node = Builder.node('a', [href:'javascript:findImages()']);
}

function imageSelected1(url)
{
  imageSelected(url, 1)
}

function imageSelected2(url)
{
  imageSelected(url, 2)
}

function imageSelected3(url)
{
  imageSelected(url, 3)
}

function imageSelected(url, target_id)
{
  id = 'yahoo_image_url' + target_id
  $(id).value = url;
  try {
    $(id).onchange();
  } catch (err) {
  }
  Dialog.closeInfo();
}

// DOM Helper methods
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function disableForm(form)
{
    var children = $(form).getElementsByTagName('input');
    for( var i = 0; i < children.length; i++ ) {
        children[i].disabled = true
    }
}

function enableForm(form)
{
    var children = $(form).getElementsByTagName('input');
    for( var i = 0; i < children.length; i++ ) {
        children[i].disabled = false
    }
}

/* Random Procedures */

/* grab Elements from the DOM by className */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function showTab(id)
{
    document.getElementById('inbox').style.display = 'none';
    document.getElementById('videos').style.display = 'none';
    document.getElementById('groups').style.display = 'none';
    document.getElementById('locker').style.display = 'none';
    document.getElementById('favoritevids').style.display = 'none';
    document.getElementById('favoriteusers').style.display = 'none';
    
    document.getElementById(id).style.display='block'
    //deleteCookie('account_tab');
    setCookie('account_tab', id, 1);
}

function restoreTab()
{
    var tabId = getCookie('account_tab');
    if( tabId ){
        showTab(tabId);
    }
}

/* get, set, and delete cookies */
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
	
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
	
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/* window 'load' attachment */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function HoverRow(id, className)
{
  if (highlighted_id == null){
    highlighted_id = 0
  }
  if (id == highlighted_id)
    return false;
  
  // Unhighlighted old item
  // Don't unhighlight if it has video details being shown
  if($('list_item_' + highlighted_id))
  {
    if ($('row_details_'+highlighted_id).style.display == 'none')
    {
      $('list_item_' + highlighted_id).className = className;
      $('info_link_' + highlighted_id).style.display = 'none';
    }
  }
  
  $('list_item_' + id).className = className + ' ' + className + '_hover';
  if ($('hide_info_link_' + id).style.display != 'block')
  {
    $('info_link_' + id).style.display = 'block';
  }

  highlighted_id = id;
}

function ShowRowInfo(id, className)
{
  //new Effect.BlindDown('row_details_' + id, {duration:0.3});
  Element.show('row_details_' + id);
  $('hide_info_link_' + id).style.display='block';
  $('info_link_' + id).style.display='none';
  $('list_item_' + id).className = className + ' ' + className + '_hover';
  
  return false;
}

function HideRowInfo(id)
{
  new Effect.BlindUp('row_details_' + id, {duration:0.3});
  $('hide_info_link_' + id).style.display='none';
  $('info_link_' + id).style.display='block';
  //$('video_list_item_' + id).className = 'video';
  
  return false;
}

function highlight_rating(rating)
{
  for(i = 1; i <= rating; i++)
  {
    $('rating_' + i).src = '/images/rating_full.gif';
  }
  for(j=parseInt(rating)+1; j <= 10; j++)
  {
    $('rating_' + j).src = '/images/rating_empty.gif';
  }
  
  $('rater_label').innerHTML = rating + ".0";
  /*$('review_rating').value = rating;*/
}

function unhighlight_rating(rating)
{
  current_rating = parseInt($('rating').value) || 0;
  for(i = 1; i <= current_rating; i++)
  {
    $('rating_' + i).src = '/images/rating_full.gif';
  }
  /*
  if (current_rating>=i+0.5 && current_rating<i+1 )
  {
    $('rating_' + i+1).src = '/images/rating_half.gif';
  }*/
  
  for(j=current_rating+1; j <= 10; j++)
  {
    $('rating_' + j).src = '/images/rating_empty.gif';
  }
  
  $('rater_label').innerHTML = $('rating').value || 0;
}

function select_rating(rating)
{
  $('rating').value = rating;
  
  $('rate_video').onsubmit();
  
  return false;
}

function disableAnchor(obj, disable)
{
  if(disable){
    var href = obj.getAttribute("href");
    if(href && href != "" && href != null){
       obj.setAttribute('href_bak', href);
    }
    obj.removeAttribute('href');
    obj.setAttribute('href_color', obj.style.color);
    obj.style.color="gray";
  }
  else{
    obj.setAttribute('href', obj.attributes['href_bak'].nodeValue);
    obj.style.color=obj.getAttribute('href_color');
  }
}

// Used to report that the user has clicked a download link so that 
// we can record the fact of the download
function report_download(url,user_id,video_id,format)
{
    var pars = 'user_id=' + user_id + '&video_id=' + video_id + '&format=' + format;
    new Ajax.Request(url, 
                       {
                        method: 'get',
                        parameters: pars
                       });
}

function showUploadProgress()
{
  $('progress').style.display='block';
  $('upload_form').style.display='none';
  $('submitbutton').disabled = true;
}

function editVideo(edit_url)
{
  window.opener.location = edit_url;
  window.close();
}

function MultiPowUpload_onCompleteAbsolute(type, uploadedBytes)
{
  invokeUploadComplete();
}
function MultiPowUpload_onProgress(type, fileIndex, fileBytesLoaded, fileBytesLength, 
                                  totalBytesLoaded, totalBytesLength) 
{
  percent = parseInt((totalBytesLoaded * 100)/totalBytesLength);
  document.title = 'Vodpod: ' + percent + '%';
  if (percent == 100) {
    $('finishing_upload').style.visibility = "visible";
    setTimeout('enableFinishButton()', 30000);
  }
}
function enableFinishButton()
{
  $('finish_button').style.visibility = 'visible';
}

/*
function maximizeVideo()
{
  var width, height;
  
  width = document.documentElement.clientWidth;
  
  if (self.innerHeight) // all except Explorer
  {
  	//width = self.innerWidth;
  	height = self.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientHeight)
  	// Explorer 6 Strict Mode
  {
  	//width = document.documentElement.clientWidth;
  	height = document.documentElement.clientHeight;
  }
  else if (document.body) // other Explorers
  {
  	//width = document.body.clientWidth;
  	height = document.body.clientHeight;
  }
  
  $('maximized_video_container').style.left = '0px';
  $('maximized_video_container').style.top = '0px';
  $('maximized_video_container').style.width = width + 'px';
  $('maximized_video_container').style.height = height + 'px';
  $('maximized_embed_container').style.width = width-30 + 'px';
  $('maximized_embed_container').style.height = height + 'px';
  
  nodes = $('embed_holder').childNodes;
  for(i=0;i<nodes.length;i++)
  {
    if (nodes[i].tagName == 'OBJECT' || nodes[i].tagName == 'EMBED')
    {
      embed = nodes[i];
      break;
    }
  }
  $('maximized_embed_container').appendChild(embed);
  $('maximized_video_container').style.display = 'block';
  Element.scrollTo(document.body);
}

function minimizeVideo()
{
  embed=$('maximized_embed_container').childNodes[0];
  $('embed_holder').appendChild(embed);
  $('maximized_video_container').style.display = 'none';
}*/

function highlightStep(step_no)
{
  try
  {
    $('step1').className = 'step';
    $('step2').className = 'step';
    $('step3').className = 'step';
  } catch(e) {}
  
  $('step' + step_no).className = 'step active';
}

function highlightVideo(id)
{
  video_els = document.getElementsByClassName('video');
  
  for(i=0;i<video_els.length;i++)
  {
    video = video_els[i];
    if (id==video.id) {
      video.className='video highlighted_video';
    } else {
      video.className='video';
    }
  }
}

function handleEnter(e, func)
{
   var key;

   if(window.event){
        key = window.event.keyCode;     //IE
   } else {
        key = e.which;     //firefox
   }

   if(key == 13){
        func();
        return false;
   } else {
        return true;
   }
}

function addCategory()
{
  if ($('cat_title').value == '' || $('cat_title').value == 'ENTER A NEW CATEGORY')
  {
    alert('Please enter a category name');
    return false;
  }
  $('category_title').value=$('cat_title').value;
  $('add_category_form').onsubmit();
  return false;
}

function addCategoryHTML(response)
{
  category = eval('(' + response + ')');
  category_html = "<input type=\"checkbox\" name=\"categories[]\" id=\"categories[]\" value=\"" + category.attributes.id + "\" checked=\"checked\"/> " +
    category.attributes.title + "<br/>";
  $('categories').innerHTML = category_html + $('categories').innerHTML;
  try {
    $('no_cats_msg').innerHTML = '';
  } catch(exception) {} 
}

function stopSearchEmbed()
{
  elts = $('search_embed').getElementsByTagName('embed');
  if (elts && elts.length > 0 ){
    elts[0].src = 'http://';
  }
  $('search_embed').parentNode.removeChild($('search_embed'));
  Dialog.closeInfo();
}

function importSearchResult(title, url, embed)
{
  new Ajax.Updater('add_video_container', '/group/import_video?url=' + escape(url), {asynchronous:true, evalScripts:true});  
}

function pod_this(url)
{
  var x = (screen.width-660)/2;
  var y = (screen.height-630)/2;
  window.open(url, 'vodshare', 'toolbar=0,status=0,resizable=1,width=660,height=630,left='+x+',top='+y);
}

// Takes a link, and submits it's parent form
function submitParentForm(el, original_el)
{
  if (!original_el) {
    original_el = el;
  }
  el.color_back = el.style.color;
  el.style.color = '#deeacb';
  el.style.cursor = 'wait';
  var parent = el.parentNode;
  if (parent != null && parent.tagName == 'FORM')
  {
    // Call the parents on submit
    if (parent.onsubmit != null)
    {
      if(parent.onsubmit() == true)
      {
        parent.submit();
      } else {
        // reset the button
        original_el.style.cursor = '';
        original_el.style.color = original_el.color_back;
      }
    }
    else
    {
      parent.submit();
    }
  }
  else
  {
    submitParentForm(parent, original_el);
  }
}

function resetSubmitLink(el) {
    el.style.color = el.color_back;
    el.style.cursor = null;
}

function getGroupDetails(id, url)
{
  group_data = $('group_data_' + id);
  
  // Fetch the data
  if (Element.getNodeAttribute(group_data, 'has_data') == 'false')
  {
    new Ajax.Updater('group_data_' + id, url, {onSuccess:function(){Element.setNodeAttribute(group_data, 'has_data','true');showGroupDetails(id);},asynchronous:true} );
  } else {
    // Display the existing data
    showGroupDetails(id);
  }
}

function showGroupDetails(id)
{
  group_data = $('group_data_' + id);
  
  if (group_data.style.display == 'none')
    $('toggle_icon_'+id).src = '/images/minus.gif';
  else
    $('toggle_icon_'+id).src = '/images/plus.gif';
  
  new Effect.toggle(group_data, 'blind', {duration:0.3});  
}

function hoverGroupOver(header, id, color)
{
  header.style.background = color;
  //$('group_link_' + id).style.visibility = 'visible';
}

function hoverGroupOut(header, id, color)
{
  header.style.background = color;
  //$('group_link_' + id).style.visibility = 'hidden';
}

function hoverFeedVideo(feed, video_id)
{
  video_details = eval(feed + '[' + video_id + ']');
  $(feed + '_rank').innerHTML = video_details.rank;
  $(feed + '_video_href').href = video_details.url;
  $(feed + '_video_href').innerHTML = video_details.title;
  $(feed + '_group_href').href = video_details.group_url;
  $(feed + '_group_href').innerHTML = video_details.group_name;
}


Element.setNodeAttribute = function(element, name, value) {
  element = $(element);
  // Determine if this attribute exists
  if (element.attributes.getNamedItem(name) != null)
  {
    // Set the value
    element.attributes.getNamedItem(name).value = value;
    return element.attributes.getNamedItem(name);
  } else {
    // Create and set the attribute
    attr = document.createAttribute(name);
    attr.value = value;
    element.attributes.setNamedItem(attr);
    return attr;
  }
}
  
Element.getNodeAttribute = function(element, name) {
  element = $(element);
  if (element.attributes.getNamedItem(name) != null)
  {
    return element.attributes.getNamedItem(name).value;
  }
}

function hoverVideo(video_node, show) {
  var title_hover = video_node.select('.thumb_title_hover')[0];
  var title = video_node.select('.thumb_title')[0];
  var title_box = video_node.select('.thumb_title_box')[0];
  
  if (title_hover)
  {
    if (show && title_hover.style.display=='none')
    {
      Element.show(title_hover);
      Element.hide(title);
      Element.hide(title_box);
    } else {
      Element.hide(title_hover);
      Element.show(title);
      Element.show(title_box);
    }
  }
}

function embedClicked() {
  $('embed_cover_trigger').style.display = 'none';
  showVideo($('first_video_id').value);
}

function showToolTip(relativeElementId, tipElementId) {
    if ( $(relativeElementId) && $(tipElementId) ){
        var pos = Position.cumulativeOffset($(relativeElementId));
        //pos[0] = pos[0] + ($(relativeElementId).offsetWidth / 3);
        pos[1] = pos[1] + $(relativeElementId).offsetHeight;
        pos[0] = pos[0] - Position.positionedOffset($('wrapper'))[0];
        $(tipElementId).style.left = String(pos[0]) + "px";
        $(tipElementId).style.top = String(pos[1]) + "px";
        $(tipElementId).style.display = "inline";
    }
}

function hideToolTip(tipElementId) {
    if( $(tipElementId) ){
        $(tipElementId).style.display = "none";
    }
}

var search_object = {url : null, sites : null, query : null, page : 0, group_id : null, results_template : null};

function runSearch(sites, url, q,page,group_id,results_template,video_id) {
  //if (sites.length == 1 && sites[0] == 'vodpod') {
    // Shortcut for paging actions for vodpod search results
      //action = url.match("/search/widgetsearch") ? 'search/widgetsearch' : 'search/site_search'
  //    action = url;
  //    alert("Running vodpod search against url: " + action);
  //    new Ajax.Updater('vodpod', action + '?site=vodpod&q=' + escape(q) + '&p=' + page, 
  //      {asynchronous:true, evalScripts:true}); 
  //} else {
      search_object.page = page;
      search_object.url = url;
      search_object.sites = sites;
      search_object.query = escape(q);
      search_object.group_id = group_id;
      search_object.results_template = results_template;
      search_object.video_id = video_id;
      
      var script = document.createElement('script');
      script.src = '/javascripts/websearch.js?' + String(Math.random()*9999);
      $('footer').appendChild(script);
  //}
  return false;
}

function failSearch(site) {
    $(site + '_progress').innerHTML = "failed";
    $(site + '_progress').className = '';
}

function getFieldValue(id) {
  try {
    var result = null;
    if ($(id)){
        if ($(id).value) {
            result = $(id).value;
        } else {
            result = $(id).innerHTML;
        }
    }
    if (result == 'null') {
        result = null;
    }
    return result;
  } catch(e) {
    return null;
  }
}

function stripUtfEscapes(text) {
    if (text) {
        return text.replace(/\%u[0-9A-Za-z]{4}/g, '');
    } else {
        return null;
    }
}

function buildUrl(root, args_hash) {
    var res = '' + root + '?';
    for( var elt in args_hash ){
        var value = args_hash[elt];
        if (value) {
            res = res + elt + '=' + escape(value) + '&';
        }
    }
    return res;
}
var ptv_theme;

function activateSearchResult(result_id) {
    title = getFieldValue(result_id + '_title');
    desc = getFieldValue(result_id + '_desc');
    tags = getFieldValue(result_id + '_tags');
    url = getFieldValue(result_id + '_url');
    group_id = getFieldValue(result_id + '_group_id');
    vembed = getFieldValue(result_id + '_embed');
    img = $(result_id + '_img').src;
    height = getFieldValue(result_id + '_height');
    gvid = getFieldValue(result_id + '_gvid');
    if (gvid) {
        document.location = '/pod/show_video/' + gvid;
        return;
    }
    // Set the groupvideo_id if this is a Vodpod result...
    ptv_url = buildUrl('/site/search_ptv', 
        {t : title, d : desc, tags:tags, p : url, v : 3, id : group_id, em : vembed, image : img, ap : 1, h : height, gvid: gvid})
    if (ptv_theme) {
        ptv_url = ptv_url + 'theme=' + ptv_theme;
    }
    ptv_url = stripUtfEscapes(ptv_url);
    pod_this(ptv_url);
    return false;
}

function activateSearchBox(target,inputId) {
    $('search_target').value = target;
    if (target == 'videos') {
        $('search_videos').className = "highlight_green";
        $('search_pods').className = "";
    } else if (target == 'pods') {
        $('search_videos').className = "";
        $('search_pods').className = "highlight_green";
    }
}

function clearInput(inputField) {
    if (inputField.value.indexOf('>') == 0 ){
        inputField.value = '';
    }
}

// Turns a pod name into a valid subdomain name
function simplifyGroupName(name)
{
  if (name)
    return name.replace(/[^A-Za-z0-9\-]/g, '').toLowerCase()
    
  return ''
}

function switch_actions_panel(active) {
  if (active == 'login') {
    $('actions_top').style.display = 'none';
    $('actions_register').style.display = 'none';
    $('actions_login').style.display = 'block';
  } else {
      if (global_current_user) {
        $('actions_top').style.display = 'none';
        $('actions_' + active).style.display = 'block';
      } else {
        $('actions_top').style.display = 'none';
        if (active != 'send') {
            $('actions_register').style.display = 'block';
        } else {
            $('actions_register_send').style.display = 'block';
        }
      }
  }
}

function close_actions_panel(active) {
  if (global_current_user) {
    $('actions_' + active).style.display = 'none';
    $('actions_top').style.display = 'block';
  } else {
    $('actions_register').style.display = 'none';
    $('actions_register_send').style.display = 'none';
    $('actions_top').style.display = 'block';
  }
}

function clearDefaultFormFields() {
    var elts = document.getElementsByTagName('input');
    for( var i = 0; i < elts.length; i++ ){
        var inp = elts[i];
        if (inp.default_text && inp.value == inp.default_text) {
            inp.value = '';
        }
    }
}

function selectBlogTab(id)
{
    $$('.blog_tab').each(function(item) { item.style.fontWeight = 'normal'} );
    $(id).style.fontWeight = 'bold';
    $$('.help_tab').each(function(item) { item.style.backgroundColor = ''} );
    $('help_tab_' + id).style.backgroundColor = '#C1FBFF';
}

function disableSubmitButton(element)
{
  setTimeout(function() {element.disabled = true}, 50);
  Element.setOpacity(element, 0.5);
}

function enableSubmitButton(element)
{
  setTimeout(function() {element.disabled = false}, 50);
  Element.setOpacity(element, 1);
}

function disableImageButton(element)
{
  if (!element) {
    return;
  }
  setTimeout(function() {element.disabled = true}, 50);
  Element.setOpacity(element, 0.5);
}

function enableImageButton(element)
{
	if (!element) {
		return;
	}
  try {
    setTimeout(function() {element.disabled = false}, 50);
    element.style.opacity = 1.0;
    element.style.filter = "";
  } catch(e) {}
}

function disableRemixButton(element)
{
  Element.setNodeAttribute(element, 'saved_onclick', element.onclick);
  element.onclick = "return false";
  element.style.opacity = 0.5;
}

function enableRemixButton(element)
{
  element.style.opacity = 1.0;
  element.onclick = Element.getNodeAttribute(element, 'saved_onclick');
}

// Facebook functions

function fb_add_embed_code()
{
  var val = $('embed_url').value;
  ptv_theme = 'facebook';
  if (val) {
    if (val.indexOf('<embed') != -1 || val.indexOf('<EMBED') != -1 ) {
        // Looks like an embed code
        $('single_vid_embed').value = val;
        activateSearchResult('single_vid');
    } else {
        // Assume it's a url
        $('single_vid_url').value = val;
        activateSearchResult('single_vid');
    }
  }
}

// Local Background Job support
BackgroundJob = Class.create();

BackgroundJob.prototype = {
  url: null,
  update_id: null,
  job_id: null,
  progress_text: "in progress",
  frequency: 2,
  complete_func: null,
  failed_func: null,
  complete: false,
  
  initialize: function(options) {
    this.job_id = options.job;
    this.update_id = options.update;
    if (options.frequency) {
      this.frequency = options.frequency;
    }
    if (options.progress) {
      this.progress_text = options.progress;
    }
    if (options.complete) {
      this.complete_func = options.complete;
    }
    if (options.failed) {
      this.failed_func = options.failed;
    }
    var pe = new PeriodicalExecuter(this.pollJobStatus.bind(this), this.frequency);
  },
  
  pollJobStatus: function() {
    if (!this.complete) {
      new Ajax.Request('/shared/get_job_status/' + this.job_id,
                       {onComplete: this.processJobStatus.bind(this)} );
    }
  },
  
  processJobStatus: function(request) {
    var response = eval('(' + request.responseText + ')');
    if (response.status == 'complete') {
      this.complete = true;
      if (this.complete_func) {
        this.complete_func();
      } else {
        $(this.update_id).innerHTML = "complete";
      }
    } else if( response.status == 'failed') {
      this.complete = true;
      if (this.failed_func) {
        this.failed_func();
      } else {
        $(this.update_id).innerHTML = "failed";
      }
    } else {
      msg = response.message;
      if (!msg) {
        msg = '';
      }
      $(this.update_id).innerHTML = this.progress_text + ' ' + msg;
    }
  }
}

function validateSearch() {
  if ($('mature_box') && $('search_mature')) {
    if ($('mature_box').checked) {
      $('search_mature').value = "true";
    } else {
      $('search_mature').value = "false";
    }
  }
}

function check_uncheck(selecta, control) {
  var checkbox = document.getElementById(control);
  if(checkbox.checked == true) {
    $A(document.getElementsByClassName(selecta)).each(function(el) {el.checked=true});
  } else {
    $A(document.getElementsByClassName(selecta)).each(function(el) {el.checked=false});
  }
}

var action_tracker = null;
function track_event(path, options) {
  try {
  if (typeof(_gat) != "undefined") {
  	if (!action_tracker) {
      action_tracker = _gat._getTracker("UA-555813-7");
      action_tracker._initData();
  	}
  	if (options && options.setVar) {
  		action_tracker._setVar(options.setVar);
  	}
    action_tracker._trackPageview(path);
  }
  } catch(e) { }
}

function sizeText(container, size) {
  var text = container.innerHTML;
  var originalText = text;
  var fontSize = container.getStyle('font-size');
  
  div = Element.setStyle(document.createElement('div'), {
    position: 'absolute',
    right: '0px',
    bottom: '0px',
    height: '1.2em',
    fontSize: fontSize
  });

  div.innerHTML = text;
  container.parentNode.appendChild(div);
  var chopped = false;
  
  div.innerHTML = text;
    
  while (div.getDimensions().width > size) {
    text = text.substring(0, text.length - 2);
    div.innerHTML = text + '&hellip;';
    chopped = true;
  }
  
  if (chopped) {
    text = text.replace(/\s+$/,"") + '&hellip;'
    
    // Add a tooltip.
    if (typeof RemixTooltip != 'undefined') {
      new RemixTooltip(container, originalText);
    }
  }
  
  container.parentNode.removeChild(div);
  container.innerHTML = text;
}

function change_publish(elt) {
  var target = $F(elt);
  window.location = "/account/widgets/" + target;
}
