var Collection	 = {
	// variables
	results:{},
	view:"",
	display:{
		iteration:0,
		pages:0,
		max:0,
		view:{
			list:{
				max:25
			},
			grid:{
				max:16
			},
			thumbs:{
				max:25
			},
			gallery:{
				max:5
			}
		}		
	},
	browse:false,
	//
	panels:{
		view:"view",		
		display:"display",
		empty:"empty",
		pending:"pending"
	},
			
	// service
	services:{
		server:"",
		path:"services/",
		collection:"collection.wsdl.php",
		browse:"browse.wsdl.php"
	},	
	
	// views
	control:{
		// set
		set:function(view)
		{
			Collection.view	= view;	
			$("div[class^='holder'] .display").show();
			this.change();
						
			var service	= !Collection.browse ? Collection.services.collection : Collection.services.browse;
			service		= Collection.services.server + Collection.services.path + service;

			$.ajax(
				{
					url:service,
					cache:false,
					data:{view:view},
					dataType:"json",
					type:"POST",
					success:function(response)
					{

					},
					error:function()
					{
						console.log("failed:" + service);
					}
				}
			);			
		},
		
		bind:function(browse, favorites)
		{
			if(favorites){Collection.favorites = favorites;}

			Collection.browse = !browse ? false : true;
			$("li[class^='view']").bind(
				'click',
				function()
				{
					var view	= $(this).attr("class");
					view		= view.slice(5, view.length);
					Collection.control.set(view, Collection.browse);			
				}
			);			
		},
				
		change:function()
		{
			// change highlight
			for(var view in Collection.display.view)
			{
				view == Collection.view	? $("." + view).addClass("on") : $("." + view).removeClass("on")
			}

			Item.change();					
		}
	},
	
	// data
	data:function()
	{
		var service	= !Collection.browse ? this.services.collection : this.services.browse;
		service		= this.services.server + this.services.path + service;

		var post	= this.search();
		if(Collection.favorites){post['favorites'] = true;}

		$.ajax(
			{
				url:service,
				cache:false,
				data:post,
				dataType:"json",
				type:"POST",
				success:function(response)
				{
					if(!response)
					{
						$("#" + Collection.panels.display).hide();
						$("#" + Collection.panels.view).hide();						
						$("#" + Collection.panels.empty).show();
					}
					else
					{
						$("#" + Collection.panels.display).show();
						$("#" + Collection.panels.empty).hide();
						Collection.results	= response;
						Collection.build();
					}
				},
				error:function()
				{
					console.log("failed:" + service);
				}
			}
		);		
	},
	
	build:function()
	{
		$("#" + this.panels.display).html("");
		for(result in this.results)
		{
			$("#" + this.panels.display).append(Item.generate(this.results[result]));
		}	
		this.control.change();
	},

	search:function()
	{
		var post	= {get:true}
		if (location.search != ""){ 
			var x = location.search.substr(1).split("&") 
			for (var i=0; i<x.length; i++){ 
				var y = x[i].split("="); 
				post[y[0]] = y[1];
			} 
		}
		return post;
	}
}

