/*----------------------------------------------------------------------------------------------------
GuardianFacebookConnector
----------------------------------------------------------------------------------------------------*/
var GuardianFacebookConnector = {

	session_key: null,
	feedId: '',
	space_url: "space.page?spaceid=",
	video_url: "space.page?",
	
	profileHtml: function(name,icon){
		var html = "<div style=\"margin-left: 150px;\"><h3>You are using your Facebook account. Please go to "+
			"<a style=\"color:#0606EE\" href=\"http://www.facebook.com/profile.php?v=info&edit_info=all\">facebook</a> for changing your profile</h3>";
		html += "<div>Username:<b>  " + name + "</b></div>";
		html += "<div><img src=" + icon +  "/></div></div>";
		return html;
	},
	
	faviconLink: "http://static.ak.fbcdn.net/images/icons/favicon.gif",
	
	loginHtml: "<a href=\"#\" onclick=\"GuardianFacebookConnector.loginByFacebook();\">" +
			   "<img style=\"float: left; margin-top: 10px;\" id=\"fb_login_image\" src=\"http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_light_medium_long.gif\" alt=\"Connect\" />" +
			   "</a>",
		
	init: function(){		
		//document.write('<script type="text/javascript" src="/static_files/FeatureLoader.js.php"></script>'); 
		FB.init(GuardianConf.FACEBOOK_API_KEY, "xd_receiver.htm",{"ifUserNotConnected":this.onNotConnected, "ifUserConnected":this.onConnected}); 	
		this.feedId = GuardianConf.F_TEMPLATE_PUBLISH_SPACE;
		this.space_url = GuardianUtil.getCurrentPath() + "space.page?spaceid=";
		this.video_url = GuardianUtil.getCurrentPath() + this.video_url;
	},	
		
	loginByFacebook: function(){
		FB.Connect.requireSession(GuardianFacebookConnector.loginCallback2); 
	},
	
	logoutByFacebook: function(cbk){
		FB.Connect.logout(cbk);
	},
	
	onNotConnected:function(){
		if(GuardianLogin.account != null && GuardianLogin.account.external){
			GuardianLogin.account.external=false;
			GuardianLogin.logout();
		}
	},
	
	onConnected:function(userid){
		if(GuardianLogin.account != null && GuardianLogin.account.external && GuardianLogin.account.extId!=userid){
			GuardianLogin.account.external=false;
			GuardianLogin.logout();
		}
	},

		
	loginCallback: function(){
		var api = new FB.ApiClient(GuardianConf.FACEBOOK_API_KEY);
		var session_key = api.get_session().session_key;
		var userId = api.get_session().uid;
		GuardianLogin.loginByFacebook(userId,session_key);		
	},
	
	loginCallback2: function(){
		var api = new FB.ApiClient(GuardianConf.FACEBOOK_API_KEY);
		var userId = api.get_session().uid;
		api.users_getInfo([userId],['name','birthday','first_name','last_name','pic','sex','hometown_location'], 
				function(infos, ex){
					var country = null;
					var info = infos[0];
				    if(info.hometown_location != null)
				         country = info.hometown_location.country;
					GuardianLogin.loginByFacebookWithUserProfile(info.uid, info.name, info.first_name, info.last_name, info.sex, info.pic, country);	
				});
	},
	
	clearSession: function(){
		FB.Connect.logout();
		this.loginByFacebook();
	},
	
	postFeedVideos: function(spaceName, spaceId, spaceImage, videos){
		var user_message_prompt = "What do you think of these videos?"; 
		var user_message = {value: "write your review here"};
		var body_general = '';
		
		var template_data = new Object();
		template_data['space']='<a href="'+GuardianFacebookConnector.space_url+spaceId+'">'+spaceName+'</a>';
		
		if(videos != null && videos.length > 0){
			var images = new Array();
			for(var i=0;i<videos.length && i<5;i++){
				images[i] = new Object();
				images[i].src = videos[i].imageName; 
				images[i].href = GuardianFacebookConnector.video_url+"spaceid="+spaceId+"&videoid="+videos[i].id;
			}
			template_data['images']=images;
		}
		
		/*FB.Connect.showFeedDialog(GuardianFacebookConnector.feedId, 
										template_data, 
										'', 
										body_general, 
										null, 
										FB.RequireConnect.promptConnect, 
										GuardianFacebookConnector.postFeedVideosCallback, 
										user_message_prompt, 
										user_message);
		*/
		
		var video = new Object();
		if(videos != null && videos.length > 0){
			video.title = videos[0].title;
			video.description = videos[0].description;
			video.imageName = videos[0].imageName; 
			video.imageHref = GuardianFacebookConnector.video_url+"spaceid="+spaceId+"&videoid="+videos[0].id;			
		}
		var attachment = { 
		'name': video.title,
		 'href': template_data['space'],		 
		  'description': video.description,
		  'media': [{ 'type': 'image', 'src': video.imageName , 'href': video.imageHref}]
		  };

		FB.Connect.streamPublish('', attachment, null, null, user_message_prompt, GuardianFacebookConnector.streamFeedVideosCallback);

		/*, 
		  'properties': { 'category': { 'text': 'sport', 'href': 'http://bit.ly/KYbaN'}, 'ratings': '5 stars' },
		  'media': [{ 'type': 'image', 'src': 'http://icanhascheezburger.files.wordpress.com/2009/03/funny-pictures-your-cat-is-bursting-with-joy1.jpg', 'href': 'http://bit.ly/187gO1'}]  */
	},
	
	postFeedVideosCallback: function(r){
		GuardianAudience.closeFacebookPostLink();
	},
	
	streamFeedVideosCallback: function(r, e){		
		GuardianAudience.closeFacebookPostLink();
	},
	
	
	requirePermissionCbkYes:null,
	requirePermissionCbkNo:null,
	
	requirePermissions: function(cbkYes, cbkNo){
		var api = new FB.ApiClient(GuardianConf.FACEBOOK_API_KEY);
		api.users_hasAppPermission("email",GuardianFacebookConnector.showRequirePermissionsCbk);	
		GuardianFacebookConnector.requirePermissionCbkYes =	cbkYes;
		GuardianFacebookConnector.requirePermissionCbkNo =	cbkNo;
	},
	
	showRequirePermissionsCbk:function(result){
		if(result == 0)
			FB.Connect.showPermissionDialog("email",GuardianFacebookConnector.requirePermissionsCbk);
		else
			eval(GuardianFacebookConnector.requirePermissionCbkYes);
	},

	requirePermissionsCbk:function(result){
		if(result == true)
			eval(GuardianFacebookConnector.requirePermissionCbkYes);
		else
			eval(GuardianFacebookConnector.requirePermissionCbkNo);
	}
	
};
var GuardianLogin = {
    
    account: null,
    privateChannel:false,
    loginPage:"login",
    callPage:"/",
	  
    //Synchronus call
	login_onstartup: function(){
		var result = jsonrpc.auth.getSessionOwner();
		GuardianLogin.account= result;
		var page = GuardianUtil.getCurrentPage();		
		var h = "";
		if(result != null){
			if(page=="join" || page=="reset_password" || page=="confirmMail" || page==GuardianLogin.loginPage){
				document.location=GuardianLogin.callPage;
			}
	   	    
			$('#utility_links_welcome').hide();
			$('#utility_links_login').show();
	   	   
			$('#f_account > a > span:eq(1)').text(result.username);
			$('#f_account > a').attr("href", "profile_edit.page");	   	    	
			$('#my_account > a').attr("href", "profile_edit.page");
			//$('#help a').attr("href","javascript:GuardianUtil.underConstruction()");
			$('#signout a').attr("href","javascript:GuardianLogin.logout()");
			if(!result.external){
				$('#f_account > a > span.f_usericon').hide();
			}					
	   }else{
		   if(GuardianLogin.privateChannel && page!=GuardianLogin.loginPage && page!="join" && page!="terms" && page!="privacy"){
				document.location=GuardianLogin.loginPage + ".page";
			}
	   
			$('#utility_links_welcome').show();
			$('#utility_links_login').hide();
	   	    
			$('#f_login a').attr("href","javascript:GuardianFacebookConnector.loginByFacebook()");
	   		
			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;
			
			$('#g_login a').attr("href",loginpage);
			$('#signup a').attr("href",joinpage); 		
	   }
   },   
   
   login:function(){
  	   var user= $('input#username').val();
	   var pass= $('input#password').val();
	   var remember= $('#rememberme').checked;
	   
	   if(remember == null)
			remember = false;
			
	   var result = jsonrpc.auth.login(user, pass, remember);
	   if(result == null){
	        $('div.box_join_login div.clean-error').fadeIn('slow');
	        $('div.box_log_in div.clean-error').fadeIn('slow');
	      	return;
	   }else{
		   GuardianLogin.account= result;
		   var cbk = GuardianUtil.getArgs()['callback'];
		   if(cbk != null){
		   		var url = cbk + ".page?";
		  	   var args = GuardianUtil.getArgs();
		  	   var nameArgs = GuardianUtil.getArgsNames();
		  	   for(i=0; i<nameArgs.length; i++){		  	   
		  	   		if(nameArgs[i].toLowerCase()!='callback'){
		  	   			url = url+nameArgs[i]+'='+args[nameArgs[i]]+'&';
		  	   		}
		  	   }
		  	   document.location = url.substring(0,url.length-1);
		   }		  
		   else
		   	   document.location.reload();
	   }
	   return;
   },
   
   loginByFacebook: function(userId, sessionKey){
	   var result = jsonrpc.auth.loginByFacebook(userId, sessionKey);
	   if(result == null){
	      	alert("Login incorrect");
	      	GuardianFacebookConnector.clearSession();
	      	return false;
	   }else{
		   GuardianLogin.account= result;
		   var cbk = GuardianUtil.getArgs()['callback'];
		   if(cbk != null){
		   		var url = cbk + ".page?";
		  	   var args = GuardianUtil.getArgs();
		  	   var nameArgs = GuardianUtil.getArgsNames();
		  	   for(i=0; i<nameArgs.length; i++){		  	   
		  	   		if(nameArgs[i].toLowerCase()!='callback'){
		  	   			url = url+nameArgs[i]+'='+args[nameArgs[i]]+'&';
		  	   		}
		  	   }
		  	   document.location = url.substring(0,url.length-1);
		   }		  
		   else
		   	   document.location.reload();
	   }
   },
      
   loginByFacebookWithUserProfile: function(userId, uname, first_name, last_name, sex, pic, country){
	   var result = jsonrpc.auth.loginByFacebookWithUserProfile(userId, uname, first_name, last_name, sex, pic, country);
	   if(result == null){
	      	alert("Login incorrect");
	      	return false;
	   }else{
		   GuardianLogin.account= result;
		   var cbk = GuardianUtil.getArgs()['callback'];
		   if(cbk != null){
		   		var url = cbk + ".page?";
		  	   var args = GuardianUtil.getArgs();
		  	   var nameArgs = GuardianUtil.getArgsNames();
		  	   for(i=0; i<nameArgs.length; i++){		  	   
		  	   		if(nameArgs[i].toLowerCase()!='callback'){
		  	   			url = url+nameArgs[i]+'='+args[nameArgs[i]]+'&';
		  	   		}
		  	   }
		  	   document.location = url.substring(0,url.length-1);
		   }		  
		   else
		   	   document.location.reload();
	   }
   },

				
   logout: function(){
   		if(GuardianLogin.account.external){
   			GuardianFacebookConnector.logoutByFacebook(function(){ jsonrpc.auth.logout(GuardianLogin.cbk_logout) });
   		}else{
			jsonrpc.auth.logout(this.cbk_logout);
		}
   },
	 
   cbk_logout: function(result, e){
		   if(e!=null){
		     //alert(e);
		   }else{
		     GuardianLogin.account = null;
			 window.location.reload();
		   }
   },
   
   forgotPassword: function(){
   		var username = $('#username_f').val();
   		if(jQuery.trim(username)!= ''){
   			jsonrpc.accountService.forgotPassword(username);
   			setTimeout("document.location='/'",1000);
   		}
   		GuardianUtil.closeModalDialog();
   }

};


var GuardianHeader = {

		search_page: 'search_results.page?query=',
		search_empty: 'search..',
		loadSearch: function () {
	var search_text = $(".text_field > #search_text").val();
	if (search_text == "" || search_text == GuardianHeader.search_empty) {
		return;
	}
	window.location = GuardianHeader.search_page + search_text;
},
initSearchBox: function () {
	var args = GuardianUtil.getArgs();
	var search_query = args["query"];
	var button = $(".btn_search .search");
	$(button).click(GuardianHeader.loadSearch);
	var input = $(".text_field > #search_text");
	$(input).blur(GuardianHeader.textSearchBoxOnBlur);
	$(input).focus(GuardianHeader.textSearchBoxOnFocus);
	$(input).keyup(function (e) {
		if (e.keyCode == 13) {
			var search_text = $(input).val();
			if (search_text == "") {
				return;
			}
			var s = GuardianHeader.search_page + search_text;
			document.location.href = s;
		}
	});
	if (search_query != null) {
		$(input).val(search_query);
	}
},
textSearchBoxOnBlur: function () {
	var input = $(".text_field > #search_text");
	if ($(input).val() == "") {
		$(input).val(GuardianHeader.search_empty);
	}
},
textSearchBoxOnFocus: function () {
	var input = $(".text_field > #search_text");
	if ($(input).val() == GuardianHeader.search_empty) {
		$(input).val("");
	}
}
};


var GuardianFooter = {	
	init: function(){
		if(GuardianLogin.account == null){
			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;

			$('#login_footer > a').attr("href",loginpage);
			$('#join_footer > a').attr("href",joinpage);
		}
		else{
			$('#login_footer').hide();
			$('#join_footer').hide();
		}	
	}
};


var GuardianSplash = {
		search_page: 'search_results.page?query=',
		search_empty: 'search..',
	    loadSearch: function () {
	        var search_text = $(".splash_search #search_text_splash").val();
	        if (search_text == "" || search_text == GuardianSplash.search_empty) {
	            return;
	        }
	        window.location = GuardianHeader.search_page + search_text;
	    },
	    init: function () {
	        var args = GuardianUtil.getArgs();
	        var search_query = args["query"];
	        var button = $(".splash_search .search_passion");
	        $(button).click(GuardianSplash.loadSearch);
	        var input = $(".splash_search #search_text_splash");
	        $(input).blur(GuardianSplash.textSearchBoxOnBlur);
	        $(input).focus(GuardianSplash.textSearchBoxOnFocus);
	        if (search_query != null) {
	            $(input).val(search_query);
	        }
	    },
	    textSearchBoxOnBlur: function () {
	        var input = $(".splash_search #search_text_splash");
	        if ($(input).val() == "") {
	            $(input).val(GuardianSplash.search_empty);
	        }
	    },
	    textSearchBoxOnFocus: function () {
	        var input = $(".splash_search #search_text_splash");
	        if ($(input).val() == GuardianSplash.search_empty) {
	            $(input).val("");
	        }
	    }
	};

var GuardianUtil = {

	default_page: 'index',

    getCurrentPage: function(){
		var URL = unescape(location.href);	// get current URL in plain ASCII
		var xstart = URL.lastIndexOf("/")+1;
		var xend = URL.lastIndexOf(".page");
		var page = GuardianUtil.default_page;
		if(xend > 0)
			page = URL.substring(xstart,xend);
		return page;
	},
	
	getCurrentPath : function(){
			var URL = unescape(location.href);	// get current URL in plain ASCII
			var xstart = URL.lastIndexOf("/") + 1;
			var herePath = URL.substring(0,xstart);
			return herePath;
	},
	
	getArgs: function(){
		var args = new Object(); 
		var query = location.search.substring(1);
		var pairs = query.split("&"); 

		for(var i = 0; i < pairs.length; i++) { 
			var pos = pairs[i].indexOf('=');
			if (pos == -1) continue; 
			var argname = pairs[i].substring(0,pos).toLowerCase(); 
			var value = pairs[i].substring(pos+1); 
			args[argname] = unescape(value); 
		} 
		return args;
	},
	
	getArgsNames: function(){
		var args = new Array(); 
		var query = location.search.substring(1);
		var pairs = query.split("&"); 

		for(var i = 0; i < pairs.length; i++) { 
			var pos = pairs[i].indexOf('=');
			if (pos == -1) continue; 
			var argname = pairs[i].substring(0,pos).toLowerCase(); 
			args[i] = argname; 
		} 
		return args;
	},
	
	showModalDialog: function(divId){
		var el = $('#'+divId);
		var l = ($(window).width() - el.width()) / 2;
   	 	var t = ($(window).height() - el.height()) / 2;
   	 	
   	 	t = Math.max(0,t);
   	 	l = Math.max(0,l);
   	 	
   	 	$.blockUI.defaults.css.top = t;
	 	$.blockUI.defaults.css.left = l;
	 	$.blockUI.defaults.css.padding = 0;
    	$.blockUI.defaults.css.margin = 0;
   	 	
   	 	$.blockUI({ 
			message: $('#'+divId),
			allowBodyStretch: true
    	});
	},
	
	closeModalDialog: function(){
	 	try{
			$.unblockUI();
		}catch(e){}
	},
	
	showLoading: function(){
		$.blockUI.defaults.overlayCSS.opacity = '0.1';
		this.showModalDialog("loading");
	},
	
	hideLoading: function(){
		$.blockUI.defaults.overlayCSS.opacity = '0.6';
		this.closeModalDialog();
	},
	
	confirmDialog: function(message,callFunction){
	   	var l = ($(window).width() - 300) / 2;
   	 	var t = ($(window).height() - 50) / 2;
   	 	
   	 	t = Math.max(0,t);
   	 	l = Math.max(0,l);
   	 	
   	 	$.blockUI.defaults.css.top = t;
   	 	$.blockUI.defaults.css.left = l;
	    
		$.blockUI({ message: "<div class=\"box_overlay\" style=\"width:300px; padding-left: 20px; padding-right: 20px; padding-bottom: 20px; text-align:center;\"><h3>" + message + "</h3><input id=\"yes\" type=\"button\" value=\"yes\" /> \
			<input id=\"no\" type=\"button\"value=\"no\" /><div>"}); 
         
        $('#yes').click(function() { 
        	try{
				$.unblockUI();
			}catch(e){}
            eval(callFunction);
        }); 
 
        $('#no').click(function() { 
           	try{
				$.unblockUI();
			}catch(e){}
            return false; 
        }); 
	},
	
	showLoadingInDiv: function(divEl){
		$(divEl).addClass("loading");
		$(divEl).css("height",$(divEl).height());
	},
	
	hideLoadingInDiv: function(divEl){
		$(divEl).removeClass("loading");
		$(divEl).css("height",'');
	},
	
	readCookie: function(name) {
		var prefix = name + "=" 
    	var start = document.cookie.indexOf(prefix) 

    	if (start==-1) {
       	 	return null;
    	}
    	var end = document.cookie.indexOf(";", start+prefix.length)
   	 	if (end==-1) {
        	end=document.cookie.length;
    	}

    	var value=document.cookie.substring(start+prefix.length, end) 
    	return unescape(value);
	},
	
	resolveSize: function(n) {
        if (n != null) {
            n = n.toLowerCase();
            var factor = 1;
          	var number = 1;
            if (n.indexOf("g")>0) {
                factor = 1024 * 1024 * 1024;
                number = n.substring(0, n.length - 1);
            } else if (n.indexOf("m")>0) {
                factor = 1024 * 1024;
                number = n.substring(0, n.length - 1);
            } else if (n.indexOf("k")>0) {
                factor = 1024;
                number = n.substring(0, n.length - 1);
            }

            var nReturn = number * factor;
        }
        return nReturn;
    },
    
    newCaptcha: function(){
   	 	var c = new Date();
    	document.getElementById('captcha_im').src = "JCaptcha?id=" + c.getTime();
	},
	
	wrapWord: function(el,content,boxSize,wrapSize){
		var word_wrap = true;
		var index = 0;
		var start = 0;
		var _title = content;
		
		$(el).html('');
		$(el).append("<label></label>");	
		$(el).find("label").text(_title);
		
		while(word_wrap){
			if($(el).find("label").width() > boxSize){
				start = index * wrapSize;
				_title = _title.substring(0,start) + " " +  _title.substring(start);
				$(el).html('');
				$(el).append("<label></label>");	
				$(el).find("label").text(_title);
				index++;
			}else{
				word_wrap = false;
			}
		}			
	},
	
	underConstruction: function(){
		alert("Under Contruction");
	},
		
	validateEmail: function(str){
	        var at = "@";
	        var dot = ".";
	        var lat = str.indexOf(at);
	        var lstr = str.length;
	        var ldot = str.indexOf(dot);
	        if (str.indexOf(at) == -1) {
	            return false;
	        }
	        
	        if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
	            return false;
	        }
	        
	        if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
	            return false;
	        }
	        
	        if (str.indexOf(at, (lat + 1)) != -1) {
	            return false;
	        }
	        
	        if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
	            return false;
	        }
	        
	        if (str.indexOf(dot, (lat + 2)) == -1) {
	            return false;
	        }
	        
	        if (str.indexOf(" ") != -1) {
	            return false;
	        }
	        
	        return true;
	},
	
	MAX_DUMP_DEPTH : 10,
    
    dumpObj :function (obj, name, indent, depth) {
           if (depth > this.MAX_DUMP_DEPTH) {
                  return indent + name + ": <Maximum Depth Reached>\n";
           }

           if (typeof obj == "object") {
                  var child = null;
                  var output = indent + name + "\n";
                  indent += "\t";
                  for (var item in obj)
                  {
                        try {
                               child = obj[item];
                        } catch (e) {
                               child = "<Unable to Evaluate>";
                        }

                        if (typeof child == "object") {
                        		output += GuardianUtil.dumpObj(child, item, indent, depth + 1);
                        } else {
                               output += indent + item + ": " + child + "\n";
                        }
                  }
                  return output;
           } else {
                  return obj;
           }
    },
    
    formatDuration: function(secs){
    	if(secs == null)
			return "0 sec";
		var formattedTime;
		var minutes= Math.floor(secs/60);
		secs %= 60;		
		formattedTime = minutes + ":" + (secs < 10 ? "0"+ secs : secs);
		return formattedTime;
    },
    
    formatDate: function(milliseconds){
    	var date = new Date(milliseconds);
    	var formattedDate = (date.getDate()>9 ? date.getDate(): "0" +date.getDate()) + "/" + 
    	(date.getUTCMonth()>9 ? date.getUTCMonth(): "0" + date.getUTCMonth()) + "/" + date.getFullYear();
		return formattedDate;
    }

	
	/*
	readChannelName: function(){
		var href = location.href;
    	var refs = href.split("/");
   	 	return refs[4];
	},
		
	deleteCookie: function(name,path,domain) {
		if (this.readCookie(name)) {
    		var c = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-70 00:00:01 GMT"; 
      		document.cookie = c;
  		}
	},
	
	months: new Array(),

	revMonths : new Array("gen", "feb", "mar", "apr", "may", 
		"jun", "jul", "aug", "sep", "oct", "nov", "dec"),

	parseObjectDate: function(date){
		var y,m,d;
		var t= date.split(" ");
		m=this.months[t[0].toLowerCase()];
		d= t[1].replace(",", "");
		y= t[2];
		return new Date(y - 1900, m - 1, d);
	},

	toObjectDate: function(day, month, year){
		var da= "";
	
		var d= day;
		if(day < 10) d= "0" + day;
	
		var m= month;
		if(m < 10) m= "0" + m;
	
		da= year + "-" + m + "-" + d;
		return da;
	},*/
	
    /*
	hide: function(id){
		var el=document.getElementById(id);
		if(el){
			el.style.display="none";
		}
	},
	
	show: function(id){
		var el=document.getElementById(id);
		if(el){
			el.style.display="block";
		}
	},
	
	openInviteFriends: function(){
		if(GuardianLogin.account == null){
			alert("User must be logged");
		}
		else {
			this.popup("contacts/index.jsp", "InviteFriends", 807, 630);
		}
	},
	
	popup: function(url, name, width, height){	
    	var left = (screen.width - width) / 2;
   	 	var top = (screen.height - height) / 2;
    	var params = "width=" + width + ", height=" + height;
   	 	params += ",top=" + top + ",left=" + left;
    	params += ",location=no";
    	params += ",menubar=no";
    	params += ",resizable=no";
    	params += ",scrollbars=no";
    	params += ",status=no";
    	params += ",toolbar=no";
    	var newwin = window.open(url, name, params);
    	return false;
	},
	
	*/
};var GuardianVideoList = {
	video_page: 1,
	video_page_size: 10,
	videoAd: null,
	
	getShuffleVideoList: function(){
		$('#guardian_VideoList').children('div').fadeOut("slow");
		
		var adsList = GuardianAds.getAds(10,'test');
		if(adsList != null && adsList.list.length > 0){
				var rand_no = Math.random() * adsList.list.length;
				rand_no = Math.ceil(rand_no);
				GuardianVideoList.videoAd = adsList.list[rand_no];		
				GuardianVideoList.video_page_size = 9;
		}
		
		jsonrpc.videoListService.getShuffleVideosInChannel(
			GuardianVideoList.videoListCallback,GuardianVideoList.video_page,GuardianVideoList.video_page_size);
	},

	videoListCallback: function(result, e){
		if(e != null){
			GuardianUtil.hideLoading();
			return;
		}
			
		//Video List
		var code = "";
		
		if(result.list == null)
			return;
			
		$('#btn_more a').attr('href', 'javascript:GuardianVideoList.getShuffleVideoList()');
		
		var videos = result.list.list;
		
		var idx = 0;
		var rand_no = -1;
		
		var endIdx = videos.length + 1;
		if(GuardianVideoList.videoAd == null){
			endIdx = videos.length;	
		}else{
			rand_no = Math.random() * (videos.length-1);
			rand_no = Math.ceil(rand_no);
		}		
		
		for(i=0;i<endIdx;i++){ 
		    var el = $($('#guardian_VideoList').children('div')[i]);
		   
		    if(rand_no == i){
		        	var thumb = $(el).children('div')[0];
					$(thumb).removeClass('thumb');	
					$(thumb).addClass('thumb_adv');
				
					var img = $(thumb).find('img');	
					var a = $(thumb).find('a');
					$(img).attr('src',GuardianVideoList.videoAd.image);
					$(img).attr('alt',GuardianVideoList.videoAd.title);
					$(a).attr('href',GuardianVideoList.videoAd.clickUrl);
			
					var meta = $(el).children('div')[1]; 
					$(meta).find('.meta_title a').text(GuardianVideoList.videoAd.title);
					$(meta).find('.meta_title a').attr('href',GuardianVideoList.videoAd.clickUrl);
			
					$(meta).find('.meta_owner a').attr('href',GuardianVideoList.videoAd.clickUrl);
					$(meta).find('.meta_owner a').text(GuardianVideoList.videoAd.description);
			
					$(meta).find('.meta_duration').hide();
					$(meta).find('.meta_date').hide();
					$(meta).find('.meta_views').hide();
					
					ads=false;			
		    }else{
			
				var thumb = $(el).children('div')[0];
				$(thumb).removeClass('thumb_adv');	
				$(thumb).addClass('thumb');
		
				var img = $(thumb).find('img');	
				var a = $(thumb).find('a');
				$(img).attr('src',videos[idx].imageName);
				$(img).attr('alt',videos[idx].title);
				$(a).attr('href','space.page?videoid=' + videos[idx].id);
			
				var meta = $(el).children('div')[1]; 
				$(meta).find('.meta_title a').text(videos[idx].title);
				$(meta).find('.meta_title a').attr('href','space.page?videoid=' + videos[idx].id);
			
				$(meta).find('.meta_duration').text(videos[idx].formattedTime);
				$(meta).find('.meta_date').text('Add: '+videos[idx].creationDate);
			
				var sname="unknown";
				var shref="#";
				if(videos[idx].space != null){
					shref = 'space.page?spaceid=' + videos[idx].space.spaceId;
					sname = videos[idx].space.name;
				}
				$(meta).find('.meta_owner a').attr('href',shref);
				$(meta).find('.meta_owner a').text(sname);
				$(meta).find('.meta_views').text('Views: '+videos[idx].views);
				
				$(meta).find('.meta_duration').show();
				$(meta).find('.meta_date').show();
				$(meta).find('.meta_views').show();
				
				idx++;
			}
			
			el.fadeIn("slow");
		}
	}				
};var GuardianVideoPlayer = {

	idVideo: 1,
	
	playerUrl : 'swf/jwf/player.swf',
	player: null,
	eventController: new Object(),
	eventModel: new Object(),
	eventView: new Object(),
	MAX_DESCRIPTION:300,
	videoDescription:null,
	played: false,
		
	fillVideoPlayer: function(){
		var args = GuardianUtil.getArgs(); 	 
		if (args['videoid'] != null) 
		  this.idVideo = args['videoid'];
	    jsonrpc.videoPageService.getVideoInfo(this.fillVideoPlayerCallback,this.idVideo);
	},

	fillVideoPlayerCallback: function(result, e){
		if (e != null) {
			//alert(e);
			return;
		}
		var video = result;		 
		GuardianVideoPlayer.fillDivVideoPlayer('videoPlayer',video.title, video.description, video.videoName, video.imageName, video.duration, video.external, video.embedCode, '640', '360');
	},
	
	fillDivVideoPlayer: function(divId, title, description, videoUrl, imageUrl, duration, external, embedCode, width, height){
		var flashvars = "";
		
		var flashvars = {};
		var params = {
			allowfullscreen:'true',
	  		allowscriptaccess:'always',
	   		allownetworking:'all',
	   		wmode:'opaque'
		};
		
		if(!external){
			flashvars.file = videoUrl;
			flashvars.image = imageUrl;
			flashvars.controlbar = 'over';
			flashvars.duration = duration;
			flashvars.fullscreen = 'true';
			flashvars.stretching = 'uniform';
			flashvars.backcolor = '111111';
			flashvars.frontcolor = 'cccccc';
			flashvars.lightcolor='AAAAAA';
			flashvars.skin = 'swf/jwf/stylish.swf';
			flashvars.autostart = GuardianVideoPlayer.played;
		}		
		else{
			this.playerUrl = embedCode + "&rel=0" + "&showinfo=0";
		}
	    
	    this.videoDescription = description;
	    
	    this.lessDescriptionSize(divId);
	    
	    /*if(swfobject.hasFlashPlayerVersion("9")){
	       	swfobject.embedSWF(this.playerUrl, divId, width, height, "9","",flashvars,params); */
	    if($.hasFlashPlayerVersion("9")){
	    	var flash = $.flash({
	    		swf: this.playerUrl,
	    		width: width,
	    		height: height,
	    		flashvars: flashvars,
	    		params: params
	    	});	     	
	    	$("#" + divId).html(flash);
	    }else{
	    	var html = "<a href=\"http://www.adobe.com/go/getflashplayer\" target=\"_blank\">\
				<img src=\"http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif\" alt=\"Get Adobe Flash player\" />\
				</a>";	
	    	$('#' + divId).html(html);
	    }	    	    
	    	
	},
	
	initEvents: function(){
		
		for(var e in GuardianVideoPlayer.eventController){
			GuardianVideoPlayer.player.addControllerListener(e,GuardianVideoPlayer.eventController[e]);
		}
		for(var e in GuardianVideoPlayer.eventModel){
			GuardianVideoPlayer.player.addModelListener(e,GuardianVideoPlayer.eventModel[e]);
		}
		for(var e in GuardianVideoPlayer.eventView){
			GuardianVideoPlayer.player.addViewListener(e,GuardianVideoPlayer.eventView[e]);
		}
	},
	
	addControllerListener: function(event, fun){
		GuardianVideoPlayer.eventController[event]=fun;
	},
	
	addModelListener: function(event, fun){
		GuardianVideoPlayer.eventModel[event]=fun;
	},
	
	addViewListener: function(event, fun){
		GuardianVideoPlayer.eventView[event]=fun;
	},
	
	fullDescriptionSize: function(){
		var cmd = " <a href='javascript:GuardianVideoPlayer.lessDescriptionSize();'>(less)<a>";
		$("#preview_video_description").text(this.videoDescription);
		$("#preview_video_description").append(cmd);	
	},
	
	lessDescriptionSize: function(){
		var cmd="";
		var d = this.videoDescription;
		if(d.length > this.MAX_DESCRIPTION){
			d = d.substring(0, this.MAX_DESCRIPTION);
			cmd = "... <a href='javascript:GuardianVideoPlayer.fullDescriptionSize();'>(more)<a>";
		}
		
		$("#preview_video_description").text(d);
		$("#preview_video_description").append(cmd);
	}
	
};

