var UNDEFINED = -1;

var TYPE_CITY             = 1;
var TYPE_PROVINCE         = 2;
var TYPE_CITYRANGE        = 3;
var TYPE_POSTALCODERANGE  = 4;
var TYPE_DISTRICT         = 5;
var TYPE_REGION           = 6;
var TYPE_PROJECT          = 7;

var isCircularSearching       = false;
var selectedHouseModelIds     = new Array();
var selectedBuildingStatusId  = new Array();
var selectedKindOfPiv         = new Array();

//The location list consists out of 5 items
var maxLocations = 5;
var locationIds = new Array(maxLocations);
var locationTypes = new Array(maxLocations);

for (var i=0; i<maxLocations; i++)
{
   locationIds[i]    = UNDEFINED;
   locationTypes[i]  = UNDEFINED;
}

//This variable is used during an update of the location list.
//It counts the locations, so it can keep track of our 5 location limits.
//It also indicates the next location list div to use.
var locationIndex;





function extendedSearchInit()
{
   extendedSearch('', '');
}

function extendedSearch(searchEntity, commaSeperatedValues)
{

   var action = xmlClientUrl + '/extendedsearch?XMLOnly=true';

   if (searchEntity != '')
   {
      action += '&' + searchEntity + '=' + commaSeperatedValues;
   }

   jQuery.ajax({ url: action,
            context: document.body,
            success: extendedSearchCallback
          });

   window.status = 'Bezig met ophalen van nieuwe zoekcriteria.';
   //showPreLoaderDiv(true);
}

function extendedSearchCallback(xmlResponse)
{
   if (getSearchArea(xmlResponse) != 'piv')
   {
      updateFromPrice(xmlResponse);
      updateToPrice(xmlResponse);

      updateBuildingStatus(xmlResponse);
      updateRoomCount(xmlResponse);
      updateGroundSurface(xmlResponse);
      updateLivingSurface(xmlResponse);
      updateHouseCount(xmlResponse);
   }
   else
   {
      updateKindOfPiv(xmlResponse);
      updateMinimumDate(xmlResponse);
      updateMaximumDate(xmlResponse);
      updateProjectCount(xmlResponse);
      updateHouseExpectedCount(xmlResponse);
   }
   updateRegionSelectbox(xmlResponse);
   updateLocations(xmlResponse);
   updateHouseModels(xmlResponse);

   if (selectedMaxLocations() || isCircularSearching)
   {
      disableLocationSelections();
   }
   else
   {
      enableLocationSelections();
   }

   window.status = 'Gereed';
}

function extendedSearchOnSelectbox(searchEntity, selectbox)
{
   var selectedItems = '';
   for (var i=0; i<selectbox.options.length; i++)
   {
      if (selectbox.options[i].selected)
      {
         if (selectedItems.length > 0)
         {
             selectedItems += ',';
         }

         selectedItems += selectbox.options[i].value;
      }
   }

   extendedSearch(searchEntity, selectedItems);
}

function showPreLoaderDiv(show)
{
   if (show)
   {
      changeDisplay('preloader','block');
   }
   else
   {
      changeDisplay('preloader','none');
   }
}

function updateLocations(xmlResponse)
{
   resetLocations();

   locationIndex = 0;

   // Select the XML elements to place in the location list.
   // Cities requires a more refined element selection, because the project elemenent also has a city subelement.
   var project          = xmlResponse.getElementsByTagName('project');
   var province         = xmlResponse.getElementsByTagName('province');
   var cities           = xmlResponse.getElementsByTagName('cities')[0].getElementsByTagName('city');
   var cityrange        = xmlResponse.getElementsByTagName('cityrange');
   var postalcoderange  = xmlResponse.getElementsByTagName('postalcoderange');
   var district         = xmlResponse.getElementsByTagName('district');
   var allRegion        = xmlResponse.getElementsByTagName('region');
   var region           = new Array();

   // Filter out selected regions only.
   for( var i=0; i < allRegion.length; i++ )
   {
      if (allRegion[i].getAttribute('selected') == 'true')
      {
         region.push(allRegion[i]);
      }
   }

   //Add provinces to the list of locations.
   appendLocationsByElementsIdAndName( project );
   appendLocationsByElementsIdAndName( province );
   appendLocationsByElementsIdAndName( postalcoderange );   //Rangeable
   appendLocationsByElementsIdAndName( cities );            //Rangeable
   appendLocationsByElementsIdAndName( cityrange );
   appendLocationsByElementsIdAndName( district );
   appendLocationsByElementsIdAndName( region );
}

