var array_historydata = new Array()   // array of processed historydata for the current house
var historydataParameters;
function getHistoryData(searchoption,cachetab, tabid)
{
  if(cachetab==null)
    cachetab=false;
  if(tabid==null)
    tabid=0;

  da('txtPlaats').className="extendHistoryZoomText";
  da('txtPostcode').className="extendHistoryZoomText";
  da('txtStraat').className="extendHistoryZoomText";

  if(searchoption==1 && da('txtPlaats')!=null) 
  {
    da('txtPlaats').className="extendHistoryZoomTextActive";
  }
  if(searchoption==2 && da('txtPostcode')!=null) 
  {
    da('txtPostcode').className="extendHistoryZoomTextActive";
  }
  if(searchoption==3 && da('txtStraat')!=null) 
  {
    da('txtStraat').className="extendHistoryZoomTextActive";
  }
  urchinTracker('Zoek/House/Tab3/'+searchoption);
  var txtPlaats = "";
  var txtPostcode = "";
  var soStraal = "";
  var txtStraat = "";
  var txtCurrentHouse ="";
  var isRowSelected = da('hiddenCurrentHistoryIsRowSelected').value;
  var selectedRow = CalculateSelectedRow();

  var startRow = parseInt(da('hiddenCurrentHistoryStartRow').value);
  if(startRow ==0) startRow = CalculateStartRow()

  var currentTab = "price";
  if(da('hiddenCurrentHistoryTab').value == 1)
    currentTab="price";
  else if(da('hiddenCurrentHistoryTab').value == 2)
    currentTab="count";
  else if(da('hiddenCurrentHistoryTab').value == 3)
    currentTab="last20";
  else if(da('hiddenCurrentHistoryTab').value == 4)
  {
    currentTab="main";
  }
  if(searchoption == 1)
    var txtPlaats = da('txtPlaats').value;
  if(searchoption == 2)
  {
    var txtPostcode = da('txtPostcode').value;
    var soStraal = 1;
    //
  }

  if(searchoption == 3)
    var txtStraat = da('txtStraat').value;

  if(searchoption == 4)
  {
    if (da('currentHouse'))
      var txtCurrentHouse = da('currentHouse').value;
    var txtStraat = da('street').value;
    var txtPostcode = da('txtPostcode').value;
    var txtPlaats = da('txtPlaats').value;
    var soStraal = 1;
  }

  if(searchoption != 4)
	  da('hiddenCurrentHistoryDataSearchoption').value = searchoption;

  var hdView = "room"; //default
  if(da('hdtoggleView1').checked == true)
    hdView = "room";
  else
    hdView = "area";

  if (da('currentHouseID'))
  {
    currentHouseId = da('currentHouseID').value
  }
  historydataParameters = 'city=' + txtPlaats
                        + '&zip=' + txtPostcode
                        + '&range=' + soStraal
                        + '&street=' + txtStraat
                        + '&selectedRow=' + selectedRow
                        + '&currentTab=' + currentTab
                        + '&startRoom=' + startRow
                        + '&IsRowSel=' + isRowSelected
                        + '&currentHouseId=' + currentHouseId
                        + '&groupBy=' + hdView;
  if(da('showparcel') && searchoption==4)
  {
    if (da('showparcel').checked)
      historydataParameters += "&showparcel=1&showrooms=0";
    if (da('showall').checked)
      historydataParameters += "&showparcel=0&showrooms=0";
//    if (da('showrooms').checked)
//      historydataParameters += "&showparcel=0&showrooms=1";
//    if (da('showboth').checked)
//      historydataParameters += "&showparcel=1&showrooms=1";

  }
  url = "Housing/getHistoryData.aspx";
  found = false;
  for (i=0;i<array_historydata.length;i++)
  {
    if(array_historydata[i]==tabid)
    {
      found = true;
    }
  }
  if((!found && cachetab)||!cachetab)
  {
    da('HDpleaseWait').style.display = 'block';

    array_historydata.push(tabid)
    url= baseUrl + "/ajax/"+url+"?tm=" + new Date().getTime() + "&" + historydataParameters;

    if(currentTab=="last20"){
      xmlHttp = GetXmlHttpObject(gotLast20HistoryData);
       da('HDpleaseWait').style.height = '574px';
    }
    else
    {
      xmlHttp = GetXmlHttpObject(gotHistoryData);
       da('HDpleaseWait').style.height = '500px';
       da('Hd').style.height = '500px';
    }
    xmlHttp.open("GET", url , true)
    xmlHttp.send(null);

    if(currentTab=="main"){
      /*
      //make the seconde request to get the data for the second table
      historydataParameters = historydataParameters.replace('currentTab=main','currentTab=main_last5')
      url = baseUrl + "/ajax/Housing/getHistoryData.aspx";
      url += "?tm=" + new Date().getTime() + "&" + historydataParameters;
      xmlHttpMain2 = GetXmlHttpObject(gotHistoryDataMainLast5);
      xmlHttpMain2.open("GET", url , true)
      xmlHttpMain2.send(null);
      */
    }
  }
}
function selectRow(selectedRow,tabId)
{
  searchoption = da('hiddenCurrentHistoryDataSearchoption').value;
  if(da('hiddenCurrentHistorySelectedRow').value == selectedRow)
    da('hiddenCurrentHistoryIsRowSelected').value = 0;
  else{
    da('hiddenCurrentHistorySelectedRow').value = selectedRow ;
    da('hiddenCurrentHistoryIsRowSelected').value = 1;
  }
  getHistoryData(searchoption,true,tabId);
}
function gotLast20HistoryData()
{
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  {
    if(xmlHttp.responseText != "")
    {

      var response = xmlHttp.responseText;
      var isRowSelected = da('hiddenCurrentHistoryIsRowSelected').value;
      var selectedRow = CalculateSelectedRow();
      var startRow = 1;
      var hDiv = da('hDiv3');
      var hDivChild = document.createElement('div')
      var euroSymbole = '&euro; '
      var tableCelTotal = 'Gem.';

      startRow = parseInt(da('hiddenCurrentHistoryStartRow').value);

      var innerH = '<table id="HdTable3" class="HdTable" cellpadding="0" cellspacing="0"">'
      var allData = response.split(';;');
      for(i= 0;i<allData.length;i++)
      {
        if(i==0)
          innerH += '<tr>'
        //else if((isRowSelected==1) && (selectedRow == i) && (selectedRow!=0))
        //    innerH += '<tr class="HdTableSelectedRow" onclick="selectRow(' + i + ');popup(' + i + ');">'
        else
          innerH += '<tr onclick="popup(' + i + ');">'

        var rowData = allData[i].split('||');

        if(rowData == "")
        {
          innerH += "</tr>";
          continue;
        }
        for(x = 0; x<rowData.length;x++){
          var cellData = rowData[x].split('::')
          //Create table cell with class name
          if (i==0)
          {
            innerH += '<td class="HdTableHeader">';
          }else if((x==0) || (x==2) || (x==3) || (x==4) || (x==5))
            innerH += '<td class="HdTableCellNr">';
          else
            innerH += '<td class="HdTableCell">';

          if(cellData == "") {
            innerH += "</td>";
            continue;
          }

          //populate table cells
          if((x==0) && (i!=0)){
            innerH += '<input id="hiddenLast20SelectedID'+ i +'" type="hidden" value="'+ cellData[1] +'" />' + i ;
          }
          else{
              innerH += cellData[1];
          }

          innerH += '</td>';
        }
        innerH += '</tr>'
      }
      innerH += '</table>'
      hDivChild.innerHTML = innerH;
      clearChilds(hDiv);
      //hDiv.children.clear();
      hDiv.appendChild(hDivChild)
      addTableRolloverEffect('HdTable3','tableRollOverEffect1','tableRowClickEffect1');

      da('HDpleaseWait').style.display = 'none';
    }
  }
}
function clearChilds(n){
if(n.childNodes != null)
  {
  var childs = n.childNodes;
  var nrD = childs.length;
  for(var i = nrD-1; i >= 0; i--) {
      var old = n.removeChild(childs[i]);
    }
  }
}

