﻿$(document).ready(function() {
    fes_quicksearch_dash.Init();
});

var fes_quicksearch_dash = 
{
    _searchResultPropertiesForSalePageKey : 0,
    _searchResultPropertiesForRentPageKey : 0,
    _searchResultProjectsForSalePageKey : 0,
    _searchResultProjectsForRentPageKey : 0,
    _nvmNumbers : '',
    Init : function (){
        // Click event handlers: hide/show sale/rent prices.
        $("#sys_fgd_input_sale").click(fes_quicksearch_dash.ShowHidePrices);
        $("#sys_fgd_input_rent").click(fes_quicksearch_dash.ShowHidePrices);
        $("#sys_fgd_input_project").click(fes_quicksearch_dash.ShowHidePrices);
        $("#sys_fgd_input_project_rent").click(fes_quicksearch_dash.ShowHidePrices);
        
        // Show sale prices as default.
        $("#sys_fgd_input_sale").attr('checked', 'checked');
        fes_quicksearch_dash.ShowHidePrices();    
        
        $("#sys_fgd_input_price_sale_start").change(fes_quicksearch_dash.ValidateSalePriceSelection);
        $("#sys_fgd_input_price_sale_end").change(fes_quicksearch_dash.ValidateSalePriceSelection);
        $("#sys_fgd_input_price_rent_start").change(fes_quicksearch_dash.ValidateRentPriceSelection);
        $("#sys_fgd_input_price_rent_end").change(fes_quicksearch_dash.ValidateRentPriceSelection);
        
        if(fes_quicksearch_dash._searchResultPropertiesForRentPageKey > 0)
        {
            $("#sys_fgd_label_rent").show(); 
            $("#sys_fgd_input_rent").show(); 
        }
        if(fes_quicksearch_dash._searchResultProjectsForSalePageKey > 0)
        {
            $("#sys_fgd_label_project").show(); 
            $("#sys_fgd_input_project").show(); 
        }
        if(fes_quicksearch_dash._searchResultProjectsForRentPageKey > 0)
        {
            $("#sys_fgd_label_project_rent").show(); 
            $("#sys_fgd_input_project_rent").show(); 
        }      
    },
    ShowHidePrices : function(){    
        if(( $("input[name='sys_fgd_radio_type']:checked").val() == 'rent') ||
            ( $("input[name='sys_fgd_radio_type']:checked").val() == 'project_rent'))
        {
            $('#sys_fgd_label_price_rent_start').show(); 
            $('#sys_fgd_input_price_rent_start').show(); 
            $('#sys_fgd_label_price_rent_end').show(); 
            $('#sys_fgd_input_price_rent_end').show(); 
            $('#sys_fgd_label_price_sale_start').hide(); 
            $('#sys_fgd_input_price_sale_start').hide(); 
            $('#sys_fgd_label_price_sale_end').hide(); 
            $('#sys_fgd_input_price_sale_end').hide(); 
        }    
        else{
            $('#sys_fgd_label_price_sale_start').show(); 
            $('#sys_fgd_input_price_sale_start').show(); 
            $('#sys_fgd_label_price_sale_end').show(); 
            $('#sys_fgd_input_price_sale_end').show(); 
            $('#sys_fgd_label_price_rent_start').hide(); 
            $('#sys_fgd_input_price_rent_start').hide(); 
            $('#sys_fgd_label_price_rent_end').hide(); 
            $('#sys_fgd_input_price_rent_end').hide();
        }
    
        if(mapsdash) // Does this page contains the FES_GOOGLE_DASHBOARD module?
        {
            mapsdash.ShowGoogleDashboard($("input[name='sys_fgd_radio_type']:checked").val());
        }
    },
    ValidateSalePriceSelection : function(){ 
       var minValue = parseInt($("#sys_fgd_input_price_sale_start").val());
       var maxValue = parseInt($("#sys_fgd_input_price_sale_end").val());
       if (minValue > maxValue){
        $("#sys_fgd_input_price_sale_end").val(minValue);
       }
    },
    ValidateRentPriceSelection : function(){ 
       var minValue = parseInt($("#sys_fgd_input_price_rent_start").val());
       var maxValue = parseInt($("#sys_fgd_input_price_rent_end").val());
       if (minValue > maxValue){
        $("#sys_fgd_input_price_rent_end").val(minValue);
       }  
    },
    StartSearch : function(){  
        var pageKey; 
        var iMinValue;
        var iMaxValue; 
        var searchType
        var postcodePlace = $("#sys_fgd_city").val();
    
        if( $("input[name='sys_fgd_radio_type']:checked").val() == 'sale') {
            pageKey = fes_quicksearch_dash._searchResultPropertiesForSalePageKey;
            iMinValue = $("#sys_fgd_input_price_sale_start").val();
            iMaxValue = $("#sys_fgd_input_price_sale_end").val();
            searchType = 'sale';
        }
        else if($("input[name='sys_fgd_radio_type']:checked").val() == 'rent') {
            pageKey = fes_quicksearch_dash._searchResultPropertiesForRentPageKey;
            iMinValue = $("#sys_fgd_input_price_rent_start").val();
            iMaxValue = $("#sys_fgd_input_price_rent_end").val();
            searchType = 'rent';
        }
        else if($("input[name='sys_fgd_radio_type']:checked").val() == 'project_rent') {
            pageKey = fes_quicksearch_dash._searchResultProjectsForRentPageKey;
            iMinValue = $("#sys_fgd_input_price_rent_start").val();
            iMaxValue = $("#sys_fgd_input_price_rent_end").val();
            searchType = 'project_rent';
        }
        else{
            pageKey = fes_quicksearch_dash._searchResultProjectsForSalePageKey;
            iMinValue = $("#sys_fgd_input_price_sale_start").val();
            iMaxValue = $("#sys_fgd_input_price_sale_end").val();
            searchType = 'project';
        }
        
        var iRangeValue = $("#sys_fgd_input_range").val();

        postcodePlace = fes_quicksearch_dash.CleanUpSearchInput(postcodePlace);
        if(IsNumeric(postcodePlace))
        {
            document.location.href = "/default.aspx?pageKey="+ pageKey +"&minPrice=" + iMinValue + "&maxPrice=" + iMaxValue + "&placeOrZip=" + postcodePlace.toUpperCase() +"&range=" + iRangeValue + "&type=" + searchType + "&SearchInputPage=1&Display=map";
        }
        else
        {
           document.location.href = "/default.aspx?pageKey="+ pageKey +"&minPrice=" + iMinValue + "&maxPrice=" + iMaxValue + "&city=" + postcodePlace.toUpperCase() +"&range=" + iRangeValue + "&type=" + searchType + "&SearchInputPage=1&Display=map";
        }
    },
    CleanUpSearchInput : function(searchInputText){  
        if(searchInputText.Length <= 0){
            return '';}
        
        // Check if first char is a numeric char. If not return searchInputText.
        var validChars = "0123456789";
        if(validChars.indexOf(searchInputText[0]) == -1){
            return searchInputText;}
        
        
        // Cleanup input string number by removing all invalid (none-numeric) chars.
        var result = '';
        for (i = 0; i < searchInputText.length; i++) 
        { 
            var c = searchInputText.charAt(i); 
            if (validChars.indexOf(c) == -1) 
            {
                return result;
            }
            else
            {
                result = result + c;
            }
        }
        return result;
    }
}

