var serverEngine = "php";
var projectRoot = "http://www.manyego.com/flashcoms/";

var communicatorWindows = new Object();
var messengerWindows = new Object();
var countBlocks = 0;

if($.browser.msie && $.browser.version != "7.0") {
	window.onload = 
	function () {
		$(document).pngFix(); 
	}
}

//prende le cittą di una data regione
function getCity(id) {
	$.ajax({
	   type: "POST",
	   url: "/ajax_checkusr.php",
	   data: 'url='+id+'&o=3',
	   success: function(html){
		   $('#select_city').html(html);
	   }
	 });
}


//funzioni per la textarea con smiles
function showSmile(id)
{
	var targetContent = $('#smiles_'+id);
	if (targetContent.css('display') == 'none') {
		targetContent.slideDown(300);
		//$(this).html('[-]');
	} else {
		targetContent.slideUp(300);
		//$(this).html('[+]');
	}
	return false;
};

function addsmile(text,id) {
	var range = $('#textarea_'+id).getSelection();
	$('#textarea_'+id).replaceSelection(text, true);

	showSmile(id);
}

function posteditor(code) {
	var range = $('#textarea_0').getSelection();
	$('#textarea_0').replaceSelection('['+code+']'+range.text+'[/'+code+']', true);
}

function posteditorOut(code,text) {
	var range = $('#textarea_0').getSelection();
	$('#textarea_0').replaceSelection('['+code+']'+text+'[/'+code+']', true);

	tb_remove();
}

function showPreviewPost() {
	var text = encodeURIComponent($('#textarea_0').val());
	if($('#textarea_BB').css('display')=="block") {
		$.ajax({
		   type: "POST",
		   url: "/ajax_blogpreview.php",
		   data: 'text='+text,
		   success: function(html){
			   $('#textarea_BB').css('display','none');
			   $('#textarea_Prev').html(html);
			   $('#textarea_Prev').css('display','block');
			   $('.post_anteprima a').html('Modifica');
			   $('.smile_button_post').css('display','none');
			   $('.button_post').css('display','none');
		   }
		 });
	} else {
	   $('#textarea_BB').css('display','block');
	   $('#textarea_Prev').css('display','none');
	   $('.smile_button_post').css('display','block');
	   $('.button_post').css('display','block');
	   $('.post_anteprima a').html('Anteprima');
	}
}


//funzioni per cambiare lo stato dell'utente loggato
function showUserStatus()
{
	var targetContent = $('#user_stato_header');
	if (targetContent.css('display') == 'none') {
		if(targetContent.html()=="") {
			$.ajax({
			   type: "POST",
			   url: "/ajax_userstatus.php",
			   data: '',
			   success: function(html){
				   $('#user_stato_header').html(html);
			   }
			 });
		}
		targetContent.slideDown(300);
		
	} else {
		targetContent.slideUp(300);
	}
	return false;
};

function changeUserStatus(id) {
	var targetContent = $('#user_stato_header');
	$.ajax({
	   type: "POST",
	   url: "/ajax_userstatus.php",
	   data: 'action=change&id='+id,
	   success: function(html){
		   targetContent.slideUp(300);
		   if(id==1) $('#UserStatusContent').html('<a href="#" class="UserOnline" onclick="showUserStatus();return false;">'+html+'</a>');
		   else $('#UserStatusContent').html('<a href="#" class="UserOccupato" onclick="showUserStatus();return false;">'+html+'</a>');
	   }
	 });
	
}	

//funzioni per inviare messaggi privati
function send_msg() {
	
	var id = $('#id').val();
	var oggetto = $('#oggetto').val().replace(/&/g,"%26");
	var msg = $('#textarea_1').val().replace(/&/g,"%26");
	oggetto = oggetto.replace(/\+/g,"%2B");
	msg = msg.replace(/\+/g,"%2B");
	if(id=="" || oggetto=="" || msg=="") {
		alert("Tutti i campi sono Obbligatori");
		return false;
	} else {
		$('.buttonSubmit').css('display','none');
		$.ajax({
		   type: "POST",
		   url: "/ajax_sendmsg.php",
		   data: 'action=submit&id='+id+'&oggetto='+oggetto+'&msg='+msg,
		   success: function(html){
			   $('#conten_send_msg').html(html);
		   }
		 });
	}
	
}	

