function preinit_send_to(rcpt,tpoa) {
	switch_tab('t/sendsms.php',$('#tab_invio'),null,function() {
		$("#send_sms_radio_num").click();
		$("#wrapper_numeri_singoli").find("input").val(rcpt).click();
		$('#input_custom_tpoa').val(tpoa);
		$('#wrapper_tipi_sms').find("input[customtpoa='true']").click();
		$('#sms_text').focus();
	});
}

function init_send_to_contacts() {
	send_sms_change('cnt',function() {
		open_contacts_list('stc');
	},function() {
		$('#send_sms_radio_cnt').focus();
	});
}

function init_send_to_groups() {
	send_sms_change('grp',function() {
		open_groups_list('stg');
	},function() {
		$('#send_sms_radio_grp').focus();
	});
}

function set_send_to_contacts(contacts_selection,contacts_count) {
	set_sending_to_info('cnt', contacts_count > 0);
	$('#send_sms_selected_contacts').val(contacts_selection);
	if (contacts_count > 0) {
		show_send_sms_warn_text(label_resolve($('#sms_send_cnt_template').html(),contacts_count));
	} else {
		hide_send_sms_warn_text();
	}
}
function set_send_to_groups(groups_selection,groups_count,contacts_count) {
	set_sending_to_info('grp', groups_count > 0);
	$('#send_sms_selected_groups').val(groups_selection);
	$('#send_sms_to_groups_contacts_count').val(contacts_count);
	if (groups_count > 0) {
		show_send_sms_warn_text(label_resolve($('#sms_send_grp_template').html(),groups_count,contacts_count));
	} else {
		hide_send_sms_warn_text();
	}
}

function init_send_to_num() {
	send_sms_change('num',undefined,function() {
		$('send_sms_radio_num').focus();
	});
}
function update_num_value(input) {
	send_sms_change('num',function() {
		input.removeAttr('readonly');
		var num = input.val();
		if (num.length == 0) {
			num = default_prefix;
		} else {
			if (num.substr(0,1) != '+')
				num = default_prefix + num;
		}
		isvalid = find_nation(num) != null;
		var removed = false;
		if (!isvalid && !sms_num_last(input)) {
			remove_number(input);
			removed = true;
		}
		if (isvalid && sms_num_last(input)) {
			add_new_sms_num();
		}
		if (!removed) {
			if (num != input.val()) {
				input.val(num);
				input.putCursorAtEnd();
			}
		}
		count_num_recipients();
	},function() {
		input.attr('readonly','readonly');
	});
}

function add_new_sms_num() {
	$('#wrapper_numeri_singoli').children('.metti_leva').each(function() {
		$(this).children(".input_numero_singolo").each(function() {
			$(this).attr('last','no');
		});
	});
	var dup = $('#wrapper_numeri_singoli').children(":first").clone();
	dup.hide();
	var new_input = dup.children('.input_numero_singolo');
	new_input.attr('last','last');
	new_input.val('');
	$(new_input).phonenumber();
	dup.children("[name='del_num']").show();
	dup.appendTo('#wrapper_numeri_singoli');
	dup.fadeIn('slow');
	new_input.change();
	new_input.val(new_input.val());
	new_input.focus();
}

function sms_num_last(input) {
	if (input.attr('last') !== undefined) {
		return input.attr('last') == 'last';
	}
	return false;
}

function valid_number(num) {
	return find_nation(num) != null;
}

function remove_number(input) {
	input.parent().fadeOut('slow',function() {
		input.parent().remove();
		var has_last = false;
		var new_last = null;
		var is_first = true;
		$('#wrapper_numeri_singoli').children('.metti_leva').each(function() {
			if (is_first) {
				$(this).children("[name='del_num']").hide();
				is_first = false;
			}
			$(this).children(".input_numero_singolo").each(function() {
				if ($(this).attr('last') == 'last') {
					has_last = true;
				} else {
					new_last = this;
				}
			});
		});
		if (!has_last) {
			$(new_last).attr('last','last');
		}
		count_num_recipients();
	});
}

function count_num_recipients() {
	var count_rcpts = 0;
	$('#wrapper_numeri_singoli').children('.metti_leva').each(function() {
		$(this).children(".input_numero_singolo").each(function() {
			if (valid_number($(this).val()))
				count_rcpts++;
		});
	});
	set_sending_to_info('num', count_rcpts > 0);
	if (count_rcpts == 0) {
		hide_send_sms_warn_text();
	} else {
		show_send_sms_warn_text(label_resolve($('#sms_send_num_template').html(),count_rcpts));
	}
	return count_rcpts;
}

