/* FORMS - List options 
 * this handles the form that appears in the edit list dialog 
 */
Weblist.Forms.ListOptions =  
{
	init: function(data)
	{
		this.messageBoxCSS = {
				"position"  : "relative",
				"top"		: "-270px",
				"left"      : "0px",
				"width"		: "388px"
		};
		
		//bind the events
		$("input#dialog_listname").bind("invalid_field",null,function(){
			Weblist.Forms.Utils.createMessageBox("Invalid list name",Weblist.Forms.ListOptions.messageBoxCSS,"div#dialog_list_options");
		});
		
		//add the values
		this.bindData(data);
	},
	
	bindData: function(data)
	{
		if(!data)
			return;
		
		var listname 	= (data.listname) ? data.listname : "";
		var description = (data.description) ? data.description : "";
		var tags 		= (data.tags) ? data.tags : "";
		var list_type   = (data.list_type) ? data.list_type : "thumbnails"; //default value
		var list_voting = (data.list_voting) ? data.list_voting : false;
		var list_private = (data.list_private) ? data.list_private : false;
		
		
		$("input#dialog_listname").val(listname);
		$("textarea#dialog_description").val(description);
		$("input#dialog_tags").val(tags);
		
		if(list_type == "thumbnails")
			$("input#dialog_list_thumbnail").attr('checked',true);
		else
			$("input#dialog_list_full_items").attr('checked',true);
		
		$("input#dialog_list_voting").attr('checked', list_voting);
		$("input#dialog_list_private").attr('checked', list_private);
		
		$("input#options_list_name").val(listname);
	},	
	
	validate: function()
	{
		var filter = $("input#dialog_listname")
	    .filter(function() {
	    	if(this.value.length == 0) return true;
	        return this.value.match(/[^\a-zA-Z0-9-_ ]/);
	    });
		
		if(filter.length > 0)
		{
			filter.trigger("invalid_field");
			return false;
		}
		
		return true;
	},
	
	submit: function()
	{
		if(this.validate())
		{
			//collect the data
			var data = {
				"listname" 		: $("input#dialog_listname").val(),
				"description"	: $("textarea#dialog_description").val(),
				"tags"			: $("input#dialog_tags").val(),
				"list_type"		: ($("input#dialog_list_thumbnail").attr('checked')) ? "thumbnails" : "full_items",
				"list_voting" 	: $("input#dialog_list_voting").attr('checked'),
				"list_private" 	: $("input#dialog_list_private").attr('checked')
			};
			
			Weblist.Frames.List.update(data);
			Weblist.Dialog.close();
		}
	}
};

/*
 * FORMS - WEBPAGE ADD 1 
 * this is the form that appears in the first step of adding a webpage item 
 */

Weblist.Forms.WebpageUrl = 
{
	init: function(data)
	{
		//register the events
		$("textarea#dialog_urls_text").bind("invalid_field",null,function()
		{
			
			var css = {
					"position"  : "relative",
					"top"		: "-193px",
					"left"      : "-24px",
					"width"		: "370px"
			};
			
			Weblist.Forms.Utils.createMessageBox("You must insert at least one url",css,"div#dialog_webpage_url");
		});
		
		//bind the data
		$("textarea#dialog_urls_text").val(data);
	},
	
	getData: function()
	{
		 var matched_urls = $("textarea#dialog_urls_text").val().match(/(\b(?:(?:https?|ftp):\/\/|www\.)[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\/%=~_|])/g);
		 
		 if(matched_urls == null)
			 return [];
		 
		 var data = [];
		 for(var i=0;i<matched_urls.length;i++)
		 {
			 data[i] = {
				url : matched_urls[i],
				title: "",
				description: "",
				type: Weblist.Utils.ItemTypeEnum.Webpage
			 };
		 }
		 
		 return data;
	},
	
	validate: function()
	{
		var urls = this.getData();
		if(urls.length == 0)
		{
			$("textarea#dialog_urls_text").trigger("invalid_field");
			return false;
		}
		
		return true;
	}
};

/*
 * FORMS - EDIT DETAILS OF NEWLY CREATED ITEMS
 * this form appears in the second step of item creation 
 */

