$(function() {

/*var*/g_enable_javascript = true
     , g_smooth_slider = true
     , g_smooth_slider_increment = 10000
     , g_smooth_scroll = !$.browser.msie
     , g_twitter_feed_scroll_interval_ms = 7000


if(!g_enable_javascript)
	return
    
    /**
    * Add String.trim() funcionality to IE
    */
    if(typeof String.prototype.trim !== 'function') {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, '');
        }
    }

function clamp($l, $v, $u) { return Math.max($l, Math.min($v, $u)) }

/**
* Google maps integration
*/

var geocoder;
var map;
var markers = Array();
//var bounds;
var bounds_set = false;

var marker_image = '/images/maps/huis_icon.png';


/**
* small map on detail page
*/

if($('#map').hasClass('gmap_detail'))
{
    var detailOptions = {
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        panControl: false,
        zoomControl: false,
        mapTypeControl: false,
        streetViewControl: false
        
    }
    map = new google.maps.Map($('#map')[0], detailOptions);
    
    
    var address = $('#map').attr('address');
    var lat = $('#map').attr('lat');
    var lng = $('#map').attr('long');
    
    if(lat != undefined && lng != undefined) {
        var location = new google.maps.LatLng(lat,lng);
        
        var marker = new google.maps.Marker({
            map: map,
            position: location,
            title: address,
            icon: marker_image
        });
        detailOptions['center'] = location;
        
        map.setCenter(location);
        
    } else {
        geocoder.geocode({ address: address } , function(results, status){
         
            if(status == google.maps.GeocoderStatus.OK) {
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: results[0].formatted_address,
                    icon: marker_image
                });
                map.setCenter(results[0].geometry.location);
            }
        });
    }
}





/**
* search maps
*/



function initMap() {
    geocoder = new google.maps.Geocoder();
    
    bounds_set = false;
    
    if($('#map').hasClass('gmap_big')) {
        var myOptions = {
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            panControl: true,
            zoomControl: true,
            mapTypeControl: false,
            streetViewControl: false
        }
    }
    else {
        var myOptions = {
            zoom: 16,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            panControl: false,
            zoomControl: false,
            mapTypeControl: false,
            streetViewControl: false
        }
    }
    map = new google.maps.Map($('#map')[0], myOptions);
    
    setTimeout(function() {addMarkers()}, 2000)    
    
}

function addMarkers() {
    $('.estate_item').each(function() {
        
        if($('#map').hasClass('gmap_big')) {
            var address = $(this).html();
            var lat = $(this).attr('lat');
            var long = $(this).attr('long');
            var url = $(this).attr('title');
        }
        else {
            var address = $(this).find('.information a>h2')[0].innerHTML;
            var lat = $(this).find('.information a.property_information').attr('lat');
            var long = $(this).find('.information a.property_information').attr('long');
            var url = $(this).find('.information a.detaillink').attr('href');
        }
        var id = $(this).attr('rel');
        if(markers[id] == undefined) {
            if(lat != undefined && long != undefined) {
                createMarker(new google.maps.LatLng(lat,long), address, id, url);
            } else {
                geocoder.geocode({ address: address } , function(results, status){
                 
                    if(status == google.maps.GeocoderStatus.OK) {
                        createMarker(results[0].geometry.location, results[0].formatted_address, id, url);
                        
                    }
                });
            }
        }
    })
}

function createMarker(location, address, propertyId, url) {
    var marker = new google.maps.Marker({
        map: map,
        position: location,
        title: address,
        icon: marker_image
    });
    
    if($('#map').hasClass('gmap_big')) {
        var img_url = $('.estate_item[rel='+propertyId+']').attr('img');
        
        var price = $('.estate_item[rel='+propertyId+']').attr('price');
        var surface = $('.estate_item[rel='+propertyId+']').attr('surface');
        var roomcount = $('.estate_item[rel='+propertyId+']').attr('roomcount');
        var contentString = '<div style="width:400px;height:100px;"><div id="siteNotice"></div><h2>' + address + '</h1><div id="bodyContent"><p><img style="margin-right: 10px; float: left" src="'+ img_url + '" alt="' + address + '" /> ' + price + '<br />'  + surface +  ' m<sup>2</sup><br />'  + roomcount + ' kamers</p></div></div>';
        var info_window = new google.maps.InfoWindow({
            

            content: contentString
        });
        
        google.maps.event.addListener(marker, "mouseover", function () {
            //map.setCenter(location);
            info_window.open(map, marker);
        })
        google.maps.event.addListener(marker, "mouseout", function () {
            info_window.close();
        })
        
        google.maps.event.addListener(marker, "click", function () {
            info_window.close();
            document.location.href=url;
        })
        
    }
    else {
    
        $('li.estate_item[rel='+propertyId+']').bind('mouseenter',function(ev) {
            map.setCenter(location);
            //info_window.open(map, marker);
            marker.setAnimation(google.maps.Animation.BOUNCE);
        })
        $('li.estate_item[rel='+propertyId+']').bind('mouseleave', function(ev) {
            //info_window.close();
            map.setCenter(location);
            marker.setAnimation(null);
        })
        google.maps.event.addListener(marker, "click", function () {
            document.location.href=url;
        })
    }
    if(!bounds_set) {
        //bounds.extend(location);
        map.setCenter(location)
        bounds_set = true;
    }
    //map.fitBounds(bounds);
    markers[propertyId] = marker;
    
}

function removeMarkers() {
    for(var i=0; i < markers.length; i++) {
        if(markers[i]) {
            markers[i].setMap(null);
        }
    }
    markers = Array();
}

// page refresh setup map
if($('#estate_bar').hasClass('fully_visible')) {
    initMap();    
}

if($('.ranges').length > 0) {
    convertRangesToSliders();
}