function find_nation(num) {
	var id_nation = null;
	var prefix = null;
	for (var id_n in nations) {
		pfx = nations[id_n];
		if (num.substr(0,pfx.length) == pfx) {
			id_nation = id_n;
			prefix = pfx;
			break;
		}
	}
	if (prefix && num.substr(prefix.length).length > 1)
		return id_nation;
	return null;
}

function hide_send_sms_warn_text() {
	$('#warning_numero_destinatari').fadeOut('slow');
}
function show_send_sms_warn_text(text) {
	$('#send_sms_warn_text').html(text);
	$('#warning_numero_destinatari').fadeIn('slow');
}

sms_to_has_recipients = false;
current_send_sms_type = '';
function reset_sms_to() {
	sms_to_has_recipients = false;
	current_send_sms_type = '';
}
function set_sending_to_info(type,has_recipients) {
	sms_to_has_recipients = has_recipients;
	current_send_sms_type = type;
	send_sms_show_hide_params_div(type != 'num');
}

function reset_send_to() {
	$('#send_sms_selected_contacts').val('');
	$('#send_sms_selected_groups').val('');
	$('#wrapper_numeri_singoli').children('.metti_leva').each(function() {
		$(this).children(".input_numero_singolo").each(function() {
			if ($(this).attr('last') == 'no') {
				$(this).parent().remove();
			} else {
				$(this).val('');
				$(this).parent().find("[name='del_num']").hide();
			}
		});
	});
	hide_send_sms_warn_text();
}

function send_sms_change(type,callback,ucallback) {
	if (type == current_send_sms_type) {
		if (isFunction(callback))
			callback();
		return;
	}
	send_sms_show_hide_params_div(type != 'num');
	if (sms_to_has_recipients) {
		ppconfirm_div('send_sms_change_alert',function() {
			do_lock_ui();
			reset_send_to();
			set_sending_to_info(type, false);
			$("#send_sms_radio_"+type).attr('checked','checked');
			if (isFunction(callback))
				callback();
		},function() {
			$("#send_sms_radio_"+current_send_sms_type).attr('checked','checked');
			send_sms_show_hide_params_div(current_send_sms_type != 'num');
			if (isFunction(ucallback))
				ucallback();
		});
	} else {
		set_sending_to_info(type, false);
		reset_send_to();
		$("#send_sms_radio_"+type).attr('checked','checked');
		if (isFunction(callback))
			callback();
	}
}

function send_sms_show_hide_params_div(is_show) {
	if (is_show)
		$('#sms_send_params_div').show();
	else
		$('#sms_send_params_div').hide();
}

var sms_text_params = new Array(to_param("NAME"),to_param("SURNAME"));
function to_param(a_string) {
	return "%"+a_string+"%";
}
function sms_text_has_parameters(sms_text_id) {
	var has_parameters = false;
	var sms_text = $('#'+sms_text_id).val();
	for (var i=0;i<sms_text_params.length;i++) {
		if (sms_text.indexOf(sms_text_params[i]) >= 0) {
			has_parameters = true;
			break;
		}
	}
	return has_parameters;
}

function sms_text_insert_param(sms_text_id, param_name) {
	$('#'+sms_text_id).val($('#'+sms_text_id).val()+"%"+param_name+"%");
	$('#'+sms_text_id).blur();
}

function send_sms_switch_send_delayed(is_delayed) {
	if (is_delayed) {
		$('#send_sms_hour').timeEntry('setTime',new Date());
		$('#send_sms_date').datepicker('setDate',dt_send_delayed_sms_default());
		$('#send_sms_date_div').fadeIn('fast',function() {
			$('#send_sms_hour_div').fadeIn('fast');
		});
	} else {
		$('#send_sms_hour_div').fadeOut('fast',function() {
			$('#send_sms_date_div').fadeOut('fast');
		});
	}
}

function update_send_sms_credits() {
	$("#elenco_crediti_banner_interno").find("span[name='sms_type_qty_span']").each(function() {
		$('#send_'+$(this).attr('id')).text($(this).text());
	});
}

function send_sms_check_delayed_time(oldTime, newTime, minTime, maxTime) {
	var date = send_sms_get_delayed_date();
	var now = new Date();
	if (is_today(date)) {
		if (newTime.getHours() > now.getHours())
			return newTime;
		if (newTime.getHours() == now.getHours()) {
			if (newTime.getMinutes() >= now.getMinutes())
				return newTime;
		}
		return now;
	}
	return newTime;
}

function send_sms_check_delayed_date(dateText, inst) {
	var date = send_sms_get_delayed_date();
	if (is_today(date)) {
		var time = $('#send_sms_hour').timeEntry('getTime');
		var now = new Date();
		if (time.getHours() == now.getHours) {
			if (time.getMinutes() < now.getMinutes())
				send_sms_actualize_time();
		}
		if (time.getHours() < now.getHours())
			send_sms_actualize_time();
	}
}

