var selectedPhotoImg = null;

function getActiveTab()
{
	var parent = $("image_selector_options");
	var children = parent.getElementsByTagName("div");
	for (var i=0; i<children.length; i++)
	{
		if (children[i].style.display == "block")
		{
			return children[i].id;
		}
	}

	return false;
}

function onEffectContinue()
{
	var args = null;

	if (global_dumpr_has_extra) 
	{
		if (selectedMaster == null) 
		{
			this.showTrickError("Please select effect variant from Step 2");
			return;
		}

		effect_extra = selectedMaster;
	}

	switch(getActiveTab())
	{
		case "tab_upload":
		// file upload
		if ($('pickr_userfile').value == "") 
		{
			dumprjs.showTrickError("Please use 'Browse' button to select a photo");
			return;
		}
		
		var filename = $('pickr_userfile');
		dumprjs.prepareTrickUpload(effect_extra);
		break;

		case "tab_flickr":
		case "tab_picasa":
		case "tab_facebook":
		if (selectedPhotoImg == null) 
		{
			dumprjs.showTrickError("Please select a photo from your stream");
			return;
		}

		if ($("is_public"))
		{
			$("is_public").checked = false;
		}
		
		dumprjs.prepareTrickFetch(selectedPhotoImg, effect_extra);
		break;

		case "tab_url":
		var url = $("pickr_url").value;
		if (dumprjs.validateUrl(url) == false)
		{
			dumprjs.showTrickError("Please enter a valid url");
			return;
		}
	
		if ($("is_public"))
		{       		
			$("is_public").checked = false;
		}
		
		dumprjs.prepareTrickFetch(url, effect_extra);
		break;
	}
}

var DumprTabManager = Class.create(
{
	initialize: function()
	{
	},

	onTabNameClick: function(evt, name)
	{
		
	}
});

function selectTab(name)
{
	var names = ["upload", "facebook", "picasa", "flickr", "url"]; //, "recent"];
	for (var i=0; i<names.length; i++)
	{
		if (names[i] == name)
		{
			var top = -5 + (34 * i);
			$("post_element").style.top = top;
			break;
		}
	}

	names.each(function(suffix) {
		$("tab_" + suffix).style.display = "none";
	});
	
	$("tab_" + name).style.display = "block";

	document.cookie = "imagepicker_lasttab=" + name;
	return false;
}

function trim(str)
{
	return str.replace(/^\s*|\s*$/g,"");
}

function getCookieByName(name)
{
	var cookies = document.cookie.split(";");
	for (var i=0; i<cookies.length; i++)
	{
		var keyvalue = cookies[i].split("=");
		if (trim(keyvalue[0]) == name)
		{
			return trim(keyvalue[1]);
		}
	}

	return null;
}

function setToLastTab()
{
	var lastTab = getCookieByName("imagepicker_lasttab");
	if (lastTab)
	{
		selectTab(lastTab);
	}	
}

function form_on_click()
{
	if ($("pickr_url").value == "http://")
	{
		$("pickr_url").value = "";
		$("pickr_url").style.color = "#000";
	}
}

var DumprPhotoImport = Class.create(
{
	token: null,
	service: null,
	       
	initialize: function(service)
	{
		this.service = service;
	},

	call: function(method, args, onsuccess)
	{
		args = args || {};

		var url = "/services/new/?method=" + method;
		for (var key in args)
		{
			url += "&" + key + "=" + args[key];
		}

		new Ajax.Request(url,
		{
			onComplete: function(xh)
			{
				var json = xh.responseText.evalJSON();
				return onsuccess(json);
			}
		});
	},

	getService: function()
	{
		return this.service;
	},

	getPhotos: function(setId, onsuccess)
	{
		this.call("dumpr.import.getPhotos", {token: this.token, setId: setId}, onsuccess);
	},

	getSets: function(onsuccess)
	{
		this.call("dumpr.import.getSets", {token: this.token}, onsuccess);
	},

	getLatestPhotos: function(onsuccess)
	{
		this.call("dumpr.import.getLatestPhotos", {token: this.token}, onsuccess);
	},

	authorize: function(onsuccess)
	{
		this.call("dumpr.import.authorize", {service: this.service}, onsuccess);
	},

	disconnect: function(onsuccess)
	{
		this.call("dumpr.import.disconnect", {token: this.token}, onsuccess);
		this.token = null;
	}
});

