// oggetto di verifica stato
var readyState = {
 INATTIVO:       0,
 INIZIALIZZATO:  1,
 RICHIESTA:      2,
 RISPOSTA:       3,
 COMPLETATO:     4
};

// array descrittivo dei codici restituiti dal server
var statusText = new Array();
 statusText[100] = "Continue";
 statusText[101] = "Switching Protocols";
 statusText[200] = "OK";
 statusText[201] = "Created";
 statusText[202] = "Accepted";
 statusText[203] = "Non-Authoritative Information";
 statusText[204] = "No Content";
 statusText[205] = "Reset Content";
 statusText[206] = "Partial Content";
 statusText[300] = "Multiple Choices";
 statusText[301] = "Moved Permanently";
 statusText[302] = "Found";
 statusText[303] = "See Other";
 statusText[304] = "Not Modified";
 statusText[305] = "Use Proxy";
 statusText[306] = "(unused, but reserved)";
 statusText[307] = "Temporary Redirect";
 statusText[400] = "Bad Request";
 statusText[401] = "Unauthorized";
 statusText[402] = "Payment Required";
 statusText[403] = "Forbidden";
 statusText[404] = "Not Found";
 statusText[405] = "Method Not Allowed";
 statusText[406] = "Not Acceptable";
 statusText[407] = "Proxy Authentication Required";
 statusText[408] = "Request Timeout";
 statusText[409] = "Conflict";
 statusText[410] = "Gone";
 statusText[411] = "Length Required";
 statusText[412] = "Precondition Failed";
 statusText[413] = "Request Entity Too Large";
 statusText[414] = "Request-URI Too Long";
 statusText[415] = "Unsupported Media Type";
 statusText[416] = "Requested Range Not Satisfiable";
 statusText[417] = "Expectation Failed";
 statusText[500] = "Internal Server Error";
 statusText[501] = "Not Implemented";
 statusText[502] = "Bad Gateway";
 statusText[503] = "Service Unavailable";
 statusText[504] = "Gateway Timeout";
 statusText[505] = "HTTP Version Not Supported";
 statusText[509] = "Bandwidth Limit Exceeded";


// funzione per prendere un elemento con id univoco
function prendiElementoDaId(id_elemento) {
 var elemento;
 if(document.getElementById)
  elemento = document.getElementById(id_elemento);
 else
  elemento = document.all[id_elemento];
 return elemento;
};

// funzione per assegnare un oggetto XMLHttpRequest
function assegnaXMLHttpRequest() {
 var XHR = null, browserUtente = navigator.userAgent.toUpperCase();
 if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object")
  XHR = new XMLHttpRequest();
 else if(window.ActiveXObject && browserUtente.indexOf("MSIE 4") < 0) {
  if(browserUtente.indexOf("MSIE 5") < 0)
   XHR = new ActiveXObject("Msxml2.XMLHTTP");
  else
   XHR = new ActiveXObject("Microsoft.XMLHTTP");
 }
 return XHR;
};

function check_scrolled_textarea(id, callback) {
 var elemento = prendiElementoDaId(id);
 if ((elemento.scrollTop + elemento.scrollHeight + 10) > elemento.offsetHeight) {
  callback;
 }
}

function active_checkbox(id) {
 var elemento = prendiElementoDaId(id);
 if (elemento.disabled == true)
	elemento.disabled = false;
}

function ajax_getcontent(url, val, id, preload) {
 var ajax = assegnaXMLHttpRequest();
 var elemento = prendiElementoDaId(id);
 if (preload)
  elemento.innerHTML = preload;
 if(ajax) {
  ajax.open("POST", (url), true);
  ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  ajax.setRequestHeader("connection", "close");

  ajax.onreadystatechange = function() {
   if(ajax.readyState === readyState.COMPLETATO) {
    ajax = assegnaXMLHttpRequest();
   }
  }
  ajax.send(val);
  ajax.onreadystatechange = function() {
   if(ajax.readyState === 4) {
    if(ajax.status == 200) {
     elemento.innerHTML = ajax.responseText;
    }
   }
  }
 }
 else
  alert('Error! Browser not supported!');
}

function ajax_user_exist(val, module, other) {
 var elemento = prendiElementoDaId(module);
 var ajax = assegnaXMLHttpRequest();
 if(ajax) {
  ajax.open("POST", ('/static/ajax/check_user.php'), true);
  ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  ajax.setRequestHeader("connection", "close");

  ajax.onreadystatechange = function() {
   if(ajax.readyState === readyState.COMPLETATO) {
    ajax = assegnaXMLHttpRequest();
   }
  }
  if (other) {
   ajax.send('user='+escape(val.value)+'&module='+escape(module)+"&other="+escape(other));
  } else {
  	ajax.send('user='+escape(val.value)+'&module='+escape(module));
  }
  ajax.onreadystatechange = function() {
   if(ajax.readyState === 4) {
    if(ajax.status == 200) {
     if (ajax.responseText.indexOf('FALSE') < 0) {
	  if (val.name) {
	   elemento[val.name].value = '';
	   elemento[val.name].focus();
	   elemento[val.name].select();
     }
     alert(ajax.responseText);
     }
    }
   }
  }
 }
 else
  alert('Error! Browser not supported!');
}

