$(function() {
					 
	// Eventi che scorrono
	/*$("#prossimiEventi").cycle({ 
		fx:      "fade", 
		speed:    1000, 
		timeout:  4000,
		pause: 1
	});*/
	
	
	/* MENU */
	$("#menu ul#menu-sinistro").superfish({ 
    	hoverClass:  'menuOver',          						// the class applied to hovered list items 
			delay:       400,                            // one second delay on mouseout 
			animation:   { opacity: 'show', height:'show' },  // fade-in and slide-down animation 
    	disableHI:   false,	              						// set to true to disable hoverIntent detection 
			speed:       200,                          // faster animation speed 
			autoArrows:  false,                           // disable generation of arrow mark-up 
			dropShadows: false                            // disable drop shadows 
	});
	
	
	
	/* COMMENTI */
	// Mostra tutti
	$('.commenti-mostraTutti').live('click', function() {
		$(this).parents('.bottom').find('li').show();
		$(this).parents('li').remove();
		return false;
	});
	
	// Show/Hide nuovo commento
	$('.commento-nuovoFake').live('click', function() {
		$(this).hide().next().show().find('textarea:last').focus();
	});
	$('.commento-nuovo').live('blur', function() {
		if ($(this).find('textarea').val().length == 0)
		{
			$(this).hide().prev().show();
		}
	});
	$('.commento-commenta').live('click', function() {
		$(this).parents('.bottom').find('.commento-nuovo-li').show();
		$(this).parents('.bottom').find('.commento-nuovoFake').hide().next().show().find('textarea').focus();
		return false;
	});
	$('.commento-textarea textarea').keydown(function(event) {
		if (event.keyCode == '13') {
			console.log('ciao');
			$(this).parents('.ajaxForm').submit();
			event.preventDefault();
		}
	});
	
	// Elimina
	/*$('.commento-elimina').live('click', function() {
		var commento = $(this).parents('li:first');
		var url = $(this).attr('href');
		$('#elimina-dialog').dialog({
			width: 				400,
			open: 				function() {
				$('.ui-dialog *:focus').blur();
				$(this).find('.dialog-conferma').click(function() {
					$.get(url, function() {
						$(commento).fadeOut();
						$(dialog).dialog('close');
					});
				});
				var dialog = this;
				$(this).find('.dialog-close').click(function() {
					$(dialog).dialog('close');
				});
			}
		});
		return false;
	});*/
	
	
	
	// MENU EDITORE
	$('.oggetto').live('mouseover mouseout', function(event) {
  	if (event.type == 'mouseover') {
			$(this).children('.menuEditore').show();
		} else {
			$(this).children('.menuEditore').hide();
		}
	});
	
	// Elimina
	$('.elimina').live('click', function() {
		var elemento = $(this).closest('.oggetto');
		var url = $(this).attr('href');
		$('#elimina-dialog').dialog({
			modal: 				true,
			width: 				400,
			title:				$(this).attr('rel'),
			open: 				function() {
				$('.ui-dialog *:focus').blur();
				$(this).find('.dialog-conferma').click(function() {
					if (elemento.length != 0)
					{
						$.get(url, function() {
							$(elemento).fadeOut();
							$(elemento).remove();
							$(dialog).dialog('close');
						});
					} else {
						console.log('ciao');
						window.location = url;
					}
				});
				var dialog = this;
				$(this).find('.dialog-close').click(function() {
					$(dialog).dialog('close');
				});
			}
		});
		return false;
	});
  $('.comento-elimina').live('click', function() {
		var elemento = $(this).closest('.oggetto');
		var url = $(this).attr('href');
		var cntRel = $(this).attr('rel');
		$('#elimina-dialog').dialog({
			modal: 				true,
			width: 				400,
			title:				$(this).attr('rel'),
			open: 				function() {
				$('.ui-dialog *:focus').blur();
				$(this).find('.dialog-conferma').click(function() {
					if (elemento.length != 0)
					{
						$.get(url, function(data) {
							$(elemento).fadeOut();
							$(elemento).remove();
							$(dialog).dialog('close');
							// Update comment counter
							$('#'+cntRel).html(data);
						});
					} else {
						window.location = url;
					}
				});
				var dialog = this;
				$(this).find('.dialog-close').click(function() {
					$(dialog).dialog('close');
				});
			}
		});
		return false;
	});
	// Confirm
	$('.confirm').live('click', function() {
		var elemento = $(this).closest('.oggetto');
		var url = $(this).attr('href');
		var msg = $(this).attr('msg');
		$('#confirm-dialog').dialog({
			modal: 				true,
			width: 				400,
			title:				$(this).attr('rel'),
			open: 				function() {
				$('.ui-dialog *:focus').blur();
				$(this).find('.dialog-content').html( '<div class="dialog-testo">'+msg+'</div>' );
				//$('<button class="dialog-conferma pulsante-attivo">Invia</button>').insertBefore($(this).find('.dialog-close'));
				$(this).find('.dialog-conferma').click(function() {
					if (elemento.length != 0)
					{
						$.get(url, function() {
							$(elemento).fadeOut();
							$(elemento).remove();
							$(dialog).dialog('close');
						});
					} else {
						console.log('ciao');
						window.location = url;
					}
				});
				var dialog = this;
				$(this).find('.dialog-close').click(function() {
					$(dialog).dialog('close');
				});
			}
		});
		return false;
	});
	
	// Menu Top Pagina
	$('.pageTopContextMenu-trigger').live('click', function(event) {
		var menu = $(this).parents('.pageTopContextMenu').children('.pageTopContextMenu-options');
		$(menu).toggle('slide', { direction: 'up' }, 150);
		$('html').one('click',function() {
    	$(menu).hide('slide', { direction: 'up' }, 150);
  	});
		event.stopPropagation();
	});
	$('.pageTopContextMenu-options li a').live('click', function(event) {
		$(this).parents('.pageTopContextMenu').children('.pageTopContextMenu-options').toggle('slide', { direction: 'up' }, 150);
	});
	
	
	
	/* LIKE */
	// Like-Unlike
	$('.iLikeIt').live('click', function(a) {
		$.get(a.currentTarget, function(data) {
			$('body').append('<div id="temp"></div>');
			var temp = $('#temp').html(data);
			$(a.currentTarget).closest('.bottom').find('.like-box-container').replaceWith(temp.find('.like-box-container'));
			$(a.currentTarget).replaceWith(temp.find('.iLikeIt'));
			$('#temp').remove();
		});
		return false;
	});
	
	// Dialog
	$('.whoLikesIt').live('click', function(a) {
		$('#whoLikes-content').load(a.currentTarget.href, function() {
			$('#whoLikes').dialog();
		});
		return false;
	});
	
	/* FAN */
	//Become Fan - Unbecome Fan
	$('.becomeFan, .unbecomeFan').live('click', function(a) {	
		$.get(a.currentTarget.href, function(data) {
			$(a.currentTarget).parents('.fanButton').replaceWith(data);
			$.get($('#profileFans').attr('ajaxUrl'), function(data) {
				$('#profileFans').replaceWith(data);
			});
		});
		return false;
	});
	
	// Dialog
	$('.whoIsFan').live('click', function(a) {
		$('#whoIsFan-content').load(a.currentTarget.href, function() {
			$('#whoIsFan').dialog();
		});
		return false;
	});
	$('.whoIsMember').live('click', function(a) {
		$('#whoIsMember-content').load(a.currentTarget.href, function() {
			$('#whoIsMember').dialog();
		});
		return false;
	});
	

	/* MESSAGGI */ 
	function messageComposeDialog(trigger)
	{                                                                  
		var usr = $(trigger).attr('user');
		var disabledValue = $(trigger).attr('disabled');
		
		$.get($(trigger).attr('href'), function(data) {
  		$('body').append(data);
			$('#messaggioNuovo-dialog').dialog({
				autoOpen: 			true,
				open: 				function() {
					var dialog = this;
					$(this).find('.dialog-close').click(function() {
						$(dialog).dialog('close');
					});
					$('.form-select-peopleAutocomplete').peopleAutocomplete({
						url: '/index.php/utenti/autocomplete',
						defaultEntry: usr,
						disabled: disabledValue
					});	
					$('#messaggioNuovo-dialog-confirm').attr('disabled', 'disabled').addClass('pulsante-disabled');
					$('#messaggio_body, .ui-autocomplete-input, .ui-autocomplete-x, .ui-autocomplete .ui-menu-item').live('keyup mouseup focus click', function(e) {
						if($('#messaggio_destinatari').val() != '' && $('#messaggio_body').val() != '')
						{
							$('#messaggioNuovo-dialog-confirm').removeAttr('disabled').removeClass('pulsante-disabled').addClass('pulsante-attivo');
						}
						else
						{
							$('#messaggioNuovo-dialog-confirm').attr('disabled', 'disabled').removeClass('pulsante-attivo').addClass('pulsante-disabled');
						}
					});
					$('form textarea', '.ui-dialog').elastic();
							$('#messaggioNuovo-dialog-confirm').click(function() { 
								$('#messaggioNuovo-dialog form').ajaxSubmit({ 
									success: function(data) {
										$('body').append('<div id="temp">'+data+'</div>');
										$('#messaggioNuovo-dialog-content').replaceWith($('#temp').find('#messaggioNuovo-dialog-content'));
										$('#temp').remove();
										if ($('#messaggioNuovo-dialog-content').find('.conferma').length)
										{
											$('#messaggioNuovo-dialog').dialog( "widget" ).delay(800).fadeOut(300, function() {
												$('#messaggioNuovo-dialog').remove();
											});
										}
										else
										{
											$('.form-select-peopleAutocomplete').peopleAutocomplete({
												url: '/index.php/utenti/autocomplete',
												defaultEntry: usr
											});	
											$('form textarea', '.ui-dialog').elastic();
										}
									}
								}); 
							});
				},
				close:				function() {
					$('#messaggioNuovo-dialog').remove();
				}
			});
		});                
	} 
	$('#messaggioNuovo, .messaggioNuovo').live('click', function(event) {
		messageComposeDialog(event.currentTarget);
		return false;
	});
	
	var requestDialog = function(target) {
		$.get($(target).attr('href'), function(data) {
  		$('body').append(data);
			$('#request-dialog').dialog({
				autoOpen: 			true,
				open: 				function() {
					var dialog = this;
					$(this).find('.dialog-close').click(function() {
						$(dialog).dialog('close');
					});
					$('.form-select-peopleAutocomplete').peopleAutocomplete({
						url: '/index.php/utenti/autocomplete'
					});
					$('#request-dialog-confirm').click(function() { 
						$('#request-dialog form').ajaxSubmit({ 
							success: function(data) {
								$('body').append('<div id="temp">'+data+'</div>');
								$('#request-dialog-content').replaceWith($('#temp').find('#request-dialog-content'));
								$('#temp').remove();
								if ($('#request-dialog-content').find('.conferma').length)
								{
									$('#request-dialog').dialog( "widget" ).delay(800).fadeOut(300, function() {
										$('#request-dialog').remove();
									});
								}
								else
								{
									$('.form-select-peopleAutocomplete').peopleAutocomplete({
										url: '/index.php/utenti/autocomplete'
									});	
								}
							}
						}); 
					});
				}
			});
		});
	}
	
	
	$('.request').click( function(event) {
		requestDialog(event.currentTarget);
		return false;
	});
	
var participationDialog = function(target,rel) {
		$.get('/index.php/participants/dialog', {
				current: $('#participants_'+rel).val()
		  }, function(data) {
  		$('body').append(data);
			$('#participation-dialog').dialog({
				autoOpen: 			true,
				open: 				function() {
					var dialog = this;
					$(this).parent().find('.ui-dialog-titlebar-close').click(function() {
						$(dialog).remove();						
					});
					$(this).find('.dialog-close').click(function() {
						$(dialog).remove();
					});
					$('.form-select-peopleAutocomplete').peopleAutocompleteInvite({
						url: '/index.php/utenti/autocomplete',
						defaultEntry: $('#currentMark').val() ? $('#currentMark').val() : null
					});
					$('#participation-dialog-confirm').click(function() {
						$.post('/index.php/participants/dialog/',
								{ invitedPeople: $('#invitedPeople').val() },function(data){
								$('#participants_'+rel).html(data);
								$('#participants_btn_'+rel).val(lbl_selectParticipants + ' ('+($('#participants_'+rel+' option').size())+')');
								$('#participation-dialog').dialog( "widget" ).delay(800).fadeOut(300, function() {
										$('#participation-dialog').remove();
								});
						});
					});
				}
			});
		});
	}
	
	$('#evento_group_id, #qfEventGroup').change(function() {
		$.get('/index.php/participants/get', { group_id: $(this).val() }, function(data) {
				$('#participants_eventi').html(data);
				$('#participants_btn_eventi').val(lbl_selectParticipants + ' ('+($('#participants_eventi option').size())+')');
		});
	});
	
	$('#disco_group_id, #qfDiscGroup').change(function() {
		$.get('/index.php/participants/get', { group_id: $(this).val() }, function(data) {
				$('#participants_dischi').html(data);
				$('#participants_btn_dischi').val(lbl_selectParticipants + ' ('+($('#participants_dischi option').size())+')');
		});
	});
	
	$('#articolo_group_id, #qfArticleGroup').change(function() {
		$.get('/index.php/participants/get', { group_id: $(this).val() }, function(data) {
				$('#participants_stampa').html(data);
				$('#participants_btn_stampa').val(lbl_selectParticipants + ' ('+($('#participants_stampa option').size())+')');
		});
	});
	
	$('.participation').click( function(event) {
		participationDialog(event.currentTarget, $(this).attr('rel'));
		return false;
	});
	
	// Menu Right Tabs
	$('#menu-destro > li > a.menuTab-trigger').toggle(function(event) {  
		var menuButton = this;
		var menuTab = $(this).next('.menuTab');
		$('.tabOpen').click();     
		$(this).addClass('tabOpen');          
		$(menuTab).show(); 
		if ($(this).attr('ajaxUrl'))
		{                    
			$.get($(this).attr('ajaxUrl'), function(data) {
				var loader = $(menuTab).find('.menuTab-loader');
				if ( $(loader).attr('id') != undefined )
						$(menuTab).find('.menuTab-loader').replaceWith(data);
				else
						$(menuTab).find('.menuTab-content').html(data);
				$(menuButton).find('.count_new').removeClass('visible').html('0').hide(); 
				$('#lastMessages li.menuTab-element-new').switchClass('menuTab-element-new', 'menuTab-element-unread', 3000);          
				$('#lastNotifications li.menuTab-element-new').removeClass('menuTab-element-new', 3000);          
			 	closeMenuTabs(event, menuTab, menuButton);       
			});                                  
		} 
		else 
		{ 
			closeMenuTabs(event, menuTab, menuButton)	
		}
		return false;
	}, function() {
  	$(this).next('.menuTab').hide(); 
		$(this).removeClass('tabOpen');  
	});       
	
	function closeMenuTabs(event, currentTab, currentButton)
	{   
		$('html').one('click', function() {
			if ($(currentTab).is(':visible'))
			{                                                                                                                                    
				$(currentButton).click();
			}
  	});     
		$(currentTab).click(function(event) {
			event.stopPropagation();
		});
		$('.messaggioNuovo').click(function(event) {
			messageComposeDialog(event.currentTarget);
			return false;
		});    		
	}
	
	
	
	/* BACHECA */
	$('#show_more_posts a').live('click', function() {
		$(this).html('<img src="/images/loader/loader.gif" />');
		$.get($(this).attr('href'), function(data) {
			$('#show_more_posts').replaceWith(data);
		});
		return false;
	});
	
	function loadOnScroll()
	{
		$(window).scroll(function(){
			if ($('#show_more_posts a').length != 0 && ($(document).height() - $(window).height()) - $(window).scrollTop() <= $(window).height() / 100 * 65)
			{
				//console.log('document: ' + $(document).height() + ' - window: ' + $(window).height() + ' - scroll: ' + $(window).scrollTop() + ' - (document - window - scroll): ' + ($(document).height() - $(window).height() - $(window).scrollTop()));
				$('#show_more_posts a').html('<img src="/images/loader/loader.gif" />');
				$.get($('#show_more_posts a').attr('href'), function(data) {
					$('#show_more_posts').replaceWith(data);
					loadOnScroll();
				});
				$(window).unbind("scroll");
			}
		});
	}
	loadOnScroll();
	
	
	

	// Tooltip
	$(".tooltip[title]").wijtooltip({
		animation: false,
		position: { my: 'left bottom', at: 'center top' },
		mouseTrailing: true
	});
	
	
	
	// Media
	$.fn.media.defaults.flvPlayer = '/comune/player/mediaplayer-viral/player-viral.swf';
	$.fn.media.defaults.mp3Player = '/comune/player/mediaplayer-viral/player-viral.swf';
	$('.media-audio').media( { width: 429, height: 20, autoplay: true } ); 
	$('.media-video').media({ 
		width: 			470,
		height: 		320,
		autoplay: 	true,
		bgColor:		'#000000'
	});
	
	
	
	/* FORMS */
	// Input
	//$(':input[type="text"], :input[type="password"]').not('textarea#messaggio_body, #menu input').wijtextbox();
	
	// Checkbox
	//$(":input[type='checkbox']").wijcheckbox();

	// Textarea
	$('textarea[class!="mceAdvanced"]').elastic();
	
$.datepicker.regional['it'] = {
		closeText: 'Chiudi',
		prevText: '&#x3c;Prec',
		nextText: 'Succ&#x3e;',
		currentText: 'Oggi',
		monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno',
			'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
		monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu',
			'Lug','Ago','Set','Ott','Nov','Dic'],
		dayNames: ['Domenica','Luned&#236','Marted&#236','Mercoled&#236','Gioved&#236','Venerd&#236','Sabato'],
		dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'],
		dayNamesMin: ['Do','Lu','Ma','Me','Gi','Ve','Sa'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['it']);
	
	$('.form-datepicker, .form-datepickernotime').datepicker({
		dateFormat: 'dd/mm/yy',
		altField: '#'+$(this).attr('id')+'_alt',
		onSelect: function(dateText,inst) {
			var inputID = '#'+$(inst).attr('id');
			$(inputID).attr('value',dateText);
		}
	});
	
	$( ".form-datepicker, .form-datepickernotime" ).datepicker( "option",
				$.datepicker.regional[ 'it' ] );
	
	$('.form-datepicker').each( function(index,value) {
		var timePicker = '<select class="timebox" id="time_'+$(this).attr('id')+'" name="evento[time_'+$(this).attr('id')+']">';
		var selectedVal = $('#time_'+$(this).attr('id')+'_val').val();
		
		if ( selectedVal != undefined ) {
			var selectedHour = selectedVal.substr(0,2);
			var selectedMin = selectedVal.substr(3,2);
		}
		selected1 = selected2 = '';
		
		for( var h = 0; h <= 24; h++ ) {
			if ( h == 12 && selectedVal == undefined ) selected1 = ' selected';
			if ( h <= 10 ) hT = h;
			else hT = h;
			
			if ( selectedVal != undefined
				&& selectedHour == hT
				&& selectedMin == '00' )
				selected1 = ' selected';
			if( selectedVal != undefined
				   && selectedHour == hT
				   && selectedMin == '30' )
				selected2 = ' selected';
			
			timePicker += '<option value="'+hT+':00"'+selected1+'>'+hT+':00</option>';
			timePicker += '<option value="'+hT+':30"'+selected2+'>'+hT+':30</option>';
			
			selected1 = '';
			selected2 = '';
		}
		timePicker += '</select>';
		$(timePicker).insertAfter( $(this) );
	});
	
	
	
	// Date Input
	/*$('.form-wijinputdate').each(function(index, value) {
		var input_id 			= $(this).attr('id');
		var input					= $('#'+input_id);
		var input_value		= $(input).val().replace(/-/g, '/');
		input_value.length != 0 ? default_date = input_value : default_date = new Date();
		$(input).hide().after($('<input type="text" id="'+input_id+'wijinputdate" class="wijinputdate" /><input type="text" id="'+input_id+'wijinputtime" class="wijinputtime" />'));
		$('#'+input_id+'wijinputtime').wijinputdate({ 
			culture: 			'it-IT', 
			dateFormat: 	't',
			date: 				default_date,
			//date: 				input_value,
			datechanged: 	function() {
				var input_new_value = $(this).val();
				$(input).val(input_new_value.substr(6,4)+'-'+input_new_value.substr(3,2)+'-'+input_new_value.substr(0,2)+' '+input_new_value.substr(11,2)+':'+input_new_value.substr(14,2)+':00');
				console.log(input_id, input_new_value, $(input).val());
			}
		}).parents('.wijmo-wijinput').css({ display: 'inline-block', width: 50 }).end().css({ width: 50 });
		$('#'+input_id+'wijinputdate').wijinputdate({ 
			culture: 			'it-IT', 
			dateFormat: 	'd',
			date: 				default_date,
			//date: 				input_value,
			datechanged: 	function() {
				var input_new_value = $(this).val();
				$(input).val(input_new_value.substr(6,4)+'-'+input_new_value.substr(3,2)+'-'+input_new_value.substr(0,2)+' '+input_new_value.substr(11,2)+':'+input_new_value.substr(14,2)+':00');
				console.log(input_id, input_new_value, $(input).val());
			},
			showTrigger: true
		}).parents('.wijmo-wijinput').css({ display: 'inline-block', width: 200 }).end().css({ width: 200 });
	});*/
	
	// Selects
	/*$('.form-row select').wijcombobox({
		//forceSelectionText: true,
		isEditable: false
	});
	$('.wijmo-wijcombobox').css({ display: 'inline-block', width: 356 });
	$('form .wijmo-wijcombobox-wrapper').width(352);
	$('form .wijmo-wijcombobox-trigger').height(23).find('.ui-icon-triangle-1-s').css('margin-top', 3.5);*/

	
	// Birth Date Input
	/*$('.form-wijinputdatebirth').each(function(index, value) {
		var input_id 			= $(this).attr('id');
		var input					= $('#'+input_id);
		var input_value		= $(input).val().replace(/-/g, '/');
		input_value.length != 0 ? default_date = input_value : default_date = new Date();
		$(input).hide().after($('<input type="text" id="'+input_id+'wijinputdate" class="wijinputdate" />'));
		$('#'+input_id+'wijinputdate').wijinputdate({ 
			culture: 			'it-IT', 
			date: 				default_date,
			dateFormat: 	'd',
			startYear: 		1905,
			datechanged: 	function() {
				var input_new_value = $(this).val();
				$(input).val(input_new_value.substr(6,4)+'-'+input_new_value.substr(3,2)+'-'+input_new_value.substr(0,2));
			}
		}).parents('.wijmo-wijinput').css({ display: 'inline-block', width: 423 }).end().css({ width: 413 });
	});  
	$('.form-wijinputdatebirth').each(function() {
		var nascita_input_value	= $(this).val().replace(/-/g, '/');
		$(this).wijinputdate({ 
			culture: 			'it-IT', 
			date: 				nascita_input_value,
			dateFormat: 	'd',
			startYear: 		1905
		}).parents('.wijmo-wijinput').css({ display: 'inline-block', width: 354 }).end().css({ width: 344 });
	});*/
	
	
	// Cities Autocomplete
	var proxy = new wijhttpproxy({
		url: 				'http://ws.geonames.org/searchJSON',
		dataType: 	'jsonp',
		data: {
			featureClass: 'P',
			style: 				'full',
			maxRows: 			10
		},
		key: 				'geonames'
	});

	var myReader = new wijarrayreader([{
		name: 'label',
		mapping: function (item) {
			return item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName
		}
	}, {
		name: 'value',
		mapping: 'name'
	}, {
		name: 'selected',
		defaultValue: false
	}]);

	var datasource = new wijdatasource({
		reader: myReader,
		proxy: proxy
	});
	
	$(".form-wijinputcities").wijcombobox({
		data: datasource,
		showTrigger: false,
		search: function (e, obj) {
			obj.datasrc.proxy.options.data.name_startsWith = obj.term.value;
		}
	}).parents('.wijmo-wijcombobox').width(385).css('display', 'inline-block').end().parent().width(383).height(26).end().width(373).height(22);

	
	
	
	// AJAX FORM
	$('.ajaxForm').submit(function() {
		var form = this;
		$(this).ajaxSubmit({ 
			success: function(responseText, statusText, xhr, $form) {
				$(form).parents('ul').find('li:last').before(responseText);
				$(form).find('textarea').focus().val('');
			}
		});
		return false;
	}); 
	$('.form-ajax').submit(function() {                     
		var form = this;
		$(this).ajaxSubmit({ 
			success: function(responseText, statusText, xhr, $form) {
				$(form).replace(responseText);
			}
		});
		return false;
	}); 
	
	
	
	// Default Username e Password
	var passwordField = $('#columnLeft input[name="signin[password]"]');
	var usernameField = $('#columnLeft input[name="signin[username]"]');
	var usernameFieldDefault = usernameField.val();
	passwordField.after('<input id="passwordPlaceholder" type="text" value="Password" autocomplete="off" class="form-input" />');
	var passwordPlaceholder = $('#passwordPlaceholder');
	passwordPlaceholder.show();
	passwordField.hide();
	passwordPlaceholder.focus(function() {
		passwordPlaceholder.hide();
		passwordField.show().focus();
	});
	passwordField.blur(function() {
		if(passwordField.val() == '') {
			passwordPlaceholder.show();
			passwordField.hide();
		}
	});
	usernameField.focus(function() {
		if(usernameField.val() == usernameFieldDefault) { usernameField.val(''); }
	});
	usernameField.blur(function() {
		if(usernameField.val() == '') { usernameField.val(usernameFieldDefault); }
	});
	
	
	
	// Dialog Defaults
	$.extend(
		$.ui.dialog.prototype.options, {
			autoOpen: 			true,
			bgiframe: 			true,
			closeOnEscape: 	true,
			draggable:			false,
			hide: 					'fade',
			minHeight:			50,
			modal: 					false,
			resizable: 			false,
			width: 					500,
			open: 					function() {
				//$('.ui-dialog *:focus').blur();
				var dialog = this;
				$(this).find('.dialog-close').click(function() {
					$(dialog).dialog('close');
				});
			},
			close:          function() {
				$(this).remove();
			}
	});

	
							
});
	
