var reset       = true;
var searchArea  = null;


var provinceArray       = new Array();
var cityArray           = new Array();
var districtArray       = new Array();
var neighbourhoodArray  = new Array();
var modelArray          = new Array();


function hideinfo() {
  document.getElementById('infoback').style.display = 'none';
  document.getElementById('infotext').style.display = 'none';
}

function showinfo() {
  switch (initType) {
    case 'piv':
       if(document.getElementById('i3'))
       {
         document.getElementById('i3').className = 'info info3a';
       } break;
    default:
  }
}

/* remove empty (undefined) items from array */
function trimArray(a) {
  var counter = 0;
  var retval = '';
  for (var i=0; i<a.length; i++) {
    if (a[i] != undefined) {
      if (counter > 0) retval += ',';
      retval += (a[i]);
      counter++;
    }
  }
  return retval;
}

var selectArr = new Array();

function changeClass(sId, iD, searchType) {
  selectArr[sId] = (selectArr[sId] == undefined)?true:undefined;

  var paramtype;
  var theArray = new Array();

  switch (searchType) {
    case 'province':
      paramtype = 'provinces'; provinceArray[iD] = (provinceArray[iD]==undefined)?iD:undefined; theArray = provinceArray; break;
    case 'city':
      paramtype = 'cities'; cityArray[iD] = (cityArray[iD]==undefined)?iD:undefined; theArray = cityArray; break
    case 'district':
      paramtype = 'districts'; districtArray[iD] = (districtArray[iD]==undefined)?iD:undefined; theArray = districtArray; break
    case 'neighbourhood':
      paramtype = 'neighbourhoods'; neighbourhoodArray[iD] = (neighbourhoodArray[iD]==undefined)?iD:undefined; theArray = neighbourhoodArray; break
    case 'model':
      paramtype = 'models'; modelArray[iD] = (modelArray[iD]==undefined)?iD:undefined; theArray = modelArray; break
    default: break;
  }

  var idString = trimArray(theArray);

  jQuery('#' + searchType + iD).attr('class', getEntitySelectionStateStyleClass(sId));

  sndReq(xmlClientUrl+'/' + indexSearchActionName + '?'+paramtype+'='+idString+'&XMLOnly=true&searchdistricts=' + searchDistricts + '&searchneighbourhoods=' + searchNeighbourhoods);
}


function reformatDate(s) {
  var s1 = s.substr(0,1);
  var s2 = s.substr((s.length-4),4);
  return s1+'-'+s2;
}


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('&euro;&nbsp;'+s);
}


function changeOption(thisid, thisvalue) {
  var params = '';
  var thisid = thisid.substr("select".length, thisid.length)

  switch (thisid) {
    case 'startingprices':
      thisid = 'pricefrom';
      break;
    case 'endingprices':
      thisid = 'priceto';
      break;
    case 'startingdates':
      thisid = 'buildfrom';
      thisvalue = reformatDate(thisvalue);
      break;
    case 'endingdates':
      thisid = 'buildto';
      thisvalue = reformatDate(thisvalue);
      break;
  }
  params = thisid+'='+thisvalue;
  sndReq(xmlClientUrl+'/' + indexSearchActionName + '?'+params+'&XMLOnly=true&searchdistricts='+ searchDistricts +'&searchneighbourhoods=' + searchNeighbourhoods);
}


/* indicator to show number of houses found */
function createIndicator(housecount, projectcount, type) {
    var houseCountForPiv;
    var count;
    var text;

    switch (type) {
    case 'koop':
      text = (housecount==1)?'koopwoning':'koopwoningen';
      count = housecount;
      break;
    case 'huur':
      text = (housecount==1)?'huurwoning':'huurwoningen';
      count = housecount;
      break;
    case 'piv':
      text = (projectcount==1)?'project':'projecten';
      count = projectcount;
      houseCountForPiv = housecount;
      break;
  }

  jQuery('#indicator1').html(count);

  if(type == 'piv')
  {
      jQuery('#indicator2').html('('+houseCountForPiv+' woningen)');
  }
}


