/**
 * Really just a way to scope our variables
 */
function Dreamer()
{
	// to store our dialogs
	this.dialogs = new Array();
	
	this.logged_in = false;
	this.edit_on = true;
	this.current_focus = null;
	this.mousePositionX = 0;
	this.mousePositionY = 0;
	this.on_ready = new Array();

	this.ready = function(func) {
		this.on_ready.push(func);
	}
	
	// onReady is calle AFTER all of the $(document).ready() stuff ... we needed to add it because the 
	// auto-focus stuff wasn't working
	this.onReady = function()
	{
		for (i = 0; i < this.on_ready.length; i++)
		{
			this.on_ready[i]();
		}
	}

	/** install dreamer.me in the browser stuff **/
	this.add = function() {
		try {
			window.external.AddSearchProvider('http://dreamer.me/opensearch.xml');
		}
		catch (e) {
			alert("Currently, the search provider function requires either Firefox 2 or Internet Explorer 7.");
			return;
		}
	}
	
	// doesn't work ... browsers don't allow
	this.isInstalled = function() {
		try {
			return window.external.IsSearchProviderInstalled('http://dreamer.me/opensearch.xml') > 0;
		} catch (e) {
			return false;
		}
	}

	this.grayScreen = function(title, message) {
		$('#grayscreen').css({	background:"#000000", position: "absolute", top: 0, left:0, "display": "block", filter:"alpha(opacity=50)", opacity: 0.5, "width":$(document).width(),"height":$(document).height()});
	
		//$('#grayscreen').css({ position: "fixed", top: 0, left:0, "z-index": "900", "display": "block", opacity: 0.6, "width":getPageWidth(),"height":getPageHeight()});
		//$('.body').attr('scroll', 'no');
		if (title) {
			$('#grayscreen').html("<center><img src='one.gif' height='1' width='1'/><br/><div id='grayscreen_message' title='" + title + "' class='ui-dialog blue-dialog no-close'>" + message + "</div></center>");
			$('#grayscreen_message').dialog({
				closeOnEscape: false,
				dialogClass: 'no-close'
			});
			//$('#grayscreen_message').parent().hide();
		}
	}
	this.restoreScreen = function() { 	
		$('#grayscreen_message').dialog('close');
		$('#grayscreen').html('');
		$('#grayscreen').css("display", "none");
	}
}

function hideBox(id) 
{
	$('#' + id).css("display", "none");
}

var dreamer = new Dreamer();

/************** mouse position tracker *************/
$().mousemove(function(e){   
	dreamer.mousePositionX = e.pageX;
	dreamer.mousePositionY = e.pageY;
});


/** generic functions .. available to ppl **/
function listToArray(list)
{
	while (list.indexOf(" ") > 0)
		list = list.replace(" ", "");
	return list.split(",");
}



/** search suggestion stufff **/
var sug_original = "";
var sug_hs = 0;
var sug_num = 0;
var sug_insugbox = false;
var sug_inblur = true;
var sug_form = null;
var suggestions = $("#suggestions");
var sug_shop_url = "http://completion.amazon.com/search/complete?method=completion&search-alias=aps&mkt=1&q=";
var sug_web_url = "http://suggestqueries.google.com/complete/search?output=firefox&client=firefox&hl=en&q=";
var sug_url = sug_web_url;

// word.command = 'goto ';
// word.word = 'kobe'

// so the "item" might come to us as "goto nba lakers"
// where "goto nba" has already bee typed
// so 
//     goto - is the commmand
//     lakers - is the hilight
//     nba - is the word
//
// 
// for example Item('goto kobe', 'kobe bryant')

function Input(str)
{
	this.command = '';
	this.word = '';
	/*this.commandOrWord = function() {
		if (this.word == '') return this.command;
		return this.word;
	}*/
	this.getAlt = function(item) {
		return this.command + item;
	}
	this.isShop = function() {
		return this.command == "buy " || this.command == "shop ";
	}
	this.getURL = function(query) {
		if (this.isShop()) return sug_shop_url + escape(this.word);
		if (this.command != '') return sug_web_url + escape(this.word);
		return sug_url + escape(this.word);
	}
	
	var sug_commands = ['-', 'goto', 'go', 'define', 'buy', 'shop', 'image', 'images', 'show', 'news'];
	for (i = 0; i < sug_commands.length; i++) 
	{
		var command = sug_commands[i];

		var starts_index = str.indexOf(command + ' ');
		//var ends_index = str.indexOf(' ' + command);
		/*
		if (command == str)
		{
			this.command = str;
			this.word = '';
			return;
		}
		else*/ if (starts_index == 0)
		{ 	
			this.command = str.substring(0, command.length + 1);
			this.word = str.substring(command.length + 1);
			return;
		}
		/*else if (ends_index > 0 && ends_index == str.length - command.length - 1)
		{
			this.command = str.substring(ends_index, str.length);
			this.word = str.substring(0, ends_index);
			this.cmdstarts = false;
			return;
		}*/
		else
		{
			this.word = str;
		}
    }
}

