

		
		// remote scripting library
		// (c) copyright 2005 modernmethod, inc
		var sajax_debug_mode = false;
		var sajax_request_type = "POST";
		var sajax_target_id = "";
		var sajax_failure_redirect = "";
		
		function sajax_debug(text) {
			if (sajax_debug_mode)
				alert(text);
		}
		
 		function sajax_init_object() {
 			sajax_debug("sajax_init_object() called..")
 			
 			var A;
 			
 			var msxmlhttp = new Array(
				'Msxml2.XMLHTTP.5.0',
				'Msxml2.XMLHTTP.4.0',
				'Msxml2.XMLHTTP.3.0',
				'Msxml2.XMLHTTP',
				'Microsoft.XMLHTTP');
			for (var i = 0; i < msxmlhttp.length; i++) {
				try {
					A = new ActiveXObject(msxmlhttp[i]);
				} catch (e) {
					A = null;
				}
			}
 			
			if(!A && typeof XMLHttpRequest != "undefined")
				A = new XMLHttpRequest();
			if (!A)
				sajax_debug("Could not create connection object.");
			return A;
		}
		
		var sajax_requests = new Array();
		
		function sajax_cancel() {
			for (var i = 0; i < sajax_requests.length; i++) 
				sajax_requests[i].abort();
		}
		
		function sajax_do_call(func_name, args) {
			var i, x, n;
			var uri;
			var post_data;
			var target_id;
			
			sajax_debug("in sajax_do_call().." + sajax_request_type + "/" + sajax_target_id);
			target_id = sajax_target_id;
			if (typeof(sajax_request_type) == "undefined" || sajax_request_type == "") 
				sajax_request_type = "GET";
			
			uri = "/";
			if (sajax_request_type == "GET") {
			
				if (uri.indexOf("?") == -1) 
					uri += "?rs=" + escape(func_name);
				else
					uri += "&rs=" + escape(func_name);
				uri += "&rst=" + escape(sajax_target_id);
				uri += "&rsrnd=" + new Date().getTime();
				
				for (i = 0; i < args.length-1; i++) 
					uri += "&rsargs[]=" + escape(args[i]);

				post_data = null;
			} 
			else if (sajax_request_type == "POST") {
				post_data = "rs=" + escape(func_name);
				post_data += "&rst=" + escape(sajax_target_id);
				post_data += "&rsrnd=" + new Date().getTime();
				
				for (i = 0; i < args.length-1; i++) 
					post_data = post_data + "&rsargs[]=" + escape(args[i]);
			}
			else {
				alert("Illegal request type: " + sajax_request_type);
			}
			
			x = sajax_init_object();
			if (x == null) {
				if (sajax_failure_redirect != "") {
					location.href = sajax_failure_redirect;
					return false;
				} else {
					sajax_debug("NULL sajax object for user agent:\n" + navigator.userAgent);
					return false;
				}
			} else {
				x.open(sajax_request_type, uri, true);
				// window.open(uri);
				
				sajax_requests[sajax_requests.length] = x;
				
				if (sajax_request_type == "POST") {
					x.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
					x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				}
			
				x.onreadystatechange = function() {
					if (x.readyState != 4) 
						return;

					sajax_debug("received " + x.responseText);
				
					var status;
					var data;
					var txt = x.responseText.replace(/^\s*|\s*$/g,"");
					status = txt.charAt(0);
					data = txt.substring(2);

					if (status == "") {
						// let's just assume this is a pre-response bailout and let it slide for now
					} else if (status == "-") 
						alert("Error: " + data);
					else {
						if (target_id != "") 
							document.getElementById(target_id).innerHTML = eval(data);
						else {
							try {
								var callback;
								var extra_data = false;
								if (typeof args[args.length-1] == "object") {
									callback = args[args.length-1].callback;
									extra_data = args[args.length-1].extra_data;
								} else {
									callback = args[args.length-1];
								}
								callback(eval(data), extra_data);
							} catch (e) {
								sajax_debug("Caught error " + e + ": Could not eval " + data );
							}
						}
					}
				}
			}
			
			sajax_debug(func_name + " uri = " + uri + "/post = " + post_data);
			x.send(post_data);
			sajax_debug(func_name + " waiting..");
			delete x;
			return true;
		}
		
				
		// wrapper for getImageFromSession		
		function x_getImageFromSession() {
			sajax_do_call("getImageFromSession",
				x_getImageFromSession.arguments);
		}
		
		

