var tx,dragtx,tw;
var ty,dragty,th;
//file name
var current_pic = '';
var current_history = 0;
//list of files(path) by step, 0 - original
var pic_history = [];
var effect_params = [];
var hexHistory = 255;

//define historymessage constants for setHistoryText()
var TEXT_RESIZE_75 = 'Your picture has been resized by 75%';
var TEXT_RESIZE_50 = 'Your picture has been resized by 50%';
var TEXT_RESIZE_25 = 'Your picture has been resized by 25%';
var TEXT_RESIZE_CUSTOM = 'Your picture has been resized to a custom size.';
var TEXT_CROP = 'Your picture has been cropped. Press Ctrl+Z to undo this action.';
var TEXT_NEW_SELECTION = 'You have made a selection. Click inside and drag to move. Hold down the Shift key while resizing<br/>the selection to contrain to a square. Double-click inside to crop. Click outside to deselect.';
var TEXT_DESELECT = 'Your selection has been deselected.';
var TEXT_UNDO = 'You have undone the previous action.';
var TEXT_REDO = 'You have redid the previously undid action.';
var TEXT_ROTATE_CW = 'Your picture has been rotated 90 degrees clockwise.';
var TEXT_ROTATE_CCW = 'Your picture has been rotated 90 degrees counter-clockwise.';
var TEXT_ROTATE_180 = 'Your picture has been rotated 180 degrees (upside down).';
var TEXT_BRIGHTNESS;
var TEXT_CONSTRAST;
var TEXT_AUTOFIX;
var TEXT_RAISE;
var TEXT_FRAME;
var TEXT_BLUR;
var TEXT_SPREAD;
var TEXT_GRAYSCALE;
var TEXT_SHARPEN;
var TEXT_EQUALIZE;
var TEXT_OILPAINT;
var TEXT_BRUSH;
var TEXT_POLAROID;

function preHide()
{
	hideBrush();
}

function hideCanvas(dlgName)
{
	if(dlgName != "BrushDialog") {
		hideBrush();
	} else {
		showBrush();
	}
}

function lockRatio(){
	if (document.all || document.getElementById){
		if (document.getElementById('lockratio').checked==true){
			document.pre_form.elements.im_hmu.disabled=true;
			document.pre_form.elements.im_height.disabled=true;
			document.getElementById('ResizeHeight').style.color = '#808080';
			document.getElementById('ratiolock').style.visibility = 'visible';
		}
		else {
                        document.pre_form.elements.im_hmu.disabled=false;
                        document.pre_form.elements.im_height.disabled=false;
			document.getElementById('ResizeHeight').style.color = '#000000';
			document.getElementById('ratiolock').style.visibility = 'hidden';
		}
	}
}


function setHistoryText(historymessage,historyicon){
	var showhistoryicon;
	if(historyicon == 'SUCCESS') showhistoryicon = 'check.gif';
	else if(historyicon == 'INFO') showhistoryicon = 'info.gif';
	else showhistoryicon = 'check.gif'; 
	document.getElementById("HistoryText").innerHTML = '<img src="images/'+ showhistoryicon +'" align="absbottom"> ' + historymessage;
	fadeHistoryText();
}

function fadeHistoryText(){
	if(hexHistory>0) {
		hexHistory-=11;
		document.getElementById("HistoryText").style.color="rgb("+hexHistory+","+hexHistory+","+hexHistory+")";
		setTimeout("fadeHistoryText()",30);
	}
	else {
		hexHistory=255

	}
}

function ajaxHistoryText(){
	document.getElementById("HistoryText").innerHTML = '<img src="images/ajax.gif">';
}


function changeText()
{
	var o_text = window.document.getElementById('pic_label');
	param_text = window.document.getElementById('label');
	text = param_text.value
	if (text.length > 0) {
		document.getElementById('pic_text').style.display = "block";
		font = window.document.getElementById('tt_font');
		color = window.document.getElementById('tt_color');
		size = window.document.getElementById('tt_size');
		
		
		var src = "/?rm=show_text&label=" + text +"&size="+size.value+"&font="+font.value+ "&color="+color.value.replace(/#/, '');
		
		if (o_text.style.filter) {
			o_text.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='image')";
		} else {
			o_text.src = src;
		}
	} else {
		document.getElementById('pic_text').style.display = "none";
	}
}

function startMoveText(e)
{
	var pic_text = document.getElementById('pic_text');
	var pic_label = document.getElementById('pic_label');
	var pic = window.document.getElementById('select_pic');
	
	var o_div = window.document.getElementById('pic_sel');
	
	var text_pos = get_object_position(pic_text);
	var pic_pos = get_object_position(pic);
	var oPosition = get_event_position1(e);
	
	//x1 = pic_pos.left;
	//y1 = pic_pos.top;
	//x2 = pic_pos.left + pic_pos.width;
	//y2 = pic_pos.top + pic_pos.height;
	
	//o_div.style.clip = "rect("+x1+","+y1+","+x2+","+y2+")";

	dragtx = oPosition.x;
	dragty = oPosition.y;
	tx = (text_pos.x-pic_pos.x);
	ty = (text_pos.y-pic_pos.y);
	
	pic.onmousemove = dragText;
	pic_text.onmousemove = dragText;
	document.onmouseup = stopMoveText;
}

