var isDebug = false;
var googleCategories = "ristorante";
var _staticCoupon="/static_loveresto/coupon/";

var stopWords = "ristorante, ristoranti, restaurants, restaurant";

var regionCode = [];
regionCode['01'] = "Abruzzo";
regionCode['02'] = "Basilicata";
regionCode['03'] = "Calabria";
regionCode['04'] = "Campania";
regionCode['05'] = "Emilia Romagna";
regionCode['06'] = "Friuli Venezia Giulia";
regionCode['07'] = "Lazio";
regionCode['08'] = "Liguria";
regionCode['09'] = "Lombardia";
regionCode['10'] = "Marche";
regionCode['11'] = "Molise";
regionCode['12'] = "Piemonte";
regionCode['13'] = "Puglia";
regionCode['14'] = "Sardegna";
regionCode['15'] = "Sicilia";
regionCode['16'] = "Toscana";
regionCode['17'] = "Trentino Alto Adice";
regionCode['18'] = "Umbria";
regionCode['19'] = "Valle D'Aosta";
regionCode['20'] = "Veneto";

var zoomLimit = 7;

/*----------------------------------------------------------------------------------------------------
GuardianFacebookConnector
----------------------------------------------------------------------------------------------------*/
(function(d){
    var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    d.getElementsByTagName('head')[0].appendChild(js);
}(document));
     
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(){	
		try{	
			FB.init({
            	appId: GuardianConf.FACEBOOK_API_KEY,
            	channelUrl:'http://loveresto.com/channel_fb.html',
            	status: true, 
            	cookie: true
            });
		}catch(e){
			//alert(e);
		}
	},	

	loginByFacebook: function(){
		GuardianUtil.showLoading();
		FB.login(GuardianFacebookConnector.loginCallback, {scope:'email'});
	},
	
	logoutByFacebook: function(cbk){
		FB.logout(cbk);
	},
	
	
	loginCallback: function(response){
	 	if (response.authResponse) {
			FB.api('/me', function(info) {
		       //console.log(info.id + "," + info.name + "," + info.first_name + "," +info.last_name + "," + info.gender + "," + info.pic + "," + "" + "," + info.email);
		    
		     	FB.api('/me/picture', function(picture) {
		     		//console.log("picture " + picture);
		     		GuardianLogin.loginByFacebookWithUserProfile(info.id, info.name, info.first_name, info.last_name, info.sex, picture, "");	
		     		GuardianUtil.hideLoading();
		     	});
		    });
		}
		else {
		     //console.log('User cancelled login or did not fully authorize.');
		     GuardianUtil.hideLoading();
		}
	},
	
	clearSession: function(){
		//console.log("Clear Session");
	},
	
	postFeedVideos: function(spaceName, spaceId, spaceImage, videos){
		var user_message_prompt = "What do you think of these?"; 
		var user_message = {value: "write your review here"};
		var body_general = '';
	
		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 = GuardianUtil.getCurrentPath() + "/profile/" + spaceName;
		}
	
		var obj = {
	          method: 'feed',
	          link: GuardianUtil.getCurrentPath() + "/profile/" + spaceName,
	          name: video.title,
	          caption: spaceName,
	          description: video.description
	    };
	    
	    if(video.imageName != null){
			obj.picture = video.imageName;	
		}
		FB.ui(obj, GuardianFacebookConnector.streamFeedVideosCallback);
	},
		
	postFeedVideosCallback: function(r){
		//GuardianAudience.closeFacebookPostLink();
	},
	
	streamFeedVideosCallback: function(r, e){		
		//GuardianAudience.closeFacebookPostLink();
	}
};

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 > span:eq(1)').text(result.username);
		
		$('#utility_links_login .menulink').attr("href","javascript:GuardianLogin.logout()");
		if(!result.external){
			$('#f_account > 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 GuardianUtil = {

		default_page: 'loveresto',

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 = decodeURI(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;
},

getAnchorTag: function(){
	var pairs = location.href.split("#");
	if(pairs.length>1)
		return pairs[1]; 
},

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;
},

getLocation: function(callback){
	var city = GuardianUtil.readCookie("_city_search");
	var lat = GuardianUtil.readCookie("_lat_search");
	var lng = GuardianUtil.readCookie("_lng_search");
	
	var loc = {lat:'',lng:'',city:''};
	
	if(city != null && city != ""){
		loc.lat = lat;
		loc.lng = lng;
		loc.city = city;
		callback(loc);
	}else{
		if(navigator.geolocation){
			navigator.geolocation.getCurrentPosition(
				//OK
				function(position){
					if(position != null){
						
						var geocoder = new google.maps.Geocoder();
						
						request = {};
						request.latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
						
						geocoder.geocode(request, function(results, status) {
							if (status == google.maps.GeocoderStatus.OK) {
								loc.lat = results[0].geometry.location.lat();
								loc.lng = results[0].geometry.location.lng();
								loc.city = getFormattedAddress(results[0].address_components);
								callback(loc);
							}else{
								loc.lat = geoplugin_latitude();
								loc.lng = geoplugin_longitude();
								loc.city = geoplugin_city();
								callback(loc);
							}
						});
					}else{
						//console.log("null");
						loc.lat = geoplugin_latitude();
						loc.lng = geoplugin_longitude();
						loc.city = geoplugin_city();
						callback(loc);
					}
				},
				//ERROR
				function(){
					//console.log("error");
					loc.lat = geoplugin_latitude();
					loc.lng = geoplugin_longitude();
					loc.city = geoplugin_city();
					callback(loc);
				},
				{maximumAge: 30000, timeout:100000}
			);
		}else{
			loc.lat = geoplugin_latitude();
			loc.lng = geoplugin_longitude();
			loc.city = geoplugin_city();
			callback(loc);
		}
	}	
},

getCitiesByRegion: function(){
	jsonrpc.geoWorldCountry.getCitiesByRegion(GuardianUtil.citiesCbk,"IT",$("#regione").val());
	//GuardianAdsManager.citiesCbk();	
},

citiesCbk: function(result,e){
	var list = [];
	
	for(var i=0;i<result.list.length;i++){
		list[list.length] = result.list[i].accentCity;
	}
	$( "#cities" ).autocomplete({
			source: list
	});
},

modalDialogId : null,

showModalDialog: function(divId, closeCbk){
	try{
		GuardianUtil.modalDialogId = divId;
		$("#" + divId).show();
		
		transition = (closeCbk != null ? 'none':'elastic');
		
		$.fancybox({
			'href': "#" + divId,
			'scrolling'	: 'no',
			'titleShow'	: false,
			'centerOnScroll': true,
			'transitionIn'	: transition,
			'transitionOut'	: transition,
			'onClosed': function() {
				$("#" + divId).hide();
				if(closeCbk != null){
					setTimeout(closeCbk,100);
				}
			}
		});
	}catch(e){}	
},

showModalDialog2: function(divId, closeCbk){
	try{
		GuardianUtil.modalDialogId = divId;
		$("#" + divId).show();
		
		transition = (closeCbk != null ? 'none':'elastic');
		
		$.fancybox({
			'href': "#" + divId,
			'scrolling'	: 'no',
			'titleShow'	: false,
			'centerOnScroll': true,
			'transitionIn'	: transition,
			'transitionOut'	: transition,
			'onCleanup': function(event) {
				r = closeCbk();
				if(r == true){
				   $("#" + divId).hide();
				}
				return r;	
			}
		});
	}catch(e){}	
},


showInlineBox: function(objectId, target, closeCbk){
	try{
		$("#" + objectId).show();
		
		$.fancybox({
			'href': "#" + objectId,
			'titleShow'	: false,
			'overlayShow': false,
			'overlayOpacity': 0.6,
			'showCloseButton':false,
			'speedIn': 0,
			'onComplete': function(){
				$('#fancybox-wrap').animate({top:target.offsetTop+10,left:(target.offsetLeft-510)},200);
			},
			'onCleanup': function(event) {
			    closeCbk();
			}
		});
	}catch(e){}	
},
	
closeModalDialog: function(){
	try{
		//alert("Close " + GuardianUtil.modalDialogId);
		//$("#" + GuardianUtil.modalDialogId).hide();
		$.fancybox.close();
	}catch(e){}
},

showLoading: function(){
	$.blockUI.defaults.overlayCSS.opacity = '0.1';
	$.blockUI({ 
		message: $('#loading'),
		allowBodyStretch: true
	});
},

showUploading: function(msg){
	$.blockUI.defaults.overlayCSS.opacity = '0.6';
	$.blockUI({ 
		message: "<h1 style='width: 300px; color: #FFFFFF;'>" + msg + "</h1>",
		allowBodyStretch: true
	});
},


hideLoading: function(){
	$.unblockUI();
},

showLoadingMap: function(message){
	$("#loading_map").text(message);
	$("#loading_map").show();
},

hideLoadingMap: function(){
	$("#loading_map").fadeOut("slow");
},

confirmDialog: function(message,callFunction){
	content = "<div class='box_overlay' style='width:300px; padding-left: 20px; padding-right: 20px; padding-bottom: 20px; text-align:center;'><h3 style='margin-bottom: 0;'>" + message + "</h3><div style='text-align: left; height: 20px; margin-top:10px;'><a id='yes' style='margin-left: 60px;'>" + _messages.yes + "</a><a style='margin-left:90px;' id='no'>" + _messages.no + "</a></div></div>";
	
	$.fancybox({
		'content': content,
		'scrolling'	: 'no',
		'titleShow'	: false,
		'centerOnScroll': true,
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'onClosed': function() {
			
		}
	});
	
	$('#yes').click(function() { 
		try{
			$.fancybox.close();
		}catch(e){}
		eval(callFunction);
	}); 

	$('#no').click(function() { 
		try{
			$.fancybox.close();
		}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.getMonth()>9 ? date.getMonth(): "0" + date.getMonth()) + "/" + date.getFullYear();
	return formattedDate;
},

createCookie:function(name, value, path, domain, hours)
{
	if (hours) {
		var date = new Date();
		date.setTime(date.getTime()+(hours*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+ value + expires + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "");
},

elementRate: function(el_rating,rate){
	if(rate==-1){
		el_rating.attr("src", "/static_loveresto/Image/rating_three.png");
	}else if(rate==0){
		el_rating.attr("src", "/static_loveresto/Image/rating_zero.png");
	}
	else if(rate<=0.2){
		el_rating.attr("src", "/static_loveresto/Image/rating_one.png");
	}
	else if(rate<=0.4){
		el_rating.attr("src", "/static_loveresto/Image/rating_two.png");
	}
	else if(rate<=0.6){
		el_rating.attr("src", "/static_loveresto/Image/rating_three.png");
	}
	else if(rate<=0.8){
		el_rating.attr("src", "/static_loveresto/Image/rating_four.png");
	}
	else{
		el_rating.attr("src", "/static_loveresto/Image/rating_five.png");
	}
}

};

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_log_in .clean-error').hide();
	$('.box_log_in .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_log_in .clean-error').html(msg);
		$('.box_log_in .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_log_in .clean-error').fadeIn('slow');
		$('.box_log_in .clean-error').html(msg);
		GuardianUtil.newCaptcha();
		return;
	}

	$('.box_log_in .clean-ok').fadeIn('slow');

	//hide form
	$('.box_log_in form').hide();
	$('.box_log_in > div > a').hide();
	$('.box_log_in > 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 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) {
		return;
	}
	var video = result;		 
	GuardianVideoPlayer.fillDivVideoPlayer('videoPlayer',video.title, video.description, video.videoName, video.imageName, video.duration, video.external, video.externalId, video.externalCdn, video.embedCode, '640', '360');
},

fillDivVideoPlayer: function(divId, title, description, videoUrl, imageUrl, duration, external, externalId, externalCdn, embedCode, width, height){
	// browser web - flash
	var isMobile = false;
	if(GuardianConf.USER_AGENT.indexOf("iPhone")>0 || GuardianConf.USER_AGENT.indexOf("iPad") > 0)
		isMobile = true;

	if(isMobile==false){
		var flashvars = "";

		var flashvars = {};
		var params = {
				allowfullscreen:'true',
				allowscriptaccess:'always',
				allownetworking:'all',
				wmode:'opaque'
		};

		if(!external && !externalCdn){
			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;
			flashvars.bufferlength = 5;
		}		
		else{
			this.playerUrl = embedCode + "&rel=0&showinfo=0&hd=1";
		}

		this.videoDescription = description;

		this.lessDescriptionSize(divId);

		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);
		}	
	}

	//ios - html5
	else{
		if(!external && !externalCdn){
			var v_frame = "<video src=\"" + videoUrl + "\" width=" + width + " height=" + height + "></video>";
			$("#" + divId).html(v_frame);
		}else{
			this.playerUrl = "http://www.youtube.com/embed/" + externalId;
			var v_frame = "<iframe class=\"youtube-player\" type=\"text/html\" width=\"" + width + "\" height=\"" + height + "\" src=\"http://www.youtube.com/embed/" + externalId + "\" frameborder=\"0\"></iframe>";
			$("#" + divId).html(v_frame);
		}	
	}	
},

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);
}

};