function send_invita_gruppo() {
	
	var id = $('#id').val();
	var alias = $('#gruppo').val();
	var oggetto = "Invito al Gruppo";
	var msg = 'Ciao! ti invito a partecipare al Gruppo <a href="http://it.manyego.com/gruppi/'+alias+'/" target="_blank">http://it.manyego.com/gruppi/'+alias+'/</a> <br>Troverai tanti amici come me che ti aspettano...non perdere altro tempo vienici a trovare!';
	if(id=="" || alias=="" || msg=="") {
		alert("Tutti i campi sono Obbligatori");
		return false;
	} else {
		$('.buttonSubmit').css('display','none');
		$.ajax({
		   type: "POST",
		   url: "/ajax_sendmsg.php",
		   data: 'action=submit&id='+id+'&oggetto='+oggetto+'&msg='+msg,
		   success: function(html){
			   $('#conten_send_msg').html(html);
		   }
		 });
	}
	
}	

function send_invita_evento() {
	
	var id = $('#id').val();
	var alias = $('#gruppo').val();
	var oggetto = "Invito all'Evento";
	var msg = 'Ciao! ti invito a partecipare all\'Evento <a href="http://it.manyego.com'+alias+'" target="_blank">http://it.manyego.com'+alias+'</a>  <br>Troverai tanti amici come me che ti aspettano...non perdere altro iscriviti all\'Evento!';
	if(id=="" || alias=="" || msg=="") {
		alert("Tutti i campi sono Obbligatori");
		return false;
	} else {
		$('.buttonSubmit').css('display','none');
		$.ajax({
		   type: "POST",
		   url: "/ajax_sendmsg.php",
		   data: 'action=submit&id='+id+'&oggetto='+oggetto+'&msg='+msg,
		   success: function(html){
			   $('#conten_send_msg').html(html);
		   }
		 });
	}
	
}	

function change_selected(a){
	if(a==1){
		$("#email").removeAttr("disabled");
		$("#gruppo_amici").attr("disabled","disabled")
	} else {
		$("#gruppo_amici").removeAttr("disabled");
		$("#email").attr("disabled","disabled")
	}
}

function checkFriendMail(){
	var a=$("#email").val();
	$("#mailcheck").slideUp(300,function(){
		$.ajax({
			type:"POST",
			url:"/ajax_checkusrmsg.php",
			data:"url="+a,
			success:function(b){
				$("#mailcheck").html(b);
				var c=$("#mailch").val();
				if(c==1){$("#frindMail").removeAttr("disabled")}
				else{$("#frindMail").attr("disabled","disabled")}
				$("#mailcheck").slideDown(300)
			}
		})
	})
}

function control_group(a){
	if(a==""){$("#frindMail").attr("disabled","disabled")}
	else{$("#frindMail").removeAttr("disabled")}
}

function add_friend(){
	var a=$("#id_friend").val();
	var b=$("#textarea_1").val();
	$('.buttonSubmit').css('display','none');
	$.ajax({
		type:"POST",
		url:"/ajax_addfrind.php",
		data:"id_friend="+a+"&motivo="+b+"&action=submit",
		success:function(c){
			$("#conten_add_group").html(c)
		}
	})
}


// apri pannelli bottombar
function open_online_friend() {
	//alert($('#online_friends').offset().left);
	var w = ($(window).width() - $('#bottom_bar').width())/2;
	if($('#amici_online').css('display')=='none') {
		$('#online_friends').css('background','#eeeeee');
		$.ajax({
		   type: "POST",
		   url: "/ajax_bottombar_online.php",
		   data: '',
		   success: function(html){
			   $('#amici_online').html(html);
			   $('#amici_online').css('right',w+'px');
			   $('#amici_online').css('display','block');
		   }
		 });
	} else {
		$('#amici_online').css('display','none');
		$('#online_friends').css('background','#cccccc');
	}
}	

