jQuery.noConflict();
var map;
var civico = null;
var geoCodForm = null;
var point = null;

jQuery(document).ready(function(){
	
	if (jQuery('#activation_type').attr("value") == "1"){
		jQuery("#softwareCode").hide();
		jQuery("#haveSoftwareCode").text("Ho un codice software");
	}
  
  jQuery("#haveSoftwareCode").click(function(){

    jQuery("#softwareCode").toggle("fade");
    if ( jQuery('#activation_type').attr("value") == '1'){
	  jQuery("#haveSoftwareCode").text("Non ho un codice software");
	  jQuery('#activation_type').attr({value: '2'});
    }
    else{
	  jQuery('#activation_type').attr({value: '1'});
	  jQuery("#haveSoftwareCode").text("Ho un codice software");
    }
  });
	var msgColor = [
					{param:"background-color",fromColor:"white",toColor:"#F6D040",duration:1000},
					{param:"color",random:true}
					];
		jQuery(".message").colorBlend(msgColor);
		//jQuery(".message").Highlight(1500, '#FFF');
	
});
/*
 * autoFieldAdvance
 */
var globalKeyCode, afaCurrentField, afaNextField, afaPrevField, afaFieldLength;
var BACKSPACE_KEY = 8;
var TAB_KEY = 9;
var BACK_TAB_KEY = 16;

function autoFieldAdvance( currentField, nextFieldId, prevFieldId ) {
    afaCurrentField = currentField;
    afaFieldLength = currentField.value.length;
    if(nextFieldId!=null)
        afaNextField = document.getElementById(nextFieldId);
    else
        afaNextField = null;
    if(prevFieldId!=null)
        afaPrevField = document.getElementById(prevFieldId);
    else
        afaPrevField = null;

    if ( ( globalKeyCode != TAB_KEY ) && ( globalKeyCode != BACK_TAB_KEY )) {
        document.getElementsByTagName("form")[0].focus();
        setTimeout( 'checkFieldLength()', 1 );
    }
}

function checkFieldLength() {
    if (afaFieldLength==0 && globalKeyCode==BACKSPACE_KEY && afaPrevField!=null) {
        afaPrevField.focus();
        afaPrevField.value = afaPrevField.value; 
    } else if (afaCurrentField.value.length==afaCurrentField.maxLength && afaNextField!=null ) {
		//var valid = validateHardwareCodeChar(afaCurrentField)
		//if ( valid ){
			afaNextField.focus();
	        afaNextField.select();
		//}
    } else {
        afaCurrentField.focus();
    }
}


function catchGlobalKeyStroke( e ) {
    globalKeyCode  = e.keyCode;
}

function validateRegex(element, regex, callback) {
	var v = (regex.test(element.value));
	//var v = (element.value.match(regex));
	callback(v);
	return v;
}
function validateLength(element, minLength, callback) {
	var v = element.value.length>=minLength;
	callback(v);
	return v;
}
function validateHardwareCode(form){
	var valid = true;
	for (var i=1; i<=26; i++){
 		valid = valid && validateHardwareCodeChar(form['hardware_code_' + i]);
	}
	
	return valid;
}

function validateSoftwareCode(form){
	var valid = true;
	for (var i=1; i<=23; i++){
 		valid = valid && validateSoftwareCodeChar(form['software_code_' + i]);
	}
	
	return valid;
}