var GuardianDropboxConfiguration = {
		
		spaceid: -1,
		space_name_page_link: 'space_name.page',
		space: null,
		yourDropoxElement:		'#dropbox_configuration',
		yourListElement:		'#dropbox_configuration #your_list',
		yourListElement1:		'div:first',
		yourListElement2:		'.spaces_single',
		yourListElement3:		'.spaces_root',
		yourListElement4:		'.spaces_createdate',
		yourListElement5:		'.spaces_delete a',
		noDropboxElement: '',
		
		
		init:function(){
			var args = GuardianUtil.getArgs();
			this.oauth_token = args['oauth_token'];
			this.path = args['path'];
			
			$("form input").val('');
			
			var page = GuardianUtil.getCurrentPage();
	        
	        var loginpage = "login.page?callback=" + page;
			var joinpage = "join.page?callback=" + page;
			
			$('#no_account a:eq(0)').attr('href',loginpage);
			
			$("#guardian_DropboxConfiguration").fadeIn("slow");
			
	        if (GuardianLogin.account == null) {
				$("#no_account").fadeIn("slow");
				$("#your_spaces").hide();
				return;
	        }
	        
			if(this.oauth_token){
				GuardianUtil.showLoading();
		  		
				try{
					var r = jsonrpc.dropboxManager.callbackAccessTokenPartner(this.path);
				}catch(ex){
				}
				
				document.location = GuardianUtil.getCurrentPath() + "dropbox_configuration.page";
			}else{
				this.getDropboxConfiguration();
		   }
	  	},
	  	
	  	makeAuthRequest: function(){
	  		GuardianUtil.showLoading();
	  		
	  		path = $("#path").val();
	  		if(path == ""){
	  			alert("Inserire il path della directory dropbox da importare");
	  			return;
	  		}
	  		
			var callback = document.location + "?path=" + path;
			var url = jsonrpc.dropboxManager.requestAccessToken("" + callback);
			document.location = url;
		},
		
		deleteConfiguration: function(id){
			GuardianUtil.confirmDialog("Are you sure you want to delete your Dropbox Account?","GuardianDropboxConfiguration.postDeleteAccount('" + id + "');");
		},
		
		postDeleteAccount: function(id){
			jsonrpc.dropboxManager.deleteAccountConfiguration(id);
			GuardianDropboxConfiguration.init();
		},
		
		createAccountCbk: function(result, e){
			GuardianUtil.hideLoading();
			if(e){
				alert(e);
			}
			
			$('.clean-ok').fadeIn("slow");
			$('.create_space').fadeOut("slow");
			
			GuardianDropboxConfiguration.init();
		},

		getDropboxConfiguration: function(){
			var el = $(GuardianDropboxConfiguration.yourListElement);
			var el_c  = el.find(GuardianDropboxConfiguration.yourListElement1);
			el.html("");
			el.append(el_c);
			jsonrpc.dropboxManager.getDropboxAccountConfiguration(
					this.getDropboxConfigurationCbk);
		},
		
		getDropboxConfigurationCbk: function(result, e){
			if(e != null){
				return;
			}
			
			$('.create_space').fadeIn("slow");
			
			if(result == null || result.list == null || result.list.length == 0){
				$(GuardianDropboxConfiguration.yourDropoxElement).hide();
				$(GuardianDropboxConfiguration.noDropboxElement).fadeIn('slow');
				return;
			}			
			
			var configurations = result.list;
			var el;
			
			el = $(GuardianDropboxConfiguration.yourListElement);
			
			var html;
			for(i=0;i<configurations.length;i++){ 
				var el_c = $(el).find(GuardianDropboxConfiguration.yourListElement1).clone();
				var el_name = el_c.find(GuardianDropboxConfiguration.yourListElement2);
				$(el_name).text(configurations[i].username);
				el_c.find(GuardianDropboxConfiguration.yourListElement3).text(configurations[i].rootFolder);
				el_c.find(GuardianDropboxConfiguration.yourListElement4).text(configurations[i].insDate);
				el_c.find(GuardianDropboxConfiguration.yourListElement5).attr("href","javascript:GuardianDropboxConfiguration.deleteConfiguration(" + configurations[i].accountId + ")");
				el.append(el_c);
				el.append("<br/>");
				el_c.show();
			}	
			$(GuardianDropboxConfiguration.yourDropoxElement).fadeIn("slow");
		}

};


