var cookieUrl = "http://watch.io";
var baseUrl = "http://watch.io/";
var qid = null;
var qkey = null;
var max=100;
var start=0;	
	
function MakeUrlParam(key, value, isFirst)
{
	if(value !== null && value.length > 0)
	{
		return  isFirst ? "?" + key + "=" + encodeURI(value) : "&" + key + "=" + encodeURI(value);
	}
	
	return "";
}

function Confirm(msg)
{
	$('#confMessage').text(msg);
	$('#confirmation').fadeIn(400).delay(4000).fadeOut(400);
}

function QueueExists()
{
	if($.cookie('queue') == null)
	{
		return false;
	}
	
	return true;
}

function GetRemoteSearch(q, site)
{
	var link = "searchbing.php?q=" + escape(q) + "&site=" + site;
	$("#popdialog").html("<img src='images/ajax-loader.gif'>");
	var title = q + ' on ' + site;
	$("#popdialog").dialog
	({
		height: 320,
		width: 490,
		modal: true,
		title: title
	});
	var ajaxreq = $.ajax({ url: link });

	ajaxreq.success(OnSearchBingSuccess);
	ajaxreq.error(OnSearchBingError);
}

function OnSearchBingSuccess(data)
{
	$("#popdialog").html(data);
}

function OnSearchBingError(data)
{
	$("#popdialog").html("<p class='errortext'>ERROR: </p><p>An error occurred while processing your request.</p>");
}

function AddToQueue(source, show, title, identifier)
{
	var link = "queue.php";
	var params = "fn=add" + MakeUrlParam("source", source, false) + MakeUrlParam("show", show, false) 
		+ MakeUrlParam("title", title, false) + MakeUrlParam("identifier", identifier, false);
		
	if(QueueExists())
	{
		var queue = $.parseJSON($.cookie('queue'));
		params += MakeUrlParam("qid", queue.id, false) + MakeUrlParam("qkey", queue.key, false)
	}
	
	var ajaxreq = $.ajax({ url: link , type : "POST", data : params});

	ajaxreq.success(OnAddQueueItemSuccess);
	ajaxreq.error(OnAddQueueItemError);
}

function OnAddQueueItemSuccess(data)
{	
	var res = $.parseJSON(data);
	if(res.result == "SUCCESS")
	{
		if(!QueueExists())
		{
			$.cookie('queue', data, { expires: 365, path: '/', raw : true});
		}
		
		Confirm("Added " + res.source.toUpperCase() + " : " + res.show + " : " + res.title);
	}
	else{ Confirm("ERROR: An error occurred while trying to add this item to your queue. Please wait a few minutes before trying again."); }
}

function OnAddQueueItemError(data)
{
	Confirm("ERROR: An error occurred while trying to add this item to your queue.");
}

function Go(url, target)
{
	if(target == null){ target = "_blank"; }
	window.open(url, target);
}

function MClick(e)
{
	if(e.button==1)
	{
		e.target.click(); 
		return false;
	}
}