function resetLocations()
{
   //Hide remove buttons of not used location list items
   var i = 0;
   while (i  < maxLocations)
   {
      //Hide location remove button
      changeVisibility('locationRemove' + i, 'hidden');

      //Hide location range selection
      changeVisibility('rangeSelect' + i, 'hidden');
      changeVisibility('locationRemove' + i, 'hidden');

      locationIds[i]    = UNDEFINED;
      locationTypes[i]  = UNDEFINED;

      //Clear location name
      document.getElementById("location" + i).innerHTML = "";
      i++;
   }

   //Reset ID arrays.
   selectedProvinceIds          = new Array();
   selectedCityIds              = new Array();
   selectedCityIdAndRanges      = new Array();
   selectedPostalCodesAndRanges = new Array();
   selectedDistrictIds          = new Array();
   selectedRegionIds            = new Array();
   selectedProjectsIds          = new Array();

}

function appendLocationsByElementsIdAndName( elementsArray )
{
   var i=0;

   //for each project add the name as option
   while ((i<elementsArray.length) && (locationIndex < maxLocations))
   {
      var range = 0;
      var rangeAble = false;
      var locationId = locationIndex++;

      var elementName = elementsArray[i].tagName;

      var name;

      if ( elementName == 'city')
      {
         id = elementsArray[i].getAttribute('id');
         name = elementsArray[i].firstChild.nodeValue;
         rangeAble = true;

         locationTypes[locationId]  = TYPE_CITY;
         locationIds[locationId]    = id;
         selectedCityIds.push(id);
      }
      else if ( elementName == 'province' )
      {
         id = elementsArray[i].getAttribute('id');
         name = elementsArray[i].firstChild.nodeValue;

         name = rewriteProvinceName(name);

         locationTypes[locationId]  = TYPE_PROVINCE;
         locationIds[locationId]    = id;
         selectedProvinceIds.push(id);
      }
      else if (elementName == 'cityrange' )
      {
         id = elementsArray[i].getAttribute('cityid');
         range = elementsArray[i].getAttribute('range');
         name = elementsArray[i].firstChild.nodeValue;
         rangeAble = true;

         locationTypes[locationId]  = TYPE_CITYRANGE;
         locationIds[locationId]    = id;
         selectedCityIdAndRanges.push(new ValueWithRange(id, range));
      }
      else if (elementName == 'postalcoderange' )
      {
         id = elementsArray[i].getAttribute('postalcode');
         range = elementsArray[i].getAttribute('range');
         name = elementsArray[i].firstChild.nodeValue;
         rangeAble = true;

         locationTypes[locationId]  = TYPE_POSTALCODERANGE;
         locationIds[locationId]    = id;
         selectedPostalCodesAndRanges.push(new ValueWithRange(id, range));
      }
      else if (elementName == 'district' )
      {
         id = elementsArray[i].getAttribute('id');
         var cityName = elementsArray[i].getAttribute('cityName');
         name = cityName + ' (' + elementsArray[i].firstChild.nodeValue + ')';

         locationTypes[locationId]  = TYPE_DISTRICT;
         locationIds[locationId]    = id;
         selectedDistrictIds.push(id);
      }
      else if (elementName == 'region')
      {
         name = elementsArray[i].firstChild.nodeValue;
         id = elementsArray[i].getAttribute('id');

         locationTypes[locationId]  = TYPE_REGION;
         locationIds[locationId]    = id;
         selectedRegionIds.push(id);
      }
      else if (elementName == 'project')
       {
          id = elementsArray[i].getAttribute('id');
          var cityName = elementsArray[i].getElementsByTagName('city')[0].firstChild.nodeValue;
          name = elementsArray[i].firstChild.nodeValue + ' (' + cityName + ')';

          locationTypes[locationId] = TYPE_PROJECT;
          locationIds[locationId]   = id;
          selectedProjectsIds.push(id);
       }


      //Set the location name
      document.getElementById("location" + locationId).innerHTML = name;
      changeVisibility('locationRemove' + locationId, 'visible');

      //Show the range button
      if (rangeAble)
      {
         changeVisibility('rangeSelect' + locationId, 'visible');

         var selectBoxRange = document.getElementById('rangeSelect' + locationId);

         selectBoxRange.value = range;

         //City begins with 0km range. But postalcode has a default minimum of 1km
         if ((elementName == 'cityrange' ) || (elementName == 'city'))
         {
            makeRangeFirstOptionZero(selectBoxRange);
         }
         else if (elementName == 'postalcoderange' )
         {
            makeRangeFirstOptionOne(selectBoxRange);
         }
      }

      i++;
   }
}

