var GuardianSpaceName = {
	page: 1,
	page_size: 12,
	filter: "ALL",
	order: "ORDER_INDEX",
	selector: "VIDEOS", //VIDEOS, IMAGES, DOCUMENTS, COUPON
	query:"",
	isFilter:false,
	filterLabel:"in all time",
	MAX_DESCRIPTION: 100,

	space_id: -1,
	videos: null,
	preview_w: 425,
	preview_h: 344,
	space:null,
	videoDescription:null,
	
	init: function(){
		var offset = (this.page -1)*this.page_size;		
		var args = GuardianUtil.getArgs();
		
		this.selector = args['type'];
		if(this.selector == null)
			this.selector = "VIDEOS";
		
		if(this.selector == "IMAGES")
			$(".tab_content_menu:eq(1)").addClass("activelink");
		else if(this.selector == "DOCUMENTS")
			$(".tab_content_menu:eq(2)").addClass("activelink");
		else if(this.selector == "TEXTCONTENTS")
			$(".tab_content_menu:eq(3)").addClass("activelink");
		else if(this.selector == "COUPON")
			$(".tab_content_menu:eq(4)").addClass("activelink");
		else
			$(".tab_content_menu:eq(0)").addClass("activelink");
		
		$(".tab_content_menu:eq(0)").click(function(){document.location="partnerManager.page?type=VIDEOS"});
		$(".tab_content_menu:eq(1)").click(function(){document.location="partnerManager.page?type=IMAGES"});
		$(".tab_content_menu:eq(2)").click(function(){document.location="partnerManager.page?type=DOCUMENTS"});
		$(".tab_content_menu:eq(3)").click(function(){document.location="partnerManager.page?type=TEXTCONTENTS"});
		$(".tab_content_menu:eq(4)").click(function(){document.location="partnerManager.page?type=COUPON"});
		
		if(GuardianLogin.account!=null){
			var result = jsonrpc.v2spaceService.getSpacesByAccount(GuardianLogin.account.id,"ADDED","",0,1,"SpaceSmall");
			var space = {};
			if(result.list != null && result.list.list.length>0){
				space = result.list.list[0];
			}
			
			var spaceid = space.spaceId;
			if(this.selector != "COUPON")
				$('.tools').show();
			
			$('.list3').show();
			
			if(spaceid != null){		
				GuardianSpaceName.space_id = spaceid;
				GuardianSpaceName.space = space;
				GuardianSpaceName.initMenu(spaceid);
				GuardianSpaceName.getContentList();
				$('.spacename_title .meta_title').text(_messages.yourchannel + space.name);
						
				$('#sendAll').attr('href',"javascript:GuardianSpaceName.showSendAll()");
				$('#addContent').attr('href', 'import.page?spaceid='+GuardianSpaceName.space_id + "&type=" +GuardianSpaceName.selector);		
			}
			else{
				document.location.href='loveresto.page';
			}			
		}
		else{		
			var page = 'partnerManager';
		
			var loginpage = "login.page?callback=" + page;
			var joinpage = "join.page?callback=" + page;
			
			var str = '&';
			var args = GuardianUtil.getArgs();
			var nameArgs = GuardianUtil.getArgsNames();
			for(i=0; i<nameArgs.length; i++){		  	   
				if(nameArgs[i].toLowerCase()!='callback'){
					str = str+nameArgs[i]+'='+args[nameArgs[i]]+'&';
				}
			}			
			str = str.substring(0,str.length-1);
			loginpage = loginpage + str;
			joinpage = joinpage +str;			
			
			$('#no_account a:eq(0)').attr('href',loginpage);
			$('#no_account a:eq(3)').attr('href',joinpage);
			$('#no_account').show();
		}
		
		$('#publish_share').css("width","590px");	
		$('#update_audience').css("width","800px");	
		//$('#preview_video').css("width","500px");		
	},
	
	initSettings: function(){
			$(".tab_content_menu:eq(0)").click(function(){document.location="partnerManager.page?type=VIDEOS"});
			$(".tab_content_menu:eq(1)").click(function(){document.location="partnerManager.page?type=IMAGES"});
			$(".tab_content_menu:eq(2)").click(function(){document.location="partnerManager.page?type=DOCUMENTS"});
			$(".tab_content_menu:eq(3)").click(function(){document.location="partnerManager.page?type=TEXTCONTENTS"});
			$(".tab_content_menu:eq(4)").click(function(){document.location="partnerManager.page?type=COUPON"});
	
			if(GuardianLogin.account!=null){
				var result = jsonrpc.v2spaceService.getSpacesByAccount(GuardianLogin.account.id,"ADDED","",0,1,"SpaceSmall");
				var space = {};
				if(result.list != null && result.list.list.length>0){
					space = result.list.list[0];
				}
			
				var spaceid = space.spaceId;
				if(spaceid != null){	
					$('.tools').show();
					GuardianSpaceName.initMenu(spaceid);
					$('.spacename_title .meta_title').text(_messages.yourchannel + space.name);
					jsonrpc.partnerService.getPartnerDetails(GuardianSpaceName.getPartnerDetailsCbk, spaceid);
				}
			}
			else{		
				var page = 'partnerManager';
		
				var loginpage = "login.page?callback=" + page;
				var joinpage = "join.page?callback=" + page;
			
				var str = '&';
				var args = GuardianUtil.getArgs();
				var nameArgs = GuardianUtil.getArgsNames();
				for(i=0; i<nameArgs.length; i++){		  	   
					if(nameArgs[i].toLowerCase()!='callback'){
						str = str+nameArgs[i]+'='+args[nameArgs[i]]+'&';
					}
				}			
				str = str.substring(0,str.length-1);
				loginpage = loginpage + str;
				joinpage = joinpage +str;			
			
				$('#no_account a:eq(0)').attr('href',loginpage);
				$('#no_account a:eq(3)').attr('href',joinpage);
				$('#no_account').show();
			}
		
	},
	
	initMenu: function(spaceId){
	    v = '<center><iframe width="1050px" height="780px" frameborder="0" src="http://loveresto.com/partnerProfileEmbed.page?spaceid=' + spaceId + '></iframe></center>';
		$("#embedSpace textarea").val(v);
 
		result = jsonrpc.spaceService.getSpaceProperty(spaceId,"SERVICES");
		settings = null;
		if(result==null){
			$(".service_box input").attr("checked","checked");
			$(".tab_content_menu").show();
		}else{
			eval("settings = " + result.value);
			GuardianSpaceName.settingsId = result.id;
			$(".tab_content_menu:gt(0)").hide();

			for(i=0;i<settings.length;i++){
		    			$(".service_box #" + settings[i]).attr("checked","checked");
		    			if(settings[i]=="sImage"){
		    				$(".tab_content_menu:eq(1)").show();
		    			}
		    			if(settings[i]=="sMenu"){
		    				$(".tab_content_menu:eq(2)").show();
		    			}
		    			if(settings[i]=="sNews"){
		    				$(".tab_content_menu:eq(3)").show();
		    			}
		    			if(settings[i]=="sCoupon"){
		    				$(".tab_content_menu:eq(4)").show();
		    			}
		   			 }
			}
			GuardianSpaceName.settings = settings;
	},
	
	pagination: function(total) { 
	   if(total == 0){
		 $('.pagination').hide();
		 return;
	   }
	   
	   var nPages = Math.ceil(total/this.page_size);
	   var el = $($('.list3')).find('.count_pages');
	   //Videos list 1 of 50
	   el.html("Pagina <b>" + this.page + "</b> di " + nPages);
	   
	   var prev = $($('.list3')).find('.prev');
	   prev.attr("href","#");
	   if(this.page > 1)
	   		prev.attr("href","javascript:GuardianSpaceName.changePage(" + (this.page - 1) + ")");
	   var more = $($('.list3')).find('.more');
	   more.attr("href","#");
	   if(this.page != nPages)
		    more.attr("href","javascript:GuardianSpaceName.changePage(" + (this.page + 1) + ")");
	},
	
	changePage: function(page){
		GuardianSpaceName.page = page;
		$(".list3 .clean-ok").fadeOut("slow");
		GuardianSpaceName.getContentList();
	},
	
	getContentList: function(){
	    GuardianUtil.showLoading();
	    
	    $("#no_videos").fadeOut("slow");
	    
		var offset = (GuardianSpaceName.page -1)*GuardianSpaceName.page_size;
		
		if(GuardianSpaceName.selector=="IMAGES"){
			$("#gallery").show();
			$(".add_content_request:eq(1)").show();
			
			jsonrpc.spaceService.getImagesInSpaceByStatus(GuardianSpaceName.getVideoListCallback, 
													GuardianSpaceName.space_id, 
													GuardianSpaceName.query, 
													GuardianSpaceName.order, 
													GuardianSpaceName.filter, 
													null,null,
													GuardianSpaceName.page, 
													GuardianSpaceName.page_size);	
		}else if(GuardianSpaceName.selector=="DOCUMENTS"){
			jsonrpc.spaceService.getDocumentsInSpaceByStatus(GuardianSpaceName.getVideoListCallback, 
					GuardianSpaceName.space_id, 
					GuardianSpaceName.query, 
					GuardianSpaceName.order, 
					GuardianSpaceName.filter, 
					null,null,
					GuardianSpaceName.page, 
					GuardianSpaceName.page_size);	
		}else if(GuardianSpaceName.selector=="VIDEOS"){
			$("#addContent").hide();
			$(".add_content_request:eq(0)").show();

			jsonrpc.spaceService.getVideosInSpaceByStatus(GuardianSpaceName.getVideoListCallback, 
					GuardianSpaceName.space_id, 
					GuardianSpaceName.query, 
					GuardianSpaceName.order, 
					GuardianSpaceName.filter, 
					null,null,
					GuardianSpaceName.page, 
					GuardianSpaceName.page_size);	
		}else if(GuardianSpaceName.selector=="TEXTCONTENTS"){
			jsonrpc.spaceService.getTextContentInSpaceByStatus(GuardianSpaceName.getVideoListCallback, 
					GuardianSpaceName.space_id, 
					GuardianSpaceName.query, 
					GuardianSpaceName.order, 
					GuardianSpaceName.filter, 
					null,null,
					GuardianSpaceName.page, 
					GuardianSpaceName.page_size);	
		}else if(GuardianSpaceName.selector=="COUPON"){
			$("#sendAll").hide();
			$("#addContent").hide();
			$(".add_content_request:eq(2)").show();
			$("#couponManagerFrame").fadeIn("slow");
        	GuardianSpaceCoupon.spaceId = this.space.spaceId;
			GuardianSpaceCoupon.init();
			GuardianUtil.hideLoading();
      	}
	},
	
	getSpaceCouponCbk: function(result,e){
		if(e != null){
			GuardianUtil.hideLoading();
			return;
		}
		if(result != null){
			$("#couponId").val(result.id);
			$("#description").val(result.description);
			$("#couponType").val(result.type);
			if(result.startDate != null){
			}
			if(result.endDate != null){
			}
		}else{
		
		}
		GuardianUtil.hideLoading();
	},
	
	getPartnerDetailsCbk: function(space, e){
		if(e != null){
			GuardianUtil.hideLoading();
			return;
		}
		
		$("#settings").show();
		GuardianSpaceName.space = space;
		
		GuardianSpaceName.fillMetadataField("#f_description",space.description);
		GuardianSpaceName.fillMetadataField("#f_phone",space.owner.phoneNumber);
		GuardianSpaceName.fillMetadataField("#f_web",space.owner.website);
		GuardianSpaceName.fillMetadataField("#f_mail",space.owner.email);
		GuardianSpaceName.fillMetadataField("#f_cucina",space.categories.map.cucina);
		GuardianSpaceName.fillMetadataField("#f_specialita",space.categories.map.specialita);
		GuardianSpaceName.fillMetadataField("#f_consigliato",space.categories.map.consigliato);
		GuardianSpaceName.fillMetadataField("#f_ambiente",space.categories.map.ambiente);
		GuardianSpaceName.fillMetadataField("#f_prezzo",space.categories.map.prezzo);
		GuardianSpaceName.fillMetadataField("#f_pagamento",space.categories.map.pagamento);
		GuardianSpaceName.fillMetadataField("#f_chiusura",space.categories.map.chiusura);
		GuardianSpaceName.fillMetadataField("#f_servizi",space.categories.map.servizi);
		GuardianSpaceName.fillMetadataField("#f_claim",space.categories.map.claim);
		GuardianSpaceName.fillMetadataField("#f_trip_advisor",space.categories.map.trip_advisor);
		GuardianSpaceName.fillMetadataField("#f_facebook",space.categories.map.facebook);
		GuardianSpaceName.fillMetadataField("#f_twitter",space.categories.map.twitter);
		GuardianSpaceName.fillMetadataField("#f_googleplaces",space.categories.map.googleplaces);
		GuardianSpaceName.fillMetadataField("#f_wikipedia",space.categories.map.wikipedia);

		GuardianUtil.hideLoading();
	},
		
	savePartnerSettings: function(){
		$(".clean-ok").hide();
		
		space = GuardianSpaceName.space;
		settings = GuardianSpaceName.settings;

		if(space.categories == null)
			space.categories = {};
		
		space.description = GuardianSpaceName.getMetadataField("#f_description",space.description);
		space.owner.phoneNumber = GuardianSpaceName.getMetadataField("#f_phone",space.owner.phoneNumber);
		space.owner.website = GuardianSpaceName.getMetadataField("#f_web",space.owner.website);
		space.owner.email = GuardianSpaceName.getMetadataField("#f_mail",space.owner.email);
		
		space.categories.map.cucina = GuardianSpaceName.getMetadataField("#f_cucina",space.categories.map.cucina);
		space.categories.map.specialita = GuardianSpaceName.getMetadataField("#f_specialita",space.categories.map.specialita);
		space.categories.map.consigliato = GuardianSpaceName.getMetadataField("#f_consigliato",space.categories.map.consigliato);
		space.categories.map.ambiente = GuardianSpaceName.getMetadataField("#f_ambiente",space.categories.map.ambiente);
		space.categories.map.prezzo=GuardianSpaceName.getMetadataField("#f_prezzo",space.categories.map.prezzo);
		space.categories.map.prezzo=GuardianSpaceName.getMetadataField("#f_pagamento",space.categories.map.pagamento);
		space.categories.map.chiusura=GuardianSpaceName.getMetadataField("#f_chiusura",space.categories.map.chiusura);
		space.categories.map.servizi=GuardianSpaceName.getMetadataField("#f_servizi",space.categories.map.servizi);
		space.categories.map.claim=GuardianSpaceName.getMetadataField("#f_claim",space.categories.map.claim);
		space.categories.map.trip_advisor=GuardianSpaceName.getMetadataField("#f_trip_advisor",space.categories.map.trip_advisor);
		space.categories.map.facebook=GuardianSpaceName.getMetadataField("#f_facebook",space.categories.map.facebook);
		space.categories.map.twitter=GuardianSpaceName.getMetadataField("#f_twitter",space.categories.map.twitter);
		space.categories.map.googleplaces=GuardianSpaceName.getMetadataField("#f_googleplaces",space.categories.map.googleplaces);
		space.categories.map.wikipedia=GuardianSpaceName.getMetadataField("#f_wikipedia",space.categories.map.wikipedia);
		
		jsonrpc.partnerManager.updateSpaceWithCategories(space.spaceId,space.name, space.description, 
				space.address,  space.city, space.region, space.country, space.latitude, space.longitude, space.owner.email, space.owner.phoneNumber, space.owner.website, space.categories);
	
		btnChecked = $(".service_box input:checked");
		services = [];
		for(i=0;i<btnChecked.length;i++){
			services[i] = $(btnChecked[i]).attr("id");
		}
		
		if(GuardianSpaceName.settings == null){
			jsonrpc.spaceService.addPropertyToSpace("SERVICES",toJSON(services).json,space.spaceId,-1);
		}else{
			jsonrpc.spaceService.setPropertySpace("SERVICES",toJSON(services).json,GuardianSpaceName.settingsId);
		}
		
		GuardianSpaceName.initMenu(space.spaceId);
		
		$(".clean-ok").html(_messages.settings_ok); 
		$(".clean-ok").show();
	},
	
	fillMetadataField:function(id,value){
		if(value != null && value != ""){
			$(id).val(value);
		}else{
			$(id).val("");
		}
		
		$(id).bind("keyup",GuardianSpaceName.updateFieldCounter);
	},
	
	updateFieldCounter: function(event){
		var c = $(event.target).val();
		var m = $(event.target).attr("counter");
		if(m == null) 
			m = 128;
		else 
			m = parseInt(m);
		
		$("#settings .clean-error").remove();
		
		if(c.length > m){
			$(event.target).val(c.substring(0,m));
			p = $(event.target).parent();
			div = p.parent();
			div.prepend("<div class='clean-error' style='margin-bottom: 11px; text-align: center;'></div>");
			msg = _messages.error_counterfield;
			msg = msg.replace("%0",p.find("b").text());
			msg = msg.replace("%1",m);
			msg = msg.replace(":","");
			$("#settings .clean-error").text(msg);
			$("#settings .clean-error").show();
			return;
		}
	},
	
	getMetadataField:function(id,p){
		value = $(id).val().trim();
		if(value != null && value != ""){
			return value;
		}
		return null;
	},
	
	getVideoListCallback: function(result, e){
                
        GuardianUtil.hideLoading();
        
		if(e != null){
			return;
		}
		
		if(result==null){
			return;
		}
		
		if(result.list == null)
			return;
		
		var total = result.total;
		GuardianSpaceName.pagination(0);
		
		var results = result.list.list;
		
		GuardianSpaceName.videos=results;
		
		$('#sortable').html("");
		
		if(results.length==0){
			if(GuardianSpaceName.selector=="IMAGES"){
				$('#no_videos').text(_messages.noimg);
			}else if(GuardianSpaceName.selector=="DOCUMENTS"){
				$('#no_videos').text(_messages.nomenu);
			}else if(GuardianSpaceName.selector=="TEXTCONTENTS"){
				$('#no_videos').text(_messages.nonews);
			}else{
				$('#no_videos').text(_messages.novideo);
			}
			$('#no_videos').fadeIn('slow');
			return;
		}
		else{
			for(i=0;i<results.length;i++){ 
				var video = results[i];
				var el = null;
				
				if(GuardianSpaceName.selector=="IMAGES"){
					el = $(".video_list .box_content:first").clone();
					GuardianSpaceName.buildImageElement(video,el,i);
				}else if(GuardianSpaceName.selector=="DOCUMENTS"){
					el = $(".video_list .box_content:first").clone();
					GuardianSpaceName.buildDocumentElement(video,el,i);
				}else if(GuardianSpaceName.selector=="TEXTCONTENTS"){
					el = $(".video_list .box_text_content:first").clone();
					GuardianSpaceName.buildTextContentElement(video,el,i);
				}else{
					el = $(".video_list .box_content:first").clone();
					GuardianSpaceName.buildVideoElement(video,el,i);
				}
				el.show();
				$('.list3 .video_list ul').append(el);
			}
			
			$('.list3 .video_list').fadeIn("slow");
			
			if(GuardianSpaceName.selector == "IMAGES" || GuardianSpaceName.selector == "DOCUMENTS"){
				$( "#sortable").sortable({handle:".move"});
				$( "#sortable").disableSelection();
				$( "#sortable").bind( "sortupdate",GuardianSpaceName.goReorder);
			}
			
		}
	},
		

	buildVideoElement: function(video,el,i){
		$(el).children('.status').text(video.status);
		$(el).children('.status').addClass(video.status);
		$(el).children('.order_tools').addClass(video.status);
		$(el).children('.order_tools').html("");
		
		if(video.status == "ONLINE"){
			$(el).find('img').attr('src',video.imageName);
			$(el).find('.tools a:eq(0)').attr('href', 'javascript:GuardianSpaceName.showSendVideo('+i+')');
			$(el).find('img').bind("mouseover",function(){
					$('.preview').css("z-index",-1); 
					$(el).find('.preview').css("z-index",100)}
			);
			$(el).find('.preview').bind("mouseout",function(){$(el).find('.preview').css("z-index",-1)});
			$(el).find('.preview').bind("click",function(){$(el).find('.preview').css("z-index",-1);GuardianSpaceName.previewVideo(i)});
			$(el).find('.text .box_text_title').bind("click",function(){GuardianSpaceName.previewVideo(i)});
		}else{
			$(el).find('img').attr('src',"templates/defaultThumb.jpg");
			$(el).find('.tools').hide();
		}
		
		$(el).find('.delete a').hide();
		
  		$(el).find('.text .box_text_title').text(video.title);
  		$(el).find('.text .box_text_date').text(video.formattedTime);
	},
	
	buildImageElement: function(image,el,i){
		$(el).children('.status').text(image.status);
		$(el).children('.status').addClass(image.status);
		$(el).children('.order_tools').addClass(image.status);
		$(el).attr("imageId",image.id);
		$(el).attr("id","image_" + image.id);
		
		$(el).find('.order_tools .left').click({index:i},GuardianSpaceName.clickReorderLeft);
		if(i==0){
			$(el).find('.order_tools .left').css("visibility","hidden");
		}
		$(el).find('.order_tools .right').click({index:i},GuardianSpaceName.clickReorderRight);
		if(i==(GuardianSpaceName.videos.length-1)){
			$(el).find('.order_tools .right').css("visibility","hidden");
		}
		
		image.imageName = image.thumbnail;
		
		if(image.status == "ONLINE"){
			$(el).find('img').attr('src',image.thumbnail);
			$(el).find('.tools a:eq(0)').attr('href', 'javascript:GuardianSpaceName.showSendVideo('+i+')');
			$(el).find('img').bind("mouseover",function(){
					$('.preview').css("z-index",-1); 
					$(el).find('.preview').css("z-index",100)}
			);
			$(el).find('.preview').bind("mouseout",function(){$(el).find('.preview').css("z-index",-1)});
			$(el).find('.preview').bind("click",function(){$(el).find('.preview').css("z-index",-1);GuardianSpaceName.previewImage(i)});
			$(el).find('.text .box_text_title').bind("click",function(){GuardianSpaceName.previewImage(i)});

		}else{
			$(el).find('img').attr('src',"templates/defaultThumb.jpg");
			$(el).find('.tools').hide();
		}
		
		if(image.status != "PUBLISHING"){
			$(el).find('.delete a').attr('href', 'javascript:GuardianSpaceName.preDeleteImage('+i+')');
		}else{
			$(el).find('.delete a').hide();
		}
		
  		$(el).find('.text .box_text_title').text(image.title);
  		$(el).find('.text .box_text_date').text(image.creationDate);
  	},
  	
  	buildDocumentElement: function(document,el,i){
		$(el).children('.status').text(document.status);
		$(el).children('.status').addClass(document.status);
		$(el).children('.order_tools').addClass(document.status);
		$(el).attr("imageId",document.id);
		$(el).attr("id","image_" + document.id);
		
		$(el).find('.order_tools .left').click({index:i},GuardianSpaceName.clickReorderLeft);
		if(i==0){
			$(el).find('.order_tools .left').css("visibility","hidden");
		}
		$(el).find('.order_tools .right').click({index:i},GuardianSpaceName.clickReorderRight);
		if(i==(GuardianSpaceName.videos.length-1)){
			$(el).find('.order_tools .right').css("visibility","hidden");
		}
		
		document.imageName = document.thumbnail;
		
		if(document.status == "ONLINE"){
			$(el).find('img').attr('src',document.thumbnail);
			$(el).find('.tools a:eq(0)').attr('href', 'javascript:GuardianSpaceName.showSendVideo('+i+')');
			$(el).find('img').bind("mouseover",function(){
					$('.preview').css("z-index",-1); 
					$(el).find('.preview').css("z-index",100)}
			);
			$(el).find('.preview').bind("mouseout",function(){$(el).find('.preview').css("z-index",-1)});
			$(el).find('.preview').bind("click",function(){$(el).find('.preview').css("z-index",-1);GuardianSpaceName.previewDocument(i)});
			$(el).find('.text .box_text_title').bind("click",function(){GuardianSpaceName.previewDocument(i)});
		}else{
			$(el).find('img').attr('src',"templates/defaultThumb.jpg");
			$(el).find('.tools').hide();
		}
		
		if(document.status != "PUBLISHING"){
			$(el).find('.delete a').attr('href', 'javascript:GuardianSpaceName.preDeleteDocument('+i+')');
		}else{
			$(el).find('.delete a').hide();
		}
		
  		$(el).find('.text .box_text_title').text(document.title);
  		$(el).find('.text .box_text_date').text(document.creationDate);
  	},		
  	
  	buildTextContentElement: function(content,el,i){
  		$(el).children('.status').text(content.status);
		$(el).children('.status').addClass(content.status);
		$(el).find('.text_content .box_text_title').text(content.title);
		$(el).find('.text_content .box_text_content').html(content.description);
		$(el).find('.text_content .box_text_date').text(content.formattedTime);
		
		$(el).find('.tools a:eq(0)').attr('href', 'javascript:GuardianSpaceName.showSendVideo('+i+')');
		$(el).find('.tools a:eq(1)').hide();
		$(el).find('.delete a').attr('href', 'javascript:GuardianSpaceName.preDeleteTextContent('+i+')');
  	},
  	
  	clickReorderRight: function(event){
  		el = $(event.target).parent().parent();
  		next = $(event.target).parent().parent().next();
  		c = el.clone(true);
  		c.find('img').bind("mouseover",function(){
					$('.preview').css("z-index",-1); 
					c.find('.preview').css("z-index",100)}
		);
		c.find('.preview').bind("mouseout",function(){c.find('.preview').css("z-index",-1)});
			
  		el.remove();
  		$(next).after(c);
  		GuardianSpaceName.goReorder();
  	},
  	
	clickReorderLeft: function(event){
		el = $(event.target).parent().parent();
  		next = $(event.target).parent().parent().prev();
  		c = el.clone(true);
  		c.find('img').bind("mouseover",function(){
					$('.preview').css("z-index",-1); 
					c.find('.preview').css("z-index",100)}
		);
		c.find('.preview').bind("mouseout",function(){c.find('.preview').css("z-index",-1)});
		el.remove();
  		$(next).before(c);
  		GuardianSpaceName.goReorder();
  	},
	
  	goReorder: function(){
  		list = $("#sortable li");
		var order = [];
		for(var i=0;i<list.length;i++){
			imageId = $(list[i]).attr("imageId");
			order[i] = imageId;
			
			if(i==0){
			  $("#image_" + imageId).find('.order_tools .left').css("visibility","hidden");
			}else{
			  $("#image_" + imageId).find('.order_tools .left').css("visibility","");
			}
			
			if(i==(list.length-1)){
			  $("#image_" + imageId).find('.order_tools .right').css("visibility","hidden");
			}else{
			  $("#image_" + imageId).find('.order_tools .right').css("visibility","");
			}
		}
		jsonrpc.spaceService.changeOrderDataObject(GuardianSpaceName.space.spaceId,order);
  	},
  	
	showSendVideo: function(idx){	
		$(".clean-ok").fadeOut("slow");

	    var v = new Array();
	    v[0] = GuardianSpaceName.videos[idx];
 		GuardianAudience.showSendContents(v,GuardianSpaceName.space,GuardianSpaceName.selector);
	},
	
	showSendAll: function(idx){	
		GuardianAudience.showSendAll(GuardianSpaceName.videos, GuardianSpaceName.space, GuardianSpaceName.selector);
	},
	
	editTitleMouseEnter: function(){
		$('.spacename_title .meta_title').unbind("click",GuardianSpaceName.editTitleMouseEnter);
		var val = $('.spacename_title .meta_title').text();
		$('.spacename_title .meta_title').html('<input id="spacename_title_input" type="text"></input>');
		$('#spacename_title_input').val(val);
		$('#spacename_title_input').focus();
		//$('.spacename_title .meta_title').bind("click",GuardianSpaceName.editTitleMouseLeave);
		$('#spacename_title_input').bind("keyup",GuardianSpaceName.editTitleKeyUp);
		
		$('.spacename_title .btn_save').fadeIn('slow');
		$('.spacename_title .btn_save').bind("click",GuardianSpaceName.editTitleMouseLeave);
	},
	
	editTitleMouseLeave: function(){
		$('.spacename_title .meta_title').bind("click",GuardianSpaceName.editTitleMouseEnter);
		var val = $('#spacename_title_input').val();
		try{
			jsonrpc.spaceService.updateSpace(GuardianSpaceName.space.spaceId,val,'');
			$('.spacename_title .meta_title').text(val);
			
			$('.spacename_title .btn_save').fadeOut('slow');
		}catch(e){
			//alert(e);
		}		
	},
	
	editTitleKeyUp: function(e){
		if(e.keyCode == 13) {
			GuardianSpaceName.editTitleMouseLeave();
		}
	},
	
	previewVideo: function(index,button){
		 $(".clean-ok").fadeOut("slow");

		var el = $("#preview_video .content #video_box");
		
		el.css("height",GuardianSpaceName.preview_h + "px");
		el.css("width",(GuardianSpaceName.preview_w+60) + "px");
		
		var video = GuardianSpaceName.videos[index];		
		
		GuardianVideoPlayer.fillDivVideoPlayer($(el).attr('id'), video.title, video.description,video.videoName,video.imageName, video.duration, video.external,video.externalId,video.externalCdn,video.embedCode,GuardianSpaceName.preview_w,GuardianSpaceName.preview_h);
		
		GuardianUtil.showModalDialog("preview_video");
	},
	
	previewImage: function(index){
		 $(".clean-ok").fadeOut("slow");

		var el = $("#preview_video .content #video_box");
		var video = GuardianSpaceName.videos[index];		
		
		$("#video_box").html("<img height=" + video.properties.map.height + " width=" + video.properties.map.width + " src='" + video.mediaContext + "'></img>");
		
		GuardianSpaceName.videoDescription = null;
		GuardianSpaceName.lessDescriptionSize();
		
		GuardianUtil.showModalDialog("preview_video");
	},
	
	previewDocument: function(index){
		 $(".clean-ok").fadeOut("slow");

		var el = $("#preview_video .content #video_box");
		var video = GuardianSpaceName.videos[index];		
		
		el.css("width","460px");
		
		$("#video_box").html("<iframe height=510px width=425px style='border: 0 none;' src='http://www.slideshare.net/slideshow/embed_code/" + video.externalId + "'></iframe>");
				
		GuardianSpaceName.videoDescription = null;
		GuardianSpaceName.lessDescriptionSize();
		
		GuardianUtil.showModalDialog("preview_video");
	},
	
	preDeleteVideo: function(index){
	    $(".clean-ok").fadeOut("slow");
		GuardianUtil.confirmDialog(_messages.video_remove,"GuardianSpaceName.deleteObject('" + index + "');");
	},
	
	preDeleteImage: function(index){
	    $(".clean-ok").fadeOut("slow");
		GuardianUtil.confirmDialog(_messages.image_remove,"GuardianSpaceName.deleteObject('" + index + "');");
	},
	
	preDeleteDocument: function(index){
	    $(".clean-ok").fadeOut("slow");
		GuardianUtil.confirmDialog(_messages.document_remove,"GuardianSpaceName.deleteObject('" + index + "');");
	},
	
	preDeleteTextContent: function(index){
	    $(".clean-ok").fadeOut("slow");
		GuardianUtil.confirmDialog(_messages.news_remove,"GuardianSpaceName.deleteObject('" + index + "');");
	},
	
	deleteObject: function(index){
		GuardianUtil.showLoading();
		var video = GuardianSpaceName.videos[index];
		
		if(GuardianSpaceName.selector=="IMAGES"){
			jsonrpc.spaceService.removeImageFromSpace(GuardianSpaceName.deleteObjectCallback, GuardianSpaceName.space_id, video.id);
		}else if(GuardianSpaceName.selector=="DOCUMENTS"){
			jsonrpc.spaceService.removeDocumentFromSpace(GuardianSpaceName.deleteObjectCallback, GuardianSpaceName.space_id, video.id);
		}else if(GuardianSpaceName.selector=="TEXTCONTENTS"){
			jsonrpc.spaceService.removeTextContentFromSpace(GuardianSpaceName.deleteObjectCallback, GuardianSpaceName.space_id, video.id);
		}else{
			jsonrpc.spaceService.removeVideoFromSpace(GuardianSpaceName.deleteObjectCallback, GuardianSpaceName.space_id, video.id);
		}
	},
	
	deleteObjectCallback: function(result, e){
		if(e!=null){
			return;
		}	
		$(".clean-ok").html(_messages.remove_ok);
		$(".clean-ok").fadeIn("slow");
		GuardianSpaceName.getContentList();
	},
	
	fullDescriptionSize: function(){
		var cmd = " <a href='javascript:GuardianSpaceName.lessDescriptionSize();'>(less)<a>";
		$("#preview_video_description").text(GuardianSpaceName.videoDescription);
		$("#preview_video_description").append(cmd);	
	},
	
	lessDescriptionSize: function(){
		var d = GuardianSpaceName.videoDescription;
		if(d == null){
			$("#preview_video_description").hide();
			return;
		}
		
		$("#preview_video_description").show();
		var cmd="";
		if(d.length > GuardianSpaceName.MAX_DESCRIPTION){
			d = d.substring(0, GuardianSpaceName.MAX_DESCRIPTION);
			cmd = "... <a href='javascript:GuardianSpaceName.fullDescriptionSize();'>(more)<a>";
		}
		$("#preview_video_description").text(d);
		$("#preview_video_description").append(cmd);
		
	},
	
	initGalleryImage: function(list,pos){
		$("#imageGallery").remove();
		$("body").css("overflow","hidden");
		
		$("body").append("<div id='imageGalleryCmd'><ul id='lightbox-nav'><li class='first'><a class='lightbox-prev'><span></span>" + _messages.prev + "</a></li><li class='counter'><a class='lightbox-counter'></a></li><li><a class='lightbox-next'>" + _messages.next + "<span></span></a></li><li class='close'><a class='lightbox-close'>"+ _messages.close + "<span></span></a></li></ul></div>");
		
		$(".lightbox-prev").click(function(){$.fancybox.prev();});
		$(".lightbox-next").click(function(){$.fancybox.next();});
		$(".lightbox-close").click(function(){$.fancybox.close();});
		
		result = list;
		if(result == null)
			result = jsonrpc.spaceService.getImagesInSpace(GuardianSpaceName.space_id,"","ORDER_INDEX","",0,100);
		
		if(result != null && result.list.list != null && result.list.list.length > 0){
			list = result.list.list;
			html = "<div id='imageGallery' style='display:none'>";
			for(i=0;i<list.length;i++){
				html += "<a class='grouped' title='" + escape(list[i].title) + "'rel='group1' href='"+ list[i].mediaContext + "'><img src='" + list[i].mediaContext + "'></img></a>";
			}
			html += "</div>"
			
			$("body").append(html);
			
			$(".grouped").fancybox(
				{
				'cyclic':true,
				'centerOnScroll': true,
				//'titlePosition' : "inside",
				'transitionIn'	: 'elastic',
				'transitionOut'	: 'elastic',
				'overlayOpacity':0.9,
				'overlayColor' : '#444',
				'showCloseButton': false,
				'titleFormat'	: formatTitle,
				'onClosed': function() {
					$("#imageGalleryCmd").remove();
					$("#fancybox-bg-n").css("background","");
    				$("#fancybox-bg-n").css("height","0px");
    				$("#fancybox-bg-n").html("");
					$("body").css("overflow","auto");
				 },
				}
			);
			
			index = 0;
			if(pos != null)
				index = pos;
			$('.grouped:eq(' + index + ')').trigger('click.fb');
		}
	},
	
	showSendNewVideo: function(){
		$(".clean-ok").hide();
		$(".clean-error").hide();
		$("#messageText").val(_messages.newvideo);
		GuardianUtil.showModalDialog("message_content");
		$("#btn_message").click(GuardianSpaceName.sendNewVideo);
	},
	
	showSendNewImage: function(){
		$(".clean-ok").hide();
		$(".clean-error").hide();
		$("#messageText").val(_messages.newfoto);
		GuardianUtil.showModalDialog("message_content");
		$("#btn_message").click(GuardianSpaceName.sendNewImage);
	},
	
	showSendNewCoupon: function(){
		$(".clean-ok").hide();
		$(".clean-error").hide();
		$("#messageText").val(_messages.newcoupon);
		GuardianUtil.showModalDialog("message_content");
		$("#btn_message").click(GuardianSpaceName.sendNewCoupon);
	},

	sendNewVideo: function(){
		account = GuardianLogin.account;
		try{
			jsonrpc.contact.sendMessage("Richiesta Nuovo Video",$("#messageText").val());
		}catch(e){
			$("#message_content .clean-error").text("Errore: messaggio non inviato");
			$("#message_content .clean-error").show();
			return;
		}
		GuardianUtil.closeModalDialog();
		$(".clean-ok").text("La Troupe di Loveresto sarà lieta di preparare un nuovo Short direttamente presso il vostro domicilio");
		$(".clean-ok").show();
	},
	
	sendNewImage: function(){
		account = GuardianLogin.account;
		try{
			jsonrpc.contact.sendMessage("Richiesta Nuova Sessione Fotografica",$("#messageText").val());
		}catch(e){
			$("#message_content .clean-error").text("Errore: messaggio non inviato");
			$("#message_content .clean-error").show();
			return;
		}
		GuardianUtil.closeModalDialog();
		$(".clean-ok").text("La Troupe di Loveresto sarà lieta di preparare una sessione fotografica professionale direttamente presso il vostro domicilio");
		$(".clean-ok").show();
	},
	
	sendNewCoupon: function(){
		account = GuardianLogin.account;
		try{
			jsonrpc.contact.sendMessage("Richiesta Nuovo Coupon",$("#messageText").val());
		}catch(e){
			$("#message_content .clean-error").text("Errore: messaggio non inviato");
			$("#message_content .clean-error").show();
			return;
		}
		GuardianUtil.closeModalDialog();
		$(".clean-ok").text("La Troupe di Loveresto sarà lieta di preparare una immagine e comunicazione su misura per il vostro domicilio");
		$(".clean-ok").show();
	},
	
	
	showEmbedCode: function(){
		c = $("#embedSpace").css("display");
		if(c=="none"){
	   		//$(".backButtonContr:first").css("color","#fff");
	    	$("#embedSpace").show();
	    }else{
	   		//$(".backButtonContr:first").css("color","#B40000");
	    	$("#embedSpace").hide();
	    }
		
	}
	
};

