var bg_selector_query;
var bg_selector_page=1;

var orig_bgColor;
var orig_bgImage;
var orig_bgScroll;
var orig_bgPosition;
var orig_bgRepeat;

function show_bgselector(e) {
	
	
	if(window.event) { e = window.event; }             
	// check if event is set
	if (!e) return;
	// check what element it was in, and if it passes the other test for pages that can use this
	var tb = e.target || e.srcElement;
	if(!($("profile-to-get") || Q) || tb.id != "top-bar") return;
	
	//if its profile, is it your profile?
	if ($("profile-to-get")) {
		if (!((un && tok) && (unescape($("profile-to-get").value) == unescape(un)))) return;
	}
	
	orig_bgColor = $("top-bar").style.backgroundColor;
	orig_bgImage = $("top-bar").style.backgroundImage;
	orig_bgScroll = $("top-bar").style.backgroundAttachment;
	orig_bgPosition = $("top-bar").style.backgroundPosition;
	orig_bgRepeat = $("top-bar").style.backgroundRepeat;

	
	
	if (document.getElementById("dialog-lightbox")) {
		
		document.getElementById("dialog-lightbox").style.display="block";
	}
	else {		
		var lightbox = document.createElement("div");
		lightbox.setAttribute("id", "dialog-lightbox");
		lightbox.style.position = "absolute";
		lightbox.style.top = "0px";
		lightbox.style.left = "0px";
		lightbox.style.width = "100%";
		lightbox.style.height = "100%";
		lightbox.style.zIndex = 50;
		lightbox.style.backgroundColor = "#888888";
		lightbox.style.opacity="0.50";
		lightbox.style.filter="alpha(opacity=50)";
		document.body.appendChild(lightbox);
		
		
	}
	
	//set height of lightbox for IE
	var browser=navigator.appName;
	var b_version=navigator.appVersion;
	var version=parseFloat(b_version);
	
	if ((browser=="Microsoft Internet Explorer") && (version<7)) {
		var window_height = document.documentElement.clientHeight;
		$('dialog-lightbox').style.height=window_height;
	}
	
	var query = (($("q") && $("q").value != "") ? $("q").value : "");
	if (query == "") query = ((un&&tok) ? unescape(un) : "search");
	bg_selector_query = query;
	
	if (document.getElementById("dialog-window")) {
		
		$("dialog-window").innerHTML = show_bgselector_contents(query);
		change_bg_selector_keyword(query);
		$("dialog-window").style.display="block";
	}
	else {		
		//var query = $("q").value;
		//bg_selector_query = query;
		var window_width = 0;
		var dialog_margin = 0;
		var bgSelect = document.createElement("div");
		
		bgSelect.setAttribute("id", "dialog-window");
		bgSelect.innerHTML = show_bgselector_contents(query);
		
		if ( typeof( window.innerWidth ) == 'number' ) {
		    //Non-IE
		    window_width = window.innerWidth;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		    //IE 6+ in 'standards compliant mode'
		    window_width = document.documentElement.clientWidth;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		    //IE 4 compatible
		    window_width = document.body.clientWidth;
		}
		dialog_margin = (window_width - 500) / 2;
		bgSelect.style.left = dialog_margin + "px";
		
		bgSelect.style.position = "absolute";
		bgSelect.style.top = "50px";
		//bgSelect.style.left = "350px";
		bgSelect.style.width = "500px";
		bgSelect.style.textAlign = "left";
		//bgSelect.style.margin = "0 auto";
		//bgSelect.style.marginRight = "auto";
		bgSelect.style.zIndex = 100;
		document.body.appendChild(bgSelect);
		change_bg_selector_keyword(query);
		
	}
	
	
	try {
		document.body.style.overflow="hidden";
		document.body.scroll = "no";
	}
	catch (ex){}
	scroll(0,0);
	
}

