var Utilities = {
	extendedUserUrl: false,
	maxDate: (new Date().getMonth() + 1) + '/' + new Date().getDate() + '/' + (new Date().getFullYear() - 14),
	
	isArray: function (obj) {
	    return obj && obj.constructor == new Array().constructor;
	},
	
	getAssociativeArrayLength: function (associative_array) {
		var length = 0;
		for(var id in associative_array) length++;
		return length;
	},
	
	getUserAvatar: function (encryptedContentId, gender, standard) {
		if(!gender) gender = "K";
		if(!standard) standard = "i22x22";
		
		if(encryptedContentId && encryptedContentId.substr(0, 4) == 'http')
			return encryptedContentId;
		
		return ((!encryptedContentId) ?
				"http://" + conf.staticUrl + "/gfx/NoFoto_" + gender.toUpperCase() + ImageStandards.image[standard].width +
				(gender == "K" ? "off" : "") + ".gif" :
				conf.imageServerUrl + "c/" + encryptedContentId + "/s/" + ImageStandards.image[standard].standard +
				"/profile.jpg"
		);
	},
	
	_getUserAvatar: function (gender, standard, cid) {
		if(!gender) gender = 'K';
		if(!standard) standard = "i22x22";
		
		// Url immagine
		if(cid && cid.substr(0, 4) == 'http') return cid;
		
		// Avatar mancante
		if(!cid) return "http://" + conf.staticUrl + "/gfx/NoFoto_" + gender.toUpperCase() + ImageStandards.image[standard].width +
				(gender == "K" ? "off" : "") + ".gif";
		
		// Content id criptato
		if(cid.length == 22) return conf.imageServerUrl + "c/" + cid + "/s/" + ImageStandards.image[standard].standard + "/profile.jpg";
		
		// Content id
		return conf.imageServerUrl + cid + "/image.jpg";
	},
	
	extractDomain: function (url) {
		var splitted_url = url.split(".");
		return ((splitted_url.length == 2) ? splitted_url[0] + "." + splitted_url[1] : splitted_url[1] + "." + splitted_url[2]);
	},
	
	formatDate: function (date) {
		return "alle " + date.toLocaleTimeString() + " di " + date.toLocaleDateString();
	},
	
	parseHybridResponse: function (response) {
		var pResponse = '';
		
		try {
			pResponse = response.split("|||||");
			
			if(pResponse.length == 1) {
				pResponse = Utilities.jsonParse(pResponse[0]);
				// Logger.log('json');				
			}
			else {
				pResponse[0] = Utilities.jsonParse(pResponse[0]);
				// Logger.log('json + testo');
			}
		} catch (e) {
			pResponse = response;
			// Logger.log(response + ' testo semplice');
		}
		
		return pResponse;
	},
	
	openChat: function (t_pid, t_nick) {
		window.open("http://" + conf.dynamicUrl + "/chat121.php?profile_id=" + t_pid + "@" + conf.applicationId + "&nickname=" + my_profile.nick + "+-+" + t_nick, "_blank", "toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0,width=345,height=462");
	},
	
	openChatRoom: function (room_id, nome_stanza, titolo) { 
		var callback = {
		   success : function (o) { Utilities.successChatRoom(o, room_id, nome_stanza, titolo); },
		    failure : function (o) { Logger.log(o); },
		    upload: function (o) { Utilities.successChatRoom(o, room_id, nome_stanza, titolo); }
		};
		
		var conn = YAHOO.util.Connect.asyncRequest("POST", 'http://' + conf.baseUrl + '/overlay_manager/apri_chatroom', callback, 'aaa_fn=Chat.room.access');
	},
	
	successChatRoom: function (o, room_id, nome_stanza, titolo) {
		
		var res = Utilities.parseHybridResponse(o.responseText);
		
		 if(res.result == 'LP') {
				
			 OverlayConfiguration.genericMessage.overlay.hide();
			 if(res.enc_profile_id) OverlayManager.show('lp', res.lp, res.enc_profile_id);
				else OverlayManager.show('lp', res.lp);
		 }
		 else if(!res[0]){
			 
			 window.open("http://" + conf.dynamicUrl + "/chatroom.php?room_id=" + room_id + "&nome_stanza="+ nome_stanza + "&titolo="+ titolo, "chat_room", "toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0,width=950,height=567");
		 }
		 else if(res[0].result == "KO"){
			 
			 OverlayConfiguration.genericMessage.showPlain('', res[1], 'rosso', 300); 			
		 }
	},
	
	openChatBadge: function () {
		window.open("http://" + conf.dynamicUrl + "/download_client.php", "Chat", "toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0,width=235,height=200");		
	},
	
	prettyDate: function (date) {
		var s = 1000,
		i = 60,
		h = i * 60,
		d = h * 24,
		w = d * 7,
		m = d * 30;
		
		var now = new Date();
		var diff = Math.ceil((now.getTime() - date.getTime()) / s);
		
		// if(diff < 0) return "non so... :\\";
		if(diff < 5) return "adesso";
		if(diff < i) return diff + " secondi fa";
		if(Math.floor(diff / i) == 1) return "1 minuto fa";
		if(diff < h) return Math.floor(diff / i) + " minuti fa";
		if(Math.floor(diff / h) == 1) return "1 ora fa";
		if(diff < d) return Math.floor(diff / h) + " ore fa";
		if(diff < (d * 2) && date.getHours() == 1) return "ieri all'" + date.getHours() + ":" + Utilities.twoDigitsTime(date.getMinutes());
		if(diff < (d * 2)) return "ieri alle " + date.getHours() + ":" + Utilities.twoDigitsTime(date.getMinutes());
		if(diff < w) return Math.floor(diff / d) + " giorni fa";
		if(Math.floor(diff / w) == 1) return "una settimana fa";
		if(diff < m) return Math.floor(diff / w) + " settimane fa";
		return "molto tempo fa ;)";		
	},
	
	twoDigitsTime: function (time) {
		if(time < 10) return "0" + time;
		return time;
	},
	
	// apre/chiude i commenti relativi al post c_id
	showComments : function(c_id) {
		var c_box = YAHOO.util.Dom.get(c_id);
		
		if(c_box.style.display == 'block' || c_box.style.display == '') c_box.style.display = 'none';
		else c_box.style.display = 'block';
	},
	
	invitaAmico: function (url, email) {
	  url = url + '/' + email;
		
		var callback = {
			success: function(o) {			
				document.getElementById('successo').innerHTML = o.responseText;
				document.getElementById('div_progress_upload').style.display = 'block';
				document.getElementById('button_fuxia').style.display = 'none';
				document.getElementById('invitato').style.display = 'block';
				document.getElementById('invita').style.display = 'none';
			}, 
			failure: function(o) {
				document.getElementById('errore').innerHTML = o.responseText;
				document.getElementById('invitato_ko').style.display = 'block';
				document.getElementById('invita').style.display = 'none';		
			}
		}		
		
		var transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);	  
	},
	
	invitaAltroAmico: function () {				
		document.getElementById('div_progress_upload').style.display = 'none';
		document.getElementById('invitato').style.display = 'none';			
		document.getElementById('invita').style.display = 'block';
		document.getElementById('button_fuxia').style.display = 'block';
	},
	
	isUserHome: function () {
		return location.hostname.slice(0, 3) != 'www';
	},
	
	// attiva/disattiva le checkbox  'botta sicura' e 'con affinity' in search
	setAffinityCheckbox: function(){
		if(document.getElementById('clubA').checked){
			document.getElementById('con_affinity').disabled = false;
			document.getElementById('botta_sicura').disabled = false;
		}
		else{
			document.getElementById('con_affinity').checked = false;
			document.getElementById('botta_sicura').checked = false;
			document.getElementById('con_affinity').disabled = true;
			document.getElementById('botta_sicura').disabled = true;
		}
	},
	
	showHideBox: function (elm) {
		var status = document.getElementById(elm).style.display;
		if(status == 'block') {
			document.getElementById(elm).style.display = "none";
		} else {
			document.getElementById(elm).style.display = "block";
		}
	},
	
	getUrlByContentId: function (encryptedContentId, standard) {
		if(encryptedContentId.substr(0, 4) == 'http')
			return encryptedContentId;
		else
			return conf.imageServerUrl + 'c/' + encryptedContentId + '/s/' + (standard ? standard : '499') + '/profile.jpg';		
	},
	
	showHideMmsUpload: function (div_id, msg_type) {
		var div = YAHOO.util.Dom.get(div_id);
		
		if(msg_type == 'SMS')
			YAHOO.util.Dom.setStyle(div, 'display', 'none');
		else
			YAHOO.util.Dom.setStyle(div, 'display', 'block');
	},
	
	needLP: function (responseText, isOverlay) {
		var response = Utilities.jsonParse(responseText);
		return response.result == 'LP' || (!isOverlay && response.result == 'KO');
	},
	
	// Controlla se bisogna lanciare una landing page
	checkFeature: function(responseText, isOverlay) {
		if(!Utilities.needLP(responseText, isOverlay)) return;
		
		try {
			var res = Utilities.jsonParse(responseText);
			
			if(res.result == 'LP') {
				switch(String(res.lp)) {  				
					case 'freerider':	OverlayManager.show('lp', 'freerider');
										break;
						
					case 'upgrade':	OverlayManager.show('lp', 'upgrade', res['enc_profile_id']);
									break;
						
					case 'cc':	OverlayManager.show('lp', 'cc', res['enc_profile_id']);
								break;
						
					case 'image':	OverlayManager.show('lp', 'image', res['enc_profile_id']);
									break;
				}
			}
			
			else if(res.result == 'KO') {
				switch(res.billing_mode) {
					case 'never':	OverlayManager.show('genericMessage', 'Attenzione', res['message'], 'rosso');
									break;
						
					case 'suspended':	OverlayManager.show('genericMessage', 'Attenzione', res['message'], 'rosso');
										break;
						
					case 'no_response':	OverlayManager.show('genericMessage', 'Attenzione', res['message'], 'rosso');
										break;
						
					default:	if(res.message) OverlayManager.show('genericMessage', 'Attenzione', res['message'], 'rosso');
								else OverlayManager.show('genericMessage', 'Attenzione', 'Oops! Qualcosa č andato storto, riprova pių tardi!', 'rosso');
								break; 
				}
			}
		} catch (e) { }
	},
	
	jsonParse: function (json) {
		return json_parse(json, Utilities._jsonDateParse);
	},
	
	_jsonDateParse: function (key, value) {
        if(typeof value === 'string') {
            date = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
            if(date) return new Date(Date.UTC(+date[1], +date[2] - 1, +date[3], +date[4], +date[5], +date[6]));
        }
        return value;
	},
	
	getUserUrl: function (nick) {
		try {
			if(Utilities.extendedUserUrl)
				return Utilities.savantPlugin(conf.domain, nick);
			else
				return 'http://' + nick + '.' + conf.domain;
		} catch (e) { }
	},
	
	savantPlugin: function (base_domain, this_domain, path) {
		var url = 'http://www.';
        
        path = (path ? '/' + path : '');  
        url += base_domain;
  
        if(this_domain && Utilities.trim(this_domain) != '')
        	url += '/u/' + this_domain;
  
        return url + path;
    },
    
    trim: function (str) {
        while(str.substring(0, 1) == ' ')
        	str = str.substring(1, str.length);
        while(str.substring(str.length - 1, str.length) == ' ')
        	str = str.substring(0, str.length - 1);
        return str;
    },
    
    /**
     * @deprecated use Ajax.createActionString
     */
    createActionString: function (params) {
    	return Ajax.createActionString(params);
    },
    
    addslashes: function (str) {
    	str=str.replace(/\\/g,'\\\\');
    	str=str.replace(/\'/g,'\\\'');
    	str=str.replace(/\"/g,'\\"');
    	str=str.replace(/\0/g,'\\0');
    	return str;
    },
    
    stripslashes: function (str) {
    	str=str.replace(/\\'/g,'\'');
    	str=str.replace(/\\"/g,'"');
    	str=str.replace(/\\0/g,'\0');
    	str=str.replace(/\\\\/g,'\\');
    	return str;
    }
};

var ImageStandards = {
	video: { },
	image: {
		profileThumb: { standard: 497, width: 56, height: 56 },
		i22x22: { standard: 586, width: 22, height: 22 }
	}
};

var AbuseTypes = {
	descrizione: 1,
	video: 2,
	photo: 3,
	status: 4,
	commento: 6
};