function formatTitle(title, currentArray, currentIndex, currentOpts) {
    
    $("#fancybox-bg-n").css("background","none repeat scroll 0 0 #FFFFFF");
    $("#fancybox-bg-n").css("height","30px");
    $("#fancybox-bg-n").html("<b>" + unescape(title) + "</b>");
    $(".counter a").html(_messages.image + " " + (currentIndex + 1) + _messages.of + currentArray.length);

    /*return '<div id="tip7-title"><span><a href="javascript:;" onclick="$.fancybox.close();"><img src="/static_loveresto/Stylesheet/fancybox/closelabel.gif" /></a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + 'Immagine ' + (currentIndex + 1) + ' di ' + currentArray.length + '</div>';*/
}

var GuardianAudience = {

	audience:null,
	contents:null,
	space:null,
	type:null,
	reloadCbk:null,
	opened:false,
	finalCbk:null,
	
	init:function(contents,space,type,finalCbk){
			//$("#publish_share .content a").attr("href","javascript:GuardianSpaceName.sendAll();");
		$("#publish_share #toggle_btn input").change(GuardianAudience.toggleSelectAll);
		$(".content #post_facebook_box").show();
		$("#publish_share .close a").attr("href","javascript:GuardianAudience.skip();");
		$("#publish_share .clean-ok > a").attr("href","javascript:GuardianAudience.skip();");
		$("#publish_share .content h1 > a").attr("href","javascript:GuardianAudience.skip();");
		GuardianAudience.contents = contents;
		GuardianAudience.type = type;
		GuardianAudience.space = space;
		GuardianAudience.opened = true;
		GuardianAudience.finalCbk = finalCbk;
	},
	
	getAudience:function(videoId){
		var result = jsonrpc.audienceService.getAllAudienceContact();
		GuardianAudience.audience= result.list;
	},
	
	showSendAll: function(contents,space,type,finalCbk){
		this.init(contents,space,type,finalCbk);
		this.initSendAll();
	},
	
	initSendAll: function(){
		$(".clean-ok").hide();

		this.getAudience();
		$("#publish_share #send_friends").attr("href","javascript:GuardianAudience.sendAll();");
	    $("#import_audience_b > a").attr("href","javascript:GuardianAudience.showImportAudience('GuardianAudience.initSendAll();')");
	    $("#publish_share .clean-alert > a").attr("href","javascript:GuardianAudience.showImportAudience('GuardianAudience.initSendAll();')");
	    $("#publish_share #send_facebook").attr("href","javascript:GuardianAudience.showSendSpaceToFacebook()"); 
	    
	    $("#publish_share #import_audience_container").hide();
	    $("#publish_share #send_friends").hide();
	    $("#publish_share .clean-alert").hide();
	        
		//remove all the contacts from publish_share
		$("#publish_share .content .friends_list table").empty();
		
		//populate contacts, one row per contact
		var $table=$("#publish_share .content .friends_list table");
		
		for(var i=0; i< this.audience.length; i++){
		       var contact= this.audience[i];
			this.addContactRow($table, contact.id, contact.label);
		}
		
		if(this.audience.length > 0){
			$("#publish_share #import_audience_container").fadeIn("slow");
			 $("#publish_share #send_friends").fadeIn("slow");
		}else{
			$("#publish_share .clean-alert").fadeIn("slow");
		}
		
		GuardianTwitterConnector.initTweetButton(GuardianAudience.space.name,GuardianAudience.space.name);
		
		GuardianUtil.showModalDialog('publish_share',function(){});
	},
	
	sendAll: function(){
		var ids=[];
		
		var $checkboxes= $(".friends_list table").find("input:checked");
		
		for(var i=0; i<$checkboxes.length; i++){
		    ids[i]= $($checkboxes[i]).attr("class");
		}
		
		if(ids.length==0){
			 GuardianUtil.closeModalDialog();
			 if(this.finalCbk != null){
	  	    	this.finalCbk();
		     }
			 return;
		}
		jsonrpc.audienceService.sendSpace(GuardianAudience.sendContentCallback, this.space.spaceId, ids);
	},
	
	addContactRow: function($table, id, label){
		var $templateRow= $("#template_audience_row:eq(0)");
		
		$templateRow.find("td:eq(0)").text(label);
		
		var newRow= $templateRow.clone();
		newRow.find("td:eq(1) input").addClass(""+id);
		//newRow.show();
		
		$table.append(newRow);
	},
	
	toggleSelectAll: function(){
	     var value= $("#publish_share #toggle_btn").find("input").attr("checked");
	     $(".friends_list table").find("input").attr("checked",value);
	},
	
	showSendContents:function(contents,space,type,finalCbk){
		this.init(contents,space,type,finalCbk);
		this.initSendContent();
	},
	
	initSendContent: function(){
		$(".clean-ok").hide();
		
		this.getAudience();
	
	    $("#publish_share #send_friends").attr("href","javascript:GuardianAudience.sendContent();");
	    $("#import_audience_b > a").attr("href","javascript:GuardianAudience.showImportAudience('GuardianAudience.initSendContent();')");
        $("#publish_share .clean-alert > a").attr("href","javascript:GuardianAudience.showImportAudience('GuardianAudience.initSendContent();')");
	    $("#publish_share #send_facebook").attr("href","javascript:GuardianAudience.showSendVideosToFacebook()"); 
	    
	    $("#publish_share #import_audience_container").hide();
	    $("#publish_share #send_friends").hide();
	    $("#publish_share .clean-alert").hide();
	     
	     //remove all the contacts from publish_share
		$("#publish_share .content .friends_list table").empty();
		
		//populate contacts, one row per contact
		var $table=$("#publish_share .content .friends_list table");
		
		for(var index in this.audience){
			var contact= this.audience[index];
			this.addContactRow($table, contact.id, contact.label);
		}
		
		if(this.audience.length > 0){
			$("#publish_share #import_audience_container").fadeIn("slow");
			 $("#publish_share #send_friends").fadeIn("slow");
		}else{
			$("#publish_share .clean-alert").fadeIn("slow");
		}
		
		GuardianTwitterConnector.initTweetButton(GuardianAudience.space.name,GuardianAudience.contents[0].title);
		
		GuardianUtil.showModalDialog('publish_share',function(){});
	},
	
	sendContent: function(){
	     //collect selected ids in table #publish_share .content .friends_list
		
		var ids=[];
		
		var $checkboxes= $(".friends_list table").find("input:checked");
		
		for(var i=0; i<$checkboxes.length; i++){
		    ids[i]= $($checkboxes[i]).attr("class");
		}
		
		var contentIds=[];
		
		for(var i=0; i< this.contents.length; i++){
			contentIds[i]= this.contents[i].id;
		}
		
		if(ids.length==0 || contentIds.length==0){
			 GuardianUtil.closeModalDialog();
			 if(this.finalCbk != null){
	  	    	this.finalCbk();
		     }
			 return;
		}
		
		//objects[], contacts[], spaceId
		if(GuardianAudience.type == "VIDEOS"){
			jsonrpc.audienceService.sendVideo(GuardianAudience.sendContentCallback, contentIds, ids, this.space.spaceId);
		}
		if(GuardianAudience.type == "IMAGES"){
			jsonrpc.audienceService.sendImage(GuardianAudience.sendContentCallback, contentIds, ids, this.space.spaceId);
		}
		if(GuardianAudience.type == "DOCUMENTS"){
			jsonrpc.audienceService.sendDocument(GuardianAudience.sendContentCallback, contentIds, ids, this.space.spaceId);
		}
		if(GuardianAudience.type == "TEXTCONTENTS"){
			jsonrpc.audienceService.sendTextContent(GuardianAudience.sendContentCallback, contentIds, ids, this.space.spaceId);
		}
		
	},
	
	sendContentCallback: function(result, e){
	    if(e!=null){
	       //handle exception
	       return;
	    }
	    
	    GuardianUtil.closeModalDialog();
		$(".clean-ok").html("Il contenuto è stato condiviso, i tuoi amici riceveranno presto una email");
		$(".clean-ok").show();
		    
	    if(GuardianAudience.finalCbk != null){
	    	GuardianAudience.finalCbk();
	    }
	},
	
	showSendSpaceToFacebook: function(){
		GuardianFacebookConnector.postFeedVideos(this.space.name,this.space.spaceId,this.spaceImage, this.contents);
	},
	
	showSendVideosToFacebook: function(){
		GuardianFacebookConnector.postFeedVideos(this.space.name,this.space.spaceId,this.spaceImage, this.contents);
	},
	
	showImportAudience: function(cbk){
		GuardianUtil.closeModalDialog();
		$('#import_frame').attr("src", GuardianUtil.getCurrentPath() + "/contacts/index.jsp?type=AUDIENCE&locale=" + _messages.language);
		$('#import_frame').css({'width':'780px','height':'458px'});
		//$('#update_audience .close > a').attr("href","javascript:GuardianAudience.reloadImportAudience()");
		this.reloadCbk = cbk;
		GuardianAudience.opened = true;
		GuardianUtil.showModalDialog("update_audience",GuardianAudience.reloadImportAudience);
	},
	
	reloadImportAudience: function(){
		$('#import_frame').attr("src","");
		eval(GuardianAudience.reloadCbk);
	},
	
	closeFacebookPostLink:function(){
		$(".content #post_facebook_box").fadeOut();
	},
	
	skip:function(){
		//close "send all" box
		GuardianUtil.closeModalDialog();
		    
		if(this.finalCbk != null){
	  	  	this.finalCbk();
		}	
	}
};


