/*******************************************************
HOW TO USE JSON

function updatediv(){
var obj = makePostJson("controller.php","action=prova");

var myOptions = {

  "Value 1" : obj[0],
  "Value 2" : "Text 1"
}
jQuery("#people").addOption(myOptions, false);

}
**************************************************/

var VALID_ERROR_CLASS = 'valid_error';
//validation handler;
var v = null;
var successfunc = null;
//variabile utilizzata per la validazione di due form sulla stessa pagina che eseguono due operazioni diverse al success della validazione
var redir = 0;

function makePostAjax(controller,params,successfunc,target){

var cont = jQuery.ajax({
           				//mode : "queue",
           				type: "POST",
           				url: controller,
          				data: params,
           				async: true,
 	   	   				success: function(responseText) {
 	                                if(successfunc.length > 0)
 	                                {
 	                                	var fn= eval(successfunc);
										fn(responseText,target);
									}

								}
					});
}

function makePostUpd(controller,param,div){

var cont = jQuery.ajax({
          // 	mode : "queue",
           type: "POST",
           url: controller,
           data: param,
           async: false
           }).responseText;

     jQuery(div).html(cont);
}

function makePostAdv(controller,param){

var cont = jQuery.ajax({
           //	mode : "queue",
           type: "POST",
           url: controller,
           data: param,
           async: false
           }).responseText;
     return cont;
}





function makePostNoUpd(controller,param){

jQuery.ajax({
           //mode : "queue",
           type: "POST",
           url: controller,
           data: param,
           async: true
});

}

function makePostRedir(controller,param){

jQuery.ajax({
           //mode : "queue",
           type: "POST",
           url: controller,
           data: param,
           success: function(msg){

                      var result= new Array();
                      result=msg.split('|');
                      if(result[0]=='ok'){
                      	window.location.href= base_url_no_index + '' +result[1];
                      }else{
                      	alert(result[1]);
                      }
           }
});

}

function makePostJson(controller,param){

var json = jQuery.ajax({
           type: "POST",
           dataType: "json",
           url: controller,
           async: false,
           data: param
		   });

var json = eval('(' + json.responseText + ')');
return json;
}

function doLoad(div){
cont="<center><img src='" + base_url_no_index +"assets/shared/themes/default/images/ajax-loading.gif'></center>";
jQuery(div).html(cont);
}


/*
*FDesc:popola una select con delle opzioni ottenute da un array JSON encodato
*/
function populateSelect(selectid,controller,param){
//selectid is select#pippo or select[@name='tizio']

var obj =makePostJson(controller,param);


var options ='<option value=\'\'></option>';

for (i = 0; i < obj.length; i++) {

options = options + '<option value="' + obj[i].value + '" >' + (obj[i]).text + '</option>';
}

jQuery(selectid).html(options);

jQuery(selectid+" option:eq(0)").attr("selected","selected");

return true;
}



/*
FDesc:disabilita o abilita tutti gli input in un contenitore
*/
function disableInputs(containername,option){
/*containername es:span#pippo*/
jQuery(':input',containername).each(function() {
		if(option)
		{

			jQuery(this).attr("disabled","disabled")
			//in case of validation class remove the class 'errorClass' assigned  from validation function
			jQuery(this).removeClass(VALID_ERROR_CLASS);
		}
		else{jQuery(this).attr("disabled","")};
 	});
}


/*
FDesc:svuota tutti gli input in un contenitore
*/
function emptyInputs(containername){
/*containername es:span#pippo*/
jQuery(':input',containername).each(function() {
		jQuery(this).val('')

 	});
}


/*Fdesc:Valida la form passata per nome

formid="form#formid"
param="action=xxx"
errdiv="div#errors"
*/

function formvalidate(formid,controller,errdiv,successfunc,loadingdiv){

       var v = jQuery(formid).validate({

       errorLabelContainer: jQuery(errdiv),

       //errorElement: "label",

	   focusInvalid: false,
	   errorClass: VALID_ERROR_CLASS,
       submitHandler: function(form) {

       if(loadingdiv.length!=0) doLoad(loadingdiv);
       jQuery(form).ajaxSubmit({
       url: controller,
	   type : 'POST',
	   //beforeSubmit: alert(controller),
	   //target : '',
 	   success: function(responseText) {
 	                                if(successfunc.length > 0)
 	                                {

 	                                	var fn= eval(successfunc);
										fn(responseText,loadingdiv);
									}
								}

       	 				});
				}
		});
		//prevent the form submission
		/*jQuery(formid).submit(function() {
			return false;
		});*/

}


/*showResponse:usata per testare la validation
*
*/
function showResponse(responseText, statusText)  {
    // for normal html responses, the first argument to the success callback
    // is the XMLHttpRequest object's responseText property

    // if the ajaxForm method was passed an Options Object with the dataType
    // property set to 'xml' then the first argument to the success callback
    // is the XMLHttpRequest object's responseXML property

    // if the ajaxForm method was passed an Options Object with the dataType
    // property set to 'json' then the first argument to the success callback
    // is the json data object returned by the server

    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
        '\n\nThe output div should have already been updated with the responseText.');
}



/*Fdesc:fa il redirect a partire da una risposta
answrtype= 'ok!page.php'
*/
function redirAns(msg){

	var result= new Array();
	result=msg.split('|');
	if(result[0]=='ok'){
		linklocation = (base_url_no_index) ? '' + base_url_no_index + result[1] + '' : '' + result[1] + '';
		window.location.href= result[1];
	}else{
		if(result[0] == 'error')
		alert(result[1]);
	}
	//potrei mettere anche un alert con jqmodal

}