function removeLocation(removeIndex)
{
   var id      = locationIds[removeIndex];
   var type    = locationTypes[removeIndex];

   if (id == UNDEFINED || type == UNDEFINED)
   {
      alert("Er is een onbekende fout opgetreden. Kan lokatie niet verwijderen.");
   }
   else if (type == TYPE_CITY)
   {
      removeCity(id);
   }
   else if (type == TYPE_PROVINCE)
   {
      removeProvince(id);
   }
   else if (type == TYPE_CITYRANGE)
   {
      removeCityRange(id);
   }
   else if (type == TYPE_POSTALCODERANGE)
   {
      removePostalCodeRange(id);
   }
   else if (type == TYPE_DISTRICT)
   {
      removeDistrict(id);
   }
   else if (type == TYPE_REGION)
   {
      removeRegion(id);
   }
   else if (type == TYPE_PROJECT)
   {
      removeProject(id);
   }
}

function changeRangeForLocation(locationIndex, value)
{
   var id      = locationIds[locationIndex];
   var type    = locationTypes[locationIndex];

   if (id == UNDEFINED || type == UNDEFINED)
   {
      alert("Er is een onbekende fout opgetreden. Kan lokatie straal niet aanpassen!");
   }

   if ((type == TYPE_CITY) || (type == TYPE_CITYRANGE))
   {
      selectCity(id, value);
   }
   else if (type == TYPE_POSTALCODERANGE)
   {
      selectPostalCode(id, value);
   }

}

function makeRangeFirstOptionZero(selectbox)
{
   //selectbox.options[0].text  =  'geen';
   selectbox.options[0].text  =  '0';
   selectbox.options[0].value =  '0';
}

function makeRangeFirstOptionOne(selectbox)
{
   selectbox.options[0].text  =  '< 1';
   selectbox.options[0].value =  '1';
}

function updateRegionSelectbox(xmlResponse)
{
   var allRegion           = xmlResponse.getElementsByTagName('region');
   var notSelectedRegions  = new Array();



   // Filter out selected regions only.
   for( var i=0; i < allRegion.length; i++ )
   {
      if (allRegion[i].getAttribute('selected') == 'false')
      {
         notSelectedRegions.push(allRegion[i]);
      }
   }

   selectBox = document.getElementById('regions');
   selectBox.options.length = 0;

   selectBox.options.add(new Option(' ', -1, false));

   //for each project add the name as option
   for(var i=0; i<notSelectedRegions.length; i++)
   {
      var name = notSelectedRegions[i].firstChild.nodeValue;
      var value = notSelectedRegions[i].getAttribute('id');

      var option = new Option(name, value, false);
      option.title = name;
      selectBox.options.add(option);
   }
}



function formatPrice(s) {
  var arS = new Array();
  var tel = 0;

  while (s.length>3) {
    arS[tel++] = s.substr(s.length-3);
    s = s.substr(0, s.length-3);
  }

  for (var tel2 = tel-1; tel2>=0; tel2--) {
    s += ("."+arS[tel2]);
  }
  return('€ '+s);
}

function updatePricesSelectionBox( xmlResponse, elementName, valueAttributeName, selectboxId )
{
   var searchEntities = xmlResponse.getElementsByTagName(elementName);

   selectBox = document.getElementById(selectboxId);
   selectBox.options.length = 0;

   //for each project add the name as option
   for(var i=0; i<searchEntities.length; i++)
   {
      var name = formatPrice(searchEntities[i].firstChild.nodeValue);
      var value = searchEntities[i].getAttribute(valueAttributeName);
      var selected = searchEntities[i].getAttribute('selected');

      var option = new Option(name, value);
      option.title = name;
      option.selected = selected == 'true';
      selectBox.options.add(option);
   }
}


function updateSelectionBox( xmlResponse, elementName, valueAttributeName, selectboxId )
{
   var searchEntities = xmlResponse.getElementsByTagName(elementName);

   selectBox = document.getElementById(selectboxId);
   selectBox.options.length = 0;

   //for each project add the name as option
   for(var i=0; i<searchEntities.length; i++)
   {
      var name = searchEntities[i].firstChild.nodeValue;
      var value = searchEntities[i].getAttribute(valueAttributeName);
      var selected = searchEntities[i].getAttribute('selected');

      var option = new Option(name, value);
      option.title = name;
      option.selected = selected == 'true';
      selectBox.options.add(option);
   }
}