/** HIDDEN FUNCTIONS **/
	function __addEvent(o, e, f, s){
		var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
		r[r.length] = [f, s || o], o[e] = function(e){
			try{
				(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
				e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
				e.target || (e.target = e.srcElement || null);
				e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
			}catch(f){}
			for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
			return e = null, !!d;
		}
	}

	function __removeEvent(o, e, f, s){
		for(var i = (e = o["_on" + e] || []).length; i;)
			if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
				return delete e[i];
		return false;
	}
/** END HIDDEN FUNCTIONS **/



DEBUG = {
	print : function(msg) {
		var n = document.getElementById("debug");
		if (n.innerHTML == '') {
			n.style.display = "block";
			n.innerHTML = "<b>DEBUG INFO:</b><hr/>";
		} 
		n.innerHTML += msg + '<br/>';
	},
	
	printObject : function (obj) {
		DEBUG.print( DEBUG.objToStr(obj) );
	},
	
	objToStr : function (obj) {
		var result = "";
		for(var i in obj) {
			result += i + "=" + obj[i] + ";<br/>";// + "<br/>";
		}
		return result;
	},
	reset : function() {
		var n = document.getElementById("debug");
		n.innerHTML = '';
	}
}

COMMON = {
	
	IS_BROWSER_IE : true,
	
	IS_IE6 : false,
	
	init : function() {
		COMMON.browserDetect.init();
		COMMON.IS_BROWSER_IE = (COMMON.browserDetect.browser == "Explorer");
		if (COMMON.IS_BROWSER_IE) {
			COMMON.IS_IE6 = (COMMON.browserDetect.version <= 6);			
		}
		COMMON.setOpacity(document.getElementById("poweredBy"), 0);
	},

	/**
	 * set opacty dependences of browser
	 * @param {Object} object
	 * @param {value from 0 to 1} opacity
	 */
	setOpacity : function(object, opacity) {
		if (COMMON.IS_BROWSER_IE) {
			opacity = opacity * 100;
			object.style.filter = "alpha(opacity=" + opacity + ")";	
		} else  {
			object.style.opacity = opacity;
		}
	},

	/**
	 * get left corner's x,y of object 
	 * @param {Object} obj
	 */
	getAbsolutePostion : function(obj) {
		var result = {x:0,y:0};
		while (obj != null && obj.offsetParent != obj) {
			result.x += obj.offsetLeft;
			result.y += obj.offsetTop;
			obj = obj.offsetParent;
		}
		return result;
		 
	},
	
	getWindowHeight : function() {
		if (COMMON.IS_BROWSER_IE) {
			var diff = COMMON.IS_IE6 ? 4 : 0
			return document.body.parentNode.offsetHeight - diff;
		} else  {
			return  window.innerHeight;
		}
	},
	
	/**
	 * Create element
	 * @param {String} tagName
	 * @param {String} id
	 * @param {Object} parentElement
	 */
	createElement : function(tagName, id, parentElement) {
		var div = document.createElement(tagName);
		div.setAttribute("id", id);
		if (parentElement != null) {
			parentElement.appendChild(div);
		}
		return div;
	},
	 
	addEvent : function(element, eventType, doFunction){
		__addEvent(element, eventType, doFunction, false);
	},

	removeEvent : function(element, eventType, doFunction){
		__addEvent(element, eventType, doFunction, false);
	},

	browserDetect : {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]
	
	}
}


ARROWS = {
	setUpload : function() {
		document.getElementById("uploadArrows").style.display = "block";
		document.getElementById("customizeArrows").style.display = "none";
		document.getElementById("downloadArrows").style.display = "none";
	}, 
	
	setCustomize : function() {
		document.getElementById("uploadArrows").style.display = "none";
		document.getElementById("customizeArrows").style.display = "block";
		document.getElementById("downloadArrows").style.display = "none";
	}, 
	
	setDownload : function() {
		document.getElementById("uploadArrows").style.display = "none";
		document.getElementById("customizeArrows").style.display = "none";
		document.getElementById("downloadArrows").style.display = "block";
	} 
	
}

function getPanelBody(panel) {
	var divs = panel.getElementsByTagName("div")
	var i=0;
	while (divs[i].className != "panelBody") {
		i++;
	}
	return divs[i];
}

PREVIEW = {
	
	customizePanel : null,
	customizeBody : null,
	processImage : null,
	
	init : function() {
		PREVIEW.customizePanel = document.getElementById("customizePanel");
		PREVIEW.customizeBody = getPanelBody(PREVIEW.customizePanel);
		PREVIEW.processImage = document.getElementById("processImage");
		PREVIEW.ckeck();
		PREVIEW.setMessageCreate();
		COMMON.addEvent(document.getElementById("customizeBody"), 
			"click", function(e){
				PREVIEW.setMessageCreate();
				return true;
			}
		);
	},
	
	setMessageCreate : function() {
		var msg = document.getElementById("submitMessage");
		msg.innerHTML = "Satisfied?&nbsp;<label id=\"previewFormSubmit\">Create your ico!</label>";
		var previewFormSubmit = document.getElementById('previewFormSubmit');
		COMMON.addEvent(previewFormSubmit, 'click', PREVIEW.submit);		
	},
	
	setMessageReady : function() {
		var msg = document.getElementById("submitMessage");
		msg.innerHTML = "Your ico is ready";
	},
		
	enable : function() {
		PREVIEW.customizePanel.style.height = "auto";
		PREVIEW.customizeBody.style.display = "block";
		ARROWS.setCustomize();
		window.location.hash = "#customizeCaption";
	},
	
	disable : function() {
		PREVIEW.customizePanel.style.height = "100px";
		PREVIEW.customizeBody.style.display = "none";
		ARROWS.setUpload();
		document.getElementById("uploadStatus").innerHTML = "";	
	},
	
	showImage : function(imageUrl) {
		document.getElementById("uploadStatus").innerHTML = "Upload complete";	
		RESULT.disable();
		if (imageUrl == null || imageUrl == '') {
			PREVIEW.disable();
			return false;
		}
		var previewImage = document.getElementById('previewImage');
		previewImage.src = imageUrl;
		PREVIEW.enable();
		return true; 
	},
	
	ckeck : function() {
		var callbackFun = function(url) {
			PREVIEW.showImage(url);
		};
		x_getImageFromSession( callbackFun );
	},
	
	submit : function() {
		PREVIEW.processImage.style.display = "block";
		prepareForm();
		var previewForm = document.getElementById('previewForm');
		PREVIEW.putInactiveLayer();		
		previewForm.submit();
	},
	
	inactiveLayer : null,
	
	putInactiveLayer : function() {
		if (PREVIEW.inactiveLayer==null) {
			PREVIEW.inactiveLayer = COMMON.createElement("div", "inactiveLayer", document.body);
			PREVIEW.inactiveLayer.style.height = document.body.clientHeight + "px";
			COMMON.setOpacity(PREVIEW.inactiveLayer, 0);
		}
		PREVIEW.inactiveLayer.style.display = "block";		
	},

	removeInactiveLayer : function() {
		PREVIEW.inactiveLayer.style.display = "none";
	}
}