function switchClassOn(s)
{
    jQuery('#'+s).attr('class', getEntitySelectionStateStyleClass(s, true));
}

function switchClassOff(s)
{
    jQuery('#'+s).attr('class', getEntitySelectionStateStyleClass(s, false));
}

/**
 * Changes class style of element to either selected OR mouse enter/leave
 * @param idName name of id to alter class for
 * @param mouseOver if mouse is over.
 */
function getEntitySelectionStateStyleClass(idName, mouseOver)
{
    var stylePrefix="hc-item hc-item_";
    if (selectArr[idName])
    {
        return stylePrefix+"vi";
    }
    else if (mouseOver)
    {
        return stylePrefix+"on";
    }
    else //undefined
    {
        return stylePrefix+"off";
    }
}


/**
 * Uses xmlDocument as source. Fills htmlDestinationElement innerHTML with search entity links.
 * entityIdPrefix + database id is used to track what kind and which database entity is adjusted
 *
 * Note: xmlElementName, htmlDestinationElement and entityIdPrefix are usually equal in niki
 *
 * @param xmlDocument xml document as source
 * @param xmlElementName Name of element in source xmlDocument
 * @param htmlDestinationElement id of element to fill child ul inner html (div id="model") -> 'model'
 * @param entityIdPrefix prefix string to recognise the search type. Is used in the link as
 *                       entityIdPrefix+id (a href id="model123") -> 'model'

 */
function fillSearchBoxWithSearchRefinerLinks( xmlDocument,
                                              xmlElementName,
                                              htmlDestinationElement,
                                              entityIdPrefix)
{
    var li = '';
    jQuery(xmlDocument).find("lnp-xml-search "+xmlElementName).each(function()
    {
       var name = jQuery(this).text();
       var id = jQuery(this).attr('id');
       li += '<li id="' + entityIdPrefix + id + '" class="' + getEntitySelectionStateStyleClass(entityIdPrefix+id, false) + '"><a title="' + name + '"  href="#">' + name + '</a></li>';
    });

    jQuery('#' + htmlDestinationElement + ' ul').html(li);



    // Attach functions for mouse enter/leave and click events.
    attachAjaxSearchRefinerLinksEvents(entityIdPrefix);
}

/**
 * Synchronise XML with the Flash map
 *
 * @param xmlDocument xml source
 * @param xmlElementName element name of province (should have id attribute)
 */
function synchroniseFlashMapProvincesWithXml(xmlDocument,
                                             xmlElementName)
{
    var provincesSelected = jQuery(xmlDocument).find(xmlElementName + '[selected=true]').size();

   /**
    * If there are selected (attribute selected = true) provinces this means
    * the province selection is the current active selection. If province is
    * the current active selection the selection of the flash map is currently being adjusted
    * by a user. The state of the flash map is leading and should not be reset by the ajax callback.
    */
   if(provincesSelected == 0)
    {
       var flashprovinces = new Array();

       jQuery(xmlDocument).find(xmlElementName).each(function()
       {
          flashprovinces.push(jQuery(this).attr('id'));
       });

       sendProvincesToFlash(flashprovinces);
    }
}

/**
 * Fills div with a selectbox with options parsed from an XML source.
 *
 *
 *
 * @param xmlDocument XML document
 * @param xmlElementAddressedSpaceSeperated Element location. This is not an xpath expression, but elements are
 *        space seperated. Example: 'lnp-xml-search lnpsearch prices startingprices price'
 *        (Would select the same as xpath expression: /lnp-xml-search/lnpsearch/prices/startingprices/price)
 * @param htmlDestinationElementId id name of HTML element where selectbox is inner html-ed into
 * @param selectId
 * @param selectLastOption
 * @param optionalFormatFunction
 */