var old_content = "";

function open_chat(id_usr, session) {
	if($('#chat_'+session).length == 0) {
		//var w = (($(window).width() - $('#bottom_bar').width())/2)+200+10;
		
		$('#chatting_friend').append(
		  $.DIV(
			{id:'chat_'+session,'class':'bottom_panel chat_div'}
		  )
		);
		
		var w = $('#bottom_chat_'+session).offset().left;
		$('#chat_'+session).css('left',w+'px');
		
		$('#chatting_friend').append(
		  $.DIV(
			{id:'player_chat_div_'+session}
		  )
		);
		
		timeId = setTimeout('chat_reload("'+session+'")',2000);
		
		$.ajax({
		   type: "POST",
		   url: "/ajax_chat.php",
		   data: 'id_usr='+id_usr+'&session='+session+'&timeId='+timeId,
		   success: function(html){
				$('#chat_'+session).html(html);
				$('#bottom_chat_'+session).css('text-decoration','none');
				$('#bottom_chat_'+session).css('background','#cccccc');
				$('#bottom_chat_'+session).css('color','#000000');
				$('#chatting_friend').css('display','block');
				
				old_content = $('#box_'+session).html();
				/*
				$.jheartbeat.set({
				   url: "/ajax_chat_reload.php?session="+session+"&", // The URL that jHeartbeat will retrieve
				   delay: 2000, // How often jHeartbeat should retrieve the URL
				   div_id: "box_"+session // Where the data will be appended.
				}); 
				*/
				
			}
		 });
	}
	
}

//funzioni per la chat
function create_chat(id_usr) {
	$.ajax({
	   type: "POST",
	   url: "/ajax_chat_reload.php",
	   data: 'id_usr='+id_usr+'&create=1',
	   success: function(html){
		   if($('#amici_online').css('display')=='block') {
		   		open_online_friend();
		   }
		   $('#bottom_bar').append(
			  $.DIV(
				{id:'bottom_chat_'+html,'class':'bottom_tag chat_usr'}
			  )
			);
		   open_chat(id_usr,html);
		}
	 });
}

function chat_reload(session) {
	$.ajax({
	   type: "POST",
	   url: "/ajax_chat_reload.php",
	   data: 'session='+session,
	   success: function(html){
		   $('#box_'+session).html(html);
		   $('#box_'+session)[0].scrollTop = $('#box_'+session)[0].scrollHeight;
		   
		   if(old_content!=html) {
				$("#player_chat_div_"+session).empty();
				$("#player_chat_div_"+session).prepend(insertPlayer());
		   }
		   old_content = html;
		   
		   if($('#chat_closed_session_'+session).length > 0) {
			    old_content = "";
				$('#textarea_'+session).attr('disabled','disabled');
		   } else {
			   timeId = setTimeout('chat_reload("'+session+'")',2000);
			   $('#time_chat_'+session).val(timeId);
		   }
	   }
	 });
}

function close_chat(session) {
	timeId = $('#time_chat_'+session).val();
	clearTimeout(timeId);
	$('#chat_'+session).remove();
	$.ajax({
	   type: "POST",
	   url: "/ajax_chat_reload.php",
	   data: 'session='+session+'&close=1',
	   success: function(html){
	   		old_content = "";
	   }
	 });
	
	
}

function checkKeyPress(event, session) {
	//alert(event.keyCode);
	if(event.keyCode == 13 && !event.shiftKey) {
		//alert($("#chatlist")[0].scrollHeight);
		sendMessage(session);		
	}
}

function sendMessage(session) {
	testo = $('#textarea_'+session).val()
	id_usr = $('#chat_idusr_'+session).val()
	$('#textarea_'+session).val('').focus();
	//testo = testo.replace('\n', '<br />\n');
	$.ajax({
	   type: "POST",
	   url: "/ajax_chat_reload.php",
	   data: 'session='+session+'&testo='+testo+'&id_usr='+id_usr,
	   success: function(html){
		   $('#box_'+session).html(html);
		   old_content = html;
		   $('#box_'+session)[0].scrollTop = $('#box_'+session)[0].scrollHeight;
	   }
	 });
}