Weblist.Forms.EditDetails = 
{
	//this is called on before open and not open so we can modify the options depending the data
	init:function(data)
	{
		//clear the old data
		$("ul#details_list").children(".details_item").remove();

		
		if(data.length < 2)
			Weblist.Dialog.Options.EditDetails.height = 370;
		else
			Weblist.Dialog.Options.EditDetails.height = 500;
		
		this.bindData(data);
	},
	
	bindData:function(data)
	{
		for(var i=0;i<data.length;i++)
		{
			var item_url = Weblist.Utils.resolveUrl(data[i].url);
			//clone the reference object
			var item = $("li#details_item_reference").clone().removeAttr("id");
			item.attr("class","details_item").css("display","block");
			
			var src = global_thumbnail_small.replace('***url***', item_url);
			//"http://images.pageglimpse.com/v1/thumbnails?url="+item_url+"&size=small&devkey=3397f3b35c6ee99e3d326120d25d9b99"
			//set the image
			item.children(".details_image").children("img").attr("src", src);
			//set the url
			item.children(".details_item_url").val(item_url);
			//set the type
			item.children(".details_item_type").val(data[i].type);
			
			//set the title
			item.children(".details_inputs").children(".dialog_textfield").children(".dialog_textfield_middle").children("input").val(data[i].title);
			item.children(".details_inputs").children(".dialog_textarea").children(".dialog_textarea_middle").children("textarea").val(data[i].description);
			
			
			if(i == data.length - 1)
				item.css("border", "0px");
			//add it to the list
			$("ul#details_list").append(item);
		}
	},
	
	getData: function()
	{
		var data = [];
		
		var items = $("ul#details_list").children(".details_item");
		
		for(var i=0;i<items.length;i++)
		{
			var item = $(items[i]);
			
			data[i] = 
			{
				url 	   : item.children(".details_item_url").val(),
				title	   : item.children(".details_inputs").children(".dialog_textfield").children(".dialog_textfield_middle").children(".details_item_title").val(),
				description: item.children(".details_inputs").children(".dialog_textarea").children(".dialog_textarea_middle").children(".details_item_description").val(),
				type	   : parseInt(item.children(".details_item_type").val())
			};
		}
		
		return data;
	},
	
	submit: function()
	{
		//add the items
		Weblist.Frames.Items.addItems(this.getData());
		//close the dialog
		Weblist.Dialog.close();
	}

};

/*
 * FORMS - ADD VIDEO 
 * this is the form that is displayed in the add new video dialog
 */

Weblist.Forms.Video = 
{
	init: function(data)
	{
		//bind data
		this.bindData(data);
		
		//bind the events
	    $("input#dialog_video_url").bind("invalid_field",null,function()
		{
			var css = {
					"position"  : "relative",
					"top"		: "12px",
					"left"      : "-14px",
					"width"		: "415px"
			};
			Weblist.Forms.Utils.createMessageBox("Supported sites: " + Weblist.Utils.VideoUrlResolver.getServicesList() ,css,"div#dialog_video");
		});
	},
	
	bindData: function(data)
	{
		var url = (data && data.url) ? data.url : "";
		var title = (data && data.title) ? data.title : "";
		var description = (data && data.description) ? data.description : "";
		
		$("input#dialog_video_url").val(url);
		$("input#dialog_video_title").val(title);
		$("textarea#dialog_video_description").val(description);
	},
	
	
	validate: function()
	{
		var value = $("input#dialog_video_url").val();
		
		if(Weblist.Utils.VideoUrlResolver.validateUrl(value) == false)
		{
			$("input#dialog_video_url").trigger("invalid_field");
			return false;
		}
		
		return true;
	},
	
	submit: function()
	{
		if(this.validate())
		{
			var data = [{
				url			: $("input#dialog_video_url").val(),
				title		: $("input#dialog_video_title").val(),
				description	: $("textarea#dialog_video_description").val(),
				type 		: Weblist.Utils.ItemTypeEnum.Video
			}];
			
			//insert the new item
			Weblist.Frames.Items.addItems(data);
			
			//close the dialog 
			Weblist.Dialog.close();
		}
	}
};

/*
 * FORMS - EDIT ANY TYPE OF ITEM
 * this is the generic for handler for editing an item
 */

Weblist.Forms.EditItem = 
{
	init: function(data)
	{
		//save the data
		this.data = data;
		//bind the data
		this.bindData(this.data);
		//bind the events
		this.bindEvents();
	},
	
	bindEvents: function()
	{
		$("input#dialog_edit_url_field").bind("invalid_field",null,function()
		{
			var css = {
					"position"  : "relative",
					"top"		: "-175px",
					"left"      : "176px",
					"width"		: "238px"
			};
			Weblist.Forms.Utils.createMessageBox("The url is not valid",css,"div#dialog_edit");
		});
	},
	
	bindData: function(data)
	{
		$("input#dialog_edit_url_field").val(data.url);
		$("input#dialog_edit_title_field").val(data.title);
		$("input#dialog_edit_id_field").val(data.id);
		$("textarea#dialog_edit_description_field").val(data.description);
		
		var title = "", className = "";
		
		switch(parseInt(data.type))
		{
			case Weblist.Utils.ItemTypeEnum.Webpage: 
				title = "Edit your webpage item";
				className = "dialog_edit_icon sprite-general general-webpage_icon";
			break;
			case Weblist.Utils.ItemTypeEnum.Image:
				title = "Edit your image item";
				className = "dialog_edit_icon sprite-general general-photos_icon";
			break;
			case Weblist.Utils.ItemTypeEnum.Document:
				title = "Edit your document item";
				className = "dialog_edit_icon sprite-general general-document_icon";
			break;
			case Weblist.Utils.ItemTypeEnum.Text:
				title = "Edit your text item";
				className = "dialog_edit_icon sprite-general general-text_icon";
			break;
			case Weblist.Utils.ItemTypeEnum.Video:
				title = "Edit your video item";
				className = "dialog_edit_icon sprite-general general-video_icon";
			break;
			case Weblist.Utils.ItemTypeEnum.File:
				title = "Edit your file item";
				className = "dialog_edit_icon sprite-general general-file_icon";
			break;
		}
		
		$("div#dialog_edit_title").html(title);
		$("div#dialog_edit_icon").attr("class",className);
		
	},
	
	validate: function()
	{
		if(this.data.type == Weblist.Utils.ItemTypeEnum.Text)
			return true;
		
		var value = $("input#dialog_edit_url_field").val();
		
		if(value.match(/(\b(?:(?:https?|ftp):\/\/|www\.)[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\/%=~_|])/g) == null)
		{
			$("input#dialog_edit_url_field").trigger("invalid_field");
			return false;
		}
		
		return true;
		
	},
	
	submit: function()
	{
		if(this.validate())
		{
			//update the data
			Weblist.Frames.Items.update(Weblist.Forms.EditItem.getData());
			//close the dialog
			Weblist.Dialog.close();	
		}
	},
	
	getData: function()
	{
		var data = {};
		if($("input#dialog_edit_id_field").val().length > 0)
			data.id = parseInt($("input#dialog_edit_id_field").val());
		
		data.url = Weblist.Utils.resolveUrl($("input#dialog_edit_url_field").val());
		data.title = $("input#dialog_edit_title_field").val();
		data.description = $("textarea#dialog_edit_description_field").val();
		data.type = this.data.type;
		
		return data;
	}
};