var _placesOriginalArray
var _places = new Array()
var _placesArray = new Array()
var _hover = -1
var _cancelEnterSubmit = false
var _focused = true
var _browserOk = window.ActiveXObject || window.XMLHttpRequest
var _show = false;
var _lasturl = '';	
var IE = ( navigator.appVersion.indexOf("MSIE") != -1 )
var IE50 = ( navigator.appVersion.indexOf("MSIE 5.0") != -1 )
var _previousRequest = '';

function GetSuggestions(event, nvmNumbers){ 
    if (event){
        if ((event.keyCode == 13) || (event.keyCode == 34) || (event.keyCode == 33) || (event.keyCode == 40) || (event.keyCode == 38)){
            // Enter key was pressed. Go to result page.
            //redirect(url1);  
	        return false;
	    }
	    
	    inputcontrol = document.getElementById('sys_fgd_city'); 
	    
	    if (inputcontrol.value.length == 0) 
		{
    		Hide();
		    return true;    		
		}
	    
	    var nLeft = GetElementLeft(inputcontrol);
		var nTop = GetElementTop(inputcontrol) + GetElementHeight(inputcontrol);
		var nWidth = GetElementWidth(inputcontrol) - 2;
		
	    document.getElementById('Lijst').style.left = nLeft + 'px';
	    document.getElementById('Lijst').style.top = nTop + 'px';	
        document.getElementById('Lijst').style.width = nWidth + 'px';

	    document.getElementById('iFrame').style.left = nLeft + 'px';
	    document.getElementById('iFrame').style.top = nTop + 'px';
        document.getElementById('iFrame').style.width = nWidth + 'px';

	    document.getElementById('FrameContainer').style.left = nLeft + 'px';
	    document.getElementById('FrameContainer').style.top = nTop + 'px';
        document.getElementById('FrameContainer').style.width = nWidth + 'px';
        
        
	    // Create callback url.		    
	    var currentRequest = "/modules/fes_quicksearch_dashboard/callback.ashx?action=autoComplete";
	    currentRequest += "&plaats=" + $("#sys_fgd_city").val()[0];
	    currentRequest += "&type=" + $("input[name='sys_fgd_radio_type']:checked").val();
	    currentRequest += "&nvmNumbers=" + nvmNumbers;
	    currentRequest += "&filter=";
	    
	    if(currentRequest == _previousRequest)
	    {
	        FilterPlaatsen()
	        document.body.onkeydown = KeyDown;
			document.body.onkeyup = KeyUp;	
			document.body.onkeypress = CheckKeypress;
			document.body.onclick = DocumentClick;
			$("#Lijst").show(); 
	    }
	    else
	    {
	        _previousRequest = currentRequest;
	        var request = makeHttpObject();	
		    request.open("GET", currentRequest, true);
		    request.send(null);
		    request.onreadystatechange = function()
		    {
			    if (request.readyState == 4) {
				    _placesOriginalArray = request.responseText.split(',')
				    FilterPlaatsen()
				    document.body.onkeydown = KeyDown;
				    document.body.onkeyup = KeyUp;	
				    document.body.onkeypress = CheckKeypress;
				    document.body.onclick = DocumentClick;
				    $("#Lijst").show(); 
			    }
		    }
		}		
	}
}

