function getSmaller(a, b) {
	if (a > b) { return b; } else { return a; }
}

function getBigger(a, b) {
	if (a > b) { return a; } else { return b; }
}

function dump(m) {
	$("#dump").html("<div>" + m + "</div>");
}

function loadImage() {
	var field;
	field = $("#itype").attr("value");
	
	/* special case for local files - debug mode 
	if (window.opera) { field = escape(field); } //temp. dirty hack
	else field = "file:///" + escape(field);*/
	
	if (field != "") {  
	
		if (field.match(/.*(\.[Jj][Pp][Gg]|\.[Gg][Ii][Ff]|\.[Jj][Pp][Ee][Gg]|\.[Pp][Nn][Gg])/)) {
		
			$("#img img").attr({ src: field, alt: "Could not load image" }); 
				//fake alt - when we cannot connect to img, user sees this instead of img
			
			/* wait until image loads */
			$("#pleasewait").show();
			$("#itype").attr("disabled", "disabled");
			$("#imgLoad").attr("disabled", "disabled");
			
			$("#img img").load(function() {
			
				//$("#imgLoad").val("Update image");
				$("#imgLoadFile form").hide();
			
				$("#areaPref").val("");
			
				/* restore input fields */
				$("#pleasewait").hide();
				$("#itype").removeAttr("disabled");
				$("#imgLoad").removeAttr("disabled");				
				
				var imgWidth = $(this).width();
				var imgHeight = $(this).height();
				
				$("#target").width(imgWidth + "px");
				$("#target").height(imgHeight + "px");
				
				$("#drawAreaRect").click(function() {
				
					$(this).addClass("active");
					$("#selArea").attr("disabled", "disabled");
					
					$("#target").css("cursor", "crosshair");
					
					$("#target").bind("mousedown", function(e) {
						iMouseLeft = e.clientX + self.pageXOffset;
						iMouseTop = e.clientY + self.pageYOffset;
						iMouseLeft = iMouseLeft - 270;
						iMouseTop = iMouseTop - 20;
						
						var lilen = $("#img li").length;
						lilen++;
						
						$("#img ol").append("<li id=\"area" + lilen + "\"><a href=\"http:\/\/\">Desc</a></li>");						
						$("#area" + lilen).left(iMouseLeft + "px");
						$("#area" + lilen).top(iMouseTop + "px");
						
						var X1 = iMouseLeft;
						var Y1 = iMouseTop;
						
						$(this).bind("mousemove", function(e) {
							X2 = e.clientX + self.pageXOffset;
							Y2 = e.clientY + self.pageYOffset;
							X2 = X2 - 270;
							Y2 = Y2 - 20;
							
							var areaLeft, areaTop, areaWidth, areaHeight = 0;
	
							areaLeft = getSmaller(X1, X2);
							areaTop = getSmaller(Y1, Y2);
							areaWidth = getBigger(X1, X2) - areaLeft;
							areaHeight = getBigger(Y1, Y2) - areaTop;						
							
							$("#area" + lilen).left(areaLeft + "px");
							$("#area" + lilen).top(areaTop + "px");
							$("#area" + lilen).width(areaWidth + "px");
							$("#area" + lilen).height(areaHeight + "px");
							
						});
						
						$(this).bind("mouseup", function(e) {
							$("#imgAreas .body").append("<div><a id=\"harea" + lilen + "\" href=\"\">Area " + lilen + "</a></div>");
							
							var link = "#harea" + lilen;
							
							function makeId(o) {
								return o.id.split("h")[1];
							}
							
							$(link).hover(function(){
								if ($("#areaOutline").attr("checked")) {
									$("#" + makeId(this)).addClass("sel");
								}
							}, function() {
								if ($("#areaOutline").attr("checked")) {
									$("#" + makeId(this)).removeClass("sel");
								}
							});
							
							$("#selArea").removeAttr("disabled");
							
							$(link).click(function(e) {
								var id = makeId(this);
								
								//dump(id);
								
								$("#imgAreas .body a").removeClass("selected");
								$(this).addClass("selected");
								
								$("#aLeft").val($("#" + id).left().split("px")[0]);
								$("#aTop").val($("#" + id).top().split("px")[0]);
								$("#aWidth").val($("#" + id).width());
								$("#aHeight").val($("#" + id).height());
								
								/* preventing from pasting document URI when href is empty */
								var href = $("#" + id + " a").href();
								if (href != window.location.href) {
									$("#aLink").val(href);
								}
								$("#aLabel").val($("#" + id + " a").html());
							
								$("#imgAreasProps").show();
								$("#imgAreasProps").addClass(id);
								
								$("#img li").removeClass("act");
								$("#" + makeId(this)).addClass("act");
								
								/* bring back old settings */
								function revert() {
									$("#img li").removeClass("act");
									$("#imgAreas .body a").removeClass("selected");
									$("#imgAreasProps").hide();
									$("#imgTools button").removeAttr("disabled");
								}
								
								/*
								function dumpError(msg) {
									$("#imgErrors").show();
									msg = "<li>" + msg + "</li>";
									$("#imgErrors ul").append(msg);
								}
								*/
								
								/* save changes */
								$("#imgAreasProps").parent().submit(function() {
								
									id = $("#imgAreas .selected").id().split("h")[1];
									//dump(id);
									
									var valErr = false;
								
									var tempLeft = $("#aLeft").val();
									var tempTop = $("#aTop").val();
									var tempWidth = $("#aWidth").val();
									var tempHeight = $("#aHeight").val();
									
									var canvWidth = $("#img img").width();
									var canvHeight = $("#img img").height();
									
									var posNum = /^[1-9]+[0-9]*$/;
									
									if (!(tempLeft.match(posNum)) || !(tempTop.match(posNum)) || !(tempWidth.match(posNum)) || !(tempHeight.match(posNum))) {
										alert("Please provide positive numbers only.");
										valErr = true;
									}
									
									if ((tempLeft >= canvWidth) || (tempTop >= canvHeight)) {
										alert("New position of image map exceeds image dimensions. Check left / top values.");
										valErr = true;
									}
									
									if (parseInt(tempLeft) + parseInt(tempWidth) > canvWidth){
										if ($("#smartErrors").attr("checked")) {
											tempWidth = canvWidth - parseInt(tempLeft);
										} else {
											alert("New dimensions of image map surpass image itself. Please check width.");
											valErr = true;
										}
									}
									
									if (parseInt(tempTop) + parseInt(tempHeight) > canvHeight){
										if ($("#smartErrors").attr("checked")) {
											tempHeight = canvHeight - parseInt(tempTop);
										} else {
											alert("New dimensions of image map surpass image itself. Please check height.");
											valErr = true;
										}
									}
									
									if (!valErr) {
										$("#imgErrors ul").empty();
										$("#imgErrors").hide();
										$("#" + id).left(tempLeft + "px");
										$("#" + id).top(tempTop + "px");
										$("#" + id).width(tempWidth + "px");
										$("#" + id).height(tempHeight + "px");
										$("#" + id + " a").href($("#aLink").val());
										$("#" + id + " a").html($("#aLabel").val());
										revert();
										$("#imgAreasProps").parent().unbind("submit");
									}

									return false;
								});

								/* cancel area editing */
								$("#imgAreasProps a.cancel").click(function() {
									revert();
									$(this).unbind("click");
									return false;									
								});
								
								$("#imgTools button").attr("disabled", "disabled");
								
								e.preventDefault();
							});

							$(this).unbind("mousemove");
							$(this).unbind("mousedown");
							$(this).unbind("mouseup");
							$("#target").css("cursor", "default");
							$("#drawAreaRect").removeClass("active");
							$("#selArea").removeAttr("disabled");
						});

					});//#target mousedown
					
					return false;
				}); //drawAreaRect
				
				$("#selArea").click(function() {
					$(this).addClass("active");
					$("#drawAreaRect").attr("disabled", "disabled");
					$("#img li").css("zIndex", 200);
					$("#img li a").click(function() {
						$("#selArea").removeClass("active");
						$("#img li").css("zIndex", 50);
						$("#img li a").unbind("click");
						$("#drawAreaRect").removeAttr("disabled");
						$("#h" + $(this).parent().id()).click();
						return false;						
					});
					return false;
				}); //selArea
				
				$("#imgOptions h3 a").click(function() {
					$("#imgOptionsFields").toggle();
					return false;
				});
				
				$("#genImg form").submit(function() {
					if ($("#img li").length > 0) {
					
						var t = "\t";
						var imgsrc = $("#img img").src();
						
						if ($("#shortPath").attr("checked")) {
							var filename = /[^\/|%5C]+$/;
							imgsrc = imgsrc.substring(imgsrc.search(filename), imgsrc.length);
						}
						
						if ($("#tabsSpaces").attr("checked")) {
							t = "  ";
						}
						
						var html = "" +
											 '<div id="imgmap">\n' +
											 t + '<img height="' + $("#img img").height() + '" width="' + $("#img img").width() + '" src="' + imgsrc + '" alt="" />\n' +
											 t + '<ol>\n';
					
						var css = "" +						
											"#imgmap {\n" +
												t + "position: relative;\n" +
												t + "_zoom: 1;\n" +
											"}\n\n" +
											
											"#imgmap li {\n" +
												t + "position: absolute;\n" +
												t + "display: block;\n" +
												t + "list-style: none;\n" +
												t + "outline: 1px dashed;\n" +
												t + "overflow: hidden;\n" +
											"}\n\n" +
											
											"#imgmap li a {\n" +
												t + "display: block;\n" +
												t + "width: 100%;\n" +
												t + "height: 100%;\n" +
												t + "_background: url(space.gif);\n" +
												t + "text-indent: -1000em;\n" +
											"}\n\n";
						
						$("#img li").each(function() {
							var output = "#" + $(this).id() + " {\n";
							output = output + t + "left: " + $(this).left() + ";\n";
							output = output + t + "top: " + $(this).top() + ";\n";
							output = output + t + "width: " + $(this).width() + "px;\n";
							output = output + t + "height: " + $(this).height() + "px;\n";
							output = output + "}\n";
							css = css + output + "\n";
							html = html + t + t + '<li id="' + $(this).id() + '">' + $(this).html() + '</li>\n';
						});
						
						html = html + t + '</ol>\n' +
													'</div>';

						$("#genCSS textarea").val("");
						$("#genCSS textarea").val(css);
						$("#genCSS").show();
						$("#genHTML textarea").val("");
						$("#genHTML textarea").val(html);
						$("#genHTML").show();
						
					} else {
						alert("Please create some image maps first");
					}
					return false;
				});
				
				$("#genCSS a").click(function() {
					$("#genCSS").hide();
					return false
				});
				
				$("#genHTML a").click(function() {
					$("#genHTML").hide();
					return false
				});
				
				/* show image dimensions */
				$("#imgWidth").html(imgWidth);
				$("#imgHeight").html(imgHeight);
				
				$("#imgMore").show();
				
			});//img loads
			
		}	else {
			alert("Please provide path to an image file (PNG, JPG, GIF)");
		}
		
	} else {
		alert("Please provide path to an image");
	}
	
}

$("#config form").ready(function() {
	$("#imgReload").hide();
	$("#imgErrors ul").empty();
	$("#imgErrors").hide();
	$("#genCSS").hide();
	$("#genHTML").hide();
	$("#selArea").attr("disabled", "disabled");
	$(this).submit( function() {
		loadImage();
		return false
	});
});

$(document).ready(function() {
	$("#img").append("<ol></ol>");
});	

