/**
 Functions for visitor searchcriteria
 **/

var selectArr = new Array();
var modelArr = new Array();
var cityArr = new Array();
var params = '';

var isCitySelected = false;
var isModelSelected = false;
var minPrice;
var maxPrice;

function reload(mode)
{
   if (mode == 'all')
   {
      selectArr = new Array();
      modelArr = new Array();
      cityArr = new Array();
   }

   var action = xmlClientUrl + '/visitor/searchcriteria/update?XMLOnly=true' + provinceParam + params;

   jQuery.ajax({ url: action,
            context: document.body,
            success: function(xmlDoc)
      {
         if (mode == 'all')
         {
            //loadProvinces(xmlDoc);
            loadCities(xmlDoc);
            loadModels(xmlDoc);
            loadArea(xmlDoc);
            loadPrices(xmlDoc);
         }
         else if (mode == 'cities')
         {
            cityArr = new Array();
            loadCities(xmlDoc);
         }
         else if (mode == 'provinces')
         {
            //loadProvinces(xmlDoc);
         }
         else if (mode == 'prices')
         {
            loadPrices(xmlDoc);
         }

         loadSelected(xmlDoc);
      }
   });
}

function loadProvinces(xmlDoc)
{
   var provinces = xmlDoc.getElementsByTagName("province");
   fillProvinces(provinces);
   fillSelectedPrefs(provinces, 'pref_selected_province');
}

function loadModels(xmlDoc)
{
   var housemodels = xmlDoc.getElementsByTagName("housemodel");
   fillBox(housemodels, 'model');
   fillArray(housemodels, 'model', modelArr);
}

function loadCities(xmlDoc)
{
   var cities = xmlDoc.getElementsByTagName("cities")[0].getElementsByTagName("city");
   fillBox(cities, 'city');
   fillArray(cities, 'city', cityArr);
}

function loadArea(xmlDoc)
{
   updateArea(xmlDoc.getElementsByTagName("area")[0].firstChild.nodeValue);
}

function loadPrices(xmlDoc)
{
   var minPrices = xmlDoc.getElementsByTagName("startingprices")[0].getElementsByTagName('price');
   var maxPrices = xmlDoc.getElementsByTagName("endingprices")[0].getElementsByTagName('price');
   fillSelection(minPrices, 'startingprices');
   fillSelection(maxPrices, 'endingprices');
}

function loadSelected(xmlDoc)
{
   var provinces = xmlDoc.getElementsByTagName("province");
   fillSelectedPrefs(provinces, 'pref_selected_province');

   var selectedCities = xmlDoc.getElementsByTagName("selectedcities")[0].getElementsByTagName("city");
   isCitySelected = fillSelectedPrefs(selectedCities, 'pref_selected_city');

   var housemodels = xmlDoc.getElementsByTagName("housemodel");
   isModelSelected = fillSelectedPrefs(housemodels, 'pref_selected_model');

   var minPrices = xmlDoc.getElementsByTagName("startingprices")[0].getElementsByTagName('price');
   var maxPrices = xmlDoc.getElementsByTagName("endingprices")[0].getElementsByTagName('price');
   minPrice = fillSelectedPrice(minPrices, 'pref_selected_minprice');
   maxPrice = fillSelectedPrice(maxPrices, 'pref_selected_maxprice');
}

function fillArray(items, name, array)
{
   for (var i = 0; i < items.length; i++)
   {
      var item = items[i];
      if (item.getAttribute("selected") == 'true')
      {
         var id = item.getAttribute("id");
         array[id] = true;
         selectArr[name + "_" + item.getAttribute("id")] = true;
      }
      else
      {
         selectArr[name + "_" + item.getAttribute("id")] = undefined;
      }
   }
}

function fillBox(items, boxId)
{
   var box = document.getElementById(boxId);

   var ul = document.getElementById(boxId + "_list");
   if (ul)
   {
      box.removeChild(ul);
   }

   ul = document.createElement("ul");
   ul.setAttribute("id", boxId + "_list");
   box.appendChild(ul);

   for (var i = 0; i < items.length; i++)
   {
      var item = items[i];
      var li = createElement('li', item.firstChild.nodeValue);

      if (item.getAttribute("selected") == 'true')
      {
         //li.setAttribute("class", "hc-item hc-item_vi");
         li.className = "hc-item hc-item_vi";
      }
      else
      {
         //li.setAttribute("class", "hc-item hc-item_off");
         li.className = "hc-item hc-item_off";
      }

      li.setAttribute("id", boxId + "_" + item.getAttribute("id"));
      li.setAttribute("title", item.firstChild.nodeValue);
      //li.setAttribute("onmouseover", "switchClassOn(this.id);");
      //li.setAttribute("onmouseout", "switchClassOff(this.id);");
      li.onmouseover = function() { switchClassOn(this.id) };
      li.onmouseout = function() { switchClassOff(this.id) };
      //li.setAttribute("onclick", "changeClass(this.id, '" + item.getAttribute("id") + "', '" + boxId + "')");
      li.onclick = function() { changeClass(this.id) };

      ul.appendChild(li);
   }
}