var GuardianImportContent = {
	searchResult: null,
	currentVideo: null,
	total: null,
	page: 1,
	page_size: 8,
	query: null,
	importList:[],
	spaceid: -1,
	import_page_link: 'import.page?spaceid=',
	space_name_page_link: 'partnerManager.page',
	space: null,
	selector: "VIDEOS", //VIDEOS, IMAGES, DOCUMENTS
	
	init:function(){
	
		var args = GuardianUtil.getArgs();
		this.spaceid = args['spaceid'];
		this.selector = args['type'];
		
		var offset = (this.page -1)*this.page_size;		
		var args = GuardianUtil.getArgs();
		
		this.selector = args['type'];
		
		if(this.selector == "IMAGES")
			$(".tab_content_menu:eq(1)").addClass("activelink");
		else if(this.selector == "DOCUMENTS")
			$(".tab_content_menu:eq(2)").addClass("activelink");
		else if(this.selector == "TEXTCONTENTS")
			$(".tab_content_menu:eq(3)").addClass("activelink");
		else 
			document.location="partnerManager.page?spaceid=" + GuardianImportContent.spaceid +"&type=" + this.selector;
			
		$(".tab_content_menu:eq(0)").click(function(){document.location="partnerManager.page?type=VIDEOS"});
		$(".tab_content_menu:eq(1)").click(function(){document.location="import.page?spaceid=" + GuardianImportContent.spaceid +"&type=IMAGES"});
		$(".tab_content_menu:eq(2)").click(function(){document.location="import.page?spaceid=" + GuardianImportContent.spaceid +"&type=DOCUMENTS"});
		$(".tab_content_menu:eq(3)").click(function(){document.location="import.page?spaceid=" + GuardianImportContent.spaceid +"&type=TEXTCONTENTS"});
		$(".tab_content_menu:eq(4)").click(function(){document.location="partnerManager.page?type=COUPON"});
		
		var page = GuardianUtil.getCurrentPage();
        
        var loginpage = "login.page?callback=" + page;
		var joinpage = "join.page?callback=" + page;
			
		var str = '&';
		var args = GuardianUtil.getArgs();
		var nameArgs = GuardianUtil.getArgsNames();
		for(i=0; i<nameArgs.length; i++){		  	   
			if(nameArgs[i].toLowerCase()!='callback'){
				str = str+nameArgs[i]+'='+args[nameArgs[i]]+'&';
			}
		}			
		str = str.substring(0,str.length-1);
		loginpage = loginpage + str;
		joinpage = joinpage +str;
		
		$('#no_account a:eq(0)').attr('href',loginpage);
		$('#no_account a:eq(1)').attr('href',loginpage);
		$('#no_account a:eq(2)').attr('href',joinpage);
		
        if (this.spaceid ==  null || this.spaceid == -1) {
            $(".box_import").fadeOut("slow");
			$(".box_import_list").fadeOut("slow");            
			return;
        }
        
        if (GuardianLogin.account == null) {
			$("#no_account").fadeIn("slow");
			$(".box_import").fadeOut("slow");
			$(".box_import_list").fadeOut("slow");
			return;
        }
        
        $('#upload_btn').bind("click",
        	function(event){
        		document.location = "upload.page?spaceid=" + GuardianImportContent.spaceid + "&type=" + GuardianImportContent.selector;
        	}
        );
        
        this.space = jsonrpc.spaceService.getSpaceDetails(this.spaceid);
        GuardianSpaceName.initMenu(this.spaceid);
		
        if(this.space != null && this.space.owner.id == GuardianLogin.account.id){
$('#back_link_new > p > a:eq(0)').attr('href', GuardianImportContent.space_name_page_link + "?type=" + GuardianImportContent.selector);
			//$('#back_link > p > a:eq(0)').attr('href', GuardianImportContent.space_name_page_link + "?type=" + GuardianImportContent.selector);
			//$('#back_link > p > a:eq(0) > span').text(this.space.name);
			
			if(this.selector != "TEXTCONTENTS" && this.selector != "VIDEOS"){
				$(".box_import").fadeIn("slow");
				$(".box_import_list:first").fadeIn("slow");
        	}else if(this.selector == "TEXTCONTENTS"){
        		$("#textcontent_import").fadeIn("slow");
        	}else if(this.selector == "VIDEOS"){
        		$("#videocontent_import").fadeIn("slow");
        	}        	
  		}
  		
  		var query = args['query'];
  		
  		if(query != null){
  			$("#videosearch").val(query);	
  			this.doSearch();
  		}  	
  		
  		$('#publish_share').css("width","590px");	
		$('#update_audience').css("width","800px");	
		//$('#preview_video').css("width","500px");		
		
		$('.pagination span > select').change(GuardianImportContent.changePageSize);
		
		for(i=0;i<12;i++){
			$('.video_list').append($('.video_list .video_row:eq(0)').clone());
		}	
		
		$('.pagination span > select').selectOptions('8');
		
		$('#select_allresults').attr('href','javascript:GuardianImportContent.selectAllVideoResult();');
		$('#unselect_allresults').attr('href','javascript:GuardianImportContent.unselectAllVideoResult();');
		$("#addSelected").attr('href','javascript:GuardianImportContent.addSelectedVideoResults();');
		$("#deleteAll").attr('href','javascript:GuardianImportContent.deleteAllVideoFromImportList();');
  	},
  	
  	changePageSize: function(){
  		var sel = $('.pagination span > select').selectedValues();
  		GuardianImportContent.page_size = sel[0];
  		GuardianImportContent.call();
  	},
	
    doSearch: function(){
    	$('.box_import .clean-error').fadeOut("slow");
        var el = $("#videosearch");
        var query = el.val();
        if (query.length == 0) {
            //alert("Cosa stai cercando? Inserisci ");
            return;
        }
        
        $('.box_video_center').hide();
		$('.box_video_right').hide();
		$('.box_video_left').hide();
		$(".box_import .search_results").children().hide();
		
        GuardianImportContent.query = query;
        GuardianImportContent.page = 1;
        this.call();
    },
    
    call: function(){
    	$('.box_video_center').hide();
		$('.box_video_right').hide();
		$('.box_video_left').hide();
		
		GuardianImportContent.unselectAllVideoResult();

    	GuardianUtil.showLoading();
        var start_index = (GuardianImportContent.page - 1) * GuardianImportContent.page_size;
        
        if(GuardianImportContent.selector == "IMAGES"){
        	
        	//jsonrpc.externalPublisher.searchContents();
        	GuardianGImageSearcher.doSearch(GuardianImportContent.searchCbk, GuardianImportContent.query, GuardianImportContent.page, GuardianImportContent.page_size);
        	
        }else if(GuardianImportContent.selector == "DOCUMENTS"){
        	jsonrpc.externalPublisher.searchContents(GuardianImportContent.searchCbk, GuardianImportContent.query, start_index + 1, GuardianImportContent.page_size,'slideshare');
        }else{
        	jsonrpc.externalPublisher.searchVideos(GuardianImportContent.searchCbk, GuardianImportContent.query, start_index + 1, GuardianImportContent.page_size,'youtube');
        }
    },
    
    searchCbk: function(result, e){
        GuardianUtil.hideLoading();
        if (e != null) {
            return;
        }   
               
        if(result == null || result.total == 0){
        	$('.box_import .clean-error span').text(GuardianImportContent.query);
        	$('.box_import .clean-error').fadeIn("slow");
        	return;
        }
        
        $(".search_results .items").text(GuardianImportContent.query);
             
        GuardianImportContent.searchResult = result.list.list;
        GuardianImportContent.populateResults();
        GuardianImportContent.pagination(result.total);
        
        $(".box_import .search_results").children().fadeIn("slow");
        $(".box_import .search_results").fadeIn("slow");
    },
    
    populateResults: function(){
        var videos = GuardianImportContent.searchResult;
        var res_list = $(".box_import .search_results .video_list .video_row");
        		
		for (var i = 0; i < videos.length ; i++) {
			var el = $(res_list).children('div')[i];
			$(el).css("cursor","pointer");
			var img = $(el).find('img');
			$(img).bind('click',{'index':i},GuardianImportContent.clickVideoResult);
			var text = $(el).find('.text');
			$(text).bind('click',{'index':i},GuardianImportContent.clickVideoResult);
			img.attr("src",videos[i].thumbnailUrl);
			text.text(videos[i].title);
			var previewbtn = $(el).find(".tools").children('a')[0];
			
			if(this.selector == "IMAGES"){
				$(previewbtn).attr('href','javascript:GuardianImportContent.previewImage(' + i + ')');
			}else if(this.selector == "DOCUMENTS"){
			    $(previewbtn).attr('href','javascript:GuardianImportContent.previewDocument(' + i + ')');
			}else{
				$(previewbtn).attr('href','javascript:GuardianImportContent.previewVideo(' + i + ')');
			}
			
			var addbtn = $(el).find(".tools").children('a')[1];
			$(addbtn).attr('href','javascript:GuardianImportContent.addVideo(' + i + ')');
			
			$(el).children('img').bind("mouseover",function(){$(el).find('.preview').css("z-index",100)});
			$(el).find('.preview').bind("mouseout",function(){$(el).find('.preview').css("z-index",-1)});
			$(el).find('.preview').bind("click",function(){$(el).find('.preview').css("z-index",-1);GuardianSpaceName.previewImage(i)});
			$(el).find('.text .box_text_title').bind("click",function(){GuardianSpaceName.previewImage(i)});
			
			$(el).show();
        }   
    },
    
    selectedResults: new Array(),
    
    clickVideoResult: function(event){
    	var res_list = $(".box_import .search_results .video_list .video_row");
    	var el = $($(res_list).children('div')[event.data.index]);
    	if(el.hasClass("selected")){
    		el.removeClass("selected");
    		GuardianImportContent.selectedResults[event.data.index] = false;
    	}else{
    		el.addClass("selected");
    		GuardianImportContent.selectedResults[event.data.index] = true;
    	}
    	GuardianImportContent.checkSelectedResult();
    },   
    
    selectVideoResult: function(index){
    	var res_list = $(".box_import .search_results .video_list .video_row");
    	var el = $(res_list).children('div')[index];
    	$(el).addClass("selected");
    	GuardianImportContent.selectedResults[index] = true;	
    },   
    
   	unselectVideoResult: function(index){
    	var res_list = $(".box_import .search_results .video_list .video_row");
    	var el = $(res_list).children('div')[index];
    	$(el).removeClass("selected");
    	GuardianImportContent.selectedResults[index] = false;	
    },   
    
    selectAllVideoResult: function(){
    	var videos = GuardianImportContent.searchResult;
    	if(videos == null)
    		return;
    	for (var i=0; i < videos.length ; i++) {	
    		GuardianImportContent.selectVideoResult(i);
    	}
    	GuardianImportContent.checkSelectedResult();
    },
    
    unselectAllVideoResult: function(){
    	var videos = GuardianImportContent.searchResult;
    	if(videos == null)
    		return;
    	for (var i = 0; i < videos.length ; i++) {	
    		GuardianImportContent.unselectVideoResult(i);
    	}
    	GuardianImportContent.checkSelectedResult();
    },
    
    checkSelectedResult: function(){
    	var l = GuardianImportContent.selectedResults;
    	for(var i in GuardianImportContent.selectedResults){
    		if(l[i]){
    			$("#addSelected").fadeIn("slow");
    			return;
    		}
    	}    	
    	$("#addSelected").fadeOut("slow");
    },    
    
    addSelectedVideoResults: function(){
    	var l = GuardianImportContent.selectedResults;
    	for(var i in GuardianImportContent.selectedResults){
    		if(l[i]){
    			GuardianImportContent.addVideo(i);
    		}
    	}
    },
      
    pagination: function(total) { 
       var nPages = Math.ceil(total/this.page_size);
       var el = $($('.pagination')).find('.count_pages');
	   el.html("Pagina <b>" + this.page + "</b> di " + nPages);
	   
	   var prev = $($('.pagination')).find('.prev');
	   prev.attr("href","#");
	   if(this.page > 1)
	   		prev.attr("href","javascript:GuardianImportContent.changePage(" + (this.page - 1) + ")");
	   var more = $($('.pagination')).find('.more');
	   more.attr("href","#");
	   if(this.page != nPages)
		    more.attr("href","javascript:GuardianImportContent.changePage(" + (this.page + 1) + ")");
	},
	    
    changePage: function(page){
		this.page = page;
		this.call();
	},
	
	previewVideo: function(index){
		var video = GuardianImportContent.searchResult[index];
		var el = $("#preview_video .content #video_box");
		
		el.css("height",GuardianSpaceName.preview_h + "px");
		el.css("width",(GuardianSpaceName.preview_w+60) + "px");
		
		var addbtn = $("#preview_video .content .tools_video a:eq(0)");
		$(addbtn).attr('href','javascript:GuardianImportContent.addVideo(' + index + ')');
		
		GuardianVideoPlayer.fillDivVideoPlayer('video_box',video.title, video.description, video.videoName,video.imageName,video.duration,true,video.externalId,false,video.mediaLocation,GuardianSpaceName.preview_w,GuardianSpaceName.preview_h);  
		
		GuardianUtil.showModalDialog("preview_video");
	},
	
	previewImage: function(index){
		var image = GuardianImportContent.searchResult[index];
		var el = $("#preview_video .content #video_box");	
		
		var addbtn = $("#preview_video .content .tools_video a:eq(0)");
		$(addbtn).attr('href','javascript:GuardianImportContent.addVideo(' + index + ')');
		
		//$("#video_box").html("<img height=" + image.properties.map.height + " width=" + image.properties.map.width + " src='" + image.mediaLocation + "'></img>");
		
		$("#video_box").css("height","300px");
		$("#video_box").html("<img height='300px' src='" + image.mediaLocation + "'></img>");
		
		GuardianSpaceName.videoDescription = "";
		if(image.description != null)
			GuardianSpaceName.videoDescription = image.description;
		GuardianSpaceName.lessDescriptionSize();
		
		GuardianUtil.showModalDialog("preview_video");
	},
	
	previewDocument: function(index){
		var document = GuardianImportContent.searchResult[index];
		var el = $("#preview_video .content #video_box");	
		
		var addbtn = $("#preview_video .content .tools_video a:eq(0)");
		$(addbtn).attr('href','javascript:GuardianImportContent.addVideo(' + index + ')');
		
		$("#video_box").html("<iframe height=400px width=425px style='border: 0 none;' src='http://www.slideshare.net/slideshow/embed_code/" + document.externalId + "'></iframe>");
		
		GuardianSpaceName.videoDescription = "";
		if(document.description != null)
			GuardianSpaceName.videoDescription = document.description;
		GuardianSpaceName.lessDescriptionSize();
		
		GuardianUtil.showModalDialog("preview_video");
	},
	
	addVideo: function(index){
		var video = GuardianImportContent.searchResult[index];
		var index = $.sha1(video.externalId);
		
		if(this.importList[index] != null){
			return;
		}
				
		this.importList[index] = video;
		
		var el = $(".box_import_list .video_add .box_video");
		if(el.length>0)
			el = el[0];
		
		var el_c = $(el).clone();		
		var img = $(el_c).find('img');
		var text = $(el_c).find('.text');
		
		el_c.addClass(index);
		img.attr("src",video.thumbnailUrl);
		d = video.title;
		if(video.description != null)
			d += " - " + video.description;
		text.text(d);
		var del = $(el_c).find(".delete a");
		$(del).attr('href','javascript:GuardianImportContent.deleteVideoFromImportList("' + index + '")');
		$(".box_import_list .video_add").append(el_c);
		el_c.fadeIn("slow");
		$(".box_import_list").fadeIn("slow");
	},
	
	deleteVideo: function(index){
		var video = GuardianImportContent.searchResult[index];
		//var el = $(".box_import .search_results .video_list div:eq(" index + 1"));
		//alert("delete " + index);
	},
	
	deleteAllVideoFromImportList: function(index){
		var cl = $(".box_import_list .video_add .box_video:eq(0)").clone();
		var el = $(".box_import_list .video_add .box_video").remove();
		$(".box_import_list .video_add").append(cl);
		this.importList = new Array();
		$(".box_import_list:last").fadeOut("slow");
	},	
	
	deleteVideoFromImportList: function(index){
		this.importList[index] = null;
		var el = $(".box_import_list .video_add ." + index);
		$(el).remove();
		
		if($(".box_import_list .video_add").children('div').length <= 1){
			$(".box_import_list:last").fadeOut("slow");
		}
	},
	
    publishVideos: function(){
    	GuardianImportContent.unselectAllVideoResult();
    
    	GuardianUtil.showLoading();
    	var results = new Array();
    	var idx = 0;
    	for(var k in this.importList){
        	var video = this.importList[k];
        	if(video != null){
        		try {
        			results[idx] = new Object();
        			
        			if(GuardianImportContent.selector=="IMAGES"){
        				results[idx] = jsonrpc.externalPublisher.addUGImageToSpace(this.spaceid, video.mediaSource, video.title, video.description, video.mediaLocation, video.thumbnailUrl, video.contextUrl, video.externalId);
                    }else if(GuardianImportContent.selector == "DOCUMENTS"){
        				results[idx] = jsonrpc.externalPublisher.addUGDocumentToSpace(this.spaceid, video.mediaSource, video.title, video.description, video.mediaLocation, video.thumbnailUrl, video.format, video.externalId);
                    }else{
        				results[idx] = jsonrpc.v2externalPublisher.addUGVideoToSpace(this.spaceid, video.mediaSource, video.title, video.description, "", video.mediaLocation, video.thumbnailUrl, video.duration, video.externalId);
                	}
        			results[idx].imageName = video.thumbnailUrl;
        			var el = $(".box_import_list .video_add ." + k);
					$(el).remove();
					idx++;
        		}catch(error){
        			alert(_messages.add_fail + " " + video.title);
        		}
        	}
        	this.importList[k] = null;
        }        
        $(".box_import_list:last").fadeOut("slow");
        
        $(".clean-ok").html(_messages.add_ok);
        $(".clean-ok").show();
        
        GuardianUtil.hideLoading();
        //GuardianImportContent.showSendVideo(results);
    },
    
    publishTextContent: function(){
    	GuardianUtil.showLoading();
    	
    	var t = $("#title").val();
    	var c = $("#content").val();
    	
    	if(t == ""){
    		alert("Errore: titolo non può essere vuoto");
    		GuardianUtil.hideLoading();
    		return;
    	}
    	
    	jsonrpc.externalPublisher.addUGTextContentToSpace(this.spaceid,"",t,c,null,null,null);
    	GuardianImportContent.goToSpace();
    	GuardianUtil.hideLoading();
    },
    
    showSendVideo: function(videos){	
 		GuardianAudience.showSendContents(videos, GuardianImportContent.space, GuardianImportContent.goToSpace);
	},
	
	goToSpace:function(){
		document.location = "partnerManager.page?type=" + GuardianImportContent.selector;
	}        
};