/*
 * FORMS - ADD IMAGES FORM
 * this is used to add images 
 * NOTE: this can be merged with files (document and file) functionality. THe only difference is that images is performed in two 
 * steps and the other files upload is just in one
 */

Weblist.Forms.Images =
{
	init: function()
	{
		//error message css
		this.messageBoxCSS = {
				"position"  : "relative",
				"top"		: "20px",
				"left"      : "-10px",
				"width"		: "400px"
		};
		//init multi file
		this.initMultiFile();

		//register to the upload service
		Weblist.UploadService.bindLoadEvent(function(data){Weblist.Forms.Images.iframeHandler(data);});
	},
	
	initMultiFile: function()
	{
		$('div#dialog_files_browse').children("ul").css("list-style","decimal");
		
		//init the multifile
		$('input#images_upload').MultiFile({
			accept:'gif|jpg|jpeg|png|bmp',
			max:5,
			STRING:
			{
				file: "<li>$file</li>",
				remove: '<div class=\'sprite-general general-dialog_close_icon\'></div>'
			}	
		});
		
		$("textarea#dialog_images_field").val("");
		
		//reset the list
		$('.MultiFile-remove').click();
	},
	
	
	validate: function()
	{
		
		if($("div#images_upload_wrap_list").children().length == 0 && this.getStaticData().length == 0)
		{
			Weblist.Forms.Utils.createMessageBox("Enter at least one image URL. Supported extensions are jpg,jpeg,gif,png",this.messageBoxCSS,"div#dialog_images");
			return false;
		}
		
		if($("input#imgur_terms").attr("checked") == false && $("div#images_upload_wrap_list").children().length > 0)
		{
			Weblist.Forms.Utils.createMessageBox("Read and accept terms",this.messageBoxCSS,"div#dialog_images");
			return false;
		}
			
		return true;
	},
	
	submit: function()
	{
		if(this.validate())
		{
			
			if($("div#images_upload_wrap_list").children().length > 0)
			{
				var preloaderCSS = {
					"top" : "80px",
					"left": "90px"
				};
				
				Weblist.Dialog.showPreloader("Uploading the images ... Please wait!",preloaderCSS);
				$("form#dialog_images_form").submit();
			
			}
			else
			{
				this.postData(this.getStaticData());
			}
		}
	}, 
	
	iframeHandler: function(data)
	{
		if(data.errors)
		{
			Weblist.Dialog.hidePreloader();
			//show the errors
			Weblist.Forms.Utils.createMessageBox(data.errors[0].substring(0,30), this.messageBoxCSS, "div#dialog_images");
			
			return;
		}
		
		var staticData = this.getStaticData();
		this.postData(data.urls.concat(staticData));
		
	},
	
	postData: function(urls)
	{
		var details = [];
		for(var i=0;i<urls.length;i++)
		{
			details[i] = {
				url			: urls[i],
				title		: "",
				description	: "",
				type		: Weblist.Utils.ItemTypeEnum.Image
			};
		}
		
		var options = Weblist.Dialog.Options.EditDetails;
		options.beforeOpen = function(){
			Weblist.Forms.EditDetails.init(details);
		};
		
		Weblist.Dialog.open(options,"dialog_details");
	},
	
	getStaticData: function()
	{
		 var matched_urls = $("textarea#dialog_images_field").val().match(/(\b(?:(?:https?|ftp):\/\/|www\.)[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\/%=~_|]\.(jpg|png|jpeg|bmp|gif|JPG|PNG|JPEG|BMP|GIF))/g);
		 
		 if(matched_urls == null)
			 return [];
		 
		 
		 return matched_urls;
	}
	
};