/**
* User interaction - filters
*/
function filterSlider(el, event, ui) {
    id = $(el).attr('id');
    values = $(ui).attr('values');
    
    start = values[0];
    end = values[1];
    
    $.ajax({
            url: '/property/search',
            cache: false,
            data:   { key: id, start: start, end: end, bar: $('#estate_bar').hasClass('fully_visible')},
            success: function (data) {
                updateSearchResults(data);
            }
    });
}

$('#address_search_remove').live('click', function(el) {

    $.ajax({
            url: '/property/removeAddressSearch',
            cache: false,
            data:   { bar: $('#estate_bar').hasClass('fully_visible')},
            success: function (data) {
                updateSearchResults(data);
            }
    });
});

$('#filter_query_remove').live('click', function() { remove_query($(this)) }); 

$('#filter_query_submit').live('click', function() { filter($('#filter_query')) });

$('#estate_bar_left_filter input[type=checkbox],#home_filterbox input[type=checkbox], #settings_page input[type=checkbox]').live('click', function() { filter($(this)) });
$('input[type=radio]').live('click', function() { filter($(this)) });
$('select[id=filter_region]').live('change', function() { filter($(this)) });

function remove_query(el) {
    name = $(el).attr('name');
    
    $.ajax({
            url: '/property/search',
            cache: false,
            data:   { key: 'filter_remove_query', value: name, checked: 'false', bar: $('#estate_bar').hasClass('fully_visible')},
            success: function (data) {
                updateSearchResults(data);
            }
    });
}

function filter(el) {
    value = $(el).val();
    name = $(el).attr('name');
    checked = $(el).is(':checked');
    $.ajax({
            url: '/property/search',
            cache: false,
            data:   { key: name, value: value, checked: checked, bar: $('#estate_bar').hasClass('fully_visible')},
            success: function (data) {
                if($('#settings_filter_city').size() > 0) {
                    $.ajax({
                        cache: false,
                        url: '/index/filterCityAjax',
                        success: function(data) {
                            $('#settings_filter_city').replaceWith(data);
                        }
                    })
                }
                if(name == 'filter_region') {
                    $.ajax({
                        cache: false,
                        url: '/index/attentionListAjax',
                        success: function(data) {
                            $('#home_top3').replaceWith(data);
                        }
                    })
                    
                    $.ajax({
                        cache: false,
                        url: '/index/regionCampaignAjax',
                        success: function(data) {
                            $('ul.campaign_list').replaceWith(data);
                        }
                    })
                }
                updateSearchResults(data);
            }
    });
}

function updateSearchResults(data) {

    
    if($('#estate_bar').hasClass('fully_visible')) {
        $('#estate_bar_content_outer [id^=estate_bar_content]').replaceWith(data);
        removeMarkers();
        
        if($('#noresults').size() > 0) {
            $('#estate_bar_right').hide();
        }
        else {
            $('#estate_bar_right').show();
            initMap();
        }
    }
    else {
        $('.small_estate_list').replaceWith(data);
        centerMiniBar();
    }
    
    // scroll to top smoothly after selecting filters
    var css = { 'scrollTop' : '0px' }
    g_smooth_scroll ? $('#estate_bar_content_wrap').stop(true, false).animate(css, 'normal')
                    : $('#estate_bar_content_wrap').css(css)
    
    $.ajax({
            url: '/property/searchcountAjax',
            cache: false,
            success: function (data) {
                $('h2.estate_count').replaceWith(data);
            }
    });
    
    if($('#estate_bar').hasClass('fully_visible')) {
        
        $.ajax({
                url: '/property/searchupdateFilters',
                cache: false,
                success: function (data) {

                    $('#estate_bar_left_filter').html(data);
                    convertRangesToSliders();
                }
        });
    }
    
}

/** address search @home **/
$('#filter_address_postalcode')
    .data('timeout', null)
    .live('keyup change',function(){
        clearTimeout(jQuery(this).data('timeout'));
        jQuery(this).data('timeout', setTimeout(searchByPostalcode, 500));
    });

$('#filter_address_street')
    .data('timeout', null)
    .live('keyup change',function(){
        clearTimeout(jQuery(this).data('timeout'));
        jQuery(this).data('timeout', setTimeout(searchByStreet, 500));
    });

$('#filter_address_housenumber')
    .data('timeout', null)
    .live('keyup change',function(){
        clearTimeout(jQuery(this).data('timeout'));
        jQuery(this).data('timeout', setTimeout(searchByStreet, 500));
    });

$('#filter_address_city')
    .data('timeout', null)
    .live('keyup change',function(){
        clearTimeout(jQuery(this).data('timeout'));
        jQuery(this).data('timeout', setTimeout(searchByStreet, 500));
    });

$('#filter_address_development')
    .data('timeout', null)
    .live('keyup change',function(){
        clearTimeout(jQuery(this).data('timeout'));
        jQuery(this).data('timeout', setTimeout(searchByDevelopment, 500));
    });

function searchByPostalcode() {
    var params = {
        postalcode: $('#filter_address_postalcode').val()
    };

    $('#fieldset_development span.result_count').removeClass('active');
    $('#fieldset_address span.result_count').removeClass('active');
    $('#fieldset_development span.result_count h2').html("");
    $('#fieldset_address span.result_count h2').html("");

    if(params.postalcode.length >= 3) {
        searchByAddressParams(params, 1);
    }
    else {
        $('#fieldset_postalcode span.result_count').removeClass('active');
        $('#fieldset_postalcode span.result_count h2').html("");
    }
}

function searchByStreet() {
    var params = {
        street: $('#filter_address_street').val(),
        housenumber: $('#filter_address_housenumber').val(),
        city: $('#filter_address_city').val()
    };

    $('#fieldset_postalcode span.result_count').removeClass('active');
    $('#fieldset_development span.result_count').removeClass('active');
    $('#fieldset_postalcode span.result_count h2').html("");
    $('#fieldset_development span.result_count h2').html("");

    if(params.street.length >= 3 || params.housenumber.length >= 3 || params.city.length >= 3) {
        searchByAddressParams(params, 2);
    }
    else {
        $('#fieldset_address span.result_count').removeClass('active');
        $('#fieldset_address span.result_count h2').html("");
    }
}