function playerReady(obj) {
		GuardianVideoPlayer.player = $('#'+obj['id'])[0];		
		GuardianVideoPlayer.initEvents();
};
var nCurrent = 1;           // Init Page (offset)            
var nForPage = 3;           // Thumb for page
var bDebug = false;          // Set true to show text debug
var nTotResult = 1;

// Gallery Parameter
var bNextPrevGallery = true;

/*function readyToLoad(){
	if (bDebug)
        $('#debug').css('display', 'block');
}*/

// Request Video List
function GetAllVideosInChannel(_Current, _ForPage) {
	jsonrpc.videoListService.getFocusVideosInChannel(getFocusOnCallback,_Current,_ForPage);
}
            
function getFocusOnCallback(result, e){
	if(e != null){
		return;
	}
	var jsonData = new Object();
	jsonData.result = result;
	loadThumb(jsonData);
}

// Request Video Details
function GetVideoInfo(_idVideo) {
    // Request Data
    jsonrpc.videoPageService.getVideoInfo(getVideoInfoCallback,_idVideo);
}
            
function getVideoInfoCallback(result, e){
	if(e != null){
			return;
	}
	var jsonData = new Object();
	jsonData.result = result;
	loadVideoInfo(jsonData);
}
            
    
function loadThumb(jsonData) {
    nTotResult = jsonData.result.total;
    
    if(nTotResult > 27)
    	  nTotResult = 27;  	
    
    nNresto = 0;

    nTmp = nTotResult / 3
    nTmp = parseInt(nTmp, 10);
    if (nTotResult - nTmp > 0)
        nTmp = nTmp + 1;

    nTotResult = nTmp;

    var sHtmlPageGallery = '';
    sHtmlPageGallery = nCurrent.toString() + '/' + nTotResult.toString();
    $('.pageGallery').html(sHtmlPageGallery);    
    
    var sHtmlGallery = '';
    // left box
    for (i = 0; i < 3; i++) {
        sHtmlGallery = sHtmlGallery + '<div class="thumb">';
        sHtmlGallery = sHtmlGallery + '<div class="thumbBg"></div>';
        sHtmlGallery = sHtmlGallery + '<div class="thumbLoad"></div>';
        sHtmlGallery = sHtmlGallery + '</div>';
    }

    // cirrent box 
    for (i = 0; i < jsonData.result.list.list.length; i++) {

        // Get jsonData
        sVideoName = jsonData.result.list.list[i].videoName;
        sImageUrl = jsonData.result.list.list[i].imageName;
        sTitle = jsonData.result.list.list[i].title;
        sDescription = jsonData.result.list.list[i].description;
        sId = jsonData.result.list.list[i].id;

        // Adjust text length
        if (sTitle.length > 30)
            sTitle = sTitle.substr(0, 30);

        if (sDescription.length > 50)
            sDescription = sDescription.substr(0, 50);            

        // Add Box 
        sHtmlGallery = sHtmlGallery + '<div class="thumb">';
        sHtmlGallery = sHtmlGallery + '<div class="thumbBg"></div>';
        sHtmlGallery = sHtmlGallery + '<div class="thumbLoad"></div>';
        sHtmlGallery = sHtmlGallery + '<div class="thumbImg"><img src="' + sImageUrl + '" alt="' + sTitle + '" title="' + sTitle + '" class="reflect" /></div>';
        sHtmlGallery = sHtmlGallery + '<div class="thumbFrame" id="' + sId + '"></div>';
        sHtmlGallery = sHtmlGallery + '<div class="thumbFrameActive" id="thumbFrameActive_' + sId + '">';
        sHtmlGallery = sHtmlGallery + '	<div class="detail">';
        sHtmlGallery = sHtmlGallery + '    	<div class="txt">';
        sHtmlGallery = sHtmlGallery + '        	<div class="tit">' + sTitle + '</div>';
        sHtmlGallery = sHtmlGallery + '            <div class="subTit">' + sDescription + '</div>';
        sHtmlGallery = sHtmlGallery + '     </div>';
        sHtmlGallery = sHtmlGallery + '     <div class="button" id="' + sId + '">';
        sHtmlGallery = sHtmlGallery + '        	<a href="javascript:;">Watch now</a>';
        sHtmlGallery = sHtmlGallery + '         <div class="buttonUp"></div>';
        sHtmlGallery = sHtmlGallery + '     </div>';
        sHtmlGallery = sHtmlGallery + '  </div>';
        sHtmlGallery = sHtmlGallery + '     <div style="clear:both;display:block;"></div>';        
        sHtmlGallery = sHtmlGallery + '</div>';
        sHtmlGallery = sHtmlGallery + '</div>';
    }

    // Right Box
    if ((jsonData.result.list.list.length == 3) &&  (nCurrent < nTotResult)){
        for (i = 0; i < 3; i++) {
            sHtmlGallery = sHtmlGallery + '<div class="thumb">';
            sHtmlGallery = sHtmlGallery + '<div class="thumbBg"></div>';
            sHtmlGallery = sHtmlGallery + '<div class="thumbLoad"></div>';
            sHtmlGallery = sHtmlGallery + '</div>';
        }
    }

    // Add Html Box
    $('#catGalleryScroll').html(sHtmlGallery);

    // Set left gallery container
    var boxWidth = 262 * 3;
    $('#catGalleryScroll').css('left', '-' + boxWidth.toString() + 'px');
    setFrame();
    setScrollTo();
    addReflections();
}

function setFrame() {
    // Set listener "watch" link
    $('.button').bind('click', function() {
        var sId = $(this).attr('id');
        var sThumbFrameActive = "#thumbFrameActive_" + sId;

        GetVideoInfo(sId);

        $('.gallery').css('display', 'none');
        $('.pageGallery').css('display', 'none');
        $('.galleryDetail').css('display', 'block');
    });

    // Set listener for info video
    $('.thumbFrame').bind('mouseover', function() {
        $(".thumbFrameActive").css('display', 'none');
        var sId = $(this).attr('id');
        var sThumbFrameActive = "#thumbFrameActive_" + sId;

        $(sThumbFrameActive).css('display', 'block');
    });

    // Set listener for info video
    $('.rollout01').bind('mouseover', function() {
        $(".thumbFrameActive").css('display', 'none');
    });

    $('.rollout02').bind('mouseover', function() {
        $(".thumbFrameActive").css('display', 'none');
    });     
}

function setScrollTo() {
    var boxWidth = 262 * 3;
    var totCount = ($('.thumb').length) - 2;
    var totCountVisible = ($('.thumb').length);
    var count = 0;

    // Set width gallery container
    nWidthcatGalleryScroll = boxWidth * totCountVisible;
    $("#catGalleryScroll").css('width', nWidthcatGalleryScroll.toString() + 'px');

    // Enable Roll-over
    if (nCurrent > 1)
        $('#catSx').attr('class', 'catSx');
    else
        $('#catSx').attr('class', 'catSxDisable');

    if (nCurrent < nTotResult)
        $('#catDx').attr('class', 'catDx');
    else
        $('#catDx').attr('class', 'catDxDisable');   

    // Set listener prev link
    $('#catSx').bind('click', function() {
        if (bNextPrevGallery) {
            bNextPrevGallery = false;
            var left = parseInt($('#catGalleryScroll').css('left').replace('px', ''));
            var scr = left + boxWidth;
            if (nCurrent > 1) {
                $('#catGalleryScroll').animate({ left: (scr == 0 ? scr + 'px' : scr) }, 300);
                count--;
                nCurrent--;

                var sHtmlPageGallery = '';
                sHtmlPageGallery = nCurrent.toString() + '/' + nTotResult.toString();
                $('.pageGallery').html(sHtmlPageGallery);
                
            }
            setTimeout('EnableNext()', 500);
        }
        return false;
    });

    // Set listener next link
    $('#catDx').bind('click', function() {
        if (bNextPrevGallery) {
            bNextPrevGallery = false;
            var left = parseInt($('#catGalleryScroll').css('left').replace('px', ''));
            var scr = left - boxWidth;
            if (nCurrent < nTotResult) {
                $('#catGalleryScroll').animate({
                    left: (scr == 0 ? scr + 'px' : scr)
                }, 300);
                count++;
                nCurrent++;

                var sHtmlPageGallery = '';
                sHtmlPageGallery = nCurrent.toString() + '/' + nTotResult.toString();
                $('.pageGallery').html(sHtmlPageGallery);
                
            }
            setTimeout('EnableNext()', 1000);
        }
        return false;
    });
}

function EnableNext() {
    // Enable next and prev link
    bNextPrevGallery = true;

    // Load Current Range Box
    GetAllVideosInChannel(nCurrent, nForPage);
}	


/*VideoDetails*/
function loadVideoInfo(jsonData) {

    // Get jsonData
    sTitle = jsonData.result.title;
    sUsername = jsonData.result.space.name;
    sDescription = jsonData.result.description;
    sEmbedCode = "videoPlayer.page?videoid=" + jsonData.result.id;
    sIdUtente = jsonData.result.id;
    
    //
    var sUrlProfile =  "space.page?spaceid=" + jsonData.result.space.spaceId;

    // Set content video Info
    $('#videoTitle').html(sTitle);
    $('#videoUsername').html('<a href="' + sUrlProfile + '">' + sUsername + '</a>');
    $('#videoDescription').html(sDescription); 
    $('#videoIFrame').attr('src', sEmbedCode);
    $('#videoIFrame').css('display', 'block');

    // Show info panel
    $('#txtDetails').css('display', 'block');

    // Debug
    if (bDebug) {
        var sHtmlDebug = "<input type='text' size='150' value='" + sEmbedCode + "'>";
        $('#debug').html(sHtmlDebug);
    }

    // Set listener "close" link
    $('#buttonClose').bind('click', function() {

        // Hide info panel
        $('#txtDetails').css('display', 'none');

        $('#videoTitle').html('');
        $('#videoUsername').html('');
        $('#videoDescription').html('');
        $('#videoIFrame').css('display', 'none');
        $('#videoIFrame').attr('src', '');

        $('.gallery').css('display', 'block');
        $('.pageGallery').css('display', 'block');
        $('.galleryDetail').css('display', 'none');
    });

    ClearSpringController.register(jsonData.result,null,"buttonShare");
    ClearSpringController.init();
}


/**
 * reflection.js v1.6
 *
 * Contributors: Cow http://cow.neondragon.net
 *               Gfx http://www.jroller.com/page/gfx/
 *               Sitharus http://www.sitharus.com
 *               Andreas Linde http://www.andreaslinde.de
 *               Tralala, coder @ http://www.vbulletin.org
 *
 * Freely distributable under MIT-style license.
 */
 
/* From prototype.js */
document.getElementsByClassName = function(className) {
	var children = document.getElementsByTagName('*') || document.all;
	var elements = new Array();
  
	for (var i = 0; i < children.length; i++) {
		var child = children[i];
		var classNames = child.className.split(' ');
		for (var j = 0; j < classNames.length; j++) {
			if (classNames[j] == className) {
				elements.push(child);
				break;
			}
		}
	}
	return elements;
}

var Reflection = {
	defaultHeight : 0.4,
	defaultOpacity: 0.8,
	
	add: function(image, options) {
		Reflection.remove(image);
		
		doptions = { "height" : Reflection.defaultHeight, "opacity" : Reflection.defaultOpacity }
		if (options) {
			for (var i in doptions) {
				if (!options[i]) {
					options[i] = doptions[i];
				}
			}
		} else {
			options = doptions;
		}
	
		try {
			var d = document.createElement('div');
			var p = image;
			
			var classes = p.className.split(' ');
			var newClasses = '';
			for (j=0;j<classes.length;j++) {
				if (classes[j] != "reflect") {
					if (newClasses) {
						newClasses += ' '
					}
					
					newClasses += classes[j];
				}
			}

			var reflectionHeight = Math.floor(p.height*options['height']);
			var divHeight = Math.floor(p.height*(1+options['height']));
			
			var reflectionWidth = p.width;
			
			if (document.all && !window.opera) {
				/* Copy original image's classes & styles to div */
				d.className = newClasses;
				p.className = 'reflected';
				
				d.style.cssText = p.style.cssText;
				p.style.cssText = 'vertical-align: bottom';
			
				var reflection = document.createElement('img');
				reflection.src = p.src;
				reflection.style.width = reflectionWidth+'px';
				
				reflection.style.marginBottom = "-"+(p.height-reflectionHeight)+'px';
				reflection.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+(options['opacity']*100)+', style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+(options['height']*100)+')';
				
				d.style.width = reflectionWidth+'px';
				d.style.height = divHeight+'px';
				p.parentNode.replaceChild(d, p);
				
				d.appendChild(p);
				d.appendChild(reflection);
			} else {
				var canvas = document.createElement('canvas');
				if (canvas.getContext) {
					/* Copy original image's classes & styles to div */
					d.className = newClasses;
					p.className = 'reflected';
					
					d.style.cssText = p.style.cssText;
					p.style.cssText = 'vertical-align: bottom';
			
					var context = canvas.getContext("2d");
				
					canvas.style.height = reflectionHeight+'px';
					canvas.style.width = reflectionWidth+'px';
					canvas.height = reflectionHeight;
					canvas.width = reflectionWidth;
					
					d.style.width = reflectionWidth+'px';
					d.style.height = divHeight+'px';
					p.parentNode.replaceChild(d, p);
					
					d.appendChild(p);
					d.appendChild(canvas);
					
					context.save();
					
					context.translate(0,image.height-1);
					context.scale(1,-1);
					
					context.drawImage(image, 0, 0, reflectionWidth, image.height);
	
					context.restore();
					
					context.globalCompositeOperation = "destination-out";
					var gradient = context.createLinearGradient(0, 0, 0, reflectionHeight);
					
					gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
					gradient.addColorStop(0, "rgba(255, 255, 255, "+(1-options['opacity'])+")");
		
					context.fillStyle = gradient;
					if (navigator.appVersion.indexOf('WebKit') != -1) {
						context.fill();
					} else {
						context.fillRect(0, 0, reflectionWidth, reflectionHeight*2);
					}
				}
			}
		} catch (e) {
	    }
	},
	
	remove : function(image) {
		if (image.className == "reflected") {
			image.className = image.parentNode.className;
			image.parentNode.parentNode.replaceChild(image, image.parentNode);
		}
	}
};

