var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    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 toggleTab(action) {
  if($(action).style.display == 'none'){ $$('.hidden').each(function(s){Element.hide(s)}) };
  Element.toggle(action);
}

function popoutEmbed(hash, w, h, show_cache) {
  var casttvBarHeight = 30;
	open("/videos/popout/" + hash + "?w="+w+"&h="+h+"&show_cache=" + (show_cache ? 'true' : 'false'), hash,  "width="+(w+casttvBarHeight)+",height="+h+",status=no,toolbar=no,location=no,menubar=no,directories=no,resizable=1,scrollbars=no");
	if (embedTrack) {
		embedTrack(hash,'popout');
	}
}

function toggleEmbed(vid, cached, removed) {

  // For cached videos, use a special prefix (well, infix) on all DOM elements.
  prefix = cached ? 'cached_' : '';
  
  var div = $('embedcontent_' + prefix + vid);
  // var innerDiv = $('embedcontent_' + prefix + vid + '_inner');
  $$('.embed_div').each(function(e){
    if (e != div && e.toggleOn){
      e.toggle();
    }
  });
  
  div.toggle();
  
  // If user is toggling something other than the link last clicked on, we need to close that
  // last embed.
  if (toggleEmbed.prev_vid && ((vid != toggleEmbed.prev_vid) || (cached != toggleEmbed.prev_cached))) {
    var prev_prefix = toggleEmbed.prev_cached ? 'cached_' : '';
    var prev_link = $("text_toggle_" + prev_prefix + toggleEmbed.prev_vid);
    // We toggle big icon in cached case only if video is removed.
    var prev_big_icon = (!toggleEmbed.prev_cached || toggleEmbed.prev_removed) ? $("inset_" + toggleEmbed.prev_vid) : false;
    var prev_small_icon = $("icon_toggle_" + prev_prefix + toggleEmbed.prev_vid);
    if(prev_link) prev_link.innerHTML = (toggleEmbed.prev_cached ? 'watch cached video' : 'watch here');
  	if(prev_small_icon) prev_small_icon.src = "/images/plus.gif";
  	if(prev_big_icon) prev_big_icon.src = "/images/big_plus.gif";
    if(!toggleEmbed.prev_cached && prev_big_icon) prev_big_icon.src = "/images/big_plus.gif";
  	embedTrack(toggleEmbed.prev_vid, "close", (toggleEmbed.prev_cached ? 'cached=1' : ''));
  }
  
  // Toggle state for currently selected video.
  var link = $("text_toggle_" + prefix + vid);
  var big_icon = $("inset_" + vid);
  var small_icon = $("icon_toggle_" + prefix + vid);
  if (div.style.display == "none"){
    if (link) link.innerHTML = (cached ? 'watch cached video' : 'watch here');
	  if (small_icon) small_icon.src = "/images/plus.gif";
    if ((!cached || (cached && removed)) && big_icon) big_icon.src = "/images/big_plus.gif";
		embedTrack(vid, "close", (cached ? 'cached=1' : ''));
  } else {
    if (link) link.innerHTML = 'hide video';
	  if (small_icon) small_icon.src = "/images/minus.gif";
    if ((!cached || (cached && removed)) && big_icon) big_icon.src = "/images/big_minus.gif";
		embedTrack(vid, "open", (cached ? 'cached=1' : ''));
		scrollIntoView(div);
  }
  
  // Store info about the toggled video in a static var, so we can close it on next call to this function
  // if user starts toggling a different video.
  toggleEmbed.prev_vid = vid;
  toggleEmbed.prev_cached = cached;
  toggleEmbed.prev_removed = removed;
  
	return false;
}

function scrollIntoView(element){
  // desired position solves this equation:
  // scrollY + viewH = pos + eleH + padding

  var padding = 30;
  var scroll = document.viewport.getScrollOffsets().top;
  var viewH = document.viewport.getHeight();  
  var pos = element.cumulativeOffset().top
  var h = element.getHeight();
  var finalScroll = pos + h + padding - viewH;
  var delta = finalScroll - scroll;
  var i = 0;
  var steps = 10;
  var dt = 0.05;

  if(scroll < finalScroll) {
    new PeriodicalExecuter(function(pe) {
      window.scrollTo(0, easeInOut(i++, scroll, delta, steps));
      if(i >= steps) pe.stop();
    }, dt);
  }
}

function easeInOut (t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
}

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