/*
 * FORMS - ADD TEXT
 * This form handles the add text dialog
 */

Weblist.Forms.Text =  
{
	init:function(data)
	{
		this.data = data;
		
		//init the editor
		this.initEditor();
		
		//bind the data
		this.bindData(data);
	},
	
	initEditor: function()
	{
		//create element
		var textarea = $('<textarea class="editor" id="text_editor"></textarea>');
		//clean the container
		$("div#dialog_text_editor").html("");
		//apply editor
		$("div#dialog_text_editor").append(textarea);
		
		textarea.wysiwyg();
	},
	
	bindData: function(data)
	{
		//nothing for now
	},
	validate: function()
	{
		var text = this.getText();
		if(text.length == 0)
		{
			var css = {
					"position"  : "relative",
					"top"		: "-380px",
					"left"      : "124px",
					"width"		: "344px"
			};
			Weblist.Forms.Utils.createMessageBox("You have to enter a text",css,"div#dialog_text");
			return false;
		}
		
		return true;
		
	},
	
	submit: function()
	{
		if(this.validate())
		{
			Weblist.Frames.Items.addItems([this.getData()]);
			//close the dialog
			Weblist.Dialog.close();
		}
	},
	
	getText: function()
	{
		var iframe = $('#text_editorIFrame');
		var iframewindow= (iframe[0].contentWindow != undefined) ? iframe[0].contentWindow : iframe[0].contentDocument.defaultView;
		
		var text = iframewindow.document.body.innerHTML;
		return text;
	},
	
	getData: function()
	{
		var data = 
		{
			url			: null,
			title		: $("input#dialog_text_title").val(),
			description	: $("textarea#dialog_text_description").val(),
			type		: Weblist.Utils.ItemTypeEnum.Text,
			additional	: this.getText()
		};
		
		return data;
	}
};


/*
 * FORMS - add new file
 * This is the form used to perform Document and File upload. The difference between them is applied from 
 * the options argument 
 * NOTE : IMAGES CAN BE INCLUDED HERE 
 */
Weblist.Forms.File=
{
	init: function(options)
	{
		//error message css
		this.messageBoxCSS = {
				"position"  : "relative",
				"top"		: "-160px",
				"left"      : "178px",
				"width"		: "200px"
		};
		
		this.options = options;
	
		//apply the options to the form elements
		this.applyOptions(options);
		//init Multi upload
		this.initMultiFile(options);
		//register to the upload service
		Weblist.UploadService.bindLoadEvent(function(data){Weblist.Forms.File.iframeHandler(data);});
	},
	
	
	
	initMultiFile: function(options)
	{
		//reset the list
		$('.MultiFile-remove').click();
		$('div#dialog_files_browse').children("ul").css("list-style","none");
		
		//init the multifile
		$('input#files_upload').MultiFile({
			accept: options.accept,
			max:1,
			STRING:
			{
				file: "<li>$file</li>",
				remove: '<div class=\'sprite-general general-dialog_close_icon\'></div>'
			}	
		});
		
	},
	
	applyOptions: function(options)
	{
		$("form#dialog_files_form").attr("action",options.action);
		$("div#dialog_files_title").html(options.title);
		$("div#dialog_files_terms").html("<input type='checkbox' id='files_terms'/> I accept "+options.name+" <a href='"+options.terms_url+"' target='_blank'> terms and conditions</a>");
		$("div#dialog_files_footer").children("img").removeAttr("src").attr("src",options.footer_url);
		
		//clean the objects
		$("input#dialog_files_title_input").val("");
		$("textarea#dialog_files_description").val("");
		
		$("div#dialog_files_browse").html("<ul><input type='file' id='files_upload' name='files'/></ul>");
	},
	
	validate: function()
	{
		if($("div#files_upload_wrap_list").children().length == 0)
		{
			Weblist.Forms.Utils.createMessageBox("Enter at least one file",this.messageBoxCSS,"div#dialog_files");
			return false;
		}
		
		if($("input#files_terms").attr("checked") == false)
		{
			Weblist.Forms.Utils.createMessageBox("Read and accept terms",this.messageBoxCSS,"div#dialog_files");
			return false;
		}
			
		return true;
	},
	
	submit: function()
	{
		if(this.validate())
		{
			
			var preloaderCSS = {
				"top" : "80px",
				"left": "90px"
			};
			
			Weblist.Dialog.showPreloader(this.options.upload_title, preloaderCSS);
			
			$("form#dialog_files_form").submit();
		}
	}, 
	
	iframeHandler: function(data)
	{
		if(data.errors)
		{
			Weblist.Dialog.hidePreloader();
			//show the errors
			Weblist.Forms.Utils.createMessageBox(data.errors[0].substring(0,30), Weblist.Forms.File.messageBoxCSS  , "div#dialog_files");
	
			return;
		}
		
		var details = [];
		for(var i=0;i<data.urls.length;i++)
		{
			details[i] = {
				url			: data.urls[i],
				title		: $("input#dialog_files_title_input").val(),
				description	: $("textarea#dialog_files_description").val(),
				type		: Weblist.Forms.File.options.type
			};
		}
		
		Weblist.Frames.Items.addItems(details);
		//close the dialog
		Weblist.Dialog.close();
	}
};