// Part 2 of Tab 4(Algemeen) : the second ajax call for the Tab 4
function gotHistoryDataMainLast5(){
  if(xmlHttpMain2.readyState ==4 || xmlHttpMain2.readyState=="complete")
  {
    if(xmlHttpMain2.responseText != "" || document.getElementById('hiddenCurrentHistoryTab').value )
    {
      response = xmlHttpMain2.responseText;
      var allHTML= response.split('__');  // allHTML[0] = summary of sold house, allHTML[1] is historytable of last 20 houses sold
      if ((allHTML=="") || (allHTML[0] != 'last5')) return;

      // Create the historytable of last 20 sold houses
      innerH  ="";

      allData = allHTML[1].split(';;');
      var innerH = '<table id="HdTableLast20Tab4" class="HdTable" cellpadding="0" cellspacing="0"">'
      // var allData = response.split(';;');
      for(i= 0;i<allData.length;i++)
      {
        if(i==0)
          innerH += '<tr>'
        //else if((isRowSelected==1) && (selectedRow == i) && (selectedRow!=0))
        //    innerH += '<tr class="HdTableSelectedRow" onclick="selectRow(' + i + ');popup(' + i + ');">'
        else
          innerH += '<tr onclick="popup(' + i + ');">'

        var rowData = allData[i].split('||');

        if(rowData == "")
        {
          innerH += "</tr>";
          continue;
        }
        for(x = 0; x<rowData.length;x++){
          var cellData = rowData[x].split('::')
          //Create table cell with class name
          if (i==0)
          {
            innerH += '<td class="HdTableHeader">';
          }else if((x==0) || (x==2) || (x==3) || (x==4) || (x==5))
            innerH += '<td class="HdTableCellNr">';
          else
            innerH += '<td class="HdTableCell">';

          if(cellData == "") {
            innerH += "</td>";
            continue;
          }

          //populate table cells
          if((x==0) && (i!=0)){
            innerH += '<input id="hiddenLast20SelectedID'+ i +'" type="hidden" value="'+ cellData[1] +'" />' + i ;
          }
          else{
              innerH += cellData[1];
          }

          innerH += '</td>';
        }
        innerH += '</tr>';
      }
      innerH += '</table>';
      da('HistoryTableLast20').innerHTML = innerH;
    }
    addTableRolloverEffect('HdTableLast20Tab4','tableRollOverEffect1','tableRowClickEffect1');
  }
}
function gotHistoryData()
{
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  {

    if(xmlHttp.responseText != "" ||document.getElementById('hiddenCurrentHistoryTab').value )
    {
      var response = xmlHttp.responseText;
      var isRowSelected = da('hiddenCurrentHistoryIsRowSelected').value;

      var selectedTab = da('hiddenCurrentHistoryTab').value;
      var selectedRow = CalculateSelectedRow();
      var startRow = 1;
      var hDiv;
      var hDivChild = document.createElement('div')
      var hChart;
      //var hChartChild = document.createElement('div');
      var euroSymbole = '&euro; '
      var tableCelTotal = 'Gem.';
      var hdView = "kamer"; //default
      if(da('hdtoggleView1').checked == true)
        hdView = "kamer";
      else
        hdView = "area";


      //if (selectedRow ==0) selectedRow = da('currentHouseRooms').value;
      startRow = parseInt(da('hiddenCurrentHistoryStartRow').value);

      var tableName ;
      if (selectedTab == 1)
      {
        tableName = 'HdTable1';
        hDiv = da('hDiv1');
        hChart = da('historyChart1');
        euroSymbole = '&euro; ';
        var tableCelTotal = 'Gem.';
      }
      else if (selectedTab == 4)
      {
        tableName = 'HdTable4';
        hDiv = da('hDiv4');
        hChart = da('historyChart4');
        euroSymbole = '';
        tableCelTotal = 'Totaal';
      }
      else
      {
        tableName = 'HdTable2';
        hDiv = da('hDiv2');
        hChart = da('historyChart2');
        euroSymbole = '';
        tableCelTotal = 'Totaal';
      }
      noData = false; 
      if (document.getElementById('hiddenCurrentHistoryTab').value!=4)
      {
        if (response.indexOf("EmptyData")>-1)
        {
          innerH = "Geen data"
          noData = true;
          hDiv.innerHTML = innerH;
        } else {
          var innerH = '<table id="' + tableName + '" class="HdTable" cellpadding="0" cellspacing="0" width="90%">';
          var allData = response.split(';;');
          for(i= 0;i<allData.length;i++)
          {
            if (i==0)
              innerH += '<tr>';
            else if((isRowSelected==1) && (selectedRow == i) && (selectedRow!=0))
                innerH += '<tr class="HdTableSelectedRow" onclick="selectRow(' + i + ');">';
            else
              innerH += '<tr class="HdTableRow" onclick="selectRow(' + i + ')">';

            if(hdView =='kamer')
            {      //group by rooms
              if(i==0)
                innerH += '<td class="HdTableHeader" width=80><B># kamers</B></td>';
              else if(i == 1)
                innerH += '<td class="HdTableCell" width="100">' + (startRow + i - 1).toString() + ' kamer</td>';
              else
                innerH += i==6?'<td class="HdTableCell" width="100"> '+ tableCelTotal +'</td>':'<td class="HdTableCell" width="100">' + (startRow + i - 1).toString() + ' kamers</td>';
            }else
            {                       //group by area
              var fromArea = ((startRow + i - 1) * 50) - 50;
              var toArea = fromArea + 50;
              if(i==0)
                innerH += '<td class="HdTableHeader" width=80><B>Opp.</B></td>';
              else if(i == 1)
                innerH += '<td class="HdTableCell" width="100"> ' + fromArea.toString() + '-' + toArea.toString() +' m2</td>';
              else
                innerH += i==6?'<td class="HdTableCell" width="100"> ' + tableCelTotal + '</td>':'<td class="HdTableCell" width="100">' + fromArea.toString() + '-' + toArea.toString() +' m2</td>';

            }

            var rowData = allData[i].split('||');
            
            if(rowData == ""){
              innerH += "</tr>";
              continue;
            }

            for(x = 0; x<rowData.length;x++){

              var cellData = rowData[x].split('::')
              innerH += i==0?'<td class="HdTableHeader">':'<td class="HdTableCellNr">';
              //innerH += i!=0?euroSymbole:'';
              if(cellData == "") {
                innerH += "</td>";
                continue;
              }
              innerH += cellData[1];
              innerH += '</td>';
            }
            innerH += '</tr>';

          }
          innerH += '</table>';
          hDiv.innerHTML = innerH;
        }
      }
      else
      {  //  if Tab 4(Algemeen) is selected
        var allHTML= response.split('__');  // allHTML[0] = summary of sold house, allHTML[1] is historytable of last 20 houses sold
        if ((allHTML!="") && (allHTML[0] != 'last5'))
        {
          var innerH = '<table class="HdTable" cellpadding="0" cellspacing="0">';
          if (allHTML[0]!="")
          {
            var allData = allHTML[0].split('||'); // record set
            innerH += '<tr>';
            innerH += '<td class="HdTableHeader"><B>Locatie</B></td>';
            innerH += '<td class="HdTableHeader"><B>Gemiddelde vraagprijs</B></td>';
            innerH += '<td class="HdTableHeader"><B>Aantal</B> <img src="'+baseUrl+'/common/images/icon_hulp.gif" title="header=[Aantal woningen] body=[Aantal gevonden woningen waarvan het gemiddelde wordt berekend]" /></td>';
            innerH += '</tr>';
            text = new Array();
            text[0] = "";
            text[1] = ""; //da('txtStraat').value;
            text[2] = ""; //da('txtPostcode').value;
            text[3] = ""; //da('txtPlaats').value;
            text[4] = "";

            for(i= 0;i<allData.length;i++)
            {
              var rowData = allData[i].split('::'); // rowset
              if (rowData!="endresults")
              {
                innerH += '<tr>';
                innerH += '<td class="HdTableCell" width="250">'+rowData[0]+' '+ text[i] + '</td>';
                innerH += '<td class="HdTableCellNr">' + rowData[1] + '</td>';
                innerH += '<td class="HdTableCellNr">' + rowData[2] + '</td>';
                innerH += '</tr>'
              }
            }

            innerH += '</table>'
            hDivChild.innerHTML = innerH;
            clearChilds(hDiv);
            hDiv.appendChild(hDivChild);
          }
        }
      }

      if(selectedTab != 4) {
        if (!noData)
        {
          // <![CDATA[
          var so = new SWFObject(baseUrl + "/common/swf/History-AvaragePrice.swf", "xmlsource", "500", "250", "1", "#000000");
          so.addParam("wmode", "transparent");
          datum = new Date().getTime();
          tmpurl = baseUrl + "/ajax/Housing/getHistoryData.aspx?output=xml&" + historydataParameters + "&d="+datum;
          url = vervang(tmpurl,"&","$");
          so.addVariable("xmlsource", url);
          so.write(hChart);
          // ]]>
          da('xmlsource').style.display="block";
          da('nodata').style.display="none";
          
          addTableRolloverEffect(tableName,'tableRollOverEffect1','tableRowClickEffect1');
        } else {
          da('nodata').style.display="block";
          da('xmlsource').style.display="none";
        }
  
      }

      setTimeout(function(){
        da('HDpleaseWait').style.display = 'none';
        },1500);

      while(document.title.indexOf('#') > -1) {
        document.title = document.title.replace('#','')
      }

    }
  }
}