var DumprPhotoContainer = Class.create(
{
	container: null,
	options: null,
	selected_photo: null,

	initialize: function(container, options)
	{
		this.options = options || {};
		this.container = container;
	},

	onmouseover: function(evt, div)
	{
		var color = (div == this.selected_photo ? "green" : "#c0c0c0");
		div.setStyle({borderColor: color});
	},

	onmouseout: function(evt, div)
	{
		var color = (div == this.selected_photo ? "green" : "white");
		div.setStyle({borderColor: color});
	},

	onclick: function(evt, div, url)
	{
		if (this.selected_photo)
		{
			this.selected_photo.setStyle({borderColor: "white"});
		}
		
		this.selected_photo = div;
		selectedPhotoImg = url;
		div.setStyle({borderColor: "green"});
	},

	ondoubleclick: function(evt, div, url)
	{
		selectedPhotoImg = url;
		onEffectContinue();
	},

	add: function(photos)
	{
		this.container.innerHTML = "";
	        
		for (var i=0; i<photos.length; i++)
		{
			var img = new Image();
			img.onload = function()
			{
				var w = this.width;
				var h = this.height;
				var dx = 0, dy = 0;

				if (w >= h)
				{
					// stretch by h, crop by w
					w = Math.floor(w / (h / 75)) ///
					h = 75;
					dx = Math.floor(-((w - 75) / 2)); ///
				}
				else
				{
					h = Math.floor(h / (w / 75)); ///
					w = 75;
					dy = Math.floor(-((h - 75) / 2)); ///
				}

				$(this).setStyle({width: w + "px", height: h + "px", position: "relative", left: dx + "px", top: dy + "px", display: "block"});
			};

			img.style.display = "none";
			img.src = photos[i].thumb;
			img.title = photos[i].title;
			img.alt = photos[i].title;

			var inner = document.createElement("div");
			inner.setStyle({border: "2px solid white", cursor: "pointer", width: "75px", height: "75px", overflow: "hidden"});
			inner.observe("mouseover", this.onmouseover.bindAsEventListener(this, inner));
			inner.observe("mouseout", this.onmouseout.bindAsEventListener(this, inner));
			inner.observe("click", this.onclick.bindAsEventListener(this, inner, photos[i].img));
			inner.observe("dblclick", this.ondoubleclick.bindAsEventListener(this, inner, photos[i].img));
			inner.appendChild(img);
					
			var outer = document.createElement("div");
			outer.setStyle({float: "left", paddingRight: "4px", paddingBottom: "4px", width: "75px", height: "75px"});
			outer.appendChild(inner);					

			this.container.appendChild(outer);
		}
	}
});