RESULT = {
	
	downloadPanel : null,
	downloadBody : null,
	
	init : function() {
		RESULT.downloadPanel = document.getElementById("downloadPanel");
		RESULT.downloadBody = getPanelBody(RESULT.downloadPanel);
	},
		
	enable : function() {
		RESULT.downloadBody.style.display = "block";
		PREVIEW.processImage.style.display = "none";
		ARROWS.setDownload();
		PREVIEW.setMessageReady();
		window.location.hash = "#downloadCaption";
	},
	
	disable : function() {
		RESULT.downloadBody.style.display = "none";
	},
	
	showResult : function(thumbnails) {
		PREVIEW.removeInactiveLayer();		
		var divs = RESULT.downloadBody.getElementsByTagName('div');
		for (var i=0; i<divs.length; i++) {
			var div = divs[i];
			if (div.id) {
				if (thumbnails[div.id]) {
					if (div.id == 'ico') {
						document.getElementById('downloadLink').href = thumbnails[div.id];
					} else {
						div.childNodes[0].src = thumbnails[div.id]; 
						div.style.display = 'block';
					}
				} else {
					div.style.display = 'none';
				}
			}
		}
		RESULT.enable();
	},
	
	setMerge48 : function() {
		var div48 = document.getElementById('th48');
		var thumbnail48 = document.getElementById('thumbnail_48');
		if (this.checked) {
			div48.className = "result_48_merge";
			//thumbnail48.style.left = '67px';
			thumbnail48.style.display = 'block';
		} else {
			div48.className = "result_48";
			//thumbnail48.style.left = '33px';
			thumbnail48.style.display = 'none';
		}
	},

	setMerge32 : function(checked) {
		var div32 = document.getElementById('th32');
		var thumbnail32 = document.getElementById('thumbnail_32');
		if (this.checked) {
			div32.className = "result_32_merge";
			//thumbnail32.style.left = '67px';
			thumbnail32.style.display = 'block';
		} else {
			div32.className = "result_32";
			//thumbnail32.style.left = '33px';
			thumbnail32.style.display = 'none';
		}
	}
}


//constants of cropBound's parts 
N_BORDER = "nBorder";
W_BORDER = "wBorder";
E_BORDER = "eBorder";
NW_BORDER = "nwBorder";
NE_BORDER = "neBorder";
CROP_BODY = "cropBody";
S_BORDER = "sBorder";
SW_BORDER = "swBorder";
SE_BORDER = "seBorder";


// mouse options
mouse = {
	isDown: false,
	cropPart: null,
	shiftCropX: 0,
	shiftCropY: 0,
	shiftX: 0,
	shiftY: 0,
	x: 0,
	y: 0
};

// preview image options 
image = {
	x: 0,
	y: 0,
	width: 0,
	height: 0,
	right: 0,
	bottom: 0
};

//cropBounds options
crop = {
	x: 0,
	y: 0,
	right: 0,
	bottom: 0,
	size: 0,
	maxSize: 0,
	minSize: 16,
	borderWidth: 5, 
	borderColor: "#9F9F9F"
}

function setShadowVisibility(prefixId, visible) {
	var shadow = document.getElementById(prefixId + "Shadow");
	shadow.style.display = (visible ? "block" : "none");
}

function hideCropBounds() {
	var cropBounds = document.getElementById('cropBounds');
	mouse.isDown = false;
	mouse.cropPart = null;
	cropBounds.style.display = 'none';
	//document.getElementById('cropButtons').style.display = 'none';
	setShadowVisibility("top", false);
	setShadowVisibility("left", false);
	setShadowVisibility("bottom", false);
	setShadowVisibility("right", false);
	hideRulers();
}

function showCropBounds() {
	document.getElementById('cropButtons').style.display = 'block';
	if (crop.x < image.x || crop.y < image.y || crop.x >= image.right) {
		initObjectsLocations();
	}
	document.getElementById('cropBounds').style.display = 'block';
	setShadowVisibility("top", true);
	setShadowVisibility("left", true);
	setShadowVisibility("bottom", true);
	setShadowVisibility("right", true);
}

function setShadowLocation(prefixId, x, y, width, height) {
		var shadow = document.getElementById(prefixId + "Shadow");
		shadow.style.left = x + "px";
		shadow.style.top = y + "px";
		shadow.style.width = width + "px";
		shadow.style.height = height + "px";
}

/*************************************************************************/

function setAllShadowsLocations() {
	try {
		if (COMMON.IS_BROWSER_IE) {
			var mozDiff = 0;
			var ieDiff = 1;
		} else {
			var mozDiff = 1;
			var ieDiff = 0;
		}
		setShadowLocation("top", image.x + ieDiff, image.y-1, image.width, crop.y+1-image.y+ieDiff);
		setShadowLocation("left", image.x, crop.y+ieDiff, crop.x-image.x+ieDiff, crop.size);
		setShadowLocation("bottom", image.x + ieDiff, crop.bottom + ieDiff, image.width, image.bottom-crop.bottom);
		setShadowLocation("right", crop.right+ieDiff, crop.y+ieDiff, image.right-crop.right, crop.size);
	} catch(e) {}
}