function ajax_user_exist_newclient(val, module, other) {
 var elemento = prendiElementoDaId(module);
 var ajax = assegnaXMLHttpRequest();
 if(ajax) {
  ajax.open("POST", ('/static/ajax/check_user.php'), true);
  ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  ajax.setRequestHeader("connection", "close");

  ajax.onreadystatechange = function() {
   if(ajax.readyState === readyState.COMPLETATO) {
    ajax = assegnaXMLHttpRequest();
   }
  }
  if (other) {
   ajax.send('user='+escape(val.value)+'&module='+escape(module)+"&other="+escape(other));
  } else {
  	ajax.send('user='+escape(val.value)+'&module='+escape(module));
  }
  ajax.onreadystatechange = function() {
   if(ajax.readyState === 4) {
    if(ajax.status == 200) {
     if (ajax.responseText.indexOf('FALSE') < 0) {
     
     	 prendiElementoDaId('newclient_search').style.display = 'none';
		 prendiElementoDaId('newclient').style.display = 'block';
		 prendiElementoDaId('newclientregistration').style.display = 'none';
		 prendiElementoDaId('isolduser').value = 'true';
		 newclient_reg = oldclient;
		 
     } else {
     	 
     	 prendiElementoDaId('newclient_search').style.display = 'none';
     	 prendiElementoDaId('newclient').style.display = 'block';
     	 newclient_reg = newclient;
     
     }
    }
   }
  }
 }
 else
  alert('Error! Browser not supported!');
}

function ajax_sim_exist(val, module) {
 var elemento = prendiElementoDaId(module);
 var ajax = assegnaXMLHttpRequest();
 if(ajax) {
  ajax.open("POST", ('/static/ajax/check_sim.php'), true);
  ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  ajax.setRequestHeader("connection", "close");

  ajax.onreadystatechange = function() {
   if(ajax.readyState === readyState.COMPLETATO) {
    ajax = assegnaXMLHttpRequest();
   }
  }
  ajax.send('sim='+escape(val.value)+'&module='+escape(module));
  ajax.onreadystatechange = function() {
   if(ajax.readyState === 4) {
    if(ajax.status == 200) {
     if (ajax.responseText.indexOf('FALSE') < 0) {
	  elemento[val.name].value = '';
	  elemento[val.name].focus();
	  elemento[val.name].select();
      alert(ajax.responseText);
     }
    }
   }
  }
 }
 else
  alert('Error! Browser not supported!');
}

function check_form(fid, did, array, tosubmit) {
 var fname = prendiElementoDaId(fid);
 var dname = prendiElementoDaId(did);
 var regular = null;
 var i = 0;
 var radiocheck = false;
 var errors = '';
 for ( keyVar in array ) {
  if (fname[keyVar].value == 'N/A')
  	fname[keyVar].value = '';
  regular = new RegExp(array[keyVar]);
  if (keyVar == 'cc_id') {
   if (fname[keyVar].length > 0) {
  	 for (var b=0; b<fname[keyVar].length; b++) {
  	  if (fname[keyVar][b].checked) {
		radiocheck = true;
   	break;
     }
    }
  	 if ((radiocheck && !regular.test(fname[keyVar][b].value)) || !radiocheck) {
     errors += keyVar+',';
     i++;	
    }
  	} else {
  	 if (fname[keyVar].checked)
  	  radiocheck = true;
  	}
   if (!radiocheck) {
	 errors += keyVar+',';
    i++;
	} 
  } else {
   if (!regular.test(fname[keyVar].value)) {
	 if (fid == 'register' && (keyVar == 'pass_1' || keyVar == 'pass_2') && fname[keyVar].value == '')
	  continue;
    errors += keyVar+',';
    i++;	
   }
  }
 }
 
 if (fid == 'register') {
  if (fname['company'].value != '' && fname['code_vat'].value == '')
  //if (fname['business_name'].value != '' && fname['code_vat'].value == '')
  {
   errors += 'company_vat,';
   i++;
  }
  if (fname['business_name'].value == '' && fname['code_vat'].value != '')
  {
   errors += 'company_bus_name,';
   i++;
  }
  if (fname['company'].value == '' && fname['code_cf'].value == '') {
  //if (fname['business_name'].value == '' && fname['code_cf'].value == '') {
   errors += 'not_company_cf,';
   i++;
  }
 if (fname['code_cf'].value != '' && fname['code_vat'].value != '') {
   errors += 'cf_vat,';
   i++;
  }
  if (fname['pass_1'].value != fname['pass_2'].value) {
   errors += 'password_confirm,';
   i++;
  }
 }
 
 if (fid == 'register_user') {	
	  if (fname['business_name'].value != '' && fname['code_vat'].value == '')
	  {
	   errors += 'company_vat,';
	   i++;
	  }
	  if (fname['business_name'].value == '' && fname['code_vat'].value != '')
	  {
	   errors += 'company_bus_name,';
	   i++;
	  }
	  if (fname['business_name'].value == '' && fname['code_cf'].value == '') {
	   errors += 'not_company_cf,';
	   i++;
	  }
 }	 
  
 if (fid == 'alpitour_form') {
  //if (fname['pagamento'][0].checked == false && fname['pagamento'][1].checked == false && fname['pagamento'][2].checked == false)  
  //{
  // errors += 'spedizione,';
  // i++;
  //} 
 }
 
 if (tosubmit != false)
  tosubmit = true;
 
 if (i > 0) {

  ajax_getcontent('/static/ajax/check_form.php', 'module='+escape(fid)+'&errors='+escape(errors), did);
  dname.style.display = 'block';
  location.href='#errortop';
  return false;
  
 } else {

  dname.style.display = 'none';
  if (tosubmit)
   fname.submit();

  return true;
 }
}