function hoverHistoryZoom(e,i)
{
  e.className = "extendHistoryZoomContentMidHover";
  document.getElementById('extendHistoryZoom' + i).src = baseUrl + "/common/images_nieuw/HistoryDateZoomBetweenOver.gif";
}

function outHistoryZoom(e,i)
{
  e.className = "extendHistoryZoomContentMid";
  document.getElementById('extendHistoryZoom' + i).src = baseUrl + "/common/images_nieuw/HistoryDateZoomBetweenOff.gif";

  if(document.getElementById('hiddenCurrentHistoryDataSearchoption').value ==i)
  {
    e.className = "extendHistoryZoomContentMidHover";
    document.getElementById('extendHistoryZoom' + i).src = baseUrl + "/common/images_nieuw/HistoryDateZoomBetweenOn.gif";
  }
}

function showNext()
{
  i = document.getElementById('hiddenCurrentHistoryDataSearchoption').value;
  if(i != 3)
    getHistoryData(parseInt(i)+1);
}

function showPrevious()
{
  i = document.getElementById('hiddenCurrentHistoryDataSearchoption').value;
  if(i != 1)
    getHistoryData(parseInt(i)-1);
}
function showNextRooms()
{
  var i = parseInt(da('hiddenCurrentHistoryStartRow').value);
  da('hiddenCurrentHistorySelectedRow').value = 0;
  i+= 5;
  da('hiddenCurrentHistoryStartRow').value = i;
  getHistoryData(da('hiddenCurrentHistoryDataSearchoption').value);
}