function setBordersLocation() {
	size = crop.size - 2* crop.borderWidth;
	left = crop.size - crop.borderWidth;
	size = size - 2;
	left = left -2;
	if (size<0) {
		return;
	}
	
	b = document.getElementById(CROP_BODY);
	b.style.width = size + "px"; 
	b.style.height = size + "px"; 
	
	b = document.getElementById(N_BORDER);
	b.style.width = size + "px"; 
	
	b = document.getElementById(NE_BORDER);
	b.style.left = left + "px"; 
	
	b = document.getElementById(W_BORDER);
	b.style.height = size + "px"; 
	
	b = document.getElementById(E_BORDER);
	b.style.left = left + "px"; 
	b.style.height = size + "px"; 
	
	b = document.getElementById(SW_BORDER);
	b.style.top = left + "px"; 
	
	b = document.getElementById(S_BORDER);
	b.style.top = left + "px"; 
	b.style.width = size + "px"; 
	
	b = document.getElementById(SE_BORDER);
	b.style.top = left + "px"; 
	b.style.left = left + "px"; 	
}

function setCropLocation(cropBounds, x, y) {
	if (cropBounds == null) {
		cropBounds = document.getElementById("cropBounds");
	}
	crop.x = x;
	crop.y = y;
	crop.right = x + crop.size;
	crop.bottom = y + crop.size;
	if (COMMON.IS_BROWSER_IE) {
		x = x + 1;
		y = y + 1;
	}
	cropBounds.style.left = x + "px";
	cropBounds.style.top = y +  "px";
	setBordersLocation();
	setAllShadowsLocations();	
}

function setCropSize(cropBounds, size) {
	crop.size = size;
	crop.right = crop.x + size;
	crop.bottom = crop.y + size;
	if (cropBounds == null) {
		cropBounds = document.getElementById("cropBounds");
	}
	size = size - 2;
	cropBounds.style.width = size + "px";
	cropBounds.style.height = size + "px";
	setBordersLocation();
	setAllShadowsLocations();	
	showRulers();
}

function hideRulers() {
}

function showRulers() {
	var height = crop.size;
	var width = crop.size;
	if (width==0) {
		return;
	}
	var size = Math.round(width/2) - 1;

	var nw = document.getElementById("ruler-nw");
	nw.style.width = size + "px";
	nw.style.height = size + "px";
	
	var ne = document.getElementById("ruler-ne");
	ne.style.height = size + "px";
	ne.style.width = (width - size - 3) + "px";

	var sw = document.getElementById("ruler-sw");
	sw.style.width = size + "px";
	sw.style.height = (height - size - 2) + "px";
}

/*************************************************************************/

function setCropBounds(x, y, size) {
	var cropBounds = document.getElementById("cropBounds");
	setCropSize(cropBounds, size);
	setCropLocation(cropBounds, x, y);
}

function moveCropTo(x, y) {
	if (x + crop.size > (image.right)) {
		x = image.right - crop.size;
	} else if (x < image.x) {
		x = image.x;
	}
	if ((y + crop.size) > (image.bottom)) {
		y = image.bottom - crop.size;
	} else if (y < image.y) {
		y = image.y;
	}
	setCropLocation(null, x, y);
}

/** ====== RESIZIN FUNCTIONS ============**/

function setCropSizeByButton() {
	switch (this.id) {
		case 'btn_48': 
			var size = 48;
			break;
		case 'btn_32': 
			var size = 32;
			break;
		case 'btn_16': 
			var size = 16;
			break;
	}
	var x = crop.x;
	var y = crop.y;
	var sizeX = size;
	var sizeY = size;
	if (crop.x + size > image.right) {
		x = image.right - size; 
		if (x < image.x) {
			x = image.x;
			sizeX = image.width;
		}
	}
	if (crop.y + size > image.bottom) {
		y = image.bottom - size; 
		if (y < image.y) {
			y = image.y;
			sizeY = image.height;
		}
	}
	setCropBounds(x, y, Math.min(sizeX, sizeY));
}

function nw_resize(x, y) {
	var c = {x:(crop.x + crop.size), y:(crop.y + crop.size)};
	var dX = c.x - x;
	var dY = c.y - y;
	size = Math.max(dX, dY);
	
	if (size < crop.minSize) {
		size = crop.minSize;
	} else {
		if (size > crop.maxSize) {
			size = crop.maxSize;
		}
		if ((c.x - size) < image.x) {
			size = c.x - image.x ;
		} 
		if ((c.y - size) < image.y) {
			size = c.y - image.y ;
		} 
	}
	x = c.x - size;
	y = c.y - size;
	setCropBounds(x, y, size);
}

function sw_resize(x, y) {
	var c = {x:(crop.x + crop.size), y:(crop.y)};
	var dX = c.x - x;
	var dY = y - c.y;
	size = Math.max(dX, dY);
	
	if (size < crop.minSize) {
		size = crop.minSize;
	} else {
		if (size > crop.maxSize) {
			size = crop.maxSize;
		}
		if ((c.x - size) < image.x) {
			size = c.x - image.x ;
		} 
		if ((c.y + size) > image.bottom) {
			size = image.bottom - c.y;
		} 
	}
	x = c.x - size;
	setCropBounds(x, crop.y, size);
}