var GuardianSearchPartners = {
		page: 1,
		page_size: 8,
		filter: "ALL",
		order: "ORDER_ADDED",
		linkpage: 'space.page',
		spaces: [],
		query:"",
		zoomLevel:15,
		distance: 10,
		total: 50,
		callID: 0,
		returnType:"PARTNER_SMALL",
		groupbBy:null,
		
		init: function(){
			$(".searchItem input:checkbox").bind("click",GuardianSearchPartners.loadPartnerList);
			$("#selectTest1").bind("change",GuardianSearchPartners.loadPartnerList);
			
			var tag = GuardianUtil.getAnchorTag();
    		if(tag == "list"){
    			activeLink();
    			refreshMap = true;
    			goToList();
    		}else{
    			$("#mappa").show();
    			$("#reload_pin").show();
    		}	
			
			var c = $("#cities").val();
			GuardianSearchPartners.address = c;
			
			var list = $(".searchItem input:checked");
			var cat = "";
			for(i=0;i<list.length;i++){
				cat += $(list[i]).val();
				if(i != list.length-1){
					cat += ",";
				}
			}
				
			if(($("#selectTest1").val())!=-1){
				cat += "," +$("#selectTest1").val(); 
			}
				
			GuardianSearchPartners.categories = cat;
			
			q = $("#Search input").val().toLowerCase();
			$.trim(q);
			
			if(q == null || q == _messages.examplewhat.toLowerCase() || stopWords.indexOf(q)>0)
    			q = "";
			q = q + cat;
				
			GuardianSearchPartners.query = q;
					
			GuardianSearchPartners.loadPartnerList();
		},
		
		loadPartnerList: function () {
			//console.log(GuardianSearchPartners.query + " " + GuardianSearchPartners.address);
			if(GuardianSearchPartners.query != "" && GuardianSearchPartners.address == ""){
				GuardianSearchPartners.mylatitude = null;
				GuardianSearchPartners.mylongitude = null;
				$("#reload_pin").hide();
				GuardianSearchPartners.myaddress = GuardianSearchPartners.address;
				GuardianSearchPartners.loadPartnerListByLatLong();
			}
			
			//indirizzo
			else if(GuardianSearchPartners.address != null && GuardianSearchPartners.address != ""){
				inputAddress = GuardianSearchPartners.address;
				
				var request = {
					address : inputAddress
				};
				
				b_ne_lat = GuardianUtil.readCookie("_latlng_bounds_ne_lat");
				b_ne_lng = GuardianUtil.readCookie("_latlng_bounds_ne_lng");
				b_sw_lat = GuardianUtil.readCookie("_latlng_bounds_sw_lat");
				b_sw_lng = GuardianUtil.readCookie("_latlng_bounds_sw_lng");
				if(b_ne_lat != null && b_sw_lat != null){
					lat_ne = new google.maps.LatLng(b_ne_lat,b_ne_lng);
					lat_sw = new google.maps.LatLng(b_sw_lat,b_sw_lng);
					b = new google.maps.LatLngBounds(lat_sw,lat_ne);
					request = {
						address : inputAddress,
						bounds: b
					};
				}
				
				//console.log("Bound " + request.bounds);
				var geocoder = new google.maps.Geocoder();
				geocoder.geocode(request, function(results, status) {
					//console.log(results[0].geometry.viewport);
					if (status == google.maps.GeocoderStatus.OK) {
						GuardianSearchPartners.latitude = results[0].geometry.location.lat();
						GuardianSearchPartners.longitude = results[0].geometry.location.lng();
						t = results[0].geometry.types;
						b = results[0].geometry.viewport;
						//console.log(results[0].geometry.viewport);
						vd =(calculateDistance(b.getNorthEast().lat(),b.getNorthEast().lng(), GuardianSearchPartners.latitude,  GuardianSearchPartners.longitude)/1000);
						if(vd<5)
							vd = 5;
						
						GuardianSearchPartners.distance = vd;
						GuardianSearchPartners.address = results[0].formatted_address;
						GuardianUtil.createCookie("_city_search",$("#cities").val(),null,null,2);
						GuardianUtil.createCookie("_lat_search",GuardianSearchPartners.latitude,null,null,2);
						GuardianUtil.createCookie("_lng_search",GuardianSearchPartners.longitude,null,null,2);
					}
					GuardianSearchPartners.mylatitude = GuardianSearchPartners.latitude;
					GuardianSearchPartners.mylongitude = GuardianSearchPartners.longitude;
					GuardianSearchPartners.myaddress = GuardianSearchPartners.address;
					GuardianSearchPartners.loadPartnerListByLatLong();
				});
			}
			
			//localizzazione dell'utente
			else {
				//console.log("Localizzazione dell'utente");
				
				GuardianUtil.getLocation(function(coords){
					GuardianSearchPartners.latitude = coords.lat;
					GuardianSearchPartners.longitude = coords.lng;
					GuardianSearchPartners.address = coords.city;
					
					$("#cities").val(coords.city);
					
					GuardianSearchPartners.mylatitude = GuardianSearchPartners.latitude;
					GuardianSearchPartners.mylongitude = GuardianSearchPartners.longitude;
					GuardianSearchPartners.myaddress = GuardianSearchPartners.address;
					GuardianSearchPartners.loadPartnerListByLatLong();
				});
			}
		},
		
		loadPartnerListByLatLong: function () {
				GuardianUtil.showLoadingMap(_messages.loadingmap);
				
				clearMarkers();
	
				GuardianSearchPartners.spaces = [];  	
			
				var userType = "PARTNER_RECOMMENDED,PARTNER_RECOMMENDED_TOP";
				
				GuardianSearchPartners.checkDistance = true;
				q = GuardianSearchPartners.query;
				result = null; 	
				if(q != ""){
					if(GuardianSearchPartners.latitude != null){
						//console.log("Textual Search Spaces " + q + " " + GuardianSearchPartners.distance);
						result = jsonrpc.searchService.textualSearchSpacesPartnerByDistance(q,GuardianSearchPartners.latitude, GuardianSearchPartners.longitude, GuardianSearchPartners.distance, 0, GuardianSearchPartners.total,"AND");
						
						if(locationFromMap == false && result.total >0 && result.list.list.length>0){
							GuardianSearchPartners.latitude = result.list.list[0].latitude;
							GuardianSearchPartners.longitude = result.list.list[0].longitude;
						}
						
					}else{
						GuardianSearchPartners.searchAll();
						return;
					}
				}
				else{
					//console.log("" + GuardianSearchPartners.latitude);
					if(GuardianSearchPartners.latitude != null){
						if(GuardianSearchPartners.groupBy == "city"){
							result = jsonrpc.partnerService.getPartnersGroupByNearTo("", "", "", "", userType, GuardianSearchPartners.latitude, GuardianSearchPartners.longitude,
									GuardianSearchPartners.distance, 1, GuardianSearchPartners.total, "city");
						}else{
							result = jsonrpc.partnerService.getPartnersInChannelByCategoriesNearTo("", "ORDER_DISTANCE", "", "", userType, GuardianSearchPartners.latitude, GuardianSearchPartners.longitude,
								GuardianSearchPartners.distance, 1, GuardianSearchPartners.total, GuardianSearchPartners.returnType);
						}
					}
				}
				
				GuardianSearchPartners.callID++;
				GuardianSearchPartners.searchSpaceListCallback(result,GuardianSearchPartners.callID);	
		},
		
		searchAll: function () {
			//console.log("SearchAll"); 
			GuardianSearchPartners.callID++;
			
			allResults = null;
			if(GuardianSearchPartners.query != ""){
				//console.log("SearchAll"); 
				allResults = jsonrpc.searchService.textualSearchSpacesPartnerByQuery(GuardianSearchPartners.query, 0, GuardianSearchPartners.total,"AND");
			}
			if(allResults== null || allResults.list.list.length == 0){
				$("#loading_map").text(_messages.error_loading_map);
				if(GuardianSearchPartners.latitude == null){
					$("#mappa").hide();
					return;
				}
			}else{
				GuardianSearchPartners.latitude = allResults.list.list[0].latitude;
				GuardianSearchPartners.longitude = allResults.list.list[0].longitude;
			}
			
			GuardianSearchPartners.searchSpaceListCallback(allResults,GuardianSearchPartners.callID);
		},
		
		searchSpaceListCallback: function (result,callID) { 
			//console.log("Call ID " + callID);   	
			if(GuardianSearchPartners.callID != callID){
				//console.log("Discard Result ID " + callID);
				return;
			}
				
			results =  {};
			
			if (result == null || result.list.list.length == 0) {
				//console.log("No Result");
			}else{
				results = result.list.list;
			}   
			
						
			for(var i=0;i<results.length;i++){
				d = null;
				
				idx = GuardianSearchPartners.spaces.length;
				GuardianSearchPartners.spaces[idx] = results[i];
				GuardianSearchPartners.spaces[idx].distance = calculateDistance(GuardianSearchPartners.latitude,GuardianSearchPartners.longitude,results[i].latitude,results[i].longitude);
			 	GuardianSearchPartners.spaces[idx].distance = d;
			 	GuardianSearchPartners.spaces[idx].weight = 1000 + i;
			}	
			
			GuardianSearchPartners.totalLover = GuardianSearchPartners.spaces.length;
			
			//draw map
			loadGooglePlaces(GuardianSearchPartners.query, callID);
		},
				
		drawList: function(p){
			
			$('#allPartners').find('td').hide();
			if(GuardianSearchPartners.spaces == null){
				GuardianUtil.hideLoading();
				return;
			}
		
			var spaces = GuardianSearchPartners.spaces;
			
			
			GuardianSearchPartners.pagination(spaces.length);
			start = this.page_size*(p-1);
			end = this.page_size + start;
			
			if(end > spaces.length)
				end = spaces.length;
			
			//console.log("drawList page " + p + ", s=" + start + ", e=" + end);
			
			idx = 0;
			for(var i=start; i<end; i++) {
				var el = $($('#allPartners').find('td')[idx]);
				idx++;
				var text = $(el).find('.menulink');
				
				if(spaces[i].type != null){
			  		spaces[i].owner = {};
			  		spaces[i].owner.type = spaces[i].type;
				}
				
				//get details
				if(spaces[i].owner.type!="GOOGLE" && GuardianSearchPartners.groupbBy == null){
					spaces[i] = jsonrpc.partnerService.getPartnerDetails(spaces[i].spaceId);
				}
				
				//name
				a = spaces[i].name;
				if(a.length > 20)
					a = a.substring(0,20) + "....";
				$(text).text(a);
				
				//icon
				if(spaces[i].imageIcon == "templates/defaultThumb.jpg")
					spaces[i].imageIcon = "/static_loveresto/Image/videoThumbNull.png";
				
				$(el).find('.thumbnail').attr("src",spaces[i].imageIcon);
				
				if(spaces[i].html){
					$(el).find('.thumbnail').html(spaces[i].html);
				}
				
				//address
				a = spaces[i].address;
				$(el).find('.result_address').text(a);
				
				//cucina
				c = $(el).find('.result_phone');
				
				if(spaces[i].owner.type=="GOOGLE"){
					GuardianSearchPartners.listItemGoogleDetail(i,c);					
				}else{
					if(spaces[i].owner.phoneNumber != null){
						c.text(spaces[i].owner.phoneNumber);
					}else{
						c.text(_messages.unavailable);
					}
				}
				
				var rat = $(el).find('.rating');
				if(spaces[i].rate != null){
					GuardianUtil.elementRate(rat,spaces[i].rate);
					rat.show();
				}else{
					rat.hide();
				}
				
				//type
				//shape
				$(text).attr("href", "#");
				$(el).find('.partnersListBox').unbind("click");
				$(el).find('.partnersListBox').bind("click",{"spaceid":spaces[i].spaceId},function(event){document.location = "partnerProfile.page?spaceid=" + event.data.spaceid});
				
				if(spaces[i].owner.type == "PARTNER_RECOMMENDED_TOP"){
                                        
					//url("/static_loveresto/Image/iconaVip.png") no-repeat scroll center center #FDEBC4
					$(el).find('.partnersListBox div').css('background-image','url("/static_loveresto/Image/iconaVip.png")');
				}else if(spaces[i].owner.type == "PARTNER_RECOMMENDED" && spaces[i].videos > 0){
					$(el).find('.partnersListBox div').css('background-image','url("/static_loveresto/Image/IconaVideo.png")');
 
				}else if(spaces[i].owner.type == "PARTNER_RECOMMENDED"){
					$(el).find('.partnersListBox div').css('background-image','url("/static_loveresto/Image/iconaNoVideo.png")');
 
				}else{
					$(el).find('.partnersListBox').unbind("click");
					$(el).find('.partnersListBox').bind("click",{"idx":i},function(event){showGoogleDetails(event.data.idx)});
					$(el).find('.partnersListBox div').css('background-image','url("/static_loveresto/Image/google_pointer.png")');
				}
				el.show();
			}
			GuardianUtil.hideLoading();
		},
		
		
		pagination: function (total) {
			//alert("total " + total);
			var nPages = Math.ceil(total / this.page_size);
			
			var prev = $('#paginazione > span:first');
			prev.unbind("click");
			prev.css("visibility","hidden");
			
			if (this.page > 1){
				prev.bind("click",{p:this.page-1},GuardianSearchPartners.changePage);
				prev.css("visibility","visible");
			}
			var more = $('#paginazione > span:last');
			more.unbind("click");
			more.css("visibility","hidden");
			
			if (nPages != 0 && this.page != nPages){
				more.bind("click",{p:this.page+1},GuardianSearchPartners.changePage);
				more.css("visibility","visible");
			}
		},

		changePage: function (event) {
			GuardianSearchPartners.page = event.data.p;
			GuardianUtil.showLoading();
			setTimeout(function(){GuardianSearchPartners.drawList(GuardianSearchPartners.page)},100);
			GuardianUtil.hideLoading();
		},
		
		viewLightBoxVideo: function(sid){
			GuardianPartnerProfile.initLightBoxVideo(sid);
			GuardianUtil.showModalDialog("video_lbox");
		},
		
		listItemGoogleDetail: function(i,phone_el){
			var request = {
  				reference: GuardianSearchPartners.spaces[i].reference
			};
			
			placeService.getDetails(request,
				function (place, status) {
				  		if (status == google.maps.places.PlacesServiceStatus.OK) {
				  			//console.log(place.name + " " + place.international_phone_number);
  							space = GuardianSearchPartners.spaces[i];
  							space.address = place.formatted_address;
							addr_list = place.address_components;
									
							for(var z=0;z<addr_list.length;z++){
								addr_types = addr_list[z].types;
								for(var t=0;t<addr_types.length;t++){
									if(addr_types[t] == "locality"){
										space.city = addr_list[z].long_name;
									}
									if(addr_types[t] == "administrative_area_level_1"){
										space.region = addr_list[z].long_name;
									}
									if(addr_types[t] == "country"){
										space.country = addr_list[z].long_name;
									}
								}
							}
							space.google_id = place.id; 
							space.owner.phoneNumber = place.international_phone_number;
  							
  							if(place.international_phone_number != null){
  								phone_el.text(place.international_phone_number);
							}else{
								phone_el.text(_messages.unavailable);
							}
							
							GuardianSearchPartners.spaces[i] = space;
  						}	
  				});
		}
				
};