function showPreviousRooms()
{
  var i = parseInt(da('hiddenCurrentHistoryStartRow').value);
  da('hiddenCurrentHistorySelectedRow').value = 0;
  if(i >5)
    i-=5;
  da('hiddenCurrentHistoryStartRow').value = i;
  getHistoryData(da('hiddenCurrentHistoryDataSearchoption').value);
}
function CalculateStartRow(){
  var rooms = da('currentHouseRooms').value;
  var start = 0;
  if((rooms == null) || (rooms < 6))
    start = 1;
  else
    start = Math.round((5*(Math.ceil(rooms/5)-1) +1));

  da('hiddenCurrentHistoryStartRow').value = start
  return start;
}
function toggleHDView(index)
{
  da('hdtoggleView1').checked = false;
  da('hdtoggleView2').checked = false
  da('hdtoggleView' + index).checked = true;
  getHistoryData(da('hiddenCurrentHistoryDataSearchoption').value);
}
function CalculateSelectedRow()
{
  var selectedRow = da('hiddenCurrentHistorySelectedRow').value;
  //var startRow = 1;
  var rooms = da('currentHouseRooms').value;
  if ((rooms == undefined) || (selectedRow == null) || (selectedRow ==0))
  {
    da('hiddenCurrentHistorySelectedRow').value = 0;
    selectedRow = 0
  }else if((rooms != undefined)&&(selectedRow == null) || (selectedRow ==0)){
    selectedRow = Math.round((rooms % 5));
    da('hiddenCurrentHistorySelectedRow').value = selectedRow;
  }else
    da('hiddenCurrentHistorySelectedRow').value = selectedRow;


  return selectedRow;
}