function getSearchArea(xmlResponse)
{
   return xmlResponse.getElementsByTagName('searchtype')[0].firstChild.nodeValue;
}

function updateProjectCount(xmlResponse)
{
   var projectCount = xmlResponse.getElementsByTagName('projectcount')[0].firstChild.nodeValue;
   document.getElementById("countsearchresults").innerHTML = projectCount;

   setDisabledCircularRefiners(projectCount == 0, false);
}

function updateHouseExpectedCount(xmlResponse)
{
   //var housesExpectedCount = xmlResponse.getElementsByTagName('countSearchResults')[0].firstChild.nodeValue;
   //document.getElementById("countSearchResults").innerHTML = housesExpectedCount;
}

function updateHouseCount(xmlResponse)
{
   var houseCount = xmlResponse.getElementsByTagName('housecount')[0].firstChild.nodeValue;
   ;
   if (document.getElementById("countsearchresults"))
   {
     document.getElementById("countsearchresults").innerHTML = houseCount;
   }

   setDisabledCircularRefiners(houseCount == 0, true);
}


function updateFromPrice(xmlResponse)
{
   updatePricesSelectionBox(xmlResponse, 'minprice', 'value', 'minprice');
}

function updateToPrice(xmlResponse)
{
   updatePricesSelectionBox(xmlResponse, 'maxprice', 'value', 'maxprice');
}

function updateMinimumDate(xmlResponse)
{
   updateSelectionBox(xmlResponse, 'minimumdate', 'key', 'minimumdate');
}

function updateMaximumDate(xmlResponse)
{
   updateSelectionBox(xmlResponse, 'maximumdate', 'key', 'maximumdate');
}

function selectKindOfPiv(kindOfPiv)
{
   switchToCircularSearch();
   selectedKindOfPiv = getArrayWithAddedId(selectedKindOfPiv, kindOfPiv);
   extendedSearch('kindofpiv', arrayToCommaSeparated(selectedKindOfPiv));
}

function removeKindOfPiv(kindOfPiv)
{
   switchToCircularSearch();
   selectedKindOfPiv = getArrayWithRemovedId(selectedKindOfPiv, kindOfPiv);
   extendedSearch('kindofpiv', arrayToCommaSeparated(selectedKindOfPiv));
}

function updateKindOfPiv(xmlResponse)
{
   var projectstatus = xmlResponse.getElementsByTagName('kindofpiv');

   var html = '<ul>\n';
   for (var i=0; i<projectstatus.length; i++)
   {
      var value      = projectstatus[i].getAttribute('value');
      var selected   = projectstatus[i].getAttribute('selected') == 'true';
      var name       = projectstatus[i].firstChild.nodeValue;

      if (selected)
      {
         html += '   <li onclick="javascript:removeKindOfPiv(\'' + value + '\');" class="selected">' + name + '</li>\n';
      }
      else
      {
         html += '   <li onclick="javascript:selectKindOfPiv(\'' + value + '\')" class="notselected">' + name + '</li>\n';
      }
   }

   html += '</ul>\n';

   //IE gives problems
   document.getElementById('kindofpiv').innerHTML = html;
}

function selectHouseModel(houseModelId)
{
   switchToCircularSearch();
   selectedHouseModelIds = getArrayWithAddedId(selectedHouseModelIds, houseModelId);
   extendedSearch('models', arrayToCommaSeparated(selectedHouseModelIds));
}

function removeHouseModel(houseModelId)
{
   switchToCircularSearch();
   selectedHouseModelIds = getArrayWithRemovedId(selectedHouseModelIds, houseModelId);
   extendedSearch('models', arrayToCommaSeparated(selectedHouseModelIds));
}

function updateHouseModels(xmlResponse)
{
   var housemodels = xmlResponse.getElementsByTagName('housemodel');

   var html = '<ul>\n';
   for (var i=0; i<housemodels.length; i++)
   {
      var id         = housemodels[i].getAttribute('id');
      var selected   = housemodels[i].getAttribute('selected') == 'true';
      var name       = housemodels[i].firstChild.nodeValue;

      if (selected)
      {
         html += '   <li onclick="javascript:removeHouseModel(' + id + ')" class="selected">' + name + '</li>';
      }
      else
      {
         html += '   <li onclick="javascript:selectHouseModel(' + id + ')" class="notselected">' + name + '</li>';
      }
   }
   html += '</ul>\n';

   var houseModelDiv = document.getElementById('soortwoning');
   houseModelDiv.innerHTML = html;
}