function showWebSuggestions(event)
{
	suggestions = $("#suggestions");
	sug_url = sug_web_url;
	showSuggestions(event, document.forms['home_form']);
}
function showImagesSuggestions(event)
{
	suggestions = $("#images_suggestions");
	sug_url = sug_web_url;
	showSuggestions(event, document.forms['images_form']);
}
function showNewsSuggestions(event)
{
	suggestions = $("#news_suggestions");
	sug_url = sug_web_url;
	showSuggestions(event, document.forms['news_form']);
}
function showShopSuggestions(event)
{
	suggestions = $("#shop_suggestions");
	sug_url = sug_shop_url;
	showSuggestions(event, document.forms['shop_form']);
}
function showSuggestionBox()
{
	suggestions.show();
}
function hideSuggestionBox()
{
	suggestions.hide();
}
function blurSuggestions()
{
	if (!sug_insugbox)
	{
		sug_inblur = true;
		hideSuggestionBox();
		if (sug_form != null) sug_form.q.value = sug_original;
	}
}
function lowlightSuggestion(id)
{
	$("#suggestion_" + id).removeClass("suggestion-hilight-row");
	/*
	if (! suggestions.is(":hidden"))
		sug_form.q.value = sug_original;
	*/
	if (sug_inblur)
	{
		//sug_form.q.value = sug_original;
		sug_inblur = false;
	}
	else
	{
		sug_form.q.focus();
		setCaretPosition(sug_form.q, sug_form.q.value.length);
	}
}
function hilightSuggestion(id)
{
	$("#suggestion_" + id).addClass("suggestion-hilight-row");
}
function takeSuggestion(id)
{
	sug_form.q.value = $("#suggestion_" + id).attr("alt").replaceAll("_DREAMER_SINGLE_QUOTE_", "'");
	sug_original = sug_form.q.value;
	hideSuggestionBox();
	sug_form.q.focus();
	setCaretPosition(sug_form.q, sug_form.q.value.length);
}
function showSuggestions(event, the_form)
{
	sug_form = the_form;
	var value = the_form.q.value;
	
	if (event.keyCode == KEY_ESCAPE)
	{
		sug_hs = 0;
		if (the_form.q.value != sug_original) the_form.q.value = sug_original;
		hideSuggestionBox();
	}
	else if (event.keyCode == KEY_ARROW_UP)
	{
		$("#suggestion_" + sug_hs).removeClass("suggestion-hilight-row");
		if (sug_hs > 0)
		{
			sug_hs--;
			if (sug_hs == 0)
				the_form.q.value = sug_original;
			else
				the_form.q.value = $("#suggestion_" + sug_hs).attr("alt").replaceAll("_DREAMER_SINGLE_QUOTE_", "'");
		}
		$("#suggestion_" + sug_hs).addClass("suggestion-hilight-row");
	}
	else if (event.keyCode == KEY_ARROW_DOWN)
	{
		if (sug_num > 0) showSuggestionBox();
		$("#suggestion_" + sug_hs).removeClass("suggestion-hilight-row");
		if (sug_hs < sug_num) 
		{
			sug_hs++;
			the_form.q.value = $("#suggestion_" + sug_hs).attr("alt").replaceAll("_DREAMER_SINGLE_QUOTE_", "'");
		}
		$("#suggestion_" + sug_hs).addClass("suggestion-hilight-row");
	}
	else
	{
		if (value == '') return;
		sug_original = value;
		
		var input = new Input(value);
		
		//shop http://completion.amazon.com/search/complete?method=completion&q={searchTerms}&search-alias=aps&client=amzn-search-suggestions/9fe582406fb5106f343a84083d78795713c12d68&mkt=1
		// http://completion.amazon.com/search/complete?method=completion&q=toys&search-alias=aps&mkt=1
		
		//var request = "http://suggestqueries.google.com/complete/search?output=firefox&client=firefox&hl=en&q=" + escape(input.word);
		var request = input.getURL();
		//if (!jQuery.browser.msie)
			request = "serv?c=proxy&type=json&url=" + escape(request);

		$.getJSON(request, function(data){
	        	$("#suggestions").text("");
	        	$("#images_suggestions").text("");
	        	$("#news_suggestions").text("");
	        	$("#shop_suggestions").text("");
	        	if (data[1].length > 0) 
	        		showSuggestionBox();
	        	else
	        		hideSuggestionBox();
	        	
	        	sug_hs = 0;
	        	var count = 1;
	        	sug_num = data[1].length;
	        	

				// for each suggestion
	          $.each(data[1], function(i,item){
	          	var alt = input.getAlt(item);
	        	suggestions.append("<div onmouseover='hilightSuggestion(" + count + ")' onmouseout='lowlightSuggestion(" + count + ")' onclick='takeSuggestion(" + count + ")' class='suggestion-item' alt='" + alt.replaceAll("'", "_DREAMER_SINGLE_QUOTE_") + "' id='suggestion_" + count++ + "'>" + sug_hilight(input, item) + "</div>");
	          });
	          if (input.command != '')
			     suggestions.append("<div class='command-box suggestion-item'><span title='What are commands?' class='suggestion-command'>" + input.command + "</span><span class='suggestion-hilight-word menulink'> is a <a href='/features-and-keyboard-shortcuts#commands'>command keyword</a></span></div>");
	        });
	}        
}

