function getImageSrc (el) {
	var img = $(el).find('img')[0];
	if(img.src.indexOf("blank") != -1) {
		var reg = new RegExp(/.*src=['"](.*?)['"].*/);
		var img_src = img.style.filter.replace(reg, "$1");
	}
	else
		var img_src = img.src;
	
	return img_src;
}

function setImageSrc (el, src) {
	var img = $(el).find('img')[0];
	img.src = src;
}

function prepend(src, prefix) {
	var slash_idx = src.lastIndexOf("/") + 1;		
	return src.substr(0, slash_idx) + prefix + "-" + src.substr(slash_idx);
}

function setBg(el) {
	var img_src = getImageSrc(el);
	$(el).css("background-image", "url(" + prepend(img_src, "bg") + ")");
}

function addTooltip (el) {
	var img_src = getImageSrc(el);
	var tooltip = document.createElement("img");
	tooltip.src = prepend(img_src, "tooltip");
	$(tooltip).addClass("tooltip");
	$(tooltip).attr("alt", "tooltip");
	$(tooltip).attr("width", "174");
	$(tooltip).attr("height", "13");
	$(tooltip).hide();
	$(tooltip).fadeTo(0,0);
	$(el).append(tooltip);
}

function button_enter (el) {
	if(el.src.indexOf("blank") <= 0) {
		var slash_idx = el.src.lastIndexOf("/") + 1;		
		el.src = el.src.substr(0, slash_idx) + "over-" + el.src.substr(slash_idx);
	}
}

function button_leave (el) {
	if(el.src.indexOf("blank") <= 0) {
		el.src = el.src.replace("over-", "");
	}
}

$(document).ready(function() {
	$("#menu .selected").each(function() { setBg(this); });
	$("#menu .entry").each(function() { addTooltip(this); });
	$("#menu .entry a").bind('mouseenter', function() {
		var tooltip = $(this).parent().find(".tooltip");
		if(!$(tooltip).is("visible"))
			$(tooltip).show();
		tooltip.stop(true);
		tooltip.fadeTo('normal', 1);
	});
	$("#menu .entry a").bind('mouseleave', function() {
		var tooltip = $(this).parent().find(".tooltip");
		tooltip.stop(true);
		tooltip.fadeTo('normal', 0);
	});
	
	// $("#submenu .entry").bind('mouseenter', function() {
	// 		if($(this).hasClass('selected'))
	// 			return false;
	// 		var src = getImageSrc(this);
	// 		setImageSrc(this, prepend(src, "over"));
	// 	});
	// 	$("#submenu .entry").bind('mouseleave', function() {
	// 		if($(this).hasClass('selected'))
	// 			return false;
	// 		var src = getImageSrc(this);
	// 		setImageSrc(this, src.replace("over-", ""));
	// 	});
	
	$(".button").bind('mouseenter', function() {
		button_enter($(this).find('img')[0]);
	});
	
	$(".button").bind('mouseleave', function() {
		button_leave($(this).find('img')[0]);
	});
	
	$("input[type='image']").bind('mouseenter', function() {
		button_enter(this);
	});
	
	$("input[type='image']").bind('mouseleave', function() {
		button_leave(this);
	});
});