function se_resize(x, y) {
	var c = {x:(crop.x), y:(crop.y)};
	var dX = x - c.x;
	var dY = y - c.y;
	size = Math.max(dX, dY);
	
	if (size < crop.minSize) {
		size = crop.minSize;
	} else {
		if (size > crop.maxSize) {
			size = crop.maxSize;
		}
		if ((c.x + size) > image.right) {
			size = image.right - c.x ;
		} 
		if ((c.y + size) > image.bottom) {
			size = image.bottom - c.y;
		} 
	}
	setCropSize(null, size);
}

function ne_resize(x, y) {
	var c = {x:(crop.x), y:(crop.y + crop.size)};
	var dX = x - c.x;
	var dY = c.y - y;
	size = Math.max(dX, dY);
	
	if (size < crop.minSize) {
		size = crop.minSize;
	} else {
		if (size > crop.maxSize) {
			size = crop.maxSize;
		}
		if ((c.x + size) > image.right) {
			size = image.right - c.x;
		} 
		if ((c.y - size) < image.y) {
			size = c.y - image.y ;
		} 
	}
	y = c.y - size;
	setCropBounds(crop.x, y, size);
}

function n_resize(y) {
	size = crop.size + (crop.y - y);
	if (size < crop.minSize) {
		y = crop.y + crop.size - crop.minSize;
		size = crop.minSize;
	} else {
		if (y <= image.y) {
			y = image.y;
			size = crop.size + (crop.y - y);
		}
		if ((crop.x  + size) > image.right) {
			size = image.right - crop.x; 
			y = crop.size + crop.y - size;	
		}		
	}
	setCropBounds(crop.x, y, size);
}

function w_resize(x) {
	size = crop.size + (crop.x - x);
	if (size < crop.minSize) {
		x = crop.x - crop.minSize + crop.size;
		size = crop.minSize;
	} else {
		if (x < image.x) {
			x = image.x;
			size = crop.size + (crop.x - x);
		}
		if ((crop.y  + size) > image.bottom) {
			size = image.bottom - crop.y; 
			x = crop.size + crop.x - size;	
		}		
	}
	setCropBounds(x, crop.y, size);
}

function e_resize(x) {
	size = x - crop.x;
	if (size < crop.minSize) {
		size = crop.minSize;
	} else {
		if ((crop.x + size) > (image.right)) {
			size = image.right - crop.x ;
		}
		if ((crop.y + size) > (image.bottom)) {
			size = image.bottom - crop.y;
		}
	}
	setCropSize(null, size);
}

function s_resize(y) {
	size = y - crop.y;
	if (size < crop.minSize) {
		size = crop.minSize;
	} else {
		if ((crop.x + size) > (image.right)) {
			size = image.right - crop.x ;
		}
		if ((crop.y + size) > (image.bottom)) {
			size = image.bottom - crop.y;
		}
	}
	setCropSize(null, size);
}

/** ====== RESIZIN FUNCTIONS ============**/


function changeCropSize(cropSizeNew) {
	if (cropSizeNew < crop.minSize) {
		cropSizeNew = crop.minSize;
	} else {
		if ((crop.x + cropSizeNew) > (image.width + image.x)) {
			cropSizeNew = image.width - crop.x  + image.x;
		}
		if ((crop.y + cropSizeNew) > (image.height + image.y)) {
			cropSizeNew = image.height - crop.y + image.y;
		}
	}
	setCropSize(null, cropSizeNew);
}

function returnFalse(e) {
	return false;	
}

function returnTrue(e) {
	return false;	
}

function initImagePreview() {
	var previewImage = document.getElementById("previewImage");
	image.height = previewImage.offsetHeight;
	image.width = previewImage.offsetWidth;
	var imagePos = COMMON.getAbsolutePostion(previewImage);
	image.x = imagePos.x;
	image.y = imagePos.y;
	image.right = imagePos.x + image.width;
	image.bottom = imagePos.y + image.height;

	//document.getElementById('cropButtons').style.display = 'none';
}

function initObjectsLocations() {
	initImagePreview();
	initCropBounds();
}

function initCropBounds() {
	crop.maxSize = Math.min(image.width, image.height);
	setCropBounds(image.x, image.y, crop.maxSize);
}

function setCropBorderCololor(color) {
	var boundsBorder = document.getElementById("cropBounds");
	if (color == null) {
		color = crop.borderColor
	}
	boundsBorder.style.border = "1px solid " + color;
	
	var nw = document.getElementById("ruler-nw");
	nw.style.borderBottom = "1px solid " + color;
	nw.style.borderRight = "1px solid " + color;
	var ne = document.getElementById("ruler-ne");
	ne.style.borderBottom = "1px solid " + color;
	var sw = document.getElementById("ruler-sw");
	sw.style.borderRight = "1px solid " + color;
}

function setCursor(cursor) {
	var cropBounds = document.getElementById("cropBounds");
	cropBounds.style.cursor = cursor;
}