/*
 * FORMS - THE MAIN FORM 
 * this wrappes all the frames
 * 
 */

Weblist.Forms.Main =
{
	init:function()
	{
	},
	
	submit:function()
	{
	}
};


/*
 * DIALOG OPTIONS 
 * this dialog opens when a user click edit in the list frame
 */
Weblist.Dialog.Options.ListOptions = 
{
	autoOpen: true,
	height: 430,
	width: 500,
	modal: true,
	
	buttons: {
		'Update': function() 
		{ 
			Weblist.Forms.ListOptions.submit();
		}
	},
	
	open: function(){
		Weblist.Forms.ListOptions.init(Weblist.Frames.List.getData());
	}
};

/*
 * DIALOG OPTIONS 
 * this dialog opens when a user click to add a webpage item
 */

Weblist.Dialog.Options.WebpageUrl = 
{
	autoOpen: true,
	height: 400,
	width: 450,
	modal: true,
	
	buttons: 
	{
		'Next': function() 
		{ 
			if(Weblist.Forms.WebpageUrl.validate())
			{
				var options = Weblist.Dialog.Options.EditDetails;
				options.beforeOpen = function() {
					Weblist.Forms.EditDetails.init(Weblist.Forms.WebpageUrl.getData());
				};
					
				Weblist.Dialog.open(options,"dialog_details");
			}
		}
	},
	
	open: function(){
		Weblist.Forms.WebpageUrl.init("");
	}
};



/*
 * DIALOG OPTIONS 
 * this dialog opens in the second step of item creation (image item , webpage item)
 */
Weblist.Dialog.Options.EditDetails =
{
	autoOpen: true,
	height: 500,
	width: 565,
	modal: true,
	
	buttons: {
		'Add to list': function() 
		{ 
			Weblist.Forms.EditDetails.submit();
		}
	}
};


/*
 * DIALOG OPTIONS
 * this dialog opens when the user clicks to add a video item
 */
Weblist.Dialog.Options.Video =
{
	autoOpen: true,
	height: 450,
	width: 500,
	modal: true,
	
	buttons: {
		'Upload': function(){ 
			Weblist.Forms.Video.submit();
		}
	},
	
	open: function(){
		Weblist.Forms.Video.init();
	}
};

/*
 * DIALOG OPTIONS 
 * this dialog opens when the user click to edit one item
 */

Weblist.Dialog.Options.EditItem =
{
	height: 365,
	width: 500,
	modal:true,
	buttons: {
		"Update" : function()
		{
			Weblist.Forms.EditItem.submit();
		}
	},
	open: function(){
		Weblist.Forms.EditItem.init(Weblist.Frames.Items.getData(true));
	}
};

/* DIALOG OPTIONS IMAGES 
 * This dialog opens when the use click to add one imge
 */
Weblist.Dialog.Options.Images = 
{
	height: 480,
	width: 450,
	modal:true,
	buttons: 
	{
		"Next" : function()
		{
			Weblist.Forms.Images.submit();
		}
	},
	open: function()
	{
		Weblist.Forms.Images.init();
	}
};

/*
 * DIALOG OPTIONS text
 * this dialog opens when a user click to add a text 
 */

Weblist.Dialog.Options.Text =
{
	width:550,
	height:550,
	modal: true,
	buttons:
	{
		"Add to list": function()
		{
			Weblist.Forms.Text.submit();
		}
	},
	
	open: function()
	{
		Weblist.Forms.Text.init();
	}
},

/* 
 * DIALOG OPTIONS crocodoc
 * this dialog opens when the use click to add a document
 */ 
Weblist.Dialog.Options.Crocodoc =
{
	height: 440,
	width: 450,
	modal:true,
	buttons: 
	{
		"Add to list" : function()
		{
			Weblist.Forms.File.submit();
		}
	},
	
	open: function()
	{
		var options = {
			type		: Weblist.Utils.ItemTypeEnum.Document,
			accept		: "ppt|pptx|doc|docx|pdf|psd",
			title   	: "Select a document to upload. Don't forget to enter a title and description. Once you're ready, click the 'add to list' button to upload.",
			name    	: "Crocodoc",
			terms_url 	: "http://crocodoc.com/legal/terms-of-use/",
			action		: weblistRootPath + "upload/crocodoc",
			footer_url  : weblistRootPath + "public/images/index/crocodoc_logo_small.gif",
			upload_title: "Uploading the document ... Please wait!"
		};
		
		Weblist.Forms.File.init(options);
	},
	title: "Add a Document"
};

/*
 * DIALOG OPTIONS Rapidshare - file
 * this opens when the user clicks to add a new file item
 */