function KeyDownLink(i)
{
	if ( parseInt(document.getElementById('Lijst').scrollTop) < -36 + i*16 ) document.getElementById('Lijst').scrollTop = -36 + i*16
	if ( parseInt(document.getElementById('Lijst').scrollTop) > i*16 ) document.getElementById('Lijst').scrollTop = i*16
	MouseOverLink(i)
	return false;
}

function DocumentClick()
{
	if ( !_browserOk ) return
	Hide()
}

function CheckKeypress(e)
{
    var key = window.event ? window.event.keyCode : e.which;

	if ( !_browserOk ) return
	if ( _show == true )
	{
	    if ( key == 40 ) return false
	    if ( key == 38 ) return false
	}
	return true
}

function KeyDown(e)
{
    var key = window.event ? window.event.keyCode : e.which;

	if ( key == 13 )
	{
		_cancelEnterSubmit = _show
	}
	else
	{
		_cancelEnterSubmit = false
	}
	if ( key == 34 ) GoDown(4)
	if ( key == 33 ) GoUp(4)
	if ( key == 40 ) GoDown(1)
	if ( key == 38 ) GoUp(1)
}

function KeyUp(e)
{
  	var key = window.event ? window.event.keyCode : e.which;
	if ( key == 13 ) Enter()
	if ( key == 27 ) Enter()
	if ( key == 9 ) Enter()
}

function Enter(bEnter)
{
   	if ( !_browserOk ) return
	if ( _show == true )
	{
        CheckAutocompleteSubmit();
		Hide()
		$("#sys_fgd_city").focus()
	}
}

function GoDown(n)
{
	if ( !_browserOk ) return
	if ( _focused == false ) return
	if ( _show == false ) Check()
	n = _hover + n
	if ( !window.itemCount ) return
	if ( n > itemCount-1 )
	{
		n = 0
	}
	KeyDownLink(n)
}

function GoUp(n)
{
	if ( !_browserOk ) return
	if ( _focused == false ) return
	if ( _show == false ) Check()
	n = _hover - n
	if ( n < 0 )
	{
		n = itemCount-1
	}
	KeyDownLink(n)
}

function CheckAutocompleteSubmit()
{
	if (( _focused == true && _show == true ) || _cancelEnterSubmit == true )
	{
		Hide();
		$("#sys_fgd_city").val(_places[_hover]);
		_cancelEnterSubmit = false;
		return false;
	}
	
	return CheckInput()
 }

function Click(s)
{
    $("#sys_fgd_city").val(s);
	_show = false
	document.getElementById('Lijst').style.display = 'none'
	if ( IE && !IE50 ) document.getElementById('FrameContainer').style.display = 'none'
	$("#sys_fgd_city").focus()
}