function addReflections() {
	var rimages = document.getElementsByClassName('reflect');
	for (i=0;i<rimages.length;i++) {
		var rheight = null;
		var ropacity = null;
		
		var classes = rimages[i].className.split(' ');
		for (j=0;j<classes.length;j++) {
			if (classes[j].indexOf("rheight") == 0) {
				var rheight = classes[j].substring(7)/100;
			} else if (classes[j].indexOf("ropacity") == 0) {
				var ropacity = classes[j].substring(8)/100;
			}
		}
		
		Reflection.add(rimages[i], { height: rheight, opacity : ropacity});
	}
}
var GuardianAds = {
    
    enable:false,
    advListSize:4,
    advBoxElement: null,
    keywords: null,
    advTitleSize: 20,
	    
    getAds: function(n,keywords){
    	if(!GuardianAds.enable)
    		return null;    
  		return jsonrpc.ads.getAds(n,keywords);
    },
    
    getAdvItems: function(){
		jsonrpc.ads.getAds(GuardianAds.getAdvItemsCbk,GuardianAds.advListSize,GuardianAds.keywords);
	},
	
	getAdvItemsCbk: function(result,e){
		if(e)
			return;
			
		var advItems = result.list;
		var el = $(GuardianAds.advBoxElement);
		
		el.fadeIn("slow");
		for(var i=0;i<advItems.length;i++){ 
            var link = $(el.children()[i]);
			$(link).attr("href",advItems[i].clickUrl);
			
			var title = link.find('.box_ads .title');
			var description = link.find('.box_ads .desc');
			var clickUrl = link.find('.box_ads .link');
			//fix strange character
			var _title = advItems[i].title.replace(/\xC2/g,' ');
			$(title).text(_title);
			var _description = advItems[i].description.replace(/\xC2/g,' '); 
			$(description).text(_description);
			$(clickUrl).text("");
			
			$(link.find('.box_ads')).fadeIn('slow');
			
			//$(clickUrl).text(advItems[i].url);
			GuardianUtil.wrapWord(clickUrl,advItems[i].url,160,20);	
		}
	},
	
	readChannelName: function(){
		var href = location.href;
		href = href.replace("http://","");
    	var refs = href.split(".");
   	 	return refs[0];
	}
    
};
var GuardianSupport = {

	CAPTCHA_WRONG:"The verification text is wrong",

    init:function(){
    	$("#mail").val('');
    	$("#name").val('');
    	$("#web_address").val('');
    	$("#message").val('');
    	$("#verification").val('');
    	
    	$('.btn_send').parent().attr('href','javascript:GuardianSupport.sendMsg();');
    },

	sendMsg:function(){
    	$('.clean-ok').fadeOut('slow');
    	$('.clean-error').fadeOut('slow');
    	    	
    	var f = true;
        var msg = "";
        
	  	$("#name").css('border-color','');
	  	$("#mail").css('border-color','');
	  	$("#web_address").css('border-color','');
		$("#message").css('border-color','');
		$("#verification").css('border-color','');
		
		
		var username=$("#name").val();
       	if(username == ""){
           		msg += "&#8226; The name is empty.<br />";
           		$("#name").css('border-color','red');
				f=false;
       	}

		var email=$("#mail").val();
		if(!GuardianSupport.validateEmail(email)){
			msg += "&#8226; The email address doesn't seem to be valid.<br />";
			$("#mail").css('border-color','red');
			f=false;
		}
       	
       	var web_address=$("#web_address").val();
		if(web_address == ""){
           		msg += "&#8226; The web address is empty.<br />";
           		$("#web_address").css('border-color','red');
				f=false;
       	}
		
		var input_msg=$("#message").val();
		if(input_msg == ""){
           		msg += "&#8226; The message is empty.<br />";
           		$("#message").css('border-color','red');
				f=false;
       	}
       			
		var captcha=$("#verification").val();

		var c_message = "Web Address = \n" + web_address + "\n";
		c_message += "Message =\n " + input_msg;
		
		if(f==false){
   			$('.clean-error').fadeIn('slow');
			$('.clean-error').html(msg);
			return;
		}
		
		jsonrpc.contact.reportBug(GuardianSupport.sendMsgCallBack,username,'',email,c_message,captcha)
	},
	
	sendMsgCallBack: function(result,e){
		$("#name").css('border-color','');
	  	$("#mail").css('border-color','');
	  	$("#web_address").css('border-color','');
		$("#message").css('border-color','');
		$("#verification").css('border-color','');
	
		if(e != null){
	  		var error = "" + e;
	  		error = error.substring(error.indexOf(':') + 1);
	  		
	  		var msg = error;
	  		
	  		if(error.indexOf("CAPTCHA_WRONG")>0){
	  			msg = GuardianSupport.CAPTCHA_WRONG;
	  			$("#verification").css('border-color','red');
	  			//$('#verification_l').css('color','red');
	  		}
	  		
	  		$('.clean-error').fadeIn('slow');
			$('.clean-error').html(msg);
			
			GuardianSupport.newCaptcha();
			return;
	  	}

		GuardianSupport.init();
		GuardianSupport.newCaptcha();
		$('.clean-ok').fadeIn('slow');
	},
	
	validateEmail: function(str){
	        var at = "@";
	        var dot = ".";
	        var lat = str.indexOf(at);
	        var lstr = str.length;
	        var ldot = str.indexOf(dot);
	        if (str.indexOf(at) == -1) {
	            return false;
	        }
	        
	        if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
	            return false;
	        }
	        
	        if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
	            return false;
	        }
	        
	        if (str.indexOf(at, (lat + 1)) != -1) {
	            return false;
	        }
	        
	        if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
	            return false;
	        }
	        
	        if (str.indexOf(dot, (lat + 2)) == -1) {
	            return false;
	        }
	        
	        if (str.indexOf(" ") != -1) {
	            return false;
	        }
	        
	        return true;
	},
	
	newCaptcha: function(){
   	 	var c = new Date();
    	document.getElementById('captcha_im').src = "JCaptcha?id=" + c.getTime();
	}

};
var GuardianImportVideo = {
	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: 'space_name.page?spaceid=',
	space: null,
	
	init:function(){
	
		var args = GuardianUtil.getArgs();
		this.spaceid = args['spaceid'];
		
		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",
        	{spaceid:this.spaceid},
        	function(event){
        		document.location = "upload.page?spaceid=" + event.data.spaceid;
        	}
        );
        
        this.space = jsonrpc.spaceService.getSpaceDetails(this.spaceid);
        
        if(this.space != null && this.space.owner.id == GuardianLogin.account.id){

			//$('#back_link > p > a:eq(0)').attr('href', GuardianImportVideo.import_page_link+GuardianImportVideo.spaceid);
			$('#back_link > p > a:eq(0)').attr('href', GuardianImportVideo.space_name_page_link+GuardianImportVideo.spaceid);
			$('#back_link > p > a:eq(0) > span').text(this.space.name);
			
            $(".box_import").fadeIn("slow");
            $(".box_import_list:first").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(GuardianImportVideo.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:GuardianImportVideo.selectAllVideoResult();');
		$('#unselect_allresults').attr('href','javascript:GuardianImportVideo.unselectAllVideoResult();');
		$("#addSelected").attr('href','javascript:GuardianImportVideo.addSelectedVideoResults();');
		$("#deleteAll").attr('href','javascript:GuardianImportVideo.deleteAllVideoFromImportList();');

  	},
  	
  	changePageSize: function(){
  		var sel = $('.pagination span > select').selectedValues();
  		GuardianImportVideo.page_size = sel[0];
  		GuardianImportVideo.call();
  	},
	
    doSearch: function(){
    	$('.box_import .clean-error').fadeOut("slow");
        var el = $("#videosearch");
        var query = el.val();
        if (query.length == 0) {
            alert("Write something in the search box.");
            return;
        }
        
        $('.box_video_center').hide();
		$('.box_video_right').hide();
		$('.box_video_left').hide();
		$(".box_import .search_results").children().hide();
		
        GuardianImportVideo.query = query;
        GuardianImportVideo.page = 1;
        this.call();
    },
    
    call: function(){
    	//document.getElementById("videoBox").style.display = "none";
    	
		$('.box_video_center').hide();
		$('.box_video_right').hide();
		$('.box_video_left').hide();
		
		GuardianImportVideo.unselectAllVideoResult();

    	GuardianUtil.showLoading();
        var start_index = (GuardianImportVideo.page - 1) * GuardianImportVideo.page_size;
        jsonrpc.externalPublisher.searchVideos(GuardianImportVideo.searchCbk, GuardianImportVideo.query, start_index + 1, GuardianImportVideo.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(GuardianImportVideo.query);
        	$('.box_import .clean-error').fadeIn("slow");
        	return;
        }
        
        $(".search_results .items").text(GuardianImportVideo.query);
             
        GuardianImportVideo.searchResult = result.list.list;
        GuardianImportVideo.populateResults();
        GuardianImportVideo.pagination(result.total);
        
        $(".box_import .search_results").children().fadeIn("slow");
        $(".box_import .search_results").fadeIn("slow");
    },
    
    populateResults: function(){
        var videos = GuardianImportVideo.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},GuardianImportVideo.clickVideoResult);
			var text = $(el).find('.text');
			$(text).bind('click',{'index':i},GuardianImportVideo.clickVideoResult);
			img.attr("src",videos[i].thumbnailUrl);
			text.text(videos[i].title);
			var previewbtn = $(el).find(".tools").children('a')[0];
			$(previewbtn).attr('href','javascript:GuardianImportVideo.previewVideo(' + i + ')');
			var addbtn = $(el).find(".tools").children('a')[1];
			$(addbtn).attr('href','javascript:GuardianImportVideo.addVideo(' + i + ')');
			var del = $(el).find(".delete a");
			$(del).attr('href','javascript:GuardianImportVideo.deleteVideo(' + i + ')');
			$(del).parent().hide();
			$(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");
    		GuardianImportVideo.selectedResults[event.data.index] = false;
    	}else{
    		el.addClass("selected");
    		GuardianImportVideo.selectedResults[event.data.index] = true;
    	}
    	GuardianImportVideo.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");
    	GuardianImportVideo.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");
    	GuardianImportVideo.selectedResults[index] = false;	
    },   
    
    selectAllVideoResult: function(){
    	var videos = GuardianImportVideo.searchResult;
    	if(videos == null)
    		return;
    	for (var i=0; i < videos.length ; i++) {	
    		GuardianImportVideo.selectVideoResult(i);
    	}
    	GuardianImportVideo.checkSelectedResult();
    },
    
    unselectAllVideoResult: function(){
    	var videos = GuardianImportVideo.searchResult;
    	if(videos == null)
    		return;
    	for (var i = 0; i < videos.length ; i++) {	
    		GuardianImportVideo.unselectVideoResult(i);
    	}
    	GuardianImportVideo.checkSelectedResult();
    },
    
    checkSelectedResult: function(){
    	var l = GuardianImportVideo.selectedResults;
    	for(var i in GuardianImportVideo.selectedResults){
    		if(l[i]){
    			$("#addSelected").fadeIn("slow");
    			return;
    		}
    	}    	
    	$("#addSelected").fadeOut("slow");
    },    
    
    addSelectedVideoResults: function(){
    	var l = GuardianImportVideo.selectedResults;
    	for(var i in GuardianImportVideo.selectedResults){
    		if(l[i]){
    			GuardianImportVideo.addVideo(i);
    		}
    	}
    },
      
    pagination: function(total) { 
       var nPages = Math.ceil(total/this.page_size);
       var el = $($('.pagination')).find('.count_pages');
	   el.html("Videos list <b>" + this.page + "</b> of " + nPages);
	   
	   var prev = $($('.pagination')).find('.prev');
	   prev.attr("href","#");
	   if(this.page > 1)
	   		prev.attr("href","javascript:GuardianImportVideo.changePage(" + (this.page - 1) + ")");
	   var more = $($('.pagination')).find('.more');
	   more.attr("href","#");
	   if(this.page != nPages)
		    more.attr("href","javascript:GuardianImportVideo.changePage(" + (this.page + 1) + ")");
	},
	    
    changePage: function(page){
		this.page = page;
		this.call();
	},
	
	previewVideo: function(index){
		var video = GuardianImportVideo.searchResult[index];
		var el = $("#preview_video .content #video_box");
		
		var addbtn = $("#preview_video .content .tools_video a:eq(0)");
		$(addbtn).attr('href','javascript:GuardianImportVideo.addVideo(' + index + ')');
		
		/*var del = $("#preview_video .content .tools_video a:eq(1)");
		$(del).attr('href','javascript:GuardianImportVideo.deleteVideo(' + i + ')');*/
		GuardianVideoPlayer.fillDivVideoPlayer('video_box',video.title, video.description, video.videoName,video.imageName,video.duration,true,video.mediaLocation,425,344);  
		GuardianUtil.showModalDialog("preview_video");
	},
	
	addVideo: function(index){
		var video = GuardianImportVideo.searchResult[index];
		var index = $.sha1(video.title);
		
		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);
		text.text(video.description);
		var del = $(el_c).find(".delete a");
		$(del).attr('href','javascript:GuardianImportVideo.deleteVideoFromImportList("' + index + '")');
		$(".box_import_list .video_add").append(el_c);
		el_c.fadeIn("slow");
		$(".box_import_list").fadeIn("slow");
	},
	
	deleteVideo: function(index){
		var video = GuardianImportVideo.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(){
    	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();
        			results[idx].id = 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("Error during video publication " + video.title);
        		}
        	}
        	this.importList[k] = null;
        }        
        $(".box_import_list:last").fadeOut("slow");
        GuardianUtil.hideLoading();
        GuardianImportVideo.showSendVideo(results);
    },
    
    showSendVideo: function(videos){	
 		GuardianAudience.showSendVideo(videos,GuardianImportVideo.space, GuardianImportVideo.goToSpace);
	},
	
	goToSpace:function(){
		document.location = "space_name.page?spaceId=" + GuardianImportVideo.space.spaceId;
	}        
};
var GuardianRecommendedList = {
	page: 1,
	page_size: 12,
	filter: "ALL",
	order: "ORDER_VIEWED",
	selector: "VIDEOS", //ALL, SPACES, VIDEOS
	query:"",
	isFilter:false,
	filterLabel:"in all time",
	init: false,
	clipType: "UGVideoMedium",
    
	pagination: function(total) { 
	
	   
	   var nPages = Math.ceil(total/this.page_size);
	   var el = $($('#guardian_RecommendedList')).find('#nav_total');
	   //"search word" In Spaces 1 of 50
	   //In Recommended <b>1</b> of 50
	   el.html("In Recommended <b>"+this.page+"</b> of "+ nPages);
	   
	   var prev = $($('#guardian_RecommendedList')).find('.prev');
	   prev.attr("href","#");
	   if(this.page > 1)
	   		prev.attr("href","javascript:GuardianRecommendedList.changePage(" + (this.page - 1) + ")");
	   var more = $($('#guardian_RecommendedList')).find('.more');
	   more.attr("href","#");
	   if(this.page != nPages)
		    more.attr("href","javascript:GuardianRecommendedList.changePage(" + (this.page + 1) + ")");
	
	   $('#guardian_RecommendedList .pagination').fadeIn('slow');
	},
	
	clickSearch: function(event){
		GuardianRecommendedList.page = 1;
		GuardianRecommendedList.isFilter = true;
		if(event.type == 'keyup' && event.keyCode != 13){
			return;
		}
		GuardianRecommendedList.query = $('.box_right .filter_query .text').val();
		GuardianRecommendedList.getRecommendedList();
	},
	
	changePage: function(page){
		GuardianRecommendedList.page = page;
		GuardianRecommendedList.getRecommendedList();
	},
	
	changeOrder: function(order){
		GuardianRecommendedList.page = 1;
		GuardianRecommendedList.order = order;
		if(order == "ORDER_ADDED"){
			var el = $('#most_recent').find('a');
			el.html("<b>Most Recent</b>");
			el = $('#most_viewed').find('a');
			el.html("Most Viewed");
		}
	
		if(order == "ORDER_VIEWED"){
			var el = $('#most_viewed').find('a');
			el.html("<b>Most Viewed</b>");
			el = $('#most_recent').find('a');
			el.html("Most Recent");
		}
		GuardianRecommendedList.getRecommendedList();
	},
	
	changeFilter: function(filter){
		GuardianRecommendedList.page = 1;
		this.isFilter = true;
		this.filter = filter;
		var filters = $('div .filter').find('span');
		filters.css("text-decoration","none");
		if(filter == "TODAY"){
			$(filters[0]).css("text-decoration","underline");
			this.filterLabel = "today";
		}
		if(filter == "WEEK"){
			$(filters[1]).css("text-decoration","underline");
			this.filterLabel = "in this week";
		}
		if(filter == "MONTH"){
			$(filters[2]).css("text-decoration","underline");
			this.filterLabel = "in this month";
		}
		if(filter == "ALL"){
			$(filters[3]).css("text-decoration","underline");
			this.filterLabel = "in all time";
		}
		GuardianRecommendedList.getRecommendedList();
	},
	
	changeSelector: function(selector){
		GuardianRecommendedList.selector = selector;
		GuardianRecommendedList.getRecommendedList();
	},
	
	getRecommendedList: function(){
		var offset = (GuardianRecommendedList.page -1)*GuardianRecommendedList.page_size;
		this.initSearchBox();
		GuardianUtil.showLoading();
jsonrpc.v2clipListService.getAllClipsInChannel(GuardianRecommendedList.recommendedListCallback,
		GuardianRecommendedList.query,GuardianRecommendedList.order,GuardianRecommendedList.filter,
		GuardianRecommendedList.page,GuardianRecommendedList.page_size,GuardianRecommendedList.clipType);
	},
	
	initSearchBox: function(){
		if(this.init)
			return;

		this.init =true;
		var input = $('.filter_query .text');
		$(input).blur(GuardianRecommendedList.textSearchBoxOnBlur);	
        $(input).focus(GuardianRecommendedList.textSearchBoxOnFocus);
        $(input).val('search featured videos..');
	},
	
	textSearchBoxOnBlur: function(){
	    var input = $('.filter_query .text');
		if($(input).val()==''){
        	$(input).val('search featured videos..');
      	}
	},
	
	textSearchBoxOnFocus: function(){
		var input = $('.filter_query .text');
        if($(input).val()=='search featured videos..'){
        	$(input).val('')
        }
	},

	recommendedListCallback: function(result, e){
		GuardianUtil.hideLoading();
               
		if(e != null){
			return;
		}
		
		$('#no_videos').hide();
		
		$('.box_video_center').hide();
		$('.box_video_right').hide();
		$('.box_video_left').hide();
		$('#guardian_RecommendedList .pagination').hide();

		if(result == null || result.list == null || result.total == 0){
			if(!GuardianRecommendedList.isFilter){	
				$('#no_videos').text("No Videos found");
				$('#no_videos').fadeIn('slow');
			}else{
				$('#no_videos').text("No Videos found for '" + GuardianRecommendedList.query + "' that has been published " + GuardianRecommendedList.filterLabel);
				$('#no_videos').fadeIn('slow');
			}
			return;
		}	
		
		var total = result.total;
		GuardianRecommendedList.pagination(total);
		
		var results = result.list.list;
		
		
		for(i=0;i<results.length;i++){ 
			var el = $($('#guardian_RecommendedList').children('div')[i+1]);
            //el = $(el).children('.box_video');
			var text = $(el).children('.metadata');	

			var img = $(el).find('div.thumb a img'); 
                        var a = $(el).find('div.thumb a');                      	
			
			$(img).attr('src',results[i].thumbnail);
			$(img).attr('alt',results[i].name);
            $(a).attr('href', 'space.page?videoid=' + results[i].id);
			
			var el_title = $(text).find('.meta_title a');
            var el_duration = $(text).find('.meta_duration');
            var el_owner = $(text).find('.meta_owner a');
            var el_views = $(text).find('.meta_views');
            var el_date = $(text).find('.meta_date');
                        
                        
			el_title.text(results[i].title);
            el_title.attr('href', 'space.page?videoid=' + results[i].id);
            el_duration.text(GuardianUtil.formatDuration(results[i].duration));
            var cDate = "";
			if(results[i].creationDate != null)
				cDate = GuardianUtil.formatDate(results[i].creationDate.time);
            el_date.text('Add: '+cDate);
            
            var sname="unknown";
			var shref="#";
			if(results[i].space != null){
				shref = 'space.page?spaceid=' + results[i].space.spaceId;
				sname = results[i].space.name;
			}
            el_owner.attr('href', shref);
			el_owner.text(sname);
            
			if(results[i].views == null)
				results[i].views = 0;
            el_views.text('Views: '+results[i].views);

			el.show();	
            el.parent('div').show();		
		}
		$('#guardian_RecommendedList').show();

		
		$('.box_right #most_viewed a').attr("href","javascript:GuardianRecommendedList.changeOrder('ORDER_VIEWED');");
		$('.box_right #most_recent a').attr("href","javascript:GuardianRecommendedList.changeOrder('ORDER_ADDED');");
		$('.box_right .filter a:eq(0)').attr("href","javascript:GuardianRecommendedList.changeFilter('TODAY');");
		$('.box_right .filter a:eq(1)').attr("href","javascript:GuardianRecommendedList.changeFilter('WEEK');");
		$('.box_right .filter a:eq(2)').attr("href","javascript:GuardianRecommendedList.changeFilter('MONTH');");
		$('.box_right .filter a:eq(3)').attr("href","javascript:GuardianRecommendedList.changeFilter('ALL');");
		
		$('.box_right .filter_query .btn_search .search').bind('click',GuardianRecommendedList.clickSearch);
		$('.box_right .filter_query .text').bind('keyup',GuardianRecommendedList.clickSearch);
		
		$('.box_right').show();

	}
};var GuardianSearchList = {
    page: 1,
    page_size: 12,
    filter: "ALL",
    order: "ORDER_ADDED",
    selector: "VIDEOS",
    query: null,
    noresult_page: 'all_spaces.page',
    noresult_newspace: false,
    linkpage: 'space.page',
    linkpage_subchannel: false,
    clipType: "UGVideoMedium",
    
    pagination: function (total) {
        var a_nav_all = $('.navigation #nav_all a');
        a_nav_all.attr('href', 'javascript:GuardianSearchList.changeSelector(\'ALL\')');
        var a_nav_spaces = $('.navigation #nav_spaces a');
        a_nav_spaces.attr('href', 'javascript:GuardianSearchList.changeSelector(\'SPACES\')');
        var a_nav_videos = $('.navigation #nav_videos a');
        a_nav_videos.attr('href', 'javascript:GuardianSearchList.changeSelector(\'VIDEOS\')');
        var nPages = Math.ceil(total / this.page_size);
        var el = $($('#guardian_SearchList')).find('#nav_total');
        el.html("\"" + GuardianSearchList.query + "\" In Spaces <b>" + this.page + "</b> of " + nPages);
        var prev = $($('#guardian_SearchList')).find('.prev');
        prev.attr("href", "#");
        if (this.page > 1) prev.attr("href", "javascript:GuardianSearchList.changePage(" + (this.page - 1) + ")");
        var more = $($('#guardian_SearchList')).find('.more');
        more.attr("href", "#");
        if (this.page != nPages) more.attr("href", "javascript:GuardianSearchList.changePage(" + (this.page + 1) + ")");
    },
    changePage: function (page) {
        this.page = page;
        this.getSearchList();
    },
    changeOrder: function (order) {
        this.order = order;
        if (order == "ORDER_ADDED") {
            var el = $('#most_recent').find('a');
            el.html("<b>Most Recent</b>");
            el = $('#most_viewed').find('a');
            el.html("Most Viewed");
        }
        if (order == "ORDER_VIEWED") {
            var el = $('#most_viewed').find('a');
            el.html("<b>Most Viewed</b>");
            el = $('#most_recent').find('a');
            el.html("Most Recent");
        }
        this.getSearchList();
    },
    changeFilter: function (filter) {
        this.filter = filter;
        var filters = $('div .filter').find('span');
        filters.css("text-decoration", "none");
        if (this.filter == "TODAY") {
            $(filters[0]).css("text-decoration", "underline");
        }
        if (this.filter == "WEEK") {
            $(filters[1]).css("text-decoration", "underline");
        }
        if (this.filter == "MONTH") {
            $(filters[2]).css("text-decoration", "underline");
        }
        if (this.filter == "ALL") {
            $(filters[3]).css("text-decoration", "underline");
        }
        this.getSearchList();
    },
    changeSelector: function (selector) {
        this.selector = selector;
        this.getSearchList();
    },
    getSearchList: function () {
        var offset = (this.page - 1) * this.page_size;
        var args = GuardianUtil.getArgs();
        var search_query = args['query'];
        this.query = search_query;
        if (search_query != null) {
            GuardianUtil.showLoading();
            jsonrpc.v2searchService.searchClipsByQuery(GuardianSearchList.searchListCallback, 
            		search_query, offset, this.page_size,this.clipType);
        }
    },
    searchListCallback: function (result, e) {
        GuardianUtil.hideLoading();
        if (e != null) {
            return;
        }
        $('.box_video_center').hide();
        $('.box_video_right').hide();
        $('.box_video_left').hide();
        if (result.total == null || result.total == 0) {

            if(GuardianSearchList.noresult_newspace==true){              	
            	$('.clean-error').html("No Videos found for \"" + GuardianSearchList.query + "\". You will be redirected to space page in few seconds.");
            	$('.clean-error').show();
            	$('.pagination').hide();
            	$('#guardian_SearchList').show();          	
            	setTimeout("document.location='" + GuardianSearchList.noresult_page + "?spacename="+GuardianSearchList.query+"'", 2000);
            }
            else{            
            	$('.clean-error').html("No Videos found for \"" + GuardianSearchList.query + "\". You will be redirected to home page in few seconds.");
            	$('.clean-error').show();
            	$('.pagination').hide();
            	$('#guardian_SearchList').show();
            	setTimeout("document.location='" + GuardianSearchList.noresult_page + "'", 2000);
            }            
            return;
        }
        var total = result.total;
        GuardianSearchList.pagination(total);
        var results = result.list.list;
        for (i = 0; i < results.length; i++) {
            var el = $($('#guardian_SearchList').children('div')[i + 1]);
            el = $(el).children('.box_video');
            var text = $(el).children('div .metadata');
            var img = $(el).find('div.thumb a img');
            var a = $(el).find('div.thumb a');
            $(img).attr('src', results[i].thumbnail);
            $(img).attr('alt', results[i].name);
            var linkPage = GuardianSearchList.linkpage;
            
            if(GuardianSearchList.linkpage_subchannel){
            	linkPage = Config.getSubChannelLink(results[i].subChannel.name) + GuardianSearchList.linkpage;	
            }
            
            $(a).attr('href', 'javascript:GuardianSpacePage.clickOnVideo("' + linkPage + '",{videoid:"' + results[i].id + '"})');
        	
            //$(a).attr('href', linkPage + '?videoid=' + results[i].id);
            
            var el_title = $(text).find('.meta_title a');
            var el_duration = $(text).find('.meta_duration');
            var el_owner = $(text).find('.meta_owner a');
            var el_views = $(text).find('.meta_views');
            var el_date = $(text).find('.meta_date');
            el_title.text(results[i].title);
            
            //el_title.attr('href', linkPage + '?videoid=' + results[i].id);
            
            $(el_title).attr('href', 'javascript:GuardianSpacePage.clickOnVideo("' + linkPage + '",{videoid:"' + results[i].id + '"})');
        	
            el_duration.text(GuardianUtil.formatDuration(results[i].duration));
            var cDate = "";
			if(results[i].creationDate != null)
				cDate = GuardianUtil.formatDate(results[i].creationDate.time);
            el_date.text('Add: '+cDate);
            var sname = "unknown";
            var shref = "#";
            if (results[i].space != null) {
                shref = linkPage + '?spaceid=' + results[i].space.spaceId;
                sname = results[i].space.name;
            }
            el_owner.text(sname);
            el_owner.attr('href', shref);
            if(results[i].views == null)
				results[i].views = 0;
            el_views.text('Views: ' + results[i].views);
            el.show();
            el.parent('div').show();
        }
        $('#guardian_SearchList').show();
    }
};var GuardianAccount = {
		PWD_MIN:4,
	    PWD_MAX:10, 
	 
	 	CAPTCHA_WRONG:"The verification text is wrong",
		EXISTS_USER:"The username you choose is already used. Try a new one.",
		EXISTS_EMAIL:"The email you choose is already used. Try a new one.",

	    
	    init: function(){
	    	$("#password_r").passStrength({
				userid:			"#username_r",		//required override
				shortPass: 		"top_shortPass",	//optional
				badPass:		"top_badPass",		//optional
				goodPass:		"top_goodPass",		//optional
				strongPass:		"top_strongPass",	//optional
				baseStyle:		"top_testresult",	//optional
				messageloc:		1			//before == 0 or after == 1
			});

	    },  

		register: function(){
			var f = true;
            var msg = "";
            
            $('.box_join .clean-error').hide();
            $('.box_join .clean-ok').hide();
            
            $('#email_l').css('color','black'); 
            $('#username_l').css('color','black'); 
            $('#password_l').css('color','black'); 
            $('#confirm_psw_l').css('color','black'); 
            $('#verification_l').css('color','black'); 
            
           	var email=$("#email").val();
		   	if(!GuardianUtil.validateEmail(email)){
				msg += "&#8226; The address you entered doesn't seem to be valid.<br />";
				$('#email_l').css('color','red'); 
				f=false;
			}
			
			var username=$("#username_r").val();
           	if(username == ""){
           		msg += "&#8226; The username is null.<br />";
				$('#username_l').css('color','red'); 
				f=false;
           	}
          
            var pwd=$("#password_r").val();		
			if(!this.validatePasswordLength(pwd)){
				$('#password_l').css('color','red');  
				msg += "&#8226; Password length must be between "+ this.PWD_MIN +" and "+ this.PWD_MAX + " charachters.<br />";
				f=false;
			}
           
        	if(!this.passwordCorrect("#password_r","#confirm_psw")){
				msg += "&#8226; Passwords are different. Double check them.<br />";
				$('#password_l').css('color','red'); 
				$('#confirm_psw_l').css('color','red'); 
				f=false;
			}
			
			if(!f){
				$('.box_join .clean-error').html(msg);
				$('.box_join .clean-error').fadeIn('slow');
				return;
			}
			
			var captcha=$("#verification").val();
			
			//TODO
			var gender = "M";
			var country = "";
			var birthDate = "1980-01-01";
			var zipCode = "000";
			var firstname="";
			var lastname="";
			
			GuardianUtil.showLoading();	
			
			jsonrpc.accountService.create(GuardianAccount.createCbk, username, pwd, firstname, lastname, gender, birthDate, country, email, zipCode, captcha);
	},
	
	
	createCbk: function(result, e){
	  	$('#verification').val("");
	  	
	  	GuardianUtil.hideLoading();	
        
	  	if(e != null){
	  		var error = "" + e;
	  		error = error.substring(error.indexOf(':') + 1);
	  		
	  		var msg = error;
	  		
	  		if(error.indexOf("CAPTCHA_WRONG")>0){
	  			msg = GuardianAccount.CAPTCHA_WRONG;
	  			$('#verification_l').css('color','red');
	  		}
	  		
	  		if(error.indexOf("EXISTS_USER")>0){
	  			msg = GuardianAccount.EXISTS_USER;
	  			$('#username_l').css('color','red');
	  		}
	  		
	  		if(error.indexOf("EXISTS_EMAIL")>0){
	  			msg = GuardianAccount.EXISTS_EMAIL;
	  			$('#email_l').css('color','red');
	  		}
			
			$('.box_join .clean-error').fadeIn('slow');
			$('.box_join .clean-error').html(msg);
			GuardianUtil.newCaptcha();
			return;
	  	}
	  
	  	$('.box_join .clean-ok').fadeIn('slow');
	  	
	  	//hide form
	  	$('.box_join form').hide();
		$('.box_join > div > a').hide();
		$('.box_join > p').hide();
		//GuardianAccount.reset();	
	},
	
	
	reset:function(){
		 $('#email').val(''); 
         $('#username_r').val('');
         $('#password_r').val(''); 
         $('#confirm_psw').val(''); 
         $('#verification').val(''); 
         $('.top_testresult').remove();
         GuardianUtil.newCaptcha();
	},
	
	confirmMail: function(){
		var args = GuardianUtil.getArgs(); 	 
		jsonrpc.accountService.confirmMail(GuardianAccount.confirmCbk,args.id);
	},
	
	confirmCbk: function(result,e){	
		if (e != null) {
			return;
		}	
		var el = $('#guardian_confirmMail');
		$(el).find("#username").html(result.username);
		el.fadeIn('slow');
	},
	
	passwordCorrect: function(pass,confPass){
        var pass = $(pass).val();
        var pass1 = $(confPass).val();
        return pass == pass1;
	},

	validatePasswordLength: function(password){
			var l=password.length;
			return l>=this.PWD_MIN && l<=this.PWD_MAX;
	},
	
	resetPassword: function(){
		$('.clean-error').fadeOut('slow');
		$('.clean-ok').fadeOut('slow');
		$('#password_l').css('color','black');  
		$('#confirm_psw_l').css('color','black');  
		
		var pwd=$("#password").val();
		var msg="";
		var f = true;
		if(!this.validatePasswordLength(pwd)){
			$('#password_l').css('color','red');  
			msg += "&#8226; Password length must be between "+ this.PWD_MIN +" and "+ this.PWD_MAX + " charachters.<br />";
			f=false;
		}
       
    	if(!this.passwordCorrect("#password","#password1")){
			msg += "&#8226; Passwords are different. Double check them.<br />";
			$('#password_l').css('color','red'); 
			$('#confirm_psw_l').css('color','red'); 
			f=false;
		}
		
		if(!f){
			$('.clean-error').html(msg);
			$('.clean-error').fadeIn('slow');
			return;
		}
		
		var regId = GuardianUtil.getArgs()["id"];
		
		var res = jsonrpc.accountService.changePasswordByRegId(regId,pwd);
		
		if(res == true){
			$('.clean-ok').fadeIn('slow');
		}else{
			$('.clean-error').text("Error while updating password");
			$('.clean-error').fadeIn('slow');
		}
		
		setTimeout("document.location='/'",1000);
	}
	
	
};
var GuardianAudience = {

	audience:null,
	videos:null,
	space:null,
	reloadCbk:null,
	opened:false,
	finalCbk:null,
	
	init:function(videos,space,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.videos = videos;
		GuardianAudience.space = space;
		GuardianAudience.opened = true;
		GuardianAudience.finalCbk = finalCbk;
	},
	
	getAudience:function(videoId){
		var result = jsonrpc.audienceService.getAllAudienceContact();
		GuardianAudience.audience= result.list;
	},
	
	showSendAll: function(videos, space,finalCbk){
		this.init(videos,space,finalCbk);
		this.initSendAll();
	},
	
	initSendAll: function(){
		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");
		}
		
		GuardianUtil.showModalDialog('publish_share');
	},
	
	sendAll: 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");
		}
		
		if(ids.length==0){
			 GuardianUtil.closeModalDialog();
			 if(this.finalCbk != null){
	  	    	this.finalCbk();
		     }
			 return;
		}
		jsonrpc.audienceService.sendSpace(function(result, e){
		    if(e!=null){
		       //handle exception
		       return;
		    }
		    
		    //close "send all" box
		    GuardianUtil.closeModalDialog();
		    
		    if(this.finalCbk != null){
	  	    	this.finalCbk();
		    }		    
		}, 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);
	},
	
	showSendVideo:function(videos,space,finalCbk){
		this.init(videos,space,finalCbk);
		this.initSendVideo();
	},
	
	initSendVideo: function(){
		this.getAudience();
	
	    $("#publish_share #send_friends").attr("href","javascript:GuardianAudience.sendVideo();");
	    $("#import_audience_b > a").attr("href","javascript:GuardianAudience.showImportAudience('GuardianAudience.initSendVideo();')");
        $("#publish_share .clean-alert > a").attr("href","javascript:GuardianAudience.showImportAudience('GuardianAudience.initSendVideo();')");
	    $("#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");
		}
		
		GuardianUtil.showModalDialog('publish_share');
	},
	
	sendVideo: 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 videoIds=[];
		
		for(var i=0; i< this.videos.length; i++){
		    videoIds[i]= this.videos[i].id;
		}
		
		if(ids.length==0 || videoIds.length==0){
			 GuardianUtil.closeModalDialog();
			 if(this.finalCbk != null){
	  	    	this.finalCbk();
		     }
			 return;
		}
		
		//videos[], contacts[], spaceId
		jsonrpc.audienceService.sendVideo(function(result, e){
		    if(e!=null){
		       //handle exception
		       return;
		    }
		    //close "send all" box
		    GuardianUtil.closeModalDialog();
		    
		    if(this.finalCbk != null){
		    	this.finalCbk();
		    }
		    	    
		}, videoIds, ids, this.space.spaceId);
	},
	
	showSendSpaceToFacebook: function(){
		GuardianFacebookConnector.postFeedVideos(this.space.name,this.space.spaceId,this.spaceImage, this.videos);
	},
	
	showSendVideosToFacebook: function(){
		GuardianFacebookConnector.postFeedVideos(this.space.name,this.space.spaceId,this.spaceImage, this.videos);
	},
	
	showImportAudience: function(cbk){
		$('#import_frame').attr("src","../contacts/index.jsp?type=AUDIENCE");
		$('#import_frame').css({'width':'730px','height':'458px'});
		$('#update_audience .close > a').attr("href","javascript:GuardianAudience.reloadImportAudience()");
		this.reloadCbk = cbk;
		GuardianAudience.opened = true;
		GuardianUtil.showModalDialog("update_audience");
	},
	
	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 GuardianDigest = {
    already_sign: false,
    timerId: -1,
    updates: new Array(),
    digest: null,
    CAPTCHA_WRONG: "The verification text is wrong",
    callback_name: "home",
    callback_page: "/",
    arg_digest_id: "digest_id",
    arg_callback: "callback",
    arg_callback_name: "callback_name",
    arg_passion: "passion",
    passion_setted: false,
    login_join_callback_page: 'digest',
    
    box_digest: '.box_digest',
    box_digest_spot: '.box_digest_spot',
    
    init: function () {
        if (GuardianLogin.account != null) {
            GuardianDigest.reset();
            GuardianDigest.updates["w"] = "weekly";
            GuardianDigest.updates["q"] = "quarter";
            GuardianDigest.updates["m"] = "monthly";
            $("#email").keypress(GuardianDigest.checkEmail);
            $("#send_digest a").attr("href", "javascript:GuardianDigest.sendDigest()");
            var args = GuardianUtil.getArgs();
            var digestId = args[GuardianDigest.arg_digest_id];
            var callback = args[GuardianDigest.arg_callback];
            var callback_name = args[GuardianDigest.arg_callback_name];
            var passion = args[GuardianDigest.arg_passion];
            if (callback != null && callback_name != null) {
                GuardianDigest.callback_page = callback;
                GuardianDigest.callback_name = callback_name;
                $(".clean-ok > small > span").text(callback_name);
            } else {
                $(".clean-ok > small > span").text(GuardianDigest.callback_name);
            }
            if (passion != null) {
                GuardianDigest.passion_setted = true;
                $("#your_passion").val(passion);
            } else {
                GuardianDigest.passion_setted = false;
            }
            if (digestId != null) {
                GuardianDigest.getDigestById(digestId);
            } else { if (GuardianLogin.account.email != "") {
                    $("#email").val(GuardianLogin.account.email);
                    $("#name").val(GuardianLogin.account.firstName);
                    $("#last_name").val(GuardianLogin.account.lastName);
                    GuardianDigest.checkEmail();
                }
            }
            $(GuardianDigest.box_digest).show();
            $(GuardianDigest.box_digest_spot).show();
            
        } else {
            var page = GuardianDigest.login_join_callback_page;
            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(2)").attr("href", joinpage);
            $(".list3").children().hide();
            $("#no_account").show();
        }
    },
    reset: function () {
        $(".box_digest").find("input").attr("disabled", true);
        $("#email").attr("disabled", false);
        $("#email").val("");
        $("#your_passion").val("");
        $("#name").val("");
        $("#last_name").val("");
        $("#verification").val("");
        $($("input[name='period']")[0]).attr("checked", true);
        $(".text-ok").hide();
        GuardianUtil.newCaptcha();
    },
    checkEmail: function () {
        if (GuardianUtil.validateEmail($("#email").val())) {
            if (GuardianDigest.timerId != -1) {
                clearTimeout(GuardianDigest.timerId);
            }
            GuardianDigest.timerId = setTimeout(GuardianDigest.getDigestInfo, 1000);
        }
    },
    confirmDigest: function () {
        var args = GuardianUtil.getArgs();
        jsonrpc.digestService.confirmDigest(GuardianDigest.confirmDigestCallback, args.id);
    },
    confirmDigestCallback: function (result, e) {
        if (e != null) {
            return;
        }
        var el = $("#guardian_confirmDigest");
        $(el).find("#username").html(result);
        el.fadeIn("slow");
    },
    getDigestInfo: function () {
        var email = $("#email").val();
        jsonrpc.digestService.getDigestByEmail(GuardianDigest.getDigestInfoCallback, email);
    },
    getDigestById: function (digestId) {
        jsonrpc.digestService.getDigestById(GuardianDigest.getDigestInfoCallback, digestId);
    },
    getDigestInfoCallback: function (result, e) {
        if (e != null) {
            return;
        }
        if (result == null) {
            GuardianDigest.setNewDigest();
        } else {
            $("#text-ok_loading").show();
            GuardianDigest.digest = result;
            setTimeout(GuardianDigest.setDigest, 1000);
        }
    },
    setNewDigest: function () {
        $(".box_digest").find("input").attr("disabled", false);
        $(".text-ok").hide();
        $("#update_digest").hide();
        $("#subscribe_digest").show();
        GuardianDigest.already_sign = false;
    },
    setDigest: function () {
        var digest = GuardianDigest.digest;
        $(".box_digest").find("input").attr("disabled", false);
        $("#email").val(digest.email);
        if (!GuardianDigest.passion_setted) {
            $("#your_passion").val(digest.passion);
        }
        $("#name").val(digest.name);
        $("#last_name").val(digest.lastName);
        var arrayRadio = $("input[name='period']");
        var control = false;
        for (i = 0; i < arrayRadio.length; i++) {
            if (!control) {
                var v = $($("input[name='period']")[i]).val();
                if (GuardianDigest.updates[v] == digest.updates) {
                    $($("input[name='period']")[i]).attr("checked", true);
                    control = true;
                }
            }
        }
        if (!control) {
            $($("input[name='period']")[0]).attr("checked", true);
        }
        $("#subscribe_digest").hide();
        $("#update_digest").show();
        GuardianDigest.already_sign = true;
        $("#text-ok_loading").hide();
        $("#text-ok_loaded").show();
    },
    sendDigest: function () {
        $(".clean-error").fadeOut("slow");
        var email = $("#email").val();
        var passion = $("#your_passion").val();
        var name = $("#name").val();
        var lastName = $("#last_name").val();
        var verification = $("#verification").val();
        var v = $($("input[name='period']:checked")).val();
        var updates = GuardianDigest.updates[v];
        GuardianUtil.showLoading();
        if (GuardianDigest.already_sign) {
            jsonrpc.digestService.updateDigest(GuardianDigest.sendDigestCallback, email, passion, name, lastName, updates, verification);
        } else {
            jsonrpc.digestService.createDigest(GuardianDigest.sendDigestCallback, email, passion, name, lastName, updates, verification);
        }
        $("#verification").val("");
    },
    sendDigestCallback: function (result, e) {
        GuardianUtil.newCaptcha();
        GuardianUtil.hideLoading();
        if (e != null) {
            var msg = "" + e;
            msg = msg.substring(msg.indexOf(":") + 2);
            if (msg.toLowerCase() == "the captcha is wrong".toLowerCase()) {
                $(".spacer").css("color", "red");
                $(".clean-error").text(GuardianDigest.CAPTCHA_WRONG);
                $(".clean-error").fadeIn("slow");
            }
            return;
        }
        $("#digest_form").hide();
        if (GuardianDigest.already_sign) {
            $("#clean-ok_upd").show();
        } else {
            $("#clean-ok_sub").show();
        }
        setTimeout(GuardianDigest.goToCallback, 2000);
    },
    goToCallback: function () {
        document.location.href = GuardianDigest.callback_page;
    }
};var GuardianProfile = {

	user_id: -1,
	user: null,	
	
	spaces_filter_1: "ALL",
	spaces_order_1: "ORDER_ADDED",
	
	spaces_subscribed_1: null,
	spaces_size_1: 10,
	spaces_name_1: 'Spaces',
	spaces_page_1: 1,
	spaces_page_size_1: 10,
	spaces_page_container_1: '.subspace > .subscribed',
	
	spaces_subscribed_2: null,
	spaces_size_2: 10,
	spaces_name_2: 'Subscriptions',
	spaces_page_2: 1,
	spaces_page_size_2: 10,
	spaces_page_container_2: '.subspace > .subscribed2',
	
	comments_page: 1,
	comments_page_size: 10,
	comments_size: 10,
	comments_container: '.box_under > .comments_big',
	
	video_page_url: 'space.page?videoid=',
	
	space_page_url: 'space.page?spaceid=',
	
	init: function(){		
		
		var args = GuardianUtil.getArgs();
		var uid = args['userid'];
		
		if(uid!=null){
		
			GuardianProfile.spaces_subscribed_1=$('.subspace > .subscribed');
			GuardianProfile.spaces_subscribed_2=$('.subspace > .subscribed2');
						
			$('#more_space_subscribed a').attr('href','javascript:GuardianProfile.moreSpaces1()');	
			$('#more_space_subscribed2 a').attr('href','javascript:GuardianProfile.moreSpaces2()');
			$('#more_comments a').attr('href','javascript:GuardianProfile.moreComments()');							
		
			GuardianProfile.user_id = uid;
			GuardianProfile.getUserInfo();
		}
		else{
			$('#alert_no_profile').show();
		}		
	},
	
	getUserInfo: function(){
		jsonrpc.members.getProfile(GuardianProfile.getUserInfoCallback,GuardianProfile.user_id);
	},
	
	getUserInfoCallback: function(result, e){
		if(e!=null){
			return;
		}
		
		if(result==null){
			return;
		}
		
		var user = result.owner;
		GuardianProfile.user = user;
		
		var box = null;
		if(user.external){
			box = $('#prof_info_fb');
			$(box).find('.img_profile_fb > img').attr('src',user.imageUrl);
		}
		else{
			box = $('#prof_info');
			$(box).find('.img_profile > img').attr('src',user.imageUrl);
		}
		
		$(box).find('.nick').text(user.username+'\'s profile');
		$(box).find('.details_colm1 .details_username').text(user.username);
		$(box).find('.details_colm1 .details_date').text('Joined: '+user.registerDate);
		
		
		$(box).fadeIn("slow");		
		
		GuardianProfile.getUserSpaceInfo();
		if($(GuardianProfile.comments_container).length > 0){
			GuardianProfile.getUserComment();
		}
	},
	
	getUserComment: function(){	
	
		GuardianProfile.comments_page = 1;
		
		jsonrpc.members.getCommentsByAccountId(GuardianProfile.getUserCommentCallback, 
													GuardianProfile.user_id, 
													GuardianProfile.comments_page, 
													GuardianProfile.comments_page_size);
	},
	
	getUserCommentCallback: function(result, e){
		if(e!=null){
			return;
		}
		if(result==null){
			return;
		}
		
		GuardianProfile.writeComments(result.list.list, result.total);
	},
	
	writeComments: function(comments, total){
		
		var comment_container = $(GuardianProfile.comments_container);
		
		$(comment_container).children('.title').text(GuardianProfile.user.username+'\'s Comments');
		
		var comment_box = $(comment_container).find('#single_comments_box');
		
		var single_comment_box = $(comment_container).find('.single_comments:eq(0)');
		
		var n = Math.min(GuardianProfile.comments_size, total);
		
		for(var i=0; i<comments.length; i++){
			var comment = comments[i];
			
			var el_comment = $(single_comment_box).clone();
			
			$(el_comment).find('.video_title > a').text(comment.video.title);
			$(el_comment).find('.video_title > a').attr('href',GuardianProfile.video_page_url+comment.video.id);
			$(el_comment).find('.date').text('('+comment.commentAddDate+')');
			$(el_comment).find('.body_comment').text(comment.comment);
			
			$(el_comment).show();
			
			$(comment_box).append(el_comment);
			
		}
					
		if(n<total){
			$(comment_container).find('#more_comments').show();
		}
		else{
			$(comment_container).find('#more_comments').hide();		
		}
		
		if($('.box_under').css('display').toLowerCase()=='none'){
			$('.box_under').fadeIn('slow');
		}
		if($(comment_container).css('display').toLowerCase()=='none'){
			$(comment_container).fadeIn('slow');
		}
	},
	
	getUserSpaceInfo: function(){

		GuardianProfile.spaces_page_1 = 1;
		GuardianProfile.spaces_page_2 = 1;
	
		if(GuardianProfile.spaces_subscribed_1.length>0){
			jsonrpc.spaceService.getSpacesByAccount(GuardianProfile.getSpacesByAccountCallback, 
													GuardianProfile.user_id, 
													GuardianProfile.spaces_order_1, 
													GuardianProfile.spaces_filter_1,
													GuardianProfile.spaces_page_1,
													GuardianProfile.spaces_size_1);
		}									
		if(GuardianProfile.spaces_subscribed_2.length>0){
			jsonrpc.subscriptionService.getSubscriptionsByAccountId(GuardianProfile.getSubscriptionsByAccountCallback, 
													GuardianProfile.user_id,
													GuardianProfile.spaces_page_2,
													GuardianProfile.spaces_size_2);
		}
	},
	
	getSpacesByAccountCallback: function(result, e){
		if(e!=null){
			return;
		}
		
		if(result==null){
			return;
		}
		
		GuardianProfile.writeSpace(GuardianProfile.spaces_subscribed_1, 
										result.list.list, 
										GuardianProfile.spaces_size_1, 
										GuardianProfile.spaces_name_1,
										result.total);		
	},
	
	getSubscriptionsByAccountCallback: function(result, e){
		if(e!=null){
			return;
		}
		
		if(result==null){
			return;
		}
		
		var array = new Array();
		
		for(var i=0; i<result.list.list.length; i++){
			array[i]=result.list.list[i].space;
		}
		
		
		GuardianProfile.writeSpace(GuardianProfile.spaces_subscribed_2, 
										array, 
										GuardianProfile.spaces_size_2,
										GuardianProfile.spaces_name_2,
										result.total);
		
	},
	
	writeSpace: function(subscribed_box, spaces, spaces_size, name, total){
	
		if(spaces!=null){
		
			var space_box = $(subscribed_box).find('.single_space_box');
			var single_space_box = $(subscribed_box).find('.single_space:eq(0)');
		
			$(subscribed_box).children('.title').text(GuardianProfile.user.username+'\'s '+name);
			
			var n = Math.min(spaces_size, total);
			
			for(var i=0; i<spaces.length; i++){
				var space=spaces[i];
				
				var el_space = $(single_space_box).clone();
				$(el_space).find('a').text(space.name);
				$(el_space).find('a').attr('href',GuardianProfile.space_page_url+space.spaceId);
		
				
				$(el_space).show();
				
				$(space_box).append(el_space);
			}	
			
			if(n<total){
				$(subscribed_box).find('.name_space_box > .single_space:eq(1)').show();
			}
			else{
				$(subscribed_box).find('.name_space_box > .single_space:eq(1)').hide();
			}
			
			if($(subscribed_box).css('display').toLowerCase()=='none'){
				$(subscribed_box).fadeIn('slow');
			}
		}
	},
	
	moreSpaces1: function(){
	
		GuardianProfile.spaces_page_1++;
		
		GuardianProfile.spaces_size_1+= GuardianProfile.spaces_page_size_1;
		
		jsonrpc.spaceService.getSpacesByAccount(GuardianProfile.getSpacesByAccountCallback, 
													GuardianProfile.user_id, 
													GuardianProfile.spaces_order_1, 
													GuardianProfile.spaces_filter_1,
													GuardianProfile.spaces_page_1,
													GuardianProfile.spaces_page_size_1);
											

	},
	
	moreSpaces2: function(){
	
		GuardianProfile.spaces_page_2++;
		
		GuardianProfile.spaces_size_2+= GuardianProfile.spaces_page_size_2;
			
		jsonrpc.subscriptionService.getSubscriptionsByAccountId(GuardianProfile.getSubscriptionsByAccountCallback, 
													GuardianProfile.user_id,
													GuardianProfile.spaces_page_2,
													GuardianProfile.spaces_page_size_2);
	},
	
	moreComments: function(){
		GuardianProfile.comments_page++;
		
		GuardianProfile.comments_size+= GuardianProfile.comments_page_size;
		
		jsonrpc.members.getCommentsByAccountId(GuardianProfile.getUserCommentCallback, 
													GuardianProfile.user_id, 
													GuardianProfile.comments_page, 
													GuardianProfile.comments_page_size);
	}
};var GuardianProfileEdit = {
    facebook_edit_page: "http://www.facebook.com/editaccount.php",
    digest_page: "digest.page?digest_id=",
    close_message: "Are you sure you want to close your account?",
    close_message_f: "Are you sure you want to delete your contents?",
    close_ok_message: "Your account was successfully removed. You will be redirected to home page in few seconds.",
    close_ok_message_f: "Your contents were successfully removed. You will be redirected to home page in few seconds.",
    change_image_message: "Your image was successfully updated.",
    profile_sel: "#content_all > .prof_info",
    spaces_filter_1: "ALL",
    spaces_order_1: "ORDER_ADDED",
    spaces_subscribed_1: null,
    spaces_size_1: 10,
    spaces_name_1: "Spaces",
    spaces_page_1: 1,
    spaces_page_size_1: 10,
    spaces_edit_link_1: "space_name.page?spaceid=#",
    spaces_remove_link_1: "javascript:GuardianProfileEdit.removeSpace(#)",
    spaces_remove_message_1: "Are you sure you want to remove this space?",
    spaces_message_sel_1: ".subspace_1 > .subscribed",
    spaces_subscribed_2: null,
    spaces_size_2: 10,
    spaces_name_2: "Subscriptions",
    spaces_page_2: 1,
    spaces_page_size_2: 10,
    spaces_edit_link_2: "",
    spaces_remove_link_2: "javascript:GuardianProfileEdit.removeSubscription(#)",
    spaces_remove_message_2: "Are you sure you want to remove this subscription?",
    spaces_message_sel_2: ".subspace > .subscribed2",
    comments_page: 1,
    comments_page_size: 10,
    comments_size: 10,
    comment_remove_message: "Are you sure you want to remove this comment?",
    comments_message_sel: ".box_under > .comments_big",
    digests_page_size: 10,
    digests_size: 10,
    digests: null,
    digests_callback: "profile_edit.page",
    digests_callback_name: "profile edit",
    digest_remove_message: "Are you sure you want to remove this digest?",
    digests_message_sel: ".subspace > .subscribed",
    audiences_increment_size: 10,
    audiences_size: 10,
    audiences: null,
    audience_remove_message: "Are you sure you want to remove this contact?",
    audience_remove_message_ok: "Your contact was successfully deleted",
    audience_remove_message_error: "There was an error during the removal of the contact, please try again later.",
    audiences_message_sel: ".box_under > .audience",
    audience_remove_ok: "Your contact was successfully deleted.",
    audience_update_ok: "Your contacts were successfully updated.",
    video_page_url: "space.page?videoid=",
    space_page_url: "space.page?spaceid=",
    image_url: "",
    no_account_page: "/",
    init: function () {
        if (GuardianLogin.account != null) {
            var user = GuardianLogin.account;
            GuardianProfileEdit.spaces_subscribed_1 = $(GuardianProfileEdit.spaces_message_sel_1);
            GuardianProfileEdit.spaces_subscribed_2 = $(GuardianProfileEdit.spaces_message_sel_2);
            $("#more_space_subscribed a").attr("href", "javascript:GuardianProfileEdit.moreSpaces1()");
            $("#more_space_subscribed2 a").attr("href", "javascript:GuardianProfileEdit.moreSpaces2()");
            $("#more_comments a").attr("href", "javascript:GuardianProfileEdit.moreComments()");
            $("#more_contacts a").attr("href", "javascript:GuardianProfileEdit.moreAudiences()");
            var box = null;
            if (user.external) {
                box = $("#prof_edit_fb");
                $("#prof_edit").remove();
                $(box).find(".img_profile_fb > img").attr("src", user.imageUrl);
                $(box).find("#change_img").attr("href", GuardianProfileEdit.facebook_edit_page);
                $(box).find("#change_img").attr("target", "_blank");
                var c_link = "javascript:GuardianUtil.confirmDialog(GuardianProfileEdit.close_message_f,'GuardianProfileEdit.closeAccount()')";
                $(box).find("#close_account").attr("href", c_link);
            } else {
                box = $("#prof_edit");
                $("#prof_edit_fb").remove();
                $(box).find(".img_profile > img").attr("src", user.imageUrl);
                $(box).find("#change_img").attr("href", "javascript:GuardianUtil.showModalDialog('change_img_dialog')");
                var c_link = "javascript:GuardianUtil.confirmDialog(GuardianProfileEdit.close_message,'GuardianProfileEdit.closeAccount()')";
                $(box).find("#close_account").attr("href", c_link);
            }
            $(box).find(".nick").text(user.username + "'s profile");
            $(box).find(".details_colm1 .details_username").text(user.username);
            $(box).find(".details_colm1 .details_date").text("Joined: " + user.registerDate);
            $(box).fadeIn("slow");
            $(".audience > .title > .update > a").attr("href", "javascript:GuardianProfileEdit.openImportAudience()");
            $(".audience > .box_border > .clean-alert > a").attr("href", "javascript:GuardianProfileEdit.openImportAudience()");
          
            if($(GuardianProfileEdit.spaces_subscribed_1).length > 0 && $(GuardianProfileEdit.spaces_subscribed_2).length > 0){
            	GuardianProfileEdit.getUserSpaceInfo();
            }
            if($(GuardianProfileEdit.comments_message_sel).length > 0){
            	GuardianProfileEdit.getUserComment();
            }
            if($(GuardianProfileEdit.audiences_message_sel).length > 0){
            	GuardianProfileEdit.getAudience();
            }
            if($(GuardianProfileEdit.digests_message_sel).length > 0){
            	GuardianProfileEdit.getDigests();
            }
        } else {
            document.location = GuardianProfileEdit.no_account_page;
        }
        $("#change_img_dialog").css("width", "380px");
        $("#update_audience").css("width", "800px");
    },
    getDigests: function () {
        jsonrpc.digestService.getMyDigests(GuardianProfileEdit.getDigestsCallback);
    },
    getDigestsCallback: function (result, e) {
        if (e != null) {
            return;
        }
        if (result == null) {
            return;
        }
        GuardianProfileEdit.digests = result.list.list;
        $(".subspace > .subscribed > .box_border > .name_digest_box > .single_digest_box").empty();
        GuardianProfileEdit.writeDigest(0);
    },
    writeDigest: function (from) {
        var digests_container = $(GuardianProfileEdit.digests_message_sel);
        var box = $(digests_container).find(".box_border > .name_digest_box > .single_digest_box");
        var el = $(digests_container).find(".box_border > .name_digest_box > .single_digest:eq(0)");
        var total = GuardianProfileEdit.digests.length;
        var n = Math.min(GuardianProfileEdit.digests_size, total);
        for (var i = from; i < n; i++) {
            var digest = GuardianProfileEdit.digests[i];
            var el_a = $(el).clone();
            $(el_a).show();
            $(el_a).find(".digest_name > #passion > strong").text(digest.passion);
            $(el_a).find(".digest_name > #email > strong").text(digest.email);
            $(el_a).find(".digest_name > #updates > strong").text(digest.updates);
            var r_link = "javascript:GuardianUtil.confirmDialog(GuardianProfileEdit.digest_remove_message,'GuardianProfileEdit.removeDigest(" + digest.id + ")')";
            $(el_a).find(".remove a").attr("href", r_link);
            var e_link = GuardianProfileEdit.digest_page + digest.id + "&callback=" + GuardianProfileEdit.digests_callback + "&callback_name=" + GuardianProfileEdit.digests_callback_name;
            $(el_a).find(".edit a").attr("href", e_link);
            $(box).append(el_a);
        }
        if (n < total) {
            $(digests_container).find("#more_digest_subscribed").show();
        } else {
            $(digests_container).find("#more_digest_subscribed").hide();
        }
        if ($(".box_under").css("display").toLowerCase() == "none") {
            $(".box_under").fadeIn("slow");
        }
        if ($(digests_container).css("display").toLowerCase() == "none") {
            $(digests_container).fadeIn("slow");
        }
        if (GuardianProfileEdit.digests.length == 0) {
            var space_box = $(digests_container).find(".clean-alert").show();
        } else {
            var space_box = $(digests_container).find(".clean-alert").hide();
        }
    },
    getAudience: function () {
        jsonrpc.audienceService.getAllAudienceContact(GuardianProfileEdit.getAudienceCallback);
    },
    getAudienceCallback: function (result, e) {
        if (e != null) {
            return;
        }
        if (result == null) {
            return;
        }
        GuardianProfileEdit.audiences = result.list;
        $(".audience > .box_border > #single_contacts_box").empty();
        GuardianProfileEdit.writeAudience(0);
    },
    writeAudience: function (from) {
        var audience_container = $(GuardianProfileEdit.audiences_message_sel);
        var total = GuardianProfileEdit.audiences.length;
        var box = $(audience_container).find(".box_border > #single_contacts_box");
        var el = $(audience_container).find(".box_border > .user_mail:eq(0)");
        var n = Math.min(GuardianProfileEdit.audiences_size, total);
        for (var i = from; i < n; i++) {
            var audience = GuardianProfileEdit.audiences[i];
            var el_a = $(el).clone();
            $(el_a).show();
            $(el_a).find(".user_contact").text(audience.contact);
            var r_link = "javascript:GuardianUtil.confirmDialog(GuardianProfileEdit.audience_remove_message,'GuardianProfileEdit.removeAudienceContact(" + audience.id + ")')";
            $(el_a).find(".remove_contact a").attr("href", r_link);
            $(box).append(el_a);
        }
        if (n < total) {
            $(audience_container).find("#more_contacts").show();
        } else {
            $(audience_container).find("#more_contacts").hide();
        }
        if ($(".box_under").css("display").toLowerCase() == "none") {
            $(".box_under").fadeIn("slow");
        }
        if ($(audience_container).css("display").toLowerCase() == "none") {
            $(audience_container).fadeIn("slow");
        }
        if (GuardianProfileEdit.audiences.length == 0) {
            var space_box = $(audience_container).find(".clean-alert").show();
        } else {
            var space_box = $(audience_container).find(".clean-alert").hide();
        }
    },
    getUserSpaceInfo: function () {
        GuardianProfileEdit.getUserSpace1();
        GuardianProfileEdit.getUserSpace2();
    },
    getUserSpace1: function () {
        GuardianProfileEdit.spaces_page_1 = 1;
        jsonrpc.spaceService.getSpacesByAccount(GuardianProfileEdit.getSpacesByAccountCallback, GuardianLogin.account.id, GuardianProfileEdit.spaces_order_1, GuardianProfileEdit.spaces_filter_1, GuardianProfileEdit.spaces_page_1, GuardianProfileEdit.spaces_size_1);
    },
    getUserSpace2: function () {
        GuardianProfileEdit.spaces_page_2 = 1;
        jsonrpc.subscriptionService.getSubscriptionsByAccountId(GuardianProfileEdit.getSubscriptionsByAccountCallback, GuardianLogin.account.id, GuardianProfileEdit.spaces_page_2, GuardianProfileEdit.spaces_size_2);
    },
    getUserComment: function () {
        GuardianProfileEdit.comments_page = 1;
        var comment_container = $(".box_under > .comments_big");
        var comment_box = $(comment_container).find("#single_comments_box");
        $(comment_box).empty();
        jsonrpc.members.getCommentsByAccountId(GuardianProfileEdit.getUserCommentCallback, GuardianLogin.account.id, GuardianProfileEdit.comments_page, GuardianProfileEdit.comments_page_size);
    },
    getUserCommentCallback: function (result, e) {
        if (e != null) {
            return;
        }
        if (result == null) {
            return;
        }
        GuardianProfileEdit.writeComments(result.list.list, result.total);
    },
    writeComments: function (comments, total) {
        var comment_container = $(GuardianProfileEdit.comments_message_sel);
        var comment_box = $(comment_container).find("#single_comments_box");
        var single_comment_box = $(comment_container).find(".single_comments:eq(0)");
        var n = Math.min(GuardianProfileEdit.comments_size, total);
        for (var i = 0; i < comments.length; i++) {
            var comment = comments[i];
            var el_comment = $(single_comment_box).clone();
            $(el_comment).find(".video_title > a").text(comment.video.title);
            $(el_comment).find(".video_title > a").attr("href", GuardianProfileEdit.video_page_url + comment.video.id);
            $(el_comment).find(".date").text("(" + comment.commentAddDate + ")");
            $(el_comment).find(".body_comment").text(comment.comment);
            var r_link = "javascript:GuardianUtil.confirmDialog(GuardianProfileEdit.comment_remove_message,'GuardianProfileEdit.removeComment(" + comment.commentId + ")')";
            $(el_comment).find(".remove_comment a").attr("href", r_link);
            $(el_comment).show();
            $(comment_box).append(el_comment);
        }
        if (n < total) {
            $(comment_container).find("#more_comments").show();
        } else {
            $(comment_container).find("#more_comments").hide();
        }
        if ($(".box_under").css("display").toLowerCase() == "none") {
            $(".box_under").fadeIn("slow");
        }
        if ($(comment_container).css("display").toLowerCase() == "none") {
            $(comment_container).fadeIn("slow");
        }
        if (comments.length == 0) {
            var space_box = $(comment_container).find(".clean-alert").show();
        } else {
            var space_box = $(comment_container).find(".clean-alert").hide();
        }
    },
    getSpacesByAccountCallback: function (result, e) {
        if (e != null) {
            return;
        }
        if (result == null) {
            return;
        }
        var space_box = $(GuardianProfileEdit.spaces_subscribed_1).find(".single_space_box");
        $(space_box).empty();
        GuardianProfileEdit.writeSpace(GuardianProfileEdit.spaces_subscribed_1, result.list.list, GuardianProfileEdit.spaces_size_1, GuardianProfileEdit.spaces_name_1, result.total, GuardianProfileEdit.spaces_edit_link_1, GuardianProfileEdit.spaces_remove_link_1, GuardianProfileEdit.spaces_remove_message_1);
    },
    getSubscriptionsByAccountCallback: function (result, e) {
        if (e != null) {
            return;
        }
        if (result == null) {
            return;
        }
        var space_box = $(GuardianProfileEdit.spaces_subscribed_2).find(".single_space_box");
        $(space_box).empty();
        var array = new Array();
        for (var i = 0; i < result.list.list.length; i++) {
            array[i] = result.list.list[i].space;
        }
        GuardianProfileEdit.writeSpace(GuardianProfileEdit.spaces_subscribed_2, array, GuardianProfileEdit.spaces_size_2, GuardianProfileEdit.spaces_name_2, result.total, GuardianProfileEdit.spaces_edit_link_2, GuardianProfileEdit.spaces_remove_link_2, GuardianProfileEdit.spaces_remove_message_2);
    },
    writeSpace: function (subscribed_box, spaces, spaces_size, name, total, linkEdit, linkRemove, removeMessage) {
        if (spaces != null) {
            var space_box = $(subscribed_box).find(".single_space_box");
            var single_space_box = $(subscribed_box).find(".single_space:eq(0)");
            var n = Math.min(spaces_size, total);
            for (var i = 0; i < spaces.length; i++) {
                var space = spaces[i];
                var el_space = $(single_space_box).clone();
                $(el_space).find(".space_name > a").text(space.name);
                $(el_space).find(".space_name > a").attr("href", GuardianProfileEdit.space_page_url + space.spaceId);
                if (linkEdit.length > 0) {
                    $(el_space).find(".edit > a").attr("href", linkEdit.replace(/#/g, space.spaceId));
                }
                if (linkRemove.length > 0) {
                    var r_link = "javascript:GuardianUtil.confirmDialog('" + removeMessage + "','" + linkRemove.replace(/#/g, space.spaceId) + "')";
                    $(el_space).find(".remove > a").attr("href", r_link);
                }
                $(el_space).show();
                $(space_box).append(el_space);
            }
            if (n < total) {
                $(subscribed_box).find(".name_space_box > .single_space:eq(1)").show();
            } else {
                $(subscribed_box).find(".name_space_box > .single_space:eq(1)").hide();
            }
            if ($(subscribed_box).css("display").toLowerCase() == "none") {
                $(subscribed_box).fadeIn("slow");
            }
            if (spaces.length == 0) {
                var space_box = $(subscribed_box).find(".clean-alert").show();
            } else {
                var space_box = $(subscribed_box).find(".clean-alert").hide();
            }
        }
    },
    changeImage: function () {
        GuardianUtil.closeModalDialog();
        GuardianProfileEdit.hideAllMessages();
        var image = $("#change_img_dialog > .content > form > .text_field").val();
        GuardianProfileEdit.image_url = image;
        jsonrpc.accountService.changeImageUrl(GuardianProfileEdit.changeImageCallback, image);
    },
    changeImageCallback: function (result, e) {
        if (e != null) {
            return;
        }
        $(GuardianProfileEdit.profile_sel).find(".clean-ok").text(GuardianProfileEdit.change_image_message);
        GuardianProfileEdit.showOkMessage(GuardianProfileEdit.profile_sel);
        $(".img_profile > img").attr("src", GuardianProfileEdit.image_url);
    },
    moreSpaces1: function () {
        GuardianProfileEdit.spaces_page_1++;
        GuardianProfileEdit.spaces_size_1 += GuardianProfileEdit.spaces_page_size_1;
        jsonrpc.spaceService.getSpacesByAccount(GuardianProfileEdit.getSpacesByAccountCallback, GuardianLogin.account.id, GuardianProfileEdit.spaces_order_1, GuardianProfileEdit.spaces_filter_1, GuardianProfileEdit.spaces_page_1, GuardianProfileEdit.spaces_page_size_1);
    },
    moreSpaces2: function () {
        GuardianProfileEdit.spaces_page_2++;
        GuardianProfileEdit.spaces_size_2 += GuardianProfileEdit.spaces_page_size_2;
        jsonrpc.subscriptionService.getSubscriptionsByAccountId(GuardianProfileEdit.getSubscriptionsByAccountCallback, GuardianLogin.account.id, GuardianProfileEdit.spaces_page_2, GuardianProfileEdit.spaces_page_size_2);
    },
    moreComments: function () {
        GuardianProfileEdit.comments_page++;
        GuardianProfileEdit.comments_size += GuardianProfileEdit.comments_page_size;
        jsonrpc.members.getCommentsByAccountId(GuardianProfileEdit.getUserCommentCallback, GuardianLogin.account.id, GuardianProfileEdit.comments_page, GuardianProfileEdit.comments_page_size);
    },
    moreAudiences: function () {
        var hold = GuardianProfileEdit.audiences_size;
        GuardianProfileEdit.audiences_size += GuardianProfileEdit.audiences_increment_size;
        GuardianProfileEdit.writeAudience(hold);
    },
    moreDigests: function () {
        var hold = GuardianProfileEdit.digests_size;
        GuardianProfileEdit.digests_size += GuardianProfileEdit.digests_increment_size;
        GuardianProfileEdit.writeDigests(hold);
    },
    removeComment: function (commentId) {
        GuardianProfileEdit.hideAllMessages();
        jsonrpc.videoPageService.deleteComment(GuardianProfileEdit.removeCommentCallback, commentId);
    },
    removeCommentCallback: function (result, e) {
        if (e != null) {
            return;
            GuardianProfileEdit.showErrorMessage(GuardianProfileEdit.comments_message_sel);
        }
        GuardianProfileEdit.getUserComment();
        GuardianProfileEdit.showOkMessage(GuardianProfileEdit.comments_message_sel);
    },
    removeSpace: function (spaceId) {
        GuardianProfileEdit.hideAllMessages();
        jsonrpc.spaceService.deleteSpace(GuardianProfileEdit.removeSpaceCallback, spaceId);
    },
    removeSpaceCallback: function (result, e) {
        if (e != null) {
            return;
            GuardianProfileEdit.showErrorMessage(GuardianProfileEdit.spaces_message_sel_1);
        }
        GuardianProfileEdit.getUserSpace1();
        GuardianProfileEdit.showOkMessage(GuardianProfileEdit.spaces_message_sel_1);
    },
    removeSubscription: function (spaceId) {
        GuardianProfileEdit.hideAllMessages();
        jsonrpc.subscriptionService.unsubscribe(GuardianProfileEdit.removeSubscriptionCallback, spaceId);
    },
    removeSubscriptionCallback: function (result, e) {
        if (e != null) {
            return;
            GuardianProfileEdit.showErrorMessage(GuardianProfileEdit.spaces_message_sel_2);
        }
        GuardianProfileEdit.getUserSpace2();
        GuardianProfileEdit.showOkMessage(GuardianProfileEdit.spaces_message_sel_2);
    },
    removeAudienceContact: function (audienceId) {
        GuardianProfileEdit.hideAllMessages();
        jsonrpc.audienceService.removeAudienceContact(GuardianProfileEdit.removeAudienceContactCallback, audienceId);
    },
    removeAudienceContactCallback: function (result, e) {
        if (e != null) {
            return;
            GuardianProfileEdit.showErrorMessage(GuardianProfileEdit.audiences_message_sel);
        }
        GuardianProfileEdit.getAudience();
        $(GuardianProfileEdit.audiences_message_sel).find(".clean-ok").text(GuardianProfileEdit.audience_remove_ok);
        GuardianProfileEdit.showOkMessage(GuardianProfileEdit.audiences_message_sel);
    },
    removeDigest: function (disgetId) {
        GuardianProfileEdit.hideAllMessages();
        jsonrpc.digestService.deleteDigest(GuardianProfileEdit.removeDigestCallback, disgetId);
    },
    removeDigestCallback: function (result, e) {
        if (e != null) {
            return;
            GuardianProfileEdit.showErrorMessage(GuardianProfileEdit.digests_message_sel);
        }
        GuardianProfileEdit.getDigests();
        GuardianProfileEdit.showOkMessage(GuardianProfileEdit.digests_message_sel);
    },
    openImportAudience: function () {
        GuardianAudience.showImportAudience("GuardianProfileEdit.closeImportAudience()");
    },
    closeImportAudience: function () {
        GuardianUtil.closeModalDialog();
        GuardianProfileEdit.getAudience();
        $(GuardianProfileEdit.audiences_message_sel).find(".clean-ok").text(GuardianProfileEdit.audience_update_ok);
        GuardianProfileEdit.showOkMessage(GuardianProfileEdit.audiences_message_sel);
    },
    hideAllMessages: function () {
        $(".clean-ok:visible").fadeOut("slow");
        $(".clean-error:visible").fadeOut("slow");
    },
    hideAllMessages: function (mainSelector) {
        $(mainSelector).find(".clean-ok:visible").fadeOut("slow");
        $(mainSelector).find(".clean-error:visible").fadeOut("slow");
    },
    showOkMessage: function (mainSelector) {
        $(mainSelector).find(".clean-ok").fadeIn("slow");
    },
    showErrorMessage: function (mainSelector) {
        $(mainSelector).find(".clean-error").fadeIn("slow");
    },
    closeAccount: function () {
        GuardianProfileEdit.hideAllMessages();
        jsonrpc.accountService.closeAccount(GuardianProfileEdit.closeAccountCallback, "");
    },
    closeAccountCallback: function (result, e) {
        if (e != null) {
            return;
        }
        if (GuardianLogin.account != null) {
            if (GuardianLogin.account.external) {
                $(GuardianProfileEdit.profile_sel).find(".clean-ok").text(GuardianProfileEdit.close_ok_message_f);
            } else {
                $(GuardianProfileEdit.profile_sel).find(".clean-ok").text(GuardianProfileEdit.close_ok_message);
            }
        }
        GuardianProfileEdit.showOkMessage(GuardianProfileEdit.profile_sel);
        setTimeout("GuardianProfileEdit.goAway()", 2000);
    },
    goAway: function () {
        GuardianLogin.logout();
        document.location.href = "/";
    }
};
var GuardianSpaceList = {
	page: 1,
	page_size: 12,
	filter: "ALL",
	order: "ORDER_ADDED",
	createOkLabel: "Your space has been created successfully. Now you can add videos to your new space!!!!",
	deleteOkLabel: "Your space has been deleted successfully",
	byAccount: false,
	query:"",
	isFilter:false,
	filterLabel:"in all time",
	init:false,
	
	//conf params
	spaceListElement:		'#guardian_SpaceList',
	countPageElement:		'.count_pages',
	prevElement:			'.prev',
	moreElement:			'.more',
	paginationElement:		'#guardian_SpaceList .pagination',
	
	queryFilterElement:		'.box_right .filter_query .text',
	
	mostRecentElement:		'#most_recent',
	mostViewedElement:		'#most_viewed',
	
	filterElement:			'div .filter',
	
	noSpaceElement:			'#no_spaces',
	
	boxVideoCenter:			'.box_video_center',
	boxVideoRight:			'.box_video_right',
	boxVideoLeft:			'.box_video_left',
	
	spaceLinkElement:		'a',
	spaceImageElement:		'div.thumb_space img',
	spaceMetadataElement:	'div .metadata',
	spaceTitleElement:		'.metadata .meta_title a',
	spaceVideosElement:		'.metadata .meta_videos',
	spaceOwnerElement:		'.metadata .meta_owner_big a',
	spaceViews:				'.metadata .meta_views',
	
	boxRightMostViwed:		'.box_right #most_viewed a',
	boxRightMostRecent:		'.box_right #most_recent a',
	boxRightFilter0:		'.box_right .filter a:eq(0)',
	boxRightFilter1:		'.box_right .filter a:eq(1)',
	boxRightFilter2:		'.box_right .filter a:eq(2)',
	boxRightFilter3:		'.box_right .filter a:eq(3)',
	boxRightFilterSearch:	'.box_right .filter_query .btn_search .search',
	boxRightFilterText:		'.box_right .filter_query .text',
	boxRight:				'.box_right',
	
	yourListElement:		'#guardian_YourSpaces #your_list',
	yourListElement1:		'div:not(:first)',
	yourListElement2:		'br',
	
	yourSpacesElement:		'#your_spaces',
	noAccountElement:		'#no_account',
	createAccountElement:	'.cnt_btncreate',
	noSpacesElement:		'#no_spaces',

	cleanOkElement:			'.clean-ok',
	
	createSpaceElement:		'#content_all .create_space',
	createSpaceCreate:		'.create',
	createSpaceCancel:		'.cancel',
	createSpaceSelector:	'form label:not(:first)',
	titleSpaceElement:		'#title_space',	
	
	guardianYourSpaces:		'#guardian_YourSpaces',
	_yourListElement:		'#guardian_YourSpaces #your_list',
	_yourListElement1:		'div:first',
	_yourListElement2:		'.spaces_single a',
	_yourListElement3:		'.spaces_createdate',
	_yourListElement4:		'.spaces_delete > a',	
	featured: false,
	
	init: function(){
		GuardianSpaceList.changeOrder(GuardianSpaceList.order);
	},
	
	pagination: function(total) { 
	   
	   var nPages = Math.ceil(total/this.page_size);
	   var el = $(GuardianSpaceList.spaceListElement).find(GuardianSpaceList.countPageElement);
	   el.html("In all Spaces <b>" + this.page + "</b> of " + nPages);
	   
	   var prev = $(GuardianSpaceList.spaceListElement).find(GuardianSpaceList.prevElement);
	   prev.attr("href","#");
	   if(this.page > 1)
	   		prev.attr("href","javascript:GuardianSpaceList.changePage(" + (this.page - 1) + ")");
	   var more = $(GuardianSpaceList.spaceListElement).find(GuardianSpaceList.moreElement);
	   more.attr("href","#");
	   if(this.page != nPages)
		    more.attr("href","javascript:GuardianSpaceList.changePage(" + (this.page + 1) + ")");
	
	   $(GuardianSpaceList.paginationElement).fadeIn('slow');
	},
	
	changePage: function(page){
		this.page = page;
		this.getSpaceList();
	},
	
	clickSearch: function(event){
		this.page = 1;
		GuardianSpaceList.isFilter = true;
		if(event.type == 'keyup' && event.keyCode != 13){
			return;
		}
		GuardianSpaceList.query = $(GuardianSpaceList.queryFilterElement).val();
		GuardianSpaceList.getSpaceList();
	},
	
	changeOrder: function(order){
		this.page = 1;
		this.order = order;
		if(order == "ORDER_ADDED"){
			var el = $(GuardianSpaceList.mostRecentElement).find('a');
			el.html("<b>Most Recent</b>");
			el = $(GuardianSpaceList.mostViewedElement).find('a');
			el.html("Most Viewed");
		}
	
		if(order == "ORDER_VIEWED"){
			var el = $(GuardianSpaceList.mostViewedElement).find('a');
			el.html("<b>Most Viewed</b>");
			el = $(GuardianSpaceList.mostRecentElement).find('a');
			el.html("Most Recent");
		}
		if(this.byAccount){
			this.getSpaceListByAccount();
		}else{
			this.getSpaceList();
		}
	},
	
	changeFilter: function(filter){
		GuardianSpaceList.page = 1;
		GuardianSpaceList.isFilter = true;
		GuardianSpaceList.filter = filter;
		var filters = $(GuardianSpaceList.filterElement).find('span');
		filters.css("text-decoration","none");
		if(filter == "TODAY"){
			$(filters[0]).css("text-decoration","underline");
			GuardianSpaceList.filterLabel = "today";
		}
		if(filter == "WEEK"){
			$(filters[1]).css("text-decoration","underline");
			GuardianSpaceList.filterLabel = "in this week";
		}
		if(filter == "MONTH"){
			$(filters[2]).css("text-decoration","underline");
			GuardianSpaceList.filterLabel = "in this month";
		}
		if(filter == "ALL"){
			$(filters[3]).css("text-decoration","underline");
			GuardianSpaceList.filterLabel = "in all time";
		}
		if(GuardianSpaceList.byAccount){
			GuardianSpaceList.getSpaceListByAccount();
		}else{
			GuardianSpaceList.getSpaceList();
		}
	},
	
	getSpaceList: function(){
		GuardianSpaceList.byAccount = false;
		this.initSearchBox();
		GuardianUtil.showLoading();
		
		if(!GuardianSpaceList.featured){
			jsonrpc.v2spaceService.getSpacesInChannel(
					GuardianSpaceList.spaceListCallback,
					GuardianSpaceList.query,
					GuardianSpaceList.order,
					GuardianSpaceList.filter,
					GuardianSpaceList.page,
					GuardianSpaceList.page_size, "Space");
		}		
		else{
			jsonrpc.v2spaceService.getSpacesByAccount(
					GuardianSpaceList.spaceListCallback,1,GuardianSpaceList.order,GuardianSpaceList.filter,GuardianSpaceList.page,GuardianSpaceList.page_size,"Space");
		}
		
	},
	
	initSearchBox: function(){
		if(this.init)
			return;

		this.init =true;
		var input = $(GuardianSpaceList.queryFilterElement);
		$(input).blur(GuardianSpaceList.textSearchBoxOnBlur);	
        $(input).focus(GuardianSpaceList.textSearchBoxOnFocus);
        $(input).val('search spaces..');
	},
	
	textSearchBoxOnBlur: function(){
	    var input = $(GuardianSpaceList.queryFilterElement);
		if($(input).val()==''){
        	$(input).val('search spaces..');
      	}
	},
	
	textSearchBoxOnFocus: function(){
		var input = $(GuardianSpaceList.queryFilterElement);
        if($(input).val()=='search spaces..'){
        	$(input).val('')
        }
	},

	spaceListCallback: function(result, e){
		GuardianUtil.hideLoading();
		if(e != null){
			return;
		}
		
		$(GuardianSpaceList.noSpaceElement).hide();
		
		$(GuardianSpaceList.boxVideoCenter).hide();
		$(GuardianSpaceList.boxVideoLeft).hide();
		$(GuardianSpaceList.boxVideoRight).hide();
		$(GuardianSpaceList.paginationElement).hide();

		if(result == null || result.list == null || result.total == 0){
			if(!GuardianSpaceList.isFilter){	
				$(GuardianSpaceList.noSpaceElement).text("No Spaces found");
				$(GuardianSpaceList.noSpaceElement).fadeIn('slow');
			}else{
				$(GuardianSpaceList.noSpaceElement).text("No Spaces found for '" + GuardianSpaceList.query + "' that has been published " + GuardianSpaceList.filterLabel);
				$(GuardianSpaceList.noSpaceElement).fadeIn('slow');
			}
			return;
		}	
				
		var total = result.total;
		GuardianSpaceList.pagination(total);
		
		var spaces = result.list.list;
		
		for(i=0;i<spaces.length;i++){ 
			var el = $($(GuardianSpaceList.spaceListElement).children('div')[i+1]);
			var a = $(el).find(GuardianSpaceList.spaceLinkElement);
			var img = $(el).find(GuardianSpaceList.spaceImageElement);
			var text = $(el).find(GuardianSpaceList.spaceMetadataElement);	
			
			$(a).attr('href','space.page?spaceid=' + spaces[i].spaceId);
			
			$(img).attr('src',spaces[i].thumbnail);
			$(img).attr('alt',spaces[i].name);
			
			var el_name = $(el).find(GuardianSpaceList.spaceTitleElement);
			$(el_name).attr('href','space.page?spaceid=' + spaces[i].spaceId);
			$(el_name).text(spaces[i].name);
			el_name = $(el).find(GuardianSpaceList.spaceVideosElement);
			if(spaces[i].videos == null)
				spaces[i].videos = 0;
			$(el_name).text(spaces[i].videos + " videos");
			el_name = $(el).find(GuardianSpaceList.spaceOwnerElement);
			$(el_name).text(spaces[i].owner.username);
			$(el_name).attr('href','profile.page?userid=' + spaces[i].owner.id);
			el_name = $(el).find(GuardianSpaceList.spaceViews);
			if(spaces[i].views == null)
				spaces[i].views = 0;
			$(el_name).text(spaces[i].views + " views");
			el.show();			
		}
		$(GuardianSpaceList.spaceListElement).fadeIn("slow");
		
		$(GuardianSpaceList.boxRightMostViwed).attr("href","javascript:GuardianSpaceList.changeOrder('ORDER_VIEWED');");
		$(GuardianSpaceList.boxRightMostRecent).attr("href","javascript:GuardianSpaceList.changeOrder('ORDER_ADDED');");
		$(GuardianSpaceList.boxRightFilter0).attr("href","javascript:GuardianSpaceList.changeFilter('TODAY');");
		$(GuardianSpaceList.boxRightFilter1).attr("href","javascript:GuardianSpaceList.changeFilter('WEEK');");
		$(GuardianSpaceList.boxRightFilter2).attr("href","javascript:GuardianSpaceList.changeFilter('MONTH');");
		$(GuardianSpaceList.boxRightFilter3).attr("href","javascript:GuardianSpaceList.changeFilter('ALL');");
		
		$(GuardianSpaceList.boxRightFilterSearch).bind('click',GuardianSpaceList.clickSearch);
		$(GuardianSpaceList.boxRightFilterText).bind('keyup',GuardianSpaceList.clickSearch);
		
		$(GuardianSpaceList.boxRight).show();

	},
	
	getSpaceListByAccount: function(){
		this.byAccount = true;
		this.initSearchBox();
		
		var el = $(GuardianSpaceList.yourListElement);
		el.find(GuardianSpaceList.yourListElement1).remove();
		el.find(GuardianSpaceList.yourListElement2).remove();
		
		if(GuardianLogin.account == null){
			$(GuardianSpaceList.yourSpacesElement).hide();
			$(GuardianSpaceList.noAccountElement).fadeIn('slow');
			$(GuardianSpaceList.createAccountElement).hide();
			return;
		}
		jsonrpc.v2spaceService.getSpacesByAccount(
				this.spaceByAccountCallback,GuardianLogin.account.id,this.order,this.filter,this.page,100,"SpaceSmall");
	},
	
	spaceByAccountCallback: function(result, e){
		if(e != null){
			return;
		}
		
		if(result == null || result.list == null){
			$(GuardianSpaceList.yourSpacesElement).hide();
			$(GuardianSpaceList.noSpacesElement).fadeIn('slow');
			GuardianSpaceList.createSpace();
			return;
		}			
		
		var spaces = result.list.list;
		var el;
		
		if(spaces.length==0){
			$(GuardianSpaceList.yourSpacesElement).hide();
			$(GuardianSpaceList.noSpacesElement).fadeIn('slow');
			GuardianSpaceList.createSpace();
			return;
		}
		
		el = $(GuardianSpaceList._yourListElement);
		
		var html;
		for(i=0;i<spaces.length;i++){ 
			var el_c = $(el).find(GuardianSpaceList._yourListElement1).clone();
			var el_name = el_c.find(GuardianSpaceList._yourListElement2);
			$(el_name).text(spaces[i].name);
			$(el_name).attr("href","space_name.page?spaceid=" + spaces[i].spaceId);
			var cDate = "";
			if(spaces[i].creationDate != null)
				cDate = GuardianUtil.formatDate(spaces[i].creationDate.time);
			el_c.find(GuardianSpaceList._yourListElement3).text(cDate);
			el_c.find(GuardianSpaceList._yourListElement4).attr("href","javascript:GuardianSpaceList.deleteSpace(" + spaces[i].spaceId + ")");
			el.append(el_c);
			el.append("<br/>");
			el_c.show();
		}	
		$(GuardianSpaceList.guardianYourSpaces).fadeIn("slow");
		
		/*$('.box_right #most_viewed a').attr("href","javascript:GuardianSpaceList.changeOrder('ORDER_VIEWED');");
		$('.box_right #most_recent a').attr("href","javascript:GuardianSpaceList.changeOrder('ORDER_ADDED');");
		$('.box_right .filter a:eq(0)').attr("href","javascript:GuardianSpaceList.changeFilter('TODAY');");
		$('.box_right .filter a:eq(1)').attr("href","javascript:GuardianSpaceList.changeFilter('WEEK');");
		$('.box_right .filter a:eq(2)').attr("href","javascript:GuardianSpaceList.changeFilter('MONTH');");
		$('.box_right .filter a:eq(3)').attr("href","javascript:GuardianSpaceList.changeFilter('ALL');");
		
		$('.box_right').show();*/

	},
	
	createSpace: function(){
		//$('.clean-ok').fadeOut("slow");
		var create = $(GuardianSpaceList.createSpaceElement).find(GuardianSpaceList.createSpaceCreate);
		create.click(this.postCreateSpace);
		var cancel = $(GuardianSpaceList.createSpaceElement).find(GuardianSpaceList.createSpaceCancel);
		cancel.click(this.cancelCreateSpace);
		$(GuardianSpaceList.createSpaceElement).find(GuardianSpaceList.titleSpaceElement).val("");
		$(GuardianSpaceList.createSpaceElement).fadeIn("slow");
		$(GuardianSpaceList.createSpaceElement).find(GuardianSpaceList.createSpaceSelector).remove();
	},
	
	deleteSpace: function(spaceId){
		$(GuardianSpaceList.cleanOkElement).fadeOut("slow");
		GuardianUtil.confirmDialog("Are you sure you want to delete your Space?","GuardianSpaceList.postDeleteSpace('" + spaceId + "');");
	},
	
	postDeleteSpace: function(spaceId){
		GuardianUtil.showLoading();
		jsonrpc.spaceService.deleteSpace(GuardianSpaceList.deleteSpaceCbk, spaceId);
	},
	
	deleteSpaceCbk: function(spaceId){
		GuardianUtil.hideLoading();
		$(GuardianSpaceList.cleanOkElement).text(GuardianSpaceList.deleteOkLabel);
		$(GuardianSpaceList.cleanOkElement).fadeIn("slow");
		GuardianSpaceList.getSpaceListByAccount();
	},
	
	postCreateSpace: function(){
		var spaceName = $(GuardianSpaceList.createSpaceElement).find(GuardianSpaceList.titleSpaceElement).val();
		if(spaceName == '')
			return;
		var description ="";
		GuardianUtil.showLoading();
		$(GuardianSpaceList.noSpacesElement).fadeOut("slow");
		$(GuardianSpaceList.createSpaceElement).fadeOut("slow");
		jsonrpc.spaceService.createSpace(GuardianSpaceList.createSpaceCbk, spaceName,description);
	},
	
	cancelCreateSpace: function(){
		$(GuardianSpaceList.createSpaceElement).fadeOut("slow");
	},
	
	createSpaceCbk: function(result, e){
		GuardianUtil.hideLoading();
		if(e){
			alert(e);
		}
		
		$(GuardianSpaceList.cleanOkElement).text(GuardianSpaceList.createOkLabel);
		$(GuardianSpaceList.cleanOkElement).fadeIn("slow");
		GuardianSpaceList.getSpaceListByAccount();
		
		setTimeout("document.location = 'import.page?spaceId=" + result.spaceId + "&query="+result.name + "'",2000);
	}
	
};
var GuardianSpaceName = {
	page: 1,
	page_size: 12,
	filter: "ALL",
	order: "ORDER_ADDED",
	selector: "VIDEOS", //ALL, SPACES, VIDEOS
	query:"",
	isFilter:false,
	filterLabel:"in all time",
	
	space_id: -1,
	videos: null,
	preview_w: 425,
	preview_h: 344,
	guardian_space_page_link: 'guardian_spaces.page',
	space:null,
	
	init: function(){
		
		var offset = (this.page -1)*this.page_size;		
		var args = GuardianUtil.getArgs();
		
		var spaceid = args['spaceid'];
		
		
		if(GuardianLogin.account!=null){			
			$('.tools').show();
			$('.list_spacename').show();
			
			if(spaceid != null){		
				$('#back_link > p > a:eq(0)').attr('href', GuardianSpaceName.guardian_space_page_link);
				GuardianSpaceName.space_id = parseInt(spaceid);
				GuardianSpaceName.getSpaceInfo();
			}
			else{
				document.location.href='guardian_spaces.page';
			}			
		}
		else{		
			var page = 'space_name';
		
			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");		

		this.initSearchBox();
	},
	
	initSearchBox: function(){
		var input = $('.filter_query .text');
		$(input).blur(GuardianSpaceName.textSearchBoxOnBlur);	
        $(input).focus(GuardianSpaceName.textSearchBoxOnFocus);
        $(input).val("search in space's videos..");
	},
	
	textSearchBoxOnBlur: function(){
	    var input = $('.filter_query .text');
		if($(input).val()==''){
        	$(input).val("search in space's videos..");
      	}
	},
	
	textSearchBoxOnFocus: function(){
		var input = $('.filter_query .text');
        if($(input).val()=="search in space's videos.."){
        	$(input).val('')
        }
	},

	
	pagination: function(total) { 
	   if(total == 0){
		 $('.pagination').hide();
		 return;
	   }
	   
	   var nPages = Math.ceil(total/this.page_size);
	   var el = $($('.list_spacename')).find('.count_pages');
	   //Videos list 1 of 50
	   el.html("Videos list <b>"+this.page+"</b> of "+ nPages);
	   
	   var prev = $($('.list_spacename')).find('.prev');
	   prev.attr("href","#");
	   if(this.page > 1)
	   		prev.attr("href","javascript:GuardianSpaceName.changePage(" + (this.page - 1) + ")");
	   var more = $($('.list_spacename')).find('.more');
	   more.attr("href","#");
	   if(this.page != nPages)
		    more.attr("href","javascript:GuardianSpaceName.changePage(" + (this.page + 1) + ")");

	},
	
	clickSearch: function(event){
		GuardianSpaceName.page = 1;
		GuardianSpaceName.isFilter = true;
		if(event.type == 'keyup' && event.keyCode != 13){
			return;
		}
		GuardianSpaceName.query = $('.box_right .filter_query .text').val();
		GuardianSpaceName.getSpaceList();
	},
	
	changePage: function(page){
		GuardianSpaceName.page = page;
		$(".list_spacename .clean-ok").fadeOut("slow");
		GuardianSpaceName.getSpaceList();
	},
	
	changeOrder: function(order){
		GuardianSpaceName.page = 1;
		GuardianSpaceName.order = order;
		if(order == "ORDER_ADDED"){
			var el = $('#most_recent').find('a');
			el.html("<b>Most Recent</b>");
			el = $('#most_viewed').find('a');
			el.html("Most Viewed");
		}
	
		if(order == "ORDER_VIEWED"){
			var el = $('#most_viewed').find('a');
			el.html("<b>Most Viewed</b>");
			el = $('#most_recent').find('a');
			el.html("Most Recent");
		}
		GuardianSpaceName.getSpaceList();
	},
	
	changeFilter: function(filter){
		GuardianSpaceName.page = 1;
		GuardianSpaceName.isFilter = true;
		this.filter = filter;
		var filters = $('div .filter').find('span');
		filters.css("text-decoration","none");
		if(filter == "TODAY"){
			$(filters[0]).css("text-decoration","underline");
			this.filterLabel = "today";
		}
		if(filter == "WEEK"){
			$(filters[1]).css("text-decoration","underline");
			this.filterLabel = "in this week";
		}
		if(filter == "MONTH"){
			$(filters[2]).css("text-decoration","underline");
			this.filterLabel = "in this month";
		}
		if(filter == "ALL"){
			$(filters[3]).css("text-decoration","underline");
			this.filterLabel = "in all time";
		}
		GuardianSpaceName.getSpaceList();
	},
	
	changeSelector: function(selector){
		GuardianSpaceName.selector = selector;
		GuardianSpaceName.getSpaceList();
	},
	
	getSpaceList: function(){
	    GuardianUtil.showLoading();
	    
	    $("#no_videos").fadeOut("slow");
	    
		var offset = (GuardianSpaceName.page -1)*GuardianSpaceName.page_size;
		
		jsonrpc.spaceService.getVideosInSpace(GuardianSpaceName.getSpaceListCallback, 
													GuardianSpaceName.space_id, 
													GuardianSpaceName.query, 
													GuardianSpaceName.order, 
													GuardianSpaceName.filter, 
													GuardianSpaceName.page, 
													GuardianSpaceName.page_size);	
	},
	
	getSpaceInfo: function(){
		jsonrpc.spaceService.getSpaceDetails(GuardianSpaceName.getSpaceInfoCallback,GuardianSpaceName.space_id);
	},

	getSpaceListCallback: function(result, e){
                
        GuardianUtil.hideLoading();
        
		if(e != null){
			return;
		}
		
		if(result==null){
			return;
		}
		
		if(result.list == null)
			return;
		
		var total = result.total;
		GuardianSpaceName.pagination(total);
		
		var results = result.list.list;
		
		GuardianSpaceName.videos=results;
		
		$('.box_video_center').hide();
		$('.box_video_right').hide();
		$('.box_video_left').hide();
		
		if(results.length==0){
			if(!GuardianSpaceName.isFilter){	
				$('#no_videos').text("No videos are present in this space");
				$('.box_right').hide();
				$('#no_videos').fadeIn('slow');
			}else{
				$('#no_videos').text("No Videos found for '" + GuardianSpaceName.query + "' that has been published " + GuardianSpaceName.filterLabel);
				$('#no_videos').fadeIn('slow');
			}
			return;
		}
		else{
			for(i=0;i<results.length;i++){ 
				var video = results[i];
				var el = $($('.video_list').children('div')[i+1]);
            
				$(el).find('.tools a:eq(0)').attr('href', 'javascript:GuardianSpaceName.showSendVideo('+i+')');
				$(el).find('.tools a:eq(1)').attr('href', 'javascript:GuardianSpaceName.previewVideo('+i+')');
			
				$(el).find('.delete a').attr('href', 'javascript:GuardianSpaceName.preDeleteVideo('+i+')');
          
				$(el).children('img').attr('src',video.imageName);
          	
          		$(el).find('.text .box_text_title').text(video.title);
          		$(el).find('.text .box_text_date').text(video.formattedTime);

				$(el).show();		
			}
			$('.list_spacename .video_list').fadeIn("slow");
		}
		

		$('.box_right #most_viewed a').attr("href","javascript:GuardianSpaceName.changeOrder('ORDER_VIEWED');");
		$('.box_right #most_recent a').attr("href","javascript:GuardianSpaceName.changeOrder('ORDER_ADDED');");
		$('.box_right .filter a:eq(0)').attr("href","javascript:GuardianSpaceName.changeFilter('TODAY');");
		$('.box_right .filter a:eq(1)').attr("href","javascript:GuardianSpaceName.changeFilter('WEEK');");
		$('.box_right .filter a:eq(2)').attr("href","javascript:GuardianSpaceName.changeFilter('MONTH');");
		$('.box_right .filter a:eq(3)').attr("href","javascript:GuardianSpaceName.changeFilter('ALL');");
		
		$('.box_right .filter_query .btn_search .search').bind('click',GuardianSpaceName.clickSearch);
		$('.box_right .filter_query .text').bind('keyup',GuardianSpaceName.clickSearch);
		
		$('.box_right').show();

	},
		
	showSendVideo: function(idx){	
		$(".list_spacename .clean-ok").fadeOut("slow");

	    var v = new Array();
	    v[0] = GuardianSpaceName.videos[idx];
 		GuardianAudience.showSendVideo(v,GuardianSpaceName.space);
	},
	
	showSendAll: function(idx){	
		GuardianAudience.showSendAll(GuardianSpaceName.videos, GuardianSpaceName.space);
	},
	
	getSpaceInfoCallback: function(result, e){
	
		if(e!=null){
			return;
		}
		
		if(result==null){
			return;
		}
		
		GuardianSpaceName.space = result;
		
		if(result != null && result.owner.id != GuardianLogin.account.id){
			document.location.href="space_name.page";
			return;			
		}
		
		GuardianSpaceName.getSpaceList();
		
		$('.spacename_title .meta_title').text(result.name);
		$('.spacename_title .meta_title').bind("click",GuardianSpaceName.editTitleMouseEnter);
		
		$('#sendAll').attr('href',"javascript:GuardianSpaceName.showSendAll()");
		$('#addVideo').attr('href', 'import.page?spaceid='+GuardianSpaceName.space_id);		
	},
	
	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){
		 $(".list_spacename .clean-ok").fadeOut("slow");

		var el = $("#preview_video .content #video_box");
		var video = GuardianSpaceName.videos[index];		
		
		//CORREGGERE!!!
		GuardianVideoPlayer.fillDivVideoPlayer($(el).attr('id'),
													video.title,
													video.description,
													video.videoName, 
													video.imageName,
													video.duration,  
													video.external, 
													video.embedCode,
													GuardianSpaceName.preview_w,
													GuardianSpaceName.preview_h);
		
		GuardianUtil.showModalDialog("preview_video");
	},
	
	preDeleteVideo: function(index){
	    $(".list_spacename .clean-ok").fadeOut("slow");
		GuardianUtil.confirmDialog("Are you sure you want to delete this video?","GuardianSpaceName.deleteVideo('" + index + "');");
	},
	
	deleteVideo: function(index){
		GuardianUtil.showLoading();
		var video = GuardianSpaceName.videos[index];		
		jsonrpc.spaceService.removeVideoFromSpace(GuardianSpaceName.deleteVideoCallback, GuardianSpaceName.space_id, video.id);
	},
	
	deleteVideoCallback: function(result, e){
		if(e!=null){
			return;
		}	
		$(".list_spacename .clean-ok").fadeIn("slow");
		GuardianSpaceName.getSpaceList();
	}
};
var GuardianSpacePage = {

	player: null,

	page: 1,
	page_size: 10,
	filter: "ALL",
	order: "ORDER_ADDED",
	rel_page: 1,
	rel_page_size: 4,
	video: null,
	video_id: -1,
	space_id: -1,
	space_name: null,
	video_exid: null,
	video_width: 640,
	video_height: 360,
	space: null,
	advListSize:4,
	advSearchSize:5,
	//description_full_size: false,
	//description_original_size: '1px',
	//description_more_original_text: 'View full description...',
	//description_less_full_text: 'View less description...',
	
	single_comment_box: null,
	comments: null,
	comments_size: 10,
	comments_increment: 10,
	comment_box_visible: false,
	comment_action: 'submit',
	
	sourceFakeSpace: 'youtube',
	
	login_box_visible: false,

	div_video_id:'video_box',
	
	MAX_DESCRIPTION:300,
	
	profileElement: null,
	commentElement: null,
	relatedElement: null,
	spaceVideoListElement: null,
	playerElement: null,
	subscribeElement: null,
	advBoxElement: null,
	advSearchBoxElement:null,
	videoLink: "space.page",
	backgroundSubscribe: "#99CC00",
	borderSubscribe: "1px solid #999999",
	backgroundUnSubscribe: "#CC0000",
	borderUnSubscribe: "1px solid #999999",
	backgroundCreate: "#99CC00",
	borderCreate: "1px solid #999999",
	channel_image_box: '#channel_img > img',
	showOverlayVideoPlayer:false,
	
	init: function(){
	
		GuardianSpacePage.single_comment_box = $('.comments .single_comments:first');
		$('#more_comments a').attr('href', 'javascript:GuardianSpacePage.changeCommentSize()');
		
		GuardianSpacePage.description_original_size=$('.video_description').height();
		GuardianSpacePage.description_more_original_text=$('.video_description_full a').text();
		
		GuardianSpacePage.getSpacePage();
		
		//$('.video_description_full a').attr('href','javascript:GuardianSpacePage.changeDescriptionSize()');
		$('#post_comment_link a').attr('href','javascript:GuardianSpacePage.openCommentBox()');
		
		var page = 'space';
		
		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;
		
		$('#box_login_link a').attr('href',loginpage);
		$('#box_signup_link a').attr('href',joinpage);
		
		$('#user_not_login').css("width","470px");	
		$('#user_logged').css("width","330px");
		
		$('#flag_video_box').css("width","430px");
		$('#flag_video').click(GuardianSpacePage.showFlagVideo);
		
		$('#add_video_box').css("width","430px");
		$('#add_video').click(GuardianSpacePage.showAddVideoToSpace);
		//$('#button_post_comment').click(GuardianSpacePage.selectCommentAction('submit'));
		//$('#button_discard_comment').click(GuardianSpacePage.selectCommentAction('discard'));
	},

	getSpacePage: function(){
		var offset = (this.page -1)*this.page_size;		
		var args = GuardianUtil.getArgs();
		var vid = args['videoid'];
		var spaceid = args['spaceid'];
		var spaceName = args['spacename'];
		var videxid = args['videoexid'];
		
		GuardianUtil.showLoading();
		if(spaceName != null && videxid!=null){
			GuardianSpacePage.video_exid = videxid;
			GuardianSpacePage.space_name = spaceName;
			GuardianSpacePage.getSpaceInfoBySpaceName();			
		}else if(spaceName != null){
			GuardianSpacePage.space_name = spaceName;
			GuardianSpacePage.getSpaceInfoBySpaceName();
		}else if(vid != null && spaceid != null){
			GuardianSpacePage.video_id = vid;
			GuardianSpacePage.space_id = spaceid;
			GuardianSpacePage.getSpaceInfo();
			return;
		}else if(vid != null){		
			GuardianSpacePage.video_id = vid;
			GuardianSpacePage.getSpaceOwner();		
			return;
		}else if(spaceid != null){		
			GuardianSpacePage.space_id = spaceid;
			GuardianSpacePage.getSpaceInfo();
		}

	},	
	
	getSpaceInfoBySpaceName: function(){
		jsonrpc.spaceService.getSpaceDetailsBySpaceName(GuardianSpacePage.getSpaceInfoBySpaceNameCallback,GuardianSpacePage.space_name);
	},
	
	getSpaceOwner: function(){
		jsonrpc.spaceService.getSpaceOwnerByVideo(GuardianSpacePage.getVideoOwnerVideoCallback, GuardianSpacePage.video_id);
	},

	getVideoInfo: function(){
		jsonrpc.videoPageService.getVideoInfo(GuardianSpacePage.getVideoCallback,GuardianSpacePage.video_id);
	},
	
	getExternalVideoInfo: function(){
		jsonrpc.videoPageService.getExternalVideoInfo(GuardianSpacePage.getVideoCallback,GuardianSpacePage.video_exid);
	},
		
	getSpaceInfo: function(){
		jsonrpc.spaceService.getSpaceDetails(GuardianSpacePage.getVideoOwnerCallbackSpaceWrapper,GuardianSpacePage.space_id);
	},
	
	getSubscriptionInfo: function(){
	    if(GuardianLogin.account != null){	   
			jsonrpc.subscriptionService.isSubscribed(GuardianSpacePage.getSubscriptionInfoCbk,GuardianSpacePage.space_id);
		}else{
			GuardianSpacePage.getSubscriptionInfoCbk(false);
		}
	},	
	
	getVideoInfoBySpaceId: function(){
		if(GuardianSpacePage.space_id==-1){
			//fake space
			if(GuardianSpacePage.video_exid!=null){
				GuardianSpacePage.getExternalVideoInfo();
			}
			else{
				jsonrpc.spaceService.getFirstVideoInFakeSpace(GuardianSpacePage.getVideoCallbackSpaceWrapper,
																GuardianSpacePage.space_name,
																GuardianSpacePage.sourceFakeSpace);
			}
		}
		else{
			//true space
			if(GuardianSpacePage.video_id == -1){
				jsonrpc.spaceService.getFirstVideoInSpace(GuardianSpacePage.getVideoCallbackSpaceWrapper,GuardianSpacePage.space_id);
			}else{
				GuardianSpacePage.getVideoInfo();
			}
		}
	},
	
	getAdvItems: function(){
		jsonrpc.ads.getAds(GuardianSpacePage.getAdvItemsCbk,GuardianSpacePage.advListSize,GuardianSpacePage.space.name);		
		if(GuardianSpacePage.advSearchBoxElement != null)
			jsonrpc.ads.getSearchAds(GuardianSpacePage.getAdvSearchCbk,GuardianSpacePage.advSearchSize,GuardianSpacePage.space.name);
	},
		
	getRelated: function(){
		var rel_offset = (GuardianSpacePage.rel_page -1)*GuardianSpacePage.rel_page_size+1;	
		if(GuardianSpacePage.video_id!=-1){
			jsonrpc.v2searchService.searchClipsByClipId(GuardianSpacePage.getRelatedCallback,
													GuardianSpacePage.video_id,
													rel_offset,
													GuardianSpacePage.rel_page_size,"UGVideoMedium");
		}
		else{
			jsonrpc.v2searchService.searchClipsByExternalId(GuardianSpacePage.getRelatedCallback,
															GuardianSpacePage.video_exid, 
															rel_offset, 
															GuardianSpacePage.rel_page_size, 
															-1);
		}
	},

	getVideoInSpace: function(){	
		if(GuardianSpacePage.space_id!=null && GuardianSpacePage.space_id != -1){
			$(".list").children().fadeOut('slow'); 
			GuardianUtil.showLoadingInDiv(".list");
			jsonrpc.v2clipListService.getAllClipsInSpace(GuardianSpacePage.getVideoInSpaceCallback, 
													GuardianSpacePage.space_id, 
													GuardianSpacePage.page, 
													GuardianSpacePage.page_size,"UGVideoSmall");									
		}
		else{
			if(GuardianSpacePage.space_id!=null && GuardianSpacePage.space_id == -1){
				jsonrpc.v2clipListService.getAllClipsInFakeSpace(GuardianSpacePage.getVideoInSpaceCallback,
															GuardianSpacePage.space_name,
															GuardianSpacePage.page, 
															GuardianSpacePage.page_size,
															GuardianSpacePage.sourceFakeSpace);
			}
			else{
				//COME COMPORTARSI SE IL VIDEO NON E' IN NESSUN SPACE? PUO' SUCCEDERE? CHE SI FA?
			}
		}

		

	},
	
	getSpaceInfoBySpaceNameCallback: function(result, e){
		if(e!=null){
			return;
		}
		if(result==null){
			//build fake space
			result = new Object();
			result.name = GuardianSpacePage.space_name;
			result.spaceId = -1;
			result.owner = null;
			result.imageIcon = '';
			if(!GuardianSpacePage.showOverlayVideoPlayer){
				GuardianSpacePage.getVideoInfoBySpaceId();
			}
			GuardianSpacePage.getVideoOwnerCallback(result);
		}
		else{
			//build real space		
			GuardianSpacePage.space_id = result.spaceId;
			GuardianSpacePage.getVideoOwnerCallbackSpaceWrapper(result, e);
		}
	},
	
	getVideoOwnerVideoCallback: function(result, e){
		if(e!=null){
			return;
		}
		if(result==null){
			GuardianUtil.hideLoading();
			
			//NO VIDEO
			$('#content_all').children().hide();
			$('.left').children().hide();
			$('.left').show();
			$('.left #alert_no_video').show();
			
			setTimeout("document.location = 'all_spaces.page'", 2000);
			return;
		}
							
		GuardianSpacePage.getVideoInfo();	
		GuardianSpacePage.getVideoOwnerCallback(result, e);
	},
	
	
	getVideoOwnerCallbackSpaceWrapper: function(result, e){
		if(e!=null){
			return;
		}	
		
		if(result==null){
			GuardianUtil.hideLoading();
			
			//NO SPACE
			$('#content_all').children().hide();
			$('.left').children().hide();
			$('.left').show();
			$('.left #alert_no_space').show();
			setTimeout("document.location = 'all_spaces.page'", 2000);
			return;
		}
		
		if(!GuardianSpacePage.showOverlayVideoPlayer){
			GuardianSpacePage.getVideoInfoBySpaceId();
		}	
		GuardianSpacePage.getVideoOwnerCallback(result, e);
	},
	
	
	getVideoOwnerCallback: function(result, e){
		GuardianUtil.hideLoading();
		
		if(result==null){
			return;
		}
		
		GuardianSpacePage.space = result;
		
		//fill space
		var sname = result.name;
		
		if(sname.length > 30)
		    sname = sname.substring(0,30) + "..";
		
		$('#space_name').text(sname);
                $('#space_name_keywords').text(sname);
		$('#space_name').parent().fadeIn("slow");
		
		if(result.owner!=null && GuardianSpacePage.profileElement != null && $(GuardianSpacePage.profileElement).length > 0){
			var pDiv = GuardianSpacePage.profileElement;
			$(pDiv + ' .your_img img').attr('src', result.owner.imageUrl);
			var link = '<a href="profile.page?userid=' + result.owner.id + '">' + result.owner.username + '</a>';
			$(pDiv + ' .your_note .name').html(link);
			var meta = $(pDiv + ' .your_note .info');
			$(meta[0]).text(result.owner.registerDate);
			$(meta[1]).text(result.owner.country);
			$(pDiv).fadeIn("slow");
		}
		
		GuardianSpacePage.space_id = result.spaceId;
		
		if(GuardianSpacePage.subscribeElement != null && $(GuardianSpacePage.subscribeElement).length>0){
			if(GuardianSpacePage.space_id!=-1){
				$(GuardianSpacePage.subscribeElement).attr('href','javascript:GuardianSpacePage.showConfirmSubscribe();');
				GuardianSpacePage.getSubscriptionInfo();
			}
			else{
			
				$(GuardianSpacePage.subscribeElement).attr('href','javascript:GuardianSpacePage.showConfirmCreateSpace();');
				$(GuardianSpacePage.subscribeElement).find('.btn_subscribe').css("background-color",GuardianSpacePage.backgroundCreate);
				$(GuardianSpacePage.subscribeElement).find('.btn_subscribe').css("border",GuardianSpacePage.borderCreate);
				$(GuardianSpacePage.subscribeElement).find('.btn_subscribe').text('Create now!');
				$(GuardianSpacePage.subscribeElement).find('.btn_subscribe').fadeIn("slow");

			}			
		}
		
		if(GuardianSpacePage.spaceVideoListElement != null && $(GuardianSpacePage.spaceVideoListElement).length>0){
			GuardianSpacePage.getVideoInSpace();
		}
		
		if(GuardianSpacePage.advBoxElement != null && $(GuardianSpacePage.advBoxElement).length>0){
			GuardianSpacePage.getAdvItems();
		}
		
		if(result.imageIcon != null && result.imageIcon != "")
			$(GuardianSpacePage.channel_image_box).attr("src",result.imageIcon);
		else
			$(GuardianSpacePage.channel_image_box).parent().hide();
	},

	getVideoCallbackSpaceWrapper: function(result, e){
		
		if(result!=null){
			GuardianSpacePage.getVideoCallback(result, e);
		}
		else{
			//NO VIDEO IN SPACE
			$('.left').children().hide();
			$('.left #alert_no_videos_in_space').show();
			setTimeout("document.location = 'all_spaces.page'", 2000);
			return;
		}
	},

	getVideoCallback: function(result, e){

		if (e != null) {
			return;
		}

		if(result==null){
			//NO VIDEO
			return;
		}

		var video = result;	
		GuardianSpacePage.video = video;
		GuardianSpacePage.video_id = result.id;
		GuardianSpacePage.video_exid = result.externalId;
		
		//chiamo l'incremento della view dello space
		GuardianSpacePage.incrementSpaceViews();

		if(GuardianSpacePage.relatedElement != null && $(GuardianSpacePage.relatedElement).length>0){
			GuardianSpacePage.getRelated();
		}
	 
		if(GuardianSpacePage.playerElement != null && $(GuardianSpacePage.playerElement).length>0){
			GuardianSpacePage.lessDescriptionSize();
		
			$('.video_title').text(video.title);	
		
			GuardianVideoPlayer.fillDivVideoPlayer(GuardianSpacePage.div_video_id, 
		                                            video.title,
		                                            video.description,	                                            
													video.videoName, 
													video.imageName,
													video.duration, 
													video.external,
													video.embedCode,
													GuardianSpacePage.video_width, 
													GuardianSpacePage.video_height);
		
			if(video.external){
				GuardianVideoPlayer.played = false;
				GuardianSpacePage.incrementVideoViews();
			}else{
				GuardianVideoPlayer.addViewListener("PLAY","GuardianSpacePage.incrementVideoViews");		
			}
 		
 			$(GuardianSpacePage.playerElement + " .video_toolbox").fadeIn('slow');
 			
 			ClearSpringController.register(video,GuardianSpacePage.space_id,"share_video");
   			ClearSpringController.init();
		}
 		
 		if(GuardianSpacePage.commentElement != null && $(GuardianSpacePage.commentElement).length>0){
			var comments = video.comment;
			comments = comments.list;
			GuardianSpacePage.comments = comments;
			//fill Comments
			GuardianSpacePage.writeComments(0);
		}					
	},
		
	writeComments: function(from){
		if(GuardianSpacePage.comments!=null){
			var comments = GuardianSpacePage.comments;
			
			var n = Math.min(comments.length, GuardianSpacePage.comments_size);			
			
			$('#comment_cnt').text("Comments (" + comments.length + ")");
						
			if(comments.length == 0){
				$('.comments .clean-alert').fadeIn('slow');
				$('.comments .clean-alert > a').attr('href','javascript:GuardianSpacePage.openCommentBox();');
			}else{
				$('.comments .clean-alert').hide();
			}
			
			var com_box = $('#single_comments_box');
			
			for(var i=from; i<n ;i++){
		    	var com=comments[i];
		    	var el_com = $(GuardianSpacePage.single_comment_box).clone();
				$(el_com).find('.name_author a').text(com.account.username);
				$(el_com).find('.name_author a').attr('href','profile.page?userid=' + com.account.id);
				
				$(el_com).find('.date').text(" (" + com.commentAddDate + ")");
				$(el_com).find('.body_comment').text(com.comment);
				
				
				//if(com.account.username==GuardianLogin.account.username){
					//$(el_com).find('').attr('href','javascript:GuardianSpacePage.deleteComment('+com.commentId+')');
					//$(el_com).find('').show();
				//}
				
				$(el_com).show();
				
				$(com_box).append(el_com);
			}	
			
			if(n<comments.length){
				$('#more_comments').show();
			}
			else{
				$('#more_comments').hide();
			}
		
			if($('.comments').css('display').toLowerCase()=='none'){
				$('.comments').fadeIn('slow');
			}
			
			if($('#comment_cnt').parent().css('display').toLowerCase()=='none'){
				$('#comment_cnt').parent().fadeIn('slow');
			}
		}	
	},
	
	
	getAdvItemsCbk: function(result,e){
		if(e!=null){
			return;
		}
		
		if(result==null){
			return;
		}	
			
		var advItems = result.list;
		var el = $(GuardianSpacePage.advBoxElement);		
		for(var i=0;i<advItems.length && i < GuardianSpacePage.advListSize;i++){ 
			var link = $(el.children()[i]);
			$(link).attr("href",advItems[i].clickUrl);
			
			var title = link.find('.box_ads .title');
			var description = link.find('.box_ads .desc');
			var clickUrl = link.find('.box_ads .link');
			$(title).html(advItems[i].title);
			$(description).html(advItems[i].description);
			$(clickUrl).text(advItems[i].url);
			
			$(link.find('.box_ads')).fadeIn('slow');
		}
		
		el.fadeIn("slow");	
	},
	
	getAdvSearchCbk: function(result,e){
		if(e!=null){
			return;
		}
		
		if(result==null){
			return;
		}	
			
		var advItems = result.list;
		var el = $(GuardianSpacePage.advSearchBoxElement);		
		for(var i=0;i<advItems.length && i < GuardianSpacePage.advSearchSize;i++){ 
			var link = $(el.children()[i]);
			$(link).attr("href",advItems[i].clickUrl);			
			var title = link.find('.box_ads .title');
			var description = link.find('.box_ads .desc');
			var clickUrl = link.find('.box_ads .link');
			$(title).html(advItems[i].title);
			$(description).html(advItems[i].description);
			$(clickUrl).text(advItems[i].url);
			
			$(link.find('.box_ads')).fadeIn('slow');
		}
		
		el.fadeIn("slow");	
	},
	
	openCommentBox: function(){
		if(GuardianLogin.account==null){	
			$('#user_not_login span.action').text('Want to post a Comment?');		
			GuardianUtil.showModalDialog('user_not_login');
		}
		else{
			$('#body_comment').val('');
			GuardianUtil.showModalDialog('user_logged');
		}
	},
	
	postComment: function(){
		var comment = $('#body_comment').val();
		if(jQuery.trim(comment)!= ''){
			if(GuardianSpacePage.comment_action.toLowerCase()=='submit'){
   				jsonrpc.videoPageService.postComment(GuardianSpacePage.postCommentCallback,GuardianSpacePage.video_id,comment);
			}
   		}
		GuardianUtil.closeModalDialog();
	},

	postCommentCallback: function(result, e){
		if(e!=null){
			return;
		}
		jsonrpc.videoPageService.getVideoInfo(GuardianSpacePage.reloadCommentsCallback,GuardianSpacePage.video_id);
	},
	
	deleteComment: function(commentId){
		jsonrpc.videoPageService.postComment(GuardianSpacePage.deleteCommentCallback,commentId);
	},
	
	deleteCommentCallback: function(result, e){
		if(e!=null){
			return;
		}
		jsonrpc.videoPageService.getVideoInfo(GuardianSpacePage.reloadCommentsCallback,GuardianSpacePage.video_id);	
	},
	
	reloadCommentsCallback: function(result, e){
		
		if (e != null) {
			return;
		}

		if(result==null){
			return;
		}

		var video = result;	
		
		var comments = video.comment;
		comments = comments.list;
		GuardianSpacePage.comments = comments;
		
		$('#single_comments_box').empty();
		
		GuardianSpacePage.writeComments(0);		
	},
	
	selectCommentAction: function(type){
		GuardianSpacePage.comment_action = type;
	},

	getRelatedCallback: function(result, e){

		if(e != null){
			return;
		}


		if(result == null || result.list == null)
			return;

		var total = result.total;
		var results = result.list.list;
		
		var relEl = GuardianSpacePage.relatedElement;
		
		var vlink = GuardianSpacePage.videoLink;
		
		for(i=0;i<results.length;i++){ 

			var el = $($(relEl).children('.box_video')[i]);			
			var text = $(el).children('.text');	
			var img = $(el).find('.img a img'); 
			var a = $(el).find('.img a');
			$(img).attr('alt',results[i].name);
			$(img).attr('src',results[i].thumbnail);
			
			if(GuardianSpacePage.space_id!=null && GuardianSpacePage.space_id!=-1){
				$(a).attr('href', vlink + '?videoid='+results[i].id);
			}
			else{				
				$(a).attr('href', vlink + '?videoexid=' + results[i].externalId + '&spacename=' + GuardianSpacePage.space_name);
			}
			var el_title = $(text).find('.meta_title a');
            var el_owner = $(text).find('.meta_owner a');
            var el_views = $(text).find('.meta_views');
			el_title.text(results[i].title);
			
			if(GuardianSpacePage.space_id!=null && GuardianSpacePage.space_id!=-1){
				el_title.attr('href', vlink + '?videoid=' + results[i].id + '&spaceid=' + GuardianSpacePage.space_id);
			}
			else{
				el_title.attr('href', vlink + '?videoexid=' + results[i].externalId + '&spacename=' + GuardianSpacePage.space_name);
			}


			if(GuardianSpacePage.space_id!=null && GuardianSpacePage.space_id!=-1){
	            var sname="unknown";
				var shref="#";
				if(results[i].space != null){
					shref = vlink + '?spaceid=' + results[i].space.spaceId;
					sname = results[i].space.name;            
					el_owner.attr('href',shref);
				}
				el_owner.text(sname);
				if(results[i].views == null)
					results[i].views = 0;
            	el_views.text(results[i].views+' views');
			}
			else{
				el_owner.hide();
				el_views.hide();
			}
			el.show();			
		}
		$('#top_bar_related').fadeIn("slow");
		$(relEl).fadeIn("slow");
	},

	getVideoInSpaceCallback: function(result, e){
		$('.pagination').hide();
		$('.box_video_center').hide();
		$('.box_video_right').hide();
		$('.box_video_left').hide();
		
		GuardianUtil.hideLoadingInDiv(".list");
		
		if(result == null || result.list == null){
			return;
		}

		var total = result.total;
		
		if(total==0)
			return;
		
		GuardianSpacePage.pagination(total);

		var results = result.list.list;
		var vlink = GuardianSpacePage.videoLink; 

		for(i=0;i<results.length;i++){ 

			var el = $($('.list').children('div')[i+1]);
			var text = $(el).find('.metadata');
			var img = $(el).find('a img'); 
            var a = $(el).find('a');                      	
			$(img).attr('src',results[i].thumbnail);
			$(img).attr('alt',results[i].name);
			if(GuardianSpacePage.space_id!=null && GuardianSpacePage.space_id!=-1){
				$(a).attr('href', 'javascript:GuardianSpacePage.clickOnVideo("' + vlink + '",{videoid:"' + results[i].id + '",spaceid:"' + GuardianSpacePage.space_id + '"})');
			}
			else{
				$(a).attr('href', 'javascript:GuardianSpacePage.clickOnVideo("' + vlink + '",{videoexid:"' + results[i].externalId + '",spacename:"' + GuardianSpacePage.space_name + '"})');
			}
            
			var el_title = $(text).find('.meta_title a');
			var el_duration = $(text).find('.meta_duration');
			var el_views = $(text).find('.meta_views');
			var el_date = $(text).find('.meta_date');
			el_title.text(results[i].title);
			
			if(GuardianSpacePage.space_id!=null && GuardianSpacePage.space_id!=-1){
				$(el_title).attr('href', 'javascript:GuardianSpacePage.clickOnVideo("' + vlink + '",{videoid:"' + results[i].id + '",spaceid:"' + GuardianSpacePage.space_id + '"})');
			}
			else{
				$(el_title).attr('href', 'javascript:GuardianSpacePage.clickOnVideo("' + vlink + '",{videoexid:"' + results[i].externalId + '",spacename:"' + GuardianSpacePage.space_name + '"})');
			}
			
			el_duration.html(GuardianUtil.formatDuration(results[i].duration));
			var cDate="";
			if(results[i].creationDate != null)
				cDate = GuardianUtil.formatDate(results[i].creationDate.time);
            el_date.text('Add: '+cDate);
			
			if(GuardianSpacePage.space_id!=null && GuardianSpacePage.space_id!=-1){
				if(results[i].views == null)
					results[i].views = 0;
				el_views.text(results[i].views+' views');
			}
			else{
				el_views.hide();
			}
			el.fadeIn("slow");
		}
	},
	
	clickOnVideo: function(vLink,parameters){
		if(GuardianSpacePage.showOverlayVideoPlayer){
			if(parameters['videoid'] != null)
				jsonrpc.videoPageService.getVideoInfo(GuardianSpacePage.getVideoCallback,parameters['videoid']);
			else
				jsonrpc.videoPageService.getExternalVideoInfo(GuardianSpacePage.getVideoCallback,parameters['videoexid']);
			
			GuardianUtil.showModalDialog('preview_video');
		}
		else{
			var q="";
			for(var index in parameters){
				q+= "" + index + "=" + parameters[index] + "&";
			}
			document.location = vLink + "?" + q;
		}
	},

	pagination: function(total) { 
	   var nPages = Math.ceil(total/this.page_size);
	   var el = $($('.list')).find('.pagination .count_pages');
	   
	   var sname = GuardianSpacePage.space.name;
	   if(sname.length > 20)
		    sname = sname.substring(0,20) + "..";
	   
	   el.html("Videos in \"" + sname + "\" <b>"+this.page+"</b> of "+ nPages);
	   var prev = $($('.list')).find('.prev');
	   prev.attr("href","#");
	   if(this.page > 1)
	   		prev.attr("href","javascript:GuardianSpacePage.changePage(" + (this.page - 1) + ")");
	   var more = $($('.list')).find('.more');
	   more.attr("href","#");
	   if(this.page != nPages)
		    more.attr("href","javascript:GuardianSpacePage.changePage(" + (this.page + 1) + ")");
	   $('.pagination').fadeIn("slow");				
	},

	

	changePage: function(page){
		GuardianSpacePage.page = page;
		GuardianSpacePage.getVideoInSpace();
	},

	

	changeOrder: function(order){
		GuardianSpacePage.order = order;
		if(order == "ORDER_ADDED"){
			var el = $('#most_recent').find('a');
			el.html("<b>Most Recent</b>");
			el = $('#most_viewed').find('a');
			el.text("Most Viewed");
		}

		if(order == "ORDER_VIEWED"){
			var el = $('#most_viewed').find('a');
			el.html("<b>Most Viewed</b>");
			el = $('#most_recent').find('a');
			el.text("Most Recent");
		}

		GuardianSpacePage.getVideoInSpace();

	},
	

	changeFilter: function(filter){
		this.filter = filter;
		var filters = $('div .filter').find('span');
		filters.css("text-decoration","none");
		if(GuardianSpacePage.filter == "TODAY"){
			$(filters[0]).css("text-decoration","underline");
		}
		if(GuardianSpacePage.filter == "WEEK"){
			$(filters[1]).css("text-decoration","underline");
		}

		if(GuardianSpacePage.filter == "MONTH"){
			$(filters[2]).css("text-decoration","underline");
		}

		if(GuardianSpacePage.filter == "ALL"){
			$(filters[3]).css("text-decoration","underline");
		}

		GuardianSpacePage.getVideoInSpace();
	},
	
	fullDescriptionSize: function(){
		var cmd = " <a href='javascript:GuardianSpacePage.lessDescriptionSize();'>(less)</a>";
		$('.video_description').text(this.video.description);
		$('.video_description').append(cmd);	
	},
	
	lessDescriptionSize: function(){
		var d = GuardianSpacePage.video.description;
		var cmd="";
		if(d.length > this.MAX_DESCRIPTION){
			d = d.substring(0, this.MAX_DESCRIPTION);
			cmd = "... <a href='javascript:GuardianSpacePage.fullDescriptionSize();'>(more)</a>";
		}
		
		$('.video_description').text(d);
		$('.video_description').append(cmd);
	},
	
	changeCommentSize: function(){
		var hold = GuardianSpacePage.comments_size;
		GuardianSpacePage.comments_size+=GuardianSpacePage.comments_increment;
		GuardianSpacePage.writeComments(hold);
	},
	
	incrementSpaceViews: function(){
		if(GuardianSpacePage.space_id!=null && GuardianSpacePage.space_id!=-1){
			jsonrpc.videoPageService.incrementSpaceViews(GuardianSpacePage.incrementSpaceViewsCallback,GuardianSpacePage.space_id);
		}
	},
	
	incrementSpaceViewsCallback: function(result, e){
		
	},
	
	incrementVideoViews: function(){
		if(!GuardianVideoPlayer.played){
			jsonrpc.videoPageService.incrementViews(GuardianSpacePage.incrementVideoViewsCallback,GuardianSpacePage.video_id);
			GuardianVideoPlayer.played = !GuardianVideoPlayer.played;
		}		
	},
	
	incrementVideoViewsCallback: function(result, e){
	
	},
	
	showConfirmSubscribe: function(){
		if(GuardianLogin.account == null){
			$('#user_not_login span.action').text('Want to subscribe?');
			GuardianUtil.showModalDialog('user_not_login');
			return;
		}
		
		/*if(GuardianSpacePage.space.owner.id == GuardianLogin.account.id){
			return;
		}*/
		
		if(!GuardianLogin.account.external){
			//GuardianUtil.confirmDialog("Do you want to subscribe on this space?", "GuardianSpacePage.subscribe();");
			GuardianSpacePage.subscribe();
		}else{
			GuardianFacebookConnector.requirePermissions("GuardianSpacePage.permissionDone()","GuardianSpacePage.permissionDenied()");
		}
	},
	
	showConfirmUnsubscribe: function(){
		if(GuardianLogin.account == null){
			return;
		}
		GuardianSpacePage.unsubscribe();
		//GuardianUtil.confirmDialog("Do you want to unsubscribe on this space?", "GuardianSpacePage.unsubscribe();");
	},
	
	showConfirmCreateSpace: function(){
		if(GuardianLogin.account == null){
			$('#user_not_login span.action').text('Want to create a new "'+GuardianSpacePage.space_name+'" space?');
			GuardianUtil.showModalDialog('user_not_login');
			return;
		}
		
		/*if(GuardianSpacePage.space.owner.id == GuardianLogin.account.id){
			return;
		}*/
		
		GuardianUtil.confirmDialog("Do you want to create a new \""+GuardianSpacePage.space_name+"\" space?", "GuardianSpacePage.createSpace();");
	},
	
	createSpace: function(){
		var spaceName = GuardianSpacePage.space_name;
		if(spaceName == '')
			return;
		var description ="";
		GuardianUtil.showLoading();
		$('.content_homeSpace').children().hide();
		jsonrpc.spaceService.createSpace(GuardianSpacePage.createSpaceCbk, spaceName,description);
	},
	
	createSpaceCbk: function(result, e){
		GuardianUtil.hideLoading();
		if(e!=null || result==null){
			//alert(e);
			$('.left').children().hide();
			$('.left').show();
			$('.left #alert_no_create').show();
			$("#alert_no_create").fadeIn("slow");
			setTimeout("document.location = 'all_spaces.page'", 2000);
			
			return;	
		}
		
		if($("#ok_create").length > 0){
			$('.left').children().hide();
			$('.left').show();
			$('.left #ok_create').show();
			$("#ok_create #create_name").text(GuardianSpacePage.space_name);
			$("#ok_create").fadeIn("slow");
		}
		setTimeout("document.location = 'import.page?spaceId=" + result.spaceId + "&query="+result.name + "'",2000);
	},
	
	getSubscriptionInfoCbk: function(result, e){
		if(e != null){
			return;
		}	
		
		var elSub = GuardianSpacePage.subscribeElement;
		
		var btn = $(elSub + ' .btn_subscribe');
		var link = $(elSub);
		if(result){
			btn.text("Unsubscribe");
			btn.css("background-color",GuardianSpacePage.backgroundUnSubscribe);
			btn.css("border",GuardianSpacePage.borderUnSubscribe);
			link.attr("href","javascript:GuardianSpacePage.showConfirmUnsubscribe();");
		}else{
			btn.text("Subscribe");
			
			btn.css("background-color",GuardianSpacePage.backgroundSubscribe);
			btn.css("border",GuardianSpacePage.borderSubscribe);
			link.attr("href","javascript:GuardianSpacePage.showConfirmSubscribe();");
		}
		
		btn.fadeIn("slow");
	},
	
	subscribe: function(){
		$("#sub_ok").fadeOut("slow");
		$("#sub_error").fadeOut("slow");
		
		GuardianUtil.showLoading();
	
		jsonrpc.subscriptionService.subscribe(function(result, e){
			GuardianUtil.hideLoading();
		 		
			if(e != null){
				$("#sub_error").text("Error occured " + e);
				$("#sub_error").fadeIn("slow");
				return;
			}
			
			if(result){
			    GuardianSpacePage.getSubscriptionInfoCbk(true);
				$("#sub_ok").text("You have been subscribed to this space.");
				$("#sub_ok").fadeIn("slow");
			}else{
				$("#sub_error").text("You are already subscribed to this space.");
				$("#sub_error").fadeIn("slow");
			}
			
		}, GuardianSpacePage.space.spaceId);
	},
	
	unsubscribe: function(){
		$("#sub_ok").fadeOut("slow");
		$("#sub_error").fadeOut("slow");
		
		GuardianUtil.showLoading();
	
		jsonrpc.subscriptionService.unsubscribe(function(result, e){
			GuardianUtil.hideLoading();
		 		
			if(e != null){
				$("#sub_error").text("Error occured " + e);
				$("#sub_error").fadeIn("slow");
				return;
			}
			
			GuardianSpacePage.getSubscriptionInfoCbk(false);
			$("#sub_ok").text("You have been unsubscribed to this space.");
			$("#sub_ok").fadeIn("slow");
			
		}, GuardianSpacePage.space.spaceId);
	},
	
		
	permissionDone:function(){
		//GuardianUtil.confirmDialog("Do you want to subscribe on this space?", "GuardianSpacePage.subscribe();");
		GuardianSpacePage.subscribe();
	},	
	
	permissionDenied:function(){
		$("#sub_error").text("Please, enable Guardian to send you emails through Facebook");
		$("#sub_error").fadeIn("slow");
	},
	
	
	showFlagVideo: function(){
		if(GuardianLogin.account == null){
			$('#user_not_login span.action').text('Want to flag a Video?');
			GuardianUtil.showModalDialog('user_not_login');
			return;
		}
		
		$("#flag_video_box .clean-error").hide();
		$("#flag_video_box .clean-ok").hide();
		
		GuardianUtil.showModalDialog('flag_video_box');
	},
	
	flagVideo: function(){
		$("#flag_video_box .clean-error").hide();
		if(this.selectedItemId != null){
			var msg = $('#selectedFlagReason').text();
			jsonrpc.videoManager.flagVideo(GuardianSpacePage.flagVideoCbk,GuardianSpacePage.video.id,msg);
		}else{
			$("#flag_video_box .clean-error").fadeIn('slow');
		}
	},
	
	flagVideoCbk: function(e,result){
		if(e){
			return;
		}
		
		$("#flag_video_box .clean-ok").fadeIn('slow');		
		
		var href = "space.page?spaceid=" +  GuardianSpacePage.space.spaceId; 
		setTimeout("document.location = '" + href + "'", 2000);
	},	
	
	selectedItemId:null,
	focusElementId:null,
	
	setVisible: function(id,bool){
		if(bool){
			$('#' + id).show();
			$('#' + id).focus();
		}else{
			//$('#' + id).hide();
		}		
		return false;
	},
	
	selectItem: function(parentId, id, bool){
		if(bool){
			$('#' + parentId).show();
			$('#' + id).parent().css('background-color','#BBCCCC');
			this.focusElementId = id;
		}else{
			//$('#' + parentId).hide();
			$('#' + id).parent().css('background-color','');
			$('#' + this.selectedItemId).parent().css('background-color','#6681BA');
		}		
		return false;
	},
	
	flagReasonSelection: function(parentId, textId, id){
		$('#' + textId).text($('#' + id).text());
		$('#' + this.selectedItemId).parent().css('background-color','');
		$('#' + id).parent().css('background-color','#6681BA');
		this.selectedItemId = id;
		$('#' + parentId).hide();
	},
	
	showAddVideoToSpace: function(){
		if(GuardianLogin.account == null){
			$('#user_not_login span.action').text('Want to add a Video into a Space?');
			GuardianUtil.showModalDialog('user_not_login');
			return;
		}
		
		$("#add_video_box .clean-error").hide();
		$("#add_video_box .clean-ok").hide();
		$("#add_video_box #your_spaces").show();
		
		try{
			var result = jsonrpc.spaceService.getSpacesByAccount(GuardianLogin.account.id,"ORDER_ADDED","ALL",1,100);
			
			var el = $('#add_video_box #spaces_main');
			
			if(result == null || result.list == null){
				$('#add_video_box #your_spaces').hide();
				$('#add_video_box #no_spaces').show();
				GuardianUtil.showModalDialog('add_video_box');
				return;
			}			
		
			var spaces = result.list.list;
			
			if(spaces.length==0){
				$('#add_video_box #your_spaces').hide();
				$('#add_video_box #no_spaces').show();
				GuardianUtil.showModalDialog('add_video_box');			
				return;
			}
		
			GuardianSpacePage.spacesByAccount = spaces;
			$(el).children().remove();
			
			for(i=0;i<spaces.length;i++){ 
				var elId = "spaces_" + spaces[i].spaceId;
 				var html =
				"<li onmouseout=\"GuardianSpacePage.selectItem('spaces_main','" + elId + "', false);\"\ onmouseover=\"GuardianSpacePage.selectItem('spaces_main','" + elId + "', true);\">\
								<a id=\"" + elId + "\" class=\"sub\" onclick=\"GuardianSpacePage.spaceSelection('spaces_main','selectedSpace','" + elId + "','" + i + "');return false;\" href=\"#\" style=\"border-top-width: 1px;\">" + spaces[i].name + "</a>\
			</li>";
				el.append(html);
			}	
			
			if(!GuardianSpacePage.video.external){
				$("#add_video_box .clean-alert span.user_label").text(GuardianSpacePage.video.owner.username);
				$("#add_video_box .clean-alert").show();
			}
			
		}catch(e){
		}
		
		GuardianUtil.showModalDialog('add_video_box');
	},
	
	spacesByAccount: null,
	selectedSpaceIndex: null,
	
	spaceSelection: function(parentId, textId, id, index){
		$('#' + textId).text($('#' + id).text());
		$('#' + this.selectedItemId).parent().css('background-color','');
		$('#' + id).parent().css('background-color','#6681BA');
		this.selectedItemId = id;
		this.selectedSpaceIndex = index;
		$('#' + parentId).hide();
	},
	
	addVideoToSpace: function(){
		$("#add_video_box .clean-error").hide();
		$("#add_video_box .clean-ok").hide();

		if(GuardianSpacePage.selectedSpaceIndex == null){
			$("#add_video_box .clean-error").text("Please select a Space");
			$("#add_video_box .clean-error").fadeIn('slow');
			return;
		}
		else{
			var space = GuardianSpacePage.spacesByAccount[GuardianSpacePage.selectedSpaceIndex];
			jsonrpc.spaceService.addVideoToSpace(GuardianSpacePage.addVideoToSpaceCbk, GuardianSpacePage.video.id,space.spaceId);
		}
	},
	
	addVideoToSpaceCbk: function(result, e){
		if(e){
			return;
		}
	
		if(result != 'OK'){
			$("#add_video_box .clean-error").text(result);
			$("#add_video_box .clean-error").fadeIn('slow');
			setTimeout("GuardianUtil.closeModalDialog()",2000);
			return;
		}
		
		$("#add_video_box .clean-ok").fadeIn('slow');
		$("#add_video_box #your_spaces").fadeOut('slow');
		setTimeout("GuardianUtil.closeModalDialog()",2000);
		return;
	}	
};var ClearSpringController = {

		widget : new Array(),
		spacePage: "space.page",

		/* Init all registered Widgets*/
		init : function() {
			try{
				for (x in this.widget){
					eval(this.widget[x].menu);
				}
			}catch(e){}
		},
		
		initWidget : function(id) {
			try{
				eval(this.widget[id].menu);
			}catch(e){}
		},
		
		/* Register New Widget*/
		register : function(video,spaceId,elementId){
			var wid = video.id;
			var sourceid = "content_"+wid;
			var html = "<div style=\"display:none;\">" +
	    		"<div id=\"content_" + wid + "\">" + 
	    			this.getVideoSharedCode(video.id,spaceId,
	    		   		video.title,video.description,
	    		   		video.imageName,'') + 
	     		"</div></div>";
			
			$("#"+elementId).append(html);			
					
			this.widget[wid] = new Object();
			
			var bookmarkUrl = this.getCurrentPath() + ClearSpringController.spacePage + "?videoid=" + video.id;
			
			if(spaceId != null)
				bookmarkUrl += "&spaceid=" + spaceId;
			
			//var bookmarkUrl = "http://3rdi.selfip.org:8890/stat_mediaplatform/File/clearspringTest3.html?videoId=" + + video.id;
			this.widget[wid].menu = "$Launchpad.CreateMenu({\"userId\": \"48d78b445d1a2f58\", " +
					"\"wid\":\"491ea99028fc0d4b\", \"actionElement\" : \"" + elementId + "\" , " +
					"\"unique\":true, \"useFacebookLink\":true, \"bookmarkUrl\":\"" + bookmarkUrl + "\", " +
					"\"source\": \"" + sourceid + "\", " +
					" \"menuWidth\": 400, \"menuHeight\": 240}); ";
		
		},
		
		getCurrentPath : function(){
			var URL = unescape(location.href);	// get current URL in plain ASCII
			var xstart = URL.lastIndexOf("/") + 1;
			var herePath = URL.substring(0,xstart);
			return herePath;
		},

		getMenu : function(id){
			return this.widget[id].menu;
		},
		
		getVideoSharedCode: function(clipId, spaceId, title, description, thumbnail_url, logo_url){
			var link = this.getCurrentPath() + ClearSpringController.spacePage + "?videoid=" + clipId;
			
			if(spaceId != null)
				link += "&spaceid=" + spaceId;
			
			var chtml = "<div>";
			
			var t_url = thumbnail_url;
			
			var r_url = "" + document.location;
			
			var end = r_url.lastIndexOf("/");
			r_url = r_url.substring("0",end);
						
			if(thumbnail_url.indexOf("http://") == -1){
				t_url = r_url + "/" + thumbnail_url;
			}
		
			var logo2_url = r_url + "/templates/logo_guardian.gif"
			
			chtml += "<div style=\"background:#9bd4e5;border:#6893a0 2px solid;float:left;width:290px;padding:10px 0 10px 10px;font-family:Arial, Helvetica, sans-serif\">";
			chtml += "<div style=\"float:left;width:114px;padding-bottom:15px\"><img style=\"border:2px solid #787878\" src=\"" + t_url + "\" alt=\"Video Thumbnail\"></div>";
            chtml += "<div style=\"float:left;width:162px;padding:0 0 15px 14px\">";
            chtml += "<p style=\"font-size:12px;line-height:16px;padding:0;margin:0\">" 
                      + "<strong style=\"color:#002551;font-weight:bold;font-size:13px\">" + title + "</strong><br>";
            var d = description;
            if(description.length > 200)
            	 d = description.substring(0,200);
            chtml +=  d + "</p>";
    		chtml += "<p><a style=\"font-size:11px;color:#015b7d!important\" href=\"" + link + "\">Watch Video</a></p>";
    		chtml += "</div><div align=\"center\"><img src=\"" + logo2_url + "\"></div></div></div>";
    		return chtml;		
		}		
};
var GuardianManageFriends = {
    audiences_increment_size: 10,
    audiences_size: 10,
    audiences: null,
    audience_remove_message: "Are you sure you want to remove this contact?",
    audience_remove_message_ok: "Your contact was successfully deleted",
    audience_remove_message_error: "There was an error during the removal of the contact, please try again later.",
    audiences_message_sel: ".box_friends_list",
    audience_remove_ok: "Your contact was successfully deleted.",
    audience_update_ok: "Your contacts were successfully updated.",
	
	init: function(){
		if (GuardianLogin.account != null) {
            $(GuardianManageFriends.audiences_message_sel).find(".friends > .cnt_btnupdate > a").attr("href", "javascript:GuardianManageFriends.openImportAudience()");
            $(GuardianManageFriends.audiences_message_sel).find(".friends > .box_border > .clean-alert > a").attr("href", "javascript:GuardianManageFriends.openImportAudience()");
			GuardianManageFriends.getAudience();
		}
		else{
			var page = "manage_friends";
            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(2)").attr("href", joinpage);
            $(".box_friends_list").hide();
            $("#no_account").show();
		}
	},
	getAudience: function () {
        jsonrpc.audienceService.getAllAudienceContact(GuardianManageFriends.getAudienceCallback);
    },
	getAudienceCallback: function (result, e) {
        if (e != null) {
            return;
        }
        if (result == null) {
            return;
        }
        GuardianManageFriends.audiences = result.list;
        $(GuardianManageFriends.audiences_message_sel).find(".box_border > #single_contacts_box").empty();
        GuardianManageFriends.writeAudience(0);
    },
    writeAudience: function (from) {
        var audience_container = $(GuardianManageFriends.audiences_message_sel);
        var total = GuardianManageFriends.audiences.length;
        var box = $(audience_container).find(".box_border > #single_contacts_box");
        var el = $(audience_container).find(".box_border > .user_mail:eq(0)");
        var n = Math.min(GuardianManageFriends.audiences_size, total);
        for (var i = from; i < n; i++) {
            var audience = GuardianManageFriends.audiences[i];
            var el_a = $(el).clone();
            $(el_a).show();
            $(el_a).find(".user_contact").text(audience.contact);
            var r_link = "javascript:GuardianUtil.confirmDialog(GuardianManageFriends.audience_remove_message,'GuardianManageFriends.removeAudienceContact(" + audience.id + ")')";
            $(el_a).find(".remove_contact a").attr("href", r_link);
            $(box).append(el_a);
        }
        if (n < total) {
            $(audience_container).find("#more_contacts").show();
        } else {
            $(audience_container).find("#more_contacts").hide();
        }
        if ($(".box_friends_list").css("display").toLowerCase() == "none") {
            $(".box_friends_list").fadeIn("slow");
        }
        if ($(audience_container).css("display").toLowerCase() == "none") {
            $(audience_container).fadeIn("slow");
        }
        if (GuardianManageFriends.audiences.length == 0) {
            var space_box = $(audience_container).find(".clean-alert").show();
        } else {
            var space_box = $(audience_container).find(".clean-alert").hide();
        }
    },
    moreAudiences: function () {
        var hold = GuardianManageFriends.audiences_size;
        GuardianManageFriends.audiences_size += GuardianManageFriends.audiences_increment_size;
        GuardianManageFriends.writeAudience(hold);
    },
    openImportAudience: function () {
        GuardianAudience.showImportAudience("GuardianManageFriends.closeImportAudience()");
    },
	closeImportAudience: function () {
        GuardianUtil.closeModalDialog();
        GuardianManageFriends.getAudience();
        $(GuardianManageFriends.audiences_message_sel).find(".clean-ok").text(GuardianManageFriends.audience_update_ok);
        GuardianManageFriends.showOkMessage(GuardianManageFriends.audiences_message_sel);
    },
    hideAllMessages: function () {
        $(".clean-ok:visible").fadeOut("slow");
        $(".clean-error:visible").fadeOut("slow");
    },
    hideAllMessages: function (mainSelector) {
        $(mainSelector).find(".clean-ok:visible").fadeOut("slow");
        $(mainSelector).find(".clean-error:visible").fadeOut("slow");
    },
    showOkMessage: function (mainSelector) {
        $(mainSelector).find(".clean-ok").fadeIn("slow");
    },
    showErrorMessage: function (mainSelector) {
        $(mainSelector).find(".clean-error").fadeIn("slow");
    },
	removeAudienceContact: function (audienceId) {
        GuardianManageFriends.hideAllMessages();
        jsonrpc.audienceService.removeAudienceContact(GuardianManageFriends.removeAudienceContactCallback, audienceId);
    },
    removeAudienceContactCallback: function (result, e) {
        if (e != null) {
            return;
            GuardianManageFriends.showErrorMessage(GuardianManageFriends.audiences_message_sel);
        }
        GuardianManageFriends.getAudience();
        $(GuardianManageFriends.audiences_message_sel).find(".clean-ok").text(GuardianManageFriends.audience_remove_ok);
        GuardianManageFriends.showOkMessage(GuardianProfileEdit.audiences_message_sel);
    }
};
var GuardianMioBox = {

	CAPTCHA_WRONG:"The verification text is wrong",
	login_join_callback_page: 'buy',
	callback_page: "/",
	
    init:function(){
    	//if (GuardianLogin.account != null) {
    		$("#email").val("");//GuardianLogin.account.email);
    		$("#name").val("");//GuardianLogin.account.firstName);
    		$("#last_name").val("");//GuardianLogin.account.lastName);
    		$("#phone").val('');
    		$("#address").val('');
    		$("#message").val('');
    		$("#verification").val('');
    	
    		$('#subscribe').parent().attr('href','javascript:GuardianMioBox.sendMsg();');
    	/*} else {
            var page = GuardianMioBox.login_join_callback_page;
            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(2)").attr("href", joinpage);
            $(".list3").children().hide();
            $("#no_account").show();
        }*/
    },

	sendMsg:function(){
    	$('.clean-ok').fadeOut('slow');
    	$('.clean-error').fadeOut('slow');
    	    	
    	var f = true;
        var msg = "";
        
        $("#email").css('border-color','');
	  	$("#name").css('border-color','');
	  	$("#last_name").css('border-color','');
	  	$("#address").css('border-color','');
	  	$("#phone").css('border-color','');
		$("#message").css('border-color','');
		$("#verification").css('border-color','');
		
		
		var username=$("#name").val();
       	if(username == ""){
           		msg += "&#8226; The name is empty.<br />";
           		$("#name").css('border-color','red');
				f=false;
       	}
       	
       	var lastname=$("#last_name").val();
       	if(lastname == ""){
           		msg += "&#8226; The last name is empty.<br />";
           		$("#last_name").css('border-color','red');
				f=false;
       	}
       	
		var email=$("#email").val();
		if(!GuardianMioBox.validateEmail(email)){
			msg += "&#8226; The email address doesn't seem to be valid.<br />";
			$("#email").css('border-color','red');
			f=false;
		}
       	
       	var web_address=$("#address").val();
		if(web_address == ""){
           		msg += "&#8226; The address is empty.<br />";
           		$("#address").css('border-color','red');
				f=false;
       	}
		
		var input_msg=$("#message").val();
		if(input_msg == ""){
           		msg += "&#8226; The message is empty.<br />";
           		$("#message").css('border-color','red');
				f=false;
       	}
       			
		var captcha=$("#verification").val();

		var c_message = "Email Address = \n" + email + "\n";
		//c_message += "Message =\n " + input_msg;
		
		if(f==false){
   			$('.clean-error').fadeIn('slow');
			$('.clean-error').html(msg);
			return;
		}
		
		jsonrpc.contact.reportBug(GuardianMioBox.sendMsgCallBack,username,lastname,email,c_message,captcha)
	},
	
	sendMsgCallBack: function(result,e){
		$("#name").css('border-color','');
		$("#last_name").css('border-color','');
	  	$("#email").css('border-color','');
	  	$("#address").css('border-color','');
	  	$("#message").css('border-color','');
		$("#verification").css('border-color','');
	
		if(e != null){
	  		var error = "" + e;
	  		error = error.substring(error.indexOf(':') + 1);
	  		
	  		var msg = error;
	  		
	  		if(error.indexOf("CAPTCHA_WRONG")>0){
	  			msg = GuardianMioBox.CAPTCHA_WRONG;
	  			$("#verification").css('border-color','red');
	  			//$('#verification_l').css('color','red');
	  		}
	  		
	  		$('.clean-error').fadeIn('slow');
			$('.clean-error').html(msg);
			
			GuardianMioBox.newCaptcha();
			return;
	  	}

		$('#clean-ok_sub').fadeIn('slow');
		$('#buy_form').fadeOut('slow');
		setTimeout("document.location='" + GuardianMioBox.callback_page + "'", 2000);
	},
	
	validateEmail: function(str){
	        var at = "@";
	        var dot = ".";
	        var lat = str.indexOf(at);
	        var lstr = str.length;
	        var ldot = str.indexOf(dot);
	        if (str.indexOf(at) == -1) {
	            return false;
	        }
	        
	        if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
	            return false;
	        }
	        
	        if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
	            return false;
	        }
	        
	        if (str.indexOf(at, (lat + 1)) != -1) {
	            return false;
	        }
	        
	        if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
	            return false;
	        }
	        
	        if (str.indexOf(dot, (lat + 2)) == -1) {
	            return false;
	        }
	        
	        if (str.indexOf(" ") != -1) {
	            return false;
	        }
	        
	        return true;
	},
	
	newCaptcha: function(){
   	 	var c = new Date();
    	document.getElementById('captcha_im').src = "JCaptcha?id=" + c.getTime();
	}

};
var GuardianUploadVideo = {
	
	spaceid: null,
	import_page_link: 'import.page?spaceid=',
	space_name_page_link: 'space_name.page?spaceid=',
	
	init: function(){
		var args = GuardianUtil.getArgs();
		this.spaceid = args['spaceid'];
		
		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_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);
        
        	if(space != null && space.owner.id == GuardianLogin.account.id){

				$('#back_link > p > a:eq(0)').attr('href', GuardianUploadVideo.import_page_link+space.spaceId);
				$('#back_link > p > a:eq(1)').attr('href', GuardianUploadVideo.space_name_page_link+space.spaceId);
				$('#back_link > p > a:eq(1) > span').text(space.name);
			
            	$('.box_upload').fadeIn("slow");
          	 	$('.box_metatags_video').fadeIn("slow");
		
				var msize = GuardianUtil.resolveSize(GuardianConf.MAX_FILE_SIZE);
		
				$('#browse_files').fileUpload ({
					'uploader'  : '../swf/upload/uploader.swf',
					'script'    : 'UploadVideo',
					'auto'      : false,
					'multi': true,
					'wmode': 'transparent',
					'sizeLimit': msize,
					'onComplete': this.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);	
		$("#browse_files").fileUploadStart();
	},
	
	fileUploadComplete: function(event, queueID, fileObj, response, data){
	    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];
	    } 
		jsonrpc.videoManager.updateVideo(response, metadata.title, metadata.description, metadata.tags);	
	},
	
	metadataFiles:new Array()
};


/*
Uploadify v1.6.2
Copyright (C) 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,
						cancelImg:     '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;
							}
							
							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 filesize!"; 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.clearFileMetadata();
		},
		
		fileSelectName:function(queueID,filename) {
			$(this).each(function() {
				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).animate({"backgroundColor":"#C9FFCA"},1000);
			});
		},
		
		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': ''});
					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);