function mouseDown(e, cropPart) {
	if (e.button <= 1) {
		mouse.isDown = true;
		mouse.cropPart = cropPart;
		mouse.shiftCropX = e.clientX - crop.x;  
		mouse.shiftCropY = e.clientY - crop.y;  
		mouse.x = e.clientX;  
		mouse.y = e.clientY;  
		mouse.shiftX = crop.x - image.x;  
		mouse.shiftY = crop.y - image.y;
		switch (mouse.cropPart) {
			case E_BORDER: 
			case NE_BORDER: 
				mouse.shiftX += crop.size;  
				break;
			case S_BORDER: 
			case SW_BORDER: 
				mouse.shiftY += crop.size;  
				break;
			case SE_BORDER: 
				mouse.shiftX += crop.size;  
				mouse.shiftY += crop.size;  
				break;
		}
		if (cropPart == CROP_BODY) {
			setCursor("move");
		}
		setCropBorderCololor("white");
	}
}



function mouseUp(e) {
	if (e.button <= 1) {
		mouse.isDown = false;
		if (mouse.cropPart == CROP_BODY) {
			setCursor("auto");
		}
		mouse.cropPart = null;
		setCropBorderCololor(null);
	}
}

function mouseMove(e) {
	if (mouse.isDown) {
		var x = image.x + e.clientX - mouse.x + mouse.shiftX;
		var y = image.y + e.clientY - mouse.y + mouse.shiftY;
		switch (mouse.cropPart) {
			case CROP_BODY: 
				moveCropTo(e.clientX - mouse.shiftCropX, e.clientY - mouse.shiftCropY);
				break;
			case N_BORDER: 
				n_resize(y);
				break;
			case W_BORDER: 
				w_resize(x);
				break;
			case S_BORDER: 
				s_resize(y);
				break;
			case E_BORDER: 
				e_resize(x);
				break;
			case NW_BORDER: 
				nw_resize(x, y);
				break;
			case NE_BORDER: 
				ne_resize(x, y);
				break;
			case SW_BORDER: 
				sw_resize(x, y);
				break;
			case SE_BORDER: 
				se_resize(x, y);
				break;
		}
	}
	
}

function (x, y) {
	if (x > 0 && y > 0) {
		return Math.max(x, y);
	} 
	if (x < 0 && y < 0) {
		return Math.min(x, y);
	}
	return x + y;
}
/**
 * set value into hidden inputs of form
 */
function prepareForm() {
	var xOffset = document.getElementById("xOffset");
	var yOffset = document.getElementById("yOffset");
	var width = document.getElementById("width");
	var height = document.getElementById("height");
	xOffset.value = getPercentX(crop.x - image.x);
	yOffset.value = getPercentY(crop.y - image.y);
	width.value = getPercentX(crop.size);
	height.value = getPercentY(crop.size);
}

function getPercentX(value) {
	return Math.round((value / image.width) * 100);
}

function getPercentY(value) {
	return Math.round((value / image.height) * 100);
}

function mmm(e) {
	DEBUG.reset();
	DEBUG.print(" x="+ e.clientX + "  y=" + e.clientY);
	DEBUG.print(" crx="+ crop.x + "  cry="+ crop.y);
}

function createCropBounds() {
	
	function createDiv(id, events, parent) {
		var div = document.createElement("div");
		div.setAttribute("id", id);
		COMMON.setOpacity(div, 0);
		for(var event in events) {
			COMMON.addEvent(div, event, function(e){events[event](e, id)});
		}
		parent.appendChild(div);
	}

	var test = document.getElementById("cropBounds");
	if (test != null) {
		return null;
	} 
	var cropBounds = document.createElement("div");
	cropBounds.setAttribute("id", "cropBounds");
	createDiv(CROP_BODY, {mousedown:mouseDown}, cropBounds);
	createDiv(N_BORDER,  {mousedown:mouseDown}, cropBounds);
	createDiv(NW_BORDER, {mousedown:mouseDown}, cropBounds);
	createDiv(NE_BORDER, {mousedown:mouseDown}, cropBounds);
	createDiv(W_BORDER,  {mousedown:mouseDown}, cropBounds);
	createDiv(E_BORDER,  {mousedown:mouseDown}, cropBounds);			
	
	createDiv(SW_BORDER, {mousedown:mouseDown}, cropBounds);
	createDiv(S_BORDER,  {mousedown:mouseDown}, cropBounds);
	createDiv(SE_BORDER, {mousedown:mouseDown}, cropBounds);

	function createRulerDiv(id, parent) {
		var div = document.createElement("div");
		div.setAttribute("id", id);
		div.style.background = "transparent";
		parent.appendChild(div);
	}
	createRulerDiv("ruler-nw", cropBounds);
	createRulerDiv("ruler-ne", cropBounds);
	createRulerDiv("ruler-sw", cropBounds);
          
	return cropBounds;
}

function createShadow(prefixId) {
	var shadow = document.createElement('div');
	shadow.className = "shadow";
	shadow.setAttribute("id", prefixId + "Shadow");
	COMMON.setOpacity(shadow, 0.6);
	return shadow;
}

function resizeWindow(e) {
	var x = image.x;
	var y = image.y;
	initImagePreview();
	x = x - image.x; 	
	y = y - image.y;
	setCropLocation(null, crop.x - x, crop.y - y);	
}