Weblist.Dialog.Options.RapidShare =
{
	height: 440,
	width: 450,
	modal:true,
	buttons: 
	{
		"Upload" : function()
		{
			Weblist.Forms.File.submit();
		}
	},
	
	open: function()
	{
		var options = {
			type		: Weblist.Utils.ItemTypeEnum.File,
			title   	: "Upload a file from your computer to your list. Files can be of any format. Don't forget to add a title and description to your file.",
			name    	: "RapidShare",
			terms_url 	: "http://rapidshare.com/#!rapidshare-ag/rapidshare-ag_privacy",
			action		: weblistRootPath + "upload/rapidshare",
			footer_url  : weblistRootPath + "public/images/index/rapidshare_logo_small.gif",
			upload_title: "Uploading the file ... Please wait!"
		};
		
		Weblist.Forms.File.init(options);
	},
	title: "Add a File"
};







/*
 * FRAMES - List options
 * this is the frame that handles all the list options : private list , thumbnail , list_name ...
 */

Weblist.Frames.List =  
{
	init:function()
	{
		//bind the events
		this.bindEvents();
	},
	
	bindEvents: function()
	{
		if($("#options_edit").length > 0)
			$("#options_edit").bind("click",null , function(){
				Weblist.Dialog.open(Weblist.Dialog.Options.ListOptions,"dialog_list_options");
			});
		
		if($("#options_edit_link").length > 0)
			$("#options_edit_link").bind("click",null , function(){
				Weblist.Dialog.open(Weblist.Dialog.Options.ListOptions,"dialog_list_options");
			});
		
		if($("#options_list_name").length > 0)
			$("#options_list_name").bind("change",null , function(){
				var _this = Weblist.Frames.List;
				
				var data = _this.getData();
				if(data)
					data.listname = $(this).val();
				
				_this.update(data);
			});
		
	},
	
	update: function(data)
	{
		//alert(JSON.stringify(data));
		$("input#list_data").val(JSON.stringify(data));
		
		this.updateUI(data);
	},
	
	updateUI: function(data)
	{
		$("#options_list_name").val((data && data.listname) ? data.listname : "");
	},
	
	getData: function()
	{
		var value = $("input#list_data").val();
		
		if(value.length == 0)
			return {};
		
		var data = eval("(" +value+ ")");
		
		if(data.list_voting == "true") data.list_voting = true;
		if(data.list_voting == "false") data.list_voting = false;
		if(data.list_private == "true") data.list_private = true;
		if(data.list_private == "false") data.list_private = false;
		
		return data;
	}, 
	
	validateData: function()
	{
		var data = this.getData();
		
		if(data.listname && data.listname.length > 0 && data.listname.match(/[^\a-zA-Z0-9-_ ]/) != null)
			return "Please enter a valid list name";
		
		return true;
	}
};


/*
 * FRAMES - ADD ITEM
 * this frames is the object that displays the buttons for displaying add dialogs
 */

Weblist.Frames.AddItems =
{
	init: function()
	{
		//bind the events
		$("div#button_web").bind("click",null, function(){
			Weblist.Dialog.open(Weblist.Dialog.Options.WebpageUrl,"dialog_webpage_url");
		});
		
		$("div#button_photo").bind("click",null, function(){
			Weblist.Dialog.open(Weblist.Dialog.Options.Images,"dialog_images","dialog_images_footer");
		});
		
		$("div#button_text").bind("click",null, function(){
			Weblist.Dialog.open(Weblist.Dialog.Options.Text,"dialog_text");
		});
		
		$("div#button_document").bind("click",null, function(){
			Weblist.Dialog.open(Weblist.Dialog.Options.Crocodoc,"dialog_files","dialog_files_footer");
		});
		
		$("div#button_video").bind("click",null, function(){
			Weblist.Dialog.open(Weblist.Dialog.Options.Video,"dialog_video");
		});
		
		$("div#button_file").bind("click",null, function(){
			Weblist.Dialog.open(Weblist.Dialog.Options.RapidShare,"dialog_files","dialog_files_footer");
		});
	}
};


/*
* 
* FRAME Items - this is capi di tuti capi 
* this is the frame that handles the items edit , position set , it includes all the hidden fields required
* 
*/