function send_sms_get_delayed_date() {
	var a_date = $('#send_sms_date').datepicker('getDate');
	if (a_date == null)
		return new Date();
	return a_date;
}
function send_sms_actualize_time() {
	$('#send_sms_hour').timeEntry('setTime',new Date());
}


function send_sms() {
	$('#sms_text').sms_text('clean');
	var final_recipients = send_sms_count_final_recipients();
	if (final_recipients == 0) {
		pperror_div('send_sms_error_no_recipients');
		return;
	}
	if (!text_filled('input_testo_sms')) {
		pperror_div('send_sms_error_no_text');
		return;
	}
	var message_type_radio = $("input[name='send_sms_message_type']:checked");
	if (message_type_radio.attr('customtpoa') == 'true' && !valid_tpoa()) {
		pperror_div('send_sms_error_invalid_tpoa');
		return;
	}

	do_send_sms(true);
}

function do_send_sms(just_count) {
	var rcpt_param_name,rcpt_param_value;
	switch (current_send_sms_type) {
		case 'num':
			rcpt_param_name = 'numbers';
			rcpt_param_value = '';
			var first = true;
			$('#wrapper_numeri_singoli').find("input[name='num']").each(function() {
				var a_num = $(this).val();
				if (!valid_number(a_num))
					return;
				if (first) {
					rcpt_param_value += a_num;
					first = false;
				} else {
					rcpt_param_value += ","+a_num;
				}
			});
			break;
		case 'cnt':
			rcpt_param_name = 'id_contacts';
			rcpt_param_value = $('#send_sms_selected_contacts').val();
			break;
		case 'grp':
			rcpt_param_name = 'id_groups';
			rcpt_param_value = $('#send_sms_selected_groups').val();
			break;
	}
	var send_when = send_sms_get_send_when();
	params = { };
	params['op'] = 'send_to_'+current_send_sms_type;
	params['id_message_type'] = $("input[name='send_sms_message_type']:checked").val();
	params['tpoa'] = $("#input_custom_tpoa").val();
	params['message'] = $('#sms_text').val();
	params[rcpt_param_name] = rcpt_param_value;
	if (send_when != null)
		params['send_when'] = datetime_to_string(send_when);
	if (just_count) {
		params['op'] = 'count_'+params['op'];
		post_ajax('t/sendsms.php',params,function(data) {
			var text_confirm = '';
			switch (current_send_sms_type) {
				case 'num': text_confirm = label_resolve($('#send_sms_confirm_numbers').html(),data['sms-count'],data['recipients-count']); break;
				case 'cnt': text_confirm = label_resolve($('#send_sms_confirm_contacts').html(),data['sms-count'],data['recipients-count']); break;
				case 'grp': text_confirm = label_resolve($('#send_sms_confirm_groups').html(),data['sms-count'],send_sms_count_selected_groups(),data['recipients-count']); break;
			}
			ppconfirm(text_confirm,do_send_sms);
		});
		lock_ui();
	} else {
		render_ajax('t/sendsms.php','#wrapper_azioni_invio',params);
	}
}


function valid_tpoa() {
	var custom_tpoa = $("#input_custom_tpoa").val();
	return is_valid_tpoa(custom_tpoa);
}

function is_valid_tpoa(str_tpoa) {
	var regexp_numeric_tpoa = new RegExp("^\\+{0,1}\\d{1,16}$");
	var regexp_alpha_tpoa = new RegExp("^.{1,11}$");
	return str_tpoa.match(regexp_alpha_tpoa) || str_tpoa.match(regexp_numeric_tpoa);
}

function send_sms_count_final_recipients() {
	if (!sms_to_has_recipients)
		return 0;
	var num_recipients = 0;
	switch (current_send_sms_type) {
		case 'num': num_recipients = count_num_recipients(); break;
		case 'cnt':
			num_recipients = send_sms_count_selected_contacts(); break;
		case 'grp':
			num_recipients = send_sms_count_selected_groups(); break;
	}
	return num_recipients;
}

function send_sms_count_selected_contacts() {
	var sel = $('#send_sms_selected_contacts').val();
	if (sel.indexOf(',') >= 0)
		return sel.match(/,/g).length + 1;
	return sel.length ? 1 : 0;
}
function send_sms_count_selected_groups() {
	var sel = $('#send_sms_selected_groups').val();
	if (sel.indexOf(',') >= 0)
		return sel.match(/,/g).length + 1;
	return sel.length ? 1 : 0;
}

function send_sms_count_final_smss() {
	return parseInt($('#send_sms_count_smss').text());
}

function send_sms_get_send_when() {
	if ($('#send_sms_send_delayed:checked').exists())
		return get_date_time('send_sms_date','send_sms_hour');
	return null;
}