function insertPlayer(){

	//var soundz = ['gimme_money.mp3','hu_babe.mp3','oh_dude.mp3','again.mp3','script_4me.mp3']

	var playerpath	= '/chat_sound.swf';
	var filename		= '/oh_dude.mp3';
	//var filename	= path + soundz.random();

	var mp3html = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
	mp3html += 'width="1" height="1" ';
	mp3html += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">';
	mp3html += '<param name="movie" value="'+playerpath+'?';
	mp3html += 'showDownload=false&file=' + filename + '&autoStart=true';
	mp3html += '&backColor=ffffff&frontColor=ffffff';
	mp3html += '&repeatPlay=false&songVolume=50" />';
	mp3html += '<param name="wmode" value="transparent" />';
	mp3html += '<embed wmode="transparent" width="1" height="1" ';
	mp3html += 'src="' + playerpath + '?'
	mp3html += 'showDownload=false&file=' + filename + '&autoStart=true';
	mp3html += '&backColor=ffffff&frontColor=ffffff';
	mp3html += '&repeatPlay=false&songVolume=50" ';
	mp3html += 'type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
	mp3html += '</object>';
	return mp3html;

}

function openVideochatWindow(roomId, uid, langId)
{
    if(!roomId) roomId = '';
    if(!uid) uid = 'Test';
	if(!langId) langId = '';
    var name = 'videochat_' + uid;
    var url = makeUrl('videochat') + '?roomId=' + roomId + '&uid=' + uid + '&langId=' + langId;
    openWindow(url, name, 765, 560, true);
}

function openVideochatFullscreen(roomId, uid, langId)
{
    if(!roomId) roomId = '';
    if(!uid) uid = 'Test';
	if(!langId) langId = '';

    var name = 'videochat_' + uid;
    name = name.replace(/[^\w\d]/, '_');
    name = name.replace(/undefined/, '_');
    name = name.replace(/\./, '_');

    var url = makeUrl('videochat') + '?roomId=' + roomId + '&uid=' + uid + '&langId=' + langId;
    url = projectRoot + url;

    var styleStr = makeStyle(0, 0, screen.width, screen.height, true);
    window.open(url, name, styleStr);
}

function openVideochatCorpWindow(roomId, uid, langId)
{
    if(!roomId) roomId = '';
    if(!uid) uid = 'Test';
	if(!langId) langId = '';

    var name = 'videochat_' + uid;
    name = name.replace(/[^\w\d]/, '_');
    name = name.replace(/undefined/, '_');
    name = name.replace(/\./, '_');
    
    var url = makeUrl('videochat') + '?roomId=' + roomId + '&uid=' + uid + '&langId=' + langId;
    url = projectRoot2 + url;

    var left = Math.round((screen.width - 765) / 2);
    var top = Math.round((screen.height - 560) / 2);    
    var styleStr = makeStyle(left, top, 765, 560, true);
    
    window.open(url, name, styleStr);    
}

function openChatWindow(roomId, uid, langId)
{
    if(!roomId) roomId = '';
    if(!uid) uid = 'Test';
	if(!langId) langId = '';
    var name = 'chat_' + uid;
    var url = makeUrl('chat') + '?roomId=' + roomId + '&uid=' + uid + '&langId=' + langId;
    openWindow(url, name, 720, 480, true);
}

function openAdminconsoleWindow(isHideVideo)
{
	if(!isHideVideo) isHideVideo = false;
	
    var name = 'adminconsole';
    var url = makeUrl('adminconsole') + '?isHideVideo=' + isHideVideo;
    openWindow(url, name, 590, 370, false);
}