function searchByDevelopment() {
    var params = {
        development_name: $('#filter_address_development').val()
    };
    $('#fieldset_postalcode span.result_count').removeClass('active');
    $('#fieldset_address span.result_count').removeClass('active');
    $('#fieldset_postalcode span.result_count h2').html("");
    $('#fieldset_address span.result_count h2').html("");

    if(params.development_name.length >= 3) {
        searchByAddressParams(params, 3);
    }
    else {
        $('#fieldset_development span.result_count').removeClass('active');
        $('#fieldset_development span.result_count h2').html("");
    }
}

function searchByAddressParams(searchParams, searchType) {

    $.ajax({
            url: '/property/searchByAddress',
            cache: false,
            data:   { params: searchParams, type: searchType, bar: $('#estate_bar').hasClass('fully_visible')},
            success: function (data) {
                updateSearchResults(data);


                if(searchType == 1) {
                    $('#fieldset_postalcode span.result_count').addClass('active');
                } else if(searchType == 2) {
                    $('#fieldset_address span.result_count').addClass('active');
                } else if(searchType == 3) {
                    $('#fieldset_development span.result_count').addClass('active');
                }
            }
    });
}

$('.filter_tabs li').live('click', function() {
    switchHomeBox($(this).attr('id').substring(3));
})

function switchHomeBox(name) {
    if(! $('#li_'+name).hasClass('active')) {
        $('ul.filter_tabs li').removeClass('active');

        $('#li_'+name).addClass('active');
        $('div.box_content').addClass('hidden');


        $.ajax({
            url: '/property/searchTypeSwitch',
            cache: false,
            data:   { iType: $('#li_'+name).attr('rel'), bar: $('#estate_bar').hasClass('fully_visible')},
            success: function (data) {
                updateSearchResults(data);
            }
        });
        if($('#li_'+name).attr('rel') == 1) {
            $('#form_address span.result_count').removeClass('active');
            $('#form_address span.result_count h2').html("");
            $('#form_address input').val("");
        }

        $('#div_'+name).removeClass('hidden');
    }

}

/**
* Slide to bottom -> get more properties
*/
function getMore(el) {
    
    $.ajax({
            url: '/property/searchmoreAjax',
            cache: false,
            success: function (data) {
            
                
                $('#loading_icon').remove()
                var strdata = data;
                if(strdata.trim() == '') {
                    $('a.shown_all').removeClass("invisible");
                    $('a.show_more_houses').addClass("invisible");
                }
                else {
                    $(el).parent().find('ul.estate_list').append(data);
                    $(el).data('disabled', false).show()
                    setTimeout(function() {addMarkers()}, 3000)
                }
                    
                    // Scroll down to the new houses
                    //        $('#estate_bar_content_wrap').animate({
                    //            scrollTop : $('#estate_bar_content_outer').height()
                    //        }, 'normal')
            }
    });
}

/**
* User interaction - sorting
*/

$('.estate_bar_sort_type a').live('click', function() { sort($(this)) });

function sort(el) {
    if($(el).hasClass('active')) {
        $(el).toggleClass('sort_asc sort_desc');
        if($(el).hasClass('sort_desc'))
            dir = "desc";
        else
            dir = "asc";
        $.ajax({
                url: '/property/search',
                cache: false,
                data:   { sort: $(el).attr('id'), dir: dir},
                success: function (data) {
                    updateSearchResults(data);
                }
        });
        
        
    } else {
        $('.estate_bar_sort_type a.active').removeClass('active sort_asc sort_desc');
        $(el).addClass('active sort_asc');
        $.ajax({
                url: '/property/search',
                cache: false,
                data:   { sort: $(el).attr('id'), dir: 'asc'},
                success: function (data) {
                    updateSearchResults(data);
                }
        });
    }
}


/**
* 
*/        
function redirect_search() { 
    $.ajax({
        url: '/index/getlastsearchpageAJAX',
        cache: false,
        dataType: 'json',
        success: function(data) {
            document.location = data.last;
        }
    })
 }
function redirect_back() { 
    $.ajax({
        url: '/index/getlastpageAJAX',
        cache: false,
        dataType: 'json',
        success: function(data) {
            document.location = data.last;
        }
    })
}

	/**
	 * Format a number the nice way (thousand separator) etc.
	 * http://phpjs.org/functions/number_format:481
	 */
function number_format(number, decimals, dec_point, thousands_sep)
{
    number = (number+'').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }    return s.join(dec);
}

	/**
	 * Replacing select boxes by range sliders
	 * Assumptions:
	 * - that the first and second select boxes contain the same values,
	 *   only the values of the first select box are used to create the
	 *   slider
	 * - the interval (step size) is chosen as the smallest difference
	 *   between two consecutive values of the select box, so for instance
	 *   a select box containing 50 100 200 and 500 as values will create
	 *   a slider with 50 100 150 200 250 300 350 400 450 and 500 as
	 *   possible values (due to a limitation of jquery slider)
	 */
