var provinceArray       = new Array();
var cityArray           = new Array();
var districtArray       = new Array();
var neighbourhoodArray  = new Array();
var modelArray          = new Array();
var tagArray            = new Array();
var html                = new Array();
var fromjsvar = '';                                              
var tags;

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();

//var curClicked;
function changeClass(sId, iD, t) {
  selectArr[sId] = (selectArr[sId] == undefined)?true:undefined;

  var paramtype;
  var theArray = new Array();
  className = (selectArr[sId])?'hc-item hc-item_vi':'hc-item hc-item_off';
  curClicked = (document.getElementById(t+iD).parentNode.parentNode["id"])
  switch (curClicked) {
    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);
  if (idString == '')
  {
     curClicked = '';
  }

  document.getElementById(t+iD).className = className;
  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(5, 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);
}


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 switchType(searchType) {
  switch (searchType) {
      case 'piv':
        tags.push('startingdates/date');
        tags.push('endingdates/date');
/*
        document.getElementById('startingprices').style.display = 'none';
        document.getElementById('endingprices').style.display = 'none';
        document.getElementById('startingdates').style.display = 'block';
        document.getElementById('endingdates').style.display = 'block';
*/
        break;
      case 'koop':
        tags.push('startingprices/price');
        tags.push('endingprices/price');
/*
        document.getElementById('startingprices').style.display = 'block';
        document.getElementById('endingprices').style.display = 'block';
        document.getElementById('startingdates').style.display = 'none';
        document.getElementById('endingdates').style.display = 'none';
*/
        break;
      case 'huur':
        tags.push('startingprices/price');
        tags.push('endingprices/price');
/*
        document.getElementById('startingprices').style.display = 'block';
        document.getElementById('endingprices').style.display = 'block';
        document.getElementById('startingdates').style.display = 'none';
        document.getElementById('endingdates').style.display = 'none';
*/
        break;
    }
}

/* 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;
  }

   if(count < 10)
   {
      document.getElementById('indicator1').innerHTML = "&#160;" + count;
   }
   else
   {
      document.getElementById('indicator1').innerHTML = count;
   }

  document.getElementById('indicator1').innerHTML = count;

  if(type == 'piv')
  {
      document.getElementById('indicator2').innerHTML = '('+houseCountForPiv+' woningen)';
  }
}

/**
* Fills niki's boxes with provinces, cities, etc.
*
 * uses:
 * global var 'tags' -> contains strings like province, city etc.
 * @param j index for global var 'tags'
 */
function createElements(j)
{

  //Piece of code to allow usage of elementA/elementB selections
  var selected = '';
  var slashIndex   = (tags[j].indexOf('/'));
  var tagStripped1 = (slashIndex!=-1)?tags[j].substring(0, tags[j].indexOf('/')) :tags[j];
  var tagStripped2 = (slashIndex!=-1)?tags[j].substring((tags[j].indexOf('/')+1)):'';
  /* xml subnodes are treated different in ff */

  //Find cities within the LNP XML (EC Compatible)
  var lnpRootElement = xmldoc.getElementsByTagName('lnp-xml-search')[0];

  //Select elements by tags name or if it exists of two elements select by tagStripped1/tagStripped2
  var items = (tagStripped2)?lnpRootElement.getElementsByTagName(tagStripped1)[0].getElementsByTagName(tagStripped2):lnpRootElement.getElementsByTagName(tags[j]);
  //Create selectbox html (Useable for price/date selection)
  html[j] = (tagStripped2!='')?'<select id="test_'+tagStripped1+'" onchange="changeOption(this.id, this.value)">':'<ul>';

  var flashprovinces = new Array();
  for(i=0, k=0, l=0; i < items.length; i++)
  {
    if (items[i].firstChild.nodeValue != null)
    {
      if(selectArr[tags[j] + items[i].getAttribute('id')])
      {
         className = 'hc-item hc-item_vi';
      }
      else
      {
         className = 'hc-item hc-item_off';
      }

      if (tagStripped2!='')
      {
        //alert (j +' : '+ slashIndex);
     
        // last endingprice is selected
        if(tagStripped1 == 'endingprices')
        {
          k++;
          if(k == xmldoc.getElementsByTagName('endingprices')[0].getElementsByTagName('price').length)
          {
            selected = 'selected="selected"';
          }
        }
        // last endingdate is selected
        if(tagStripped1 == 'endingdates')
        {
          l++;
          if(l == xmldoc.getElementsByTagName('endingdates')[0].getElementsByTagName('date').length)
          {
            selected = 'selected="selected"';
          }
        }
        var formattedItem = (tagStripped1 == 'startingprices' || tagStripped1 == 'endingprices')?formatPrice(items[i].firstChild.nodeValue):items[i].firstChild.nodeValue;
        html[j] += '<option '+selected+' id="'+tagStripped1+'_'+i+'" value="'+items[i].firstChild.nodeValue+'">'+formattedItem+'</option>';
      }
      else if (tagStripped1 == 'province')
      {
          flashprovinces[i] = (items[i].getAttribute('id'));
      }
      else
      {
         html[j] +='<li id="'+tags[j]+items[i].getAttribute('id')+'" class="'+className+'" onclick="changeClass(this.id, '+items[i].getAttribute('id')+', \''+tags[j]+'\');" onmouseover="switchClassOn(this.id);" onmouseout="switchClassOff(this.id);" title="'+items[i].firstChild.nodeValue+'">'+items[i].firstChild.nodeValue+'</li>' ;
      }
    }
  }

  if (tagStripped1 == 'province')
  {
    if(curClicked!='')
    {
      sendProvincesToFlash(flashprovinces)
    }
  }

  html[j]+= (tagStripped2!='')?'</select>':'</ul>';

  if (tagStripped1 != curClicked && tagStripped1 != 'province')
  {
    document.getElementById(tagStripped1).innerHTML = html[j];
  }
}

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';
  }
  setBox(s);
  if(!optimizedIndex)
  {
    Set_Cookie_Caller(s);
  }
}

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;
  }
    //now done in xslt
   //if (document.getElementById('fadeoverlay')) {
    //document.getElementById('fadeoverlay').className = 'fadeoverlay fadeoverlay_'+s;
    //document.getElementById('indicator1').className = 'indicator1 indicator1_'+s;
   //}
  if (document.getElementById('fade') && searchDistricts!='true') {
    if (ie)
    {
      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
    {
      document.getElementById('fade').style.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;
  }
}

function setBox(s) {
//  if (document.getElementById('box_1_3')) {
//    document.getElementById('box_1_3').className = 'box box_1_3 box_1_3_'+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;
    }
  }
}

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(!optimizedIndex)
   {
      if(initType == 'null')
      {
         initUrl = xmlClientUrl+'/' + indexSearchActionName + '?XMLOnly=true&searchdistricts=' + searchDistricts + '&searchneighbourhoods=' + searchNeighbourhoods;
      }
      else
      {
         initUrl = xmlClientUrl+'/' + indexSearchActionName + '?switchto='+initType+'&XMLOnly=true&searchdistricts=' + searchDistricts + '&searchneighbourhoods=' + searchNeighbourhoods;
      }

      if (!document.getElementById('uitgebreidzoeken')) {
         sndReq(initUrl);
      }
   }

   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();
   }
}