
function get_states(prepack_folder, id_country) {
	if(id_country === undefined) id_country = jQuery('#country').val();
	url = prepack_folder + 'combo.php?method=get_states&id_parent=' + id_country;
	jQuery('#state').removeOption(/./);
	jQuery('#state').show();
	jQuery('#state').ajaxAddOption(url, {}, true, setState);
}

function get_cities(prepack_folder, id_state) { 
	if(id_state === undefined) id_state = jQuery('#state').val();
	url = prepack_folder + 'combo.php?method=get_cities&id_parent=' + id_state;
	jQuery('#city').removeOption(/./);
	jQuery('#city').show();
	jQuery('#city').ajaxAddOption(url, {}, true, setCity);	
}

function swPage(p){
	jQuery('#hdn_page').val(p);
	jQuery('#frm').submit(); 
}

function isNumberKey(evt) {
   var charCode = (evt.which) ? evt.which : event.keyCode
   if (charCode > 31 && (charCode < 48 || charCode > 57))
      return false;

   return true;
}

/**
 * 
 * @param string prepack_folder
 * @param string success_text
 * @return void
 */
function js_suscribe(prepack_folder, success_text) {  
	
   var err = false;  
   var sus_name = jQuery('#sus_name').val();  
   var sus_email = jQuery('#sus_email').val();  
   var sus_country = jQuery('#sus_country').val();  
		
   if(sus_name =='' ){  
     var err = true;  
     jQuery('#sus_name').css('background', 'red');  
   } else {  
     var err = false;  
     jQuery('#sus_name').css('background', 'white');  
   }  

   if(sus_email.indexOf('@') < 2 ){  
     var err = true;  
     jQuery('#sus_email').css('background', 'red');  
   } else {  
     var err = false;  
     jQuery('#sus_email').css('background', 'white');  
   }  		

   if(err == false) { 
	   jQuery('#sus_div').fadeOut('slow');  		
	   jQuery.get(prepack_folder + 'suscribe.php?sus_name='+sus_name+'&sus_email='+sus_email+'&sus_country='+sus_country);  
	   jQuery('#sus_div_msg').html('<b>' + success_text + '</b>');  
	   jQuery('#sus_div_msg').fadeIn('slow');  
   }  
} 




function TrimString(sInString) {
  if ( sInString ) {
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
  }
}

//Populates the Property Type selected with the types from the prop types list

/**
 * @param string defaultPropType
 * @param string idPropTypeSel
 * @param string lang
 */
function populatePropType(defaultpType, idpTypeSel, lang) {
	 
  switch( lang ) {
	
	case 'en':
		var pTypeLineArray = prop_type_en.split('|');  // Split into lines	
		break;
	
	case 'en_us':
		var pTypeLineArray = prop_type_en_us.split('|');  // Split into lines	
		break;
	
	case 'en_uk':
		var pTypeLineArray = prop_type_en_uk.split('|');  // Split into lines	
		break;
	
	case 'sp':
		var pTypeLineArray = prop_type_sp.split('|');  // Split into lines	
		break;		
	
	case 'sp_ar':
		var pTypeLineArray = prop_type_sp_ar.split('|');  // Split into lines	
		break;
	
	case 'sp_sp':
		var pTypeLineArray = prop_type_sp_sp.split('|');  // Split into lines	
		break;							
  }
  


  var selObj = document.getElementById(idpTypeSel);
  if(lang == 'sp') {
  	selObj.options[0] = new Option('Indistinto','');
  } else {
  	selObj.options[0] = new Option('All','');
  }
  
  selObj.selectedIndex = 0;
  for (var loop = 0; loop < pTypeLineArray.length; loop++) {
    lineArray = pTypeLineArray[loop].split(':');
    pTypeCode  = TrimString(lineArray[0]);
    pTypeName  = TrimString(lineArray[1]);
    if ( pTypeCode != '' ) {
      selObj.options[loop + 1] = new Option(pTypeName, pTypeCode);
    }
    if ( defaultpType == pTypeCode ) {
      selObj.selectedIndex = loop + 1;
    }
  }
  
}


// Populates the country selected with the counties from the country list