var GuardianTwitterConnector={
		
		space_url: "partnerProfile?spaceId=",
		
		initTweetButton: function(spaceName,title){
			$("#tweetButton").html("");
			
			text = encodeURIComponent(title) + "...";
			url = encodeURIComponent(GuardianUtil.getCurrentPath() + "/profile/" + spaceName);
			
			hash = spaceName.replace(/[ \()]/g,"");
			
			button = '<iframe scrolling="no" frameborder="0" allowtransparency="true" style="height: 20px;" src="http://platform.twitter.com/widgets/tweet_button.html#_=1324330446435&_version=2&count=none&enableNewSizing=true&id=tweetButton&size=m' +
				'&type=hashtag&button_hashtag=' + hash +  
				'&url=' + url +
				'&text=' + text + '"></iframe>';
			
			$("#tweetButton").html(button);
		}	
};

var GuardianUploadVideo = {
	
	spaceid: null,
	import_page_link: 'import.page?spaceid=',
	space_name_page_link: 'partnerManager.page?spaceid=',
	selector: "VIDEOS", //VIDEOS, IMAGES, DOCUMENTS
	
	init: function(){
		var args = GuardianUtil.getArgs();
		this.spaceid = args['spaceid'];
		this.selector = args['type'];
		
		var page = GuardianUtil.getCurrentPage();
		
		if(this.selector == "IMAGES")
			$(".tab_content_menu:eq(1)").addClass("activelink");
		else if(this.selector == "DOCUMENTS")
			$(".tab_content_menu:eq(2)").addClass("activelink");
		else {
			document.location="import.page?spaceid=" + GuardianUploadVideo.spaceid +"&type=" + this.selector
		}
		
		$(".tab_content_menu:eq(0)").click(function(){document.location="partnerManager.page?type=VIDEOS"});
		$(".tab_content_menu:eq(1)").click(function(){document.location="upload.page?spaceid=" + GuardianUploadVideo.spaceid +"&type=IMAGES"});
		$(".tab_content_menu:eq(2)").click(function(){document.location="upload.page?spaceid=" + GuardianUploadVideo.spaceid +"&type=DOCUMENTS"});
		$(".tab_content_menu:eq(3)").click(function(){document.location="import.page?spaceid=" + GuardianUploadVideo.spaceid +"&type=TEXTCONTENTS"});
		$(".tab_content_menu:eq(4)").click(function(){document.location="partnerManager.page?type=COUPON"});
		
        var loginpage = "login.page?callback=" + page;
		var joinpage = "join.page?callback=" + page;
			
		var str = '&';
		var args = GuardianUtil.getArgs();
		var nameArgs = GuardianUtil.getArgsNames();
		for(i=0; i<nameArgs.length; i++){		  	   
			if(nameArgs[i].toLowerCase()!='callback'){
				str = str+nameArgs[i]+'='+args[nameArgs[i]]+'&';
			}
		}			
		str = str.substring(0,str.length-1);
		loginpage = loginpage + str;
		joinpage = joinpage +str;
		
		$('#no_account a:eq(0)').attr('href',loginpage);
		$('#no_account a:eq(1)').attr('href',loginpage);
		$('#no_account a:eq(2)').attr('href',joinpage);
		
        if (this.spaceid ==  null || this.spaceid == -1) {
            $(".box_upload").fadeOut("slow");
			$(".box_share_friends").fadeOut("slow");            
			return;
        }
        
        if (GuardianLogin.account == null) {
			$("#no_account").fadeIn("slow");
			$(".box_upload").fadeOut("slow");
			$(".box_share_friends").fadeOut("slow");
			return;
        }
        else{
            var space = jsonrpc.spaceService.getSpaceDetails(this.spaceid);
        	GuardianSpaceName.initMenu(this.spaceid);
		
        	if(space != null && space.owner.id == GuardianLogin.account.id){
        		
        		if(this.selector == "IMAGES"){
        			$(".box_upload > h1").text("Carica Immagini (JPG, JPEG, PNG, GIF, BMP) dal tuo Computer");
        			fileDesc = 'Immagini';
        			fileExt = '*.jpg;*.jpeg;*.jpe;*.jpf;*.tiff;*.tif;*.jfif;*.exif;*.png;*.gif;*.bmp;*.ico;*.raw;*.psb';
        		}
        		else if(this.selector == "DOCUMENTS"){
        			$(".box_upload > h1").text("Carica Documenti (PDF, DOC, PPT) dal tuo Computer");
        			fileDesc = 'Documenti';
        			fileExt = '*.pdf;*.ppt;*.pps;*.pptx;*.ppsx;*.pot;*.potx;*.odp;*.key;*.doc;*.docx;*.rtf;*.odt;*.ods;*.txt';
        		}
        		else{
        			$(".box_upload > h1").text("Carica Video (MP4, MPEG, MOV, 3GP) dal tuo Computer");
        			fileDesc = 'Video';
        			fileExt = '*.mpg;*.mpeg;*.divx;*.xvid;*.mp4;*.mpeg4;*.avi;*.3gp;*.3gp2;*.dvx;*.m2v;*.m4v;*.mjp;*.mkv;*.mov;*.qt;*.rts;*.swf';
        		}
        		
        		
				$('#back_link > p > a:eq(1)').attr('href', GuardianUploadVideo.import_page_link+space.spaceId + "&type=" + GuardianUploadVideo.selector);
				$('#back_link > p > a:eq(0)').attr('href', GuardianUploadVideo.space_name_page_link+space.spaceId + "&type=" + GuardianUploadVideo.selector);
				//$('#back_link > p > a:eq(1) > span').text(space.name);
			
            	$('.box_upload').fadeIn("slow");
            	//$('.box_metatags_video').fadeIn("slow");
            	//<a class="btn" style="margin: 0;float: left;" href="javascript:GuardianUploadVideo.fileUploadStart();"><div style="margin-left: 0px;">Carica</div></a>
		
				var msize = GuardianUtil.resolveSize(GuardianConf.MAX_FILE_SIZE);
				
		
				$('#browse_files').fileUpload ({
					'uploader'  : '../swf/upload/uploader.swf',
					'script'    : 'UploadContent',
					'auto'      : false,
					'multi': true,
					'wmode': 'transparent',
					'fileDesc': fileDesc,
					'fileExt': fileExt,
					'sizeLimit': msize,
					'onComplete': GuardianUploadVideo.fileUploadComplete,
					'titleField': '#username',
					'descriptionField': '#description',
					'tagsField': '#tags',
					'boxMetadata': 'box_metatags_video'
				});
  			}
        }
	},
	
	
	checkField: function() {
		if(this.uplooad.fileList.length <= 0){
			alert("Please, add a File");
			return;
		}

		if(this.uplooad.index_selected == -1){
			alert("Please, select File");
			return;
		}
	},

	validateFields: function() {
		var b = jsonrpc.auth.isSessionValid();
		if(!b){
			alert("User must be logged-in");
			return false;
		}
		var listM = this.uplooad.fileMetadataList;
		var list = this.uplooad.fileList;
		for(var i = 0; i<list.length;i++){
			if(listM[i].title==""){
				alert("Error: title for file " + list[i].name + " is empty");
				return false;
			}
		}	
		return true;
	},
		
	fileUploadStart: function(){
		//read session cookie
		var sid = GuardianUtil.readCookie('sid');
		$("#browse_files").fileUploadSettings("scriptData", "&sessid=" + sid + "&spaceid=" + GuardianUploadVideo.spaceid + "&type=" + GuardianUploadVideo.selector);	
		$("#browse_files").fileUploadStart();
	},
	
	fileUploadComplete: function(event, queueID, fileObj, response, data){
		//alert("Finito " + GuardianUploadVideo.selector);
		var metadata = new Object();
	    if(GuardianUploadVideo.metadataFiles==null || GuardianUploadVideo.metadataFiles[queueID] == null){
	     	metadata.title = fileObj.name;
	     	metadata.description = "";
	     	metadata.tags = "";	     	
	    }else{
	    	metadata = GuardianUploadVideo.metadataFiles[queueID];
	    } 
		
		$(".clean-ok").html(_messages.upload_ok);
        $(".clean-ok").show();
		
		//$('#browse_files').fileUploadClearQueue();
		
	    if(GuardianUploadVideo.selector == "IMAGES"){
	    	jsonrpc.imageManager.updateImage(response, metadata.title, metadata.description, metadata.tags);	
	    }else if(GuardianUploadVideo.selector == "DOCUMENTS"){
	     	jsonrpc.documentManager.updateImage(response, metadata.title, metadata.description, metadata.tags);	
	 	}else{
	 	 	jsonrpc.videoManager.updateVideo(response, metadata.title, metadata.description, metadata.tags);	
	    }
	   	
	},
	
	saveAndLoad: function(){
		GuardianUtil.closeModalDialog();
	},
	
	metadataFiles:new Array()
};


