var iconTheme = "git";
var xmldoc = '';
var LongNames = { "git" :"Gnome Icon Theme", "tit": "Tango Icon Theme", "highcontrast": "High Contrast Accessible Theme",
									"oxygen": "Oxygen\: KDE4 Theme", "gorilla": "Gorilla", "moblin": "Moblin", "moblinng": "moblin NG"
		}
var prefix = '';
var bitmaps = '';
var scalable = '';
var scalableext = '';
var suffix = '';
var divheight = '';

$(document).ready(function() {
	
  //warning for icon bee
  //console.log(document.referrer);
  //if (document.referrer == "iconbee.willmayo.com") {
  //}
	//grab theme from URL
	if (document.location.hash) {
		iconTheme = document.location.hash.replace(/^#/,"");
	}

	//set up waiters
	$("#wait").hide();
	$().ajaxStart(function () {
		$("#wait").fadeIn(100);
		$("#wait div").corner("12px");
	}).ajaxStop(function () {
		$("#wait").fadeOut(100);
	});

	//color theme switch show
	$("#themeswitch").css("right", "-140px");
	$("#themeswitch img").toggle(function () {
		$("#themeswitch").animate({ right: 0 }, 500);
	}, function () {
		$("#themeswitch").animate({ right: -140}, 200);
	});
	//color theme switching
	var cookie = readCookie("theme");
	if (cookie) {
		switchTheme(cookie);
	}
	$("#themeswitch a").click(function () {
		var theme = $(this).attr("id");
		switchTheme(theme);
		$("h2").corner("8px");//leaves artifacs otherwise
	});
	
	//clear contens
	$("#content").empty();
	$("#content").append("<h1>" + LongNames[iconTheme] + "</h1>\n");
	setBcg();



	//get contexts
	//var nameSpec = escape("http://webcvs.freedesktop.org/icon-theme/default-icon-theme/spec/icon-naming-spec.xml?revision=HEAD");
	var nameSpec = escape("icon-naming-spec.xml");
	//$.get("get.php?url=" + nameSpec, function(xml) {
	$.get(nameSpec, function(xml) {
		xmldoc = xml;
		$("/article/sect1/table", xmldoc).each( function () {
			var context = $(this).attr("id");
			if (context && context!="animations" && context!="intl") { 
				var Ccontext = context.substr(0,1).toUpperCase() + context.substr(1);
				$("#content").append("<h2 id=\"" + context + "\">" + Ccontext + "</h2>\n");
				$("#content").append("<div id=\"div-" + context + "\" class=\"iconsdiv\"></div>"); //prepare for icons
				$("#div-" + context).hide();
			}
		});
		//stuff that needs to be initialized from here
		getIcons(xmldoc);	
		$("h2").hover(function () {
			$(this).addClass("hoverheader");
		}, function () {
			$(this).removeClass("hoverheader");
		}).corner("8px");
	});

	//switching source
	$("#source a").click(switchSource);

	});







function switchSource() {
	iconTheme = $(this).attr("id");
	document.location.hash = iconTheme;
	$(".opened").each(function () {
		var id = this.id.replace(/^div-/, '');
		$("h2#" + id).trigger("click");
		$(this).removeClass("opened");
	});
	$("h1").html(LongNames[iconTheme]);
	setBcg();
}

function setBcg() {
	//var style = "url('./images/bcg-" + iconTheme + ".png') no-repeat top left";
	$("body").css({
		"background-image": "url('./images/bcg-" + iconTheme + ".png')",
		"background-repeat": "no-repeat"
	});
}

function showPreview() {
	//previews
	$(".label").css("cursor","pointer");
	var $label = $("div.label");
	var $previewbox = $("#preview");
	$label.click( function () {
		$previewbox.fadeIn();
		var dataurl = $(this).attr("rel");
		//$("#preview>div").corner("6px");

		var svg = "<object data=\"" + dataurl + "\" type=\"image/svg+xml\" ";
		svg += "width=\"48\" height=\"48\" />";


		$previewbox.children("div").html("<div><div id=\"largepreview\"></div><div id=\"tags\"></div><div id=\"metadata\"></div></div>");
		$("#largepreview").html(svg);
		svgdoc = "get.php?url=" + escape(dataurl);
		$.get(svgdoc, function (xml) {
			var author = $("creator title", xml).text();
			var contributors = $("contributor title", xml).text();
			var $tags = $("Bag li", xml);
			if($tags) {
				var tagsdiv = "<div class=\"label\">Tags:</div>\n";
				tagsdiv += "<ul>"; 
				$tags.each(function () {
					tagsdiv += "<li>" + $(this).text() + "</li>\n";;
				});
				tagsdiv += "</ul>";
				$("#tags").html(tagsdiv); 
			}
			if(author) {
				var authordiv = "<div class=\"label\">Author:</div>";
				authordiv += "<div>" + author + "</div>";
				$("#metadata").append(authordiv);
			}
			if(contributors) {
				var contdiv = "<div class=\"label\">Contributors:</div>";
				contdiv += "<div>" + contributors + "</div>";
				$("#metadata").append(contdiv);
			}

		})
	});



	//closing
	$previewbox.click(function () {
		$previewbox.fadeOut(200);
	});
	//esc closes previewbox
	$(document).keypress(function (key) {
		if(key.which == 27) {
			$previewbox.fadeOut(200);
		}
	});

}


function getIcons(xml) {
	

	//individual context icons
	$("h2").toggle(function () {
		//$("#wait").show();
		var context = $(this).attr("id");
		var iconsdiv = $("#div-" + context);
		//var selector = "//table[@id='" + context + "']/tgroup/tbody/row/entry[position()=1]";
		var selector = "//table[@id='" + context + "']/tgroup/tbody/row/entry:even()";
		switch (iconTheme) {
			case "moblinng":
				prefix = "http://repo.or.cz/w/moblin-icon-theme.git?a=blob_plain;f=moblin/";
				bitmaps = [];
				scalabledir = '24x24';
				scalable = '24';
				scalableext = '.svg';
				suffix = ';hb=refs/heads/one-size';
				divheight = '30px';
				break;
			case "moblin":
				prefix = "http://git.moblin.org/cgit.cgi/moblin-icon-theme/plain/moblin/";
				bitmaps = ['16x16','22x22', '32x32', '48x48'];
				scalable = '';
				scalableext = '';
				suffix = '';
				divheight = '80px';
				break;
			case "gorilla":
				prefix = "http://jimmac.musichall.cz/wipicons/gorilla-new/";
				bitmaps = ['64x64'];
				scalable = '';
				scalableext = '.svg';
				suffix = '';
				divheight = '80px';
				break;
			case "oxygen":
				prefix = "http://websvn.kde.org/*checkout*/trunk/kdesupport/oxygen-icons/";
				bitmaps = ['16x16', '22x22', '32x32', '48x48', '256x256']
				suffix = '';
				divheight = '80px';
				break;
			case "tit":
				prefix = "http://webcvs.freedesktop.org/tango/tango-icon-theme/";
				bitmaps = ['16x16', '22x22', '32x32'];
				scalable = '';
				scalableext = '.svg';
				suffix = '?view=co';
				divheight = '54px';
				break;
			case "highcontrast":
				prefix = "http://git.gnome.org/cgit/gnome-themes/plain/icon-themes/HighContrast-SVG/";
				bitmaps = '';
				scalabledir = 'scalable';
				scalable = '48';
				scalableext = '.svg';
				divheight = '64px';
				suffix = '';
				break;
			default:
				prefix = "http://git.gnome.org/cgit/gnome-icon-theme/plain/gnome/";
				bitmaps = ['16x16', '22x22', '32x32', '48x48', '256x256'];
				scalable = '';
				scalableext = '';
				divheight = '284px';
				suffix = '';
		}
		var body = '';
		$(selector, xml).each( function (){
			var iconName = $(this).text();
			var rel = '';
			body += "<div class=\"icon\">";
			body += "<div class=\"label\" " + rel + ">" + iconName + ":</div>\n";
			for (var i=0; i<bitmaps.length; i++) {
				var src = prefix + bitmaps[i] + "/"
				if (iconTheme != "gorilla") { src += context };
				src += "/" + iconName + ".png" + suffix;
				var img = "<img alt='-' src=\"" + src + "\" />\n";
				body += img;
			}
			if (scalable) { 
				var dataurl = prefix + scalabledir +"/";
				dataurl += context;
				dataurl += "/" + iconName + scalableext + suffix;
				body += "<object data=\"" + dataurl + "\" type=\"image/svg+xml\" ";
				body += "width=\"" + scalable + "\" height=\"" + scalable + "\" ></object>";
			}
			rel = "rel=\"" + prefix + "scalable/";
			rel += context;
			rel += "/" + iconName + scalableext + suffix + "\"";

			body += "</div>\n";
		});
		iconsdiv.html(body);
		//$("div.icon").css("height", divheight);
		//$(this).removeClass("loading");
		//$("#wait").hide();
		iconsdiv.slideDown().addClass("opened");
		if (iconTheme=="git" || iconTheme=="tit" || iconTheme=="highcontrast") {
			showPreview();
		}
	}, function () {
		$("#div-" + $(this).attr("id")).slideUp().removeClass("opened");
	});
}


//sets the color theme (including a cookie)
function switchTheme(theme) {
	$('link[@rel*=style][@title]').each( function () {
		this.disabled = true;
		if ($(this).attr("title")==theme) {
			this.disabled = false;
			createCookie('theme', theme, 365);
		}
	});
}


//cookie functions
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);
}