function dragText(e)
{
	var pic_text = document.getElementById('pic_text');
	var pic = window.document.getElementById('select_pic');

	var pic_pos = get_object_position(pic);
	var oPosition = get_event_position1(e);
	
	dx = dragtx - oPosition.x;
	dy = dragty - oPosition.y;

	dragtx = oPosition.x;
	dragty = oPosition.y;

	new_x = tx - dx;
	new_y = ty - dy;
	
	tw = pic_text.width;
	th = pic_text.height;
	
	//if ((new_x+tw) < pic.width && new_x >= 0) {
		tx = new_x;
	//}
	//if ((new_y+th) < pic.height && new_y >= 0) {
		ty = new_y;
	//}
	
	if (ty<0) {
		cy1 = ty*(-1);
	} else {
		cy1 = "auto";
	}
	
	if (tx<pic.width) {
		cx1 = pic.width - tx;
	} else {
		cx1 = "auto";
	}
	if (ty<pic.height) {
		cy2 = pic.height - ty;
	} else {
		cy2 = "auto";
	}
	
	if (tx<0) {
		cx2 = tx*(-1);
	} else {
		cx2 = "auto";
	}
	pic_text.style.clip = "rect("+cy1+","+cx1+","+cy2+","+cx2+")";
	
	pic_text.style.left = tx + 'px';
	pic_text.style.top = ty + 'px';
}

function stopMoveText(e)
{
	var pic_text = document.getElementById('pic_text');
	var pic = window.document.getElementById('select_pic');
	var text_x = window.document.getElementById('text_x');
	var text_y = window.document.getElementById('text_y');
	text_x.value = tx;
	text_y.value = ty;
	pic.onmousemove = function() {return false;};
	pic_text.onmousemove = function() {return false;};
}

function setFile(name, pic_name)
{
	var o_pic = window.document.getElementById('select_pic');
	var o_exif = window.document.getElementById('pic_exif');
	current_pic = pic_name;
	pic_history.length = 1;
	current_history = 0;
	pic_history[current_history] = name;
	o_pic.src = name;
	o_pic.style.display = "block";
}

function setOpacity(value)
{
	var o_pic_dark = window.document.getElementById('pic_dark');
	o_pic_dark.style.opacity = value/10;
	o_pic_dark.style.filter = 'alpha(opacity=' + value*10 + ')';
}

function processing()
{
	var o_pic_dark = document.getElementById('pic_dark');
	var pic = document.getElementById('select_pic');
	o_pic_dark.style.top = 0+"px";
	o_pic_dark.style.left = 0+"px";
	o_pic_dark.style.width = pic.width+"px";
	o_pic_dark.style.height = pic.height+"px";
	setOpacity(4);
	o_pic_dark.style.display = 'block';
	o_pic_dark.style.zIndex=999;
	/*
	for (var i=1;i<5;i++) {
	setTimeout('setOpacity('+i+')',50*i);
	}
	*/
	return false;
}

function on_load_image()
{
	var o_pic = window.document.getElementById('select_pic');
	var show_size = window.document.getElementById('show_size');
	var canvas = window.document.getElementById('pic_canvas');
	canvas.width = o_pic.width;
	canvas.style.width = o_pic.width;
	canvas.height = o_pic.height;
	canvas.style.height = o_pic.height;
	canvas.style.position = "absolute";
	show_size.innerHTML = o_pic.width+"x"+o_pic.height;
	no_dark();
}

function no_dark()
{
	var o_pic_dark = document.getElementById('pic_dark');
	o_pic_dark.style.display = 'none';
	//setOpacity(10);
}

function getrandom()
{
	var min_random = 0;
	var max_random = 1000000;

	max_random++;

	var range = max_random - min_random;
	var n=Math.floor(Math.random()*range) + min_random;

	return n;
}

function original()
{
	if(current_history > 0){
		if(confirm("[Revert Back to Original Picture] You will lose all of your modifications to this picture. This cannot be undone. Are you sure?")){
			coords_zero();
			//get pic by id
			var o_pic = window.document.getElementById('select_pic');
			current_history = 0;
			pic_history.length = 1;
			o_pic.src = pic_history[current_history];
			o_pic.onload = on_load_image;
			document.undo_button.src='images/undo_button_disabled.gif';
			document.redo_button.src='images/redo_button_disabled.gif';
			document.original_button.src='images/original_button_disabled.gif';
		}
	}
}

function undobutton(undo_mouse){
	if (current_history > 0){
		if (undo_mouse == 'on'){
			document.undo_button.src='images/undo_button_on.gif';
		}
		else {
			document.undo_button.src='images/undo_button.gif';
		}
	}
}

function redobutton(redo_mouse){
	if (pic_history.length > current_history+1) {
		if (redo_mouse == 'on'){
			document.redo_button.src='images/redo_button_on.gif';
		}
		else {
			document.redo_button.src='images/redo_button.gif';
		}
	}
}

function originalbutton(original_mouse){
        if (pic_history.length > 1){
                if (original_mouse == 'on'){
                        document.original_button.src='images/original_button_on.gif';
                }
                else {
                        document.original_button.src='images/original_button.gif';
                }
        }
}