function updateHistoryTab(e,c)
{

  //e = active number
  //c = count of tabs
  for(i=1;i<c+1;i++)
  {
    if (da('HdTab'+i)!=null)
    {
      da('HdTab'+i).className = "VpExtraTab";
      da('HdBarDetail'+i).className = "dn";
    }
  }

  da('HdTab'+e).className = "VpExtraTabActive";
  da('HdBarDetail'+e).className = "db";
  document.getElementById('hiddenCurrentHistoryTab').value = e;

  //Setted values for taxatie, tab 1 and 4
  if((e == 1) || (e == 2))
  {
    da('HDtoggleView').style.zIndex = '200';
    da('htZoom').style.zIndex = '201';
    da('HDtoggleView').style.display = 'block';
    da('htZoom').style.display = 'block';
  }  else {
    da('HDtoggleView').style.zIndex = '-200';
    da('htZoom').style.zIndex = '-200';
    da('HDtoggleView').style.display = 'none';
    da('htZoom').style.display = 'none';
  }
}


var arrayOfRolloverClasses = new Array();
var arrayOfClickClasses = new Array();
var activeRow = false;
var activeRowClickArray = new Array();

function highlightTableRow()
{
  var tableObj = this.parentNode;
  if(tableObj.tagName!='TABLE')tableObj = tableObj.parentNode;

  if(this!=activeRow){
    this.setAttribute('origCl',this.className);
    this.origCl = this.className;
  }
  this.className = arrayOfRolloverClasses[tableObj.id];

  activeRow = this;

}