function sug_hilight(input, item)
{
	var index = item.indexOf(input.word);

	var ret = "";
	ret += "<span class='suggestion-command'>" + input.command + "</span>";
	ret += "<span class='suggestion-word'>" + item.substring(0, index) + "</span>";
    ret += "<span class='suggestion-hilight-word'>" + item.substring(index, index+input.word.length) + "</span>";
    ret += "<span class='suggestion-word'>" + item.substring(index+input.word.length, item.length) + "</span>";
    return ret;
}


/********** dialog *************/
var disable_dialogs = false;
function Dialog(id, offset, show_close)
{
	//$.ui.dialog.defaults.bgiframe = true;
	this.focus = null;
	this.jquery = $("#" + id);
	this._init = false;
	this.xoffset = 10;
	if (offset)
		this.xoffset = offset;
	this.width = 0;
	this.height = 0;
		
	dreamer.dialogs[id] = this;

	this.open = function() 
	{
		if (disable_dialogs) return;
		this.focus = dreamer.current_focus;

		// make sure we've been initialized
		this.init();
		
		// we need to open it first at 0,0 because the initial width and height 
		// aren't going to be the actual width and height
		// so basically we're opening it to get the w, h		
		if (this.width == 0 && this.height == 0)
		{
			this.jquery.dialog('option', 'position', [0, 0]);
			this.jquery.dialog('open');
		}

		// cache width and height 
		this.width = this.jquery.parent().width();
		this.height = this.jquery.parent().height();
		
		var xpos = dreamer.mousePositionX + this.xoffset - f_scrollLeft();
		var ypos = dreamer.mousePositionY + 15 - f_scrollTop();
		
		if (dreamer.mousePositionX + this.xoffset +this.width +20 > getWindowWidth()+f_scrollLeft())
			xpos = xpos - (dreamer.mousePositionX + this.xoffset + this.width) + getWindowWidth() + f_scrollLeft() - 30;

		if (dreamer.mousePositionY + 30 + this.height > getWindowHeight()+f_scrollTop())
			ypos = ypos - (dreamer.mousePositionY + this.height) + getWindowHeight() + f_scrollTop() - 40;
			
		this.jquery.dialog('option', 'position', [xpos, ypos]);
		this.jquery.dialog('open');
	}
	this.init = function()
	{
		if (this._init) return;
		if (show_close)
		{
			this.jquery.dialog({
				autoOpen: false,
				closeOnEscape: true
			});
		}
		else
		{
			this.jquery.dialog({
				autoOpen: false,
				closeOnEscape: false,
				dialogClass: "no-close"
			});
		}
		this._init = true;
	}
	this.close = function() 
	{
		this.jquery.dialog('close');
		if (dreamer.current_focus != null && f_scrollTop() == 0 && f_scrollLeft() == 0)
			dreamer.current_focus.focus();
	}
	this.isOpen = function() 
	{
		return this.jquery.dialog('isOpen');
	}
}

var dialog_to_open = null;
function openDialog(id)
{
	dialog_to_open = id;
	setTimeout("reallyOpenDialog('" + id + "')", 500);
	//dreamer.dialogs[id].open();
}
function closeDialog(id)
{
	dialog_to_open = null;
	dreamer.dialogs[id].close();
}
function reallyOpenDialog(id)
{
	//debug(id + "," + dialog_to_open);
	if (id == dialog_to_open)
		dreamer.dialogs[id].open();
}

function debug(str)
{
	$("<div/>").load("/serv?c=debug&str=" + escape(str));
}