function validateActivation(form){
	var valid =  true;
	
	if ( form['activation_type'] == '1' ){
		var validHardware = validateHardwareCode(form);
		valid = validHardware;
	}
	else if(form['activation_type'] == '2'){
		var validHardware = validateHardwareCode(form);
		var validSoftware = validateSoftwareCode(form);
		valid = validSoftware && validHardware;
	}
	
	
	return valid;
}
function validateRequest(form){
	
	
	var vFirstName = validateLength(form['property_firstName'],1,function(result){
		if(!result){
			showError("property_firstName_bubble", "Il nome &egrave; obbligatorio");
		}
		else{
			hideError("hardwareCodeError");
		}
	});
	
	var vLastName = validateLength(form['property_lastName'],1,function(result){
		if(!result){
			showError("property_lastName_bubble", "Il cognome &egrave; obbligatorio");
		}
		else{
			hideError("property_lastName_bubble");
		}
	});
	
	/*
	var vPhoneNumber = validateLength(form['property_phoneNumber'],1,function(result){
		if(!result){
			showError("property_phoneNumber_bubble", "Il telefono &egrave; obbligatorio");
		}
		else{
			hideError("property_phoneNumber_bubble");
		}
	});
	*/
	var vAddress = validateLength(form['property_address'],1,function(result){
		if(!result){
			showError("property_address_bubble", "L'indirizzo &egrave; obbligatorio");
		}
		else{
			hideError("property_address_bubble");
		}
	});
	
	var vCity = validateLength(form['property_city'],1,function(result){
		if(!result){
			showError("property_city_bubble", "La citt&agrave; &egrave; obbligatoria");
		}
		else{
			hideError("property_city_bubble");
		}
	});
	
	var vProvince = validateLength(form['property_province'],1,function(result){
		if(!result){
			showError("property_province_bubble", "La provincia &egrave; obbligatoria");
		}
		else{
			hideError("property_province_bubble");
		}
	});
	
	var vZipCode = validateLength(form['property_zipCode'],1,function(result){
		if(!result){
			showError("property_zipCode_bubble", "Il CAP &egrave; obbligatorio");
		}
		else{
			hideError("property_zipCode_bubble");
		}
	});
	
	if (vFirstName && vLastName && vAddress && vCity && vProvince && vZipCode){
		return true;
	}
	else{
		return false;
	}
	
}

function validateHardwareCodeChar(input){
	var valid = validateLength(input, 1, function(result){
		if(!result){
			showError("hardwareCodeError", "L' Hardware Code pu&ograve; contenere solo lettere e  numeri");
			input.value="";
			input.focus();
		}
		else{
			hideError("hardwareCodeError");
		}
	});
	
	valid = valid && validateRegex(input, /[A-Za-z0-9]/, function(result){
		if (!result){
			showError("hardwareCodeError", "L' Hardware Code pu&ograve; contenere solo lettere e  numeri");
		}
		else{
			hideError("hardwareCodeError");
		}
	});
	
	return valid;
}

function validateSoftwareCodeChar(input){
	var valid = validateLength(input, 1, function(result){
		if(!result){
			showError("softwareCodeError", "Il software Code pu&ograve; contenere solo lettere e  numeri");
		}
		else{
			hideError("softwareCodeError");
		}
	});
	
	valid = valid && validateRegex(input, /[A-Za-z0-9]/, function(result){
		if (!result){
			showError("softwareCodeError", "Il software Code pu&ograve; contenere solo lettere e  numeri");
			input.value="";
			input.focus();
		}
		else{
			hideError("softwareCodeError");
		}
	});
	
	return valid;
}

function showError(input, error)
{
	jQuery("#" + input).html(error);
}
function hideError(input){
	jQuery("#" + input).html("");
}

function displayElement(element){
	jQuery("#" + element).css({display: 'block'});
}

function geoCode(formName, input) {
	geoCodForm = document.forms[formName];
	var items = input.value.split(",");
	var comune = null;
	var indirizzo = null;
	civico = null;
	geoCodForm.elements['auth_property_longitude'].value = "";
	geoCodForm.elements['auth_property_latitude'].value = "";
	hideError("address_error");
	if(items.length==1) {
		comune = items[0];
	} else if (items.length==2) {
		comune = items[1];
		sep = items[0].lastIndexOf(' ');
		if(sep>0) {
			civico = items[0].substring(sep+1);
			if(isNaN(parseInt(civico))) {
				civico = null;
				indirizzo = items[0];
			} else {
				indirizzo = items[0].substring(0,sep);
			}
		} else {
			indirizzo = items[0];
		}
	} else {
		showError("address_error", "Indirizzo errato");
		return;
	}
		
  	new PGGeoCod({regione:      null,
                  provincia:    null,
                  comune:       comune,
                  indirizzo:    indirizzo,
                  civico:       civico,
                  cap:          null,
                  onComplete:   'afterGeoCod'});
}