function fillSelectsWithSearchRefinerCriteria(xmlDocument,
                                              xmlElementAddressedSpaceSeperated,
                                              htmlDestinationElementId,
                                              selectId,
                                              selectLastOption,
                                              optionalFormatFunction)
{
    var htmlSelectCode;

    htmlSelectCode = '<select id="'+selectId+'" onchange="changeOption(this.id, this.value)">';

//    var lastSpace = xmlElementAddressedSpaceSeperated.lastIndexOf(' ');
//    var elementWithSubItems = jQuery(xmlElementAddressedSpaceSeperated.substr(0,lastSpace), xmlDocument);
//    var items = elementWithSubItems.find(xmlElementAddressedSpaceSeperated.substr(lastSpace+1));

    var items = jQuery(xmlDocument).find(xmlElementAddressedSpaceSeperated);

    //var items = jQuery(xmlDocument).find(xmlXPathToSelectOptions);
    var lastIndex = items.length-1;

    var i=0;
    items.each(function()
    {
        var selected = '';
        if(i == lastIndex && selectLastOption)
        {
            selected = 'selected="selected"';
        }

        var value = jQuery(this).text();
        var itemDisplayValue = value;
        if (optionalFormatFunction)
        {
            itemDisplayValue = optionalFormatFunction(value);
        }

        htmlSelectCode += '<option '+selected+' value="'+value+'">'+itemDisplayValue+'</option>';

        i++;
    });

  jQuery('#' + htmlDestinationElementId).html(htmlSelectCode);
}

var buttonArray = new Array('koop','huur','piv');

function switchButton(s) {
  for (i=0; i<buttonArray.length; i++)
  {
    var button = document.getElementById('button_'+buttonArray[i]);
    if(button != null)
    {
      button.className = 'button_switch button_'+buttonArray[i]+'';
    }
  }
  if (document.getElementById('button_'+s))
  {
    document.getElementById('button_'+s).className = 'button_switch button_'+s+'_on';
  }
}

function switchTo(s) {
  switchButton(s);
  var url = xmlClientUrl + '/' + searchIndexActionName + '?switchto=' + s;
  if(indexParams != '')
  {
     url += '&' + indexParams;
  }
  location.href = url;
}

function switchToExtendedSearch(s) {
   switchButton(s);
   location.href = xmlClientUrl + '/extendedsearch?switchto='+s;
}


function glowButton(s) {
  if (document.getElementById(s)) {
    document.getElementById(s).className = 'button_switch '+s+'_over';
  }
}

function restoreButton(s) {
  if (document.getElementById(s)) {
    document.getElementById(s).className = 'button_switch '+s;
  }
}

function setFade(s) {
   if (searchDistricts!='true'){
    searchImageExt='.gif';
     gfxPathExt='';

    }else{
    gfxPathExt='/index';
    searchImageExt='.png';
    }
  if (document.getElementById('toonknop')) {
    document.getElementById('toonknop').src = contextPath + '/gfx'+ gfxPathExt +'/toon_'+s+searchImageExt;
  }
  if (document.getElementById('fadebackground')) {
    document.getElementById('fadebackground').className = document.getElementById('fadebackground').className + ' ' + document.getElementById('fadebackground').className +'_'+s;
  }

  if (document.getElementById('fade') && searchDistricts!='true') {
    if (jQuery.browser.msie && jQuery.browser.version.number < 8.0)
    {
      try
      {
        document.getElementById('fade').filters(0).src = contextPath + '/gfx/fade_'+s+'.png';
        document.getElementById('fade').filters(0).sizingMethod = 'scale';
      }
      catch (e)
      {
         //Sometimes thrown when user has misconfigured or old directx.
      }
    }
    else
    {
       jQuery('#fade').css('background', 'url("' + contextPath +  '/gfx/fade_'+s+'.png")');
    }
  }
}

function snelCode() {
  var theDisplay = document.getElementById('snelcode').style.display;

  if (theDisplay == 'block') {
    theDisplay = 'none';
    document.getElementById('box_2_1').style.opacity = '0.3';
    document.getElementById('box_2_1').style.filter = 'alpha(opacity=30)';
  } else {
    theDisplay = 'block';
    document.getElementById('box_2_1').style.opacity = '1';
    document.getElementById('box_2_1').style.filter = 'alpha(opacity=100)';
  }
  document.getElementById('snelcode').style.display=theDisplay;
}

