var names = new Object();
var index = new Object();
var lengths = new Object();
var loaded = new Object();

$(document).ready(function () {
	for (var i=0; i<divnames.length; i++) {
		loaded[divnames[i]] = false;
		$("#" + divnames[i]).mousemove(function(e){
			theName = $(this).attr("id");
			if (loaded[theName]) {
				
				oLeft = $(this).offset().left;
				oTop = $(this).offset().top;
				$("#" + theName + "_text" ).css("position", "absolute");
				$("#" + theName + "_text" ).css("top", (oTop + 25) + "px");
			
				locX = e.clientX - oLeft;
				tempIndex = Math.max(0, Math.min(Math.floor(locX / index[theName]), lengths[theName]));
				$("#" + theName + "_text" ).text(names[theName][tempIndex]);
				if (locX < 75) {
					$("#" + theName + "_text" ).css("text-align", "left");	
					$("#" + theName + "_text" ).css("left", Math.max(oLeft,locX+oLeft) + "px");
				} else if (locX > 525) {	
					$("#" + theName + "_text" ).css("text-align", "right");	
					$("#" + theName + "_text" ).css("left", Math.min(400+oLeft,locX+oLeft) + "px");
				} else {
					$("#" + theName + "_text" ).css("text-align", "center");	
					$("#" + theName + "_text" ).css("left", Math.max(oLeft,oLeft+locX-100) + "px");
				}
				
				$("#" + theName + "_highlight" ).css("position", "absolute");
				$("#" + theName + "_highlight" ).css("left", e.clientX + "px");
				$("#" + theName + "_highlight" ).css("top", oTop + "px");
				$("#" + theName + "_highlight" ).css("display", "block");
			}
		});
		loadData(divnames[i], qs[i]);
	}	
});


function loadData(divElem, qsElem) {
	$.getJSON("/image?output=json&div=" + divElem + qsElem, function(data){
		if (data.div) {
			names[data.div] = data.names;
			index[data.div] = data.range;
			lengths[data.div] = data.length;
			loaded[data.div] = true;
		}
    });
}


function reloadImageAndData(divId) {
	qs = $("#" + divId + "_party").attr("value") + $("#" + divId + "_state").attr("value") + $("#" + divId + "_title").attr("value");
	//$("#" + divId).src = "/image?" + qs;
	$("#" + divId).attr("src", "/image?" + qs);
	//$("img").each(function(i){ this.src = "test" + i + ".jpg"; });	
	
	loadData(divId, qs);
}