/**
 * @param string defaultCountry
 * @param string id
 * @param string lang
 */
function populateCountry(defaultCountry, idCountrySel, lang) {
 
  var countryLineArray = country.split('|');  // Split into lines
  var selObj = document.getElementById(idCountrySel);
  if(lang == 'sp') {
  	selObj.options[0] = new Option('Indistinto','');
  } else {
  	selObj.options[0] = new Option('All','');
  }
  
  selObj.selectedIndex = 0;
  for (var loop = 0; loop < countryLineArray.length; loop++) {
    lineArray = countryLineArray[loop].split(':');
    countryCode  = TrimString(lineArray[0]);
    countryName  = TrimString(lineArray[1]);
    if ( countryCode != '' ) {
      selObj.options[loop + 1] = new Option(countryName, countryCode);
    }
    if ( defaultCountry == countryCode ) {
      selObj.selectedIndex = loop + 1;
    }
  }
  
}

/**
 * @param string idCountrySel
 * @param string idStateSel
 */
function populateState(idCountrySel, idStateSel, lang, defaultCountry, defaultState) {
  var selObj = document.getElementById(idStateSel);
  selObj.style.display = '';
  var foundState = false;
  // Empty options just in case new drop down is shorter
  if ( selObj.type == 'select-one' ) {
    for (var i = 0; i < selObj.options.length; i++) {
      selObj.options[i] = null;
    }
    selObj.options.length=null;
    if(lang == 'sp') {
    	selObj.options[0] = new Option('Indistinto','');
    } else {
    	selObj.options[0] = new Option('All','');
    }
    selObj.selectedIndex = 0;
  }
  // Populate the drop down with states from the selected country
  var stateLineArray = state.split("|");  // Split into lines
  var optionCntr = 1;
  for (var loop = 0; loop < stateLineArray.length; loop++) {
    lineArray = stateLineArray[loop].split(":");
    countryCode  = TrimString(lineArray[0]);
    stateCode    = TrimString(lineArray[1]);
    stateName    = TrimString(lineArray[2]);
  if (document.getElementById(idCountrySel).value == countryCode && countryCode != '' ) {
      if ( stateCode != '' ) {
        selObj.options[optionCntr] = new Option(stateName, stateCode);
      }
      // See if it's selected from a previous post
      if ( stateCode == defaultState && countryCode == defaultCountry ) {
        selObj.selectedIndex = optionCntr;
      }
      foundState = true;
      optionCntr++;
    }
  }
}

/**
 * @param string idStateSel
 * @param string idCitySel
 */
function populateCity(idStateSel, idCitySel, lang, defaultState, defaultCity) {
  var selObj = document.getElementById(idCitySel);
  selObj.style.display = '';
  var foundCity = false;
  // Empty options just in case new drop down is shorter
  if ( selObj.type == 'select-one' ) {
    for (var i = 0; i < selObj.options.length; i++) {
      selObj.options[i] = null;
    }
    selObj.options.length=null;
    if(lang == 'sp') {
    	selObj.options[0] = new Option('Indistinto','');
    } else {
    	selObj.options[0] = new Option('All','');
    }
    selObj.selectedIndex = 0;
  }
  // Populate the drop down with cities from the selected country
  var cityLineArray = city.split("|");  // Split into lines
  var optionCntr = 1;
  for (var loop = 0; loop < cityLineArray.length; loop++) {
    lineArray = cityLineArray[loop].split(":");
    stateCode  = TrimString(lineArray[0]);
    cityCode    = TrimString(lineArray[1]);
    cityName    = TrimString(lineArray[2]);
  if (document.getElementById(idStateSel).value == stateCode && stateCode != '' ) {
      if ( cityCode != '' ) {
        selObj.options[optionCntr] = new Option(cityName, cityCode);
      }
      // See if it's selected from a previous post
      if ( cityCode == defaultCity && stateCode == defaultState ) {
        selObj.selectedIndex = optionCntr;
      }
      foundCity = true;
      optionCntr++;
    }
  }
}

