(function($) {
	var target;
	var flag_open = false;
	var flag_summary = false;
	var flag_send = false;
	var composition = '';
	var verify_box = '<div id="verify_box" class="float_dx verify_box" style="text-align:right; display:none;">'
		+'<img src="/img/loading.gif" style="vertical-align:middle;">'
		+'Invio sms in corso'
		+'</div>'; 
	var settings = {
		'dialog_id' : 'sms_dialog', 
		'summary_id' : 'sms_summary', 
		'default_content': '<div style="width:100%;text-align:center;">'
			+'<div>'
			+'Caricamento dati...<br/>'
			+'<img src="/img/loading11.gif" />'
			+'</div>'
			+'</div>', 
		'frm_id' : 'frm_send_sms', 
		'frm_action' : '/ajax/send-sms', 
		'sms_width' : 160, 
		'sms_brk' : '\n', 
		'sms_cut' : true, 
		'sms_num' : 1, 
		'sms_max_char' : 300, 
		'sms_max_num': 3, 
		'sms_max_dest': 10, 
		'sms_price' : 0.09, 
		'sms_dest' : 0, 
		'user_current_plafond' : 0.00, 
		'user_enough_plafond' : true, 
		'temp_hide_box_id' : 'hide_box'
	};
	
	var methods = {
		init : function( options ) {
			if ( options ) { 
				$.extend( settings, options );
			}
			// Associo l'apertura del dialo al click sul link
			$(this).bind('click',methods.open);
			
			target = $(this).parent();
		}, 
		open : function() {
			
			if(flag_open) return false;
			
			flag_open = true;
			
			// Controllo se ho già inizializzato il dialog
			if($('#'+settings['dialog_id']).size() != 0) $('#'+settings['dialog_id']).empty();
			else{
				// Inizializzo il dialog
				// Creo l'oggetto
				var box_sms = $('<div></div>');
				// Setto l'id
				box_sms.attr('id',settings['dialog_id']);
				// Inserisco il div nell'html
				target.append(box_sms);
				// Inizializzo il dialog
				box_sms.dialog({
					autoOpen: false, 
					modal: true, 
					draggable: false, 
					resizable: false, 
					title: 'Invio SMS'
				});
			}
			
			if($('#'+settings['summary_id']).size() != 0) $('#'+settings['summary_id']).empty();
			else{
				// Inizializzo il dialog
				// Creo l'oggetto
				var box_sms_summary = $('<div></div>');
				// Setto l'id
				box_sms_summary.attr('id',settings['summary_id']);
				// Inserisco il div nell'html
				target.append(box_sms_summary);
				// Inizializzo il dialog
				box_sms_summary.dialog({
					autoOpen: false, 
					modal: true, 
					draggable: false, 
					resizable: false, 
					title: 'Riepilogo SMS'
				});
			}
			// Dialog di riepilogo
			box_sms_summary = $('#'+settings['summary_id']);
			// Elimino la crocetta
			box_sms_summary.parent().children().children('.ui-dialog-titlebar-close').hide();
			
			// Dialog di creazione sms
			box_sms = $('#'+settings['dialog_id']);
			// Elimino la crocetta
			box_sms.parent().children().children('.ui-dialog-titlebar-close').hide();
			// Imposto il colore standard
			$("[aria-labelledby=ui-dialog-title-"+settings.dialog_id+"] .ui-widget-header").removeClass('ui-widget-header-red');
			// Modifico il contenuto
			box_sms.html(settings.default_content);
			
			$.ajax({
				type: 'POST', 
				url: '/ajax/get-sms-send-box', 
				dataType: 'json', 
				success:function(json){
					box_sms.dialog('close');
					box_sms.empty();
					
					box_sms.append(json.html);
					
					if(!json.logged){
						box_sms.dialog('option','width',500);
						box_sms.dialog('option','buttons',{
							'Chiudi': function(){
								methods.close();
							}
						});
					}
					else{
						// Definizione del costo unitario dell'sms
						if(json.sms_price) settings.sms_price = json.sms_price;
						// plafond residuo del cliente
						if(json.plafond) settings.user_current_plafond = json.plafond;
						// Mask per l'inserimento di un numero di telefono
						$.mask.definitions['9']='';
						$.mask.definitions['~']='[0-9]';
						$('#add_phone').mask("+39 ~~~ ~~~~~~?~",{placeholder:" "});
						
						frm = box_sms.find('form');
						if(frm.size()>0){
							frm.attr('id',settings['frm_id']);
							frm.attr('action',settings['frm_action']);
						}
						
						validator = $('#'+settings.frm_id).validate({
							errorClass: 'orange', 
							errorPlacement: function(error, element){
								error.appendTo(element.nextAll('div'));
							}
						});
						
						// Gestione eventi sullla textarea
						frm.find('textarea').bind('keypress',methods.removeNewLine);
						frm.find('textarea').bind('keyup',methods.wordwrap);
						frm.find('textarea').bind('keyup',methods.updateCount);
						$('#add_phone').bind('keypress',methods.keyAddNumber);
						
						// Aggiunge un nuovo numero
						$('#add_num').bind('click',methods.addNumber);
						// Totale dell'invio dell'sms
						settings.sms_num = 1;
						settings.sms_dest = 0;
						methods.updatePrice(); //$('#tot_price').html(settings.sms_price * settings.sms_num * settings.sms_dest);
						
						box_sms.dialog('option','width',500);
						box_sms.dialog('option','buttons',{
							'Invia': function(){
								methods.summary();
							}, 
							'Chiudi': function(){
								methods.close();
							}
						});
					}
					
					box_sms.dialog('open');
					
					flag_open = false;
				}, 
				error: function(){
					alert('error');
					//window.location.reload();
				}
			});
		}, 
		close : function() {
			if($('div[id*="'+settings['dialog_id']+'"]').size() > 0) return $('#'+settings['dialog_id']).dialog('close');
			console.log('Dialog non inizializzato!');
			return false;
		}, 
		updateCount : function(event){
			$('#num_char').val($(this).val().length);
		    $('#num_sms').val(settings.sms_num);
		    methods.updatePrice();
		}, 
		removeNewLine : function(event){
			if(event.keyCode == 13) return false;
			return true;
		}, 
		wordwrap : function(event) {
			// Svuoto l'errore
			methods.emptyError();
			
			if(event.charCode < 32 || event.charCode > 126 || event.keyCode == 13) str = $(this).val();
			else str = $(this).val() + String.fromCharCode(event.charCode);
			
			if (!str) { return str; }
			
			// Definizione per i parametri del wordwrap
			brk = settings.sms_brk;
		    width = (str.length <= settings.sms_width)? settings.sms_width : settings.sms_width - 4;
		    cut = settings.sms_cut;
		    
		    // Espressione regolare
		    str = str.replace(new RegExp( "\\n", "g" ),"");
		    //var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
		    var regex = '(\\w|\\W){1,' +width+ '}(\\s|$)';
		    var tmp = str.match( RegExp(regex, 'g') );
		    
		    // Aggiorno il numero di sms correnti
		    if(tmp.length != settings.sms_num){
		    	settings.sms_num = tmp.length;
		    	//console.log(tmp);
		    }
		    
		    // Se supero il limite di sms consentito non faccio inserire nessun carattere
		    if(tmp.length > settings.sms_max_num){
		    	methods.setError('Hai superato il numero massimo di sms consentito.');
		    	if(event.charCode < 32 || event.charCode > 126) return true;
		    	else{
		    		return false;
		    	}
		    }
		    $(this).val(str);
		    return true;
		}, 
		addNumber : function(){
			// Svuoto l'errore
			methods.emptyError();
			
			if($('#add_phone').size() == 0) return false;
			// Verifico il numero massimo di destinatari inseribili
			if($('div.number').size() == settings.sms_max_dest){
				return methods.setError('Hai raggiunto il numero massimo di destinatari consentito.');
			}
			// Numero da aggiungere
			var number = $('#add_phone').val();
			if($.trim(number) == '') return false;
			// Html da aggiungere
			var htmlElement = '<div class="number" style="float:left;">'
						+'	<input type="hidden" name="phone[]" value="'+number+'" />'
						+'	<span>'+number+'</span>' 
						+'	<a onclick="$(this).deleteNumber();">'
						+'		<img src="/img/chiudi.png" title="elimina numero" />'
						+'	</a>'
						+'</div>';
			if($('#box_phone_list').children('div.ui-state-error').size() > 0) $('#box_phone_list').empty();
			$('#box_phone_list').append($(htmlElement));
			
			settings.sms_dest++;
			methods.updatePrice();
			$("#box_phone_list").attr({ scrollTop: $("#box_phone_list").attr("scrollHeight") });
			//$("#box_phone_list").animate({ scrollTop: $("#box_phone_list").attr("scrollHeight") }, 1000);
			$('#add_phone').val('');
			$('#add_phone').focus();
			return true;
		}, 
		keyAddNumber : function(event){
			if(event.keyCode == 13){
				var tmp = $(this).val();
				$(this).blur();
				if(!methods.addNumber()){
					$('#add_phone').focus();
					$(this).val(tmp);
				}
			}
		}, 
		updatePrice : function(){
			// Totale dell'invio dell'sms
			var price = settings.sms_price * settings.sms_num * settings.sms_dest;
			$('#tot_price').html(parseFloat(price).toFixed(2));
			settings.user_enough_plafond = (settings.user_current_plafond > price);
		}, 
		emptyError : function(){
			$('#error_box').html('');
		}, 
		setError: function(str){
			$('#error_box').html('<div class="ui-state-error err_validator" style="border:0px; font-size: 12px; background: none repeat scroll 0 0 #FFFFFF;">'+str+'</div>');
			return false;
		}, 
		summary : function(){
			// Svuoto l'errore
			methods.emptyError();
			
			if(!$('#'+settings.frm_id).valid()) return false;
			
			if(settings.sms_num > settings.sms_max_num){
				return methods.setError('Superato il numero massimo di sms');
			}
			
			if($('input[name^="phone"]').size() == 0){ //&& $.trim($('input[name^="phone"]:eq(0)').val()) == ''){
				var error_html = '<div class="ui-state-error" style="border:0px; font-size: 12px;">'
						+'<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>'
						+'<strong>Attenzione:</strong>'
						+' Non è stato specificato nessun destinatario!'
						+'</div>';
				if($('#box_phone_list').children('div.ui-state-error').size() == 0) $('#box_phone_list').html($(error_html));
				return false;
			}
			else $('#box_phone_list').children('div.ui-state-error').remove();
			
			// Verifica inserimento testo
			var text = $('#'+settings.frm_id+' textarea').val();
			if($.trim(text) == ''){
				return methods.setError('Testo sms vuoto.');
			}
			
			// Verifica disponibilità del plafond
			if(!settings.user_enough_plafond){
				return methods.setError('Il credito residuo per l\'invio degli sms non è sufficiente.');
			}
			
			if(flag_summary) return false;
			
			flag_summary = true;
			
			$.ajax({
				type: 'POST', 
				url: '/ajax/get-sms-summary', 
				data: $('#'+settings.frm_id).serialize(), 
				dataType: 'json', 
				success:function(json){
					box_sms = $('#'+settings['dialog_id']);
					box_sms.dialog('close');
					
					if(!json.logged){
						box_sms.empty();
						box_sms.append(json.html);
						box_sms.dialog('option','width',500);
						box_sms.dialog('option','width','');
						box_sms.dialog('option','buttons',{
							'Chiudi': function(){
								methods.close();
							}
						});
						box_sms.dialog('open');
					}
					else{
						// Dialog di riepilogo
						box_sms_summary = $('#'+settings['summary_id']);
						
						//box_sms.empty();
						box_sms_summary.dialog('option','width','');
						box_sms_summary.dialog('option','buttons',{
							'Invia': function(){
								methods.send();
							}, 
							'Indietro': function(){
								box_sms_summary.dialog('close');
								box_sms_summary.empty();
								
								box_sms.dialog('option','width',500);
								box_sms.dialog('option','buttons',{
									'Invia': function(){
										methods.summary();
									}, 
									'Chiudi': function(){
										methods.close();
									}
								});
								box_sms.dialog('open');
							}
						});
						
						box_sms_summary.append(json.html);
						box_sms_summary.dialog('open');
					}
					flag_summary = false;
				}, 
				error: function(){
					window.location.reload();
				}
			});
		}, 
		send : function(){
			if(flag_send) return false;
			flag_send = true;
			
			box_sms_summary.next('.ui-dialog-buttonpane').children().hide();
			box_sms_summary.next('.ui-dialog-buttonpane').append(verify_box);
			$('#verify_box').show();
			
			$.ajax({
				type: 'POST', 
				url: '/ajax/send-sms', 
				data: $('#'+settings.frm_id).serialize(), 
				dataType: 'json', 
				success:function(json){
					box_sms_summary.dialog('close');
					
					box_sms.empty();
					box_sms.dialog('option','width','');
					
					// Verifica utente è loggato
					if(!json.logged){
						box_sms.append(json.html);
						box_sms.dialog('option','width',500);
						box_sms.dialog('option','width','');
						box_sms.dialog('option','buttons',{
							'Chiudi': function(){
								methods.close();
							}
						});
					}
					else{
						// Verifica esito invio sms
						if(!json.esito){
							// Dialog d'errore
							$("[aria-labelledby=ui-dialog-title-"+settings.dialog_id+"] .ui-widget-header").addClass('ui-widget-header-red');
							box_sms.append('Errore nell\'invio degli sms');
							box_sms.dialog('option','buttons',{
								'Chiudi': function(){
									methods.close();
								}
							});
						}
						else{
							box_sms.dialog('option','buttons',{
								'Chiudi': function(){
									window.location.reload();
								}
							});
							//box_sms.append('<span>Invio effettuato con successo. </span>');
						}
						
						box_sms.append('<br/><span>Sono stati inviati con successo '+json.info.sms_inviati+' sms a '+json.info.dest_inviati+' destinatari'+((json.info.dest_inviati==1)?'o':'')+'. </span>');
						
						if(json.info.sms_errore != 0){
							if(json.info.sms_errore == 1)
								box_sms.append('<br/><span>'+json.info.sms_errore+' sms è andato in errore. </span>');
							else 
								box_sms.append('<br/><span>'+json.info.sms_errore+' sms sono andati in errore. </span>');
						}
					}
					
					box_sms.dialog('open');
					flag_send = false;
				}, 
				error: function(){
					//alert('error');
					window.location.reload();
				}
			});
			
		}
	};
	
	$.fn.sms = function(method) {
		
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.contrassegno' );
		}
		
		return $(this);
	};
	
	$.extend($.fn, {
		deleteNumber: function(){
			settings.sms_dest--;
			methods.updatePrice();
			$(this).parent().remove();
		}
	});

})(jQuery);