function undo()
{
	if (current_history > 0) {
		ajaxHistoryText();
		coords_zero();
		//get pic by id
		var o_pic = window.document.getElementById('select_pic');
		document.redo_button.src='images/redo_button.gif';
		current_history = current_history - 1;
		if (current_history == 0){
			document.undo_button.src='images/undo_button_disabled.gif';
		}
		setHistoryText(TEXT_UNDO,"SUCCESS");
		o_pic.src = pic_history[current_history];
		o_pic.onload = on_load_image;
	}
}

function redo()
{
	if (pic_history.length > current_history+1) {
		ajaxHistoryText();
		coords_zero();
		//get pic by id
		var o_pic = window.document.getElementById('select_pic');
		document.undo_button.src='images/undo_button.gif';
		current_history = current_history + 1;
		//alert(pic_history.length);
		if(current_history == pic_history.length-1){
			document.redo_button.src='images/redo_button_disabled.gif';
		}
		setHistoryText(TEXT_REDO,"SUCCESS");
		o_pic.src = pic_history[current_history];
		o_pic.onload = on_load_image;
	}
}

function hideParams()
{
//	document.getElementById('params_crop').style.display = "none";
//	document.getElementById('params_paloroid').style.display = "none";
//	document.getElementById('params_contrast').style.display = "none";
//	document.getElementById('params_brightness').style.display = "none";
//	document.getElementById('params_blur').style.display = "none";
//	document.getElementById('params_spread').style.display = "none";
//	document.getElementById('params_raised_frame').style.display = "none";
//	document.getElementById('params_raise').style.display = "none";
//	document.getElementById('params_apply_to').style.display = "none";
//	document.getElementById('params_apply').style.display = "none";
//	document.getElementById('rotate_to').style.display = "none";
//	document.getElementById('params_resize').style.display = "none";
//	document.getElementById('params_text').style.display = "none";
	
	document.getElementById('pic_canvas').style.display = "none";
	
	document.getElementById('pic_text').style.display = "none";
}