function convertRangesToSliders () {
    $('.ranges').each(function(idx) {
	    var $this = $(this)
	    var $select_boxes = $this.find('select')
	    
	    // Hide select boxes and replace them with a range slider
	    var slider_id = 'slider_' + $select_boxes.first().attr('id')
	    $select_boxes.css({ 'display' : 'none', 'visibility' : 'hidden' }).last().after('<div id="' + slider_id + '"></div>')
	    var $slider = $('#' + slider_id);
        
        if ($this.hasClass('single'))
            single = true;
        else
            single = false;
        
        var minimal = parseInt($(this).find('option.minimal').val())
	    var maximal = parseInt($(this).find('option.maximal').val())
	    var minstep = parseInt($(this).find('option.step').val())
        
        var value1 = parseInt($(this).find('option.value1').val())
        if(isNaN(value1))
            value1 = minimal;
        
        var value2 = parseInt($(this).find('option.value2').val())
        if(isNaN(value2))
            value2 = maximal;
        
	    if (g_smooth_slider)
		    minstep = Math.min(g_smooth_slider_increment, minstep)
	    
	   var fn_movelabels = function (event, ui) {
		    var $handles = $slider.find('.ui-slider-handle')
		      , $labels = $slider.data('labels_exist') ? $slider.parent().find('.value_label') : $slider.find('.value_label')
 		      , $label_min = $labels.first()
		      , $label_max = $labels.last()
		      , prepend = append = ''
		      , values = ui.values || $slider.slider('values')
		    
		    if ($this.hasClass('euro'))
			    prepend = '€'

		    if ($this.hasClass('square_meter'))
			    append = ' m²'

		    $label_min.text(prepend + number_format(values[0], 0, ',', '.') + append)
		    $label_max.text(prepend + number_format(values[1], 0, ',', '.') + append)

	    }
	    
		    // Invoke jquery ui to create the range slider
	    $slider.slider({
		     'range' : true
		    ,'min' : minimal
		    //,'animate' : true
		    ,'max' : maximal
		    ,'orientation' : 'horizontal'
		    ,'values' : [value1, value2]
		    ,'step' : minstep
		    ,'create' : function(event, ui) {
			    $slider.prepend(
				    '<div class="left_corner"></div>'
		  	      + '<div class="right_corner"></div>'
			    )
			    
			    var labels_exist = $slider.parent().find('.value_label').length == 2
			    if (!labels_exist)
				    $slider.prepend(
					    '<span class="value_label value_min"></span>'
				      + '<span class="value_label value_max"></span>'
				    )
			    
			    $slider.data('labels_exist', labels_exist)
			    fn_movelabels(event, ui)
		    }
		    ,'slide' : fn_movelabels
		    ,'stop' : function(event, ui) {
			    fn_movelabels(event, ui)
			    
			    filterSlider($(this), event, ui);
		    }
	    })
	    
	    var $handles = $slider.find('.ui-slider-handle')
	      , $labels = $slider.parent().find('.value_label')
	    
	    $labels.last().css({ 'right' : '-20px' })
		    /**
		     * Only 1 select box means: no range but simply a single value
		     * so hide the second slider handle
		     */
	    if (single) {
		    $handles.last().hide()
		    $labels.last().hide()
	    }
    })
}

	/**
	 * Estate search -> load extra houses
	 */
$('a.show_more_houses').live('click.showmore', function(ev) {
	var $this = $(this)
	
	if($this.data('disabled'))
		return;
		// Disable this link
	$this.data('disabled', true)
		.hide()
		.after($('<img id="loading_icon" />').attr('src', 'images/icons/loading.gif')
		.css({'display' : 'block', 'margin' : '15px auto', 'float' : 'none'}))
        
    getMore($this);
	
	ev.preventDefault()
})

	/**
	 * Estate photos -> load extra houses
	 */
$('ul.estate_photo_list a.show_more_houses').live('click.showmore', function(ev) {
	var $this = $(this)
	  , $estate_list = $('ul.estate_list')
	
	
	if($this.data('disabled'))
		return;
		
		// Disable this link
	$this.data('disabled', true).hide()
		.after($('<img id="loading_icon" />').attr('src', 'images/icons/loading.gif')
		.css({'display' : 'block', 'margin' : '15px auto', 'float' : 'none', 'clear' : 'both'}))
        
    getMore($this);
	
	ev.preventDefault()
})

	/**
	 * Estate bar sliding up (messy)
	 */
$('#estate_bar_handle, #estate_bar_openlink, #menu_open_estatebar').click(function(ev) {
	var $estate_bar = $('#estate_bar')
	$estate_bar.css({ 'z-index' : 1000 }).find('.small_estate_list').remove()
	$estate_bar
		.append($('<div></div>').css({
			 'background-color' : '#f3f3f3'
			,'height' : '100%'
			,'width' : '100%'
			,'margin-top' : '85px'
		}))
		.animate({
				 'height': ($(window).height() - 125) + 'px'
		}, 'normal', function() {
			redirect_search()
		})
	ev.preventDefault()
})

	/**
	 * Estate bar sliding down 
	 */
$('#estate_bar_closelink').click(function(ev) {
	var $estate_bar = $('#estate_bar')
	  , $estate_bar_content_wrap = $('#estate_bar_content_wrap')

	$estate_bar_content_wrap.animate({ 'top' : $(window).height() + 'px' })
	$estate_bar.animate({
		'top': ($(window).height() - 104) + 'px'
	}, 'normal', function() { redirect_back() })
	ev.preventDefault()
})

$('a.detaillink').live('click', function(ev) {
    var $estate_bar = $('#estate_bar')
      , $estate_bar_content_wrap = $('#estate_bar_content_wrap')

    var el = $(this);
    
    $estate_bar_content_wrap.animate({ 'top' : $(window).height() + 'px' })
    $estate_bar.animate({
        'top': ($(window).height() - 118) + 'px'
    }, 'normal', function() { document.location.href = $(el).attr('href'); })
    ev.preventDefault()
})

	/**
	 * Fancy scrolling of the leftmost filter bar (always in view)
	 */