// individual images
var Item	= {
	// service
	services:{
		server:"",
		path:"services/",
		collection:"collection.wsdl.php",
		browse:"browse.wsdl.php"
	},
	// nodes	
	nodes:{
		holder:
		{
			type:"div",
			css:"holder"
		},
		details:{
			type:"div",
			css:"details"
		},
		trigger:{
			type:"div",
			css:"trigger"
		},		
		description:{
			type:"p",
			css:"description"
		},
		title:{
			type:"p",
			css:"title"
		},		
		image:{
			type:"div",
			css:"image"
		},
		img:{
			type:"img",
			css:""
		},		
		tags:{
			type:"p",
			css:"tags"
		},
		screenname:{
			type:"p",
			css:"screenname"
		},
		clear:{
			type:"div",
			css:"clear"
		}
	},
	
	// generate
	generate:function(data)
	{
		var item	= {}
		for(node in this.nodes)
		{
			item[node]	= $(document.createElement(this.nodes[node].type))
			$(item[node]).addClass(this.nodes[node].css);
		}
		
		// add view type
		$(item.holder).addClass(Collection.view)
		$(item.img).css({display:"none"});
		

		// image path and holder
		$(item.img).attr({src:unescape(data.path), loading:true});
		$(item.image).append(item.img);
		
		// bind image load
		$(item.img).bind(
			"load",
			function()
			{
				$(this).removeAttr("loading");
				$(this).attr({"w":$(this).width(),"h":$(this).height()});
				$(this).parent().css({background:"none"});
				Item.resize(this);
				$(this).unbind("load");
			}
		)		
		
		// id for updating
		$(item.tags).attr({trigger:data.image_id});
		$(item.title).attr({trigger:data.image_id});
		$(item.description).attr({trigger:data.image_id});
		
		// texts
		$(item.tags).html(unescape(data.tags));		
		$(item.title).html(data.title);
		$(item.description).html(unescape(data.description));
		
		// apend all objects
		$(item.details).append(item.title);
		$(item.details).append(item.description);		
		$(item.details).append(item.tags);
				
		$(item.holder).append(item.image);
		$(item.holder).append(item.details);
		$(item.holder).append(item.trigger);		
		$(item.holder).append(item.clear);

		if(!Collection.browse)
		{
			$(item.holder).append(Functions.dashboard(data));
		}
		else
		{
			if(data.screenname)
			{
				var span		= $(document.createElement("span"));
				$(span).html("posted by: ");

				var a			= $(document.createElement("a"));
				$(a).attr(
					{
						href:"profile.php?view=" + data.user_id
					}
				)

				$(a).append(data.screenname);
				$(item.screenname).append(span);
				$(item.screenname).append(a);
				$(item.details).append(item.screenname);
			}

			// if user logged in
			if(data.favorite)
			{
				$(item.holder).append(Functions.browse(data));
			}
		}

		// return
		return $(item.holder);				
	},

	resize:function(obj)
	{
		$(obj).removeAttr("width");
		$(obj).removeAttr("height");		
		
		var w		= $(obj).parent().width();
		var h		= $(obj).parent().height();
		
		// capture original w and height
		var dW		= parseInt($(obj).attr("w"));
		var dH		= parseInt($(obj).attr("h"));
		
		dW > dH	? $(obj).attr({width:w}) : $(obj).attr({width:h})
		if($(obj).height() < h)
		{
			$(obj).removeAttr("width");
			$(obj).attr({height:h})
		}
		
		$(obj).fadeIn();
	},
	
	change:function()
	{
		Gallery.kill();
		$("div[class^='holder']").removeClass().addClass(this.nodes.holder.css + " " + Collection.view)
		Collection.view != "gallery" && Collection.view != "thumbs" ? $("div[class^='holder'] .details").show() : $("div[class^='holder'] .details").hide();
		
		if($("textarea").length > 0)
		{
			var text	= $("textarea")
			var html	= Item.nl2br($(text).val());
			var parent	= $(text).parent();
			$(text).remove();
			$(parent).html(html);			
		}
	
		this.bind();


		if(!Collection.browse)
		{
			if(Collection.view == "list" || Collection.view == "gallery")
			{
				this.editable($(".holder .title"));
				this.editable($(".holder .description"));
				this.editable($(".holder .tags"));			
			}
			else
			{
				$(".holder .title").unbind('click');
				$(".holder .description").unbind('click');
				$(".holder .tags").unbind('click');
			}
			
		}

		$("div[class^='holder']").each(
			function()
			{
				if($(this).attr("class").indexOf("zoom") == -1)
				{
					if(!$(this).find("img").attr("loading"))
					{
						Item.resize($(this).find("img"));
					}
				}
			}
		)
	},
	
	bind:function()
	{
		$("div[class^='holder'] .trigger").unbind('mouseover mouseout click');
			
		// thumbnail view
		switch(Collection.view)
		{
			// thumbnail view
			case "thumbs":
				$("div[class^='holder'] .trigger").unbind('click');
				$("div[class^='holder'] .trigger").bind(
					'mouseover mouseout',
					function(event)
					{
						Item.details($(this).prev(), event)
					}
				)

				$("div[class^='holder'] .trigger").bind(
					'click',
					function(event)
					{
						// trigger gallery view
						$("li[class^='view gallery']").trigger('click');
						Gallery.build($(this).parent())
					}
				);
			break;
			// gallery view
			case "gallery":
				$("div[class^='holder'] .trigger").bind(
					'click',
					function(event)
					{
						Gallery.build($(this).parent())
					}
				);
				$("div[class^='holder']:nth-child(1) .trigger").trigger('click');
			break;
			default:
				$("div[class^='holder'] .trigger").unbind('click');

				$("div[class^='holder'] .trigger").bind(
					'click',
					function(event)
					{
						// trigger gallery view
						$("li[class^='view gallery']").trigger('click');
						Gallery.build($(this).parent())
					}
				);				
			break;
		}
	},
	
	details:function(display, event)
	{
		event.type == "mouseover" ? $(display).fadeIn() : $(display).fadeOut('fast');	
	},

	editable:function(obj)
	{			
		if(obj)
		{
			$(obj).bind(
				'click',
				function()
				{	
					Item.editing($(this));
				}
			);
		}
	},
	
	editing:function(obj)
	{
		$(obj).unbind('click');
		
		// check for previous text field
		if($("textarea").length > 0)
		{
			var text	= $("textarea")
			var html	= Item.nl2br($(text).val());
			var parent	= $(text).parent();
			$(text).remove();
			$(parent).html(html);
			
			var post	= {
				id:$(parent).attr("trigger"),
				field:$(parent).attr("class"),
				value:$(parent).html(),
				update:true
			}
			
			// only fire if actually edited
			if(Collection.edit != post.value)
			{
				Item.connect(post, "collection")	
				
				// gallery bug fix
				if(Collection.view	== "gallery")
				{
					$("div[class^='holder'] ." + post.field + "[trigger=" + post.id + "]").html(html)
				}							
			}
		
			Item.editable($(parent));	
		}

		// capture pre edit
		Collection.edit	= $(obj).html();
		
		// create textfield
		var text	= $(document.createElement("textArea"))
		text.text(Item.br2nl($(obj).text()))
		$(obj).html("");
		$(obj).append(text);

		$(text).bind(
			'blur',
			function()
			{
				Item.editing(this)
			}
		)
	},
	
	connect:function(post, instance)
	{
		var service	= this.services.server + this.services.path + this.services[instance];
		$.ajax(
			{
				url:service,
				cache:false,
				data:post,
				dataType:"json",
				type:"POST",
				success:function(response)
				{

				},
				error:function()
				{
					console.log("failed:" + service);
				}
			}
		);	

	},	
	
	nl2br:function(text)
	{
		return text.replace(/\n/g, "<br />");
	},
	
	br2nl:function(text)
	{
		return text.replace("<br />", "/\n;");		
	}
}