function set_post_uri( base_url, lang ){
	
	//Gets the data from the form
	property_type = jQuery('#id_property_type').selectedTexts();
	operation_type = jQuery('#operation_type').selectedTexts();
	country = jQuery('#country').selectedTexts();
	state = jQuery('#state').selectedTexts();
	city = jQuery('#city').selectedTexts();
	bedrooms = jQuery('#bedrooms option:selected').val();
	code_currency = jQuery('#code_currency').selectedValues();
	amount_from = jQuery('#amount_from').val();
	amount_to = jQuery('#amount_to').val();
	surface = jQuery('#surface').val();
	surface_unit = jQuery('#code_surface').selectedValues();

	
	
	//Replace posible spaces with "_" underscores.
	property_type = property_type[0].replace(/\s+/g, "_");
	country = country[0].replace(/\s+/g, "_");
	state = state[0].replace(/\s+/g, "_");
	state = state.replace(/\-+/g, "_");
	city = city[0].replace(/\s/g, "_");
	city = city.replace(/\-+/g, "_");
	

	
	//Builds each parameter and filters the default ones
	if ( lang == 'sp' ) {
		search_term = 'buscar' + '-';
	} else {
		search_term = 'search' + '-';
	}
	
	if (property_type != 'All' && property_type != 'Indistinto'){
		property_type = clean_special_chars(property_type);
		property_type = property_type + '-';
	} else {
		property_type = '';
	}
	
	if (operation_type != 'All' && operation_type != 'Indistinto'){
		operation_type = operation_type + '-';
	} else {
		operation_type = '';
	}
	
	if (country != 'All' && country != 'Indistinto'){
		country = clean_special_chars(country);
		country = country + '-';
	} else {
		country = '';
	}
	
	if (state != 'All' && state != 'Indistinto'){
		state = clean_special_chars(state);
		state = state + '-';
	} else {
		state = '';
	}
	
	if (city != 'All' && city != 'Indistinto'){
		city = clean_special_chars(city);
		city = city + '-';
	} else {
		city = '';
	}
	
	if (bedrooms != 0){
		if ( lang == 'sp' ){
			bedrooms = bedrooms + '_dormitorios-';
		} else {
			bedrooms = bedrooms + '_bedrooms-';
		}
	} else {
		bedrooms = '';
	}
	
	if (amount_from != ''){
		amount_from = code_currency + '_' + amount_from + '-';
	} else {
		amount_from = '';
	}
	
	if (amount_to != ''){
		amount_to = code_currency + '_' + amount_to + '-';

		if (amount_from == ''){
			amount_from = code_currency + '_1-';
		}
		
	} else {
		amount_to = '';
	}
	
	if (surface != ''){
		surface = surface + '_' + surface_unit;
	} else {
		surface = '';
	}
	
	//Builds the uri string
	search_uri = search_term + 	property_type + 
								operation_type + 
								country + 
								state + 
								city + 
								bedrooms + 
								amount_from + 
								amount_to + 
								surface;
	
	//it trims a trail slash if any
	var trail_slash = search_uri.substring((search_uri.length -1), search_uri.length);

	if (trail_slash == '-'){
		search_uri = search_uri.slice (0, -1);
	}
	

	//Builds the whole url
	search_url = base_url + search_uri.toLowerCase();
	jQuery('#frm').attr( 'action', search_url );
	jQuery('#frm').submit();
	
}

//TODO create a method to clean special chars from the built uri.
function clean_special_chars(string){
	
	
	var r=string.toLowerCase();

    r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
    r = r.replace(new RegExp("æ", 'g'),"ae");
    r = r.replace(new RegExp("ç", 'g'),"c");
    r = r.replace(new RegExp("[èéêë]", 'g'),"e");
    r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
    r = r.replace(new RegExp("ñ", 'g'),"n");                            
    r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
    r = r.replace(new RegExp("œ", 'g'),"oe");
    r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
    r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
    r = r.replace(new RegExp("[\']", 'g'),"_");
    r = r.replace(new RegExp("[\`]", 'g'),"_");
    r = r.replace(new RegExp("[\´]", 'g'),"_");
    r = r.replace(new RegExp("\\W", 'g'),"");

    
    return r;


	
	//return string;
	
}