function actionEffect()
{
	effect_params['coord_x'] = document.getElementById('coord_x').value;
	effect_params['coord_y'] = document.getElementById('coord_y').value;
	effect_params['width'] = document.getElementById('width').value;
	effect_params['height'] = document.getElementById('height').value;
//	if (document.pre_form.elements.apply_to[0].checked) {
//		effect_params['apply_to'] = "selected_area";
//	} else {
//		effect_params['apply_to'] = "entire_picture";
//	}
	switch (effect_params['effect']) {
		case "oil_paint":
		        if (document.pre_form.elements.apply_to_oilpaint[0].checked) {
				TEXT_OILPAINT = 'You have applied the Oil Paint effect to the entire picture.';
		                effect_params['apply_to'] = "entire_picture";
        		} else {
				TEXT_OILPAINT = 'You have applied the Oil Paint effect to the selected area.';
                		effect_params['apply_to'] = "selected_area";
        		}
		break;
		
		case "equalize":
		        if (document.pre_form.elements.apply_to_equalize[0].checked) {
				TEXT_EQUALIZE = 'You have applied the Equalize effect to the entire picture.';
		                effect_params['apply_to'] = "entire_picture";
        		} else {
				TEXT_EQUALIZE = 'You have applied the Equalize effect to the selected area.';
                		effect_params['apply_to'] = "selected_area";
        		}
		break;		
		
		case "sharpen":
		        if (document.pre_form.elements.apply_to_sharpen[0].checked) {
				TEXT_SHARPEN = 'You have applied the Sharpen effect to the entire picture.';
		                effect_params['apply_to'] = "entire_picture";
        		} else {
				TEXT_SHARPEN = 'You have applied the Sharpen effect to the selected area.';
                		effect_params['apply_to'] = "selected_area";
        		}
		break;		
		
		case "grayscale":
		        if (document.pre_form.elements.apply_to_grayscale[0].checked) {
				TEXT_GRAYSCALE = 'You have applied the Grayscale effect to the entire picture.';
		                effect_params['apply_to'] = "entire_picture";
        		} else {
				TEXT_GRAYSCALE = 'You have applied the Grayscale effect to the selected area.';
                		effect_params['apply_to'] = "selected_area";
        		}
		break;		
		
		case "spread":
			effect_params['spread'] = document.getElementById('spread').value;
		        if (document.pre_form.elements.apply_to_spread[0].checked) {
				TEXT_SPREAD = 'You have applied the Spread effect to the entire picture.';
		                effect_params['apply_to'] = "entire_picture";
        		} else {
				TEXT_SPREAD = 'You have applied the Spread effect to the selected area.';
                		effect_params['apply_to'] = "selected_area";
        		}
		break;

		case "gaussian_blur":
			effect_params['radius_blur'] = document.getElementById('radius_blur').value;
		        if (document.pre_form.elements.apply_to_blur[0].checked) {
				TEXT_BLUR = 'You have applied the Gaussian Blur effect to the entire picture.';
		                effect_params['apply_to'] = "entire_picture";
        		} else {
				TEXT_BLUR = 'You have applied the Gaussian Blur effect to the selected area.';
                		effect_params['apply_to'] = "selected_area";
        		}		
		break;

		case "contrast":
		if (document.pre_form.elements.contrast[0].checked) {
			effect_params['contrast'] = 1;
		}
		if (document.pre_form.elements.contrast[1].checked) {
			effect_params['contrast'] = 0;
		}

		if (!document.pre_form.apply_to_contrast.checked) {
			TEXT_CONTRAST = 'You have adjusted the contrast of the entire picture.';
	        	effect_params['apply_to'] = "entire_picture";
        	} else {
			TEXT_CONTRAST = 'You have adjusted the contrast of the selected area.';
        		effect_params['apply_to'] = "selected_area";
        	}

		//effect_params['contrast'] = document.getElementById('contrast').value;
		break;

		case "brightness":
		effect_params['brightness'] = document.getElementById('brightness').value;
		        if (!document.pre_form.apply_to_brightness.checked) {
                                TEXT_BRIGHTNESS = 'You have adjusted the brightness of the entire picture.';
				effect_params['apply_to'] = "entire_picture";
                        } else {
				TEXT_BRIGHTNESS = 'You have adjusted the brightness of the selected area.';
                                effect_params['apply_to'] = "selected_area";
                        }

		break;

                case "autofix":
                        if (!document.pre_form.apply_to_autofix.checked) {
				TEXT_AUTOFIX = 'You have applied the Auto Fix feature to the entire picture.';
                                effect_params['apply_to'] = "entire_picture";
                        } else {
				TEXT_AUTOFIX = 'You have applied the Auto Fix feature to the selected area.';
                                effect_params['apply_to'] = "selected_area";
                        }

                break;


		case "raise":
			effect_params['raise'] = document.getElementById('raise').value;
		        if (document.pre_form.elements.apply_to_raise[0].checked) {
				TEXT_RAISE = 'You have applied the Raise effect to the entire picture.';
		                effect_params['apply_to'] = "entire_picture";
        		} else {
				TEXT_RAISE = 'You have applied the Raise effect to the selected area.';
                		effect_params['apply_to'] = "selected_area";
        		}
		break;

		case "raised_frame":
			effect_params['raised_color'] = document.getElementById('im_color').value;
			effect_params['raised'] = document.getElementById('raised').value;
                        if (!document.pre_form.apply_to_frame.checked) {
				TEXT_FRAME = 'You have applied the Raised Frame effect to the entire picture.';
                                effect_params['apply_to'] = "entire_picture";
                        } else {
				TEXT_FRAME = 'You have applied the Raised Frame effect to the selected area.';
                                effect_params['apply_to'] = "selected_area";
                        }

		break;
		
		case "text":
		_text();
		return false;
		break;
		
		case "brush":
		_brush();
		return false;
		break;

		case "paloroid":
		/*
		if (document.pre_form.elements.paloroid[0].checked) {
			effect_params['paloroid'] = "rotate_left";
		}
		if (document.pre_form.elements.paloroid[1].checked) {
			effect_params['paloroid'] = "stack";
		}
		if (document.pre_form.elements.paloroid[2].checked) {
			effect_params['paloroid'] = "rotate_right";
		}
		effect_params['paloroid_color'] = document.getElementById('paloroid_color').value;
		*/
		paloroid();
		return false;
		break;
	}
	effect_params['pic_data'] = { 'current_history' : current_history, 'file' : pic_history[current_history], 'current_pic' : current_pic };
	doEffect(effect_params);
}

function resize()
{
	hideParams();
	document.getElementById('params_resize').style.display = "block";
}

function doResize(resizetype)
{

	var resizeHistoryText;
        if(current_pic == ''){
                alert('Please upload a picture first.');
        } else {
	ajaxHistoryText();
	if (resizetype == '25') {
		effect_params['im_resize'] = "twentyfive";
		resizeHistoryText = TEXT_RESIZE_75;
	}
	if (resizetype == '50') {
		effect_params['im_resize'] = "fifty";
		resizeHistoryText = TEXT_RESIZE_50;
	}
	if (resizetype == '75') {
		effect_params['im_resize'] = "seventyfive";
		resizeHistoryText = TEXT_RESIZE_25;
	}
	if (resizetype == 'custom') {
		effect_params['im_resize'] = "custom";
		effect_params['im_height'] = document.pre_form.elements.im_height.value;
		effect_params['im_hmu'] = document.pre_form.elements.im_hmu.value;
		effect_params['im_width'] = document.pre_form.elements.im_width.value;
		effect_params['im_wmu'] = document.pre_form.elements.im_wmu.value;
		resizeHistoryText = TEXT_RESIZE_CUSTOM;
	}

	effect_params['pic_data'] = { 'current_history' : current_history, 'file' : pic_history[current_history], 'current_pic' : current_pic };
	//get pic by id
	var o_pic = window.document.getElementById('select_pic');
	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	// Code automatically called on load finishing.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			//cut history
			document.undo_button.src='images/undo_button.gif';
			document.original_button.src='images/original_button.gif';
			pic_history.length = current_history+1;
			file_name = req.responseJS.name;
			o_pic.src = file_name;
			current_history = current_history + 1;
			pic_history[current_history] = file_name;
			//alert('ok');
			coords_zero();
			setHistoryText(resizeHistoryText,'SUCCESS');
			o_pic.onload = on_load_image;
		}
	}
	// Prepare request object (automatically choose GET or POST).
	req.open(null, '/index.php?rm=do_resize', true);
	// Send whole form data to backend.
	req.send( effect_params );
	processing();
	}
}

