var emptyString = /^\s*$/


function checkKeyValue (field_id, keyword) {

  var fld_id = document.getElementById(field_id);
  if (fld_id.value ==  keyword ) fld_id.value = '';

}

function resetKeyValue (field_id, keyword) {

  var fld_id = document.getElementById(field_id);
  if (fld_id.value ==  '' ) fld_id.value = keyword;
}
function emptyComboBox(comboboxid) {
  var combo_obj = document.getElementById(comboboxid);
  if(combo_obj.options) {
  var combo_len =  combo_obj.options.length;
        if (combo_len > 0 ) {
            for (j=(combo_len-1); j>=0;j--) {
                combo_obj.remove(j);
            }
        }
  }
}
function getStates(country_id, states_control , selected_state){

    //Ajax
    var request = new Request.JSON({
      'method' : 'post',
      'url' : 'country_state_ajax.php',
      'data' : {
        'task' : 'getstates',
        'country_id' : country_id
      },
      'onComplete': function(responseObject, responseText) {

        emptyComboBox(states_control);
        var states_dropdown= document.getElementById(states_control);
        //First Option
        var first_optn = document.createElement("OPTION");
        first_optn.text = 'Select State/Province';
        first_optn.value = '';
        states_dropdown.options.add(first_optn);

        if (responseText!='') {
            //alert(responseText);
            //var states_names = decodeURIComponent(responseText);
            //var states_names = escape(responseText);
            var states_names = responseText;
            //alert(states_names);
            var states_arr = states_names.split(',');
            var states_arr_len = states_arr.length;

            for(var i=0;i<states_arr_len;i++) {

                var optn = document.createElement("OPTION");
                var state_id_name_arr = states_arr[i].split('<|>');
                optn.text = state_id_name_arr[1];
                optn.value = state_id_name_arr[0];
                states_dropdown.options.add(optn);
                if (selected_state == state_id_name_arr[0]) optn.selected = true;
            }

        }

      }

    });

    request.send();

}
function getCities(state_id, city_control, selected_value, show_other){
    //alert(state_id + 'c : ' + city_control + 'val : ' + selected_value);
    // Ajax
    var city_sel_value = ( typeof (selected_value) != 'undefined' && selected_value!='') ? selected_value : '';

    var request = new Request.JSON({
      'method' : 'post',
      'url' : 'country_state_ajax.php',
      'data' : {
        'task' : 'getcities',
        'state_id' : state_id
      },
      'onComplete': function(responseObject, responseText) {
        var city_dropdown= document.getElementById(city_control);
        emptyComboBox(city_control);
        //First Option
        var first_optn = document.createElement("OPTION");
        first_optn.text = 'Select City';
        first_optn.value = '';
        city_dropdown.options.add(first_optn);

        if (responseText!='') {

            var city_names = responseText;
            var city_arr = city_names.split(',');
            var city_arr_len = city_arr.length;

            for(var i=0;i<city_arr_len;i++) {
                var optn = document.createElement("OPTION");
                var city_id_name_arr = city_arr[i].split('<|>');
                optn.text = city_id_name_arr[1];
                optn.value = city_id_name_arr[0];
                city_dropdown.options.add(optn);
            }
        }
        if (show_other!='NO') { //Some drop don't need other option
            //Last Option for Others
            var last_optn = document.createElement("OPTION");
            last_optn.text = 'Other';
            last_optn.value = 'Other';
            city_dropdown.options.add(last_optn);
        }

        //to show selected value
        city_dropdown.value = city_sel_value;

      }

    });

    request.send();

}