function initPreviewPanel() {
	var previewPanel = document.getElementById("previewPanel");
	if (previewPanel != null){
		cropBounds = createCropBounds();
		if (cropBounds != null) {
			var previewImage = document.getElementById('previewImage');			
			COMMON.addEvent(previewImage, "load", initObjectsLocations);

			//create shadows
			previewPanel.appendChild(cropBounds);
			previewPanel.appendChild(createShadow("top"));
			previewPanel.appendChild(createShadow("left"));
			previewPanel.appendChild(createShadow("bottom"));
			previewPanel.appendChild(createShadow("right"));

			setCropBorderCololor(null);			
			
			COMMON.addEvent(window, "resize", resizeWindow);
			if (COMMON.browserDetect.browser!="Safari") {
				COMMON.addEvent(document, "mousedown", returnFalse);
			}
			COMMON.addEvent(document, "selectstart", returnFalse);
			COMMON.addEvent(document, "mousemove", function(e){mouseMove(e)});
			COMMON.addEvent(document, "mouseup", function(e){mouseUp(e)});
			var previewForm = document.getElementById("previewForm");
			COMMON.addEvent(previewForm, "submit", function(e){prepareForm(e)});
		}
	}
}

function test() {
	alert('test');
}
UPLOAD = {
	init : function() {
		var fakefile = document.createElement('div');
		fakefile.className = 'fakefile';
		var input = document.createElement('input');
		input.type = "text";
		input.readOnly = true;
		var browse = document.createElement('label');
		browse.type = "button";
		browse.innerHTML = "Browse...";
	
		var fileInput = document.getElementById('fileInput');
		fileInput.size = 25;
		fileInput.className = 'file_hidden';
		COMMON.setOpacity(fileInput, 0);
		fileInput.relatedElement = input;
	
		fakefile.appendChild(input);
		fakefile.appendChild(browse);
		fileInput.parentNode.appendChild(fakefile );
	
		//set location of visible element
		var browserLeft = fileInput.offsetLeft + fileInput.offsetWidth - browse.offsetWidth - 5; 
		browse.style.left = browserLeft + "px";
		browse.style.top = fileInput.offsetTop + 'px';
	
		input.style.left = fileInput.offsetLeft + 'px';
		input.style.top = fileInput.offsetTop + 'px';
		var width = browserLeft - fileInput.offsetLeft -10;
		if (COMMON.IS_BROWSER_IE) {
			width = width -3;
		}
		input.style.width = width + 'px';
		
		//set location for upload status
		var status = document.getElementById("uploadStatus");
		status.style.left = browse.offsetLeft + browse.offsetWidth + 'px';
		status.style.top = browse.offsetTop + 'px';
		
		//set events
		var setInputText = function () {
			document.getElementById("uploadStatus").innerHTML = "Now uploading your image...";
			this.relatedElement.value = this.value;
			var uploadForm = document.getElementById('uploadForm');
			uploadForm.submit();
		};
		COMMON.addEvent(fileInput, 'change', setInputText);
	}
}

ERROR = {
	background : null,
	panel : null,
	messages : null,
	
	init : function() {

		if (ERROR.background == null) {
			document.getElementById("uploadStatus").innerHTML = "";	
			ERROR.background = COMMON.createElement("div", "errorBackground", document.body);
			
			if (COMMON.IS_IE6) {
				ERROR.setBackgroundPosition = function() {
					var t = document.documentElement.scrollTop;
					var h = document.body.clientHeight - t;
					if (ERROR.background.offsetHeight < h || t < ERROR.background.offsetTop) {
						ERROR.background.style.top = t + "px";
					} else {
						var hh = Math.max(document.body.clientHeight, COMMON.getWindowHeight());
						ERROR.background.style.height = hh-ERROR.background.offsetTop + "px";
					}
				}
				ERROR.background.style.position = "absolute";
				COMMON.addEvent(window, "scroll", ERROR.setBackgroundPosition);
			}
			
			var errorFront = COMMON.createElement("div", "errorFront", ERROR.background);
			var errorBorder = COMMON.createElement("div", "errorBorder", errorFront);
			ERROR.panel = COMMON.createElement("div", "errorPanel", errorBorder);
			var closeButton = COMMON.createElement("img", "closeButton", ERROR.panel);
			closeButton.src = "img/close.gif"; 
			var closeText = COMMON.createElement("label", "closeText", ERROR.panel);
			closeText.innerHTML = "Close";
			var errorTitle = COMMON.createElement("p", "errorTitle", ERROR.panel)
			errorTitle.innerHTML = "Error";
			var errorShadow = COMMON.createElement("div", "errorShadow", errorFront);
			COMMON.setOpacity(errorShadow, 0.4);

			COMMON.addEvent(closeButton, "click", ERROR.hide);
			COMMON.addEvent(closeText, "click", ERROR.hide);
			COMMON.addEvent(window, "resize", ERROR.setBackgroundSize);
		}
	},
	
	setBackgroundSize : function() {
		ERROR.background.style.height = COMMON.getWindowHeight() + "px";
	},	
	
	setBackgroundPosition : function() {
	},
	
	show : function(msg) {
		ERROR.init();
		ERROR.messages = new Array();
		for(var i = 0; i < msg.length; i++) {
			var text = document.createElement("p");
			text.className = "errorText";
			text.innerHTML = msg[i];
			ERROR.messages[i] = text;
			ERROR.panel.appendChild(text); 
		}
		ERROR.setBackgroundSize();
		ERROR.setBackgroundPosition();
		//PREVIEW.disable();
		ERROR.background.style.display = "block";
	},
	
	hide : function() {
		ERROR.background.style.display = "none";
		a = document.getElementById("");
		for(var i = 0; i < ERROR.messages.length; i++) {
			ERROR.panel.removeChild(ERROR.messages[i]);
		}
	}
}