function doEmail()
{
        ext = document.getElementById('save_as_ext').value;
        qlty = document.getElementById('save_quality').value;

	var email_address = 'mrnich@gmail.com';
        var req = new JsHttpRequest();
        // Code automatically called on load finishing.
        req.onreadystatechange = function() {
                if (req.readyState == 4) {
			alert('this works');
                }
        }
        // Prepare request object (automatically choose GET or POST).
        req.open(null, '/index.php?rm=do_email', true);
        // Send whole form data to backend.
        req.send( { 'pic' : pic_history[current_history], 'ext' : ext, 'quality' : qlty, 'email_address' : 'nich@nich.net' } );


}

function effect(effect_name)
{
	hideParams();
	
//	clearBrush();
	effect_params['effect'] = effect_name;
//	hideParams();
	switch (effect_name) {
		case "oil_paint":
		break;
		case "equalize":
		break;
		case "sharpen":
		break;
		case "grayscale":
		break;
		case "raise":
		break;
		case "raised_frame":
		break;

		case "spread":
		break;
		case "gaussian_blur":
		break;

		case "contrast":
		break;

		case "brightness":
		break;
		case "autofix":
		break;

		case "paloroid":
		break;
		
		case "text":
		//	document.getElementById('pic_text').style.display = 'block';
		break;

		default: return;
	}
}

function crop()
{
	effect_params['coord_x'] = document.getElementById('coord_x').value;
	effect_params['coord_y'] = document.getElementById('coord_y').value;
	effect_params['width'] = document.getElementById('width').value;
	effect_params['height'] = document.getElementById('height').value;
	effect_params['pic_data'] = { 'current_history' : current_history, 'file' : pic_history[current_history], 'current_pic' : current_pic };
	if (effect_params['width'] > 0 && effect_params['height'] > 0) {
		//document.getElementById('params_crop').style.display = "none";
		doCrop(effect_params);
	} else {
		if(current_pic == ''){
			alert('Please upload a picture first.');
		}
		else{
			alert('To crop, make a selection first by clicking and dragging on your picture.');
		}
		hideParams();
		//document.getElementById('params_crop').style.display = "block";
	}
}

function email()
{
        if(current_pic == ''){
                alert('There is nothing to save. Please upload a picture first.');
        } else {

	doEmail();
	}
}

function rotate()
{
	hideParams();
//	document.getElementById('rotate_to').style.display = "block";
}

function doBrush()
{
	effect_params['pic_data'] = { 'current_history' : current_history, 'file' : pic_history[current_history], 'current_pic' : current_pic };
	//get pic by id
	var o_pic = window.document.getElementById('select_pic');
	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	// Code automatically called on load finishing.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			//cut history
			document.undo_button.src='images/undo_button.gif';
			document.original_button.src='images/original_button.gif';
			pic_history.length = current_history+1;
			file_name = req.responseJS.name;
			o_pic.src = file_name;
			current_history = current_history + 1;
			pic_history[current_history] = file_name;
			//alert('ok');
			coords_zero();
			o_pic.onload = no_dark;
		}
	}
	// Prepare request object (automatically choose GET or POST).
	req.open(null, '/index.php?rm=do_brush', true);
	// Send whole form data to backend.
	req.send( effect_params );
	processing();
}

function doRotate(rotatetype)
{
	var USE_ROTATE_TEXT;
	if(current_pic == ''){
		alert('Please upload a picture first.');
	} else {	
	ajaxHistoryText();
	if (rotatetype == 'CW') {
		effect_params['rotate'] = "rotate_cw";
		USE_ROTATE_TEXT = TEXT_ROTATE_CW;
	}
	if (rotatetype == 'CCW') {
		effect_params['rotate'] = "rotate_ccw";
		USE_ROTATE_TEXT = TEXT_ROTATE_CCW;
	}
	if (rotatetype == '180') {
		effect_params['rotate'] = "rotate_flip";
		USE_ROTATE_TEXT = TEXT_ROTATE_180;
	}
	effect_params['pic_data'] = { 'current_history' : current_history, 'file' : pic_history[current_history], 'current_pic' : current_pic };
	//get pic by id
	var o_pic = window.document.getElementById('select_pic');
	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	// Code automatically called on load finishing.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			//cut history
			document.undo_button.src='images/undo_button.gif';
			document.original_button.src='images/original_button.gif';
			pic_history.length = current_history+1;
			file_name = req.responseJS.name;
			o_pic.src = file_name;
			current_history = current_history + 1;
			pic_history[current_history] = file_name;
			//alert('ok');
			coords_zero();
//			o_pic.onload = no_dark;
			setHistoryText(USE_ROTATE_TEXT,'SUCCESS');
			o_pic.onload = on_load_image;
		}
	}
	// Prepare request object (automatically choose GET or POST).
	req.open(null, '/index.php?rm=do_rotate', true);
	// Send whole form data to backend.
	req.send( effect_params );
	processing();
	}
}