// gallery view specific
var Functions = {
	// variables
	buttons:{
		dashboard:{
			privacy:{
				style:"icon i-"
			},
			deleted:{
				style:"icon i-"
			}
		},
		browse:{
			favorite:{
				style:"icon i-"
			}
		}
	},

	

	// methods
	browse:function(data)
	{
		var buttons	= $(document.createElement("ul"));
		$(buttons).addClass("functions");

		for(prop in this.buttons.browse)
		{
			var title	= prop == "favorite" && data.favorite != "false" ? "unfavorite" : "favorite";
			var li		= $(document.createElement("li"));
			$(li).attr(
				{
					"class":this.buttons.browse[prop].style + title,
					"trigger":data.image_id,
					"field":prop,
					"title":title
				}
			)

			$(li).bind(
				'click',
				function()
				{
					var update	= $(this).attr("title");
					var field	= $(this).attr("field");
					switch(field)
					{
						case "favorite":
							var style = $(this).attr("class").slice(7, $(this).attr("class").length) == "favorite" ? "unfavorite" : "favorite";
							$(this).attr({"title":style});
							var update = style == "favorite" ? "unfavorite" : "favorite";
							$(this).attr({"class":Functions.buttons.dashboard.privacy.style + style});

							if(Navigation.favorites	=== true)
							{
								$(this).parent().parent().fadeOut(
									'slow',
									function()
									{
										$(this).remove();
									}
								)
							}
						break;
					}

					var post	= {
						id:$(this).attr("trigger"),
						value:update,
						favorite:true
					}

					Item.connect(post, "browse");
				}
			);

			$(buttons).append(li);
		}

		return $(buttons); 
	},

	dashboard:function(data)
	{
		var buttons	= $(document.createElement("ul"));
		$(buttons).addClass("functions");
	
		for(prop in this.buttons.dashboard)
		{
			var title	= prop == "privacy" ? data.privacy : prop;
			var	field	= prop == "deleted" ? "status" : prop;
			var li		= $(document.createElement("li"));
			$(li).attr(
				{
					"class":this.buttons.dashboard[prop].style + title,
					"trigger":data.image_id,
					"field":field,
					"title":title
				}
			)

			$(li).bind(
				'click',
				function()
				{
					var update	= $(this).attr("title");
					var field	= $(this).attr("field");
					switch(field)
					{
						case "privacy":
							var update = $(this).attr("class").slice(7, $(this).attr("class").length) == "private" ? "public" : "private";
							$(this).attr({"title":update});
							$(this).attr({"class":Functions.buttons.dashboard.privacy.style + update});
						break;
						case "status":
							switch(update)
							{
								case "deleted":
									$(this).parent().parent().fadeOut(
										'slow',
										function()
										{
											$(this).remove();
										}
									)
								break;
							}
						break;
					}

					var post	= {
						id:$(this).attr("trigger"),
						field:$(this).attr("field"),
						value:update,
						update:true
					}

					Item.connect(post, "collection");
				}
			);

			$(buttons).append(li);
		}

		return $(buttons);
	}
}