/*
Uploadify v1.6.2
Copyright ¬© 2009 by Ronnie Garcia
Co-developed by Travis Nickels

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
//**UPDATED: ADRIANO TAMBURO**///


var flashVer = -1;
if (navigator.plugins != null && navigator.plugins.length > 0) {
	if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
		var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
		var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
		var descArray = flashDescription.split(" ");
		var tempArrayMajor = descArray[2].split(".");			
		var versionMajor = tempArrayMajor[0];
		var versionMinor = tempArrayMajor[1];
		var versionRevision = descArray[3];
		if (versionRevision == "") {
			versionRevision = descArray[4];
		}
		if (versionRevision[0] == "d") {
			versionRevision = versionRevision.substring(1);
		} else if (versionRevision[0] == "r") {
			ersionRevision = versionRevision.substring(1);
			if (versionRevision.indexOf("d") > 0) {
				versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
			}
		}
		var flashVer = versionMajor + "." + versionMinor	 + "." + versionRevision;
	}
} else if ( $.browser.msie ) {
	var version;
	var axo;
	var e;
	try {
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
		flashVer = version.replace("WIN ","").replace(",",".");
	} catch (e) {
	}	
}

try {
	flashVer = flashVer.split(".")[0];
} catch (e) {
}

if(jQuery)(
	function($){
		$.extend($.fn,{
			fileUpload:function(options) {
				if (flashVer >= 9) {
					$(this).each(function(){
						settings = $.extend({
						uploader:      'uploader.swf',
						script:        'uploader.php',
						folder:        '',
						height:        30,
						width:         110,
						canceling:     'cancel.png',
						wmode:         'opaque',
						scriptAccess:  'sameDomain',
						fileDataName:  'Filedata',
						displayData:   'percentage',
						titleField:   '',
						descriptionField:  '',
						tagsField:   '',
						boxMetadata: '',
						onInit:        function() {},
						onSelect:      function() {},
						onCheck:       function() {},
						onCancel:      function() {},
						onError:       function() {},
						onProgress:    function() {},
						onComplete:    function() {}
					}, options);
					
					this.titleField = settings.titleField;
					this.descriptionField=settings.descriptionField;
					this.tagsField=settings.tagsField;
					this.boxMetadata=settings.boxMetadata;
					
					var pagePath = location.pathname;
					pagePath = pagePath.split('/');
					pagePath.pop();
					pagePath = pagePath.join('/') + '/';
					var data = '&pagepath=' + pagePath;
					if (settings .buttonImg) data += '&buttonImg=' + escape(settings .buttonImg);
					if (settings.buttonText) data += '&buttonText=' + escape(settings.buttonText);
					if (settings.rollover) data += '&rollover=true';
					data += '&script=' + settings.script;
					data += '&folder=' + escape(settings.folder);
					if (settings.scriptData) {
						var scriptDataString = '';
						for (var name in settings.scriptData) {
							scriptDataString += '&' + name + '=' + settings.scriptData[name];
						}
						data += '&scriptData=' + escape(scriptDataString); 
					}
					data += '&btnWidth=' + settings.width;
					data += '&btnHeight=' + settings.height;
					data += '&wmode=' + settings.wmode;
					if (settings.hideButton) data += '&hideButton=true';
					if (settings.fileDesc) data += '&fileDesc=' + settings.fileDesc + '&fileExt=' + settings.fileExt;
					if (settings.multi) data += '&multi=true';
					if (settings.auto) data += '&auto=true';
					if (settings.sizeLimit) data += '&sizeLimit=' + settings.sizeLimit;
					if (settings.simUploadLimit) data += '&simUploadLimit=' + settings.simUploadLimit;
					if (settings.checkScript) data += '&checkScript=' + settings.checkScript;
					if (settings.fileDataName) data += '&fileDataName=' + settings.fileDataName;
					if ($.browser.msie) {
						flashElement = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + settings.width + '" height="' + settings.height + '" id="' + $(this).attr("id")  + 'Uploader" class="fileUploaderBtn">\
						<param name="movie" value="' + settings.uploader + '?fileUploadID=' + $(this).attr("id") + data + '" />\
						<param name="quality" value="high" />\
						<param name="wmode" value="' + settings.wmode + '" />\
						<param name="allowScriptAccess" value="' + settings.scriptAccess + '">\
						<param name="swfversion" value="9.0.0.0" />\
						</object>';
					} else {
						flashElement = '<embed src="' + settings.uploader + '?fileUploadID=' + $(this).attr("id") + data + '" quality="high" width="' + settings.width + '" height="' + settings.height + '" id="' + $(this).attr("id") + 'Uploader" class="fileUploaderBtn" name="' + $(this).attr("id") + 'Uploader" allowScriptAccess="' + settings.scriptAccess + '" wmode="' + settings.wmode + '" type="application/x-shockwave-flash" />';
					}
					if (settings.onInit() !== false) {
						$(this).css('display','none');
						if ($.browser.msie) {
							$(this).after('<div id="' + $(this).attr("id")  + 'Uploader"></div>');
							document.getElementById($(this).attr("id")  + 'Uploader').outerHTML = flashElement;
						} else {
							$(this).after(flashElement);
						}
						$("#" + $(this).attr('id') + "Uploader").after('<div id="' + $(this).attr('id') + 'Queue" class="fileUploadQueue"></div>');
					}
					$(this).bind("rfuSelect", {'action': settings.onSelect}, function(event, queueID, fileObj) {
						if (event.data.action(event, queueID, fileObj) !== false) {
							var byteSize = Math.round(fileObj.size / 1024 * 100) * .01;
							var suffix = 'KB';
							if (byteSize > 1000) {
								byteSize = Math.round(byteSize *.001 * 100) * .01;
								suffix = 'MB';
							}
							var sizeParts = byteSize.toString().split('.');
							if (sizeParts.length > 1) {
								byteSize = sizeParts[0] + '.' + sizeParts[1].substr(0,2);
							} else {
								byteSize = sizeParts[0];
							}
							if (fileObj.name.length > 20) {
								fileName = fileObj.name.substr(0,20) + '‚Ä¶';
							} else {
								fileName = fileObj.name;
							}
							
							/*<div id="' + $(this).attr('id') + queueID + 'edit" class="edit">Proprietà</div>\ */
									
							var html = '\
							      <div id="' + $(this).attr('id') + queueID + '" class="fileUploadQueueItem">\
									<div id="' + $(this).attr('id') + queueID + 'cancel" class="cancel"></div>\
									<span class="fileName">' + fileName + ' (' + byteSize + suffix + ')\
									</span>\
									<span class="percentage">&nbsp;\
								    </span>\
									<div class="fileUploadProgress" style="width: 100%;">\
										<div id="' + $(this).attr('id') + queueID + 'ProgressBar" class="fileUploadProgressBar" style="width: 1px; height: 3px;"></div>\
									</div>\
								  </div>';
								  
							$('#' + $(this).attr('id') + 'Queue').append(html);
							var parId = '#' + $(this).attr('id');
							
							var cancel_id = '#' + $(this).attr('id') + queueID + "cancel";
							$(cancel_id).css("cursor","pointer");
							$(cancel_id).bind('click',
										{parentId:parId, queueID:queueID},		
										function(event){
											var data = event.data;
											$(data.parentId).fileUploadCancel(data.queueID);
											return false;
										} 
							);
							
							/*var el_id = '#' + $(this).attr('id') + queueID;
							$(el_id).css("cursor","pointer");
							$(el_id).bind('click',
										{parentId:parId, queueID:queueID, fileName:fileName},		
										function(event){
											var data = event.data;
											$(data.parentId).fileSelectName(data.queueID,data.fileName);
										} 
							);*/
							
							$('#' + $(this).attr('id')).fileSelectName(queueID,fileName);
						}
					});
					if (typeof(settings.onSelectOnce) == 'function') {
						$(this).bind("rfuSelectOnce", settings.onSelectOnce);
					}
					$(this).bind("rfuCheckExist", {'action': settings.onCheck}, function(event, checkScript, fileQueue, folder, single) {
						var postData = new Object();
						postData.folder = pagePath + folder;
						for (var queueID in fileQueue) {
							postData[queueID] = fileQueue[queueID];
							if (single) {
								var singleFileID = queueID;
							}
						}
						$.post(checkScript, postData, function(data) {
							for(var key in data) {
								if (event.data.action(event, checkScript, fileQueue, folder, single) !== false) {
									var replaceFile = confirm('Do you want to replace the file \'' + data[key] + '\'?');
									if (!replaceFile) {
										document.getElementById($(event.target).attr('id') + 'Uploader').cancelFileUpload(key);
									}
								}
							}
							if (single) {
								document.getElementById($(event.target).attr('id') + 'Uploader').startFileUpload(singleFileID, true);
							} else {
								document.getElementById($(event.target).attr('id') + 'Uploader').startFileUpload(null, true);
							}
						}, "json");
					});
					$(this).bind("rfuCancel", {'action': settings.onCancel}, function(event, queueID, fileObj, data) {
						if (event.data.action(event, queueID, fileObj, data) !== false) {
							$("#" + $(this).attr('id') + queueID).fadeOut(250, function() { $("#" + $(this).attr('id') + queueID).remove()});
						}
					});
					$(this).bind("rfuClearQueue", {'action': settings.onClearQueue}, function() {
						if (event.data.action() !== false) {
							$('#' + $(this).attr('id') + 'Queue').contents().fadeOut(250, function() {$('#' + $(this).attr('id') + 'Queue').empty()});
						}
					});
					$(this).bind("rfuError", {'action': settings.onError}, function(event, queueID, fileObj, errorObj) {
						if (event.data.action(event, queueID, fileObj, errorObj) !== false) {
							var msg = "Upload failed (" + errorObj.type + ")";
							switch(errorObj.status) {
								case '500': msg = "Internal server error: 500!"; break;
								case '404': msg = "Internal server error: 404!"; break;
								case '413': msg = "Upload failed, please check your file size!"; break;
								case '401': msg = "Authentication required!"; break;
								case '400': msg = "Error while upload video!"; break;
								case '412': msg = "Title is missing for the video!"; break;
								case '502': msg = "Channel not found!"; break;
							}
							
							if(errorObj.status || errorObj.type == 'File Size'){
								$("#" + $(this).attr('id') + queueID + " .fileName").text(msg);
								$("#" + $(this).attr('id') + queueID + " .percentage").text(' - Error');
								$("#" + $(this).attr('id') + queueID).css({'border': '3px solid #FBCBBC', 'background-color': '#FDE5DD'});
							}
						}
					});
					$(this).bind("rfuProgress", {'action': settings.onProgress, 'toDisplay': settings.displayData}, function(event, queueID, fileObj, data) {
						if (event.data.action(event, queueID, fileObj, data) !== false) {
							$("#" + $(this).attr('id') + queueID + "ProgressBar").css('width', data.percentage + '%');
							if (event.data.toDisplay == 'percentage') displayData = ' - ' + data.percentage + '%';
							if (event.data.toDisplay == 'speed') displayData = ' - ' + data.speed + 'KB/s';
							if (event.data.toDisplay == null) displayData = ' ';
							$("#" + $(this).attr('id') + queueID + " .percentage").text(displayData);
						}
					});
					$(this).bind("rfuComplete", {'action': settings.onComplete}, function(event, queueID, fileObj, response, data) {
						if (event.data.action(event, queueID, fileObj, unescape(response), data) !== false) {
							//$("#" + $(this).attr('id') + queueID).fadeOut(250, function() { $("#" + $(this).attr('id') + queueID).remove()});
							$("#" + $(this).attr('id') + queueID + " .percentage").text(' - Completed');
							$("#" + $(this).attr('id') + queueID).css({'border': '3px solid #00CC66', 'background-color': '#33FF99'});
						}
					});
					if (typeof(settings.onAllComplete) == 'function') {
						$(this).bind("rfuAllComplete", settings.onAllComplete);
					}
				});
			}
		},
		fileUploadSettings:function(settingName, settingValue) {
			$(this).each(function() {
				document.getElementById($(this).attr('id') + 'Uploader').updateSettings(settingName,settingValue);
			});
		},
		fileUploadStart:function(queueID) {
			this.saveCurrentMetadata();
			$(this).each(function() {
				document.getElementById($(this).attr('id') + 'Uploader').startFileUpload(queueID, false);
			});			
		},
		fileUploadCancel:function(queueID) {
			$(this).each(function() {
				$("#" + $(this).attr('id') + queueID).fadeOut(250, function() { $("#" + $(this).attr('id') + queueID).remove()});
				document.getElementById($(this).attr('id') + 'Uploader').cancelFileUpload(queueID);
			});
			this.fileDeleteMetadata(queueID);
		},
		fileUploadClearQueue:function() {
			$(this).each(function() {
				$('#' + $(this).attr('id') + 'Queue').children().fadeOut(250, function() {$('#' + $(this).attr('id') + 'Queue').empty()});
				document.getElementById($(this).attr('id') + 'Uploader').clearFileUploadQueue();
				$(this.boxMetadata).hide();
			});
			this.clearFileMetadata();
		},
		
		fileSelectName:function(queueID,filename) {
			$(this).each(function() {
				$(this.boxMetadata).hide();
				if(GuardianUploadVideo.metadataFiles == null)
					GuardianUploadVideo.metadataFiles = new Array();

				var mf = GuardianUploadVideo.metadataFiles;
				
				if(mf[queueID] == null){
						mf[queueID] = new Object();
						mf[queueID].title = filename;
						mf[queueID].description = "";
						mf[queueID].tags = "";
				}
					
				if(this.selectedFile != null){
					mf[this.selectedFile] = new Object();
					mf[this.selectedFile].title = $(this.titleField).val();
					mf[this.selectedFile].description = $(this.descriptionField).val();
					mf[this.selectedFile].tags =  $(this.tagsField).val();
					$("#browse_files" + this.selectedFile).css({'border': '1px solid #cccccc', 'background-color': ''});
				}
								
				$("#browse_files" + queueID).css({'border': '3px solid #008000', 'background-color': '#C9FFCA'});
				this.selectedFile = queueID;
				
				$(this.titleField).val(mf[queueID].title);
				$(this.descriptionField).val(mf[queueID].description);
				$(this.tagsField).val(mf[queueID].tags);
				
				//$(this.boxMetadata).css({'border': '1px solid #008000','background-color':'#ffffff'});
				//$(this.boxMetadata).fadeIn(100);
				//$(this.boxMetadata).animate({"backgroundColor":"#C9FFCA"},1000);
				//alert(this.boxMetadata);
				GuardianUtil.showModalDialog2(this.boxMetadata,checkMetadataTitle);
			});
		},
		
		
		
		saveCurrentMetadata:function() {
			$(this).each(function() {
				if(this.selectedFile != null){
					var mf = GuardianUploadVideo.metadataFiles;
					mf[this.selectedFile] = new Object();
					mf[this.selectedFile].title = $(this.titleField).val();
					mf[this.selectedFile].description = $(this.descriptionField).val();
					mf[this.selectedFile].tags =  $(this.tagsField).val();
				}			
			});
		},
		
		fileDeleteMetadata:function(queueID){
			$(this).each(function() {
				if(this.selectedFile == queueID){
					$(this.titleField).val("");
					$(this.descriptionField).val("");
					$(this.tagsField).val("");
					this.selectedFile = null;
					$(this.boxMetadata).css({'border': '', 'background-color': ''});
					$(this.boxMetadata).fadeOut();
					GuardianUploadVideo.metadataFiles[this.selectedFile] = new Object();
				}
			});
		},
		
		clearFileMetadata:function(){
			$(this).each(function() {
				$(this.titleField).val("");
				$(this.descriptionField).val("");
				$(this.tagsField).val("");
				this.selectedFile = null;
				GuardianUploadVideo.metadataFiles = new Array();
				$(this.boxMetadata).css({'border': '','background-color': ''});
			});
		},
		
		selectedFile: null,
		titleField:   '',
		descriptionField:  '',
		tagsField:   '',
		boxMetadata:   ''
		
	})
})(jQuery);