function setColors(s) {
  if (document.getElementById('box_2_0')) {
    document.getElementById('box_2_0').className = 'box box_2_0 box_2_0_'+s;
  }
  if (document.getElementById('box_2_1')) {
    document.getElementById('box_2_1').className = 'box box_2_1 box_2_1_'+s;
  }
}

var fadeOverlayClass;

function searchHover() {
  if(showProjectresult='false'){
    if (document.getElementById('fadeoverlay')) {
      fadeOverlayClass=document.getElementById('fadeoverlay').className;
      document.getElementById('fadeoverlay').className = document.getElementById('fadeoverlay').className + '_hover';
    }
  }
}


function searchHoverOff() {
  if(showProjectresult='false'){
    if (document.getElementById('fadeoverlay')) {
      document.getElementById('fadeoverlay').className = fadeOverlayClass;
    }
  }
}


//Index page
function initNiki()
{
   if (!useOWZTemplate)
   {
      changeBackground();
   }

   //this function is implemented in the index_include.xsl. Variable koop/huur/piv is defined in the xml.
   if ( typeof setInitType === 'function' )
   {
        setInitType();
   }

   if (initType != 'null')
   {
      setFade(initType);
      if (searchDistricts != 'true')
      {
         setColors(initType);
      }
      switchButton(initType);
   }
	  if (!useOWZTemplate) {
			if (document.getElementById('niki-container') && document.getElementById('niki-container').offsetHeight < document.body.offsetHeight) {
				document.getElementById('niki-container').style.height = document.body.offsetHeight - 2 + 'px';
			}
		}

   if (document.getElementById('uitgebreidzoeken'))
   {
      extendedSearchInit();
   }
   else
   {
      showinfo();
   }

   attachAjaxSearchRefinerLinksEvents("province");
   attachAjaxSearchRefinerLinksEvents("city");
   attachAjaxSearchRefinerLinksEvents("model");
   attachAjaxSearchRefinerLinksEvents("district");
   attachAjaxSearchRefinerLinksEvents("neighbourhood");

   initProvincesFlash();

   // jscrollpane for mobile webkit devices not supporting {overflow: auto}
   // ipod, iphone, ipad and android devices
   if(/(like Mac OS X|Android)/.test(navigator.userAgent))
   {
      // if the flash map is not loaded fall back to js selection
      if(!swfobject.hasFlashPlayerVersion('8'))
      {
         jQuery('#province').jScrollPane();
      }

      jQuery('#city, #model, #district, #neighbourhood').jScrollPane();
   }
   
   initLoader();
   preLoadImages();

   //add loader to all links except the ajax search items 
   jQuery('#niki-container a').not('li.hc-item a, a[href^=javascript], a[href^=#], a[target]').click(function()
   {
      showLoader();
   });
}

function initLoader()
{
   jQuery('body').append('<div id="loader" class="png"></div>');
   preLoadImage(jQuery('#loader').css('background-image').replace(/^url\(['"]?([^'"]*)['"]?\);?$/, '$1'));
}

function preLoadImages()
{
   var images = [
      '/gfx/preloader_' + initType + '.gif'
   ];

   for(i = 0 ; i < images.length; i++)
   {
      var img = new Image();
      img.src = contextPath + images[i];
   }
}

function preLoadImage(url)
{
   var img = new Image();
   img.src = url;
}

/**
 * Display a animated loader
 */
function showLoader()
{
   if(!(jQuery.browser.msie && jQuery.browser.version <= 6))
   {
      jQuery('#niki-container').fadeTo(50, 0.6);
   }

   var w = jQuery(window);

   //center position
   var loader = jQuery('#loader');
   loader.css('left', w.width() / 2 - 20 + 'px');
   loader.css('top', w.height() / 2 - 20 + 'px');
   loader.show();
}

