/*
 * Use to populate the state/country 
 */

function populateState(stateId , data) {
  var state = $("#" + stateId)[0];
  //Delete all options that existed.
  state.options.length = 0;  
  var options = data.split("|");
  var result = "";

  for(var i = 0; i < options.length; i ++){
    var temp = ($.trim(options[i])).split("=");    
    state.options[i] = (new Option(temp[1] , temp[0]));
  }
}
function inputState(inputObj,stateId)
{
 var statObj=document.getElementById(stateId);
 changeSelectValue(statObj,inputObj);
}

function changeSelectValue(statObj,inputObj)
{
  statObj.options.length=0;
  statObj.options[0]=new Option(inputObj.value,inputObj.value);
}

function getStates(countryCode , stateId) {
  $.ajax({
    type:"Get",
	async:false,
    url:contextPath + "/global/util/stateRestriction.jsp",
    data:"countryCode=" + countryCode,
    dataType:"text",
    success: function(data) {
        var stateInputId=stateId+"_"+"state_Input";
        var style = "width:120px;";
        
        try{
          style = $("#" + stateId).attr("style");
        }catch(e){
        }
        
		if($.trim(data)=="NoState")
		{

			var sel=document.getElementById(stateId);
			var parent=sel.parentNode;
			var stateInput=document.getElementById(stateInputId);
			if(stateInput!=null)
			{
				sel.style.display="none";
				stateInput.style.display="";
				inputState(stateInput,stateId);
			}
			else
			{
				var newInput= document.createElement("input"); 
				newInput.setAttribute("type","text");
				newInput.setAttribute("id",stateInputId);
				newInput.setAttribute("style",style);
				newInput.style.width=sel.style.width;
				newInput.maxLength=40;
				var onclikFunction="inputState(this,'"+stateId+"')";
				newInput.onkeyup=function(){ inputState(newInput,stateId);};
				parent.appendChild(newInput);
				sel.style.display="none";
			}
		return;
		}
		else
		{
		     var stateInput=document.getElementById(stateInputId);
			 if(stateInput!=null)
			 stateInput.style.display="none";
   			 var sel=document.getElementById(stateId);
			 if(sel!=null)
			 sel.style.display="";
			 
		}
      try{

        populateState(stateId , data);
      }catch(e){
      
      }
    },
    error: function() {

    }
  }); 
}