function doCrop(params)
{
        if(current_pic == ''){
                alert('Please upload a picture first.');
        } else {
	ajaxHistoryText();
	//get pic by id
	var o_pic = window.document.getElementById('select_pic');
	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	// Code automatically called on load finishing.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			//cut history
			document.undo_button.src='images/undo_button.gif';
			document.original_button.src='images/original_button.gif';
			pic_history.length = current_history+1;
			file_name = req.responseJS.name;
			o_pic.src = file_name;
			current_history = current_history + 1;
			pic_history[current_history] = file_name;
			coords_zero();
//			o_pic.onload = no_dark;
			
			setHistoryText(TEXT_CROP,'SUCCESS');
			o_pic.onload = on_load_image;
		}
	}
	// Prepare request object (automatically choose GET or POST).
	req.open(null, '/index.php?rm=do_crop', true);
	// Send whole form data to backend.
	req.send( params );
	processing();
	}
}

function _brush()
{
	effect_params['pic_data'] = { 'current_history' : current_history, 'file' : pic_history[current_history], 'current_pic' : current_pic };
	//get pic by id
	var o_pic = window.document.getElementById('select_pic');
	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	// Code automatically called on load finishing.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			//cut history
			document.undo_button.src='images/undo_button.gif';
			document.original_button.src='images/original_button.gif';
			pic_history.length = current_history+1;
			file_name = req.responseJS.name;
			o_pic.src = file_name;
			current_history = current_history + 1;
			pic_history[current_history] = file_name;
			coords_zero();
			document.getElementById('pic_canvas').style.display = "none";
			o_pic.onload = no_dark;
		}
	}
	// Prepare request object (automatically choose GET or POST).
	req.open(null, '/index.php?rm=do_brush', true);
	// Send whole form data to backend.
	req.send( effect_params );
	processing();
}

function _text()
{
    if(current_pic == ''){
            alert('Please upload a picture first.');
    } else {

	effect_params['label'] = document.getElementById('label').value;
	effect_params['font'] = document.getElementById('tt_font').value;
	effect_params['size'] = document.getElementById('tt_size').value;
	effect_params['color'] = document.getElementById('tt_color').value;
	effect_params['tx'] = document.getElementById('text_x').value;
	effect_params['ty'] = document.getElementById('text_y').value;
	effect_params['pic_data'] = { 'current_history' : current_history, 'file' : pic_history[current_history], 'current_pic' : current_pic };
	
	//get pic by id
	var o_pic = window.document.getElementById('select_pic');
	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	// Code automatically called on load finishing.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			//cut history
			document.undo_button.src='images/undo_button.gif';
			document.original_button.src='images/original_button.gif';
			pic_history.length = current_history+1;
			file_name = req.responseJS.name;
			o_pic.src = file_name;
			current_history = current_history + 1;
			pic_history[current_history] = file_name;
			coords_zero();
			document.getElementById('pic_text').style.display = "none";
			o_pic.onload = no_dark;
		}
	}
	// Prepare request object (automatically choose GET or POST).
	req.open(null, '/index.php?rm=do_text', true);
	// Send whole form data to backend.
	req.send( effect_params );
	processing();
	}
}

function paloroid()
{
        if(current_pic == ''){
                alert('Please upload a picture first.');
        } else {

	if (document.pre_form.elements.paloroid[0].checked) {
		TEXT_POLAROID = 'You have applied the Polaroid (Rotate Left) effect to your picture.';
		effect_params['paloroid'] = "rotate_left";
	}
	if (document.pre_form.elements.paloroid[1].checked) {
		TEXT_POLAROID = 'You have applied the Polaroid (Stack) effect to your picture.';
		effect_params['paloroid'] = "stack";
	}
	if (document.pre_form.elements.paloroid[2].checked) {
		TEXT_POLAROID = 'You have applied the Polaroid (Rotate Right) effect to your picture.';
		effect_params['paloroid'] = "rotate_right";
	}
	effect_params['paloroid_color'] = document.getElementById('paloroid_color').value;
	effect_params['pic_data'] = { 'current_history' : current_history, 'file' : pic_history[current_history], 'current_pic' : current_pic };
	//get pic by id
	var o_pic = window.document.getElementById('select_pic');
	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	// Code automatically called on load finishing.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			//cut history
			document.undo_button.src='images/undo_button.gif';
			document.original_button.src='images/original_button.gif';
			pic_history.length = current_history+1;
			file_name = req.responseJS.name;
			o_pic.src = file_name;
			current_history = current_history + 1;
			pic_history[current_history] = file_name;
			coords_zero();
			o_pic.onload = no_dark;
			setHistoryText(TEXT_POLAROID,'SUCCESS');
		}
	}
	// Prepare request object (automatically choose GET or POST).
	ajaxHistoryText();
	req.open(null, '/index.php?rm=do_paloroid', true);
	// Send whole form data to backend.
	//req.send( { 'form': document.getElementById('pre_form'), 'pic_data' : { 'current_history' : current_history, 'file' : pic_history[current_history], 'current_pic' : current_pic } } );
	req.send( effect_params );
	processing();
	}
}