function checkMetadataTitle(){
	if($("#username").val()==''){
		$("#username").css("border","2px solid #ff0000");
		$("#box_metatags_video .clean-error").html(_messages.title_notempty);
		$("#box_metatags_video .clean-error").show();
		return false;
	}
	$("#username").css("border","");
	$("#box_metatags_video .clean-error").hide();
	
	
	GuardianUploadVideo.fileUploadStart();

	//alert("Upload");
	
	return true;	
};


var GuardianSpaceCoupon = {

	spaceId: null,
	couponStyle:{},
	couponOldStyle:{},
	
	init:function(){
		$('#couponManagerFrame > iframe').attr("src","spaceCouponFrame.page?spaceid=" + GuardianSpaceCoupon.spaceId);
	},

	initUploadFrame: function(){
		$("body").css("min-width","980px");
		$("body").css("margin","0px");
		$("body").css("background","none");
		
		$('.spacename_title .meta_title').text(_messages.yourchannel + parent.GuardianSpaceName.space.name);
		
		var args = GuardianUtil.getArgs();

		$("#couponManager .create").click(GuardianSpaceCoupon.updateCoupon);
		$("#couponManager .cancel").click(GuardianSpaceCoupon.cancelCoupon);
		
		$('#couponImage').bind("change",GuardianSpaceCoupon.handleFileSelect);
		
		$(".couponPalette:eq(0)").click({field:'root'},GuardianSpaceCoupon.styleManager);
		$(".couponPalette:eq(1)").click({field:'couponText'},GuardianSpaceCoupon.styleManager);
		$(".couponPalette:eq(2)").click({field:'couponPreviewType'},GuardianSpaceCoupon.styleManager);
		$(".couponPalette:eq(3)").click({field:'couponDateStart'},GuardianSpaceCoupon.styleManager);
		$(".couponPalette:eq(4)").click({field:'couponDateEnd'},GuardianSpaceCoupon.styleManager);
		
		//$("#couponImage").focusin({field:'root'},GuardianSpaceCoupon.styleManager);
		$("#description").focusin({field:'couponText'},GuardianSpaceCoupon.styleManager);
		$("#couponValue").focusin({field:'couponPreviewType'},GuardianSpaceCoupon.styleManager);
		$("#startDateWidget").focusin({field:'couponDateStart'},GuardianSpaceCoupon.styleManager);
		$("#endDateWidget").focusin({field:'couponDateEnd'},GuardianSpaceCoupon.styleManager);
		
		$("#font_color").bind("focusout",function(){GuardianSpaceCoupon.updateStyleManager(GuardianSpaceCoupon.currentField);hideColorPicker();});
		$("#back_color").bind("focusout",function(){GuardianSpaceCoupon.updateStyleManager(GuardianSpaceCoupon.currentField);hideColorPicker();});
		
		$("#reset_back").bind("click",function(){
			$("#back_color").val(""); 
			$("#back_color").css("background",""); 
			$("#back_color").trigger("change");
			return false;
		});
		
		$("#reset_color").bind("click",function(){
			$("#font_color").val(""); 
			$("#font_color").css("background",""); 
			$("#font_color").trigger("change");
			return false;
		});
		
		$("#styleBox .minus").click(GuardianSpaceCoupon.minusMouseDown);
		$("#styleBox .plus").click(GuardianSpaceCoupon.plusMouseDown);
		$("#styleBox .up").click({index:-5},GuardianSpaceCoupon.positionMouseDown);
		$("#styleBox .down").click({index:5},GuardianSpaceCoupon.positionMouseDown);
		$("#styleBox .left").click({index:-5},GuardianSpaceCoupon.positionMouseDown);
		$("#styleBox .right").click({index:5},GuardianSpaceCoupon.positionMouseDown);
		
		$("#couponManager input").bind("keyup",function(){GuardianSpaceCoupon.updateStyleManager(GuardianSpaceCoupon.currentField)});
		$("#styleBox input").bind("keyup",function(){GuardianSpaceCoupon.updateStyleManager(GuardianSpaceCoupon.currentField)});
		$("#styleBox input").bind("change",function(){GuardianSpaceCoupon.updateStyleManager(GuardianSpaceCoupon.currentField)});
				
		$(".buttonManager:first").click(function(){GuardianSpaceCoupon.closeStyleManager(GuardianSpaceCoupon.currentField)});
		$(".buttonManager:last").click(function(){GuardianSpaceCoupon.resetField(GuardianSpaceCoupon.currentField)});
		
		//$(".closeManager:last").click(function(){GuardianSpaceCoupon.closeStyleManager(GuardianSpaceCoupon.currentField)});
		
		//$("#couponType").change(GuardianSpaceCoupon.changeCouponType);
		
		/*$("#startDateWidget").datepicker({
			onSelect: function(dateText, inst) {
				var d = $.datepicker.parseDate('dd/mm/yy',dateText);
				//d = new Date(dateText);
				$("#startDate").val(d.getTime());
			}
		});
		
		$("#endDateWidget").datepicker({
			onSelect: function(dateText, inst) {
				var d = $.datepicker.parseDate('dd/mm/yy',dateText);
				//d = new Date(dateText);
				$("#endDate").val(d.getTime());
			}
		});*/
		
		GuardianSpaceCoupon.spaceId = args["spaceid"];
		$("#spaceId").val(GuardianSpaceCoupon.spaceId);
		if(GuardianSpaceCoupon.spaceId != null){
			var c = null;
			var c = jsonrpc.couponManager.getCouponBySpaceId(GuardianSpaceCoupon.spaceId);
			if(c != null){
				$("#no_coupon").hide();
				
				$("#couponId").val(c.id);
				$("#description").val(c.description);
				$("#couponType").val(c.type);
				GuardianSpaceCoupon.changeCouponType();
				$("#couponValue").val(c.value);
				
				/*$("#startDateWidget").val("");
				$.datepicker.setDefaults({dateFormat:"dd/mm/yy"});
				
				if(c.startDate != null){
					sd = new Date(c.startDate)
					//$("#startDateWidget").datepicker("option","dateFormat","dd-mm-yy");
					$("#startDateWidget").datepicker("setDate",sd);
					$("#startDate").val(sd.getTime());
				}
				
				$("#endDateWidget").val("");
				if(c.endDate != null){
					ed = new Date(c.endDate)
					//$("#endDateWidget").datepicker("option","dateFormat","dd-mm-yy");
					$("#endDateWidget").datepicker("setDate" , ed);
					$("#endDate").val(ed.getTime());
				}*/
				
				//$(".couponPreview").html("<img style='width: 300px;' src='/static_loveresto/coupon/" + c.image  + "'></img>");
				eval("GuardianSpaceCoupon.couponStyle=" + c.style);
				if(GuardianSpaceCoupon.couponStyle == null || GuardianSpaceCoupon.couponStyle.root == null){
					GuardianSpaceCoupon.couponStyle = {root:{}};
					GuardianSpaceCoupon.couponStyle.root.visibility = "visible"; 
				}
				
				/*$("#startDate").val(sd.getTime());
				$("#endDate").val(ed.getTime());
				*/
				$("#startDateWidget").val(GuardianSpaceCoupon.couponStyle.startDate);
				$("#endDateWidget").val(GuardianSpaceCoupon.couponStyle.endDate);
				
				GuardianSpaceCoupon.couponStyle.root.image = "url(/static_loveresto/coupon/" + c.image + ")"; 	
				
				jQuery.extend(true,GuardianSpaceCoupon.couponOldStyle,GuardianSpaceCoupon.couponStyle);
				
				GuardianSpaceCoupon.previewCoupon(GuardianSpaceCoupon.couponStyle);
				
			}else{
				$("#description").val($('#couponText').text());
				$("#couponValue").val($('#couponPreviewType').text());
				$("#startDateWidget").val($('#couponDateStart').text());
				$("#endDateWidget").val($('#couponDateEnd').text());
			
				GuardianSpaceCoupon.couponStyle = {root:{}};
				GuardianSpaceCoupon.previewCoupon();
				$("#couponId").remove();
			}
		}
	},
	
	changeCouponType: function(){
		if($("#couponType").val() == "fixed"){
			//$("#couponValue").parent().show();
		}else{
			//$("#couponValue").parent().hide();
		}
	},
		
	cancelCoupon:function(){
		//alert("Clear");
		id = $("#couponId").val();
		if(id != null){
			jsonrpc.couponManager.removeCoupon(id);
		}
		document.location.reload();
		window.parent.GuardianSpaceCoupon.okMessage(_messages.coupon_removed);
	},

	updateCoupon:function(){
		GuardianSpaceCoupon.closeStyleManager(GuardianSpaceCoupon.currentField);
		
		parent.GuardianSpaceCoupon.clearMessage();
		parent.GuardianUtil.showUploading(_messages.waiting);
		
		//serialize style
		GuardianSpaceCoupon.couponStyle.startDate = $("#startDateWidget").val();
		GuardianSpaceCoupon.couponStyle.endDate = $("#endDateWidget").val();
		
		GuardianSpaceCoupon.couponStyle.root.image = "";
		$("#couponStyle").val(toJSON(GuardianSpaceCoupon.couponStyle).json);
		
		$("form").submit();
	},
	
	clearMessage: function(){
		$(".clean-error").hide();
		$(".clean-ok").hide();
	},

	response: function(e,result){
		GuardianUtil.hideLoading();
		window.scrollTo(0,0);
			    
		if(e){
			msg = e;
			/*if(e == "Coupon Image cannot be empty"){
				msg = "Selezionare l'Immagine";
			}
			if(e == "Coupon Image must be at least 326x320 pixels"){
				msg = "L'immagine deve avere una dimensione di almeno 326x320 pixels";
			}*/
				
			$(".clean-error").html("Error: " + msg);
			$(".clean-error").show();
		}else{
			$(".clean-ok").html(_messages.coupon_ok);
			$(".clean-ok").show();
		}
		GuardianSpaceCoupon.init();
	},
	
	minusMouseDown: function(evt){
		target = $(evt.target);
		input = target.parent().find("input");
		if(GuardianSpaceCoupon.currentField == "root" && (target.hasClass("minus") || target.hasClass("plus"))){
			h = parseInt($("#height").val());
			w = parseInt($("#width").val());
			if(h < 5 || w < 5) return;
			$("#height").val(h-5);
			$("#width").val(w-5);
			$("#width").trigger("change");
		}else{
			v = parseInt(input.val());
			if(v<5) v = 0;
			input.val(v-5);
			input.trigger("change");
		}
	},	
	
	plusMouseDown: function(evt){
		target = $(evt.target);
		input = target.parent().find("input");
		if(GuardianSpaceCoupon.currentField == "root" && (target.hasClass("minus") || target.hasClass("plus"))){
			h = parseInt($("#height").val());
			w = parseInt($("#width").val());
			$("#height").val(h+5);
			$("#width").val(w+5);
			$("#width").trigger("change");
		}else{
			v = parseInt(input.val());
			input.val(v+5);
			input.trigger("change");
		}	
	},	
	
	positionMouseDown: function(evt){
		idx = parseInt(evt.data.index);
		//alert(idx);
		target = $(evt.target);
		input = target.parent().find("input");
		v = parseInt(input.val());
		input.val(v+idx);
		input.trigger("change");	
	},	
	
	minusPlusMouseUp: function(){
		clearTimeout(timeout);
	},
		
	previewCoupon: function(cStyle){
		if(cStyle != null){
			for(i in cStyle){
				v = cStyle[i];
				if(i=="root"){
					//$("#couponPreview").css("width",v.width);
					//$("#couponPreview").css("height",v.height);
					$("#couponPreview").css("background-color",v.background);
					if(v.visibility=="visible"){
						if(backupImage == false){
							$("#couponPreview").css("background-image",v.image);
						}
						$("#couponPreview").css("background-size",v.width + "px " + v.height + "px");
						$("#couponPreview").css("background-repeat","no-repeat");
						$("#couponPreview").css("background-position",v.left + "px" + " " + v.top + "px");
					}
					else{
						$("#couponPreview").css("background-image","");
						$("#couponPreview").css("background-repeat","no-repeat");
						$("#couponPreview").css("background-size",v.width + "px " + v.height + "px");
						$("#couponPreview").css("background-position",v.left + "px" + " " + v.top + "px");
					}	
				}else{
					$("#couponPreview #" + i).css("width",v.width);
					$("#couponPreview #" + i).css("height",v.height);
					$("#couponPreview #" + i).css("visibility",v.visibility);
					$("#couponPreview #" + i).css("left",v.left + "px");
					$("#couponPreview #" + i).css("top",v.top + "px");
					$("#couponPreview #" + i).css("font-size",v.font_size + "px");
					$("#couponPreview #" + i).css("color",v.font_color);
					$("#couponPreview #" + i).css("background-color",v.background);
				}
			}
		}
		$('#couponText').text($("#description").val());
		$('#couponPreviewType').text($("#couponValue").val());
		
		$('#couponDateStart').text($("#startDateWidget").val());
		$('#couponDateEnd').text($("#endDateWidget").val());
		
		$('#couponPreview').show();
		//$("#preview_coupon img").attr("src",src);
	},
	
	handleFileSelect: function(evt){
		GuardianSpaceCoupon.closeStyleManager(GuardianSpaceCoupon.currentField);
		
		var files = evt.target.files;
		imagePreview = $('#couponPreview');
	 
        var reader = new FileReader();
        
        s = (parseFloat(files[0].size)/(1024*1024));
	    t = files[0].type;
	    supportedImage="image/jpeg image/gif image/png image/bmp";
		window.parent.GuardianSpaceCoupon.resetMessage();
		
	    if(s>4){
	    	window.parent.GuardianSpaceCoupon.errorMessage(_messages.error_size);
	    	GuardianSpaceCoupon.resetField("root",false);
	    	$("#couponImage").val("");
	    	return false;
	    }
	    
	    if(supportedImage.indexOf(t)<0){
	    	window.parent.GuardianSpaceCoupon.errorMessage(_messages.error_type);
	    	GuardianSpaceCoupon.resetField("root",false);
	    	$("#couponImage").val("");
	    	return false;
	    }

	    reader.onload = function(e){
	    	backupImage = true;
    		$(".couponPalette:eq(0)").trigger("click");
        	    	
        	GuardianSpaceCoupon.couponStyle.root.image = "url(" + e.target.result + ")";
        	GuardianSpaceCoupon.couponStyle.root.left = "50";
        	GuardianSpaceCoupon.couponStyle.root.top = "50";
        	GuardianSpaceCoupon.couponStyle.root.visibility = "visible"; 
        	
        	imagePreview.css("background-image","url(" + e.target.result + ")");
        	$("#styleBox #visibility").attr("checked","checked");
        	        	
        	newImg = new Image();
			newImg.src = e.target.result;
			newImg.onload = function() {
				if(newImg.width > 380 && newImg.height > 500){
					v1 = newImg.width/380;
					v2 = newImg.height/500;
					//altezza
					h1 = newImg.height/v1;
					w1 = 380;
					
					//larghezza
					h2 = 500;
					w2 = newImg.width/v2;
					
					if(h1>500){
						newImg.width = w1;
						newImg.height = h1;		
					}else{
						newImg.width = w2;
						newImg.height = h2;
					}
				}
				else if(newImg.width > 380){
					v = newImg.width/380;
					newImg.width = 380;
					newImg.height = newImg.height/v;
				}else if(newImg.height > 500){
					v = newImg.height/500;
					newImg.height = 500;
					newImg.width = newImg.width/v;
				}
				
				imagePreview.css("background-size", newImg.width + "px" + " " + newImg.height + "px");
				l = (380-newImg.width)/2;
				t = (500-newImg.height)/2;
				imagePreview.css("background-position",l + "px " + t + "px");
				
				GuardianSpaceCoupon.couponStyle.root.width = newImg.width;
	            GuardianSpaceCoupon.couponStyle.root.width = newImg.height;
	            
	            $("#styleBox #width").val(newImg.width);
	            $("#styleBox #height").val(newImg.height);
	            $("#styleBox #pos_t").val(t);
        		$("#styleBox #pos_l").val(l);
	        }
	    };
	    
	    reader.readAsDataURL(files[0]); 
	},
	
	resetMessage: function(){
		$(".clean-error").hide();
		$(".clean-ok").hide();
	},
	
	errorMessage: function(msg){
		GuardianSpaceCoupon.resetMessage();
		$(".clean-error").text(msg);
		$(".clean-error").show();
	},
	
	okMessage: function(msg){
		GuardianSpaceCoupon.resetMessage();
		$(".clean-ok").text(msg);
		$(".clean-ok").show();
	},
	
	styleManager: function(event){
		GuardianSpaceCoupon.closeStyleManager(GuardianSpaceCoupon.currentField);
		
		GuardianSpaceCoupon.currentField = event.data.field;
		
		i = event.data.field;
		
		if(i=="root"){
			$("#styleBox #font_s").parent().parent().hide();
			
			if(backupImage == true){
				$("#visibility").parent().hide();
			}else{
				$("#visibility").parent().show();
			}
			//$("#styleBox #pos_l").parent().parent().hide();
			
			//$("#styleBox #width").val($("#couponPreview").css("width").replace("px",""));
			//$("#styleBox #height").val($("#couponPreview").css("height").replace("px",""));
			
			v = $("#couponPreview").css("background-image");
			if(v!=null && v!="none"){
				$("#styleBox #visibility").attr("checked","checked");
			}else{
				$("#styleBox #visibility").removeAttr("checked");
			}	
			
			p = $("#couponPreview").css("background-position");
			
			v = p.split("px");
			$("#styleBox #pos_t").val(v[1]);
			$("#styleBox #pos_l").val(v[0]);
			
			p = $("#couponPreview").css("background-size");
			
			v = p.split("px");
			$("#styleBox #width").val(v[0]);
			$("#styleBox #height").val(v[1]);
			
			c = rgb2hex($("#couponPreview").css("background-color"));
			$("#styleBox #back_color").val(c);
			$("#styleBox #back_color").css("background-color",c);

		}else{		
		    $("#styleBox #font_s").parent().parent().show();
		    $("#styleBox #pos_t").parent().parent().show();
		    $("#visibility").parent().show();

			c = rgb2hex($("#couponPreview #" + i).css("background-color"));
			$("#styleBox #back_color").val(c);
			$("#styleBox #back_color").css("background-color",c);
		
			v = $("#couponPreview #" + i).css("visibility");
			if(v=='visible'){
				$("#styleBox #visibility").attr("checked","checked");
			}else{
				$("#styleBox #visibility").removeAttr("checked");
			}	
		
			$("#styleBox #pos_t").val($("#couponPreview #" + i).css("top").replace("px",""));
			$("#styleBox #pos_l").val($("#couponPreview #" + i).css("left").replace("px",""));
			$("#styleBox #font_s").val($("#couponPreview #" + i).css("font-size").replace("px",""));
		
			c = rgb2hex($("#couponPreview #" + i).css("color"));
			$("#styleBox #font_color").val(c);
		
			$("#styleBox #font_color").css("background-color",c);
			$("#styleBox #width").val($("#couponPreview #" + i).css("width").replace("px",""));
			$("#styleBox #height").val($("#couponPreview #" + i).css("height").replace("px",""));
		
			$("#couponPreview #" + event.data.field).css("border","2px dashed #C80000");
		}
		$("#styleBoxContainer").show();
		
		if(event.target != null){
			$('#styleBoxContainer').animate({top:event.target.offsetTop+30,left:25},200);
		}
		/*GuardianUtil.showInlineBox("styleBox",event.target,
			function(){
				$("#couponPreview #" + GuardianSpaceCoupon.currentField).css("border","0px");
				GuardianSpaceCoupon.closeStyleManager(GuardianSpaceCoupon.currentField);
			}
		);*/
	},
	
	closeStyleManager: function(field){
		try{
			$("#couponPreview #" + field).css("border","0px");
			$("#styleBoxContainer").hide();
			GuardianSpaceCoupon.updateStyleManager(field);
		}catch(e){alert(e)}
	},
	
	resetField: function(field, open){
		GuardianSpaceCoupon.currentField = null;
		
		if(field == "root"){
			$("#couponImage").val("");
			backupImage = false;
		}	
			
		jQuery.extend(GuardianSpaceCoupon.couponStyle[field],GuardianSpaceCoupon.couponOldStyle[field])
		GuardianSpaceCoupon.previewCoupon(GuardianSpaceCoupon.couponStyle);
		
		if(open != false){
			e = {data:""};
			e.data = {field:""};
			e.data.field = field;
			GuardianSpaceCoupon.styleManager(e);
		}
	},
	
	updateStyleManager: function(field){
		//alert(field);
		hideColorPicker();
		
		fieldStyle = {}; 
		
		fieldStyle.background = $("#styleBox #back_color").val();
		v = $("#styleBox #visibility:checked").length;
		fieldStyle.visibility = (v>0 ? 'visible': 'hidden');
		fieldStyle.left = $("#styleBox #pos_l").val();
		fieldStyle.top = $("#styleBox #pos_t").val();
		fieldStyle.font_size = $("#styleBox #font_s").val();
		fieldStyle.font_color = $("#styleBox #font_color").val();
		fieldStyle.width = $("#styleBox #width").val();
		fieldStyle.height = $("#styleBox #height").val();
		
		if(field == "couponText")
			this.couponStyle.couponText = fieldStyle;
		if(field == "couponDateStart")
			this.couponStyle.couponDateStart = fieldStyle;
	    if(field == "couponDateEnd")
			this.couponStyle.couponDateEnd = fieldStyle;
	 	if(field == "couponPreviewType")
			this.couponStyle.couponPreviewType = fieldStyle;
		if(field == "root"){
			fieldStyle.image = GuardianSpaceCoupon.couponStyle.root.image;
			this.couponStyle.root = fieldStyle;
		}
		GuardianSpaceCoupon.previewCoupon(this.couponStyle);
	}
}