function addResizeEvent(func) { 
 var oldonresize = window.onresize; 
   if (typeof window.onresize != 'function') { 
     window.onresize = func; 
   } else { 
     window.onresize = function() {
       oldonresize(); 
       func(); 
     } 
   } 
 }

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function arrow(id){
	var cid = 'content_'+id;
	var c = $(cid)
	var img = $(id)
	Element.toggle(c)
	if(c.style.display == 'none')
	{
		createCookie(id, "hidden")
		img.src = "/images/arrow-right.gif";
	} else {
		eraseCookie(id)
		img.src = "/images/arrow-down.gif";
	}
}
function admin_clear(){
	Cookie.erase("up");
	Cookie.erase("up_query");
	Cookie.erase("down");
	Cookie.erase("down_query");
	alert('training memory cleared.');
}
  
function admin_up(n){
  Cookie.set("up", n);
  Cookie.set("up_query", $F('q1'));
  admin_go();
}

function admin_down(n){
  Cookie.set("down", n);
  Cookie.set("down_query", $F('q1'));
  admin_go();
}

function admin_go(){
  sep = location.href.indexOf("?") > -1 ? "&" : "?";
  if(Cookie.get("up") != null && Cookie.get("down") != null){
    var comment = prompt("Comment:");
    if(comment){
      Cookie.set("comment", comment);
      location.replace(location.href + sep + "reset=true");
    }
  }
}

// DEPRECATED.  Use CastTV.searchUrl instead, which does query escaping for free
function escapeSearchQuery(s){
	return s.replace("%", "%25").replace("/", "%2F").replace("?", "%3F").replace("+", "%2B").replace(/"/g, "%22").replace("#", "%23");
}

var phoneHome = function(path, callback) {
  new Ajax.Request(path, {
          method: 'get',
          onSuccess: function(transport) {
            if (transport.responseText.match(/<Result>([^<]*)/)){
              var answer = RegExp.$1;
              callback(escape(answer));
            }
          }
        });
};

var notFromUS = function(fn) {
  phoneHome('/location/from_us', function(str) {
    if (str == 'false') { // user is not from the united states
      fn();
    }
  });
};

// opensocial makeRequest() ajax wrapper
var makeRequestWrapper = function(target, callback) {
  try {
    var server_base_url = "http://www.casttv.com";

		if (gadgets.io) {
	    var params = {
	      METHOD : 'GET',
	      AUTHORIZATION : gadgets.io.AuthorizationType.SIGNED
	    };

	    gadgets.io.makeRequest(server_base_url + target, callback, params);
		}
  } catch(er) {
    console.log(er.message);
  }
};

// base is a string. params is a hash
function queryString(base, params) {
	pairs = [];
	for (key in params) {
	  pairs.push(key + '=' + (key == 'q' ? params[key].replace(/ /g, '+') : params[key]));
	}

	return pairs.inject(base, function(url,val) {
	  return url + (url.indexOf('?') < 0 ? '?' : '&') + val;
	});
}

var copyToClipboard = function(text) {
  var id = 'flashcopier';
  var html = '';
  if (navigator.userAgent.match(/MSIE/)) {
    html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+document.location.protocol+'fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="1" height="1" id="cliptext" align="middle">';
    html += '<param name="allowScriptAccess" value="sameDomain" />';
    html += '<param name="movie" value="/misc/webapp/swf/cliptext.swf" />';
    html += '<param name="quality" value="high" />';
    html += '<param name="bgcolor" value="#ffffff" />';
    html += '<param name="FlashVars" value="cliptext='+escape(text).replace(/\+/g,'%2B')+'">';
    html += '</object>';
  }
  else {
    html = '<embed src="/misc/webapp/swf/cliptext.swf" quality="high" bgcolor="#ffffff" width="1" height="1" name="cliptext" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"  FlashVars="cliptext='+escape(text).replace(/\+/g,'%2B')+'"/>';
  }
  if (document.getElementById(id)) {
    try { document.body.removeChild( document.getElementById(id) ); } catch(e) {};
  }
  var div = document.createElement('div');
  div.id = id;
  div.setAttribute('id', id);
  div.style.position = 'absolute';
  div.style.left = '-200px';
  div.style.top = '0px';
  div.style.width = '1px';
  div.style.height = '1px';
  div.innerHTML = html;
  document.body.appendChild(div);
}

var lazyLoadImage = function(id, url, optional_function) {
  var image = $(id);
  var objImg = new Image();      
  objImg.onload = function() {
    image.src = objImg.src;
		if (optional_function)
			optional_function();
  };
  objImg.src = url;
}

var flash = function(id, appear_dur, fade_dur) {
  new Effect.Appear($(id), { duration: 2,
                                    from: 0.0,
                                    to: 1.0,
                                    afterFinish: function() {
                                      new Effect.Fade($(id), { duration: 1 });
                                    }
                                  });
}