// gallery view specific
var Gallery	= {
	// variables
	collection:"collection",
	zoom:{
		display:"display",
		details:"details",
		image:"image img"
	},
	styles:{
		clone:"holder gallery",
		zoom:"holder zoom"
	},
	current:{},
	main:{
		
	},
	
	// methods
	build:function(obj)
	{
		this.kill();
		
		// clone
		this.current	= $(obj).clone();
		$(this.current).removeClass(this.styles.clone).addClass(this.styles.zoom);
			
		// prepend
		$("#" + this.zoom.display).prepend(this.current)	
		
		// load image
		$("." + this.styles.zoom.split(" ")[1] + " ." + this.zoom.image).attr(
			{
				src:$("." + this.styles.zoom.split(" ")[1] + " ." + this.zoom.image).attr("src")
			}
		)
		
		$("." + this.styles.zoom.split(" ")[1] + " ." + this.zoom.image).css(
			{
				display:"none",
				width:"auto",
				height:"auto"
			}
		)		
		
		$("." + this.styles.zoom.split(" ")[1] + " .image img").bind(
			'load',
			function()
			{
				var w		= $("#" + Gallery.zoom.display + " ." + Gallery.zoom.image).width();
				var h		= $("#" + Gallery.zoom.display + " ." + Gallery.zoom.image).height();			
				Gallery.adjust(w, h);
			}
		)
		
		// change details
		$("." + this.styles.zoom.split(" ")[1] + " ." + this.zoom.details).show();

		if(!Collection.browse)
		{
			Item.editable($(".holder .title"));
			Item.editable($(".holder .description"));
			Item.editable($(".holder .tags"));
		}	
	},
	
	adjust:function(w, h)
	{
		var collection	= $("#" + this.collection).width();
		
		if(w > collection)
		{
			var width	= collection - 30;
			var ratio	= w/width;
			var height	= h/ratio;
			$("." + this.styles.zoom.split(" ")[1] + " .image img").width(width);			
			$("." + this.styles.zoom.split(" ")[1] + " .image img").height(height);			
		}
		
		$("." + this.styles.zoom.split(" ")[1] + " .image img").fadeIn();
	},
	
	kill:function()
	{
		// check if exists
		if($("." + this.styles.zoom.split(" ")[1]).length > 0)
		{
			$("." + this.styles.zoom.split(" ")[1] + " ." + this.zoom.image).remove()
			$("." + this.styles.zoom.split(" ")[1]).remove()
		}		
	}
}