/**
 * Auto-completes the area code included in telephone/fax related 
 * registration/profile fields, according to selected country.
 * <p>Executed only when javascript enabled and each time the value of the
 * selected country changes, so that to ease the registration/edit profile process.
 * <p>Fields to be auto-completed are the ones with ids matching 'phone' or 'fax'.
 * <p>The auto-completion of these fields is implemented in the following way:
 * If fields are empty, they take the value of area code, followed by a hyphen.
 * Else, if there is already a phone number (without a hyphen), it is preceded by
 * the area code and a hyphen.
 * Else, the number before the hyphen is substituted by the current area code.
 * @author mi
 */
	
var topologySelect = Seam.Component.getInstance("topologySelect");
    
function alterAreaCode(value) {
	topologySelect.getCodeForTopology(value,alterAreaCodeCallback);    
}
    
function alterAreaCodeCallback(result) {
	var form_id = 'profile_form' ;
	for(var index=0;index<=document.getElementById(form_id).elements.length-1;index=index+1) {
		var el = document.forms[form_id].elements[index];
		if((el.id.match('phone')) || (el.id.match('fax') ) ){
			el.value=result+'-'+el.value.substr(el.value.indexOf('-')+1);
		}
	}
}

function triggerAlterAreaCode(element, event) {
	var keycode; 
 	if (window.event) {
 		keycode = window.event.keyCode; 
 	} else if (event) {
 		keycode = event.which; 
	} 
	if (keycode == 13) {
		alterAreaCode(element.value);
	} 
}

window.onload = alterAreaCode(document.getElementById('Country').value);
