function createXmlHttpRequest ()
{
  try
  {
     var requester = new XMLHttpRequest();
  }
  catch (error)
  {
    try
    {
      var requester = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (error)
    {
      return false;
    }
  }
  return requester;
}

function toggleVisibility (object, childId)
{
  child = document.getElementById(childId)
  if (object.checked)
  {
    child.style.display = ''
  }
  else
  {
    child.style.display = 'none'
  }
}
function addInput(name)
{
  var argv = addInput.arguments;
  var argc = argv.length;
  if (argc > 1)
  {
    var id = argv[1];
  }
  else
  {
    generatedId += 1;
    var id = 'generatedId' + generatedId;
  }
  var optionsText = '';
  var div = document.createElement('div');
  changeValue (name + 'Counter', 1)
  div.id = name + 'Div-' + counters[name + 'Counter'];

  if (options[name].length > 0)
  {
    optionsText += '<div class="surfaceOptions">';
    for (var i = 0; i < options[name].length; i++)
    {
      optionsText +=
        '<input type="checkbox" id="' + options[name][i] + id + '" name="'
        + name + '_' + options[name][i] + '[' + id + ']" />'
        + ' <label for="' + options[name][i] + id + '">'
        + texts[name][options[name][i]] + '</label><br />';
    }
    optionsText += '</div>';
  }
  div.innerHTML =
    '<label for="' + name + '_surface_' + id + '">' + texts[name]['surface'] + ' (m<sup>2</sup>)'
    + ': </label> <input name="' + name + '_surface[' + id + ']" type="text" size="4" id="' + name + '_surface_' + id + '" /> ' + optionsText;
  var node = document.getElementById(name + 's');
  node.appendChild(div);
}

function removeThis (node, name)
{
  var parent = node.parentNode;
  parent.removeChild(node);
  changeValue (name + 'Counter', -1)
}

function removeInput (name, number)
{
  var divNode = document.getElementById(name + 'Div-' + number);
  var parentNode =  divNode.parentNode
  parentNode.removeChild(divNode);
  changeValue (name + 'Counter', -1)
}

function changeValue (objectName, amount)
{
  var obj = document.getElementById(objectName);
  counters[objectName] += amount;
  obj.value = counters[objectName];
}

function createDynamicOptions (name)
{
  document.getElementById(name + 's').style.display = 'none';
  counters[name + 'Counter'] = 0;
}

function setDynamicInputs (name)
{
  var obj = document.getElementById(name + 'Counter');
  var numberOfInputs = obj.value;
  var currentNumberOfInputs = counters[name + 'Counter'];
  if (numberOfInputs > currentNumberOfInputs)
  {
    for (var i = currentNumberOfInputs; i < numberOfInputs; i++)
    {
      addInput(name);
    }
  }
  else
  {
    for (var i = currentNumberOfInputs; i > numberOfInputs; i--)
    {
      removeInput(name, i);
    }
  }
}
function enableCounters ()
{
  for (var i in counters)
  {
    document.getElementById(i).disabled = false;
  }
}

function fillValues ()
{
  for (var name in values)
  {
    if (values[name].length > 0)
    {
      document.getElementById(name + 's').style.display = '';
      document.getElementById('has' + name + '-input').checked = true;
      for (var id in values[name])
      {
        addInput(name, id);
        document.getElementById(name + '_surface_' + id).value
          = values[name][id]['surface']

        if (typeof optionsChecked[name][id] != 'undefined')
        {
          for (var option in optionsChecked[name][id])
          {
            document.getElementById(optionsChecked[name][id][option] + id).checked = true;
          }
        }
      }
    }
    else
    {
      addInput(name);
    }
  }
}

generatedId = 0;
counters = new Array;
texts = new Array;
options = new Array;
optionsChecked = new Array;
values = new Array;

function updateConditional (id)
{
  for (var i = 0; i < conditionalIds['on'][id].length; i++)
  {
    var object = document.getElementById(conditionalIds['on'][id][i]);
    object.disabled = !document.getElementById(id).checked;
  }
  for (var i = 0; i < conditionalIds['off'][id].length; i++)
  {
    var object = document.getElementById(conditionalIds['off'][id][i]);
    object.disabled = document.getElementById(id).checked;
  }
}
conditionalIds = new Array;
conditionalIds['on'] = new Array;
conditionalIds['off'] = new Array;


function loadTownsSelectBox ()
{
  function populateTowns ()
  {
    if(xmlhttp.readyState == 4)
    {
      if (typeof radiusInputId != 'undefined')
      {
        var hasRadius = true;
        var radiusInput = document.getElementById(radiusInputId);
        radiusInput.disabled = false;
      }
      else
      {
        var hasRadius = false;
      }
      var townsInput = document.getElementById(townsInputId);
      townsInput.outerHTML = xmlhttp.responseText;
      var parentNode =  townsInput.parentNode
      parentNode.removeChild(townsInput);
      parentNode.innerHTML = xmlhttp.responseText + parentNode.innerHTML;
      var townsInput = document.getElementById(townsInputId);
      radiusInput.disabled = townsInput.disabled;
    }
  }
  if (typeof provinceInputId  == 'undefined') { return false;}
  if (typeof costaInputId == 'undefined') { return false; }
  if (typeof townsInputId == 'undefined') { return false; }
  var allowEmpty = townsAllowEmpty ? '1' : '0';
  var provinceInput = document.getElementById(provinceInputId);
  var provinceId = parseInt(provinceInput.value);
  var costaInput = document.getElementById(costaInputId);
  var costaId = parseInt(costaInput.value);
  if (provinceId != lastProvinceId)
  {
    var xmlhttp = createXmlHttpRequest();
    xmlhttp.open(
      'GET',
      '/script/townsSelectBox.php?sid='+provinceId+'&allowEmpty='+allowEmpty+'&aid='+agentId,
      true
    );
    xmlhttp.onreadystatechange = populateTowns
    xmlhttp.send(null);
    lastProvinceId = provinceId;
  }
  else if (costaId != lastCostaId)
  {
    var xmlhttp = createXmlHttpRequest();
    xmlhttp.open(
      'GET',
      '/script/townsSelectBox.php?cid='+costaId+'&allowEmpty='+allowEmpty+'&aid='+agentId,
      true
    );
    xmlhttp.onreadystatechange = populateTowns
    xmlhttp.send(null);
    lastCostaId = costaId;
  }
  costaInput.disabled = provinceId != 0;
  provinceInput.disabled = costaId != 0;
}

function checkMinMax(input, name, allowEqual)
{
  var minInput = document.getElementById(name + '-input');
  var maxInput = document.getElementById(name + 'Max-input');
  minValue = parseInt(
    minInput.options[minInput.selectedIndex].value
  );
  maxValue = parseInt(
    maxInput.options[maxInput.selectedIndex].value
  );
  if (input.name == minInput.name &&
    (minValue > maxValue || (!allowEqual && (minValue == maxValue)))
  )
  {
    for (var i = 0; i < maxInput.options.length; i++)
    {
      var v = maxInput.options[i].value;
      if ((v > minValue) || (allowEqual && (v == minValue)) || (v == 'infinity'))
      {
        maxInput.selectedIndex = i;
        break;
      }
    }
  }
  else
  {
    if (minValue > maxValue || (!allowEqual && (minValue == maxValue)))
    {
      for (var i = (minInput.options.length - 1); i >= 0 ; i--)
      {
        var v = minInput.options[i].value;
        if ((v < maxValue) || (allowEqual && v == maxValue))
        {
          minInput.selectedIndex = i;
          break;
        }
      }
    }
  }
}

function updateOutsetInputs (id)
{
  disabled = id != 'outset-date';
  fieldset = document.getElementById('outsetDate-input');
  children = fieldset.childNodes;
  for (var i = 0; i < children.length; i++)
  {
    children[i].disabled = disabled;
  }
}
function updateAdditionalCosts (id)
{
  var idsplit = id.split('-');
  disabled = idsplit[1] != 'excludedCosts';
  input = document.getElementById(idsplit[0] + 'Number-input');
  input.disabled = disabled;
}
function loadScroller (page, lang, id)
{
  function populateScroller ()
  {
    if(xmlhttp.readyState == 4)
    {
      scroller.innerHTML = xmlhttp.responseText;
    }
  }
  var scroller = document.getElementById('scroller');
  if (typeof(scroller) != 'undefined')
  {
    var xmlhttp = createXmlHttpRequest();
    var now = new Date();
    var dummystr = parseInt(now.getTime() / 1000);
    xmlhttp.open(
      'GET',
      '/script/scrollerFill.php?page=' + page + '&lang=' + lang + '&id=' + id +
        '&x=' + dummystr,
      true
    );
    xmlhttp.onreadystatechange = populateScroller
    xmlhttp.send(null);
  }
}
function loadBanners (costaId, lang)
{
  function populateBanners ()
  {
    if(xmlhttp.readyState == 4)
    {
      var bannersDiv = document.getElementById('banners');
      bannersDiv.innerHTML = xmlhttp.responseText;
    }
  }
  var xmlhttp = createXmlHttpRequest();
  var now = new Date();
  var dummystr = parseInt(now.getTime() / 1000);
  xmlhttp.open(
    'GET',
    '/script/bannerFill.php?lang=' + lang + '&costa=' + costaId + '&x=' + dummystr,
    true
  );
  xmlhttp.onreadystatechange = populateBanners
  xmlhttp.send(null);
}
function updateBoardShipping (prefix)
{
  var topObj = document.getElementById(prefix + 'advertType-top');
  var premiumObj = document.getElementById(prefix + 'advertType-premium');
  if (typeof premiumObj == 'undefined')
  {
    return;
  }
  if (topObj.checked)
  {
    premiumObj.checked = true;
  }
  var inputs = new Array(
    'phone','priceVisible','address','countryId','name','town','postalCode'
  );
  for (var input in inputs)
  {
    var inputObj = document.getElementById(
      prefix + inputs[input] + '-input'
    );
    if (typeof inputObj != 'undefined')
    {
      inputObj.disabled = !premiumObj.checked;
    }
  } 
}
function loadWeather(provinceId)
{
  function populateWeather ()
  {
    if(xmlhttp.readyState == 4)
    {
      var weatherDiv = document.getElementById('weather');
      weatherDiv.innerHTML = xmlhttp.responseText;
    }
  }
  var xmlhttp = createXmlHttpRequest();
  xmlhttp.open(
    'GET',
    '/script/weatherFill.php?provinceId=' + provinceId,
    true
  );
  xmlhttp.onreadystatechange = populateWeather
  xmlhttp.send(null);
}

function updateForsalePreview (prefix)
{
  var imgObj = document.getElementById('previewImage');
  var priceVisibleObj = document.getElementById(prefix + 'priceVisible-input');
  var priceObj = document.getElementById(prefix + 'price-input');
  var phoneObj = document.getElementById(prefix + 'phone-input');
  var url = '/images/dynamic/forsale.php?phone=' + phoneObj.value;
  if (priceVisibleObj.checked)
  {
    url += '&price=' + priceObj.value;
  }
  imgObj.src = url;
}
function playerCommand (id, command)
{
  var player = document.getElementById(id);
  if (typeof player == 'undefined')
  {
    return;
  }
  switch (command)
  {
    case 'play':
      player.controls.play();
      break;
    case 'stop':
      player.controls.stop();
      break;
    case 'fastForward':
      player.controls.fastForward();
      break;
    case 'fastReverse':
      player.controls.fastReverse();
      break;
    case 'fullScreen':
      player.fullScreen = true;
      alert(player.fullScreen);
      break;
  }
}
function replaceObjects()
{
	var objectTagList;
	var newNode;

	if (document.replaceNode)
	{
		// Document.replaceNode does not work in Firefox, just in IE
		objectTagList = document.getElementsByTagName("object");
		for (var i=0; i < objectTagList.length; i++)
		{
			newNode = objectTagList[i].cloneNode(true);
			objectTagList[i].replaceNode(newNode);
		}
	}
}

function showhidesearchdiv()
{
	sdiv=document.getElementById('searchdiv');	
	if(sdiv.style.display == 'none')
	{
		sdiv.style.display="";
	}
	else
	{
		sdiv.style.display='none';
	}
} 