/**
 * For all <a> elements that have an id starting with the stringIdPrefix
 *      Add events to control ajax search
 *
 * @param stringIdPrefix name of a.id prefix.
 *          Like "model" for "model1" (id = 1)
 *          Or "city" for "city5" (id = 5)
 */
function attachAjaxSearchRefinerLinksEvents( stringIdPrefix)
{

    //For all house model
    jQuery("li[id^='"+stringIdPrefix+"']").each(function()
    {
        var idAttributeValue = jQuery(this).attr('id');
        var longId = idAttributeValue.substring(stringIdPrefix.length);

        jQuery(this).children('a').click(function(event)
        {
            //Not following the a href click.
            event.preventDefault();
        });

        jQuery(this).click(function(event) {
            changeClass(idAttributeValue, longId, stringIdPrefix);
        });

        jQuery(this).mouseenter(function() {
           switchClassOn(idAttributeValue);
        });

        jQuery(this).mouseleave(function() {
           switchClassOff(idAttributeValue);
        });
    });

}


/* send the request */
function sndReq(action)
{
  // if requestobject can not be created display error message
  if(reset)
  {
     reset = false;
  }

  jQuery.ajax({ url: action,
           context: document.body,
           success: handleResponse
         });
}

function handleResponse(xmldoc)
{

      searchEntityBoxNamesWithLinks = new Array('city',
                                                'model',
                                                'district',
                                                'neighbourhood');

      // if the flash map is not enabled fall back to js selection
      if(!swfobject.hasFlashPlayerVersion('8'))
      {
         searchEntityBoxNamesWithLinks.push("province");
      }

      var searchType = jQuery("lnp-xml-search lnpsearch", xmldoc).attr('type');
      var housecount = jQuery("lnp-xml-search lnpsearch housecount", xmldoc).text();

      var projectcount = 0;

      if(searchType == 'piv')
      {
         projectcount = jQuery("lnp-xml-search lnpsearch projectcount", xmldoc).text();
      }

      createIndicator(housecount, projectcount, searchType);

	   /* get kind of realestate */
		//var koreTrueFalse=xmldoc.getElementsByTagName('kindofrealestate')[0].getAttribute('enabled');
		//setKindOfRealEstate(koreTrueFalse, searchType);

      /* create search boxes */
      for (j=0; j < searchEntityBoxNamesWithLinks.length; j++)
      {
          fillSearchBoxWithSearchRefinerLinks(xmldoc,
                                              searchEntityBoxNamesWithLinks[j],
                                              searchEntityBoxNamesWithLinks[j],
                                              searchEntityBoxNamesWithLinks[j]);

      }

    synchroniseFlashMapProvincesWithXml(xmldoc, 'province');

    if (searchType == 'koop' || searchType == 'huur')
    {
        fillSelectsWithSearchRefinerCriteria(xmldoc,
                                            "lnp-xml-search lnpsearch prices startingprices price",
                                            'startingprices',
                                            'selectstartingprices',
                                            false,
                                            formatPrice);

        fillSelectsWithSearchRefinerCriteria(xmldoc,
                                            "lnp-xml-search lnpsearch prices endingprices price",
                                            'endingprices',
                                            'selectendingprices',
                                            true,
                                            formatPrice);

    }
    else //piv
    {
        fillSelectsWithSearchRefinerCriteria(xmldoc,
                                            'date',
                                            'lnp-xml-search lnpsearch builddates startingdates date',
                                            'selectstartingdates',
                                            false,
                                            undefined);

        fillSelectsWithSearchRefinerCriteria(xmldoc,
                                            'date',
                                            'lnp-xml-search lnpsearch builddates endingdates date',
                                            'selectendingdates',
                                            true,
                                            undefined);
    }

    // reinitialise jscrollpanes
    jQuery('#province').data('jsp').reinitialise();
    jQuery('#city').data('jsp').reinitialise();
    jQuery('#model').data('jsp').reinitialise();
    jQuery('#district').data('jsp').reinitialise();
    jQuery('#neighbourhood').data('jsp').reinitialise();
}