function afterGeoCod(pgAddress) {
  if (pgAddress.ret == '0' || pgAddress.ret == '5') {
  	var fullName = geoCodForm.elements['auth_property_firstName'].value;
		//XXX commento la parte del marker della mappa
  	//point = new PGPoint({ pgAddress:pgAddress,
  							  //html: '<div style="background: transparent url(/static/common/img/icoCliente.png) no-repeat scroll left top; text-align: center; width: 70px; height: 31px; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;"><span style="padding: 8px 0px 0px; text-align: center; color: rgb(0,0,0); font-size: 8px; text-decoration: none; font-family: arial,verdana; display: block; width: 70px; height: 31px; position: relative; z-index: 251;" title="">'+fullName+'</span></div>'});
    //map.removeAllPoints();
    //map.setCenterPoint(point);
  	//map.pointAdder(point);
  	setValue(geoCodForm,'auth_property_dug',pgAddress.comuneList[0].dug);
  	setValue(geoCodForm,'auth_property_street',pgAddress.comuneList[0].ndTopo);
  	setValue(geoCodForm,'auth_property_streetNumber',civico==null?"":civico);
  	setValue(geoCodForm,'auth_property_city',pgAddress.comuneList[0].com);
  	setValue(geoCodForm,'auth_property_province',pgAddress.comuneList[0].prov);
  	setValue(geoCodForm,'auth_property_zipCode',pgAddress.comuneList[0].cap);
  	setValue(geoCodForm,'auth_property_longitude',pgAddress.comuneList[0].lon);
  	setValue(geoCodForm,'auth_property_latitude',pgAddress.comuneList[0].lat);
  	if(!isUndefined(pgAddress.comuneList[0].ndTopo)) {
	  	var address = geoCodForm.elements['address'];
	    address.value = pgAddress.comuneList[0].dug+" "+pgAddress.comuneList[0].ndTopo+(civico==null?"":" "+civico)+", "+pgAddress.comuneList[0].com;
	}
  } else if (pgAddress.ret == '2') {
  	var select = geoCodForm.elements['alternative'];
  	select.options.length = 0;
	
  	select.options[0] = new Option('Forse cercavi','Forse cercavi');
  	
    for (var i=0; i<pgAddress.addressList.length; i++) {
    	select.options[i+1] = new Option(pgAddress.addressList[i].toponimo,pgAddress.addressList[i].toponimo);
    }
    displayElement('forsecercavi','block');
  } else if (pgAddress.ret == '3') {
    showError("address", "Indirizzo errato");
  } else if (pgAddress.ret == '10') {
  	var select = geoCodForm.elements['alternative'];
  	select.options.length = 0;
  	
  	select.options[0] = new Option('Forse cercavi','Forse cercavi');
  	
    for (var i=0; i<pgAddress.comuneList.length; i++) {
    	select.options[i+1] = new Option(pgAddress.comuneList[i].com,pgAddress.comuneList[i].com);
    }
    displayElement('forsecercavi','block');
  } else {
  	showError("address", "Indirizzo errato");
  }
}

function chooseAddress(select) {
	var address = geoCodForm.elements['address'];
	var items = address.value.split(",");
	address.value = select.options[select.selectedIndex].value+","+items[1];
	displayElement('forsecercavi','none');
	geoCode(geoCodForm.name, address);
}

function initMap() {
	map = new PGMappy({nameContainer: 'mapcontainer', mapWidth: 320, mapHeight: 100, tmLnk:0});
}