/*Fdesc: cancella una form
answrtype= cancella la form
*/
function clearForm(form) {
 // iterate over all of the inputs for the form
 // element that was passed in
jQuery(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase();
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};

/*Fdesc: resetta i campi di unput in un contenitore
answrtype= no answer
*/
function clearFields(container) {
 // iterate over all of the inputs for the form
 // element that was passed in
jQuery(':input', container).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase();
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = 0;
});
};


/*Fdesc: copia il contenuto dei campi input text select di un contenitore  in un altro corrispondente
answrtype= cancella la form(da rivedere)
*/
function copyFields(containerfrom,containerto) {
 // iterate over all of the inputs for the form
 // element that was passed in
	jQuery(':input', containerfrom).each(function() {
	var name = jQuery(this).attr('name');
	var value = jQuery(this).val();
	var type = this.type;
	var tag = this.tagName.toLowerCase();
	// it's ok to reset the value attr of text inputs,
	// password inputs, and textareas
	if (type == 'text' || type == 'password' || tag == 'textarea'){
	jQuery(containerto+' input[@name='+name+']').val(value);
	}
	else if(type == 'checkbox' || type == 'radio') {
		if(jQuery(this).is(':selected')){
		jQuery(containerto+' input[@name='+name+']').attr('selected','selected');
		}else{
		jQuery(containerto+' input[@name='+name+']').attr('selected','');
		}
	}
	// select elements need to have their 'selectedIndex' property set to -1
	// (this works for both single and multiple select elements)
	else if (tag == 'select'){
	jQuery(containerto+' select[@name='+name+'] option[@value='+value+']').attr('selected','selected');
	}
	});
};


/*Fdesc: copia il contenuto dei campi input text select di un contenitore  in un altro corrispondente
answrtype= cancella la form(splitta il nome all_ e ricerca la secoda parte nel nome
*/

function copyFieldsEreg(containerfrom,containerto) {
 // iterate over all of the inputs for the form
 // element that was passed in
	jQuery(':input', containerfrom).each(function() {
	var name = jQuery(this).attr('name');
	var temp ='';
	var temp = name.split('_');
	name= temp[1];
	var value = jQuery(this).val();
	var type = this.type;
	var tag = this.tagName.toLowerCase();
	var disabled=0;

	if(jQuery(this).is(':disabled')){
	disabled=1;
	}

	// it's ok to reset the value attr of text inputs,
	// password inputs, and textareas
	if (type == 'text' || type == 'password' || tag == 'textarea'){

	if(disabled == 1){jQuery(containerto+' input[@name$='+name+']').attr('disabled','disabled');}
	else{jQuery(containerto+' input[@name$='+name+']').attr('disabled','');}

	jQuery(containerto+' input[@name$='+name+']').val(value);
	}
	else if(type == 'checkbox' || type == 'radio') {
	    if(disabled == 1){jQuery(containerto+' input[@name$='+name+']').attr('disabled','disabled');}
		else{jQuery(containerto+' input[@name$='+name+']').attr('disabled','');}

		if(jQuery(this).is(':checked')){
		jQuery(containerto+' input[@name$='+name+'][@value='+value+']').attr('checked','checked');
		}else{
		jQuery(containerto+' input[@name$='+name+'][@value='+value+']').attr('checked','');
		}
	}

	// select elements need to have their 'selectedIndex' property set to -1
	// (this works for both single and multiple select elements)
	else if (tag == 'select'){
	if(disabled == 1){jQuery(containerto+' select[@name$='+name+']').attr('disabled','disabled');}
	else{jQuery(containerto+' select[@name$='+name+']').attr('disabled','');}

	jQuery(containerto+' select[@name$='+name+'] option[@value='+value+']').attr('selected','selected');
	}
	});
};


/*Fdesc: expande un contenitore dove obj= riferimento al link,container : contenitore da espandere/chiudere
*/
function toggleExpand(obj,container)
{
	jQuery(container).toggle();
	jQuery(obj).toggleClass("active");
}

/*Fdesc: Binda il al keypress dell'enter in un input il submit della form
*/
function bindSubmit(formid,time)
{
	jQuery('input',formid).bind('keydown',function(e){

		evt = (e) ? e : event;
	    var target = (evt.target) ? evt.target : evt.srcElement;
	    var form = target.form;
	    var charCode = (evt.charCode) ? evt.charCode :
	        ((evt.which) ? evt.which : evt.keyCode);
	    if (charCode == 13)
	    {
			evt.preventDefault();
			if(formsend == false)
			{
				formsend = true;
				//resetta il formsend

				form.submit();
				setTimeout(function(){
					formsend = false;
				},time);

			}
			return false;

	    }
	    return true;
	});
}

/*Fdesc: binda il submit della form(non ajax submit),su un href posso comunque utilizzarlo anche per le richieste ajax con le opportune modifiche
es: <a href ="javascript:void(0);" onclick="vai(this);">Invia</a> attento a IE6
oppure <input type="button"  onclick="vai(this);" value="Invia">
*/
function vai(elem,form_name)
{
	jQuery('form').submit();
	elem.disabled = true;
	if(!formsend)
	{
		formsend = true;
		//resetta il formsend

		setTimeout(function(){
			formsend = false;
			elem.disabled = false;
		},3000);


		jQuery('form[name='+form_name+']').submit();
		jQuery(elem).blur();
		return true;
	}
	jQuery(elem).blur();
	return false;
}


function in_array_js(string, array) {
	for(var i=0; i<array.length; i++) {
	if (array[i] == string) return true;
	}
	return false;
}