function initializeHelp()
{
	initializeHelpFor($("[help]"), true);
}
function initializeHelpFor(jquery, open_and_close)
{
	jquery.each(function () {
		// this is the id of the dialog text
		var d = new Dialog($(this).attr("help"), 10, false);
		// these next two lines are here because of a weird Firefox bug which 
		// causes the content to shift around when you open the dialogs
		d.init();
		if (open_and_close)
		{
			d.open();
			d.close();
		}
		$(this).mouseover(function() {
			openDialog($(this).attr("help"));
		});
		$(this).mouseout(function() {
			closeDialog($(this).attr("help"));
		});
	});
}


var div_click = true;
function disableDivClick()
{
	div_click = false;
	setTimeout("enableDivClick()", 200);
}
function enableDivClick()
{
	div_click = true;
}
function initializeSearchResults(tabs)
{
	$(".search-result").each(function () {
		$(this).mouseover(function () {
			$(this).addClass("search-result-hover");
		});
		$(this).mouseout(function () {
			$(this).removeClass("search-result-hover");
		});
		$(this).click(function () {
			if (!div_click) return;
			if (tabs)
				window.open($(this).attr("href"));
			else
				document.location.href = $(this).attr("href");
		});
	});
}

function initializeFocusWatcher()
{
	$("input").each(function () {
		$(this).focus(function () {
			dreamer.current_focus = $(this);
		});
	});
}

function initializeFocus()
{
	if (dreamer.focus)
		dreamer.focus();
}

// attempt this url
function attempt(url, success, failure)
{
	$("<div/>").load(url, function () {
		var resp = $(this).find("#response");
		if (resp.attr("success") == "true")
		{
			success($(this));
		}
		else
		{
			var reason = resp.attr("reason");
			if (reason == null) return "unknown error";
			failure(reason);
		}
	});
}

function submit_login()
{
	$("#login_dialog_error").html("");
	var error = attempt("/serv?c=quicklogin&pass=" + $("#login_dialog_pass").val(), 
		function () {
			dreamer.logged_in = true;
			$("#login_dialog").dialog("close");
			saveLayout();
		},
		function (reason) {
			dreamer.logged_in = false;
			$("#login_dialog_error").html(reason);
		}
	);
}

function widget_edit_on()
{
	dreamer.edit_on = true;
	$("#edit_on").html("<u>on</u>");
	$("#edit_off").html("<a style='text-decoration:none;' href='javascript:widget_edit_off()'>off</a>");
	$("<div/>").load("/serv?c=widget-editor&on=true");
}
function widget_edit_off()
{
	dreamer.edit_on = false;
	$("#edit_off").html("<u>off</u>");
	$("#edit_on").html("<a style='text-decoration:none;' href='javascript:widget_edit_on()'>on</a>");
	$("<div/>").load("/serv?c=widget-editor&on=false");
}

/**
 * For sizing an iframe, only works when there is one per page
 * I know it's confusing, don't mess with it, and if you do do a lot of testing
 */
var the_auto_iframe = null;
function iframeAutoHeight(iframe)
{
	if (the_auto_iframe == null)
	{
		the_auto_iframe = iframe;
		setTimeout("iframeHeightRefresh()", 1000);
	}
	the_auto_iframe = iframe;
	iframeAutoHeightHelper(the_auto_iframe);
}
function iframeAutoHeightHelper(iframe)
{
	var e = iframe;
	if(e.contentDocument){
		iframe.height = e.contentDocument.body.offsetHeight + 10;
	} else {
		iframe.height = e.contentWindow.document.body.scrollHeight;
	}
}
function iframeHeightRefresh()
{
	iframeAutoHeightHelper(the_auto_iframe);
	setTimeout("iframeHeightRefresh()", 1000);
}

function initializeTable(tableid)
{
	$("#" + tableid + " tr[hilight]:even").removeClass("even-tr");
	$("#" + tableid + " tr[hilight]:odd").removeClass("odd-tr");
	$("#" + tableid + " tr[hilight]:even").addClass("even-tr");
	$("#" + tableid + " tr[hilight]:odd").addClass("odd-tr");
	$("#" + tableid + " tr[hilight]").mouseover(function() {
		$(this).addClass("over-tr");
	});
	$("#" + tableid + " tr").mouseout(function() {
		$(this).removeClass("over-tr");
	})
}

/*
var flickr_keywords = ["sunset", "mountain", "snow"];
setTimeout("getFlickrImages('" + flickr_keywords[0] + "')", 0);
setTimeout("getFlickrImages('" + flickr_keywords[1] + "')", max_flickr_images * 2000 );
setTimeout("getFlickrImages('" + flickr_keywords[2] + "')", max_flickr_images * 4000 );
*/