/*
	CRIR - Checkbox & Radio Input Replacement
	Author: Chris Erwin (me[at]chriserwin.com)
	www.chriserwin.com/scripts/crir/

	Updated July 27, 2006.
	Jesse Gavin added the AddEvent function to initialize
	the script. He also converted the script to JSON format.
	
	Updated July 30, 2006.
	Added the ability to tab to elements and use the spacebar
	to check the input element. This bit of functionality was
	based on a tip from Adam Burmister.
*/

crir = {
	userAgent: '',
	isSafari: false,
	init: function() {
		this.userAgent = navigator.userAgent.toLowerCase();
		this.isSafari = ((this.userAgent.indexOf('safari')!=-1)&&(this.userAgent.indexOf('mac')!=-1))?true:false;
		if (this.isSafari) {
			return;
		}
		
		arrLabels = document.getElementsByTagName('label');
		searchLabels:
		for (var i=0; i<arrLabels.length; i++) {			
			// get the input element based on the for attribute of the label tag
			if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value != '') {
				labelElementFor = arrLabels[i].getAttributeNode('for').value;				
				inputElement = document.getElementById(labelElementFor);
			}
			else {				
				continue searchLabels;
			}	
							
			inputElementClass = inputElement.className;	
		
			// if the input is specified to be hidden intiate it
			if (inputElementClass == 'crirHiddenJS') {
				inputElement.className = 'crirHidden';
				
				inputElementType = inputElement.getAttributeNode('type').value;	
				
				// add the appropriate event listener to the input element
				if (inputElementType == "checkbox") {
					inputElement.onclick = crir.toggleCheckboxLabel;
				}
				else {
					inputElement.onclick = crir.toggleRadioLabel;
				}
				
				// set the initial label state
				if (inputElement.checked) {
					if (inputElementType == 'checkbox') { arrLabels[i].className = 'checkbox_checked'}
					else { arrLabels[i].className = 'radio_checked' }
				}
				else {
					if (inputElementType == 'checkbox') { arrLabels[i].className = 'checkbox_unchecked'}
					else { arrLabels[i].className = 'radio_unchecked' }
				}
			}
			else if (inputElement.nodeName != 'SELECT' && inputElement.getAttributeNode('type').value == 'radio') { // this so even if a radio is not hidden but belongs to a group of hidden radios it will still work.
				arrLabels[i].onclick = crir.toggleRadioLabel;
				inputElement.onclick = crir.toggleRadioLabel;
			}
		}
	},	
	
	findLabel: function (inputElementID) {
		arrLabels = document.getElementsByTagName('label');
	
		searchLoop:
		for (var i=0; i<arrLabels.length; i++) {
			if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value == inputElementID) {				
				return arrLabels[i];
				break searchLoop;				
			}
		}		
	},	
	
	toggleCheckboxLabel: function () {
		labelElement = crir.findLabel(this.getAttributeNode('id').value);
	
		if(labelElement.className == 'checkbox_checked') {
			labelElement.className = "checkbox_unchecked";
		}
		else {
			labelElement.className = "checkbox_checked";
		}
	},	
	
	toggleRadioLabel: function () {			 
		clickedLabelElement = crir.findLabel(this.getAttributeNode('id').value);
		
		clickedInputElement = this;
		clickedInputElementName = clickedInputElement.getAttributeNode('name').value;
		
		arrInputs = document.getElementsByTagName('input');
	
		// uncheck (label class) all radios in the same group
		for (var i=0; i<arrInputs.length; i++) {			
			inputElementType = arrInputs[i].getAttributeNode('type').value;
			if (inputElementType == 'radio') {
				inputElementName = arrInputs[i].getAttributeNode('name').value;
				inputElementClass = arrInputs[i].className;
				// find radio buttons with the same 'name' as the one we've changed and have a class of chkHidden
				// and then set them to unchecked
				if (inputElementName == clickedInputElementName && inputElementClass == 'crirHidden') {				
					inputElementID = arrInputs[i].getAttributeNode('id').value;
					labelElement = crir.findLabel(inputElementID);
					labelElement.className = 'radio_unchecked';
				}
			}
		}
	
		// if the radio clicked is hidden set the label to checked
		if (clickedInputElement.className == 'crirHidden') {
			clickedLabelElement.className = 'radio_checked';
		}
	}	
}


//addEvent(window, 'load', crir.init);

window.onload = function() {
	//detect browser's type
	COMMON.init();
	
	document.PREVIEW = PREVIEW;
	document.RESULT = RESULT;
	document.UPLOAD = UPLOAD;
	document.ERROR = ERROR;
	UPLOAD.init();
	crir.init();
	PREVIEW.init();
	RESULT.init();
	initPreviewPanel()
	
	//set events for showing/hiding cropBounds
	var rbHideCrop = document.getElementById('rbHideCrop');
	var rbShowCrop = document.getElementById('rbShowCrop');
	COMMON.addEvent(rbHideCrop, 'click', hideCropBounds);
	COMMON.addEvent(rbShowCrop, 'click', showCropBounds);
	
	var cb48 = document.getElementById('cb48');
	var cb32 = document.getElementById('cb32');
	COMMON.addEvent(cb48, 'click', RESULT.setMerge48);
	COMMON.addEvent(cb32, 'click', RESULT.setMerge32);

	var btn_48 = document.getElementById('btn_48');
	var btn_32 = document.getElementById('btn_32');
	var btn_16 = document.getElementById('btn_16');
	COMMON.addEvent(btn_48, 'click', setCropSizeByButton);
	COMMON.addEvent(btn_32, 'click', setCropSizeByButton);
	COMMON.addEvent(btn_16, 'click', setCropSizeByButton);	
}