function IsNumeric(sText)
{
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) 
    { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) 
        {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function MouseOverLink(i)
{   
	if ( _hover > -1 )
	{
		if ( document.getElementById('Link' + _hover) ) document.getElementById('Link' + _hover).className = 'gewoon'			
	}
	_hover = i
	if ( i != -1 )
	{
		if ( document.getElementById('Link' + i) ) document.getElementById('Link' + i).className = 'LinkHover'				
	}							
}
function FilterPlaatsen()
{
	sString = $("#sys_fgd_city").val().toLowerCase()
	if ( _placesOriginalArray ) _placesArray = CopyArray(_placesOriginalArray)
	for ( i=_placesArray.length-1; i>-1; i-- )
	{
		if ( _placesArray[i].substring(0, sString.length).toLowerCase() != sString ) Sloop(_placesArray, i)
	}
	SetList()
}

function Sloop(_placesArray, i)
{
	for(n=i; n<_placesArray.length-1; n++)
	{
		_placesArray[n] = _placesArray[n+1]
	}
	_placesArray.length --
}	

function CopyArray(aArray)
{
	var newArray = new Array()
	for(i=0;i<aArray.length;i++)
	{
		newArray[i] = aArray[i]
	}
	return newArray
}

function Hide()
{
	document.body.onkeydown = null;
	document.body.onkeyup = null;	
	document.body.onkeypress = null;
	document.body.onclick = null;	
	_show = false
	$("#Lijst").hide(); 
    $("#FrameContainer").hide(); 
}

function makeHttpObject() {
  try {return new XMLHttpRequest();}
  catch (error) {}
  try {return new ActiveXObject("Msxml2.XMLHTTP");}
  catch (error) {}
  try {return new ActiveXObject("Microsoft.XMLHTTP");}
  catch (error) {}

  throw new Error("Could not create HTTP request object.");
}

function SetList()
{
    $("#Lijst").html('');

	itemCount = _placesArray.length > 5 ? 5 : _placesArray.length
	
	if ( _placesArray[0] != '' )
	{
		_hover = -1
		s = '<table cellpadding=0 cellspacing=0 style="width:' + '100%' + ';">'
		for(i=0;i<itemCount;i++)
		{
			var placesList = _placesArray[i]
			sAantal = placesList.substring(placesList.indexOf('|')+1, placesList.length)
			placesList = placesList.substring(0, placesList.indexOf('|'))
			placeSlash = placesList.replace('\'', '\\\'')
			_places[i] = placesList
			s += '<tr class="gewoon" id="Link' + i + '" onmouseover="MouseOverLink(' + i + ')" onclick="Click(\'' + placeSlash + '\')">' 
			s += '<td class="plaats" title="' + placesList + ', ' + sAantal + ' woningen"><span class="aantal" style="float:right;">' + sAantal + '</span>' + placesList + '</td>'
			s += '</tr>'
		}
		s += '</table>'
		$("#Lijst").html(s);
					
		_show = true
		document.getElementById('Lijst').style.display = 'block'
		document.getElementById('Lijst').style.position = 'absolute'			
		if ( IE && !IE50 ) document.getElementById('FrameContainer').style.display = 'block'
	}
	else
	{
		Hide()
	}
	if ( IE && !IE50 ) document.getElementById('iFrame').style.height = (document.getElementById('Lijst').clientHeight+2) + 'px'
	if ( itemCount == 0 ) Hide()
	MouseOverLink(0)
}

function GetElementLeft(m_elem)
{
    var x = 0;
    var elem;		
    if(typeof(m_elem) == "object")
	    elem = m_elem;
    else
	    elem = document.getElementById(m_elem);
		
    while (elem != null)
    {
	    x += elem.offsetLeft;
	    elem = elem.offsetParent;
    }
    return parseInt(x);
}

function GetElementTop(m_elem)
{
    var y = 0;
    var elem;
    if(typeof(m_elem) == "object")
    {
	    elem = m_elem;
    }
    else
    {
	    elem = document.getElementById(m_elem);
    }
    while (elem != null)
    {
	    y+= elem.offsetTop;
	    elem = elem.offsetParent;
    }
    return parseInt(y);
}

function GetElementWidth(m_elem)
{
    var elem;
    if(typeof(m_elem) == "object")
    {
	    elem = m_elem;
    }
    else
    {
	    elem = document.getElementById(m_elem);
    }
    return parseInt(elem.offsetWidth);
}

function GetElementHeight(m_elem)
{
    var elem;
    if(typeof(m_elem) == "object")
    {
	    elem = m_elem;
    }
    else
    {
	    elem = document.getElementById(m_elem);
    }
    return parseInt(elem.offsetHeight);
}	