$('#estate_bar_content_wrap').scroll(function() {
	
	if (typeof arguments.callee.prevScrollTop == 'undefined')
		arguments.callee.prevScrollTop = 0
	
	var $this = $(this)
	  , $estate_bar_right = $('#estate_bar_right')
	  , $estate_bar_left_filter = $('#estate_bar_left_filter')
	  , $estate_bar_content_outer = $('#estate_bar_content_thin')
	  , delta_scroll = $(this).scrollTop() - arguments.callee.prevScrollTop
	
		// Right bar is easy, just keep it at the top
	var css = { 'top' : ($this.scrollTop() + 10) + 'px' }
	g_smooth_scroll ? $estate_bar_right.stop(true, false).animate(css)
					: $estate_bar_right.css(css)

		// Left bar is a different story (we want special behavior)
	var max_bar_top = $estate_bar_content_outer.height()
					- $estate_bar_left_filter.height()
	
     
	var clipped_top    = $this.scrollTop()
					   - $estate_bar_left_filter.position().top
	  , clipped_bottom = $estate_bar_left_filter.height()
					   - $this.height()
					   - clipped_top
	  , at_top = clamp(10, $this.scrollTop() + 10, max_bar_top)
	  , at_bottom = clamp(10, $this.scrollTop() - $estate_bar_left_filter.height() + $this.height(), max_bar_top)
    
    

	if (delta_scroll > 0 && clipped_bottom <= 0) {
		var css = { 'top' : ($estate_bar_left_filter.height() < $this.height() ? at_top : at_bottom) + 'px' }
		
		g_smooth_scroll ? $estate_bar_left_filter.stop(true, false).animate(css)
						: $estate_bar_left_filter.css(css)
	}
	
	if (delta_scroll < 0 && clipped_top <= 0) {
		var css = { 'top' : at_top + 'px' }
		
		g_smooth_scroll ? $estate_bar_left_filter.stop(true, false).animate(css)
					    : $estate_bar_left_filter.css(css)
	}

	$a_show_more_houses = $('a.show_more_houses')
	if ($a_show_more_houses.position() != null && $a_show_more_houses.position().top + $a_show_more_houses.outerHeight() <= $this.scrollTop() + $this.height())
		$a_show_more_houses.trigger('click')

	arguments.callee.prevScrollTop = $this.scrollTop()
})

	/**
	 * Hovers that pop out the top of a link
	 */
$('.popup_top .popup').attr('title', '').live({
		'mouseenter' : function() {
			var $this = $(this)
			  , idx = $('.popup_top .popup').index(this)
			$('#tooltip' + idx).remove()
			$('<div class="tooltip tooltip_top invisible" id="tooltip' + idx + '" />')
				.append($this.find('.popup_information').clone().removeClass('invisible'))
				.append('<img src="/images/backgrounds/popup/top_handle.png" />')
				.appendTo('body')
		},
		'mouseleave' : function() {
			$('#tooltip' + $('.popup_top .popup').index(this)).fadeOut('fast', function() {
				$(this).remove()
			})
		},
		'mousemove' : function(e) {
			var idx = $('.popup_top .popup').index(this)
			  , $tt = $('#tooltip' + idx)
			  , ttw = $tt.outerWidth()
			  , httw = ttw / 2
			  , dw = $(window).width()
			$('#tooltip' + idx).css({
			 	top : e.pageY - $tt.outerHeight() - 10 + 'px'
				,left : clamp(0, e.pageX - httw - 7, dw - ttw) + 'px'
			}).removeClass('invisible')
			$('#tooltip' + idx + ' img').css({
				left : httw + Math.min(0, e.pageX - httw) + Math.max(0, httw - (dw - e.pageX + 15)) + 'px'
			})
		}
})


	/**
	 * Hovers that pop out the right side of a link
	 */
$('.popup_side .popup').attr('title', '').live({
	'mouseenter' : function() {
		var $this = $(this)
		  , idx = $('.popup_side .popup').index(this)
		$('#tooltip' + idx).remove()	
			$('<div class="tooltip tooltip_side invisible" id="tooltip' + idx + '" />')
				.append($this.find('.popup_information').clone().removeClass('invisible'))
				.append('<img src="/images/backgrounds/popup/side_handle.png" />')
				.appendTo('body')
	},
	'mouseleave' : function() {
		$('#tooltip' + $('.popup_side .popup').index(this)).fadeOut('fast', function() {
			$(this).remove()
		})
	},
	'mousemove' : function(e) {
		var $tooltip = $('#tooltip' + $('.popup_side .popup').index(this))
		$tooltip.css({
			 top : (e.pageY - ($tooltip.outerHeight() - $tooltip.height()) / 2 - 15)  + 'px'
			,left : clamp(0, e.pageX + 15, document.width - $('#tooltip' + idx).outerWidth()) + 'px'
		}).removeClass('invisible')
	}
});

	/**
	 * Center mini estate bar (only on detail page)
	 */
(function(is_estate_detail) {	
	var $small_estate_list = $('ul.small_estate_list')
	  , $active_house = $small_estate_list.find('li.active')
	  , item_width = $('ul.small_estate_list > li:first-child').outerWidth()
	  , num_estate = $('ul.small_estate_list > li').length + 1

	$small_estate_list.css({
		 'width' : (num_estate * item_width) + 'px'
		,'overflow' : 'visible'
	})
	
	if (is_estate_detail)
		$small_estate_list.css({
			'margin-left' : (-$active_house.prevAll('li').length * item_width + $small_estate_list.parent().width() / 2 - 50) + 'px'
		})
    
    if (!is_estate_detail) {
        centerMiniBar();
    }
})(window.location.toString().split('/').slice(-1)[0].match(/detail/))


/**
* center mini estate bar on other pages
*/
function centerMiniBar() {
    item_width = $('ul.small_estate_list > li:first-child').outerWidth()
    num_estate = $('ul.small_estate_list > li').length + 1 
    $('ul.small_estate_list').css({
        'margin-left' : (($('ul.small_estate_list').parent().width() - (num_estate * item_width) + 50) / 2) + 'px'
    })
}

	/**
	 * Filled in values for input fields disappear when field is clicked
	 * (only the first time the field is clicked)
	 */
$('input[type=text].validate').live('mousedown', function(ev) {
	var $this = $(this)
	if ($this.data('not_first_click'))
		return
	$this.val('').data('not_first_click', true)
});

	

	/**
	 * Mini slideshows
	 */