var DumprWebAlbumConnector = Class.create(
{
	element: null,
	service: null,
	import_service: null,

	checkAuthWindowTimer: null,
	photo_container: null,

	initialize: function(id_of_element, service)
	{
		this.element = $(id_of_element);
		this.service = service;

		// update shared dom elements
		this.element.select(".connect_button").first().observe("click", this.onConnect.bindAsEventListener(this));
		this.element.appendChild($('shared_content').select(".shared").first().cloneNode(true));
		this.element.select(".shared").first().show();
		this.element.select(".change_set_button").first().observe("click", this.onChangeSet.bindAsEventListener(this));
		this.element.select(".user_disconnect").first().observe("click", this.onDisconnect.bindAsEventListener(this));

		this.import_service = new DumprPhotoImport(service);
	},

	onDisconnect: function()
	{
		this.showConnectButton();
		this.hidePhotoContainer();
		this.hideUserPane();
		this.import_service.disconnect();
	},

	hidePhotoContainer: function()
	{
		this.element.select(".photos_container").first().hide();
	},

	showPhotoContainer: function()
	{
		this.element.select(".photos_container").first().show();
	},

	hideChangeSet: function()
	{
		this.element.select(".change_set_button").first().hide();
	},

	showChangeSet: function()
	{
		this.element.select(".change_set_button").first().show();
	},

	hideLoader: function()
	{
		this.element.select(".loader").first().hide();
		this.showPhotoContainer();
	},

	showLoader: function()
	{
		this.element.select(".loader").first().show();
		this.hidePhotoContainer();
	},

	showConnectLoader: function()
	{
		this.element.select(".connect_loader").first().show();
	},

	hideConnectLoader: function()
	{
		this.element.select(".connect_loader").first().hide();
	},

	hideConnectButton: function()
	{
		this.element.select(".connect_info").first().hide();
	},

	showConnectButton: function()
	{
		this.element.select(".connect_info").first().show();
	},

	onConnect: function(evt)
	{
		var that = this;

		this.showConnectLoader();

		if (this.authUrl)
		{
			// already authorized before
			this.openAuthWindow();
		}
		else
		{
			this.import_service.authorize(this.onAuthorizeReply.bind(this));
		}
	},

	onAuthorizeReply: function(json)
	{
		if (typeof(json.redirect) != "undefined")
		{
			this.authUrl = json.redirect;
			this.openAuthWindow();
		}
		else
		{
			this.hideConnectButton();
			this.hideConnectLoader();
			this.import_service.token = json.token;
			this.updateUserPane(json);
			this.showUserPane();
			this.showLatestPhotos();
		}
	},

	openAuthWindow: function()
	{
		if (this.authUrl)
		{
			var params = "toolbar=0,menubar=0,resizable=1,location=0,status=0,scrollbars=0,width=760,height=760";
			var win = window.open(this.authUrl, "authorizewindow_" + this.service, params);

			if (this.checkAuthWindowTimer)
			{
				clearInterval(this.checkAuthWindowTimer);
			}

			this.checkAuthWindowTimer = setInterval(this.checkAuthWindow.bindAsEventListener(this, win), 100);
		}
	},

	checkAuthWindow: function(evt, win)
	{
		if (win && win.closed)
		{
			clearInterval(this.checkAuthWindowTimer);
			this.import_service.authorize(this.onAuthorizeReply.bind(this));
		}
	},

	createPhotoContainer: function()
	{
		if (this.photo_container == null)
		{
			var div = this.element.select(".photos_container").first();

			this.photo_container = new DumprPhotoContainer(div);
			div.show(); 
		}

		return this.photo_container;
	},

	updateWithLatestPhotos: function(json)
	{
		this.hideLoader();
		this.hideConnectButton();
		this.showChangeSet();

		var ref = this.createPhotoContainer();
		ref.add(json.photos);
	},

	showLatestPhotos: function()
	{                         
		this.showLoader();  				
		this.import_service.getLatestPhotos(this.updateWithLatestPhotos.bind(this));
	},

	showUserPane: function()
	{
		new Effect.Appear(this.element.select(".user_info").first());
	},

	hideUserPane: function()
	{
		this.element.select(".user_info").first().hide();
	},

	updateUserPane: function(json)
	{
		if (json.avatar)
		{
			this.element.select(".user_info_avatar").first().src = json.avatar;
		}
		                    
		if (json.name)
		{
			this.element.select(".user_info_name").first().innerHTML = json.name;
		}
	},

	onAuthWindowClosed: function()
	{
		this.import_service.authorize(function(json)
		{
			if (json.token)
			{
				this.import_service.token = json.token;
				this.updateUserPane(json);
				this.showUserPane();
				this.showLatestPhotos();
			}
			else if (json.redirect)
			{
				// FIXME
			}
		});
	},

	updateWithSetPhotos: function(json)
	{
		this.hideLoader();
		this.showChangeSet();
		this.element.select(".photos_container").first().innerHTML = "";

		this.hideConnectButton();
		var ref = this.createPhotoContainer();
		ref.add(json.photos);
	},

	showSetPhotos: function(setId)
	{
		this.showLoader();
		this.import_service.getPhotos(setId, this.updateWithSetPhotos.bind(this));
	},

	onGetSetsReply: function(json)
	{
		this.hideChangeSet();
		this.hideLoader();
		this.cached_sets = json;

		this.element.select(".photos_container").first().innerHTML = "";

		for (var i=0; i<json.sets.length; i++)
		{
			var set = json.sets[i];

			var img = $(new Image());

			img.onload = function()
			{
				var w = this.width;
				var h = this.height;
				var dx = 0, dy = 0;

				if (w >= h)
				{
					// stretch by h, crop by w
					w = Math.floor(w / (h / 75)) ///
					h = 75;
					dx = Math.floor(-((w - 75) / 2)); ///
				}
				else
				{
					h = Math.floor(h / (w / 75)); ///
					w = 75;
					dy = Math.floor(-((h - 75) / 2)); ///
				}

				$(this).setStyle({width: w + "px", height: h + "px", position: "relative", left: dx + "px", top: dy + "px", display: "block"});
			};

			img.title = set.title;
			img.alt = set.title;
			img.style.display = "none";

			if (set.img)
			{
				img.src = set.img;
			}
			else
			{
				// album is missing cover
				img.src = "/images/facebook_album_cover_missing.png";
			}

			var inner = document.createElement("div");
			inner.setStyle({position: "absolute", left: "7px", top: "7px", width: "75px", height: "75px", border: "1px solid black", overflow: "hidden"});
			inner.appendChild(img);

			var div = document.createElement("div");
			div.setStyle({width: "91px", height: "95px", background: "#fff url(/images/set_case.gif) top left no-repeat", cursor: "pointer"});
			div.observe("click", this.showSetPhotos.bind(this, set.id));
			div.observe("dblclick", this.showSetPhotos.bind(this, set.id));
			div.appendChild(inner);

			var wrapper = document.createElement("div");
			wrapper.setStyle({position: "relative", float: "left", paddingRight: "8px", paddingBottom: "4px"});
			wrapper.appendChild(div);

			this.element.select(".photos_container").first().appendChild(wrapper);
		}
	},

	onChangeSet: function(evt)
	{
		if (this.cached_sets)
		{
			this.onGetSetsReply(this.cached_sets);
			return;
		}

		this.showLoader();
		this.import_service.getSets(this.onGetSetsReply.bind(this));
	},

	hasCookie: function(name)
	{
		var result = false;

		document.cookie.split(";").each(function(pair)
		{
			var args = pair.split("=");
			if (args && args.length > 0 && trim(args[0]) == name)
			{
				result = true;
			}
		});

		return result;
	}
});

var DumprFlickrAlbumConnector = Class.create(DumprWebAlbumConnector,
{
	initialize: function($super, id_of_element)
	{
		$super(id_of_element, "flickr");
	}
});

var DumprPicasaAlbumConnector = Class.create(DumprWebAlbumConnector,
{
	initialize: function($super, id_of_element)
	{
		$super(id_of_element, "picasa");

		if (this.hasCookie("gdataSession"))
		{
			this.import_service.authorize(this.onAuthorizeReply.bind(this));
		}
	}
});

var DumprFacebookAlbumConnector = Class.create(DumprWebAlbumConnector,
{
	initialize: function($super, id_of_element, app_id)
	{
		$super(id_of_element, "facebook");

		FB.init({appId: app_id, status: true, cookie: true, xfbml: true});

		if (this.hasCookie("fbs_" + app_id))
		{
			this.import_service.authorize(this.onAuthorizeReply.bind(this));
		}
	},

	onConnect: function(evt)
	{
		var that = this;

		FB.login(function(response)
		{
			that.import_service.authorize(that.onAuthorizeReply.bind(that));
		}, {perms: 'email,user_photos,friends_photos,publish_stream'});
	}
});

