var old_onload = window.onload;
window.onload = init;

function init () {
  objCountry  = document.getElementById("smsdCountry");
  objOperator = document.getElementById("smsdOperator");
  objText     = document.getElementById("smsdText");
  objNumber   = document.getElementById("smsdNumber");
  objValue    = document.getElementById("smsdValue");
  
  if (objCountry && objOperator && objText && objNumber && objValue) {
    objCountry.style.width = "auto";
    objOperator.style.width = "auto";
    createCountries ();
    objCountry.onchange = selectCountry;
    objOperator.onchange = selectOperator; 
  }
  else {
    if (old_onload)
      old_onload ();
    return;
  }
  if (old_onload)
    old_onload ();
}

function createCountries () {
  for (var i=0;i<listCountries.length;i++)
    addOption (objCountry,listCountries[i],i,i ? false:true);
  selectCountry ();
}

function selectCountry () {
  createOperators (objCountry.value);
}

function createOperators (country) {
  clearSelect (objOperator);
  for (var i=0;i<listOperators[country].length;i++)
    addOption (objOperator,listOperators[country][i],i,i ? false:true);
  selectOperator ();
}

function selectOperator () {
  createSMSData (objCountry.value,objOperator.value);
}

function createSMSData (country,operator) {
  if (objText.childNodes[0])
    objText.removeChild(objText.childNodes[0]);
  objText.appendChild(document.createTextNode(listSMS[country][1]));
  if (objNumber.childNodes[0])
    objNumber.removeChild(objNumber.childNodes[0]);
  objNumber.appendChild(document.createTextNode(listSMS[country][0]));
  if (objValue.childNodes[0])
    objValue.removeChild(objValue.childNodes[0]);
  objValue.innerHTML = listValues[country][operator];
}

function addOption (objSelect, text, value, isSelected) {
  var objOption = document.createElement("option");
  objOption.appendChild(document.createTextNode(text));
  objOption.setAttribute("value", value);
  objOption.defaultSelected = false;
  objOption.selected = isSelected;
  objSelect.appendChild (objOption);
}

function clearSelect (objSelect) {
  for (var i=objSelect.options.length-1;i>=0;i--)
      objSelect.remove(i);
}