$('ul.slideshow.multiple').live('mouseenter', function(e) {
	var $this = $(this)

	fn_next = function() {
		var $active = $this.children('.visible')
		  , $next = ($active.next('li').length != 0)
				  ? $active.next('li')
				  : $this.children().first()
		$active.removeClass('visible')
		$next.addClass('visible')
	}
	$this.data('timeout', setInterval(fn_next, 1000))
}).live('mouseleave', function() {
	var $this = $(this)
 	  , $active = $this.children('.visible')
	  , $original = $this.children('.original')
	$active.removeClass('visible')
	$original.addClass('visible')
	clearInterval($(this).data('timeout'))
})

// load slideshow
$('ul.slideshow.single').live('mouseenter', function(e) {
    var el = $(this)
    
    if($('#estate_bar').hasClass('fully_visible'))
        var barSize = "big";
    else
        var barSize = "small";
        
    var id = $(el).attr('rel');
    
    $.ajax({
                url: '/property/slideshowAjax',
                cache: false,
                data:   { iProperty: id, sBarSize: barSize},
                success: function (data) {
                    $(el).replaceWith(data);
                }
        });
})

	/**
	 * Overlay
	 */
window.show_overlay = function (content, fn_callback) {
	destroy_overlay()
	window.is_overlay_active = true
	$('body').append(
		$('<div id="overlay_outer"></div>')
	).append(
		$('<div id="overlay_content_container"></div>')
			.click(function() { window.destroy_overlay() })
	)
	var $overlay_outer = $('#overlay_outer')
	  , $container = $('#overlay_content_container')
	$overlay_outer.fadeTo('normal', .8, function() {
		$container.append(
			$('<div id="overlay_content"></div>')
				.click(function(ev) { ev.stopPropagation() })
				.append($('<a id="overlay_close"><h2 style="color:#cb0000">Sluit dit venster</h2></a>')
					.css({
				 		'position' : 'absolute'
						,'right' : '20px'
						,'top' : '10px'
					})
				)
				.append(content)
		)
		
		$('#overlay_close').unbind('click').click(function () { window.destroy_overlay() })
		
		if (typeof fn_callback == 'function')
			fn_callback()
		
		fn_resize_overlay()
	})
}

var fn_resize_overlay = function()
{
	var $overlay_outer = $('#overlay_outer')
	  , $overlay_content = $('#overlay_content')
	  , clip_bottom = $overlay_content.outerHeight(true) - $overlay_outer.height()
	  , $photo_more = $overlay_content.find('div.photo_more')

	$overlay_content.css({
		'height' : Math.min($overlay_content.height() - clip_bottom, 610) + 'px'
	})

	$photo_more.css({
		top : ($overlay_content.offset().top + $overlay_content.outerHeight() - 100) + 'px'
	})
}

window.is_overlay_active = false

window.destroy_overlay = function () {
	window.is_overlay_active = false
	$('#overlay_outer').remove()
	$('#overlay_content_container').remove()
}

$(window).resize(function () {
	if (!window.is_overlay_active)
		return
	fn_resize_overlay()
})

	/**
	 * Filter formulier, click huurwoning -> disable prijsklasse
	 */
$('#filter_rental').click(function() {
	
	if (this.checked) {
		var $fieldset = $('#fieldset_priceclass')
		$fieldset.addClass('disabled')
		$fieldset.find('.ui-slider').slider('disable')
		if ($fieldset.hasClass('hide_on_disable'))
			$fieldset.parent().slideUp()
	} else {
		var $fieldset = $('#fieldset_priceclass')
		$fieldset.removeClass('disabled')
		$fieldset.find('.ui-slider').slider('enable')
		if ($fieldset.hasClass('hide_on_disable'))
			$fieldset.parent().slideDown()
	}
});

/**
*  Home campaign button
$('#home_actie_link.lightbox').live('click', function(e) {
    var url = $(this).attr('rel');
    show_overlay($('#lightbox_campaign').clone().removeClass('invisible').attr('id', ''), function() {
        $('#overlay_content_container iframe').html('').attr('src', url);
    });
    e.preventDefault();
    return false;
});
*/

	/**
	 * Home twitter feed
(function() {

    if($("ul#twitter_update_list").length == 0)
        return;

    var $this = $('#twitter_feed ul')
    
    var fn_next = function() {
        var $active = $this.children('.active')
          , $next = ($active.next('li').length != 0)
                  ? $active.next('li')
                  : $this.children().first()
        $active.fadeOut('fast', function() {
            $(this).removeClass('active')
            $next.slideDown('slow', function() {
                $(this).addClass('active')
            })
        })
    }

    $.getScript("http://twitter.com/javascripts/blogger.js");
    $.getScript("http://twitter.com/statuses/user_timeline/benopzoek.json?callback=twitterCallback2&count=10", function() {
        setInterval(fn_next, g_twitter_feed_scroll_interval_ms)
        
        $("ul#twitter_update_list li:first").addClass("active");
    });
})();
*/

/**
*  open right photo in gallery when clicking on main photo
*/   
$('#estate_information a.lightbox').live('click', function() {
    $('#photo_box li[rel=main] a.lightbox').trigger('click');
})

/**
 * Detail lightbox foto
 */