var GuardianPartnerProfile = {
	video: null,	
	video_id: null,
	space_id:null,
	video_width: 350,
	video_height: 267,
	space:null,
	videos:null,
	page: 1,
	page_size: 12,
	filter: "ALL",
	order: "ORDER_ADDED",
		
	
	init:function(){
		var args = GuardianUtil.getArgs();
		GuardianPartnerProfile.space_id = args['spaceid'];

		var page = 'partnerProfile';
		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","570px");	
		$('#user_logged').css("width","330px");
		
		/*$(".voteUp").click(GuardianPartnerProfile.voteUp);
		$(".voteDown").click(GuardianPartnerProfile.voteDown);
		*/
		
		//nuova pagine
		$(".votoPositivo").click(GuardianPartnerProfile.voteUp);
		$(".votoNegativo").click(GuardianPartnerProfile.voteDown);
		
		space = jsonrpc.partnerService.getPartnerDetails(GuardianPartnerProfile.space_id);
		
		result = jsonrpc.spaceService.getSpaceProperty(space.spaceId,"SERVICES");
		if(result==null){
			//$(".tabnav li").show();
		}else{
			eval("settings = " + result.value);
			$(".tabnav li:gt(2)").hide();

			for(i=0;i<settings.length;i++){
		    	if(settings[i]=="sImage"){
		    		jsonrpc.spaceService.getImagesInSpace(GuardianPartnerProfile.getImageListCallback, GuardianPartnerProfile.space_id,"","ORDER_INDEX","",0,100);
		    	}
		    	if(settings[i]=="sMenu"){
		    		jsonrpc.spaceService.getDocumentsInSpace(GuardianPartnerProfile.getDocumentListCallback, GuardianPartnerProfile.space_id,"","ORDER_INDEX","",0,100);
		    	}
		    	if(settings[i]=="sNews"){
		    		jsonrpc.spaceService.getTextContentInSpace(GuardianPartnerProfile.getNewsListCallback, GuardianPartnerProfile.space_id,"","ORDER_INDEX","",0,100);
		    	}
		    	if(settings[i]=="sCoupon"){
					jsonrpc.couponManager.getActiveCouponBySpaceId(GuardianPartnerProfile.getCouponCallback, GuardianPartnerProfile.space_id);
		    	}
		    }
		}
		
		//subscription
		GuardianPartnerProfile.getSubscriptionInfo();
    	
		//shape
		space.markerIcon = "";
		if(space.owner.type == "PARTNER_RECOMMENDED_TOP"){
			space.markerIcon = "http://loveresto.com/static_loveresto/Image/iconaVip.png";
		}else if(space.owner.type == "PARTNER_RECOMMENDED"){
			space.markerIcon = "http://loveresto.com/static_loveresto/Image/iconaNoVideo.png";
		}
		GuardianPartnerProfile.space = space;
		
		//VIDEO
		jsonrpc.spaceService.getFirstVideoInSpace(GuardianPartnerProfile.getVideoCallback,GuardianPartnerProfile.space_id);
		
		//COMMENTS
		jsonrpc.commentService.getSpaceComments(GuardianPartnerProfile.getCommentsCbk,GuardianPartnerProfile.space_id);
		
		
		$(".tabnav li:eq(1)").show();
		$(".tabnav li:eq(2)").show();
		
		a = space.name;
		if(a.length > 30)
			a = a.substring(0,27) + "...";
		$("#titoloPartner .planresto").text(a);
		
		//nuova pagina
		$(".tab h2.titlePartner").text(a);
		
		var rat = $("#rating_box").find("img:first");
		GuardianUtil.elementRate(rat,space.rate);
		
		//nuova pagina
		GuardianUtil.elementRate($(".ratingBox").find("img:first"),space.rate);
		
		$("#f_address").text(space.address);
		$("#f_date").text(space.creationDate);
		
		GuardianPartnerProfile.fillMetadataField("#f_phone",space.owner.phoneNumber);
		GuardianPartnerProfile.fillMetadataFieldWeb("#f_web",space.owner.website);
		GuardianPartnerProfile.fillMetadataFieldWeb("#f_trip_advisor",space.categories.map.trip_advisor);
		GuardianPartnerProfile.fillMetadataFieldWeb("#f_googleplaces",space.categories.map.googleplaces);
		GuardianPartnerProfile.fillMetadataFieldWeb("#f_wikipedia",space.categories.map.wikipedia);
		GuardianPartnerProfile.fillMetadataFieldWeb("#f_facebook",space.categories.map.facebook);
		GuardianPartnerProfile.fillMetadataFieldWeb("#f_twitter",space.categories.map.twitter);
		GuardianPartnerProfile.fillMetadataFieldMail("#f_mail",space.owner.email);
		GuardianPartnerProfile.fillMetadataField("#f_cucina",space.categories.map.cucina);
		GuardianPartnerProfile.fillMetadataField("#f_specialita",space.categories.map.specialita);
		GuardianPartnerProfile.fillMetadataField("#f_consigliato",space.categories.map.consigliato);
		GuardianPartnerProfile.fillMetadataField("#f_ambiente",space.categories.map.ambiente);
		GuardianPartnerProfile.fillMetadataField("#f_prezzo",space.categories.map.prezzo);
		GuardianPartnerProfile.fillMetadataField("#f_pagamento",space.categories.map.pagamento);
		GuardianPartnerProfile.fillMetadataField("#f_chiusura",space.categories.map.chiusura);
		GuardianPartnerProfile.fillMetadataField("#f_servizi",space.categories.map.servizi);
		
		$('#social_box .menulink').click(function(){showSpaceDetailsOnMap(GuardianPartnerProfile.space)});	
		
		//nuova pagina
		$('.mapButton').click(function(){showSpaceDetailsOnMap(GuardianPartnerProfile.space)});	
		
		//chiamo l'incremento della view dello space
		GuardianPartnerProfile.incrementSpaceViews();
		
		AddThisController.register(null,space.spaceId,space.name,"shareButton");
		AddThisController.init();
	},

	fillMetadataField:function(id,value){
		if(value != null && value != ""){
			$(id).text(value);
		}else{
			$(id).text(_messages.unavailable);
		}
	},
    
    fillMetadataFieldWeb:function(id,value){
		if(value != null && value != ""){
			$(id).html('<a class="menulink" href="'+value+'" target="blank">'+value+'</a>');
		}else{
			$(id).text(_messages.unavailable);
		}
	},
    
    fillMetadataFieldMail:function(id,value){
		if(value != null && value != ""){
			$(id).html('<a class="menulink" href="mailto:'+value+'" target="blank">'+value+'</a>');
		}else{
			$(id).text(_messages.unavailable);
		}
	},
	
	initLightBoxVideo:function(s_id){
		var video = jsonrpc.spaceService.getFirstVideoInSpace(s_id);
		
		if(video == null){
			//no video
		}
		
		a = video.title;
		if(a.length > 50)
			a = a.substring(0,50) + "....";
		
		$('#l_titoloVideoBox').text(a);	

		GuardianVideoPlayer.fillDivVideoPlayer("l_video_box", 
				video.title,
				video.description,	                                            
				video.videoName, 
				video.imageName,
				video.duration, 
				video.external,
				video.externalId,
				video.externalCdn,
				video.embedCode,
				480, 
				360);

		if(video.external){
			GuardianPartnerProfile.incrementVideoViews();
		}else{
			GuardianVideoPlayer.addViewListener("PLAY","GuardianPartnerProfile.incrementVideoViews");		
		}
	},
	
	initLover:function(){
		GuardianPartnerProfile.space_id = 5589;

		var page = 'userProfile';
		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");
		
		$(".voteUp").click(GuardianPartnerProfile.voteVideoUp);
		$(".voteDown").click(GuardianPartnerProfile.voteVideoDown);
	
		space = jsonrpc.partnerService.getPartnerDetails(GuardianPartnerProfile.space_id);
		GuardianPartnerProfile.space = space;
		
		jsonrpc.spaceService.getVideosInSpace(GuardianPartnerProfile.getVideoListCallback, GuardianPartnerProfile.space_id,"","","",GuardianPartnerProfile.page,GuardianPartnerProfile.page_size);
		
		GuardianPartnerProfile.incrementSpaceViews();
	},
	
	changeVideo: function(idx){
		video = GuardianSearchPartners.videos[idx];
		if(video == null)
			return;
			
		var rat = $("#rating_box").find("img:first");
		GuardianUtil.elementRate(rat,video.rating);	
		
		GuardianPartnerProfile.getVideoCallback(video,null);
	},
	
	getVideoCallback: function(result, e){

		if (e != null) {
			return;
		}

		if(result==null){
			//nuova pagina
			$(".tabnav li:eq(1) a").addClass("active");
			$("#tab1").hide();
			$("#tab2").show();
			$("#titoloVideoBox").text(_messages.map);
			var lat = GuardianPartnerProfile.space.latitude;
			var lng = GuardianPartnerProfile.space.longitude;
			getSpaceOnMap(GuardianPartnerProfile.space,"video_box");
			return;
		}
		
		$(".tabnav li:eq(0)").show();
		$(".tabnav li:eq(2)").show();
		
		var video = result;	
		GuardianPartnerProfile.video = video;
		GuardianPartnerProfile.video_id = result.id;
		GuardianPartnerProfile.video_exid = result.externalId;

		a = video.title;
		
		if(a.length > 15)
		  a = a.substring(0,15) + "....";
		  
		if(GuardianUtil.getCurrentPage() == "userProfile"){
			a = "FIAMMETTA CICOGNA";
		}  
			
		$('#titoloVideoBox').text(a);	

		GuardianVideoPlayer.fillDivVideoPlayer("video_box", video.title, video.description,	video.videoName, video.imageName, video.duration, video.external,	video.externalId, video.externalCdn, video.embedCode, GuardianPartnerProfile.video_width, GuardianPartnerProfile.video_height);

		//nuova pagina		
		GuardianVideoPlayer.fillDivVideoPlayer("big_video_box", video.title, video.description,	video.videoName, video.imageName, video.duration, video.external,	video.externalId, video.externalCdn, video.embedCode, 980, 528);

		if(video.external){
			GuardianVideoPlayer.played = false;
			GuardianPartnerProfile.incrementVideoViews();
		}else{
			GuardianVideoPlayer.addViewListener("PLAY","GuardianPartnerProfile.incrementVideoViews");		
		}

		$(GuardianPartnerProfile.playerElement + " .video_toolbox").fadeIn('slow');
		
		$(".tabNavigation li:last").css("visibility","");			
},

	getVideoListCallback: function(result, e){
		if (e != null) {
			return;
		}
		
		if(result==null){
			return
		}
		
		var total = result.total;
		var results = result.list.list;
		GuardianSearchPartners.videos = results;
		$('#tabLoverVideo').find('td').hide();
		
		if(results.length > 0){
			GuardianPartnerProfile.changeVideo(i);
		}
		GuardianPartnerProfile.pagination(total);
		$('#paginazione').show();
			
		for (i = 0; i < results.length; i++) {        	
			var el = $($('#tabLoverVideo').find('td')[i]);
			var c = el.find("a");
			c.attr("href","javascript:GuardianPartnerProfile.changeVideo('" + i + "')");
			c.html("<img border=\"0\" src=\"" + results[i].imageName  + "\"></img>");
			el.show();
		}
		
},

		pagination: function (total) {
			var nPages = Math.ceil(total / this.page_size);
			
			var prev = $('#paginazione > span:first');
			prev.unbind("click");
			prev.css("visibility","hidden");
			
			if (this.page > 1){
				prev.bind("click",{p:this.page-1},GuardianPartnerProfile.changePage);
				prev.css("visibility","visible");
			}
			var more = $('#paginazione > span:last');
			more.unbind("click");
			more.css("visibility","hidden");
			
			if (nPages != 0 && this.page != nPages){
				more.bind("click",{p:this.page+1},GuardianPartnerProfile.changePage);
				more.css("visibility","visible");
			}
		},

		changePage: function (event) {
			GuardianPartnerProfile.page = event.data.p;
			jsonrpc.spaceService.getVideosInSpace(GuardianPartnerProfile.getVideoListCallback, GuardianPartnerProfile.space_id,"","","",GuardianPartnerProfile.page,GuardianPartnerProfile.page_size);
		},

incrementSpaceViews: function(){
	if(GuardianPartnerProfile.space_id!=null && GuardianPartnerProfile.space_id!=-1){
		jsonrpc.videoPageService.incrementSpaceViews(GuardianPartnerProfile.incrementSpaceViewsCallback,GuardianPartnerProfile.space_id);
	}
},

incrementSpaceViewsCallback: function(result,e){	
},

incrementVideoViews: function(){
	if(!GuardianVideoPlayer.played){
		jsonrpc.videoPageService.incrementViews(GuardianPartnerProfile.incrementVideoViewsCallback,GuardianPartnerProfile.video_id);
		GuardianVideoPlayer.played = !GuardianVideoPlayer.played;
	}		
},

incrementVideoViewsCallback: function(result, e){
},

getCommentsCbk: function(result, e){
	if(e != null)
	  return;
	
	GuardianPartnerProfile.comments = result.list.list;
	//fill Comments
	GuardianPartnerProfile.writeComments({data:{p:1}});
},

writeComments: function(event){
	$('#body_comment').val('');
	GuardianPartnerProfile.updateCounter();
	
	p_size = 4;
	page = event.data.p;
	
	if(GuardianPartnerProfile.comments!=null){
		var comments = GuardianPartnerProfile.comments;
		
		var nPages = Math.ceil(comments.length / p_size);
			
		var prev = $('#paginazione > span:first');
		prev.unbind("click");
		prev.css("visibility","hidden");
			
		if (page > 1){
			prev.bind("click",{p:page-1},GuardianPartnerProfile.writeComments);
			prev.css("visibility","visible");
		}
		
		var more = $('#paginazione > span:last');
		more.unbind("click");
		more.css("visibility","hidden");
			
		if (nPages != 0 && page != nPages){
			more.bind("click",{p:page+1},GuardianPartnerProfile.writeComments);
			more.css("visibility","visible");
		}
		
		start = (page-1)*p_size;
		end = start + p_size;
		
		end = Math.min(comments.length, end);			
		$('#comment_cnt').text("Comments (" + comments.length + ")");

		$('#body_comment').bind("keyup",GuardianPartnerProfile.updateCounter);

		var com_box = $('#comments_content');

		$("#comments_content .commento:not(:first)").remove();

		for(var i=start; i<end ;i++){
			var com=comments[i];
			var el_com = $("#comments_content .commento:first").clone();
			$(el_com).find('.commentoSx div:last').text(com.account.username);
			$(el_com).find('.commentoSx div:first').text(" (" + com.commentAddDate + ")");
			$(el_com).find('.commentoBody').text(com.comment);

			$(el_com).show();

			$(com_box).append(el_com);
		}
	}	
},

updateCounter: function(event){
	var c = $('#body_comment').val();
	if(c.length > 200){
		$('#body_comment').val(c.substring(0,200));
		return;
	}
	
	$('.content_count').text(200-c.length);
},

postComment: function(s){
	var comment = $('#body_comment').val();
	
	if(s == "discard"){
		$('#body_comment').val('');
		return false;
	}

	if(GuardianLogin.account == null){
		$('#user_not_login span.action').text(_messages.comment_want);
		GuardianUtil.showModalDialog('user_not_login');
		return false;
	}
	
	if($.trim(comment)!= ''){
		jsonrpc.commentService.postSpaceComment(GuardianPartnerProfile.space_id,comment);
		//COMMENTS
		jsonrpc.commentService.getSpaceComments(GuardianPartnerProfile.getCommentsCbk,GuardianPartnerProfile.space_id);
	}
	return true;
},

selectCommentAction: function(s){
	GuardianPartnerProfile.submitAction = s;
},

voteUp: function(event){
	if(GuardianLogin.account == null){
		$('#user_not_login span.action').text(_messages.rate_want);
		GuardianUtil.showModalDialog('user_not_login');
		return;
	}

	var res = jsonrpc.spaceService.voteUpSpace(GuardianPartnerProfile.space_id);	
	if(res != -1){
		alert(_messages.rate_ok);
	}else{
		alert(_messages.rate_already);
	}
},

voteDown: function(event){
	if(GuardianLogin.account == null){
		$('#user_not_login span.action').text(_messages.rate_want);
		GuardianUtil.showModalDialog('user_not_login');
		return;
	}
	var res = jsonrpc.spaceService.voteDownSpace(GuardianPartnerProfile.space_id);	
	if(res != -1){
		alert(_messages.rate_ok);
	}else{
		alert(_messages.rate_already);
	}
},

voteVideoUp: function(event){
	if(GuardianLogin.account == null){
		$('#user_not_login span.action').text(_messages.rate_want);
		GuardianUtil.showModalDialog('user_not_login');
		return;
	}

	var res = jsonrpc.videoPageService.rateVideo(GuardianPartnerProfile.video_id,5);	
	if(res != -1){
		alert(_messages.rate_ok);
	}else{
		alert(_messages.rate_video_already);
	}
},

voteVideoDown: function(event){
	if(GuardianLogin.account == null){
		$('#user_not_login span.action').text(_messages.rate_want);
		GuardianUtil.showModalDialog('user_not_login');
		return;
	}
	var res = jsonrpc.videoPageService.rateVideo(GuardianPartnerProfile.video_id,1);	
	if(res != -1){
		alert(_messages.rate_ok);
	}else{
		alert(_messages.rate_video_already);
	}
},

showMap: function(){
	getSpaceWrapper(GuardianPartnerProfile.space,false);
	GuardianUtil.showModalDialog('space_map');
},	

getImageListCallback: function(result,e){
		if(e != null){
			return;
		}
		
		if(result==null || result.list == null ){
			//$('#tab4 .list3 .clean-alert').show();
			return;
		}
		
		var total = result.total;
		
		var list = result.list.list;
		
		if(list.length==0){
			//$('#tab4 .list3 .clean-alert').show();
			return;
		}
		else{
			$(".tabnav li:eq(3)").show();
		
			GuardianPartnerProfile.images = result;
			for(i=0;i<list.length;i++){ 
				var image = list[i];
				var el = $(".list3 .box_content:first").clone();
				GuardianPartnerProfile.buildImageElement(image,el,i);
				$('.list3 .video_list').append(el);
			}
			$('.list3 .video_list').show("slow");
		}
	},
	
	buildImageElement: function(image,el,i){
		$(el).find('img').attr('src',image.thumbnail);
		$(el).find('img').bind("mouseover",function(){$('.preview').css("z-index",-1); $(el).find('.preview').css("z-index",100)});
		$(el).find('.preview').bind("mouseout",function(){$(el).find('.preview').css("z-index",-1)});
		$(el).find('.preview').bind("click",function(){$(el).find('.preview').css("z-index",-1);GuardianSpaceName.initGalleryImage(GuardianPartnerProfile.images,i)});
		el.show();
	},
	
	getDocumentListCallback: function(result,e){
		if(e != null){
			return;
		}
		
		if(result==null || result.list == null ){
			//$('#tab5 .list3 .clean-alert').show();
			return;
		}
		
		var total = result.total;
		
		var list = result.list.list;
		
		if(list.length==0){
			//$('#tab5 .clean-alert').show();
			return;
		}
		else{
			$(".tabnav li:eq(4)").show();
			
			GuardianSpaceName.videos = list;
			for(i=0;i<list.length;i++){ 
				var document = list[i];
				var el = $("#tab5 .documentBox:first").clone();
				GuardianPartnerProfile.buildDocumentElement(document,el,i);
				$('#tab5 .list3').append(el);
				el.show();
			}
			$('#tab5 .list3').show("slow");
		}
	},
	
	buildDocumentElement: function(document,el,i){
		$(el).children('img').attr('src',document.thumbnail);
		$(el).children('img').bind("click",function(){GuardianSpaceName.previewDocument(i);});
		
		$(el).children('.menulink:first').text(document.title);
		$(el).children('.menulink:first').bind("click",function(){GuardianSpaceName.previewDocument(i);});
		
		//$(el).children('img').attr('src',document.thumbnail);
	},
	
	getNewsListCallback: function(result,e){
		if(e != null){
			return;
		}
		
		if(result==null || result.list == null ){
			//$('#news_content .clean-alert').show();
			return;
		}
		
		var total = result.total;
		
		var list = result.list.list;
		
		if(list.length==0){
			//$('#news_content .clean-alert').show();
			return;
		}
		else{
			$(".tabnav li:eq(6)").show();
			
			for(i=0;i<list.length;i++){ 
				var news = list[i];
				var el = $("#news_content .commento:first").clone();
				//GuardianPartnerProfile.buildImageElement(image,el,i);
				$(el).find('.commentoSx div:eq(0)').text("News del " + news.creationDate);
				$(el).find('.commentoSx div:eq(1)').text("News del " + news.title);
				$(el).find('.commentoBody').text(news.description);
				$(el).show();
				$('#news_content').append(el);
			}
			$('#news_content').show("slow");
		}
	},
	
	getCouponCallback: function(result,e){
		if(e != null)
		 return;
		
		if(result == null){
			//$('#coupon_content .clean-alert').show();
			//$('#coupon_content .btn').hide();
			return;
		}
		
		$(".tabnav li:eq(5)").show();
		
		eval("cStyle=" + result.style);
		cStyle.root.image = "url(" + _staticCoupon + result.image + ")";
		
		if(cStyle != null){
			for(i in cStyle){
				v = cStyle[i];
				if(i=="root"){
					$("#couponPreview").css("background-color",v.background);
					if(v.visibility=="visible"){
						$("#couponPreview").css("background-image",v.image);
						$("#couponPreview").css("background-size",v.width + "px " + v.height + "px");
						$("#couponPreview").css("background-repeat","no-repeat");
						$("#couponPreview").css("background-position",v.left + "px" + " " + v.top + "px");
					}
					else{
						$("#couponPreview").css("background-image","");
						$("#couponPreview").css("background-repeat","no-repeat");
						$("#couponPreview").css("background-size",v.width + "px " + v.height + "px");
						$("#couponPreview").css("background-position",v.left + "px" + " " + v.top + "px");
					}	
				}else{
					$("#couponPreview #" + i).css("width",v.width);
					$("#couponPreview #" + i).css("height",v.height);
					$("#couponPreview #" + i).css("visibility",v.visibility);
					$("#couponPreview #" + i).css("left",v.left + "px");
					$("#couponPreview #" + i).css("top",v.top + "px");
					$("#couponPreview #" + i).css("font-size",v.font_size + "px");
					$("#couponPreview #" + i).css("color",v.font_color);
					$("#couponPreview #" + i).css("background-color",v.background);
				}
			}
		}
		$('#couponText').text(result.description);
		$('#couponPreviewType').text(result.value);
		$('#couponDateStart').text(cStyle.startDate);
		$('#couponDateEnd').text(cStyle.endDate);
		
		$('#couponPreview').show();
	},
	
	getSubscriptionInfo: function(){	
		if(GuardianLogin.account != null){
			jsonrpc.subscriptionService.isSubscribed(GuardianPartnerProfile.getSubscriptionInfoCbk,GuardianPartnerProfile.space_id,GuardianPartnerProfile.url_site);
    	}else{
    		$("#sub_btn").addClass("myButtonOrange");
    	    $("#sub_btn").text(_messages.subscribe);
    	}
    },
    
	getSubscriptionInfoCbk: function(result, e){
	  GuardianPartnerProfile.subscribed=result;
      if(result == true){
        $("#sub_btn").text(_messages.unsubscribe);
        $("#sub_btn").addClass("mybuttond");
        $("#sub_btn").removeClass("myButtonOrange");
	  }else{
        $("#sub_btn").text(_messages.subscribe);
        $("#sub_btn").addClass("myButtonOrange");
         $("#sub_btn").removeClass("mybuttond");
	  } 
	},
	
	subscribe: function(){
		jsonrpc.subscriptionService.subscribe(function(result, e){
		 	if(e != null){
				return;
			}
			GuardianPartnerProfile.getSubscriptionInfoCbk(true,null);
			alert(_messages.subscribe_ok);
			
		}, GuardianPartnerProfile.space_id,GuardianPartnerProfile.url_site);
	},
	
	unsubscribe: function(){
	    jsonrpc.subscriptionService.unsubscribe(function(result, e){
            if(e != null){
                return;
            }
        
            GuardianPartnerProfile.getSubscriptionInfoCbk(false, null);
            alert(_messages.unsubscribe_ok);
        }, GuardianPartnerProfile.space_id,GuardianPartnerProfile.url_site);
	},
	
   toggleSubscribe: function(){
   		if(GuardianLogin.account == null){
			$('#user_not_login span.action').text(_messages.subscribe_want);
			GuardianUtil.showModalDialog('user_not_login');
			return;
		}
        
        if(GuardianPartnerProfile.subscribed == true){
            if(confirm(_messages.unsubscribe_msg))
                GuardianPartnerProfile.unsubscribe();
        }else{
            if(confirm(_messages.subscribe_msg))
                GuardianPartnerProfile.subscribe();
        }
   }
};


