var magic_id = null;
var magic_server = null;
var magic_sizes = 0;
var delete_cookie = null;

var dumprjs = {
	// Effect instance of status window animation
	status_window_effect: null,
	status_window_visible: false,
	selected_tab: '',
	endpoint_url: "/dumpr.queuejob.php",

	getSelectedTab: function() {
		return this.selected_tab;
	},

	getWeb10Url: function() {
		return $('web10Url').value;
	},

	onTabSelected: function(newTab) {
		if (newTab == this.getSelectedTab()) {
			// nothing happens
			return;
		}
		
		if (this.getSelectedTab() != '') {
			$('tab' + this.selected_tab).className = "";
			$('div' + this.selected_tab).style.visibility = "hidden";
			$('div' + this.selected_tab).style.display = "none";
		}
	
		$('tab' + newTab).className = "current";
		$('div' + newTab).style.visibility = "visible";
		$('div' + newTab).style.display = "block";
		this.selected_tab = newTab;
	},

	getSelectedThumb: function() {
		return this.selectedThumb;
	},

	showTrickError: function(str) {
		$('error_message_div').style.display = 'block';
		$('error_message_div').innerHTML = str;
	},

	showTrickErrorCode: function(code) {
		this.showTrickError(err2string(code));
	},

	onEffectContinue: function() {
		var tab = this.getSelectedTab();
		var args = null;
		var extra = null;

		if (global_dumpr_has_extra) {
			if (selectedMaster == null) {
				this.showTrickError("Please select effect variant from Step 2");
				return;
			}

			extra = selectedMaster;
		}

		if (tab == "Flickr") {
			if (!global_dumpr_logged_in) {
				// paranoia
				this.showTrickError("Please authorize access your flickr photo stream");
				return;
			}
	
			var thumb = carousel.selectedPhotoId;
			if (thumb == false) {
				this.showTrickError("Please select a photo from your stream");
				return;
			}
		
			var url = "flickr://" + thumb;
			this.prepareTrickFetch(url, extra);
		} else if (tab == "Url") {
			url = this.getWeb10Url();
			if (this.validateUrl(url) == false) {
				this.showTrickError("Please enter a valid url");
				return;
			}

			this.prepareTrickFetch(url, extra);
		} else if (tab == "Upload") {
			// do post
			if ($('pickr_userfile').value == "") {
				this.showTrickError("Please use 'Browse' button to select a photo");
				return;
			}
       	
			var filename = $('pickr_userfile');
			this.prepareTrickUpload(extra);
		}
	},

	// I seriously don't like IE (part 1)
	global_extra: "",
	global_started: false,

	prepareTrickFetch: function(url, extra) {
		var that = this;
		dumprjs.setStatus("Fetching image...");

		new Ajax.Request("/dumpr.fetch.php", {
			parameters: "url=" + encodeURIComponent(url),
			method: 'get',
			onComplete: function(xh) {
				var json = xh.responseText.evalJSON();
				if (json.status == "ok") {
					dumprjs.prepareTrick(json.id, extra);
				} else {
					dumprjs.hideStatusWindow();			
					that.showTrickErrorCode(json.code);
				}
			}
		});
	},

	prepareTrick: function(id, extra) {
		var that = this;
		dumprjs.setStatus("Working...");
		
		var is_public = false;
		if ($("is_public"))
		{
			is_public = !!$("is_public").checked;
		}
	
		new Ajax.Request(this.endpoint_url, {
			parameters: "effect=" + trick_name + "&id=" + id + "&extra=" + extra + "&public=" + is_public,
			method: 'get',
			onComplete: function(xh) {
				// I seriously don't like IE (part 1.5)
				this.global_started = false;
       	
				var json = xh.responseText.evalJSON();
				if (json.status == "ok") {
					dumprjs.setStatus("Done! Here We Go..");

					if (typeof(json.url) != "undefined")
					{
						// next-url defined by effect
						document.location.href = json.url;
					}
					else
					{
						// by default go to the result image
						document.location.href = "/photo/" + json.magic + "/";
					}
				}
				else {
					dumprjs.hideStatusWindow();
					that.showTrickErrorCode(json.code);
				}
			}
		});
	},

	onIFrameLoad: function() {
		if (this.global_started) {
			return;
		}
	
		var i = document.getElementById('pickr_uploadFrame');
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
       	
		if (d.location.href == "about:blank") {
			return;
		}
       	
		var t = d.body.innerHTML;
		var json = t.evalJSON();
		if (json.status == "ok") {
			this.global_started = true;
			this.prepareTrick(json.id, global_extra);
		} else {
			dumprjs.hideStatusWindow();
			this.showTrickErrorCode(json.code);
		}
	},

	prepareTrickUpload2: function() {
		// I seriously don't like IE (part 2)
		$('pickr_uploadForm').submit();
	},     	
	
	prepareTrickUpload: function(extra) {	
		dumprjs.setStatus("Uploading image...");
       	
		// I seriously don't like IE (part 3)
		global_extra = extra;
       	
		$('pickr_uploadFrame').onload = this.onIFrameLoad.bind(this);
	
		var f = $('pickr_uploadFrame');
		if (window.addEventListener) {
			f.onload = this.onIFrameLoad.bind(this);
		} else if (f.attachEvent) {
			f.attachEvent("onload", this.onIFrameLoad.bind(this));
		}
       	
		// I seriously don't like IE (part 4)
		setTimeout(this.prepareTrickUpload2.bind(), 1);
	},

	disableFlickrUploadCheckboxes: function() {
		$("uploadr_bfriends").disabled = true;     
		$("uploadr_bfamily").disabled = true;
	},

	enableFlickrUploadCheckboxes: function() {
		$("uploadr_bfriends").disabled = false;	
		$("uploadr_bfamily").disabled = false;
	},

	resetUploadrWindow: function() {
		$('uploadr_title').value = '';
		$('uploadr_desc').value = '';
		$('uploadr_bpublic').checked = true;
		$('uploadr_bfriends').checked = false;
		$('uploadr_bfamily').checked = false;
		this.disableFlickrUploadCheckboxes();
	},

	resetSendEmailInterface: function(completely) {
		if (completely) {
			$('sendEmailYourName').value = '';
			$('sendEmailYourEmail').value = '';
		}

		$('recipient_list').value = '';
	},
		
	onUploadToFlickrContinue: function() {
		// prepare post variables
		var post = '';
		post += "title=" + escape($('uploadr_title').value);
		post += "&desc=" + escape($('uploadr_desc').value);
		if ($('uploadr_bpublic').checked) {
			post += "&bpublic=true";
		} else {
			post += "&bpublic=false&bfriends=" + $('uploadr_bfriends').checked + "&bfamily=" + $('uploadr_bfamily').checked;
		}

		post += "&fn=" + $('uploadr_fn').value;
		post += "&tool=" + global_dumpr_tool;
		post += '&magic=' + magic_id;

		Modalbox.show($('UploadProgressWindowContent').cloneNode(true), {title: 'Upload to Flickr', width: 600});

		var v = {
			parameters: post,
			method: 'post',
			onComplete: function(xh) {
				var json = xh.responseText.evalJSON();
				if (json.status == "ok") {
					$('UploadComplete_link').href = "http://www.flickr.com/photo.gne?id=" + json.photoid;
					Modalbox.show($('UploadCompleteWindowContent'), {title: 'Upload to Flickr', width: 600, overlayClose: false});
	
				}
				else {
					Modalbox.show($('UploadFailedWindowContent'), {title: 'Upload to Flickr', width: 600, overlayClose: false});
				}
			}
		};

		new Ajax.Request("/dumpr.upload.flickr.php", v);
	},

	onSendEmailContinue: function() {
		var name = $('sendEmailYourName').value;
		name = name.replace(/^\s+|\s+$/g,"");
		if (name == '') {
			alert("Please enter your name");
			$('sendEmailYourName').focus();
			return false;
		}

		var friend_name = $('sendEmailFriendName').value;
		friend_name = friend_name.replace(/^\s+|\s+$/g,"");
		if (friend_name == '') {
			alert("Please enter your friend's name");
			$('sendEmailFriendName').focus();
			return false;
		}

		var email = $('sendEmailFriendEmail').value;
		email = email.replace(/^\s+|\s+$/g,"");
		if (email == '' || /^.+@.+\.\w+$/.test(email) == false) {
			alert("Please enter a valid email address");
			$('sendEmailFriendEmail').focus();
			return false;
		}

		var args = "from_name=" + encodeURIComponent(name) + "&to_email=" + encodeURIComponent(email) + "&to_name=" + encodeURIComponent(friend_name) + '&magic=' + magic_id;

		var v = {
			parameters: args,
			method: 'get',
			onComplete: function(xh) {
				var json = xh.responseText.evalJSON();
				if (json.status == "ok") {
					Modalbox.show($('EmailWindowContent_Done'), {title: 'Email this photo', width: 600, overlayClose: false});
				}
			}
		};

		Modalbox.show($('EmailWindowContent_Progress').cloneNode(true), {title: 'Email this photo', width: 600, overlayClose: false});
		new Ajax.Request("/services/new/?method=dumpr.email.sendPhoto&" + args, v);
		return true;
	},

	uploadToFlickr: function() {
		this.resetUploadrWindow();
		Modalbox.show($('UploadWindowContent').cloneNode(true), {title: 'Upload to Flickr', width: 600, overlayClose: false});
	},
	
	emailPicture: function() {
		Modalbox.show($('EmailWindowContent_Interface').cloneNode(true), {title: 'Email this photo', width: 600, overlayClose: false});
	},

	onPhotoDelete: function() {
		if (confirm("Are you sure you want to delete this photo?\n(this operation cannot be undone)")) {
			document.location.href = "/photo/" + magic_id + "/?delete=" + delete_cookie;
		}

		return false;
	},

	_processing_hires: false,

	prepareTrickHiRes: function(magic) {

		var that = this;
		if (this._processing_hires) {
			return;
		}
	
		this._processing_hires = true;

		var v = {
			parameters: "magic=" + magic,
			method: 'get',
			onComplete: function(xh) {

				// restore old icon
				$('create_hires_image').src = "/images/zoom_in.gif";
				that._processing_hires = false;

				var json = xh.responseText.evalJSON();
				if (json.status == "ok") {
					document.location = '/photo/' + json.magic + '/savehq/';
				}
				else {
					//showTrickErrorCode(json.code);
				}
			}
		};

		// replace create-hires-image with ajaxload
		$('create_hires_image').src = "/images/loader.gif";
		new Ajax.Request("/dumpr.queuehires.php", v);
	},

	createHiRes: function() {
		if (pro_member)	{
			this.prepareTrickHiRes(magic_id);
		} else {
			//Modalbox.show($('GenerateHiResWindow_Content'), {title: 'Pro members only', width: 700, overlayClose: false});
			document.location = "/go-pro-4x.php?ref=" + magic_id;
		}
	},
	
	setStatus: function(t) {
		$('ImageProcessingContent_text').innerHTML = t;
		if (this.status_window_visible == false)
		{
			this.showStatusWindow();
		}
	},

	enableOverlay: function() {
		var overlay = new Element("div", {id: "overlay"});
		overlay.setStyle({opacity: 0});
		$(document.body).insert({'top' : overlay});
		new Effect.Fade(overlay, {from: 0, to: .65, duration: .25});
	},

	hideOverlay: function() {
		if ($('overlay')) {
			$('overlay').remove();
		}
	},

	showStatusWindow: function() {
		this.status_window_visible = true;
		Modalbox.show($('status_window').cloneNode(true), {title: '', width: 600, transitions: false, overlayClose: false});
	},

	hideStatusWindow: function() {
		Modalbox.hide();
		this.status_window_visible = false;
	},

	toggleBlinds: function(id) {
		if ($(id).style.display == "none") {
			new Effect.BlindDown(id);
		} else {
			new Effect.BlindUp(id);
		}
	},

	getPageSize: function() {
		var xScroll, yScroll;
	
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { 
			// Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
	
		var windowWidth, windowHeight;
		if (self.innerHeight) {	
			// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
	
		// for small pages with total height less then height of the viewport
		if (yScroll < windowHeight) {
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}

		// for small pages with total width less then width of the viewport
		if (xScroll < windowWidth) {	
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}

		return new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	},

	validateUrl: function(url) {
		var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
		return regexp.test(url);
	},

	onChangePerms: function(magic, perms) {

		var that = this;

		var v = {
			parameters: "method=dumpr.change_perms&perms=" + perms + "&magic=" + magic + "&render=1",
			method: 'get',
			onComplete: function(xh) {
				var json = xh.responseText.evalJSON();
				if (json.status == "ok") {
					if (typeof(json.html) != "undefined")
					{
						$("photo_div_" + magic).innerHTML = json.html;
					}
				}
				else {
				}
			}
		};

		// replace create-hires-image with ajaxload
		//$('').src = "/images/loader.gif";
		new Ajax.Request("/services/", v);
	},

	trackEvent: function(cid, extra) {
		var img = new Image();
		img.src = "/services/?method=awesome.track&img=1&cid=" + encodeURIComponent(cid) + "&extra=" + encodeURIComponent(extra);
	}
}

function err2string(code) {
	switch(code) {
		case 0:
		return "No error";

		case 1:
		return "Bad parameters";

		case 2:
		return "Unsupported URL address";

		case 3:
		case 10:
		return "Image data seems corrupted";

		case 4:
		return "No images found at given address";

		case 5:
		return "Unsupported image format";

		case 6:
		return "No file uploaded";

		case 7:
		return "File is too large";

		case 11:
		return "Image is too small";

		case 12:
		return "Image is too big";

		case 13:
		return "Image processing failed";

		case 15:
		return "Service is a bit busy. Sorry. Please try in a moment..";

		default:
		return "Server error (" + code + ")";
	}
}

function build_photo_url(server, id, size) {
	return "/static/" + server + "/" + id + "_" + size + ".jpg";
}

/* uploadr code */

/* printr code */
function printPicture() {
	var img = build_photo_url(magic_server, magic_id, "o");
	window.open('/print.php?img=' + img, 'Print', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=600,height=400');
}

function savePicture() {
	document.location = '/photo/' + magic_id + '/save/';
}

function createEmailWindow() {
	var win = new Window(
		"EmailWindow_Interface", 
		{
			className: "mac_os_x", 
			width:650, 
			height:220, 
			zIndex:2000, 
			resizable:false, 
			draggable:false,
			closable:true,
			maximizable: false,
			minimizable: false,
			title: 'Email this photo to a friend',
			showEffectOptions: {duration: 0}, 
			hideEffectOptions: {duration: 0}
		});
	
	//$('EmbedWindowContent_EmbedPanel').style.display = 'block';
	//setEmbedWindow_SelectPanel(0);
	
	resetUploadrWindow();
	win.setContent('EmailWindowContent_Interface');
	win.setDestroyOnClose();
	
	var ob = {
		onDestroy: function(eventName, handle) {
			if (handle == win) {
				$('EmailWindowContent_Interface').style.display = 'none';
				$('content').appendChild($('EmailWindowContent_Interface'));
				Windows.removeObserver(this);
				closeModal();
			}
		}
	};

	Windows.addObserver(ob);
	return win;
}

var masterSelectionEnabled = true;
var selectedMaster = null;

function setMasterColor(id, color)
{
	e = $(id);
	if (e != null)
	{
		e.style.border = "2px solid " + color;
	}
}

function hilightMaster(e)
{
	var id = e.getAttribute("id");
	if (selectedMaster != id)
	{
		setMasterColor(id, 'lightgrey');
	}
}

function lolightMaster(e)
{
	var id = e.getAttribute("id");
	if (selectedMaster != id)
	{
		setMasterColor(id, 'white');
	}
	else
	{
		setMasterColor(id, 'green');
	}
}

function selectMaster(e)
{
	var id = e.getAttribute("id");

	if (masterSelectionEnabled == false)
	{
		return;
	}

	if (selectedMaster != id)
	{
		setMasterColor(selectedMaster, 'white');
		setMasterColor(id, 'green');
		selectedMaster = id;
	}
	else
	{
		setMasterColor(selectedMaster, 'white');
		selectedMaster = null;
		setMasterColor(id, "lightgrey");
	}
}

function createImageProcessingWindow() {
	var win = new Window(
		"ImageProcessingWindow", 
		{
			className: "mac_os_x", 
			width:450, 
			height:50, 
			zIndex:2000, 
			resizable:false, 
			draggable:false,
			closable:false,
			maximizable: false,
			minimizable: false,
			title: 'We are processing your image',
			showEffectOptions: {duration: 0}, 
			hideEffectOptions: {duration: 0}
		});

	win.setContent('ImageProcessingContent');
	win.setDestroyOnClose();
	
	var ob = {
		onDestroy: function(eventName, handle) {
			if (handle == win) {
				$('ImageProcessingContent').style.display = 'none';
				$('content').appendChild($('ImageProcessingContent'));
				Windows.removeObserver(this);
				closeModal();
			}
		}
	};

	Windows.addObserver(ob);
	return win;
}

function sendToMobile() {
	var localImage = "http://www.dumpr.net" + build_photo_url(magic_server, magic_id, 'o');
	var url = '/send-to-mobile.php?image=' + localImage;
	window.open(url,'_MPUSH_','width=640,height=420,titlebar=1,resizable=1,scrollbars=1');
}

var NeatEditor = Class.create();
NeatEditor.prototype = {
	initialize: function(handle, options) {
		this.handle = $(handle);
		this.options = Object.extend(options, {
			emptyDisplay: "<i>Click here to add a title<\/i>"
		});

		this.in_edit = 0;
		this.value = this.handle.innerHTML;
		if (this.options.value) {
			this.value = this.options.value;
		}

		this.handle.onmouseover = this.onMouseOver.bindAsEventListener(this);
		this.handle.onmouseout = this.onMouseOut.bindAsEventListener(this);
		this.handle.onclick = this.onClick.bindAsEventListener(this);
		this.onMouseOut();
	},

	onMouseOver: function() {
		if (this.in_edit == 0) {
			this.handle.style.color = "#000";
			this.handle.style.background = "#ffffd3";
		}
	},

	onMouseOut: function() {
		if (this.in_edit == 0) {
			this.handle.style.color = "#000";
			this.handle.style.background = "#fff";

			if (this.value == "") {
				this.handle.innerHTML = this.options.emptyDisplay;
				this.handle.style.color = "gray";
			} else {
				if (this.options.allowHTML) {
					this.handle.innerHTML = this.value;
				} else {
					this.handle.innerHTML = this.value.escapeHTML();
				}
			}
		}
	},

	getValue: function() {
		return this.value;
	},

	escape: function(t) {
		var len = t.length;
		var ofs = 0;
		var out = '';

		while (ofs < len) {
			var c = t[ofs++];
			if (c != '<') {
				out += c;
			} else {
				// trouble?
				var i = t.indexOf('>', ofs);
				var tag = '';
				if (i >= 0) {
					tag = t.substr(ofs, i - ofs).strip();
				}

				var ok = false;
				if (tag == "b" || tag == "/b" || tag == "i" || tag == "/i" || tag == "strong" || tag == "/strong" || tag == "u" || tag == "/u" || tag == "em" || tag == "/em") {
					ok = true;
				}

				if (ok) {
					out += '<' + tag + '>';
				}

				ofs = i+1;				
			}
		}

		return out;
	},

	onSubmit: function(event) {
		// placeholder
	},

	onOK: function(e) {
		var t = $("input_" + this.in_edit).value.strip();

		if (this.options.allowHTML) {
			this.value = this.escape(t);
		} else {
			this.value = t;
		}

		this.in_edit = 0;
		this.onMouseOut();
		this.onSubmit();
		Event.stop(e);
		return false;
	},

	onCancel: function(e) {
		this.in_edit = 0;
		this.onMouseOut();
		Event.stop(e);
		return false;
	},

	onKeyDown: function(event) {
		if (event.keyCode == 27) {
			this.onCancel();
			return false;
		}

		return true;
	},

	onClick: function() {
		if (this.in_edit == false) {
			this.in_edit = new Date().getTime();

			var form = document.createElement("form");
			form.id = "form_" + this.in_edit;
			form.onsubmit = this.onOK.bindAsEventListener(this);
			
			var input = document.createElement("input");
			input.id = "input_" + this.in_edit;
			input.className = "NeatEditor";
			input.value = this.value;
			input.onkeydown = this.onKeyDown.bindAsEventListener(this);

			var ok = document.createElement("input");
			ok.type = "submit";
			ok.value = "OK";
			ok.className = "pbutton";
			ok.onclick = this.onOK.bindAsEventListener(this);

			var or = document.createElement("span");
			or.style.marginLeft = "5px";
			or.style.fontSize = "10px";
			or.innerHTML = "or ";
			var cancel = document.createElement("a");
			cancel.innerHTML = "Cancel";
			cancel.href = "#";
			cancel.onclick = this.onCancel.bindAsEventListener(this);
			or.appendChild(cancel);

			form.appendChild(input);
			form.appendChild(ok);
			form.appendChild(or);

			this.handle.style.background = "#fff";
			this.handle.innerHTML = "";
			this.handle.appendChild(form);

			input.focus();
		}
	}
};

var NeatTitleEditor = Class.create();
Object.extend(NeatTitleEditor.prototype, NeatEditor.prototype);
Object.extend(NeatTitleEditor.prototype, {
	onSubmit: function(event) {
		var title = this.getValue();
		var magic = this.options.magic;
		var that = this;

		var options = {
			asynchronous: true,
			onComplete: function(e) {
				that.onMouseOut();
			}
		};

		this.handle.innerHTML = "<i>Saving..</i>";
		this.handle.style.color = "gray";

		var url = "/services/new/?method=dumpr.photos.setTitle&magic=" + magic + "&title=" + encodeURIComponent(title);
		new Ajax.Request(url, options);
		return false;
	}
});

function confirmDeletePhoto(magic, container_id) {
	if (confirm("Are you sure you want to delete this photo?\n(this operation cannot be undone)")) {
		var url = "/services/new/?method=dumpr.photos.delete&magic=" + magic;
		var options = {
			asynchronous: true,
			onComplete: function(e) {

				if (typeof(container_id) == 'string')
				{
					new Effect.Fade(container_id);
				}
				else
				{
					container_id.each((function(f) { new Effect.Fade(f); }).bind());
				}
			}
		};

		new Ajax.Request(url, options);
	}
}

function buttonStateHandler(button, enabled) {
	alert("LEGACY CODE, PLEASE REMOVE");
}

function animHandler(carouselID, status, direction) {
	alert("LEGACY CODE, PLEASE REMOVE");
}