$('#photo_box a.lightbox').unbind('click').click(function() {
	var $this = $(this)
	var $clone = $('#lightbox_slideshow').clone().attr('id', '')
	show_overlay($clone.removeClass('invisible').attr('id', ''), function() {
		
		$photo_list = $('#overlay_content_container ul.photolist')
		$photo_list.css({ 'width' : ($photo_list.find('li').length * $photo_list.find('li').outerWidth()) + 'px' })
		
		var fn_activate = function ($which, idx) {

			var $photo_list = $('#overlay_content_container ul.photolist')
			  , item_width = $which.outerWidth()
			  , num_photo = $photo_list.find('li').length

			$('#overlay_content_container div.photo img').fadeOut('normal', function() {
				$(this).attr('src', $which.find('img').attr('rel')).fadeIn('normal')
			})

			$photo_list.find('li').removeClass('active')
			$which.addClass('active')

			$photo_list.animate({
				'margin-left' : ($which.prevAll('li').length * -$which.outerWidth() + $photo_list.parent().width() / 2 - 60) + 'px'	
			})
		}

		$('#overlay_content_container a.lightbox').click(function (ev) {

			ev.preventDefault()

			var $this = $(this)
			  , rel = $this.attr('rel')
			  , $active_li = $('#overlay_content_container li.active')
			  , active = parseInt($active_li.index()) + 1
			  , $li = $(this).parent()

			if (rel == 'prev') {
				if ($active_li.prev().length == 0)
					return
				$li = $active_li.prev()
				rel = active - 1
			}

			if (rel == 'next') {
				if ($active_li.next().length == 0)
					return
				$li = $active_li.next()
				rel = active + 1
			}

			fn_activate($li, rel)
		})
		
		$('#overlay_content_container a.lightbox[rel=' + $this.attr('rel') + ']').trigger('click')
	})
});

/**
* rental interest
*/
$('#button_rental_interest').unbind('click').click(function() {
    show_overlay($('#lightbox_rental_interest').clone().removeClass('invisible').attr('id', ''))
});

/**
 * google maps lightboxes
 */
$('#button_streetview').unbind('click').click(function() {
	show_overlay($('#lightbox_streetview').clone().removeClass('invisible').attr('id', ''))
});

$('#button_maps').unbind('click').click(function() {
	show_overlay($('#lightbox_googlemaps').clone().removeClass('invisible').attr('id', ''))
});

/**
 * Detail lightbox description
 */
$('#description_box a#description').unbind('click').click(function() {
	show_overlay($('#lightbox_description').clone().removeClass('invisible').attr('id', ''))
});

/**
 * Detail lightbox available properties
 */
$('#description_box a#available').unbind('click').click(function() {
    show_overlay($('#lightbox_subproperties').clone().removeClass('invisible').attr('id', ''))
});