function hide_bgselector(save, advanced) {
	if (save) {
		var query = (($("q") && $("q").value != "") ? $("q").value : "");
		if (query != "") {
			if(advanced) {
				var bg = $("background-select-advanced").value;
				if (Q) ktSave(Q,"bg",{"bg":bg});
				$("top-bar").style.background = $("background-select-advanced").value;
			}
			else {
				var bg = "";
				bg = $("top-bar").style.backgroundColor + " " + $("top-bar").style.backgroundImage + " " + $("top-bar").style.backgroundRepeat + " " + $("top-bar").style.backgroundAttachment + " " + $("top-bar").style.backgroundPosition;
				
				if (Q && bg != "    ") ktSave(Q,"bg",{"bg":bg});
			}
			
		}
		else {
			if(advanced) {
				var bg = $("background-select-advanced").value;
				if ($("profile-to-get")) profile_bg_save($("profile-to-get").value, bg, is_set_scroll);
				$("top-bar").style.background = $("background-select-advanced").value;
			}
			else {
				var bg = "";
				bg = $("top-bar").style.backgroundColor + " " + $("top-bar").style.backgroundImage + " " + $("top-bar").style.backgroundRepeat + " " + $("top-bar").style.backgroundAttachment + " " + $("top-bar").style.backgroundPosition;
				
				if ($("profile-to-get") && bg != "    ") {
					profile_bg_save($("profile-to-get").value, bg, is_set_scroll);
				}
			}
		}
	}
	else {
		hide_count( orig_bgImage )
		$("top-bar").style.backgroundColor = orig_bgColor;
		$("top-bar").style.backgroundImage = orig_bgImage;
		$("top-bar").style.backgroundAttachment = orig_bgScroll;
		$("top-bar").style.backgroundPosition = orig_bgPosition;
		$("top-bar").style.backgroundRepeat = orig_bgRepeat;
	}
	
	document.body.style.height = "auto";
	
	if (document.getElementById("dialog-window")) document.getElementById("dialog-window").style.display = "none";
	if (document.getElementById("dialog-lightbox")) document.getElementById("dialog-lightbox").style.display = "none";
	try {
		document.body.style.overflow="auto";
		document.body.scroll = "yes";
	}
	catch (ex){}
	
	
}

function profile_bg_save(user_name, bg, scroll) {
	hide_count( bg )
	var url = "index.php?action=ajax";
	var pars = 'rs=wfUpdateProfileBGJSON';
	pars += "&rsargs[]="+user_name+"&rsargs[]="+escape(bg)+"&rsargs[]="+scroll;
	var sUrl = server_to_use + "/" + url + "&" + pars;
	getDataFromServer("saveBg",sUrl);
}

function swapDivToAdvanced(x,y,type) {
	$("background-select-advanced").value = $("top-bar").style.background;
	swapDiv(x,y,type);
}

function swapDiv(x,y,type) {
	
	if (type==1) {
		$(x).hide();
		$(y).show();
	} else {
		$(y).hide();
		$(x).show();
	}
	
}

function bg_selector_set_advanced() {
	var bg = $("background-select-advanced").value;
	$("top-bar").style.background = bg;
	$("logo").style.display="block";
}

function bg_selector_set() {
	//alert($("top-bar").style.background);
	
	var bgImage = "";
	var bgRepeat = "";
	var bgScroll = "scroll";
	var bgPosition = "0% 20%";
	var bgColor = "transparent";
	var bg = "";

	
	for (var i=1; i<5; i++) {
		if ($("bg_selector_repeat_" + i).checked) bgRepeat = $("bg_selector_repeat_" + i).value; 
	}
		
	//alert(bgRepeat);
	
	
	if ($("bg_selector_url").value != "" && $("bg_selector_url").value != "http://") bgImage=$("bg_selector_url").value;
	
	if (bgImage!= "") bg = "transparent url(" + bgImage + ") " + bgRepeat + " scroll 0% 20%;"
	
	
	if(!bg || bg == "") return;
	//$("top-bar").style.background = bg;
	
	$("top-bar").style.backgroundColor = bgColor;
	$("top-bar").style.backgroundImage = "url(" + bgImage + ")";
	$("top-bar").style.backgroundAttachment = bgScroll;
	$("top-bar").style.backgroundPosition = bgPosition;
	$("top-bar").style.backgroundRepeat = bgRepeat;
	
	$("logo").style.display="block";
	
	hide_count( bgImage )

	//ktSave(Q,"bg",{"bg":bg});
}

function hide_count( bg ){
	if( bg ){
		$('count').hide();
	}else{
		$("count").style.display="inline";
	}
}