function clickOnTableRow()
{
  var tableObj = this.parentNode;
  if(tableObj.tagName!='TABLE')tableObj = tableObj.parentNode;

  if(activeRowClickArray[tableObj.id] && this!=activeRowClickArray[tableObj.id]){
    activeRowClickArray[tableObj.id].className='';
  }
  this.className = arrayOfClickClasses[tableObj.id];

  activeRowClickArray[tableObj.id] = this;

}

function resetRowStyle()
{
  var tableObj = this.parentNode;
  if(tableObj.tagName!='TABLE')tableObj = tableObj.parentNode;

  if(activeRowClickArray[tableObj.id] && this==activeRowClickArray[tableObj.id]){
    this.className = arrayOfClickClasses[tableObj.id];
    return;
  }

  var origCl = this.getAttribute('origCl');
  if(!origCl)origCl = this.origCl;
  this.className=origCl;

}

function addTableRolloverEffect(tableId,whichClass,whichClassOnClick)
{
  arrayOfRolloverClasses[tableId] = whichClass;
  arrayOfClickClasses[tableId] = whichClassOnClick;

  var tableObj = document.getElementById(tableId);
  if(tableObj!=null)
  {
    var tBody = tableObj.getElementsByTagName('TBODY');
    if(tBody){
      var rows = tBody[0].getElementsByTagName('TR');
    }else{
      var rows = tableObj.getElementsByTagName('TR');
    }
    for(var no=0;no<rows.length;no++){
      rows[no].onmouseover = highlightTableRow;
      rows[no].onmouseout = resetRowStyle;

      //if(whichClassOnClick){
      //	rows[no].onclick = clickOnTableRow;
      //}
    }
  }
}

function popup(id)
{
  parent.document.getElementById('pleaseWait6').style.display='block';
  var p = document.getElementById('ifrmPopup');
  if(p.style.display != 'none')
  {
    p.style.display = 'none';
  }
  else
  {
    p.style.display = 'block';
  }
  p.width = "400";
  p.height = "300";

  var width =  screen.availWidth||screen.width;
  //var height=  screen.availHeight||screen.height;
  var l=(width-400)/2;
  //var t=(height-300)/2;

  p.style.zIndex = "1000";
  //  p.style.top = (document.body.clientHeight / 2) - (p.clientHeight / 2);
  //  p.style.left = (document.body.clientWidth / 2) - (p.clientWidth / 2);
  p.style.top = 100 + getScrollTop() + 'px';
  p.style.left = l;
  p.src = baseUrl + "/woningpopup.aspx?Id="+ da('hiddenLast20SelectedID' + id).value;
  //p.style.border = "2px solid #999999";
  p.style.border = "none";
  p.style.backgroundColor = '#e0e0e0';
}