/**
*  Extra options lightbox (floorplanner, video, etc)
*/
$('#extra_options_box a').unbind('click').click(function(e) {
    var url = $(this).attr('rel');
    show_overlay($('#lightbox_tool').clone().removeClass('invisible').attr('id', ''), function() {
        $('#overlay_content_container iframe').html('').attr('src', url);
    });
    e.preventDefault();
});



    /**
     * product video lightbox / home videobox
     */
    $('#frame .promotions_list .active a.action, #home_colgroup a.movie, #estate_bar .promotions_list .active a.action')
    .live('click', function(ev) {
        var el = $(this)
        ev.preventDefault()
        show_overlay($('#lightbox_video').clone().removeClass('invisible'), function() {
            $('#overlay_content_container .video_main[rel='+$(el).attr('rel')+']').removeClass('invisible');
            $('#overlay_content_container .video_main[rel='+$(el).attr('rel')+'] div.video iframe').attr('src',$('#overlay_content_container .video_main[rel='+$(el).attr('rel')+'] div.video').attr('rel'));
            $('#overlay_content_container a.movie').click(function() {
                
                var video = $(this).attr('rel');
                $('#overlay_content_container .video_main').toggleClass('invisible', true);
                $('#overlay_content_container .video_main[rel='+video+']').removeClass('invisible');
                $('#overlay_content_container .video_main[rel='+video+'] div.video iframe').attr('src',
                    $('#overlay_content_container .video_main[rel='+video+'] div.video').attr('rel') );
                
            })
        })
    })
    
    
    /**
    * contact forms
    */
    
    /**
    * Property interest form
    */
    
    $('#form_property_interest').bind('submit', function(ev) {
        var formValid = doFormValidate();
        
        if(formValid) {
            $(this).find('button').attr('disabled',true);
            $(this).find('button').hide();

            if($(this).find('input[name=agent]').val() == 1) {
                _gaq.push(['_trackEvent', 'Contact aanvraag Makelaar', 'Klik verstuur contactaanvraag makelaar']);
            } else {
                _gaq.push(['_trackEvent', 'Contact opnemen Alliantie', 'Klik verstuur contactaanvraag Alliantie']);
            }


        
            $.ajax({
                type: 'POST',
                cache: false,
                url: '/property/mailPropertyInterestAjax',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(data) {
                    if(data.success) {
                        $('#form_property_interest').replaceWith('<p id="interest_thanks">Bedankt voor uw aanvraag. Uw formulier is in goede orde bij ons ontvangen.</p>');
                    }
                }
            });
        }  else {
            alert("Er zijn nog fouten gevonden, controleer de velden");
        }
        ev.preventDefault();
    });
    
    /**
    * Contact form
    */
    
    $('#form_contact_us').bind('submit', function(ev) {
        var formValid = doFormValidate();
        
        if(formValid) {
            $(this).find('button').attr('disabled',true);
            $(this).find('button').hide();

            _gaq.push(['_trackEvent', 'Contact opnemen Alliantie', 'Klik verstuur contactaanvraag Alliantie']);
        
            $.ajax({
                type: 'POST',
                cache: false,
                url: '/page/mailContactFormAjax',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(data) {
                    if(data.success) {
                    
                        $('#contact_form').html('<h2>Het contactformulier is verstuurd. We nemen spoedig contact met u op!</h2>');
                    }
                }
            });
        } else {
            alert("Er zijn nog fouten gevonden, controleer de velden");
        }
        ev.preventDefault();
    });
    
    /**
    * Newsletter signup form
    */
    
    $('#form_newsletter').bind('submit', function(ev) {
        var formValid = doFormValidate();
        
        if(formValid) {
            
            $(this).find('button').attr('disabled',true);
            $(this).find('button').hide();

            _gaq.push(['_trackEvent', 'Inschrijving nieuwsbrief', 'Klik verstuur nieuwsbriefinschrijving']);
        
            $.ajax({
                type: 'POST',
                cache: false,
                url: '/index/signupNewsletterAjax',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(data) {
                
                    if(data.success) {
                        $('#form_newsletter').replaceWith('<p id="newsletter_thanks">U heeft zich aangemeld voor de nieuwsbrief. Deze kunt u configureren via een link in de bevestigingse-mail die u heeft ontvangen.</p>');
                    }
                }
            });
        } else {
            alert("Er zijn nog fouten gevonden, controleer de velden");
        }
        ev.preventDefault();
    });
    
    /**
    * Newsletter settings form
    */
    
    $('#form_newsletter_settings').bind('submit', function(ev) {
        var formValid = doFormValidate();
        
        if(formValid) {
        
            $.ajax({
                type: 'POST',
                cache: false,
                url: '/index/saveNewsletterSettings',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(data) {
                    if(data.success) {
                        $('p.saved').remove();
                        $('#settings_page h1').append('<p class="saved" style="font-weight:bold;"><br />Uw instellingen zijn gewijzigd</p>')
                    }
                }
            });
        } else {
            alert("Er zijn nog fouten gevonden, controleer de velden");
        }
        ev.preventDefault();
    });
    
    
    /** generic form validate function **/
    
    function doFormValidate() {
    
        var formValid = true;
        $('input[type=text].validate, textarea.validate').each(function() {
            var $this = $(this)
              , $img = $this.parent().find('img')
              , valid = $this.attr('value').length > 3
            
            if ($this.attr('id').match(/telephone/))
                valid = $this.attr('value').match(/^\d{10}$/)
            
            if ($this.attr('id').match(/mail/))
                valid = $this.attr('value').match(/^[^@]+@[^.@]+\.\w+$/)
            if(!valid)
                formValid = false;

            if (($this.hasClass('valid') || $this.hasClass('not_valid'))) {
		        $this.removeClass('valid').removeClass('not_valid')
            }

            valid && $this.addClass('valid') || $this.addClass('not_valid')
                
            valid && $img.attr('src', '/images/icons/check_10x10.png')
                          || $img.attr('src', '/images/icons/warning.png')
                    $this.parent().find('img').css({'display' : 'block'})
        });
        
        return formValid;
    
    }
    
    /**
     * Form validation
     * (just the visual aspect)
     */
    (function() {
        $('input[type=text].validate, textarea.validate').each(function() {

            var fn_validate = function(e) {
                var $this = $(this)
                  , valid = $this.attr('value').length > 1
                
                if ($this.attr('id').match(/telephone/))
                    valid = $this.attr('value').match(/^\d{10}$/)
                
                if ($this.attr('id').match(/mail/))
                    valid = $this.attr('value').match(/^[^@]+@[^.@]+\.\w+$/)
                
                    // always update the icon upon losing focus
                    // also update the icon if it is already visible while typing
                if (e.type == 'blur' || ($this.hasClass('valid') || $this.hasClass('not_valid')) && e.type == 'keyup') {
		    $this.removeClass('valid').removeClass('not_valid')
                    valid && $this.addClass('valid') || $this.addClass('not_valid')
                }
            }
        
            $(this).keyup(fn_validate).blur(fn_validate)
        })
    })()

	$('#home_slideshow a').click(function(ev) {
		var $this = $(this)
		  , $list = $this.siblings('ul').first()
		  , $cur = $list.children('.active')
		  , $next = null
		  , rel = $this.attr('rel')

		if ($list.children(':animated').length > 0)
			return

		if (rel == 'next') {
			$next = $list.children('.active').next()
			if ($next.length == 0)
				$next = $list.children().first()
		}
		if (rel == 'prev') {
			$next = $list.children('.active').prev()
			if ($next.length == 0)
				$next = $list.children().last()
		}

		var dir = rel == 'next' ? -620 : 620

		$list.children().stop(true, true)

		$cur.animate({ 'left' : dir + 'px'  }, 'normal', 'swing', function() {
			$cur.removeClass('active').css({ 'left' : 0 })
		})
		$next.css({ 'left' : (-1 * dir) + 'px' }).addClass('active').animate({ 'left' : 0 }, 'normal', 'swing', function() {
			$next.addClass('active')
		})

		ev.preventDefault()
	})

	if ($('#home_slideshow').length > 0)
		setInterval(function() { $('#home_slideshow a.next_link').trigger('click')  }, 7500);
    

});	//	$(function() {


function initForm(sFormId, sDivId){
    
    $('#' + sFormId).submit(function(){
        submitForm(sFormId, sDivId);
        return false;
    });
    
}

function submitForm(sFormId, sDivId){
    
    disableSubmit(sDivId);

    if($('#' + sFormId).attr('id') == "form_property_rental_interest") {
        _gaq.push(['_trackEvent', 'Reactie op woning', 'Klik verstuur reactie op woning']);
    }
    var aData = {};
    $('#' + sFormId + ' input').each(function(){
        
        if($(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio'){
            if($(this).attr('checked')) aData[this.name] = $(this).val();
        }
        else aData[this.name] = $(this).val();
        
    });
    $('#' + sFormId + ' textarea').each(function(){
        if($(this).attr('class').match(/tinymce/g)) aData[this.name] = tinyMCE.get($(this).attr('id')).getContent();
        else                                        aData[this.name] = $(this).val();
    });
    $('#' + sFormId + ' select').each(function(){
        aData[this.name] = $(this).val();
    });
    
    sUrl = $('#' + sFormId).attr('action');
    if(sUrl.match(/\?/g)) sUrl = sUrl + '&random=' + Math.floor(Math.random() * 10001);
    else                  sUrl = sUrl + '?random=' + Math.floor(Math.random() * 10001);
    
    $('#' + sDivId).load(sUrl, aData, function(){
        
    });
    
}


function disableSubmit(sDivId) {
    $('#'+sDivId).find('button').hide();
}