var backupImage = false;
var timeout = null; 

function rgb2hex(rgb) {
 if(rgb == null || rgb == 'transparent')
 	 return "";	
 
 rgbm = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 if(rgbm == null)
 	return "";
 
 function hex(x) {
  return ("0" + parseInt(x).toString(16)).slice(-2);
 }
 return "#" + hex(rgbm[1]) + hex(rgbm[2]) + hex(rgbm[3]);
}


/*** GOOGLE IMAGE SEARCHER****/
var GuardianGImageSearcher = {
  
  customSearchControl: null,
  imageSearcher:null,
  
  init: function(){
    	console.log("GuardianGImageSearcher init");
    	google.search.ImageSearch.RawCompletion = GuardianGImageSearcher.callbackSearch;
    	
  		customSearchOptions = {};
	    imageSearchOptions = {};
	    imageSearchOptions['layout'] = google.search.ImageSearch.LAYOUT_CLASSIC;
	    customSearchOptions['enableImageSearch'] = true;
	    customSearchOptions['imageSearchOptions'] = imageSearchOptions;  
	    GuardianGImageSearcher.customSearchControl = new google.search.CustomSearchControl('012229308517268147799:ez53mqih2jq', customSearchOptions);
	    GuardianGImageSearcher.customSearchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
	    GuardianGImageSearcher.imageSearcher = GuardianGImageSearcher.customSearchControl.getImageSearcher();
  },
  
  doSearch: function(cbk, query, page, page_size){
  		GuardianGImageSearcher.callback = cbk;
  		console.log("page " + page);
  		GuardianGImageSearcher.customSearchControl.setResultSetSize(page_size);
  		GuardianGImageSearcher.imageSearcher.execute(query,"",page);
  },
  
  callbackSearch: function(i,results){
  		console.log("callbackSearch " + i);
  		var images = [];
  		if(results != null){
  			list = results.results;
  			for(var i=0;i<list.length;i++){
  				console.log("Risultato " + list[i].titleNoFormatting);
  				images[i] = {};
  				images[i].title = list[i].titleNoFormatting;
  				images[i].description = "";
  				images[i].thumbnailUrl = list[i].tbUrl;
  				images[i].mediaSource = "GOOGLE_IMAGES";
  				images[i].externalId = list[i].imageId;
  				images[i].contextUrl = list[i].originalContextUrl;
  				images[i].mediaLocation = list[i].unescapedUrl;
  			}
  		}
  		
  		r = {list:{}};
  		r.list.list = images;
  		console.log(results.cursor);
  		r.total = results.cursor.estimatedResultCount;
  		GuardianGImageSearcher.callback(r);
  }
   

}