function save()
{
        if(current_pic == ''){
                alert('There is nothing to save. Please upload a picture first.');
        } else {

        ext = document.getElementById('save_as_ext').value;
	qlty = document.getElementById('save_quality').value;
	document.location="/index.php?rm=save_file&quality="+qlty+"&ext=" + ext + "&pic="+pic_history[current_history];
	}
}

function hostit()
{
        if(current_pic == ''){
                alert('There is nothing to be hosted. Please upload a picture first.');
        } else {

        ext = document.getElementById('save_as_ext').value;
        qlty = document.getElementById('save_quality').value;


        hostitPage = "/index.php?rm=hostit&quality="+qlty+"&ext=" + ext + "&pic="+pic_history[current_history];

        var hostitwin = dhtmlmodal.open('hostitbox', 'iframe', hostitPage, 'DrPic.com: Save to Web', 'width=550px,height=350px,center=1,resize=0,scrolling=1');

        document.body.onscroll=function(){
                hostitwin.moveTo('middle','middle');
        }
        }
}


function facebook()
{
 	if(current_pic == ''){
                alert('There is nothing to save to Facebook. Please upload a picture first.');
        } else {

        ext = document.getElementById('save_as_ext').value;
	qlty = document.getElementById('save_quality').value;


	facebookPage = "/index.php?rm=facebook&quality="+qlty+"&ext=" + ext + "&pic="+pic_history[current_history];

	var facebookwin = dhtmlmodal.open('facebookbox', 'iframe', facebookPage, 'Save Picture to your Facebook', 'width=700px,height=450px,center=1,resize=0,scrolling=1');

	document.body.onscroll=function(){
		facebookwin.moveTo('middle','middle');
	}
        }
}



//apply effect to pic
function doEffect(params)
{
        if(current_pic == ''){
                alert('Please upload a picture first.');
        } else {

	//get pic by id
	var o_pic = window.document.getElementById('select_pic');
	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	// Code automatically called on load finishing.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			//cut history
			document.undo_button.src='images/undo_button.gif';
			document.original_button.src='images/original_button.gif';
			pic_history.length = current_history+1;
			file_name = req.responseJS.name;
			o_pic.src = file_name;
			current_history = current_history + 1;
			pic_history[current_history] = file_name;
			o_pic.onload = no_dark;
			//alert('ok');
			//coords_zero();

        switch (effect_params['effect']) {

                case "oil_paint":
			setHistoryText(TEXT_OILPAINT,"SUCCESS");
                break;
                case "equalize":
			setHistoryText(TEXT_EQUALIZE,"SUCCESS");
                break;
                case "sharpen":
			setHistoryText(TEXT_SHARPEN,"SUCCESS");
                break;
                case "grayscale":
			setHistoryText(TEXT_GRAYSCALE,"SUCCESS");
                break;
                case "raise":
			setHistoryText(TEXT_RAISE,"SUCCESS");
                break;
                case "raised_frame":
			setHistoryText(TEXT_FRAME,"SUCCESS");
                break;

                case "spread":
			setHistoryText(TEXT_SPREAD,"SUCCESS");
                break;
                case "gaussian_blur":
			setHistoryText(TEXT_BLUR,"SUCCESS");
                break;

                case "contrast":
			setHistoryText(TEXT_CONTRAST,"SUCCESS");
                break;

                case "brightness":
			setHistoryText(TEXT_BRIGHTNESS,"SUCCESS");
                break;
                case "autofix":
			setHistoryText(TEXT_AUTOFIX,"SUCCESS");
                break;

                case "paloroid":
                break;

                case "text":
                //      document.getElementById('pic_text').style.display = 'block';
                break;
			}


		}
	}
	// Prepare request object (automatically choose GET or POST).
	req.open(null, '/index.php?rm=do_effect', true);
	// Send whole form data to backend.
	//req.send( { 'form': document.getElementById('pre_form'), 'pic_data' : { 'current_history' : current_history, 'file' : pic_history[current_history], 'current_pic' : current_pic } } );
	req.send( params );
	ajaxHistoryText();
	processing();
	}
}