Weblist.Frames.Items =
{
	init:function()
	{
		if($("#items_list").length == 0)
			return;
		
		//sortable options
		this.sortableOptions = 
		{
			disabled: true,
			opacity: 0.6,
			containment: 'parent',
			cursor: 'pointer',
			items: '.item_container',
			scroll: false,
			tolerance: 'intersect',
			start: function (event,ui) {
				Weblist.Frames.Items.isDragging = true;
			},
			stop: function (event,ui){
				Weblist.Frames.Items.isDragging = false;
				$("#items_list").sortable("disable");
			}
		};
		//indicated weather the sortable is in the middle of some dragging process
		this.isDragging = false;
		
		//this is the last index id added in the list
		this.lastIndex = 0;
		
		//this is the tak id which runs every two seconds and verifies if a menu has to be closed
		this.menuTask 	= null;
		
		//indicates which item was clicked to be edited. this is usefull for a fast selection from outside
		this.focusedItem = null;
		
		//show the emplty message
		$("#items_empty_message").show();
		
		//init the sortable
		$("#items_list").sortable(this.sortableOptions);
		$("#items_list").sortable("disable");
		
		this.bindData();
	},
	
	bindData: function()
	{
		if(gListItems != undefined && gListItems.length > 0)
			this.addItems(gListItems);
	},
	
	bindItemsEvents: function(item)
	{
		var items = [];
		if(item)
			items[0] = $(item).children(".item");
		else
			items = $("div#items_list div.item");
		
		for(var i=0;i<items.length;i++)
		{
			//bind the self events
			$(items[i]).unbind("mouseenter mouseleave");
			$(items[i]).children(".move").unbind("click");
			
			$(items[i]).bind("mouseenter",null,function(){
				//$("span#weblist_debug").html("mouse over: " + $(this).parent().attr("id") + " ");
				//register it for not closing
				$(this).attr("close","false");
				
				if(Weblist.Frames.Items.isDragging) 
					return;
				
				$(this).children(".item_menu").slideDown(100);
				
				//create a new tooltip
				var item_values = eval( '(' + $(this).parent().children('.item_data').val() + ")");
				
				Weblist.Tooltip({
					parent	: this,
					follow	: "top-centered",
					title 	: (item_values.title.length > 0) ? item_values.title : 'No title',
					content	: (item_values.description.length > 0) ? item_values.description : '-'
				});
			});
			
			$(items[i]).bind("mouseleave",null,function(){
				
				//$("span#weblist_debug").html("mouse out: " + $(this).parent().attr("id") + " ");
				//register it for closing
				$(this).attr("close","true");
				
				//hide the tooltip
				Weblist.Tooltip();
				
				if(Weblist.Frames.Items.isDragging) 
					return;
				
				$(this).children(".item_menu").slideUp(200);
			});
			
			//bind the menu events
			var move = $(items[i]).children(".item_menu").children(".move");
			if(move && move.length > 0)
			{
				move = $(move[0]);
				move.unbind("mousedown").bind("mousedown",null,function(){
					//hide the tooltip
					Weblist.Tooltip();
					//enable the sortable
					$("#items_list").sortable("enable");
				});
			}
			
			var remove = $(items[i]).children(".item_menu").children(".delete");
			if(remove && remove.length > 0)
			{
				remove = $(remove[0]);
				remove.unbind("click").bind("click",null,function(){
					if(confirm("Are you sure you want to delete this item ? "))
					{
						Weblist.Frames.Items.removeItem($(this).parents(".item_container"));
						Weblist.Frames.Items.isDragging = false; 
					}
				});
			}
			
			var edit = $(items[i]).children(".item_menu").children(".edit");
			if(edit && edit.length > 0)
			{
				edit = $(edit[0]);
				edit.unbind("click").bind("click",null,function()
				{
					//select this item as the last item to be edited
					Weblist.Frames.Items.focusedItem = $(this).parents(".item_container");
					
					//open the dialog
					Weblist.Dialog.open(Weblist.Dialog.Options.EditItem,"dialog_edit");
					
					//indicate that the dragging process has stopped
					Weblist.Frames.Items.isDragging = false; 
				});
			}
			
		}
		
		//register a timer to check if there are any menus to close
		this.menuTask = setInterval(Weblist.Frames.Items.menuTaskHandler,2000);
	},
	
	menuTaskHandler: function()
	{
		var items = $("div#items_list div.item");
		for(var i=0;i<items.length;i++)
		{
			if($(items[i]).attr("close") == "true")
			{
				//trigger the mouseleave event
				//$(items[i]).trigger("mouseleave");
				//hide the menu
				$(items[i]).children(".item_menu").slideUp(200);
			}
		}
	},
	
	addItems: function(data)
	{
		if(!data) return;
		
		var itemsData = this.getDataArray();
		
		for(var i=0;i<data.length;i++)
		{
			var bBreak = false;
			//validate the item 
			for(var j=0;j<itemsData.length;j++)
			{
				if(data[i].type != 6 && data[i].url.toLowerCase() == itemsData[j].url.toLowerCase() && data[i].type == itemsData[j].type)
				{
					alert("The item with url " + data[i].url + " is already in the list so it will be skipped");
					bBreak = true;
					break;
				}
			}
			if(bBreak == true)
				continue;
			
			var item_data = data[i];
			
			var item = $("div#items_list").children("div#item_reference").clone().removeAttr("id");
			
			item.attr("id", "item_" + (this.lastIndex++));
			item.css("display","block");
			
			//bind the action on the new item
			this.bindItemsEvents(item);
			//populate with data
			this.populateItem(item,data[i]);
			
			//add it to the list
			$("div#items_list").append(item);
			
			itemsData.push(data[i]);
		}
		
		if(data.length > 0)
		{
			$("#items_empty_message").hide();
			//move the item clearer
			var clear = $("div#items_list").children(".clear").clone();
			$("div#items_list").children(".clear").remove();
			
			$("div#items_list").append(clear);
		}
		
		this.focusedItem = null;
		
	},
	
	populateItem: function(item, data)
	{
		//add content
		switch(parseInt(data.type))
		{
			case Weblist.Utils.ItemTypeEnum.Webpage:
				var src = global_thumbnail_small.replace('***url***', data.url);
				var image = $("<img src='" + src + "' style='width:100px;height:75px'/>");
				item.children(".item").children(".item_content").html("").append(image);
			break;
			case Weblist.Utils.ItemTypeEnum.Image:
				var image = $("<img src='"+data.url+"' style='width:100px;height:75px'/>");
				item.children(".item").children(".item_content").html("").append(image);
			break;
			case Weblist.Utils.ItemTypeEnum.Text:
				var image = $("<div class='sprite-general general-text_item' style='margin-top:13px'></div>");
				item.children(".item").children(".item_content").html("").append(image);
				item.children(".item").children(".item_menu").addClass('item_menu_v1');
			break;
			case Weblist.Utils.ItemTypeEnum.Document:
				var image = $("<div class='sprite-general general-document_item' style='margin-top:13px'></div>");
				item.children(".item").children(".item_content").html("").append(image);
				item.children(".item").children(".item_menu").addClass('item_menu_v1');
			break;
			case Weblist.Utils.ItemTypeEnum.Video:
				var image = $("<div class='sprite-general general-video_item' style='margin-top:13px'></div>");
				item.children(".item").children(".item_content").html("").append(image);
				item.children(".item").children(".item_menu").addClass('item_menu_v1');
			break;
			case Weblist.Utils.ItemTypeEnum.File:
				var image = $("<div class='sprite-general general-file_item' style='margin-top:13px'></div>");
				item.children(".item").children(".item_content").html("").append(image);
				item.children(".item").children(".item_menu").addClass('item_menu_v1');
			break;
		}
		
		if(!data.title) data.title = "";
		if(!data.description) data.description = "";
		if(!data.additional) data.additional = "";
		
		//try to use only this field 
		item.children(".item_data").val(JSON.stringify(data));
	},
	
	removeItem: function(item)
	{
		if(!item) return; 
		item = $(item);
		
		//mark the item as deleted
		var data = this.getData(false, item);
		
		if(data.id)
			$("form#form_main").append(jQuery("<input type='hidden' name='items_deleted[]' value='"+data.id+"'/>"));
		
		item.remove();
		
		if($("div#items_list div.item").length == 1)
		{
			$("#items_empty_message").show();
		}
	},
	
	getData: function(bFromFocused, candidate)
	{
		var item = null;
		
		if(bFromFocused)
			item = this.focusedItem;
		else
			item = candidate;
		
		if(item == null)
			return [];
		
		item = $(item);
		var value = item.children(".item_data").val();
		if(value.length == 0)
			return [];
		
		var data = eval('(' +item.children(".item_data").val()+ ')');
		
		return data;
	},
	
	getDataArray: function()
	{
		var items = $("div#items_list").children("div.item_container");
		var result = [];
		for(var i=0;i<items.length;i++)
		{
			var item = jQuery(items[i]);
			var itemData = this.getData(false,item);
			if(itemData.length == undefined || itemData.length > 0)
				result.push(itemData);
		}
		return result;
	},
	
	update: function(data)
	{
		if(this.focusedItem == null) return;
		
		var item = this.focusedItem;
		this.focusedItem = null;
		
		this.populateItem(item, data);
	},
	
	validateData: function()
	{
		var item_list = $("div#items_list .item_container");
		
		if(item_list.length < 2)
			return "Please add at least one item";
		
		return true;
	}
};