function getOtherCity(city_id, country_ctrl_id, state_ctrl_id, other_control_id, inline_css) {//other_control_id = this is the control id for other text box

  //var state_value = document.getElementById(state_ctrl_id).value;
  var city_value = document.getElementById(city_id).value;
  var inline_style = (inline_css !='' && typeof(inline_css)!='undefined') ? 'style="' + inline_css + '"' : '';
  if (city_value == 'Other') {

      document.getElementById(other_control_id + '_span').innerHTML = '<input class="text" type="text" name="' + other_control_id + '" id="' + other_control_id + '" value="Other City Name" onblur="resetKeyValue(\'' + other_control_id + '\' , \'Other City Name\');setOtherCityName(\'' + country_ctrl_id + '\', \'' + state_ctrl_id + '\', \'' + city_id + '\',  \'' + other_control_id + '\', \'Other City Name\');" onfocus="checkKeyValue(\'' + other_control_id + '\' , \'Other City Name\');" ' + inline_style + ' ><font class="redTxt11" style="vertical-align:top">*</font>&nbsp;';

  } else {

      document.getElementById(other_control_id + '_span').innerHTML = '';

  }


}

function setOtherCityName(country_id, state_ctrl_id, city_ctrl_id, other_city_id, default_value) {

   var city_name = document.getElementById(other_city_id).value;
   var state_value = document.getElementById(state_ctrl_id).value;
   var country_value = document.getElementById(country_id).value;

   if (parseInt(state_value)>0 && city_name!=default_value) {
  // Ajax
    var request = new Request.JSON({
      'method' : 'get',
      'url' : 'country_state_ajax.php',
      'data' : {
        'task' : 'setcities',
        'country_id' : country_value,
        'state_id' : state_value,
        'city_name' : city_name
      },
      'onComplete': function(responseObject, responseText) {
            //alert(responseText);
          document.getElementById(other_city_id + '_span').innerHTML = '';
          getCities(document.getElementById(state_ctrl_id).value, city_ctrl_id, responseText);
      }

    });

    request.send();
   }
}

function commonCheck (vfld) {

  if (emptyString.test(vfld.value)) {
      return false;
  }
  return true;
}

function trim(str) {
  return str.replace(/^\s+|\s+$/g, '')
}

function validateEmail  (vfld) {

  var stat = commonCheck (vfld);
  if (stat == false) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/

  if (!email.test(tfld)) return false;


  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) return false;

  return true;
}

function get_lat_lon(frm_obj, zipcode_cntl, lat_cntrl, long_ctrl, miles_ctrl, cou_ctrl, state_ctrl, city_ctrl) {

//alert('IN');
      var zipcode_obj = document.getElementById(zipcode_cntl);

	  var lat_obj     = document.getElementById(lat_cntrl);
      var lon_obj     = document.getElementById(long_ctrl);

      var country_value = document.getElementById(cou_ctrl).value;
      var state_value   = document.getElementById(state_ctrl).value;
      var city_value    = document.getElementById(city_ctrl).value;
      var miles_value   = document.getElementById(miles_ctrl).value;

	  var error_msg = '';
      if (zipcode_obj.value!='' || miles_value!='') {
         if (country_value == '') error_msg = "Please select country name\r\n"; 
         if (state_value == '')   error_msg += "Please select state name\r\n"; 
         //if (city_value == '')   error_msg += "Please select state name\r\n"; 
         if (miles_value == '')   error_msg += "Please select miles\r\n"; 
         if (zipcode_obj.value == '')   error_msg += "Please enter zipcode\r\n"; 

		 if (error_msg!='') alert(error_msg);
	  }

      if (zipcode_obj.value!='' && error_msg=='') {

          // Ajax
            var request = new Request.JSON({
              'method' : 'get',
              'url' : 'country_state_ajax.php',
              'data' : {
                'task' : 'get_lat_long',
                'country_id' : country_value,
                'state_id' : state_value,
                'city_id' : city_value,
                'zip_code' : zipcode_obj.value
              },
              'onComplete': function(responseObject, responseText) {
                  //alert(responseText);
                  if (responseText!='') {
                     var lat_lon_arr = responseText.split('<!>');
                     lat_obj.value = lat_lon_arr[1]; 
                     lon_obj.value = lat_lon_arr[0];
					 frm_obj.submit();
                  }
              }

            });
            request.send();
            return false;

      } else return true;

  }