// Tiny MCE
tinyMCE.init(
{
	mode : "textareas",
	theme : "simple",
	width: "384px",
	editor_selector : "mceSimple"
});
tinyMCE.init(
{
	mode : "textareas",
	theme : "simple",
	width: "384px",
	height: "450px",
	editor_selector : "mceSimpleTall"
});
tinyMCE.init(
{
	mode : "textareas",
	theme : "advanced",
	width: "384px",
	height: "450px",
	editor_selector : "mceAdvanced",
	theme_advanced_toolbar_location : "top",
	theme_advanced_buttons1: "bold, italic, underline,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,indent,outdent,link,unlink,code",
	theme_advanced_buttons2: "",
	theme_advanced_buttons3: "",
	plugins : "paste",
	paste_use_dialog : false,
	paste_auto_cleanup_on_paste : true,
	paste_convert_headers_to_strong : false,
	paste_strip_class_attributes : "all",
	paste_remove_spans : true,
	paste_remove_styles : true
});

// GROUP SETTINGS
var groupSettingsUpdate = function( )
{

	alert('Group settings saved!');
		
	//$.get( updateUrl, updateData, function(data) {
	//	alert('Group settings saved!');
	//}, 'json');

	return false;
}

$(document).ready(function(){

	/* Ricerca Utenti */	
	$('.utenti-cerca').wijcombobox({
		data: new wijdatasource({
	    reader: new wijarrayreader([{
			  name: 'label',
			  mapping: function (item) {
		     	return '<span class="utenti-cerca-utente"><img src="' + item.Img + '" />' + '<span class="utenti-cerca-utente-nome">' + item.value + '</span></span>'
			  }
			}, {
			  name: 'value',
			  mapping: 'name'
			}, {
			  name: 'selected',
			  defaultValue: false
			}]),
	    proxy: new wijhttpproxy({
	 			url: '/frontend_dev.php/utenti/autocomplete',
				dataType: 'json',
				data: {
					term: ''
				}
			})
		}),
		dropdownHeight: 500,
		minLength: 1,
    showTrigger: false,
    search: function (e, obj) {
        obj.datasrc.proxy.options.data.term = obj.term.value;
    },
    select: function (e, item) {
    	window.location = $(this).attr('baseUrl') + item.value.username;
			return false;
    }
	});
	
	$('#utentiSearchBar').css('width','220px');
	$('#utentiSearchBar').parents('.wijmo-wijcombobox').css('width','233px');

	var joinDialog = function(target) {
		$.get($(target).attr('href'), function(data) {
  		$('body').append(data);
			$('#request-dialog').dialog({
				autoOpen: 			true,
				open: 				function() {
					var dialog = this;
					$(this).find('.dialog-close').click(function() {
						$(dialog).dialog('close');
					});
					$('#request-dialog-confirm').click(function() {
						$.post(target,{},function(data){
							$('body').append('<div id="temp">'+data+'</div>');
							$('#request-dialog-content').replaceWith($('#temp').find('#request-dialog-content'));
							$('#joinGroupWrapper').replaceWith( $('#temp').find('#cancel_join_request') );
							$('#temp').remove();
							
							$('a.joinGroupCancel').click( function(event) {
								var target = $('#'+event.target.id);
								$.get( event.currentTarget, {}, function(message) {
									$(target).html( message );
								});
								return false;
							});
							
							if ($('#request-dialog-content').find('.conferma').length)
							{
								$('#request-dialog').dialog( "widget" ).delay(800).fadeOut(300, function() {
									$('#request-dialog').remove();
								});
							}
						});
					});
				}
			});
		});
	}
	
	/*$('.whoLikesIt').tooltip({
		bodyHandler: function() {
			var likeHandler = '#' + $(this).attr('rel');
			return $(likeHandler).html();
		},
		showUrl: false
	});*/
	
	var relationDialog = function(target) {
		$.get($(target).attr('href'), function(data) {
			$('#relation-dialog').dialog({
				autoOpen: 			true,
				open: 				function() {
					var dialog = this;
					$(this).find('.dialog-close').click(function() {
						$(dialog).dialog('close');
					});
					var toUser = 0;
					$('#relation-dialog-content').html(data);
					$('.form-select-peopleAutocomplete').autocomplete({
						source: '/index.php/utenti/autocomplete',
						minLength: 1,
						select: function(event,ui) {
							$('#toUser').val(ui.item.UserId);
						}
					});
					$('.dialog-conferma').click(function() {
						$.post(target,{
								toUser: $('#toUser').val(),
								relation: $('#relationType').val()
							},function(data){
								$('#relationsList').html( data );
							//$('body').append('<div id="temp">'+data+'</div>');
							//$('#relation-dialog-content').replaceWith($('#temp').find('#request-dialog-content'));
							//$('#temp').remove();
							//
							//if ($('#relation-dialog-content').find('.conferma').length)
							//{
							//$('#relation-dialog').toggle();
							$(dialog).dialog('close');
								//$('#relation-dialog').dialog( "widget" ).delay(800).fadeOut(300, function() {
									//$('#relation-dialog')./*z*/('');
								//});
							//}
						});
					});
				}
			});
		});
	}
	
	$('a.joinGroup').click( function(event) {
		joinDialog(event.currentTarget);
		return false;
	});
	
	$('a.joinGroupCancel').click( function(event) {
		var target = $('#'+event.target.id);
		$.get( event.currentTarget, {}, function(message) {
			$(target).html( message );
		});
		return false;
	});

	$('a#saveGroupSettingsBtn').click( function(event) { return groupSettingsUpdate(); } );
	
	$('a.openGroupAdvancedSettings').toggle( 
		function() {
			var rel = '#advancedGroupSettings' + this.rel;
			$(rel).slideDown();
			$(this).find('img').attr('src', '/images/icons/gear--minus.png');
			return false;
		}, function() {
			var rel = '#advancedGroupSettings' + this.rel;
			$(rel).slideUp();
			$(this).find('img').attr('src', '/images/icons/gear--plus.png');
			return false;			
		}
	);
	
	$('a.ajax').click( function(event) {
		$.get( event.currentTarget, {}, function(data) {
			$('#'+$(event.target).attr('rel')).remove();
		});
		return false;
	});
	
	$('#addContactBtn').click( function(event) {
		$.post( event.currentTarget, {
			contactType: $('#contactType').val(),
			contactValue: $('#contactValue').val()
		}, function(data) {
			$('#contactsList').html( data );
			$('#contactValue').val('');
		});
		return false;
	});
	
	$('.deleteContact').click( function(event) {
		$.post( event.currentTarget, {}, function(data) {
			$('#contactsList').html( data );
		});
		return false;
	})
	
	$('#addEducationBtn').click( function(event) {
		$.post( event.currentTarget, {
			contactType: $('#contactType').val(),
			contactValue: $('#contactValue').val()
		}, function(data) {
			$('#educationList').html( data );
		});
		return false;
	});
	$('#cancelAddEducationJobBtn').click(function(event){
		$('#addEducationJob').toggle();
	});
	$('#cancelAddEducationBtn').click(function(event){
		$('#addEducation').toggle();
	});
	
	$('#addNewRelation').click(function(event) {
		relationDialog(event.currentTarget);
		return false;
	})
	$('#addRelationBtn').click( function(event) {
		$.post( event.currentTarget, {
			toUser: $('#toUser').val(),
			relation: $('#relationType').val()
		}, function(data) {
			$('#relationsList').html( data );
		});
		return false;
	});
	
	$('#addEducationJobBtn').click( function(event) {
		$.post( event.currentTarget, {
			contactType: $('#contactType').val(),
			contactValue: $('#contactValue').val()
		}, function(data) {
			$('#educationList').html( data );
		});
		return false;
	});
	
	$('.deleteEducation').click( function(event) {
		$.post( event.currentTarget, {}, function(data) {
			$('#educationList').html( data );
		});
		return false;
	});
	
	
	// ENABLE tinyMCE FOR TEXTAREAS
	$('.cmeditor').each(function(index, value){
		tinyMCE.init({
			auto_focus: false,
			mode: 'exact',
			elements : $(this).attr('id'),
			theme : "advanced",
			theme_advanced_toolbar_location : "top",
			theme_advanced_buttons1: "bold, italic, underline,separator,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,indent,outdent,link,unlink,code",
			theme_advanced_buttons2: "",
			theme_advanced_buttons3: "",
			plugins : "paste",
			width: "100%",
			paste_use_dialog : false,
			paste_auto_cleanup_on_paste : true,
			paste_convert_headers_to_strong : false,
			paste_strip_class_attributes : "all",
			paste_remove_spans : true,
			paste_remove_styles : true
		});
	});
		
});

	function openRelationForm() {
		$('#addRelation').slideDown();
		return false;
	}
	
	function openContactsForm() {
		$('#addContact').slideDown();
		return false;
	}

//$.ajaxSetup ({
//    // Disable caching of AJAX responses 
//    cache: false
//});