function openCommunicatorWindow(friendName, uid, langId)
{		
    if(!friendName) friendName = '';
    if(!uid) uid = '0';
	if(!langId) langId = '';
    var name = 'communicator_' + uid + '_' + friendName + '_' + langId;
    
    if(communicatorWindows[name] != null)
    {
    	var win = communicatorWindows[name];
    	try
    	{
	    	if(win.document) 
	    	{
		    	win.focus();    	
		    	return;
	    	}
	    	else communicatorWindows[name] = null;
    	}
    	catch(err)
    	{
    		communicatorWindows[name] = null;
    	}
    }
    
    var url = makeUrl('communicator') + '?uid=' + uid + '&friendName=' + friendName + '&langId=' + langId;
    var res = openWindow(url, name, 570, 440, true);
    if(res == null) 
    {
    	countBlocks ++;
    	if(countBlocks >= 3) alert('Please disaple pop-up blocker for proper Community Messenger performance.');
    }
    else communicatorWindows[name] = res;
}

function openMessengerWindow(friendName, uid, langId)
{
    if(!friendName) friendName = '';
    if(!uid) uid = '0';
	if(!langId) langId = '';
    var name = 'messenger_' + uid + '_' + friendName;
    
    if(messengerWindows[name] != null)
    {
    	var win = messengerWindows[name];
    	try
    	{
	    	if(win.document) 
	    	{
		    	win.focus();    	
		    	return;
	    	}
	    	else messengerWindows[name] = null;
    	}
    	catch(err)
    	{
    		messengerWindows[name] = null;
    	}
    }
        
    var url = makeUrl('messenger') + '?uid=' + uid + '&friendName=' + friendName + '&langId=' + langId;
    var res = openWindow(url, name, 570, 440, true);
    if(res == null) 
    {
    	countBlocks ++;
    	if(countBlocks >= 3) alert('Please disaple pop-up blocker for proper Community Messenger performance.');
    }
    else messengerWindows[name] = res;
}

function openRecorderWindow(userName)
{
    if(!userName) userName = 'Test';
    var name = 'recorder_' + userName
    var url = makeUrl('recorder') + '?uid=' + userName;
    openWindow(url, name, 540, 330, false);
}

function openPlayerWindow(userName)
{
    if(!userName) userName = 'Test';
    var name = 'player_' + userName;
    var url = makeUrl('player') + '?uid=' + userName + '&showList=true';
    openWindow(url, name, 540, 290, false);
}

function openSmallPlayer(videoId)
{
	var name = 'small_player_' + videoId;
    var url = makeUrl('player') + '?videoId=' + videoId + '&showList=false';
    openWindow(url, name, 320, 295, false);
}

function openSiteMailWindow(uid, receiverId)
{
    if(!uid) uid = '0';
    if(!receiverId) receiverId = '0';
    var name = 'site_mail_' + uid;
    var url = makeUrl('site_mail') + '?uid=' + uid + '&receiverId=' + receiverId;
    openWindow(url, name, 560, 404, true);
}

function openGameRoomWindow(paramString, windowId)
{
    var url = makeUrl('gameroom') + paramString;
    openWindow(url, windowId, 750, 500, false);
}

function openWindow(url, name, width, height, isResizeAble)
{
    url = projectRoot + url;
    name = name.replace(/[^\w\d]/g, "_"); // added flag g
    name = name.replace(/undefined/, '_');
    name = name.replace(/\./, '_');
    url = encodeURI(url);// added to fix bug in IE 7 with usernames which has spaces
    var left = Math.round((screen.width - width) / 2);
    var top = Math.round((screen.height - height) / 2);
    var styleStr = makeStyle(left, top, width, height, isResizeAble);
    var res = window.open(url, name, styleStr);
    return res;
}

function openHelp(url)
{
    var name = 'help';
    var width = 350;
    var height = 500;
    var left = screen.width - width - 10;
    var top = 10;
    var styleStr = makeStyle(left, top, width, height, true);
    window.open(url, name, styleStr);
}

function makeUrl(application)
{
    return application + '/server/' + serverEngine + '/' + application + '.' + serverEngine;
}

function makeStyle(left, top, width, height, isResizeAble)
{
    var styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no';
    styleStr += ',resizable=' + (isResizeAble ? 'yes' : 'no');
    styleStr += ',width=' + width + ',height=' + height;
    styleStr += ',left=' + left + ',top=' + top;
    styleStr += ',screenX=' + left + ',screenY=' + top;
    return styleStr;
}