function fillSelection(items, boxId)
{
   var box = document.getElementById(boxId);

   var select = document.getElementById(boxId + "_selection");

   if (select)
   {
      box.removeChild(select);
   }

   select = document.createElement("select");
   select.setAttribute("id", boxId + "_selection");
   //select.setAttribute("onchange", "switchPrice()");
   select.onchange = function() { switchPrice() };
   box.appendChild(select);

   for (var i = 0; i < items.length; i++)
   {
      var item = items[i];
      var option = createElement('option', formatPrice(item.firstChild.nodeValue));

      if (item.getAttribute("selected") == 'true')
      {
         option.setAttribute("selected", "selected");
      }

      option.setAttribute("value", item.firstChild.nodeValue);
      option.setAttribute("title", formatPrice(item.firstChild.nodeValue));

      select.appendChild(option);
   }
}

function fillProvinces(items)
{
   var p = '';

   for (var i = 0; i < items.length; i++)
   {
      var item = items[i];
      if (item.getAttribute("selected") == 'true')
      {
         p += item.getAttribute("id");
         p += ',';
      }
   }

   //strip last ,
   p = p.substring(0, p.length - 1);

   sendProvincesToFlash(p);
}

function fillSelectedPrefs(items, boxId)
{
   var hasPrefs = false;

   var box = document.getElementById(boxId);

   var s = '';

   for (var i = 0; i < items.length; i++)
   {
      var item = items[i];
      if (item.getAttribute("selected") == 'true')
      {
         s += item.firstChild.nodeValue;
         s += ', ';

         hasPrefs = true;
      }
   }

   //strip last ,
   s = s.substring(0, s.length - 2);

   setText(box, s);

   return hasPrefs;
}

function fillSelectedPrice(items, boxId)
{
   var box = document.getElementById(boxId);

   for (var i = 0; i < items.length; i++)
   {
      var item = items[i];
      if (item.getAttribute("selected") == 'true')
      {
         var price = item.firstChild.nodeValue;
         setText(box, formatPrice(price));
         return price;
      }
   }

   return null;
}

function createElement(name, text)
{
   var element = document.createElement(name);
   var tnode = document.createTextNode(text);
   element.appendChild(tnode);
   return element;
}

function switchClassOn(s)
{
   if (!selectArr[s])
   {
      document.getElementById(s).className = 'hc-item hc-item_on';
   }
}

function switchClassOff(s)
{
   if (!selectArr[s])
   {
      document.getElementById(s).className = 'hc-item hc-item_off';
   }
}

function switchArea(area)
{
   updateArea(area);
   params = '&area=' + area;
   reload('prices');
}

function updateArea(area)
{
   document.getElementById("radio_koop").checked = (area == 'sale');
   document.getElementById("radio_huur").checked = (area == 'rent');
}

function switchPrice()
{
   var min = document.getElementById("startingprices_selection").value;
   var max = document.getElementById("endingprices_selection").value;
   params = "&pricemin=" + min + "&pricemax=" + max;
   reload();
}

function changeClass(sId)//, iD, t)
{
   var divider = sId.indexOf("_");
   var t = sId.substring(0, divider);
   var iD = sId.substring(divider + 1, sId.length);

   selectArr[sId] = (selectArr[sId] == undefined) ? true : undefined;

   className = (selectArr[sId])?'hc-item hc-item_vi':'hc-item';

   document.getElementById(sId).className = className;

   switch (t)
   {
      case 'city':
         cityArr[iD] = (cityArr[iD] == undefined) ? true : undefined;

         params = '&cities='

         for (var i = 0; i < cityArr.length; i++)
         {
            if (cityArr[i])
            {
               params += i + ",";
            }
         }

         reload('provinces');

         break;

      case 'model':
         modelArr[iD] = (modelArr[iD] == undefined) ? true : undefined;

         params = '&housemodels='

         for (var i = 0; i < modelArr.length; i++)
         {
            if (modelArr[i])
            {
               params += i + ",";
            }
         }

         reload();

         break;
   }
}

function setText(element, text)
{
   while(element.firstChild != null)
   {
      element.removeChild(element.firstChild);
   }

   var textNode = document.createTextNode(text);
   element.appendChild(textNode);
}

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 validateReceiveUpdatesForm()
{
   var mailInputElement = document.getElementById("receiveUpdatesByEmail");
   var smsInputElement = document.getElementById("receiveUpdatesBySMS");

   if(mailInputElement.disabled && smsInputElement.disabled)
   {
      alert("U moet eerst uw e-mailadres of mobiele nummer valideren");
      return false;
   }

   return true;
}

function validateSearchCriteria()
{
   var message = "";

   if(!isCitySelected)
   {
      message += "plaats ontbreekt\n"
   }

   if(!isModelSelected)
   {
      message += "soort woning ontbreekt\n"
   }

   message += validatePrice();

   if(message != "")
   {
      message = "Uw selectie is niet volledig:\n" + message;
      alert(message);
      return false;
   }

   return true;
}

function validatePrice()
{
   var message = "";

   if(minPrice == null)
   {
      message += "minimum prijs ontbreekt\n";
   }
   if(maxPrice == null)
   {
      message += "maximum prijs ontbreekt\n";
   }
   if(parseInt(minPrice) >= parseInt(maxPrice))
   {
      message += "minimum prijs is niet kleiner dan de maximum prijs\n";
   }

   return message;
}