//upload file
function doLoad(value,autoresize) {
	//get pic by id
	var o_pic_intro = window.document.getElementById('pic_intro');
	o_pic_intro.style.display = "none";
//	var o_pic_div = window.document.getElementById('pic_sel');
//	o_pic_div.style.display = "block";
//	var o_pic_text = window.document.getElementById('pic_text');
//	o_pic_text.style.display = "block";
	var o_pic = window.document.getElementById('select_pic');
	o_pic.src = "images/loading.gif";
	o_pic.style.display = "block";
	var o_error = window.document.getElementById('pic_error');
	var o_exif = window.document.getElementById('pic_exif');
	o_exif.innerHTML = "";

	var o_innerad = window.document.getElementById('InnerBanner');
	o_innerad.style.display = "block";

	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	var types = [];
	types['image/jpeg'] = 0;
	types['image/pjpeg'] = 0;
	types['image/bmp'] = 1;
	types['image/gif'] = 2;
	types['image/png'] = 3;
	
	// Code automatically called on load finishing.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			coords_zero();
			//new history
			if (req.responseJS.error == 'no') {
				setHistoryText("Your picture has been successfully uploaded.","SUCCESS");
				o_error.style.display = "none";
				current_pic = req.responseJS.pic_name;
				current_type = req.responseJS.pic_type;
				current_make = req.responseJS.pic_make;
				current_model = req.responseJS.pic_model;
				current_hasexif = req.responseJS.has_exif;
				document.getElementById('save_as_ext').selectedIndex = types[current_type];
				if(current_type == 'image/jpeg' || current_type == 'image/pjpeg') {
				    document.getElementById('save_as_quality').style.display = '';
				    o_exif.innerHTML = current_hasexif + ' Taken with '+ current_make + ' ' + current_model;
				} else {
				    document.getElementById('save_as_quality').style.display = 'none';
				}
				document.getElementById('picholder').style.height = o_pic.style.height;
				pic_history.length = 1;
				current_history = 0;
				pic_history[current_history] = req.responseJS.name;
				o_pic.src = req.responseJS.name;
				o_pic.style.display = "block";
				o_pic.onload = on_load_image;
				no_dark();
			} else if (req.responseJS.error == 'not_img') {
				o_pic.style.display = "none";
				no_dark();
				o_error.innerHTML = "Error: Not image type";
				o_error.style.display = "block";
			}
		}
	}
	//screen resolution
	var height=0;
	var width=0;
	if (self.screen)
	{
		width = screen.width
		height = screen.height
	}
	// Prepare request object (automatically choose GET or POST).
	req.open(null, '/index.php?rm=upload_pic', true);
	// Send data to backend.
	req.send( { 'file': value, 'autoresize' : autoresize, 'screenWidth' : screen.width } );
	o_error.style.display = "none";
	processing();
}


    function hvrFloatInInit(){

        if(document.cookie.indexOf("hvrNoShow") != -1)
            return;

        if(document.getElementById){

            hvrFloatingBox = document.getElementById('hvrFloatingBoxDiv');

            if(!hvrFloatingBox)
                return;

            if(!hvrFloatingBox.style.position)
                return;

            if(hvrFloatingBox.style.position != "absolute")
                return;

            if(hvrFloatingBox.style.display)
                hvrFloatingBox.style.display = "block";

            hvrBoxLeft = -470;
            hvrAcceleration = 50;
            hvrChangeRate = 1.5;

            hvrChangeRate -= ( (document.body.clientWidth-1200) * 0.00104 );

            setTimeout("hvrFloat()", 50);
        }
    }
    
    function hvrFloat(){
        hvrFloatingBox.style.left = 10 + (hvrBoxLeft += (hvrAcceleration -= hvrChangeRate));
        
        if(hvrAcceleration > 0)
            setTimeout("hvrFloat()", 50);
    }

    function hvrCloseWindow(){
        hvrFloatingBox.style.display = "none";
    }
    
    function hvrCloseAndDontShowAgain(){
        document.cookie = "hvrNoShow";
        hvrFloatingBox.style.display = "none";
    }

function brightnessColor(){

	var brightnessInput = document.getElementById('brightness');
	var brightnessImage = document.getElementById('brightnessImage');
	if(brightnessInput.value == 0){
		brightnessInput.style.color = '#000000';
		brightnessImage.innerHTML = '';
	}
	else if(brightnessInput.value < 0){
		brightnessInput.style.color = 'red';
		brightnessImage.innerHTML = '<img src="images/brightness_darkermsg.gif">';
	}
	else{
		brightnessInput.style.color = 'green';
		brightnessImage.innerHTML = '<img src="images/brightness_brightermsg.gif">';
	}

}

function sampleFrameColor(){

	var frameColorInput = document.getElementById('im_color');
	document.getElementById('colorbox').style.background = frameColorInput.value;
}

function sampleFrameHeight(){

	var frameHeightInput = document.getElementById('raised');
	document.getElementById('colorbox').style.paddingTop = frameHeightInput.value + 'px';
}

function uploadSplashOn(toggle){
if(toggle == 'on'){
	var uploadSplashInput = document.getElementById('uploadsplash');
	uploadSplashInput.style.border = '1px solid #149ecb';
	uploadSplashInput.style.backgroundColor = '#d2ecfb';
}
else{
        var uploadSplashInput = document.getElementById('uploadsplash');
        uploadSplashInput.style.border = '1px solid #80c65a';
        uploadSplashInput.style.backgroundColor = '#ddf8cc';


}
}

function uploadAutoResize(){
	var uploadAutoResize = document.getElementById('autoresize');
	if(uploadAutoResize.checked){
		document.uploadForm.action = "/index.php?rm=upload_pic&autoresize=no";
	}
	else{
		document.uploadForm.action = "/index.php?rm=upload_pic&autoresize=no";
	}

}

function uploadinternet(){
	document.getElementById('uploadcomputer').style.display = 'none';
	document.getElementById('uploadinternet').style.display = 'block';
}

function uploadcomputer(){
        document.getElementById('uploadinternet').style.display = 'none';
        document.getElementById('uploadcomputer').style.display = 'block';
}

function uploadFetch(picurl){
	window.location = 'http://drpic.com/?fetch=' + picurl.value;
}