function selectProjectStatus(buildingStatusId)
{
   switchToCircularSearch();
   selectedBuildingStatusId = getArrayWithAddedId(selectedBuildingStatusId, buildingStatusId);
   extendedSearch('projectstatus', arrayToCommaSeparated(selectedBuildingStatusId));
}

function removeProjectStatus(buildingStatusId)
{
   switchToCircularSearch();
   selectedBuildingStatusId = getArrayWithRemovedId(selectedBuildingStatusId, buildingStatusId);
   extendedSearch('projectstatus', arrayToCommaSeparated(selectedBuildingStatusId));
}

function updateBuildingStatus(xmlResponse)
{
   var projectstatus = xmlResponse.getElementsByTagName('projectstatus');

   var html = '<ul>\n';
   for (var i=0; i<projectstatus.length; i++)
   {
      var id         = projectstatus[i].getAttribute('id');
      var selected   = projectstatus[i].getAttribute('selected') == 'true';
      var name       = projectstatus[i].firstChild.nodeValue;

      if (selected)
      {
         html += '   <li onclick="removeProjectStatus(' + id + ')" class="selected">' + name + '</li>';
      }
      else
      {
         html += '   <li onclick="selectProjectStatus(' + id + ')" class="notselected">' + name + '</li>';
      }
   }
   html += '</ul>\n';

   var projectStatusDiv = document.getElementById('projectstatus');
   projectStatusDiv.innerHTML = html;
}

function updateRoomCount(xmlResponse)
{
   updateSelectionBox(xmlResponse, 'roomcount', 'value', 'roomcount');
}

function updateGroundSurface(xmlResponse)
{
   updateSelectionBox(xmlResponse, 'groundsurface', 'value', 'groundsurface');
}

function updateLivingSurface(xmlResponse)
{
   updateSelectionBox(xmlResponse, 'livingsurface', 'value', 'livingsurface');
}

function switchToCircularSearch()
{
   disableLocationSelections();
   isCircularSearching = true;
}

function disableLocationSelections()
{
   document.getElementById('projectname_edit').disabled  = true;
   document.getElementById('addprojectbutton').disabled  = true;
   document.getElementById('locationname_edit').disabled = true;
   document.getElementById('addlocationbutton').disabled = true;
   document.getElementById('regions').disabled           = true;

   for (var i=0; i<maxLocations; i++)
   {
      document.getElementById('rangeSelect' + i).disabled = true;
      changeVisibility('locationRemove' + i, 'hidden');
   }
}

function enableLocationSelections()
{
   document.getElementById('projectname_edit').disabled  = false;
   document.getElementById('addprojectbutton').disabled  = false;
   document.getElementById('locationname_edit').disabled = false;
   document.getElementById('addlocationbutton').disabled = false;
   document.getElementById('regions').disabled           = false;

//   for (var i=0; i<maxLocations; i++)
//   {
//      document.getElementById('rangeSelect' + i).disabled = false;
//      changeVisibility('locationRemove' + i, 'visible');
//   }
}



function setDisabledCircularRefiners(disabled, isSaleOrRent)
{
   if (isSaleOrRent)
   {
      //koop huur
      document.getElementById('projectstatus').disabled  = disabled;
      document.getElementById('minprice').disabled       = disabled;
      document.getElementById('maxprice').disabled       = disabled;
      document.getElementById('livingsurface').disabled  = disabled;
      document.getElementById('groundsurface').disabled  = disabled;
      document.getElementById('roomcount').disabled      = disabled;
   }
   else
   {
      //piv
      document.getElementById('minimumdate').disabled    = disabled;
      document.getElementById('maximumdate').disabled    = disabled;
   }
}



function selectedMaxLocations()
{
   var selectionCount = 0;
   selectionCount += selectedProjectsIds.length;
   selectionCount += selectedProvinceIds.length;
   selectionCount += selectedCityIds.length;
   selectionCount += selectedCityIdAndRanges.length;
   selectionCount += selectedPostalCodesAndRanges.length;
   selectionCount += selectedDistrictIds.length;

   return (selectionCount >= 5);
}