var sv = null;
var panorama = null; 
var map = null;
var selectedMarker = null;
var infowindow = null;
var placeService = null;
var locaSearch=null;
var bounds=null;
var markersArray = null;
var zoomListener = null;
var loaded = 0;
var totalResult = 0;
var hidePano = null;

function initMap(){
	var myOptions = {
		zoom: GuardianSearchPartners.zoomLevel,
		mapTypeControl: false,
		draggableCursor: 'auto',
		draggingCursor: 'pointer',
		minZoom:2,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	if(map == null){
		map = new google.maps.Map(document.getElementById("mappa"), myOptions);
		google.maps.event.addListener(map, 'dragend', dragEndCallback);
		google.maps.event.addListener(map, 'click', 
		function(){
			if(infowindow != null)
				infowindow.close();
		});
	}
};

function loadGooglePlaces(query, callID){
	initMap();
		
	var cMap = new google.maps.LatLng(GuardianSearchPartners.latitude,GuardianSearchPartners.longitude);
	map.setCenter(cMap);

    //Search Local
    b = map.getBounds();
	
	//console.log("Call Google =" + query + ", bounds " + b + " , ID=" + callID);
	var request = {};
    
    if(b == null){
    	request.location = cMap;
    	request.radius = GuardianSearchPartners.distance*1000;
    }else{
    	request.bounds = b;
    }
    
    request.keyword = googleCategories;
    if($.trim(query) != ""){
    	request.keyword += " " + query;
    }
    
    GuardianSearchPartners.spacesByGoogle = [];
    if(map.getZoom()>zoomLimit){
    	$("#placesAttribute").hide();
    	placeService = new google.maps.places.PlacesService(document.getElementById("placesAttribute"));
    	placeService.search(request, function(results, status){callbackPlaces(results, status, callID)});
    	//$("#placesAttribute").show();
    }else{
    	//console.log("No Google");
    	callbackDataLoaded();
    }
};


function callbackPlaces(results, status,callID) {
	if(callID != GuardianSearchPartners.callID){
		//console.log("Discard Results " + callID);
		return;
	}
	
	//console.log("Risultati Google " + results.length + " " +  status + " " + callID);
    if (status == google.maps.places.PlacesServiceStatus.OK) {
       $("#list").html("");
       loaded = 0;
       totalResult = results.length;
       for (var i = 0; i < results.length; i++) {
       	  //console.log("Risultato Google " + results[i].name);
       	  if(!alreadyExist(results[i].geometry.location.lat(),results[i].geometry.location.lng(),results[i].name)){
			 callbackSearchDetails(i,results[i]);
		  }else if(i==results.length-1){
		  	//callbackDataLoaded();
		  }
       }
       callbackDataLoaded();
    } else{
       callbackDataLoaded();
    } 
}

function loadGoogleDetail(reference,i,callID){
	var request = {
  		reference: reference
	};

	placeService.getDetails(request,
		function (place, status) {
			//console.log("Dettaglio " + place.name);
			if(callID != GuardianSearchPartners.callID){
				//console.log("Discard Results " + callID);
				return;
			}
			loaded++;
  			if (status == google.maps.places.PlacesServiceStatus.OK) {
  				callbackSearchDetails(i,place);
  			}
  			if(loaded==totalResult){
  				callbackDataLoaded();
  			}
  		});
}

function callbackDataLoaded(){
	//merge results
	GuardianSearchPartners.spacesByGoogle.sort(function(a,b){return a.weight-b.weight});
	
	for(var i=0;i<GuardianSearchPartners.spacesByGoogle.length;i++){
		GuardianSearchPartners.spaces.push(GuardianSearchPartners.spacesByGoogle[i]);
	}
	
	if(locationFromMap == false && GuardianSearchPartners.spaces.length==0){
		//console.log("Provo a Cercare in tutto il DB");
		$("#loading_map").text(_messages.error_loading_map);
		google.maps.event.addListener(map, 'zoom_changed', zoomChangedCallback);
		//GuardianSearchPartners.searchAll();
		locationFromMap = true;
		return;
	}
	
 	//ordino x peso
 	pag = 1;
 	if(locationFromMap == true){
 		pag = GuardianSearchPartners.page;
 	}

	addMarkers();

 	//setTimeout(function(){GuardianSearchPartners.drawList(GuardianSearchPartners.page)},2000);
	
	var tag = GuardianUtil.getAnchorTag();
	if(tag == "list"){
		GuardianSearchPartners.drawList(pag);
	}
}

var locationFromMap = false;
var reloadTimeout = null;

function dragEndCallback(){
	GuardianUtil.showLoadingMap(_messages.loadingmap);
	//console.log("DragEndCallback");
	if(infowindow != null)
		infowindow.close();
	/*d = calculateDistance(GuardianSearchPartners.latitude,GuardianSearchPartners.longitude,map.getCenter().lat(),map.getCenter().lng());
	a = Math.pow(120,21/GuardianSearchPartners.zoomLevel);
	if(d>a){
		reloadResults();
	}*/
	if(reloadTimeout != null){
		clearTimeout(reloadTimeout);
	}
	reloadTimeout = setTimeout("reloadResults()",500);	
}


function zoomChangedCallback(){
	//console.log("Zoom Changed");
	GuardianUtil.showLoadingMap(_messages.loadingmap);
	
	if(reloadTimeout != null){
		clearTimeout(reloadTimeout);
	}
	
	reloadTimeout = setTimeout("reloadResults()",500);
}

function reloadMap(){
	if(GuardianSearchPartners.mylatitude == null){
		/*center = map.getCenter();
		map = null;
		initMap();
		map.setCenter(center);
		google.maps.event.addListener(map, 'zoom_changed', zoomChangedCallback);
		reloadResults();*/
		$("#reload_pin").hide();
	}else{
		reloadCenterMap();
	}
}

function reloadCenterMap(){
	latlng = new google.maps.LatLng(GuardianSearchPartners.mylatitude,GuardianSearchPartners.mylongitude);
	map = null;
	initMap();
	map.setCenter(latlng);
	map.setZoom(16);
	google.maps.event.addListener(map, 'zoom_changed', zoomChangedCallback);
	reloadResults();
}


function reloadResults(){
	 //GuardianUtil.showLoading();
	 GuardianSearchPartners.zoomLevel = map.getZoom();
	 
	 if(map.getZoom()<zoomLimit){
	 	GuardianSearchPartners.groupBy = "city";
	 }else{
	 	GuardianSearchPartners.groupBy = null;
	 }
	 
	 GuardianSearchPartners.address = null;
	 locationFromMap = true;
     GuardianSearchPartners.latitude = map.getCenter().lat();
     GuardianSearchPartners.longitude = map.getCenter().lng();
     b = map.getBounds();
     GuardianSearchPartners.distance = (calculateDistance(b.getNorthEast().lat(),b.getNorthEast().lng(), GuardianSearchPartners.latitude,  GuardianSearchPartners.longitude)/1000);
     GuardianSearchPartners.total = 1000;
     //$("#cities").val('');
	 GuardianSearchPartners.loadPartnerListByLatLong();
}

function callbackSearchDetails(i,place) {
		idx = GuardianSearchPartners.spacesByGoogle.length;
        
        var spaceWrap = {};
        
		spaceWrap.name = place.name;
		//spaceWrap.address = place.streetAddress + "," + place.city;
		spaceWrap.address = place.vicinity;
		spaceWrap.latitude = place.geometry.location.lat();
		spaceWrap.longitude = place.geometry.location.lng();
		spaceWrap.reference = place.reference;
		spaceWrap.owner = {};
		
		markerIcon = "http://loveresto.com/static_loveresto/Image/google_pointer.png";
		var mstatic = "http://maps.google.com/maps/api/staticmap?maptype=roadmap&format=gif&sensor=false&size=187x105&zoom=13&markers=icon:" + escape(markerIcon) + "|" + spaceWrap.latitude + "," + spaceWrap.longitude;
		
		spaceWrap.imageIcon = mstatic;
		spaceWrap.weight=100+i;
		spaceWrap.owner.type="GOOGLE";
		spaceWrap.owner.phoneNumber = place.international_phone_number;
		GuardianSearchPartners.spacesByGoogle[idx] = spaceWrap;
		GuardianSearchPartners.spacesByGoogle[idx].distance = calculateDistance(GuardianSearchPartners.latitude,GuardianSearchPartners.longitude,spaceWrap.latitude,spaceWrap.longitude);
		
};

function clearMarkers(){
	if(markersArray != null){
		for (i=0;i<markersArray.length;i++) {
			markersArray[i].setMap(null);
    	}
	}
	markersArray = new Array();
};

function addMarkers(){
	if(GuardianSearchPartners.spaces != null){
		markersArray = [];
		
		var spaces = GuardianSearchPartners.spaces;
		var spacesByDistance = [];
		for(var i in spaces) {
			spacesByDistance[i] = spaces[i];
		}
		
		spacesByDistance.sort(function(a,b){return a.distance-b.distance});
				
		l = Math.floor(spaces.length*0.8);
		limit = 5000000;
		if(l>5){
			limit = spacesByDistance[l].distance;
		}
		bounds = new google.maps.LatLngBounds();
		
		//my marker
		if(GuardianSearchPartners.groupBy == null){
			//console.log("MyLatitude " + GuardianSearchPartners.mylatitude);
			if(GuardianSearchPartners.mylatitude != null){
				latlng = new google.maps.LatLng(GuardianSearchPartners.mylatitude,GuardianSearchPartners.mylongitude);	
				marker = new google.maps.Marker({
					map: map,
					position: latlng,
					zIndex:-1,
					optimized:true
				});	
				marker.setIcon("http://loveresto.com/static_loveresto/Image/myposition.png");
				
				google.maps.event.addListener(marker, 'click', function(event) {
					if(infowindow != null)
						infowindow.close();
								
					infowindow =  new google.maps.InfoWindow();
					infowindow.setContent("<div style='overflow:hidden; margin-top:0px;height:40px;font-size:14px;text-align:center;font-weight: bold;'>" + GuardianSearchPartners.myaddress + "</div>");
					infowindow.setPosition(event.latLng);
					infowindow.open(map);
				});
				
				markersArray.push(marker);
			}
		}
		
		for(var i in spaces) {
			var latlng = new google.maps.LatLng(spaces[i].latitude,spaces[i].longitude);
			if(spaces[i].distance < limit){
				bounds.extend(latlng);
			}
				
			marker = new google.maps.Marker({
				map: map,
				position: latlng,
				zIndex: spaces[i].weight
			});

			marker.setDraggable(false);
			
			markersArray.push(marker);
			        		
			marker.set('idx',i);
			marker.set('spaceid',spaces[i].spaceId);
			
			if(spaces[i].type != null){
			  spaces[i].owner = {};
			  spaces[i].owner.type = spaces[i].type;
			}
			
			//shape
			if(spaces[i].owner.type == "GOOGLE"){
				marker.setIcon("http://loveresto.com/static_loveresto/Image/google_pointer.png");
			}else if(spaces[i].owner.type == "PARTNER_RECOMMENDED_TOP"){
				marker.setIcon("http://loveresto.com/static_loveresto/Image/iconaVip.png");
			}else if(spaces[i].owner.type == "PARTNER_RECOMMENDED" && spaces[i].videos > 0){
				marker.setIcon("http://loveresto.com/static_loveresto/Image/IconaVideo.png");
			}else{
				marker.setIcon("http://loveresto.com/static_loveresto/Image/iconaNoVideo.png");
			}
			
			if(GuardianSearchPartners.groupBy != null){
				google.maps.event.addListener(marker, 'click', function(event) {
					GuardianUtil.showLoadingMap(_messages.zoom);
					setTimeout("GuardianUtil.hideLoadingMap()",3000);
					//alert("Per aprire il dettaglio, aumentare lo Zoom")}
				});
				continue;
			}
			
			sv = new google.maps.StreetViewService();
			google.maps.event.addListener(marker, 'click', function(event) {
				if(infowindow != null)
					infowindow.close();
					
				$("#tooltip").remove();
				
				var idx = this.get("idx");
				space = GuardianSearchPartners.spaces[idx];
				
				if(space == null)
					return;
				
				hidePano = false;
				if(space.owner.type == "GOOGLE"){
					var request = {
  						reference: space.reference
					};
					placeService.getDetails(request,
						function (place, status) {
							if (status == google.maps.places.PlacesServiceStatus.OK) {
								//console.log("Dettaglio " + place.name);
								space.address = place.formatted_address;
								
								addr_list = place.address_components;
									
								for(var z=0;z<addr_list.length;z++){
									addr_types = addr_list[z].types;
									for(var t=0;t<addr_types.length;t++){
										if(addr_types[t] == "locality"){
											space.city = addr_list[z].long_name;
										}
										if(addr_types[t] == "administrative_area_level_1"){
											space.region = addr_list[z].long_name;
										}
										if(addr_types[t] == "country"){
											space.country = addr_list[z].long_name;
										}
									}
								}
								space.google_id = place.id; 
								 
								space.owner.phoneNumber = place.international_phone_number;
								
								GuardianSearchPartners.spaces[idx] = space;
								
  								$("body").append(getGoogleTooltip(idx,space));
  								panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"));
	  							sv.getPanoramaByLocation(event.latLng, 50, processSVData);
								selectedMarker = event.latLng;
  							}
  						});
  				}else{
  					space = jsonrpc.partnerService.getPartnerDetails(space.spaceId);
  					
					$("body").append(getLoverTooltip(space));
					
					if(space.videos>0){
						videoPlayerTooltip(space.spaceId);
						hidePano = true;
					}
					
					panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"));
					
					sv.getPanoramaByLocation(event.latLng, 50, processSVData);
					selectedMarker = event.latLng;
				}
			});
		}
	}
	
	GuardianUtil.hideLoadingMap();
	
	if(locationFromMap == false){
		//console.log("adatto la mappa");
		//center = map.getCenter();
		map.fitBounds(bounds);
		//map.setCenter(center);
		google.maps.event.addListener(map, 'zoom_changed', zoomChangedCallback);
		//console.log("Save Bounds " + map.getBounds());
		
		ne_lat = map.getBounds().getNorthEast().lat();
		ne_lng = map.getBounds().getNorthEast().lng();
		sw_lat = map.getBounds().getSouthWest().lat();
		sw_lng = map.getBounds().getSouthWest().lng();
		GuardianUtil.createCookie("_latlng_bounds_ne_lat",ne_lat,null,null,2);
		GuardianUtil.createCookie("_latlng_bounds_ne_lng",ne_lng,null,null,2);
		GuardianUtil.createCookie("_latlng_bounds_sw_lat",sw_lat,null,null,2);
		GuardianUtil.createCookie("_latlng_bounds_sw_lng",sw_lng,null,null,2);
	}
};


function getLoverTooltip(space){
		a = space.name;
		if(a.length > 35)
			a = a.substring(0,35) + "...";	
		
		var tooltip = "<div id='tooltip' style='width:400px;height:330px;'><a href='/partnerProfile.page?spaceid=" + space.spaceId + "'><img src='/static_loveresto/Image/info.png' style='position:absolute;z-index:9999;top:-15px;left:-15px;display:none;' border='0' id='imgInfob'></a><div style='overflow:hidden;height:24px;'><a style='text-decoration:underline;font-size: 18px;font-weight: bold;' href='/partnerProfile.page?spaceid=" + space.spaceId + "'>" + a + ":</a></div><div style='overflow:hidden;height: 16px;'>" + space.address +"</div>";
		setTimeout("$('#imgInfob').show();", 500);
		if(space.owner.phoneNumber != null){
          	tooltip += "<div style=\"overflow:hidden;height: 18px; font-size: 14px; margin-bottom:10px;\">Tel: " + space.owner.phoneNumber + "</div>"
       	}
        
        if(space.videos>0){
        	tooltip += "<div class=''><a class='test' href='javascript:changePano_VideoPlayer();'>StreeView</a></div>";
        }
        
        tooltip +=  "<div id='pano' style='width:400px;height:240px;'></div>";
        
        if(space.categories.map.claim != null){
        	tooltip += "<div id='claim'>" + space.categories.map.claim + "</div>";
        }
        
		if(space.videos){
			//tooltip += "<div class=''><a class='test' href='javascript:GuardianSearchPartners.viewLightBoxVideo(" + space.spaceId + ");'>PLAY VIDEO<a></div>";
			tooltip += "<div id='video_box_tooltip' style='width:400px;height:240px;'></div>";
		}
		
		tooltip += "</div>";
		      	
      	return tooltip;
};


function videoPlayerTooltip(s_id){
		var video = jsonrpc.spaceService.getFirstVideoInSpace(s_id);
		

		/*GuardianVideoPlayer.fillDivVideoPlayer("video_box_tooltip", 
				video.title,
				video.description,	                                            
				video.videoName, 
				video.imageName,
				video.duration, 
				video.external,
				video.externalId,
				video.externalCdn,
				video.embedCode,
				400, 
				240);

		if(video.external){
			GuardianPartnerProfile.incrementVideoViews();
		}else{
			GuardianVideoPlayer.addViewListener("PLAY","GuardianPartnerProfile.incrementVideoViews");		
		} */
$('#video_box_tooltip').html('<iframe class="youtube-player" type="text/html" width="400" height="240" src="http://www.youtube.com/embed/'+ video.externalId+ '?wmode=opaque;" frameborder="0" allowfullscreen></iframe>');
};

function getGoogleTooltip(idx,space){
			a = space.name;
			if(a.length > 35)
				a = a.substring(0,35) + "...";	
			
			//tooltip Google
			var tooltip = "<div id='tooltip' style='width:400px;height:220px;'><a style='text-decoration:underline;font-size: 14px;font-weight: bold;' href='javascript:showGoogleDetails(" + idx + ")'>" + a + ":</a><div style='overflow:hidden;height:18px;'>" + space.address +"</div>";
        
        	if(space.owner.phoneNumber != null){
          		tooltip += "<div style=\"overflow:hidden;height: 18px; font-size: 14px; margin-bottom:10px;\">Tel: " + space.owner.phoneNumber + "</div>"
        	}
        
         	tooltip +=  "<div id='pano' style='width:400px;height:150px;'></div></div>";
        
        	if(GuardianLogin.account != null && checkRole()){
        		tooltip = "<div id='tooltip' style='width:400px;height:270px;'><a style='text-decoration:underline;font-size: 14px;font-weight: bold;' href='javascript:showGoogleDetails(" + idx + ")'>" + a + ":</a><div style='overflow:hidden;height: 14px;'>" + space.address +"</div><div id='pano' style='width:400px;height:150px;'></div><br/><a class='recommededButton' href='javascript:makeLover(" + idx + ",\"PARTNER_RECOMMENDED\");'>Recommended</a><a class='recommededTopButton' href='javascript:makeLover(" + idx + ",\"PARTNER_RECOMMENDED_TOP\");'>Recommended Top</a></div>";
        	}
        	
        	return tooltip;
};

function processSVData(data, status) {
	infowindow = new google.maps.InfoWindow({
		disableAutoPan: false
	});
    
    if (status == google.maps.StreetViewStatus.OK) {
      panorama.setPano(data.location.pano);
      panorama.setPov({
        heading: 270,
        pitch: 0,
        zoom: 0
      });
      panorama.setVisible(true);
    }else{
      if(hidePano==false){
      	$("#tooltip").css("height","70px");
      }else{
      	$(".test").hide();
      }
      $("#tooltip #pano").html("")
      $("#tooltip #pano").css("height","0px");
    }
    
    infowindow.setContent(document.getElementById("tooltip"));
    infowindow.setPosition(selectedMarker);
    
    if(hidePano==true){
    	$("#pano").hide();
    }
    
	infowindow.open(map);
};

function changePano_VideoPlayer(){
	if(hidePano==true){
		$("#video_box_tooltip").hide();
		$("#pano").show();
		$(".test").text("Video");
		hidePano = false;
	}else{
		$("#video_box_tooltip").show();
		$(".test").text("StreetView");
		$("#pano").hide();
		hidePano = true;
	}
};

function getSpaceWrapper(space,draggable) {
	var lat = space.latitude;
	var lng = space.longitude;

	document.getElementById("latitude").value = lat;
	document.getElementById("longitude").value = lng;

	$("#space_title").html(space.name);
	$("#address").html(space.address);

	var myOptions = {
		zoom: 16,
		mapTypeControl: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	var marker;
	//map.setZoom(15);

	var myLatlng = new google.maps.LatLng(lat,lng);
	//alert(myLatlng);

	marker = new google.maps.Marker({
		map: map,
		position: myLatlng,
	});

	google.maps.event.addListener(marker, "dragend", function(event) {
		document.getElementById("latitude").value=marker.getPosition().lat();
		document.getElementById("longitude").value=marker.getPosition().lng();
	});
	
	marker.setDraggable(draggable);
	marker.setTitle(space.name);
	map.setCenter(myLatlng);
	
	sv = new google.maps.StreetViewService();
	google.maps.event.addListener(marker, 'click', function(event) {
		$("#tooltip").remove();
		$("body").append('<div id="tooltip" style="width:410px;height:250px;"></div>');
		panorama = new google.maps.StreetViewPanorama(document.getElementById("tooltip"));
		sv.getPanoramaByLocation(event.latLng, 20, processSVData);
		selectedMarker = event.latLng;
	});
	
	return false;
}

function getSpaceOnMap(space,map_id) {
	var lat = space.latitude;
	var lng = space.longitude;

	var myOptions = {
		zoom: 16,
		mapTypeControl: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	spaceMap = new google.maps.Map(document.getElementById(map_id), myOptions);
	var marker;
	
	var myLatlng = new google.maps.LatLng(lat,lng);
	
	marker = new google.maps.Marker({
		map: spaceMap,
		position: myLatlng,
	});
	
	marker.setIcon(space.markerIcon);

	spaceMap.setCenter(myLatlng);
	
	return false;
}


function alreadyExist(lat,lng,name){
	list = GuardianSearchPartners.spaces;
	if(list != null){
		for(var i=0;i<list.length;i++){
			var a = Math.abs(list[i].latitude - lat);
			var b = Math.abs(list[i].longitude - lng);
			var d = Math.sqrt(a*a + b*b);
			n1 = list[i].name.toLowerCase();
			n2 = name.toLowerCase();
			if(d<0.001 && (n1.indexOf(n2)>-1 || n2.indexOf(n1)>-1)){
				return true;
			}
		}
	}
	return false;
}

function isNearMe(lat,lng){
	var d = calculateDistance(GuardianSearchPartners.latitude,GuardianSearchPartners.longitude,lat,lng)
	//alert(d)
	if(d<10000){
		return true;
	}
	return false;
};

function makeLover(idx,type){
	GuardianUtil.showLoading();
	space = GuardianSearchPartners.spaces[idx];
	//space = GuardianSearchPartners.spacesByDistance[idx];
	
	if(infowindow != null)
		infowindow.close();

	GuardianUtil.closeModalDialog();

	try{
	  var username = space.name;
	  username = username.replace(/\s/gi,"").toLowerCase();
	  if(username.length > 20){
	     username = username.substring(0,20);
	  };
	  categories = {javaClass:"java.util.HashMap",map:{}};
	  categories.map.GOOGLE = space.google_id;
	  
	  jsonrpc.partnerManager.createSpaceWithCategories(username,"","", 
			space.owner.phoneNumber, "", space.name,"",type, 
			space.latitude, space.longitude, space.address, space.city, space.region, space.country, categories);
	}catch(e){
	}
	
	GuardianSearchPartners.zoomLevel = map.getZoom();	
	locationFromMap = true;
	reloadResults();
	
	setTimeout(function(){GuardianSearchPartners.drawList(GuardianSearchPartners.page)},2000);
}

function showGoogleDetails(idx){
	if(infowindow != null)
		infowindow.close();
	
	space = GuardianSearchPartners.spaces[idx];
	space.markerIcon = "http://loveresto.com/static_loveresto/Image/google_pointer.png";
	
	if(GuardianLogin.account != null && checkRole()){
		html = "<a class='recommededButton' href='javascript:makeLover(" + idx + ",\"PARTNER_RECOMMENDED\");'>Recommended</a><a class='recommededTopButton' href='javascript:makeLover(" + idx + ",\"PARTNER_RECOMMENDED_TOP\");'>Recommended Top</a>";
		$("#g_details .toolbox").html(html);
	}
	
	showSpaceDetailsOnMap(space);
};

function showSpaceDetailsOnMap(space){
	$("#g_details .title").text(space.name);
	var a = "";
	if(space.address != null){
		a = space.address;
	}
	$("#g_details .address").html(a);
	$("#g_details .phone").text(space.owner.phoneNumber);
	
	GuardianUtil.showModalDialog("g_details");	
	
	getSpaceOnMap(space,"map_space");
}

function closeGoogleDetails(){
	$("map_space").html("");
	GuardianUtil.closeModalDialog();
	spaceMap = null;
};

function toRadians(v){
	return v*Math.PI/180;
};

function calculateDistance(lat1,lng1,lat2,lng2){
	//truncate(6363*sqrt(POW(RADIANS(:lat)-RADIANS(s.latitude),2) + POW(RADIANS(:lon)-RADIANS(s.longitude),2)),3)
	latr = toRadians(lat1)-toRadians(lat2);
	lngr = toRadians(lng1)-toRadians(lng2);
	latr = latr*latr;
	lngr = lngr*lngr;
	d = Math.sqrt(latr+lngr);
	d = Math.round(6363*d*1000);
	return d;
};

var AddThisController = {

		widget : new Array(),
		spacePage: "partnerProfile.page",

		/* Init all registered Widgets*/
		init : function() {
			try{
				for (x in this.widget){
					eval(this.widget[x].menu);
				}
			}catch(e){
				//alert("AddThisController " + e)
			}
		},

		initWidget : function(id) {
			try{
				eval(this.widget[id].menu);
			}catch(e){}
		},

		/* Register New Widget*/
		register : function(videoId,spaceId,text,elementId){
			var wid = videoId;
			var sourceid = "content_"+wid;

			this.widget[wid] = new Object();
	
			var bookmarkUrl = AddThisController.getCurrentPath() + AddThisController.spacePage;
			//if(videoId != null)
				//bookmarkUrl += videoId;
	
			if(spaceId != null)
				bookmarkUrl += "?spaceid=" + spaceId;

			var title = text;
			title = title.replace(/"/g,"'");
			//Internet Explorer
			if(GuardianConf.USER_AGENT.indexOf("MSIE")>0){
				this.widget[wid].menu = "addthis.button(\"#" + elementId + "\",{ui_click:true},{url:\"" + bookmarkUrl + "\",title:\"" + title + "\"});";
			}else{
				this.widget[wid].menu = "addthis.button(\"#" + elementId + "\",{ui_click:true,ui_offset_top:240,ui_offset_left:860},{url:\"" + bookmarkUrl + "\",title:\"" + title + "\"});";
			}	
		},

		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;
		}
};

var GuardianVideoStrip = {

 	nCurrent:1,         // Init Page (offset)            
	nForPage:7,           // Thumb for page
	nTotResult:1,

	bNextPrevGallery:true,
	gallerySize: 7,
	result: null,

	getAllVideosInChannel: function(_current, _forPage) {
		//GuardianPartnerProfile.space_id = 5589;
		jsonrpc.spaceService.getVideosInSpace(GuardianVideoStrip.getFocusOnCallback, GuardianPartnerProfile.space_id,"","ORDER_INDEX","",_current,_forPage);
	},
            
	getFocusOnCallback: function(result, e){
		if(e != null){
			return;
		}
		var jsonData = new Object();
		jsonData.result = result;
		GuardianVideoStrip.loadThumb(jsonData);
	},
    
	loadThumb: function(jsonData) {
	    GuardianVideoStrip.nTotResult = jsonData.result.total;
	    
	    if(GuardianVideoStrip.nTotResult > 27)
	    	  GuardianVideoStrip.nTotResult = 27;  	
	    
	    nNresto = 0;
	
	    nTmp = GuardianVideoStrip.nTotResult / GuardianVideoStrip.gallerySize
	    nTmp = parseInt(nTmp, 10);
	    if (GuardianVideoStrip.nTotResult - nTmp > 0)
	        nTmp = nTmp + 1;
	
	    GuardianVideoStrip.nTotResult = nTmp;
	
	    var sHtmlPageGallery = '';
	    sHtmlPageGallery = GuardianVideoStrip.nCurrent.toString() + '/' + GuardianVideoStrip.nTotResult.toString();
	    $('.pageGallery').html(sHtmlPageGallery);    
	    
	    var sHtmlGallery = '';
	    // left box
	    for (i = 0; i < GuardianVideoStrip.gallerySize; i++) {
	        sHtmlGallery = sHtmlGallery + '<div class="thumb">';
	        sHtmlGallery = sHtmlGallery + '<div class="thumbBg"></div>';
	        sHtmlGallery = sHtmlGallery + '<div class="thumbLoad"></div>';
	        sHtmlGallery = sHtmlGallery + '</div>';
	    }
	
		GuardianVideoStrip.result = jsonData.result.list.list;
	    // 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="button" index="' + i + '" 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 == GuardianVideoStrip.gallerySize) &&  (GuardianVideoStrip.nCurrent < GuardianVideoStrip.nTotResult)){
	        for (i = 0; i < GuardianVideoStrip.gallerySize; 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 = 122 * GuardianVideoStrip.gallerySize;
	    $('#catGalleryScroll').css('left', '-' + boxWidth.toString() + 'px');
	    GuardianVideoStrip.setScrollTo();
	    GuardianVideoStrip.setFrame();
	},

	setScrollTo: function() {
	    var boxWidth = 122 * GuardianVideoStrip.gallerySize;
	    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 (GuardianVideoStrip.nCurrent > 1)
	        $('#catSx').attr('class', 'catSx');
	    else
	        $('#catSx').attr('class', 'catSxDisable');
	
	    if (GuardianVideoStrip.nCurrent < GuardianVideoStrip.nTotResult)
	        $('#catDx').attr('class', 'catDx');
	    else
	        $('#catDx').attr('class', 'catDxDisable');   
	
	    // Set listener prev link
	    $('#catSx').bind('click', function() {
	        if (GuardianVideoStrip.bNextPrevGallery) {
	            GuardianVideoStrip.bNextPrevGallery = false;
	            var left = parseInt($('#catGalleryScroll').css('left').replace('px', ''));
	            var scr = left + boxWidth;
	            if (GuardianVideoStrip.nCurrent > 1) {
	                $('#catGalleryScroll').animate({ left: (scr == 0 ? scr + 'px' : scr) }, 300);
	                count--;
	                GuardianVideoStrip.nCurrent--;
	
	                var sHtmlPageGallery = '';
	                sHtmlPageGallery = GuardianVideoStrip.nCurrent.toString() + '/' + GuardianVideoStrip.nTotResult.toString();
	                $('.pageGallery').html(sHtmlPageGallery);
	                
	            }
	            setTimeout('GuardianVideoStrip.enableNext()', 500);
	        }
	        return false;
	    });
	
	    // Set listener next link
	    $('#catDx').bind('click', function() {
	        if (GuardianVideoStrip.bNextPrevGallery) {
	            GuardianVideoStrip.bNextPrevGallery = false;
	            var left = parseInt($('#catGalleryScroll').css('left').replace('px', ''));
	            var scr = left - boxWidth;
	            if (GuardianVideoStrip.nCurrent < GuardianVideoStrip.nTotResult) {
	                $('#catGalleryScroll').animate({
	                    left: (scr == 0 ? scr + 'px' : scr)
	                }, 300);
	                count++;
	                GuardianVideoStrip.nCurrent++;
	
	                var sHtmlPageGallery = '';
	                sHtmlPageGallery = GuardianVideoStrip.nCurrent.toString() + '/' + GuardianVideoStrip.nTotResult.toString();
	                $('.pageGallery').html(sHtmlPageGallery);
	                
	            }
	            setTimeout('GuardianVideoStrip.enableNext()', 1000);
	        }
	        return false;
	    });
	},
	
	setFrame: function() {
	    // Set listener "watch" link
	    $('.thumbFrameActive .button').bind('click', function() {
	    	$(".thumbFrameActive").css('display', 'none');
	    	
	        var sId = $(this).attr('index');
	        video = GuardianVideoStrip.result[sId];
	        GuardianVideoPlayer.fillDivVideoPlayer("big_video_box", video.title, video.description,	video.videoName, video.imageName, video.duration, video.external,	video.externalId, video.externalCdn, video.embedCode, 980, 528);
	         window.scrollTo(0,0);
	    });
	
	    // 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');
	    });   
    
	},

	enableNext: function () {
    	// Enable next and prev link
    	GuardianVideoStrip.bNextPrevGallery = true;

    	// Load Current Range Box
    	GuardianVideoStrip.getAllVideosInChannel(GuardianVideoStrip.nCurrent, GuardianVideoStrip.nForPage);
	}

};


function getFormattedAddress(address_components){
	addr = "";
	for(var z=0;z<address_components.length;z++){
		addr_types = address_components[z].types;
		for(var t=0;t<addr_types.length;t++){
			if(addr_types[t] == "locality"){
				addr += ", " + address_components[z].long_name;
			}
			if(addr_types[t] == "route"){
				addr += address_components[z].long_name;
			}
		}
	}
	return addr;
}