function bg_selector_repos(how_much, which) {
	if(!which || which !="v") which="h";
	if (!how_much) how_much=1;
	if($("top-bar") && $("top-bar").style.backgroundPosition != "") {
		var bgPosition = $("top-bar").style.backgroundPosition;
		if (bgPosition != "") {
			var left = bgPosition.substring(0, bgPosition.indexOf(" "));
			var top = bgPosition.substring(bgPosition.indexOf(" ")+1);
			
			//alert(left + " " + top);
			if (which=="h") {
				var leftMeas = "";
				if (left.indexOf("%") > -1) {
					leftMeas = "%";
					leftval = left.substring(0, left.indexOf(leftMeas));
					if (leftval>110) leftval =-10;
					else if (leftval<-10) leftval = 110;
					left = (parseInt(leftval)+how_much) + leftMeas;
				}
				else if (left.indexOf("px") > -1) {
					leftMeas = "px";
					leftval = left.substring(0, left.indexOf(leftMeas));
					left = (parseInt(leftval)+how_much) + leftMeas;
				}
				//alert(left + " " + top);
				//$("top-bar").style.backgroundPosition = left + " " + top;
			}
			else {
				var topMeas = "";
				if (top.indexOf("%") > -1) {
					topMeas = "%";
					topval = top.substring(0, top.indexOf(topMeas));
					/*if (topval>110) topval =-10;
					else if (topval<-10) topval = 110;*/
					top = (parseInt(topval)+how_much) + topMeas;
				}
				else if (top.indexOf("px") > -1) {
					topMeas = "px";
					topval = top.substring(0, top.indexOf(topMeas));
					top = (parseInt(topval)+how_much) + topMeas;
				}
				//alert(left + " " + top);
				//$("top-bar").style.backgroundPosition = left + " " + top;
				//alert(left + " " + top);
			}
			
			$("top-bar").style.backgroundPosition = left + " " + top;
		}
		
	}
}
var is_set_scroll = 0;
var bg_scroll_timer;
function bg_selector_repos_scroll() {
	if (!bg_scroll_timer) {
		//do_bg_selector_repos_scroll();
		is_set_scroll = 1;
		bg_scroll_timer = setInterval('bg_selector_repos()', 200);
	}
	else {
		//clearTimeout(bg_scroll_timer);
		is_set_scroll=0;
		clearInterval(bg_scroll_timer);
		bg_scroll_timer = 0;
	}
}

function do_bg_selector_repos_scroll() {
	bg_selector_repos(1);
	bg_scroll_timer = setTimeout('do_bg_selector_repos_scroll()', 200);
}
function bg_selector_get_prev_page() {
	if (bg_selector_page>1) change_bg_selector_keyword(bg_selector_query, bg_selector_page-1);
}
function bg_selector_get_next_page() {
	change_bg_selector_keyword(bg_selector_query, bg_selector_page+1);
}
function change_bg_selector_keyword(query, page) {
	if (!query) {
		var query = $("new_bg_selector_keyword").value;
		bg_selector_query = query;
	}
	else bg_selector_query = query;
	
	if(!page) {
		var page = 1;
		bg_selector_page = page;
	}
	else bg_selector_page = page;
	
	var id='flickr-search-script';
	
	oScript = document.getElementById(id); 
	var head = document.getElementById("flickr-scripts-div"); 
	if (oScript) {  head.removeChild(oScript); }
	// Create object 
	oScript = document.createElement("script");
	
	var url=set_flickr_url(query, page);
	if (url.indexOf("?") > -1) url += "&random="+Math.random();
	else url+= "?random="+Math.random();
	
	oScript.setAttribute("src",url); 
	oScript.setAttribute("id",id); 
	head.appendChild(oScript); 
	
	//$("flickr-scripts-div").innerHTML = "<script id=\"flickr-search-script\" type=\"text/javascript\" src=\"" + set_flickr_url(query) + "\"></script>";
}

function set_flickr_url(query, page) {
	return "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=148e34666b35345834f59d2f8f917bd6&tags=" + escape(query) + "&per_page=8&page=" + page + "&format=json&extras=owner_name&sort=interestingness-desc&license=1,2,3,4,5,6";
}