function ecommerce_tabs(tabname) {
 for (var i=0; i<tabs.length; i++) {
  var element = prendiElementoDaId(tabs[i]);
  var element2 = prendiElementoDaId('a'+tabs[i]);
  
  if (element) {
   if (tabname != tabs[i]) {
  	 element.style.display = 'none';
  	 element2.className = '';
   } else {
  	 element.style.display = 'block';
  	 element2.className = 'active';
   }
  }
 }
}


function ecommerce_quantity(cur, max, msg) {
 if (cur > max) {
  alert(msg);
  return true;
 }
 return false;
}

function array_merge(array1, array2) {
 var areturn = new Array();
 for ( keyVar in array1 )
  areturn[keyVar] = array1[keyVar];
 for ( keyVar in array2 )
  areturn[keyVar] = array2[keyVar];

 return areturn;
}

function ajax_check_rates_plan_type(msisdn) {
	$.ajax({
	  type: 'POST',
	  url: "/static/ajax/get_sim_data.php",
	  data: { "msisdn": msisdn, "type": "ratesplan" },
	  cache: false,
	  success: function(data){				    
			if (data.error != 1) return count_recharge_values(data.user_type);
			else return count_recharge_values(false);
		   },      
	  dataType: "json"
	});
}

function count_recharge_values(user_type) {	
	if (user_type)
	{
		amt = $('#amount').val();
		switch(user_type) 
		{
			case 'privati':
				$('#amount_vat').html('0 &euro;');
				$('#amount_tot').html(amt+' &euro;'); 
				break;
			case 'business':
				amt_vat = roundTo(amt * 0.2, 2); 
				amt_tot = amt * 1 + amt_vat * 1;
				$('#amount_vat').html(amt_vat+' &euro;');
				$('#amount_tot').html(amt_tot+' &euro;');
				break;			
			default:
				break;
		}
	}		
}

/**
 * Math.round of value with decimalpositions decimal
 */
function roundTo(value, decimalpositions) {
	var i = value * Math.pow(10,decimalpositions);
    i = Math.round(i);
    return i / Math.pow(10,decimalpositions);
}

/**
 * Load available free sims by rates plan id
 * @param rate plan id
 */
function ajax_load_available_msisdn_by_rates_plan(plan_id) {
	if (!isNaN(plan_id))
	{
		if (plan_id == -1) jQuery('#simid')[0].options.length = 0;
		else
		{
			jQuery.ajax({
				  type: 'POST',
				  url: "/static/ajax/get_available_sims_by_rates_plan.php",
				  data: { "plan_id": plan_id },
				  cache: false,
				  beforeSend: function() {
					  jQuery('#simid')[0].options.length = 0;
					  jQuery('#simid').append('<option value="-1">Loading...</option>');		  
				  },
				  success: function(data) {					  
					  if (data.error != 1)
							{
						  		jQuery('#simid')[0].options.length = 0;
						  		jQuery.each(data.sims, function(index, value) 
								{ 								 					 
							  		jQuery('#simid').append('<option value="'+value.i+'">'+value.m+' ('+value.p+')</option>');
								});
							}
					  else
						  {
						    alert("Errore nel caricamento della lista delle sim.");
						  }
				  },   
  			      error: function (XMLHttpRequest, textStatus, errorThrown) {  			    	  
  			    	   //alert(XMLHttpRequest.status);
					   //alert(XMLHttpRequest.responseText);
					   //alert(errorThrown);
  			    	  alert("Errore nel formato della lista delle sim.");
				  },
				  dataType: "json"
			});
		}		
	}
}