/*
 * UTILS - Video Url resolver 
 * this Object validates a video url with the known services
 */
Weblist.Utils.VideoUrlResolver = 
{
	_services:
	[
	 	{"name" : "MetaCafe" , "url_format" : "((http://www.metacafe.com/watch/)*([0-9]+)(/*))"},
	 	{"name" : "DailyMotion" , "url_format" : "(http://www.dailymotion.com/video/)"},
	 	{"name" : "Youtube" , "url_format" : "(http://www.youtube.com/watch\\?v=)"},
	 	{"name" : "Vimeo" , "url_format" : "((http://vimeo.com/)([0-9]+)$)"},
	 	{"name" : "Vimeo" , "url_format" : "((http://www.vimeo.com/)([0-9]+)$)"}
	],
	
	getServicesList: function()
	{
		var names = [];
		for(var i=0;i<this._services.length;i++)
		{
			names[i] = this._services[i].name;
		}
		
		return names;
	},
	
	validateUrl: function(url)
	{
		//create the regex pattern
		var pattern = "^";
		for(var i=0;i<this._services.length;i++)
		{
			pattern += this._services[i].url_format;
			if(i != this._services.length -1)
				pattern += "|";
		}
		
		var regex = new RegExp(pattern);
		
		if(url.match(regex) != null)
			return true;
		
		return false;
	}
};