function showHide(el) {
	$(el).toggle();
}

function show_bgselector_contents(query) {
	var return_str = "";
	//return_str += '<div id="dialog-window">';
	//return_str = "<div id='flickr-scripts-div'><script id='flickr-search-script' type='text/javascript' src='" + set_flickr_url(query) + "'></script></div>";
	var bgImage = "";
	if ($("top-bar").style.backgroundImage != "") bgImage = $("top-bar").style.backgroundImage.substring(4,$("top-bar").style.backgroundImage.length-1);
	else bgImage = "http://";
	
	return_str = "<div id='flickr-scripts-div'></div>";
		return_str += '<div id="background-select-container">';
			return_str += '<div class="dialog-actions">';
				return_str += '<a href="javascript:swapDivToAdvanced(\'background-select-container\',\'background-select-advanced-container\',1);">Advanced</a> | ';
				return_str += '<a href="javascript:hide_bgselector(false)">Close</a>';
			return_str += '</div>';
			return_str += '<h2>Select Background</h2>';
			return_str += '<div class="dialog-message">';
				return_str += 'Have some fun, change the background for this page.';
			return_str += '</div>';
			return_str += '<div id="background-select-paste-url">';
				return_str += '<h3>Paste URL</h3>';
				return_str += '<input id="bg_selector_url" type="text" class="textfield" value="' + bgImage + '"/>';
				return_str += '<input type="button" value="Add" onclick="bg_selector_set();"/>';
			return_str += '</div>';
			return_str += '<h3>Select from Flickr <span><a href="javascript:showHide(\'mw-input\');">change keyword</a></span></h3>';
			return_str += '<div id="mw-input" style="display:none;">';
				return_str += '<input type="text" class="textfield" value="' + query.replace(/\"/g, '\'') + '" id="new_bg_selector_keyword"/><input type="button" value="submit" onclick="change_bg_selector_keyword();"/>';
			return_str += '</div>';
			return_str += '<div id="mw-images=container"><div id="mw-images" class="clearfix">';
				//return_str += '<div class="mw-image" id="background-select-image-1"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/a/a1/Various_chocolate_types.jpg/120px-Various_chocolate_types.jpg"/></div>';
				//return_str += '<div class="mw-image" id="background-select-image-2"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Chocolate_en_Rama.jpg/120px-Chocolate_en_Rama.jpg"/></div>';
				//return_str += '<div class="mw-image" id="background-select-image-3"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Hot_chocolate.jpg/120px-Hot_chocolate.jpg"/></div>';
				//return_str += '<div class="mw-image" id="background-select-image-4"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Bernd_das_Brot_cup.jpg/101px-Bernd_das_Brot_cup.jpg"/></div>';
			return_str += '</div><div id="mw-image-attribution"></div></div>';
			return_str += '<h3>Repeat</h3>';
			
			var bgRepeat = "";
			bgRepeat = $("top-bar").style.backgroundRepeat;
			
			return_str += '<input type="radio" name="bg_selector_repeat" id="bg_selector_repeat_1" onclick=\"bg_selector_set();\" value="repeat" ' + ((bgRepeat == "" || bgRepeat == "repeat") ? "checked" : "") + '/> Both';
			return_str += '<input type="radio" name="bg_selector_repeat" id="bg_selector_repeat_2" onclick=\"bg_selector_set();\"  value="repeat-x" ' + ((bgRepeat == "repeat-x") ? "checked" : "") + '/> Horizontal';
			return_str += '<input type="radio" name="bg_selector_repeat" id="bg_selector_repeat_3" onclick=\"bg_selector_set();\"  value="repeat-y" ' + ((bgRepeat == "repeat-y") ? "checked" : "") + '/> Vertical';
			return_str += '<input type="radio" name="bg_selector_repeat" id="bg_selector_repeat_4" onclick=\"bg_selector_set();\"  value="no-repeat" ' + ((bgRepeat == "no-repeat") ? "checked" : "") + '/> None';
			return_str += '<h3>Position</h3> ';
			return_str += '<input type="button" value="-" onclick="bg_selector_repos(-1);" /> Left ';
			return_str += '<input type="button" value="+" onclick="bg_selector_repos(1);" /> Right ';
			return_str += '<input type="button" value="+" onclick="bg_selector_repos(1, \'v\');" /> Up ';
			return_str += '<input type="button" value="-" onclick="bg_selector_repos(-1, \'v\');" /> Down ';
			if($("profile-to-get")) return_str += '<input type="button" value="scroll" onclick="bg_selector_repos_scroll();" /> Scroll ';
			return_str += '<div id="background-select-button">';
				return_str += '<input type="button" value="Save" onclick="hide_bgselector(true);"/> ';
				return_str += '<input type="button" value="Cancel" onclick="hide_bgselector(false);"/>';
			return_str += '</div>';
		return_str += '</div>';
		return_str += '<div id="background-select-advanced-container"  style="display:none;">';
			return_str += '<div class="dialog-actions">';
				return_str += '<a href="javascript:swapDiv(\'background-select-container\',\'background-select-advanced-container\',0);">Basic</a> | ';
				return_str += '<a href="javascript:hide_bgselector(false)">Close</a>';
			return_str += '</div>';
			return_str += '<h2>Select Background</h2>';
			return_str += '<div class="background-select-text">';
				return_str += 'If you know CSS, feel free to add your own.';
			return_str += '</div>';
			return_str += '<h3>Add in your own CSS</h3>';
			return_str += '<textarea id="background-select-advanced"></textarea>';
			return_str += '<div id="background-select-button">';
				return_str += '<input type="button" value="Save" onclick="hide_bgselector(true, true);"/> ';
				return_str += '<input type="button" value="Preview" onclick="bg_selector_set_advanced();"/>';
				return_str += '<input type="button" value="Cancel" onclick="hide_bgselector(false);"/>';
			return_str += '</div>';
		return_str += '</div>';

	//return_str += '</div>';
	
	return return_str;
}

function jsonFlickrApi(results) {
	$("mw-images").innerHTML = "";
	if (!results.photos.photo.length) {
		if (bg_selector_page == 1) $("mw-images").innerHTML = "No images found that match these tags";
		else $("mw-images").innerHTML = "No more images found that match these tags - <a href=\"javascript:bg_selector_get_prev_page();\">Prev page</a>";
	}
	else {
		$("mw-images").innerHTML += '<div style="height:35px; width: 10px; background-color:#bbbbbb; color:#ffffff; float:left; border:1px solid #DCDCDC; margin:0pt 5px 0pt 0pt; padding: 15px 0px 0px 1px; cursor: pointer; font-size:14px; font-weight:bold; cursor: pointer;" ' + ((parseInt(results.photos.page)>1) ? 'onclick="bg_selector_get_prev_page()">&lt;' : '>&nbsp;') + '</div>';
		//else $("mw-images").innerHTML += '<div>&lt;</div>';
			
		for (var i=0; i<results.photos.photo.length; i++) {
			var the_photo=results.photos.photo[i];
			$("mw-images").innerHTML += '<div class="mw-image" id="background-select-image-' + i + '" onclick="bg_selector_set_flickrurl(\''+the_photo.ownername+'\', ' + i + ');"><img id="loaded_img_' + i + '" src="http://farm' + the_photo.farm + '.static.flickr.com/' + the_photo.server + '/' + the_photo.id + '_' + the_photo.secret + '_t.jpg"/></div>';
			//$image_tag = "<img src=\"http://farm{$photo['farm']}.static.flickr.com/{$photo['server']}/{$photo['id']}_{$photo['secret']}_t.jpg\">";
		}
		$("mw-images").innerHTML += '<div style="height:35px; width: 10px; background-color:#bbbbbb; color:#ffffff; float:left; border:1px solid #DCDCDC; margin:0pt 5px 0pt 0pt; padding: 15px 0px 0px 1px; cursor: pointer; font-size:14px; font-weight:bold; cursor: pointer;" onclick="bg_selector_get_next_page()">&gt;</div>';
	}
}

function bg_selector_set_flickrurl(owner, which) {
	
	$("mw-image-attribution").innerHTML="Licensed under a Creative Commons License by <a href=\"http://flickr.com/people/" + escape(owner) + ">" + owner + "</a>";
	$("bg_selector_url").value = $("loaded_img_" + which).src;
	
	bg_selector_set();
}


