var locID = 2;
var locCO = 2;
var amBOX = 400;
var amCountdown;
var amCountdownTotal = 4;
var gemeentes = new Array();
var xmlgemeentes = new Object();
var xmlgemeentesARR = new Array();
var list_pdf_url='';
var copyClip;
var copyClip2;

var amaiboxdata_form_criteria = new Array();
var amaiboxdata_form_zoekopdracht = new Array();
var amaiboxdata_form_delen = new Array();

var ajaxRequest;
var click_first_result=false;

var locationXMLloader=false;

var initialPageLoad=true;

var resultHideDetail = false;
var resultHideDetailIE = false;

var slidingResults = true;

var motorAdvancedActive = false;

var activeEstateDetail;

var getDrawing=false;

$(document).ready(function()
{
	//console.profile();
  //INITflashbg();
	INITcufon();
	INITblankLinks();
	INITmenu();
	INITcheckboxes();
	INITselectboxes();
	INITsliders();
	INITlocations();
	INITmotorMenu();
	INITadvSearch();
  	INITresult_projectImgNav();
	INITresult_projectFields();
	INITprojectMenu();
	INITpages();
	INITscrollup();
	INITtooltip();
	INITamaibox();
	INITnewprojects();
	INITtriangle();
	INITresults();
	INITshadowboxBtns();
	INITclock();
	//removeActiveMenu();
// 	INITaddressFader();
	INITaddressHover();
	INITaddressSlider();
	INITsortOptions();
	INITIEfixes();
	INITsetmotormode();
	INITResetButton();
	INITPoleScroll();
	$('.magazine-items').magazineSlider();
	
	Shadowbox.init(
	{
		overlayOpacity:0,
		displayNav:false,
		displayCounter:false,
		continuous:true,
		troubleElements:["select", "object", "embed"],
		onOpen:function(){
			desaturate();
			setTimeout('desaturate(true)', 500);
			$('#sb-wrapper').append('<a href="#" id="amai_close"></a>');
			$('#sb-wrapper').append('<a href="#" id="amai_next"></a>');
			$('#sb-wrapper').append('<a href="#" id="amai_prev"></a>');
		},
		onClose:function(){
			reset_img();
			$('#amai_close').remove();
			$('#amai_next').remove();
			$('#amai_prev').remove();
		},
		onChange:function(){
			$('#amai_close').hide();
			$('#amai_next').hide();
			$('#amai_prev').hide();
		},
		onFinish:function(){
			$('#amai_close').slideDown(300);
			$('#amai_next').show();
			$('#amai_prev').show();
		}
	});

	//INITresultDetailMenu();
	//console.profileEnd();
	
    INITContactAndSchattingForm();
    
      
  //rotator img
		setInterval( "slideHomeImg()", 5000);
		
		//rotator txt
		setInterval( "slideHomeTxt()", 3000);
		
		$('#home a.newestate').die().live('click', function(e) {
      e.preventDefault();
      $.address.value('newestate');
    } );
    
    $('#home a.schatting').die().live('click', function(e) {
      e.preventDefault();
      $.address.value('schatting');
    } );
    
    $('#home a.woonkrant').die().live('click', function(e) {
      e.preventDefault();
      $.address.value('woonkrant');
    } );
    
   $('.project_sh a').die().live( 'click', function(e) {
      e.preventDefault();
      $.address.value('second_home/'+$(this).attr('rel'));
   } );
   
   if ( typeof(showChildID)!='undefined' )
   {
    if(document.location.hash=='')
    {
      showChild(showChildID);
    }    
   }
  $('#w_content #result-detail, #w_content #result-detail-options').addClass('js');
  $('#w_content #wrap-results #result-detail, #w_content #wrap-results #result-detail-options').addClass('js');

  $(window).mouseover( function(){    
    var wrap_main=$('#wrap_main').height();
    var window = $(this).height();
    
    if (wrap_main<window)
    {
      var height=window;
    }
    else
    {
      var height=wrap_main;
    }
    $('#wrap_sketch div').css('height', height );
  } );
  
  $('.spr').click( function(){
    var $this=$(this);
    var id=$this.attr('id');
    if ( $this.children('input').length==0 )
    {
      var input=$('<input class="inputPrice inputPrice'+id+'" type="text">');
      $this.append(input);
      input.focus();
      input.keydown( function(e){        
        if (( parseInt(e.keyCode)==13 ) || ( parseInt(e.keyCode)==27 )) // enter or escape
        {
          sumbitPricerangeInput();
        }
        if ( parseInt(e.keyCode)==9 )
        {
          var parent=$(this).parent().attr('id');
          if ( parent=='spr1' )
          {
            $('#spr2 span').trigger('click');
            setTimeout( function(){
              $('#spr2 input').focus();
            }, 500 );
          }
          if ( parent=='spr2' )
          {
            $('#spr1 span').trigger('click');
            setTimeout( function(){
              $('#spr1 input').focus();
            }, 500 );
          }
        }
      } );      
    
    $('html').bind('click.priceRangeInput', function(e){        
        if ( ! $(e.target).parents().hasClass('spr') )
        {
          sumbitPricerangeInput();
        }
      } );
    
    
    }    
  } );
  
  function sumbitPricerangeInput()
  {
      var inputs=$('.spr input');
          inputs.each( function(){
            var $this=$(this);
            var value=parseInt($this.val());            
            var target=$this.parent().attr('id');
            
            var pricerange=motor_model.getPriceRange();
            
            if ( target=='spr1' )
            {
              if ( value<pricerange[1] )
              {
                motor_model.setPriceRange( value, pricerange[1] );
              }              
            }  
            if ( target=='spr2' )
            {
              if ( value>pricerange[0] )
              {
                motor_model.setPriceRange( pricerange[0], value );
              }              
            }
        		var pricerange=motor_model.getPriceRange();
            
            
              if ( $.browser.msie )
        			{              
        			 $("#slider-prijs").slider( "option", "values", [sliderScale.getScale( pricerange[0] ), sliderScale.getScale( pricerange[1] ) ]);
              }
              else
              {              
        			               
               $("#slider-prijs").slider2( "option", "values", [sliderScale.getScale( pricerange[0] ), sliderScale.getScale( pricerange[1] ) ]);        			 
              }
           
          } );
          inputs.remove();
          $('html').unbind('click.priceRangeInput');
          $.address.parameter('param', motor_model.getJSON() );
  }
  
  
      
      
      
  
});

function INITContactAndSchattingForm()
{

  	  $('#contactpage-form, #schatting-form').bind('submit', function(e) {
      
      e.preventDefault();
      var ok=true;
      var input = $(this).find('input[type=text]');
      input.each( function() {
        var id = $(this).attr('id');

        $(this).next('span').removeClass('error');
        if ( $(this).val()==$('label[for='+id+']').text() )
        {
          $(this).next('span').addClass('error');
          ok=false;
        }        
      } );
     
      $('#f3').removeClass('error');
      if ( ! echeck($('#f3').val()) )
      {
        $('#f3').addClass('error');
        $('#f3').next('span').addClass('error');
        ok=false;
      }
      
//       $('#f9').next('span').removeClass('error');
//       if ( $('#f9').val()=='' )
//       {
//         $('#f9').next('span').addClass('error');
//         ok=false;
//       }
      
      if (ok)
      {
        $.ajax({
          type: 'POST',
          url: base_url+'submitContact',
          data: $(this).serialize()
        });
        
        displayBox(base_url+'box_confirmation');
     
        $('#amaiboxcontent #bevestiging').css({'display':'none'});
        $('#amaiboxcontent #bevestiging').fadeIn(1000);
                      							
        if ( ! $.browser.msie){                  							
         	Cufon.replace('#amaiboxcontent h1');
          Cufon.replace('#amaiboxcontent h2');
        }
        amCountdown = setInterval ( "countdown()", 1000);
        countdown();
        
        input.each( function() {
          $(this).val('');
          $(this).trigger('blur');          
        });
        
        $('#f9').val('');
      }  
      return false;    
     });

    
    $('p.titles select').amaiSelect();
    
}

function showChild(id)
{
  $('#result-overview-holder .result').each( function() {
    $this=$(this);
    link=$this.children('a.result-l');
    if ( link.attr('rel') == id )
    {
      link.click();
    }
    else
    {
      $(this).remove();
    }
  } );
}

function INITclock()
{
  var v = { };
	var p = { allowFullScreen:'false', wmode:'transparent' };
	var a = { id:'clock_flash' };
	swfobject.embedSWF(base_url+"assets/swf/clockx3.swf", "clock", "143", "45", "9.0.0", false, v, p, a );
}

function INITflashbg()
{
	var v = { };
	var p = { scale:'noScale', salign:'lt', menu:'false', allowFullScreen:'false', wmode:'transparent' };
	var a = { id:'sketch', name:'sketch' };
	swfobject.embedSWF(base_url+"assets/swf/sketch.swf", "wrap_sketch_holder", "1200px", "100%", "9.0.0", false, v, p, a );
}
function INITcufon()
{
	if ( ! $.browser.msie){
  Cufon.replace('h2');
	Cufon.replace('.menu li a');
	Cufon.replace('#wmr_menu h3');
	Cufon.replace('#address-hover');
	Cufon.replace('#motor_op1 ul.topmenu li a');
	Cufon.replace('#motor_opt1_boxes label');
	Cufon.replace('#motor_op1 .it-arr');
// 	Cufon.replace('#motor_op4 .it-arr');
	Cufon.replace('#motor_op4 p');
	Cufon.replace('#motor_op1 p');
	Cufon.replace('#motor_op4 .adv_op_desc');	
	Cufon.replace('#motor_op4 label');	
	Cufon.replace('.spr');
	Cufon.replace('#motor_op3 p');
	Cufon.replace('#motor_op3 .val-km');
	Cufon.replace('#motor_op3 a.map');
	Cufon.replace('.home-detail a.l2');
	Cufon.replace('.home-square a');
	Cufon.replace('.result-m .c');
	Cufon.replace('#result-detail ul li a');
	Cufon.replace('#result-detail h3');
	Cufon.replace('#result-detail-options ul li a');
	Cufon.replace('#wrap-content-head', {hover: 'true'});
	Cufon.replace('#wrap-project-options ul li a');
	Cufon.replace('#wrap-project-c h3');
	Cufon.replace('#wrap-project-ul li a');
	Cufon.replace('#info h1');
	Cufon.replace('#schatting h1');
	Cufon.replace('#contact h1');
	Cufon.replace('#contact h2');
	Cufon.replace('#magazine h1');
	Cufon.replace('#sort-options');
	Cufon.replace('#clock_wrapper ul');
  Cufon.replace('#home-button');
  Cufon.replace('#result-label');
  Cufon.replace('#reset-search');
  Cufon.replace('#newEstateBuy');
	
	//Cufon.replace('#info-diensten-m li a', {hover: 'true'});
	//Cufon.replace('.info-gegevens-b-c ul li a', {hover: 'true'});
  }	
}

function INITmenu()
{
	var marquee_inter = 0;
	var marquee_timer = 4000;
	$('.marquee').hover
	(
		function()
		{
			clearInterval(marquee_inter);
			$(this).find('span#marquee-1').hide();
			$(this).find('span#marquee-2').show();
			marquee();
			marquee_inter = setInterval( function(){ marquee(); }, marquee_timer);
		},
		function()
		{
			clearInterval(marquee_inter);
			$('.marquee span#marquee-2').stop()
			$(this).find('span#marquee-1').show();
			$(this).find('span#marquee-2').hide();
		}
	);
	function marquee()
	{
		$('.marquee span#marquee-2').stop().css({'marginLeft':'5px'});
		$('.marquee span#marquee-2').animate({'marginLeft':'-103px'}, {queue:false, duration:4000, easing:'linear'});
	}


	$('#motor_menu li a').die().live('click',function(e)
	{
		e.preventDefault();
		
		$('#motor_menu li a').removeClass('active');
		$(this).addClass('active');
	});

	$('#motor_op1 ul.topmenu li a').die().live('click',function(e)
	{
		e.preventDefault();
		
		var option = $(this).attr('rel');
		
    $('#motor_op1 ul.topmenu li a').removeClass('active');
		$('#motor_op1 ul.topmenu li a').removeAttr('style');
		$(this).addClass('active');
		if ( ! $.browser.msie){
    Cufon.refresh('#motor_op1 ul.topmenu li a');
		}
		if (option=='1')
		{
      $('#motor_op2 h2').text(text_pricerange_buy);
      if ( ! $.browser.msie){
      Cufon.replace('#motor_op2 h2');
      }
    }
    if (option=='2')
		{
      $('#motor_op2 h2').text(text_pricerange_rent);
      if ( ! $.browser.msie){
      Cufon.replace('#motor_op2 h2');
      }
    }
		
		CALLtopmenu(option);	
	});
	
	$('#wmr_menu li a').die().live( 'click', function (e)
  {
    e.preventDefault();
    $.address.value( $(this).attr('rel') );    
  } );
	
}
	function removeActiveMenu()
	{
		$('#wmr_menu ul li a').removeClass('active');
	}

function INITadvSearch()
{
  $(".MRadioClass").click(function()
			{
				if($(this).is(":checked"))
				{					
          var clicked_name = $(this).attr('name');
          $(".MRadioLabelClass").each( function() {
            if ( $(this).attr('name')==clicked_name )
            {
              $(this).removeClass("MRadioSelected");
            }
          } );
          
          $(this).next("label").addClass("MRadioSelected");
				}
			});
			

			//IE fix
			if($.browser.msie)
			{
				$("#motor_op4 label").click(function(event) {
				 	var id = $(this).attr('for');
					$('#'+id).attr('checked', 'checked');
					$('#'+id).click();
				});
			}
  
  $('#motor_op1 a.simple').die().live('click', function(e) {
    e.preventDefault();
    
      $.address.value('advanced');
      $.address.parameter('param', motor_model.getJSON() );
      
  });
  
  $('#motor_op1 a.adv').die().live('click', function(e) {
    e.preventDefault();
    
    $.address.value('simple');    
  });
  
  $('#motor_op4 input').die().live('click', function() {
    if ($(this).attr('name')=='garden')
    {      
      if ( $(this).val()==motor_model.Garden )
      {
        motor_model.unsetGarden();
        motorUnsetAdvOpt('garden');
      }
      else
      {
        motor_model.setGarden($(this).val());
      }          
    }
    if ($(this).attr('name')=='terrace')
    {
      if ( $(this).val()==motor_model.Terrace )
      {
        motor_model.unsetTerrace();
        motorUnsetAdvOpt('terrace');
      }
      else
      {
        motor_model.setTerrace($(this).val());
      }    
    }
    if ($(this).attr('name')=='parking')
    {
      if ( $(this).val()==motor_model.Parking )
      {
        motor_model.unsetParking();
        motorUnsetAdvOpt('parking');
      }
      else
      {
        motor_model.setParking($(this).val());
       }  
    }
    if ($(this).attr('name')=='elevator')
    {
      if ( $(this).val()==motor_model.Elevator )
      {
        motor_model.unsetElevator();
        motorUnsetAdvOpt('elevator');
      }
      else
      {
        motor_model.setElevator($(this).val());

       }  
    }
    if ($(this).attr('name')=='pool')
    {
      if ( $(this).val()==motor_model.Pool )
      {
        motor_model.unsetPool();
        motorUnsetAdvOpt('pool');
      }
      else
      {
        motor_model.setPool($(this).val());
      }  
    }
    if ($(this).attr('name')=='stables')
    {
      if ( $(this).val()==motor_model.Stables )
      {
        motor_model.unsetStables();
        motorUnsetAdvOpt('stables');
      }
      else
      {
        motor_model.setStables($(this).val());
       }  
    }
    if ($(this).attr('name')=='sidebuilding')
    {
      if ( $(this).val()==motor_model.Sidebuilding )
      {
        motor_model.unsetSidebuilding();
        motorUnsetAdvOpt('sidebuilding');
      }
      else
      {
        motor_model.setSidebuilding($(this).val());
       }  
    }
    if ($(this).attr('name')=='office')
    {
      if ( $(this).val()==motor_model.Office )
      {
        motor_model.unsetOffice();
        motorUnsetAdvOpt('office');
      }
      else
      {
        motor_model.setOffice($(this).val());
       }  
    }
    $.address.parameter('param', motor_model.getJSON() );
    
    
  });
  
  $('#motor_op4 a.contact-link').die().live( 'click', function(e){
    e.preventDefault();
    
    $.address.value('contact');
  } );
  
}

function motorUnsetAdvOpt( option )
{
//   var input = $('#motor_op4 input[name='+option+']');
  var label = $('#motor_op4 label[name='+option+']');

  label.removeClass('MRadioSelected');
}

function motorSetAdvOpt( option, val )
{
//   var input = $('#motor_op4 input[name='+option+']');
  var label = $('#motor_op4 label[name='+option+']');
  
//   input.val(val);
  
    label.each( function(e)
    {
      if ( $(this).attr('for') == (option+'_'+val) )
      {
        $(this).addClass('MRadioSelected');
      }
      else
      {
        $(this).removeClass('MRadioSelected');
      }
    }
     );  
}

function hideMotorMessage()
{           
      if ( $('#motor_op1').is(':visible') )
      {
          if ( $('.topmenu').is(':visible') )
          {
            var height = 200;
          }
          else
          {
            var height = 160;
          }
          
          $('#motor_op1').animate( { height: height }, { duration: 200 ,easing: 'easeOutCirc'});
          $('#motor-message').fadeOut('fast'); 
      }
      else
      {
        setTimeout( 'hideMotorMessage()' , 6000 );
      }
}

function INITsliders()
{
	if ($.browser.msie)
	{
    $("#slider-prijs").slider({
  		range: true,
  		min: 0,
  		max: 100,
  		step: 1,
  		animate: false
  	});
  }
  else
  {    
    $("#slider-prijs").slider2({
  		range: true,
  		min: 0,
  		max: 100,
  		step: 1,
  		animate: false
  	});
	}
	$("#slider-prijs").addTouch();
	
	$('#slider-prijs').bind('slidestart',  function(event, ui){doSlide(event, ui);});
	$('#slider-prijs').bind('slide', 	   function(event, ui){doSlide(event, ui);});
	$('#slider-prijs').bind('slidechange', function(event, ui){doSlide(event, ui);});
	$('#slider-prijs').bind('slidestop',   function(event, ui){doSlide(event, ui); CALLsliderPrijs(event, ui);});
	
	function doSlide(event, ui)
	{
		var offs1 = $("#slider-prijs a:first").position();
		var xval1 = offs1.left - (35 + ((offs1.left/240)*45));
		var offs2 = $("#slider-prijs a:last").position();
		var xval2 = offs2.left + (50 - ((offs2.left/240)*35));
		
		
// 		$("#spr1").html( CommaFormatted(sliderScale.getPrice(ui.values[0])) ).css({left:xval1});
// 		$("#spr2").html( CommaFormatted(sliderScale.getPrice(ui.values[1])) ).css({left:xval2});
		
		$("#spr1 span").html( CommaFormatted(sliderScale.getPrice(ui.values[0])) );
		$("#spr2 span").html( CommaFormatted(sliderScale.getPrice(ui.values[1])) );
		
		if ( ! $.browser.msie){
    Cufon.refresh('.spr');
    }
		
	}
	
	var offs1 = $("#slider-prijs a:first").position();
	var xval1 = offs1.left - (35 + ((offs1.left/240)*45));
	var offs2 = $("#slider-prijs a:last").position();
	var xval2 = offs2.left + (50 - ((offs2.left/240)*35));
	
	if ($.browser.msie)
	{
//     $("#spr1").html( sliderScale.getPrice( $("#slider-prijs").slider("values", 0))).css({left:xval1});
// 	  $("#spr2").html( sliderScale.getPrice( $("#slider-prijs").slider("values", 1))).css({left:xval2});
	  
	  $("#spr1 span").html( sliderScale.getPrice( $("#slider-prijs").slider("values", 0)));
	  $("#spr2 span").html( sliderScale.getPrice( $("#slider-prijs").slider("values", 1)));
  }
  else
  {
//     $("#spr1").html( sliderScale.getPrice( $("#slider-prijs").slider2("values", 0))).css({left:xval1});
// 	  $("#spr2").html( sliderScale.getPrice( $("#slider-prijs").slider2("values", 1))).css({left:xval2});
	  
	  $("#spr1 span").html( sliderScale.getPrice( $("#slider-prijs").slider2("values", 0)));
	  $("#spr2 span").html( sliderScale.getPrice( $("#slider-prijs").slider2("values", 1)));
	}
	if ( ! $.browser.msie){
  Cufon.refresh('.spr');
  }
	
	//overwrite styles
// 	$("#slider-prijs a:first").css({'background':' url('+base_url+'assets/img/layout/motor/slider-left.png) no-repeat 0 center',  'margin-left': '-2em' });
	$("#slider-prijs a:last").css({'background':'url('+base_url+'assets/img/layout/motor/slider-right.png) no-repeat center center' });
  $("#slider-prijs a:first").addClass('first_handler');
  $("#slider-prijs a:last").addClass('last_handler');
	INITsliders_km();
}
function INITsliders_km()
{
	$(".slider-km").each(function(intIndex)
	{
		if ($(this).find("a.ui-slider-handle").length > 0) {}
		else
		{
			$(this).slider({
				min: 0,
				max: 20,
				step: 1,
				value:0,
				animate: false
			});
			$("#slider-prijs").addTouch();

			$(this).bind('slidestart',  function(event, ui){doSlide(event, ui);});
			$(this).bind('slide', 	  	function(event, ui){doSlide(event, ui);});
			$(this).bind('slidechange', function(event, ui){doSlide(event, ui);});
			$(this).bind('slidestop',   function(event, ui){doSlide(event, ui); CALLslideKm(event, ui);});

			function doSlide(event, ui)
			{
				var offs = $(ui.handle).position();
				var xval = offs.left - 10;
				var root = $(ui.handle).parent('div').parent('div').find(".val-km");

				root.html(ui.value + 'km').css({left:xval + 30});

				if ( ! $.browser.msie){
        Cufon.refresh('.val-km');
        }
			}
			
			var valkm = $(this).parent('div').find(".val-km");
				valkm.html('0km');

			if ( ! $.browser.msie){
      Cufon.replace('.val-km');
      }
		}
			
	});
}
	function setSliderRange()
	{
			//set props after init slider
			if ( $.browser.msie )
			{
      $("#slider-prijs").slider( "option", "min", 0); //min 
			$("#slider-prijs").slider( "option", "max", 100 ); //max
			$("#slider-prijs").slider( "option", "step", 1 ); //steps ie: 5000
      }
      else
      {
      $("#slider-prijs").slider2( "option", "min", 0); //min 
			$("#slider-prijs").slider2( "option", "max", 100 ); //max
			$("#slider-prijs").slider2( "option", "step", 1 ); //steps ie: 5000
			}
// 
			if ($("#slider-prijs").is(':visible'))
			{
//         var minpos = min;
        var pricerange = motor_model.getPriceRange();
        if ( $.browser.msie )
        {
        $("#slider-prijs").slider( "option", "values", [sliderScale.getScale( pricerange[0] ), sliderScale.getScale( pricerange[1] ) ]);
        }
        else
        {
        $("#slider-prijs").slider2( "option", "values", [sliderScale.getScale( pricerange[0] ), sliderScale.getScale( pricerange[1] ) ]);
        }
		  }
			if ( ! $.browser.msie){
      Cufon.refresh('.spr');
      }

	}
function INITcheckboxes()
{
	//clear boxes with page load
	$('input[name=cb1]').attr('checked', false);
	$('input[name=cb2]').attr('checked', false);
	$('input[name=cb3]').attr('checked', false);
	$('input[name=cb4]').attr('checked', false);
	$('input[name=cb5]').attr('checked', false);
	$('input[name=cb6]').attr('checked', false);
	$('input[name=cb7]').attr('checked', false);
	
	$('#motor_opt1_boxes .box input[type=checkbox]').prettyCheckboxes();
	$(".row1 input").change(function()
	{
		var index = $(this).attr('index');
		if(index < 4)
		{
			$("label[for=cb"+index+"]").hide();
			$('#boxes-options-'+index+'').show();
			
// 			var doHeight = $('#motor_op1').height() + 20;
// 			$('#motor_op1').stop().animate({'height':doHeight}, {queue:false, duration:300,  easing:'easeOutCirc', complete:function(){}});
		}
		
		//get proper index
		CALLcheckboxes($(this), index);
	});
	$(".row2 input").change(function()
	{
    	var index = $(this).attr('index');
		CALLcheckboxes($(this), index);
  	});
	
	$('.remove-box').click(function(e)
	{
		e.preventDefault();
		
		var ele 	= $(this).parent('div').parent('div');
		var index   = $(this).index('a.remove-box') + 1;
		
		$("input[name=cb"+index+"]").attr('checked', false);
		$("label[for=cb"+index+"]").removeClass('checked');
		$("label[for=cb"+index+"]").show();
	   
	  $(this).parent('div').find('a.open-box span').text($(this).parent('div').find('ul li:first-child a').html());
	   
		ele.hide();
		
// 		var doHeight = $('#motor_op1').height() - 20;
// 		$('#motor_op1').stop().animate({'height':doHeight}, {queue:false, duration:300,  easing:'easeOutCirc', complete:function(){}});
		
		CALLcheckboxes($(this), index);
	
	});
}
function detectDropdown_click(e)
{
        var target = $(e.target);        
        if (( ! target.parents('.boxes-options').length ) && ( ! target.parents('.adv_ops').length )) {
          closeAll();  
          $(document).unbind('click', detectDropdown_click );
          }
}
function INITselectboxes()
{
	$('.open-box').click(function(e)
	{
		e.preventDefault();
		
		var arrow 	= $(this);
		var ele 	= $(this).parent('div').find('ul');
		var root	= $(this).parent('div');
		
		closeAll();
		$(document).bind('click', detectDropdown_click );
		
		if(ele.is(':visible')){
			arrow.removeClass('active');
			root.css({'z-index':'1'});
		}
		else{
			arrow.addClass('active');
			root.css({'z-index':'3'});
			ele.slideDown(300);
		}
		
		ele.find('a').each( function() {
      $(this).removeClass('motor_active_dropdown');
      if ($(this).html()== arrow.children('span').html() )
      {
        $(this).addClass('motor_active_dropdown');
      }
    });
		
	});
	$('.box-opt-box ul li a').click(function(e) 
	{
		e.preventDefault();
		var par = $(this).parent('li').parent('ul').parent('div');
		var ele = $(this).text();
		var fie;
		
		switch(par.index())
		{
			case 0: fie = par.find('.open-box span'); break; // categories 
			case 1: fie = par.find('.open-box'); break; // kamers
		}
		
		if ((par.attr('id')=='adv-op-rooms') || (par.attr('id')=='adv-op-bathrooms'))
		{
      fie = par.find('.open-box');
    }
		
		fie.text(ele);
		closeAll();
		
		var value = $(this).attr('rel');
		var parent_cat = par.children('a.open-box').attr('rel');
		
		
		if($(this).parent('li').index() >= 1)
		{
		
      switch(par.index())
			{
				case 0: CALLselectboxes_1(value, parent_cat); break; // categories 
// 				case 1: CALLselectboxes_2(value); break; // kamers 
			}
		}
		else
		{	
			switch(par.index())
			{
				case 0: 
         var index = par.parent('.boxes-options').index('div.boxes-options') + 1;
    			//alert(index);
    			CALLcheckboxes_reset_subs(index);
        break; // categories 
// 				case 1:        
//         CALLselectboxes_2(value); 
//         break; // kamers 
			}     
		}
		if (par.attr('id')=='adv-op-rooms')
		{
      motor_model.setMinRooms(value);
//       search_motor_set('MinRooms', value);
    }
    if (par.attr('id')=='adv-op-bathrooms')
		{
      motor_model.setBathRooms(value);
//       search_motor_set('BathRooms', value);
    }
    if ((par.attr('id')=='adv-op-rooms') || (par.attr('id')=='adv-op-bathrooms'))
    {
      $.address.parameter('param', motor_model.getJSON() );
    }
		

	});
	
}
function closeAll()
	{
		$('.box-opt-box').each(
			
			function(intIndex)
			{
				var Obj = $(this);
				var Arr = $(this).find('.open-box');
				var Ele	= $(this).find('ul');
				if(Obj.is(':visible')){
					Arr.removeClass('active');
					Obj.css({'z-index':'1'});
					Ele.slideUp(300);
				}
			}
			
		);
	}
function INITlocations()
{

    getXMLdata();
	 
	$('#locField-1').blur(function()
	{
		var getID = $(this).attr("id");
		var getValue = $('label[for=' + getID + ']').text();
	 	if ($(this).val() == ""){
			$(this).val(getValue);
			$(this).css({color:'#aaa'});
		}
	});
	$('#locField-1').focus(function()
	{
		var getID = $(this).attr("id");
		var getValue = $('label[for=' + getID + ']').text();
		$(this).css({color:'#000'});
		if ($(this).val() == getValue){$(this).val("");}
		return false;
	});
		
	$('.loc input').blur(function()
	{
		//checkLocationMultiple($(this));
		var getID = $(this).attr("id");
		var getValue = $('label[for=' + getID + ']').text();			
	 	if ($(this).val() == ""){
			$(this).val(getValue);
			$(this).css({color:'#aaa'});
	 	}
	 	else
	    {
			/*
			var getID = $(this).parent('div').attr('id');
			var locCheck = getID.substr(5);
						
			if(locCheck >= locCO && locCO < 3)
			{
				locID++;
				locCO++;
			
				var root = $(this).parent('div').parent('div');
				root.append('<div class="loc" id="locid'+locID+'"><input type="text" value="Gemeente?"/><img src="img/layout/motor/Oslash.png"/><div class="slider-km"></div><div class="val-km"></div><a href="#" title="Verwijder" class="close"></a></div>');
			
				$('#locid' + locID).hide();
				$('#locid' + locID).fadeIn();
			
				 //
				 // make sure to unbind all blur events as we reinitialize our functions,
				 // otherwise events are fired multiple times
				 //
				$('.loc input').unbind('blur');
				$('.loc input').unbind('click');
				$('.loc a.close').unbind('click');
			
				//reinitialize functions
				INITlocations();
				INITsliders_km();
			}
			*/
		
		}
	});
	$('.loc input').focus(function()
	{
		var getID = $(this).attr("id");
		var getValue = $('label[for=' + getID + ']').text();
		$(this).css({color:'#000'});
		if ($(this).val() == getValue){$(this).val("");}
		return false;
	});
	
	/*
	$(".loc input").keypress(function()
	{
		checkLocationMultiple($(this));
	});
	$('#motor_op3 a.add').click(function()
	{
		locID++;
		//locCO++;
	
		var root = $('#motor_op3');
		root.append('<div class="loc" id="locid'+locID+'"><input type="text" value="'+fields_motor[0]+'"/><div class="loc-slider-wrap"><img src="img/layout/motor/Oslash.png"/><div class="slider-km"></div><div class="val-km"></div><a href="#" class="close"></a></div></div>');
	
		$('#locid' + locID).hide();
		$('#locid' + locID).fadeIn();
	
		 //
		 // make sure to unbind all blur events as we reinitialize our functions,
		 // otherwise events are fired multiple times
		 //
		$('.loc input').unbind('blur');
		$('.loc input').unbind('click');
		$('.loc input').unbind('keypress');
		$('.loc a.close').unbind('click');
		$('#motor_op3 a.add').unbind('click');
	
		//reinitialize functions
		INITlocations();
		INITsliders_km();
	});
	$('.loc a.close').click(function()
	{
		var obj = $(this).parent('div').parent('div');
		locCO--;
		obj.fadeOut(500, function(){
			obj.remove();
		});
		
		return false;
	});
	*/
}
	function SETautoComplete()
	{
		   $.ui.autocomplete.filter = function(array, term) {             
          if (term!='')
          {
             var matcher = new RegExp( "\\b"+$.ui.autocomplete.escapeRegex(term), "i" );
             return $.grep( array, function(value) {
                    var m=matcher.exec(value.label || value.value || value);
                    if ( m != null )
                    {
                      return m['input'];
                    }
             }); 
          }
        };
		
    $("#locField-1").autocomplete(
		{
			source: function(request, response)
			{
				// delegate back to autocomplete, but extract the last term
				response($.ui.autocomplete.filter(xmlgemeentesARR, extractLast(request.term)));
				
			},	
      focus: function()
      {

        return false;
      },		
			select: function(event, ui)
			{        

        var terms = split( $(this).val() );
				// remove the current input
				terms.pop();
				// add the selected item
				terms.push( ui.item.value );
				// add placeholder to get the comma-and-space at the end
				terms.push("");
				this.value = terms.join(", ");
				CALLtextarea();
        return false;
			},
			close:function(event, ui){				

        //CALLtextarea();
			},
			change: function(event, ui){				

         //CALLtextarea();
			}
		});
    
		$("#locField-2").autocomplete(
		{
			source: xmlgemeentesARR,			
			select: function(event, ui){ 
//         console.log(ui);
        this.value=ui.item.value;
        CALLtxtfield(); 
      },
			close:function(event, ui){
				//CALLtxtfield();
			},
			change: function(event, ui){
				//CALLtxtfield();
			}
		});
		$("#locField-1").autocomplete( 'option', 'delay', 500 );
		$("#locField-2").autocomplete( 'option', 'delay', 500 );
    
//     $("#locField-1").blur( function() {      
//       CALLtextarea();      
//     } );
//     $("#locField-2").blur( function() {
//       CALLtxtfield();      
//     } );
    
    $("#locField-1").keydown( function(e) {
      
      if ( parseInt(e.keyCode)==13 )
      {
        e.preventDefault();
        var terms = split( $(this).val() );						
				if (terms[terms.length-1]!="")
				{
          terms.push("");
				}
        this.value = terms.join(", ");
         CALLtextarea();
//         SETrobot(false);
         $(this).autocomplete('close');
      }
    } );
    
    $("#locField-2").keydown( function(e) {
      if ( parseInt(e.keyCode)==13 )
      {
        e.preventDefault();
//         this.value = $(this).val();
        CALLtxtfield();
//         SETrobot(false);
        $(this).autocomplete('close');
      }
    } );

	}
	function checkLocationMultiple(obj)
	{
		var root  = obj.parent('div');
		var value = obj.val();
		var words = value.split(" ");
		
		if(words.length > 1){
			root.find('.loc-slider-wrap').hide(300);
			obj.animate({width:210}, {queue:false, duration:300,  easing:'easeOutCirc'});
		}else{
			root.find('.loc-slider-wrap').show(300);
			obj.animate({width:100}, {queue:false, duration:300, easing:'easeOutCirc'});
		}
	}
	function getXMLdata()
	{
		$.ajax(
		{
			type: "GET",
			url: base_url+"data.xml",
			dataType: "xml",
			success: parseXml
		});
	}
	function parseXml(xml)
	{
  	if ( ! locationXMLloader )
    {
      var root = $(xml).find("radon");
      root.find("radon").each(function(intIndex)
  		{
  		 	xmlgemeentes[$(this).find("NAME").text()] = $(this).find("POSTCODE").text();
        xmlgemeentesARR.push($(this).find("NAME").text());
  			xmlgemeentesARR.push($(this).find("POSTCODE").text());
  		});
		  locationXMLloader=true;
    }
		SETrobot(true);
		SETautoComplete();
		
	}
	function collectPlaces(city)
	{
		gemeentes = [];
				
		var v1 = $("#locField-1").val();
		var v2 = $("#locField-2").val();
		
		var l1 = $('label[for=locField-1]').text();
		var l2 = $('label[for=locField-2]').text();
		
		if(v1 != '' && v1 != l1)
		{
			var tempArr1 = v1.split(", ");
			for(i=0;i<tempArr1.length;i++){
				var tempStr = tempArr1[i];
					tempStr = uppercaseFirst(tempStr);
				gemeentes.push(tempStr);
			}
		}
		
		//include city?
		if(city)
		{
			if(v2 != '' && v2 != l2)
			{
				var tempArr2 = uppercaseFirst(v2);
					gemeentes.push(tempArr2);
			}
		}
		

		gemeentes = uniqueArray(gemeentes);	
	}
	function getSWFid(swfID)
	{
		if(navigator.appName.indexOf("Microsoft") != -1){
		     swfid = window[swfID];
		}else{
		     swfid = document[swfID];
		}
		return swfid;
	}
	function setContent()
	{
		collectPlaces(true);
		getSWFid("map").highlightMap(gemeentes);
	}
	function resetMotorFields(str)
	{
		//add spaces to string
		var temparr = str.split(',').join(', ');
		
		//check if there is a second value + remove from string
		var v2 = $("#locField-2").val();
		
		var l1 = $('label[for=locField-1]').text();
		var l2 = $('label[for=locField-2]').text();
		
		if(v2 != '' && v2 != l2){
			temparr = temparr.split(v2+', ').join('');
			temparr = temparr.split(v2).join('');
		}
		
		//add string to group
		if(temparr != v2 || temparr != ''){
			$("#locField-1").val(temparr);

			$("#locField-1").css({color:'#000'});
		}else{
			$("#locField-1").val(l1);
		}
		
		CALLtextarea();
	}


//CALLS -> zoekrobot
function CALLtopmenu(val)
{
	motor_model.setPurposeID(val);
	setSliderRange();

	$.address.parameter('param', motor_model.getJSON() );
	

}
function CALLcheckboxes(elem, index)
{
	resetForSearch();

	if (elem.attr('checked')==true) {
		motor_model.addCategoryID(index);
	}
	else
	{
		motor_model.delCategoryID(index);		
	}	
	$.address.parameter('param', motor_model.getJSON() );
	
}
function CALLcheckboxes_reset_subs(index)
{	
	//remove subcategory
	motor_model.delSubCategoryFromCategoryID( index );
	
	$.address.parameter('param', motor_model.getJSON() );
}
function CALLselectboxes_1(elem_cat, parent_cat)
{
	
	motor_model.addSubCategoryID( elem_cat, parent_cat );
  
  $.address.parameter('param', motor_model.getJSON() );
}


function CALLsliderPrijs(event, ui)
{
	resetForSearch();
  
  motor_model.setPriceRange( sliderScale.getPrice(ui.values[0]), sliderScale.getPrice(ui.values[1]) );
  	
	$.address.parameter('param', motor_model.getJSON() );
}
function CALLslideKm(event, ui)
{
	
	//check if there's a value in the box
	var v		= $("#locField-2").val();
	var l		= $('label[for=locField-2]').text();
	
	if(v != '' && v != l)
	{
		resetForSearch();

		motor_model.setDistanceFromCity( ui.value );
		
  $.address.parameter('param', motor_model.getJSON() );
	}
	
	
}
function CALLtextarea()
{
	collectPlaces(false);
	
	var newDataArr = new Array();
	
	for(var i = 0; i< gemeentes.length; i++)
	{
		//replace all names with their related postcodes
		if(xmlgemeentes[gemeentes[i]] != undefined ){
			newDataArr[i] = xmlgemeentes[gemeentes[i]];
		}
		else{
			newDataArr[i] = gemeentes[i];
		}
	}
	
	var value;
	var key 	= 'ZipList';
	
	if(newDataArr.length > 0 ){
		value = newDataArr;
	}
	else
	{
    value = [];
  }
	
	motor_model.setZipList( value );
	
  $.address.parameter('param', motor_model.getJSON() );
}
function CALLtxtfield()
{
	var value;
	var key 	= 'City';
	var v		= $("#locField-2").val();
	var l		= $('label[for=locField-2]').text();
	
	if(v != '' && v != l){value = v;}
	else{value = '';}
	
	motor_model.setCity( value );
	
	$.address.parameter('param', motor_model.getJSON() );
}

	function CALL_search_doCallBack(foo, doslider)
	{
		doLoader(false);
		$('#w_content').css('overflow', 'hidden');
		$('#w_content').html(foo);
		removeActiveMenu();
		INITresults();
		INITtriangle();
// 		SETrobot(doslider);
		INITsortOptions();
		if ( $('#motor_menu a.active').attr('rel')=='newestate' )
		{
		  INITnewprojects();
		}
		//empty result
    if ( ! $.browser.msie){
    Cufon.replace('.result-empty');
    }
    $('.result-empty a').click( function(e) {
      e.preventDefault();
      displayBox(base_url+'box_pole_position');
    });
    
    //desaturate result images when map overlay is active
    if ( $('#amaibox').is(':visible') )
    {
      $('#result-overview-holder .result img.des').css('display', 'block');
      $('#result-overview-holder .result img.sat').css('display', 'none');
      
      $('#result-overview-holder .result .result-m p').css({'color':'#ccc'});     
      
      $('#wrap-projecten .project img.des').css('display', 'block');
      $('#wrap-projecten .project img.sat').css('display', 'none');
      
      $('#wrap-projecten .project .project-r a').css({'color':'#ccc'});  
      
    }    
    if ( $('#result-detail-holder').is(':visible') )
    {
      $('#headerDelen').css('left', 'auto');
      $('#headerPrint').css('left', 'auto');
      $('#headerDelen').css('right', 120);
      $('#headerPrint').css('right', 120);
      $('#wrap-content-head').addClass('background');
    }
    else
    {
      $('#headerDelen').css('right', 'auto');
      $('#headerPrint').css('right', 'auto');
      $('#headerDelen').css('left', 190);
      $('#headerPrint').css('left', 190);
      $('#wrap-content-head').removeClass('background');
    }
  }


// Search motor instellen adhv search_array
// 
function SETrobot(doslider)
{
	
	//set hire or buy

		var purpose=motor_model.getPurposeID();
		
		if (purpose==2)
		{
			$('#motor_op1 ul.topmenu a:first').addClass('active');
			$('#motor_op1 ul.topmenu a:last').removeClass('active');
			$('#motor_op2 h2').text(text_pricerange_rent);
		}
		if (purpose==1)
		{
      $('#motor_op1 ul.topmenu a:first').removeClass('active');
			$('#motor_op1 ul.topmenu a:last').addClass('active');
			$('#motor_op2 h2').text(text_pricerange_buy);
		}
		if ( ! $.browser.msie){
    Cufon.replace('#motor_op2 h2');
		Cufon.refresh('#motor_op1 ul.topmenu li a');
    }
	
	
	//set checkboxes
	if (motor_model.getCategoryIDList())
	{
	 var categoryIDList = motor_model.getCategoryIDList();
	 
	 $('#motor_opt1_boxes input').each( function( index ) {
    
    var input = $(this);
    var label = $(this).parent().find('label[for=cb'+(index+1)+']');
    var box_options = label.parent().find('div#boxes-options-'+(index+1));
    
    if ( $.inArray( (index+1), categoryIDList ) != -1 )
    { 
      if ( ! input.is(':checked') )
      {
          input.attr('checked', true);
          label.click();
          if ((index+1) <=3 )
          {
            label.css('display', 'none');
            box_options.css('display', 'block');
          }              
      }
      else
      {
        if ((index+1) <=3 )
          {            
            box_options.children('div.box-opt-box').find('a.open-box span').text( box_options.children('div.box-opt-box').attr('rel') );
          }     
      }
    }
    else
    {
      if ( input.is(':checked') )
      {
          input.attr('checked', false);
          label.click();
          if ((index+1) <=3 )
          {
            label.css('display', 'block');
            box_options.css('display', 'none');
          }              
      }     
    }
   });
	}
	
	if (motor_model.getSubCategoryIDList())
	{
 		var idList=motor_model.getSubCategoryIDList();
 		
 		var sc = new Array();
 				sc = sc.concat(motor_model.getSubCategoryIDList());
 
 			for(var i=0; i<sc.length;i++ )
 			{     
       var text=$('#boxes-options-'+sc[i][0]+' ul li a[rel='+sc[i][1]+']').html();
       $('#boxes-options-'+sc[i][0]+' a.open-box span').text(text);
      }
	}
	
	
	//set slider
	if(doslider){
		setSliderRange();
	}
	
	
	
	//set textfield
	if (motor_model.getZipList())
	{
		var arr3 = motor_model.getZipList();
		var temparr = [];
		
		for(var i = 0; i < arr3.length; i++){
			var tempval = arr3[i];
			for (key in xmlgemeentes){
				if(xmlgemeentes[key] == tempval){
					temparr.push(key);
				}
			}	
		}
		
		temparr = temparr.join(", ");
		$('#locField-1').val(temparr);
	}
	
	
	//set gemeente + range?
	if (motor_model.getCity())
	{
		$('#locField-2').val(motor_model.getCity());
	}
	
	
	if (motor_model.getDistanceFromCity())
	{
		var distance = motor_model.getDistanceFromCity();
		$(".slider-km").slider( "option", "value", distance);
		if ( ! $.browser.msie){
    Cufon.refresh('.val-km');
    }
	}
	
	
	//set advanced option
	if ( typeof(motor_model.Garden) != 'undefined' )
	{
    motorSetAdvOpt( 'garden', motor_model.Garden );
  }
  else
  {
    motorUnsetAdvOpt( 'garden' );
  }
  
  if ( typeof(motor_model.Terrace) != 'undefined' )
	{
    motorSetAdvOpt( 'terrace', motor_model.Terrace );
  }
  else
  {
    motorUnsetAdvOpt( 'terrace' );
  }
  
  if ( typeof(motor_model.Parking) != 'undefined' )
	{
    motorSetAdvOpt( 'parking', motor_model.Parking );
  }
  else
  {
    motorUnsetAdvOpt( 'parking' );
  }
  
  if ( typeof(motor_model.Elevator) != 'undefined' )
	{
    motorSetAdvOpt( 'elevator', motor_model.Elevator );
  }
  else
  {
    motorUnsetAdvOpt( 'elevator' );
  }
  
  if ( typeof(motor_model.Pool) != 'undefined' )
	{
    motorSetAdvOpt( 'pool', motor_model.Pool );
  }
  else
  {
    motorUnsetAdvOpt( 'pool' );
  }
  
  if ( typeof(motor_model.Stables) != 'undefined' )
	{
    motorSetAdvOpt( 'stables', motor_model.Stables );
  }
  else
  {
    motorUnsetAdvOpt( 'stables' );
  }
  
  if ( typeof(motor_model.Sidebuilding) != 'undefined' )
	{
    motorSetAdvOpt( 'sidebuilding', motor_model.Sidebuilding );
  }
  else
  {
    motorUnsetAdvOpt( 'sidebuilding' );
  }
  
  if ( typeof(motor_model.Office) != 'undefined' )
	{
    motorSetAdvOpt( 'office', motor_model.Office );
  }
  else
  {
    motorUnsetAdvOpt( 'office' );
  }
  
  
  if ( typeof(motor_model.BathRooms) != 'undefined' )
	{
    var label=$('#adv-op-bathrooms a.open-box');
    var options=$('#adv-op-bathrooms ul a');
    
    options.each( function() {
      if ( parseInt($(this).attr('rel')) == parseInt(motor_model.BathRooms) )
      {
        label.text( $(this).text() );
      }
    } );
  }
  else
  {
     var label=$('#adv-op-bathrooms a.open-box');
     label.text('----');
  }
  
  if ( typeof(motor_model.MinRooms) != 'undefined' )
	{
    var label=$('#adv-op-rooms a.open-box');
    var options=$('#adv-op-rooms ul a');
    
    options.each( function() {
      if ( parseInt($(this).attr('rel')) == parseInt(motor_model.MinRooms) )
      {
        label.text( $(this).text() );
      }
    } );
  }
  else
  {
     var label=$('#adv-op-rooms a.open-box');
     label.text('----');
  }
  if ( motor_model.getAddress() )
  {
    $('#locaction_field_address').val(motor_model.getAddress());  
  }
  $('#locaction_field_address').addressField();
  $('#searchfield_estateID').refField();
  
}


	
function INITresults()
{
	resultHideDetail = false;
// 	setTimeout( 'resultHideDetail=true;', 2000 );
	$('#result-detail-holder').css('visibility', 'visible');
	
	$('#result-detail-holder').die().live('mouseover', function() {
    resultHideDetail=true;
  } );
	
	//does a.result-l exists?
	if($("a.result-l").size())
	{
		$('.result').each(function(intIndex){
			$(this).css({left:'-600px'})
			$(this).stop().animate({'left':0}, {queue:false, duration:(intIndex * 200), easing:'easeOutCirc'});
			
			var imageholder=$("a.result-l");
      imageholder.each( function() {
        //fix image positioning
  			$(this).find('img').each( function() {
          var image = $(this);
          if ( ! image.hasClass('image-position-fixed'))
          {
            if (image.width()!=imageholder.width())
            {
              var whitespace = imageholder.width()-image.width();
              image.css('marginLeft', whitespace/2);
            }
            image.addClass('image-position-fixed');
          }
        });
      });
		});
		
		$('a.result-l').mouseover(function()
		{
  			var	par = $(this).parent('div');
  			var obj = par.find('.result-hover');
  		  
  			if($('#result-detail-holder').is(':visible')){
  			if (resultHideDetail){				
    			resultHideDetailIE=true;
          $('#result-detail-ul').css('visibility', 'hidden');
    			$('#result-detail-c').css('visibility', 'hidden');
          $('#result-detail img.des').css('display', 'block');
          $('#result-detail img.sat').css('display', 'none');
          $('#result-detail-holder').css({'zIndex':0});
    			$('#result-overview-holder').css({'zIndex':1});
        }
  
          if (( ! $(this).hasClass('disabled') ) && ( slidingResults ))
          {
            obj.css('background-color', '#fcfcfc').stop().animate({'left':'201px'}, {queue:false, duration:250, easing:'easeOutCirc'});	  				  
  				}
  			}
				
		});
		$('a.result-l').mouseout(function(e)
		{
			var	par = $(this).parent('div');
			var obj = par.find('.result-hover');
			
			if($('#result-detail-holder').is(':visible')){
			if (resultHideDetail){			
        if ( $.browser.msie )
        {
          resultHideDetailIE=false;
          setTimeout( 'hideDetailIE()', 200 );
        }
        else
        {
          $('#result-detail-ul').css('visibility', 'visible');
    			$('#result-detail-c').css('visibility', 'visible');
          $('#result-detail img.des').css('display', 'none');
          $('#result-detail img.sat').css('display', 'block');
          $('#result-detail-holder').css({'zIndex':1});
				  $('#result-overview-holder').css({'zIndex':0});	
        }
      }  
       if ( ! $(this).hasClass('disabled') )
       { 
        obj.css('background-color', '#ffffff').stop().animate({'left':-200}, {queue:false, duration:500,  easing:'easeOutCirc'});
				
// 				$('#result-shadow').hide();
      }
			}
		});	
		
		$('div.result').mouseover( function() {
        var cpos = $(this).offset();
  			if ( $('#result-label').is(':visible') )
  			{
          var ypos = cpos.top - 175 -30;
        }
        else
        {
         var ypos = cpos.top - 175;
  		  }
        $("#hovertriangle").show();
  			$("#hovertriangle").animate({top: ypos + "px"},{queue:false, duration:300, easing:'easeOutCirc'});
  			$("#hovertriangle2").show();
  			$("#hovertriangle2").animate({top: ypos + "px"},{queue:false, duration:300, easing:'easeOutCirc'});
  			
  			$('#result-detail').css('Zindex', 1);
        $("#result-detail-holder").css('Zindex', 0);
  			
    } );
		
		$('#result-detail').die('mouseover').live('mouseover', function() {
      slidingResults = true;
    } );
		
		$('a.result-l').click(function(e)
		{		
      e.preventDefault();
      if ( $(this).hasClass('parent') )
      {
        $.address.value('nieuwbouw/detail/'+$(this).attr('rel'));
      }
      else
      {
        if ( ! $(this).hasClass('disabled') )
        { 
          unsetResultListHover();
          
          resultHideDetail = false;
          slidingResults = false;
          
          var dataStr = $(this).attr('rel');
    			var	par = $(this).parent('div');
    			var obj = par.find('.result-hover');
    			if (dataStr)
    			{
        			setResultListHover( dataStr );
        			activeEstateDetail=dataStr;
        			
              if($('#result-detail-holder').is(':visible')){
        				obj.stop().animate({'left':-200}, {queue:false, duration:500,  easing:'easeOutCirc'});
        				$('#result-shadow').hide();
        			}
        			
        			list_pdf_url = $('#print_link').attr('href');
        			$('#print_link').attr('href',base_url+$(this).attr('rel')+'.pdf');
        			
        			if (motor_model.mode=='newestate')
        			{
                getDrawing=true;
              }     
              
        			$.address.value('estate/detail/'+$(this).attr('rel'));
        			
        			$('a.result-l').removeClass('active');
        			$(this).addClass('active');
    		  }
    		}
    	}
  		$('#result-detail-holder').css({'zIndex':1});
      
		});
    
    $('div.result-hover').click( function(){
      $(this).prev('a.result-l').trigger('click');
    } );
    
		$('#result-closebtn').click(function(e)
		{
			e.preventDefault();
			
      $.address.value('close');

		});
	}	
	
	//Next estate button
	$('a#result-estate-next').die().live('click', function(e) {
    e.preventDefault();
    var current_estate = $(this).attr('rel');
    var click_next=false;
    var clicked = false;
    $('div.result').each( function(index,e) {
      if (click_next)
      {
        var a = $(this).find('a');
        if (a.hasClass('disabled'))
        {
          click_next=true;
          clicked=false;
        }
        else
        {
          a.click();
          a.mouseover();
          click_next=false;
          clicked=true;
          return false;
        }
        
      }
      if ( $(this).find('a').attr('rel')==current_estate )
      {
        click_next=true;
      }
    });
    if ( ! clicked)
    {
      $('span#pagination_next a').click();
       click_first_result=true;
    }
  } );
	
	$('#result-estate-login').die().live( 'click', function(e){
    e.preventDefault();
    
       var box = $('#amaiboxcontent');
      box.css( { 'width': 546, 'height': 490, 'marginLeft': -323, 'marginTop': -295 } );
      box.addClass("smallbox");
    
      displayBox(base_url+'box_login/'+$(this).attr('rel'));
  } );
	
	
	
	   $('#form2').die('submit').live('submit', function(e) {
     e.preventDefault();
    displayBox(base_url+'box_confirmation');
 
                  							$('#amaiboxcontent #bevestiging').css({'display':'none'});
                  							$('#amaiboxcontent #bevestiging').fadeIn(1000);
                  							
                  						  if ( ! $.browser.msie){
                                Cufon.replace('#amaiboxcontent h1');
                  							Cufon.replace('#amaiboxcontent h2');
                  							}
                                amCountdown = setInterval ( "countdown()", 1000);
                  							countdown();
     } );
    
                  					
 
	
	//add content header
	if ( ! $.browser.msie){
  Cufon.replace('#wrap-content-head', {hover: 'true'});
	}
	
	INITresultPoleposition();
	
	//saturate all images
	saturateImages();
	//do paging
	INITpagination();
	Cufon.replace('#result-label');
	
	$('#motor_info #result-count').remove();
	$('#motor_info').append( $('#result-count') );
	
	if (( $('#wrap-content-head h1').length!=0 ) && ( $('#result-overview-holder').length!=0 ))
	{
    $('#wrap-content-head a.sorteer').css('display', 'none');
  }
  
  $('.result-d .flashSms').each( function(){
    var $this=$(this);
    var p = $this.children('p');
    var pHeight = p.height();
    
    var margin=0;
    if ( pHeight<110 )
    {
      margin= Math.round((115-pHeight)/2);
    }
    p.css( { marginTop: margin } );
  } );
  
  $('.result .result-d').hover( function(){
    $(this).children('.flashSms').animate( { top: 0 }, { duration: 400, easing: 'easeOutExpo', queue: false } );
  }, function(){
    $(this).children('.flashSms').animate( { top: 130 }, { duration: 400, easing: 'easeOutExpo', queue: false } );
  } );
}

function hideDetailIE()
{
    if (!resultHideDetailIE)
    {
      $('#result-detail-ul').css('visibility', 'visible');
			$('#result-detail-c').css('visibility', 'visible');
      $('#result-detail img.des').css('display', 'none');
      $('#result-detail img.sat').css('display', 'block');
      $('#result-detail-holder').css({'zIndex':1});
			$('#result-overview-holder').css({'zIndex':0});	
    }
}

function setResultListHover( activeRel )
{
  
    var result = $('#result-overview-holder .result');
    var sat = result.find('img.sat');
    var des = result.find('img.des');
    
    des.css('display', 'block');
    sat.css('display', 'none');
    
    result.find('a[rel='+activeRel+'] img.sat').css('display', 'block');
    
    result.find('a').bind('mouseenter.BWhover', function() {
      if (resultHideDetail)
      {
      $(this).children('.sat').css('display', 'block');
      }
    } );
    
    result.find('a').bind('mouseleave.BWhover', function() {
      if ( $(this).attr('rel')!=activeRel )
      {
        $(this).children('.sat').css('display', 'none');
      }
    } );
 
}

function unsetResultListHover()
{
  var result = $('#result-overview-holder .result');
  var sat = result.find('img.sat');
  var des = result.find('img.des');
  var a = result.find('a');
  
  des.css('display', 'none');
  sat.css('display', 'block');
  
  a.unbind('mouseenter.BWhover');
  a.unbind('mouseleave.BWhover');
}

function INITresultPoleposition()
{
  if ( ! $.browser.msie){
  Cufon.replace('#result-poleposition h3');
	}	
	
	$('#result-poleposition').css('width', 0).css('display', 'block').animate( { 'width': 200 }, 800, 'easeOutCirc' );
	$('#result-poleposition').die().live('click', function(){
      var box = $('#amaiboxcontent');
      box.css( { 'width': 800, 'height': 490, 'marginLeft': -450, 'marginTop': -295 } );
      box.removeClass("smallbox");
    displayBox(base_url+'box_pole_position');
  });
}

function INITnewprojects()
{
	//does a.result-l exists?
	if($("#wrap-projecten").size())
	{
		$('#wrap-projecten div.project').mouseover(function() 
		{
			// arrow
			$("#hovertriangle").show();
			$("#hovertriangle2").show();
			var cpos = $(this).offset();
			if ( $('#result-label').is(':visible') )
  			{
          var ypos = cpos.top - 175 -30;

        }
        else
        {
         var ypos = cpos.top - 175;

  		  }
			$("#hovertriangle").animate({top: ypos + "px"},{queue:false, duration:300, easing:'easeOutCirc'});
			$("#hovertriangle2").animate({top: ypos + "px"},{queue:false, duration:300, easing:'easeOutCirc'});
		});
  
      var imageholder=$("a.project-l");
      imageholder.each( function() {
        //fix image positioning
  			$(this).find('img').each( function() {
          var image = $(this);
          if ( ! image.hasClass('image-position-fixed'))
          {
            if (image.width()!=imageholder.width())
            {
              var whitespace = imageholder.width()-image.width();
              image.css('marginLeft', whitespace/2);
            }
            image.addClass('image-position-fixed');
          }
        });
      });
    
  }
   	if ( ! $.browser.msie){
    Cufon.replace('#wrap-content-head', {hover: 'true'});
    Cufon.replace('#wrap-project-options ul li a');
    Cufon.replace('#wrap-project-c h3');
    Cufon.replace('#wrap-project-ul li a');
    Cufon.replace('#wrap-projecten h2');
    }
    
    $('#wrap-project-options a.reverse').click( function(e) {
        e.preventDefault();
      
      $.address.value( $(this).attr('rel') );
    });
    
     $('#wrap-content-head a#option').die().live('click', function(e) {
        e.preventDefault();
        
        if ( $(this).hasClass('kavel') )
        {
          var url = $(this).attr('href').substr( base_url.length, ($(this).attr('href').length-base_url.length) )+'/kavels';
        }
        else
        {
          var url = $(this).attr('href').substr( base_url.length, ($(this).attr('href').length-base_url.length) );
        }
        $.address.value(url);
    });
    
    $('#wrap-project-options a#viewChildren').die().live('click', function(e) {
        e.preventDefault();
        
        var url = $(this).attr('href').substr( base_url.length, ($(this).attr('href').length-base_url.length)  );
        
        $.address.value(url);
    });
    
    $('div.project a').die().live('click', function(e) {
      e.preventDefault();      
      $.address.value('nieuwbouw/detail/'+$(this).attr('rel'));
    });
    $('div.project .project-r').die().live('click', function(e){
      $(this).prev('a').trigger('click');
    } );
    
    
    $('#project-next').die().live('click', function(e) {
      e.preventDefault();
      
      $.address.value('newestate_next/'+$(this).attr('rel'));
      
    });
    
    $('span.table-child-purpose a').die().live('click', function(e){
      e.preventDefault();
      
      $.address.value('estate/detail/'+$(this).attr('rel')+'/'+encodeURI($('#wrap-content-head h1').text())+'/'+$('#wrap-project-ul').attr('class').substr(7) );
    });
    
    
    //share buttons
//     console.log( document.location.href );
    var share_url = document.location.href.split('#', 2);
    if ( share_url.length==2 )
    {
      share_url=base_url+share_url[1].substr( 1, share_url[1].length );
//       console.log( share_url );
      $('#wrap-project-options ul').append('<li><a href="#" id="right_share">'+$('#headerDelen a').text()+'</a></li><li><a href="http://www.facebook.com/sharer.php?u='+share_url+'&t=Vansweevelt%20-%20Zoekresultaten" id="right_fbshare" target="_blank">FB share</a></li>');
      $('#headerDelen').hide();
      $('#right_share').click( function(e){
        e.preventDefault();
        $('#headerDelen a').trigger('click');
      } );
    }
    
}
function INITtriangle()
{
	var parentExists = false;
	var parent;
	
	//does result-overview-holder exists?
	if($("#result-overview-holder").size())
	{
		parent = $("#result-overview-holder");
		child = $('a.result-l');
		parentExists = true;
 	}

	//does result-overview-holder exists?
	if($("#wrap-projecten").size())
	{
		parent = $("#wrap-projecten");
		child = $('#wrap-projecten div.project');
		parentExists = true;
 	}
   	
	if(parentExists)
	{
		$("#hovertriangle").hide();
		$("#hovertriangle2").hide();
		
		parent.mouseout(function(e)
		{
			var cX 		= e.pageX;
			var cY 		= e.pageY;
			var theID 	= $(this).attr('id');
			var elem  	= document.getElementById(theID);

			if(!hitTest(cX, cY, elem))
			{
				var check = false;

				child.each(function(intIndex)
				{
					if ($(this).is('.active')) {
						check = true;
						var cpos = $(this).offset();
						if ( $('#result-label').is(':visible') )
  			{
          var ypos = cpos.top - 175 -30;

        }
        else
        {
         var ypos = cpos.top - 175;

  		  }
						$("#hovertriangle").animate({top: ypos + "px"},{queue:false, duration:300, easing:'easeOutCirc'});
            $("#hovertriangle2").animate({top: ypos + "px"},{queue:false, duration:300, easing:'easeOutCirc'});	
					}
				});
				
				if(!check){
					$("#hovertriangle").hide();
					$("#hovertriangle2").hide();
				}
			}
		});
	}
  
  
  
}
function INITresultDetailMenu()
{
  //does result-detail-holder exists?
	if($("#result-detail-holder").size())
	{
		$("#result-detail-ul li a").click(function()
		{
			$.scrollTo(126, 600, {easing:'easeOutCirc', axis: 'y'});
      var getID = $(this).parent('li').index();
				switchtabs(getID);	
			return false;
		});
		$(".amaitab").click(function()
		{
			var getID = $(this).attr('rel');
				switchtabs(getID);
			return false;
		});
		
		$('#gMaps-print').click(function()
		{
			//get url
			var getUrl = $('#gMaps #logocontrol a').attr('href');
			var theUrl = getUrl + '&pw=2';
			window.open(theUrl); //, '_blank', 'toolbar=0,location=0,menubar=0'
			return false;
		});
		
		
		function switchtabs(id)
		{
			$("#result-detail-ul li a").removeClass('active');
			$("#result-detail-ul li a").each(function(intIndex){
				if(intIndex == id){$(this).addClass('active');}
			});
			$(".res-det-c").each(function(intIndex){
				if(intIndex == id){$(this).slideDown('normal', function(){
					if(intIndex==3)	{
						INITresult_gMaps();
					}
					else{
						$('#gMaps').html('');
					}
				});}
				else{$(this).slideUp();}
			});
		}
	}
	
	$('#result-label').css('display', 'block');
  $('#result-overview-holder').css('top', 30);
  
  $('#result-label a.backtolist').die().live('click', function(e) {
    e.preventDefault();  
    
    $('#result-closebtn').trigger('click');
  } );
  
//   if ( $('#result-detail-holder').is(':visible') )
//     {
      $('#headerDelen').css('left', 'auto');
      $('#headerPrint').css('left', 'auto');
      $('#headerDelen').css('right', 120);
      $('#headerPrint').css('right', 120);
      $('#wrap-content-head').addClass('background');
//     }
//     else
//     {
//       $('#headerDelen').css('right', 220);
//       $('#headerPrint').css('right', 220);
//     }
  $('#w_content #wrap-content-head .estateAddress').remove();
  address = $('.estateAddress').clone().appendTo('#w_content #wrap-content-head');  
  $('#w_content #wrap-content-head .estateAddress').prepend( '<span class="headerEstateId">Ref. '+$('#estateDetailEstateID').text()+'</span><br>' );
  Cufon.replace('#w_content #wrap-content-head .estateAddress');
  
  
  	if($("#form-right").size())
	{			
      $("#mess_schatting").hide();
		
			$(".RadioClass").click(function()
			{
				if($(this).is(":checked"))
				{
					$(".RadioLabelClass").removeClass("RadioSelected");
					$(this).next("label").addClass("RadioSelected");
				}
				
				if($(this).attr('id') == 'radio_bericht')
				{
					$("#mess_bericht").show(500);
					$("#mess_schatting").hide(500);
				}
				else
				{
					$("#mess_bericht").hide(500);
					$("#mess_schatting").show(500);
				}
			});
			

			//IE fix
			if($.browser.msie)
			{
				$("#form-right label").click(function(event) {
				 	var id = $(this).attr('for');
					$('#'+id).attr('checked', 'checked');
					$('#'+id).click();
				});
			}
	
	$("#detail-form input").blur(function()
		{
			var getID = $(this).attr("id");
			var getValue = $('label[for=' + getID + ']').text() ;
			
			$(this).css({backgroundColor:'#edfafa'});
		 	if ($(this).val() == ""){
				$(this).val(getValue);
				$(this).css({color:'#aaa'});
		 	}
		});
		$('#detail-form input').focus(function()
		{
			var getID = $(this).attr("id");
			var getValue = $('label[for=' + getID + ']').text() ;
			
			$(this).css({color:'#000', backgroundColor:'#f9f9f9'});
			if ($(this).val() == getValue){$(this).val("");}
			return false;
		});
	  
    INITDetailForm();
	   
    }
  
    //share buttons
//     console.log( document.location.href );
    var share_url = document.location.href.split('#', 2);
    if ( share_url.length==2 )
    {
      share_url=base_url+share_url[1].substr( 1, share_url[1].length );
//       console.log( share_url );
      $('#result-detail-options ul').append('<li><a href="#" id="right_share">'+$('#headerDelen a').text()+'</a></li><li><a href="http://www.facebook.com/sharer.php?u='+share_url+'&t=Vansweevelt%20-%20Zoekresultaten" id="right_fbshare" target="_blank">FB share</a></li>');
      $('#headerDelen').hide();
      $('#right_share').click( function(e){
        e.preventDefault();
        $('#headerDelen a').trigger('click');
      } );
    }
    
}

function INITDetailForm()
{

  	   $('#detail-form').bind('submit', function(e) {

      e.preventDefault();
      var ok=true;
      var input = $(this).find('input[type=text]');
      input.each( function() {
        var id = $(this).attr('id');

        $(this).next('span').removeClass('error');
        if ( $(this).val()==$('label[for='+id+']').text() )
        {
          $(this).next('span').addClass('error');
          ok=false;
        }        
      } );
     
      $('#f3').removeClass('error');
      if ( ! echeck($('#f3').val()) )
      {
        $('#f3').addClass('error');
        $('#f3').next('span').addClass('error');
        ok=false;
      }
      
//       $('#f9').next('span').removeClass('error');
//       if ( $('#f9').val()=='' )
//       {
//         $('#f9').next('span').addClass('error');
//         ok=false;
//       }
      
      if (ok)
      {
        $.ajax({
          type: 'POST',
          url: base_url+'submitEstateContact',
          data: $(this).serialize()
        });
        
        displayBox(base_url+'box_confirmation');
     
        $('#amaiboxcontent #bevestiging').css({'display':'none'});
        $('#amaiboxcontent #bevestiging').fadeIn(1000);
                      							
        if ( ! $.browser.msie){                  							
         	Cufon.replace('#amaiboxcontent h1');
          Cufon.replace('#amaiboxcontent h2');
        }
        amCountdown = setInterval ( "countdown()", 1000);
        countdown();
        
        input.each( function() {
          $(this).val('');
          $(this).trigger('blur');          
        });
        
        $('#f9').val('');
      }      
     });
    
    $('p.titles select').amaiSelect();
    
}

function INITprojectMenu()
{
	//does #wrap-project exists?
	if($("#wrap-project").size())
	{
		$("#wrap-project-ul li a").click(function()
		{
// 				setTimeout( function(){
//           $.scrollTo(580, 600, {easing:'easeOutCirc', axis: 'y'});
//         }, 500 );
			
      $.scrollTo(126, 600, {easing:'easeOutCirc', axis: 'y'});
      var getID = $(this).parent('li').index();
				switchtabs(getID);
				
				if ( $(this).attr('rel')=='big_table' )
				{          
          $.address.value('/nieuwbouw/detail/'+ $(this).parents('#wrap-project-ul').attr('class').substr(7) + '/kavels' );
          
          $('#w_content').css('overflow', 'visible');
          var table = $('#kavels-data-table');
          $(table).css( { 'position': 'relative' });

          var table_width = 0;
          table.children('table').each( function() 
          {
            var temp_width = $(this).outerWidth();
            if ( temp_width > table_width )
            {
              table_width = $(this).outerWidth();
            }
          });          
          //available width: 503px
          if ( table_width>503)
          {
            var table_position = table.offset();
            var left = table_width-503;
            left = ((left/2)*-1);
            if ( (left*-1) > table_position.left )
            {
              left = (table_position.left-15)*-1;
            }
            else
            {
              left = left-30;
            }
            $(table).css( { 'left': left });
          }

        $('#kavels-data-table tr').each( function() {
          var row=$(this);
          var lastPosition=1;
          row.children('td.property').each( function(index) {
            
            var cell = $(this);
            var sort = parseInt(cell.children('span.sort').attr('rel'));
            
            if ( sort!=lastPosition )
            {
              var missing=sort-lastPosition;
              for (var i=0;i<missing;i++)
              {
                cell.before('<td>&nbsp;</td>');
              }
              lastPosition=sort;
            }
            
              lastPosition++;
                       
          } );
        } );

        }
        else
        {
          $('#w_content').css('overflow', 'hidden');
        }
				
			return false;
		});
		$(".amaitab").click(function()
		{
			var getID = $(this).attr('rel');
				switchtabs(getID);
			return false;
		});
		function switchtabs(id)
		{
			$("#wrap-project-ul li a").removeClass('active');
			$("#wrap-project-ul li a").each(function(intIndex){
				if(intIndex == id){$(this).addClass('active');}
				
				if ( intIndex==4 )
				{
          setTimeout( 'INITresult_gMaps()', 500);
        }
				
			});
			
			$(".wrap-project-c").each(function(intIndex){
				if(intIndex == id){$(this).slideDown();}
				else{$(this).slideUp();}
			});
		 
    }
		switchtabs(0);
	 
	 INITtooltip();
	 
	}
	
		if($("#form-right").size())
	{			
      $("#mess_schatting").hide();
		
			$(".RadioClass").click(function()
			{
				if($(this).is(":checked"))
				{
					$(".RadioLabelClass").removeClass("RadioSelected");
					$(this).next("label").addClass("RadioSelected");
				}
				
				if($(this).attr('id') == 'radio_bericht')
				{
					$("#mess_bericht").show(500);
					$("#mess_schatting").hide(500);
				}
				else
				{
					$("#mess_bericht").hide(500);
					$("#mess_schatting").show(500);
				}
			});
			

			//IE fix
			if($.browser.msie)
			{
				$("#form-right label").click(function(event) {
				 	var id = $(this).attr('for');
					$('#'+id).attr('checked', 'checked');
					$('#'+id).click();
				});
			}
	
	$("#detail-form input").blur(function()
		{
			var getID = $(this).attr("id");
			var getValue = $('label[for=' + getID + ']').text() ;
			
			$(this).css({backgroundColor:'#edfafa'});
		 	if ($(this).val() == ""){
				$(this).val(getValue);
				$(this).css({color:'#aaa'});
		 	}
		});
		$('#detail-form input').focus(function()
		{
			var getID = $(this).attr("id");
			var getValue = $('label[for=' + getID + ']').text() ;
			
			$(this).css({color:'#000', backgroundColor:'#f9f9f9'});
			if ($(this).val() == getValue){$(this).val("");}
			return false;
		});
	 
	 
INITDetailForm();
	
    }
  
    //disable "terug naar lijst met project" indien second home
    if ( $('#wrap-project-options a.reverse').attr('rel')=='second_home' )
    {
      $('#wrap-content-head a#option').css('display', 'none');
    }
	
}
function INITresult_projectFields()
{
	//does #result-detail-holde or  exists?
	if($("#result-detail-holder").size() || $("#wrap-project-c").size())
	{	


		$("#form2 input").blur(function()
		{
			var getID = $(this).attr("id");
			var getValue = $('label[for=' + getID + ']').text() ;
			
			$(this).css({backgroundColor:'#edfafa'});
		 	if ($(this).val() == ""){
				$(this).val(getValue);
				$(this).css({color:'#aaa'});
		 	}
		});
		$('#form2 input').focus(function()
		{
			var getID = $(this).attr("id");
			var getValue = $('label[for=' + getID + ']').text() ;
			
			$(this).css({color:'#000', backgroundColor:'#f9f9f9'});
			if ($(this).val() == getValue){$(this).val("");}
			return false;
		});

	
	
		$("#date-1-txt").datepicker({
			showOn: 'both',
			buttonImage: base_url+'assets/img/layout/general/cal.gif',
			buttonImageOnly: false,
			showAnim: "slideDown",
			dateFormat:'dd/mm/yy'
		});
		
		$("#date-2-txt").datepicker({
			showOn: 'both',
			buttonImage: base_url+'assets/img/layout/general/cal.gif',
			buttonImageOnly: false,
			showAnim: "slideDown",
			dateFormat:'dd/mm/yy'
		});
		
		$("#date-3-txt").datepicker({
			showOn: 'both',
			buttonImage: base_url+'assets/img/layout/general/cal.gif',
			buttonImageOnly: false,
			showAnim: "slideDown",
			dateFormat:'dd/mm/yy'
		});
		
	}
}
function INITresult_projectImgNav()
{
	
	
	
	
	
	if($("#result-photo-next").size())
	{	
		$('#result-detail-img div:first').addClass('active');
		$("#result-photo-next").click(function(e)
		{
			e.preventDefault();
      nextImg($("#result-detail-img"));
			
		});
	}
	
	if($("#project-photo-next").size())
	{	
		$('#wrap-project-img div:first').addClass('active');
		$("#project-photo-next").click(function(e)
		{
			e.preventDefault();
      nextImg($("#wrap-project-img"));
			
		});
	}

  if($("#result-detail-img").size()){
    var imageholder=$("#result-detail-img");
      //fix image positioning
			imageholder.find('.active img').each( function() {
        var image = $(this);
        if ( ! image.hasClass('image-position-fixed'))
          {
            if (image.width()!=imageholder.width())
            {
              var whitespace = imageholder.width()-image.width();
              image.css('marginLeft', whitespace/2);
            }
            image.addClass('image-position-fixed');
          }
      });    
	}
	
	if($("#wrap-project-img").size()){
		var imageholder=$("#wrap-project-img");
      //fix image positioning
			imageholder.find('.active img').each( function() {
        var image = $(this);
        if ( ! image.hasClass('image-position-fixed'))
          {
            if (image.width()!=imageholder.width())
            {
              var whitespace = imageholder.width()-image.width();
              image.css('marginLeft', whitespace/2);
            }
            image.addClass('image-position-fixed');
          }
      });
    
	}

}
	function nextImg(obj)
	{
		
    var children = obj.children('div.img');
    
    children.css('display', 'none');
    
//     children.fadeOut();
    
    var show_next=false;
    var next_shown=false;
    children.each( function() {
      var child = $(this);
        
      if (show_next)
      {
//         child.css('display', 'block');
        child.fadeIn();
        child.addClass('active');
        next_shown=true;   
             
        return false;
      }
      
      if (child.hasClass('active'))
      {
        show_next=true;
        child.removeClass('active');
      }
    } );    
    if ( ! next_shown)
    {
//       obj.children(':first-child').css('display', 'block').addClass('active');
      obj.children(':first-child').fadeIn().addClass('active');
    }
    
    if(obj.size()){
  		  var imageholder=obj;
        //fix image positioning
  			imageholder.find('.active img').each( function() {
          var image = $(this);
          if ( ! image.hasClass('image-position-fixed'))
          {
            if (image.width()!=imageholder.width())
            {
              var whitespace = imageholder.width()-image.width();
              image.css('marginLeft', whitespace/2);
            }
            image.addClass('image-position-fixed');
          }
        });         
	      }
  }
  function prevImg(obj)
	{
		var children = obj.children('div.img');    
    children.css('display', 'none');    
    
    activeIndex = obj.children('div.active').index();
    
    children.removeClass('active');
    if (activeIndex==0)
    {
      obj.children('div:nth-child('+(children.length)+')').fadeIn().addClass('active');
    }
    else
    {
      obj.children('div:nth-child('+(activeIndex)+')').fadeIn().addClass('active');
    }    

    if(obj.size()){
  		  var imageholder=obj;
        //fix image positioning
  			imageholder.find('.active img').each( function() {
          var image = $(this);
          if ( ! image.hasClass('image-position-fixed'))
          {
            if (image.width()!=imageholder.width())
            {
              var whitespace = imageholder.width()-image.width();
              image.css('marginLeft', whitespace/2);
            }
            image.addClass('image-position-fixed');
          }
        });         
	      }
  }
	function animateImg(obj)
	{
		var mouseX;
		var mouseY;
		var holderW = $(obj).width();
		var holderH = $(obj).height();
		var imgObj;
		var imgW;
		var imgH;
		var posX;
		var posY;
		var diffX;
		var diffY;

		$(obj).mousemove(function(e)
		{
			holderW = $(this).width();
			holderH = $(this).height();
			imgObj = $(this).find('.active');
			imgW = imgObj.find('img').width();
		 	imgH = imgObj.find('img').height();

			if(holderW < imgW && holderH < imgH)
			{
				imgObj.stop();
				mouseX = e.pageX - $(this).offset().left;
				mouseY = e.pageY - $(this).offset().top;
				diffY = (holderH/imgH) * mouseY;
				posY = (diffY - mouseY);
				diffX = (holderW/imgW) * mouseX;
				posX = (diffX - mouseX);
				imgObj.css({'top':posY+'px','left':posX+'px'});
			}
		});
		$(obj).mouseout(function()
		{
			animateCenter($(this));
		});
	
		animateCenter(obj);	
	}
	function animateCenter(obj)
	{
		var holderW = obj.width();
		var holderH = obj.height();
		var imgObj = obj.find('.active');
		var imgW = imgObj.find('img').width();
	 	var imgH = imgObj.find('img').height();
	
		if(holderW < imgW && holderH < imgH)
		{
	        var outPosX = -(imgW - holderW)/2;
	        var outPosY = -(imgH - holderH)/2;
	        imgObj.animate({'top':outPosX+'px','left':outPosY+'px'},{queue:false, duration:600, easing:'easeOutCirc'});
		}

	}
	function INITresult_gMaps()
	{
		//does gMaps exists?
		if($("#gMaps").size())
		{
			if ($('#amaiboxcontent').is(':visible') )
      {
        var gmap=$('#amaiboxcontent #gMaps');
        gmap.before('<div id="gMaps2" />');
        var gmap2=$('#amaiboxcontent #gMaps2');
      }
      else
      {
        var gmap=$("#gMaps");
        gmap.before('<div id="gMaps2" />');
        var gmap2=$('#gMaps2');
      }
// 			
      var gAddress = $("#gMaps-data").text();
// 			gmap.gMap({ 
// 					markers: [{ address: gAddress}], 
// 					address: gAddress, 
// 					maptype: G_HYBRID_MAP,
// 					scrollwheel: false,
// 					controls: ['GLargeMapControl', 'GMapTypeControl'],
// 					zoom: 18
// 					/*,maptype: G_HYBRID_MAP*/
// 			});
      
      
//       var latlng = new google.maps.LatLng(43.990155,4.108452);
      
//       var latlng;
      var sv = new google.maps.StreetViewService();

		  var geocoder = new google.maps.Geocoder();
		  geocoder.geocode( { 'address': gAddress}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
          
          
          var myOptions = {
                  zoom: 16,
                  center: results[0].geometry.location,            
                  mapTypeId: google.maps.MapTypeId.ROADMAP
                };
        
            var streetOptions={
                  
                  position: results[0].geometry.location
//                   pov: {
//                     heading: heading,
//                     pitch: 10,
//                     zoom: 1
//                   }            
                  
                };;
            

//             console.log( test );
        var map = new google.maps.Map(gmap2.get(0), myOptions);
         
//         console.log( streetOptions );
        var panorama = new  google.maps.StreetViewPanorama(gmap.get(0),streetOptions);
//         console.log( panorama );

            sv.getPanoramaByLocation( results[0].geometry.location, 1000, function( data, status ){
//               console.log( data, status );
//                 var carlatlng=data.location.latlng;
//                 console.log( status );
//                 console.log( data.location.latLng );
//                 console.log( results[0].geometry.location );
                var heading=google.maps.geometry.spherical.computeHeading( data.location.latLng, results[0].geometry.location );
//                 console.log( heading );
  
                panorama.setPov( {
                    heading: heading,
                    pitch: 10,
                    zoom: 2                  
                } );
//                 streetOptions = {
//                   
//                   position: results[0].geometry.location,
//                   pov: {
//                     heading: heading,
//                     pitch: 10,
//                     zoom: 1
//                   }            
//                   
//                 };
  
            } );
        
//         console.log( panorama );
         
         
         
          var marker = new google.maps.Marker({
              map: map, 
              position: results[0].geometry.location
          });
        }
        
      });
		  
    }
		
		
	}

	

function INITpages()
{
	
	//does #form-left exists?
	if($("#form-left").size())
	{
			$("#form-left input").blur(function()
			{
				var getID = $(this).attr("id");
				var getValue = $('label[for=' + getID + ']').text() ;
				
				$(this).css({backgroundColor:'#edfafa'});

			 	if ($(this).val() == ""){
					$(this).val(getValue);
					$(this).css({color:'#aaa'});
			 	}
			});
			$('#form-left input').focus(function()
			{
				var getID = $(this).attr("id");
				var getValue = $('label[for=' + getID + ']').text() ; 

				$(this).css({color:'#000', backgroundColor:'#f9f9f9'});
				if ($(this).val() == getValue){$(this).val("");}
				
				return false;
			});
		}

	//does #info-diensten-txt exists?
	if($("#info-diensten-txt").size())
	{
			$("ul#info-diensten-m li a").click(function()
			{
				var getID = $(this).parent('li').index();
				switchtabs(getID);	
				return false;
			});
			$(".amaitab").click(function()
			{
				var getID = $(this).attr('rel');
					switchtabs(getID);
				return false;
			});
			$("#onze-troeven-click").click( function()
      {
        switchtabs(6);
        return false;
      });
			function switchtabs(id)
			{
				$("ul#info-diensten-m li a").removeClass('active');
				$("ul#info-diensten-m li a").each(function(intIndex){
					if(intIndex == id){$(this).addClass('active');}
				});

				$(".info-diensten-txt-c").each(function(intIndex){
					if(intIndex == id){$(this).show(300);}
					else{$(this).hide(300);}
				});
			}
			switchtabs(0);
		}

	//does #info-diensten-txt exists?
	if($("#form-right").size())
	{
			$("#mess_schatting").hide();
		
			$(".RadioClass").click(function()
			{
				if($(this).is(":checked"))
				{
					$(".RadioLabelClass").removeClass("RadioSelected");
					$(this).next("label").addClass("RadioSelected");
				}
				
				if($(this).attr('id') == 'radio_bericht')
				{
					$("#mess_bericht").show(500);
					$("#mess_schatting").hide(500);
				}
				else
				{
					$("#mess_bericht").hide(500);
					$("#mess_schatting").show(500);
				}
			});
			

			//IE fix
			if($.browser.msie)
			{
				$("#form-right label").click(function(event) {
				 	var id = $(this).attr('for');
					$('#'+id).attr('checked', 'checked');
					$('#'+id).click();
				});
			}
	
    }

	if($("#schatting-form").size())
	{
			$("a.schatting-from-down").click(function()
			{
				$('#schatting-form-wrapper').slideDown();	
				return false;
			});
			$("a.schatting-from-up").click(function()
			{
				$('#schatting-form-wrapper').slideUp();	
				return false;
			});
		}	
}
	function slideHomeImg()
	{		
		var $active = $('#img-rotator div.active');
		if ( $active.length == 0 ) $active = $('#img-rotator div:last');
		
		var $next =  $active.next().length ? $active.next() : $('#img-rotator div:first');

		$active.addClass('last-active');

		$next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() {
			    $active.removeClass('active last-active');
		});
	}
	function slideHomeTxt()
	{		
// 		var $active = $('#l2 a.active');
// 		if ( $active.length == 0 ) $active = $('#l2 a:last');
// 		
// 		var $next = $active.next().length ? $active.next() : $('#l2 a:first');
// 
// 		$active.addClass('last-active');
// 
// 		$next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() {
// 			    $active.removeClass('active last-active');
// 		});
	}
	

function INITscrollup()
{
	//does .up exists?
	
		$('.up').die().live('click', function(e){
			e.preventDefault();
      $.scrollTo($('body'), 600, {easing:'easeOutCirc'});
	
		});
	
}
function INITtooltip()
{
		xOffset = 5;
		yOffset = 10;		

		$(".tooltip").hover(
	
		function(e)
		{
			this.t = this.title;
			
			if(this.t != "")
			{
				this.title = "";									  
				$("body").append("<div id='tooltip'>"+ this.t +"</div>");
				$("#tooltip")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px")
				.css("display", "none")
				.fadeIn("fast");
			}		
	},
		function()
		{
			if(this.t != "")
			{
				this.title = this.t;		
				$("#tooltip").remove();
			}
	});	
	
	$('.tooltip').click( function(e) {
    if ( ! $(this).hasClass('clickable') )
    {  
      e.preventDefault();
    }
  } );
	
		$(".tooltip").mousemove(function(e){
			$("#tooltip").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px");
		});			
}
function INITpagination()
{
	//does a.result-l exists?
	if($("#result-pagination").size())
	{			

      $('#pagination_next').insertBefore('#pagination_cur');
      $('#pagination_prev').insertBefore('#pagination_next');
      
      if ( ! $.browser.msie){
      Cufon.replace('#result-pagination', { hover: true } );
      }
		
		
    $('#result-pagination a').die().live('click', function(e) 
		{
			e.preventDefault();
			
			var url = $(this).attr('href').substr( base_url.length, ($(this).attr('href').length-base_url.length)  );
			
			$.address.value(url);
			
			$.scrollTo($('body'), 600, {easing:'easeOutCirc'}); 
			
		});
	}
}


function INITamaibox()
{
	// displayBox(ajaxurl); //activate box at load page
	var divInnerHeight;
	
	$('.amaibox').die().live('click', function(e) {
	  	e.preventDefault();
      var dataUrl = $(this).attr('rel');
		
		if ($(this).hasClass('map'))
		{      
      var box = $('#amaiboxcontent');
      box.css( { 'width': 800, 'height': 490, 'marginLeft': -450, 'marginTop': -295 } );
      box.removeClass("smallbox");
    }
    else
    {      
      var box = $('#amaiboxcontent');
      box.css( { 'width': 546, 'height': 490, 'marginLeft': -323, 'marginTop': -295 } );
      box.addClass("smallbox");
    }
    
    displayBox(dataUrl);
		
	});
	$('.amaibox-close').die().live('click',function(e){
		e.preventDefault();
    closeBox();
		
	});
	$('#amaibox').die().live('click',function(e){
		e.preventDefault();
    closeBox();
		
	});

	amaiboxdata();
	saturateImages();
}
	
	function displayBox(dataUrl)
	{
		if ($('#motor_menu a.active').attr('rel'))
		{
      var active_part=$('#motor_menu a.active').attr('rel');
    }
    else
    {
      var active_part='estate';
    }
		
    ajaxClear();
    ajaxRequest = $.ajax(
                		{
                			type: "POST",
                			url:dataUrl,
                			data: { 'search': motor_model.getJSON(),
                              'active_part': active_part,
                              'href': document.location.href },
                			beforeSend: function()
                			{
                				doLoader(true);
                			},
                			success: function(data, status, XMLHttpRequest) 
                			{
                				if (XMLHttpRequest.status==200)
                  			{
                        doLoader(false);
                				
                				data = '<div id="amaiboxclose"><a href="#" title="close" class="amaibox-close"></a></div>' + data ;
                				
                				$('#amaiboxcontent').html(data);
                				amaiboxdata();
                				if ( ! $.browser.msie){
                        Cufon.replace('#amaiboxcontent h1');
                				Cufon.replace('#amaiboxcontent h2');
                				}
                				
                				if (jQuery.browser.msie) {
                					$('#amaibox, #amaiboxcontent').css({'display':'block'});
										        INITcopypaste();
                				}
                				else { //other browsers
                					$('#amaibox, #amaiboxcontent').css({opacity:0,'display':'block'});
                					$('#amaibox, #amaiboxcontent').stop().animate({opacity:1}, {queue:false, duration:350, complete:function(){
										        INITcopypaste();
                            }});
                				}
                				$("#loginForm input").blur(function()
                    		{
                    			var getID = $(this).attr("id");
                    			var getValue = $('#loginForm label[for=' + getID + ']').text() ;
                    			
                    			$(this).css({backgroundColor:'#edfafa'});
                    		 	if ($(this).val() == ""){
                    				$(this).val(getValue);
                    				$(this).css({color:'#aaa'});
                    		 	}
                    		});
                    		$('#loginForm input').focus(function()
                    		{
                    			var getID = $(this).attr("id");
                    			var getValue = $('#loginForm label[for=' + getID + ']').text() ;
                    			
                    			$(this).css({color:'#000', backgroundColor:'#f9f9f9'});
                    			if ($(this).val() == getValue){$(this).val("");}
                    			return false;
                    		});
                
                			}
                			
                			if ( $('#amaiboxcontent #result-detail').is(':visible') )
                			{
                        var result_detail = $('#amaiboxcontent #result-detail');
                        
                        var estateAddress = result_detail.find('p.estateAddress');
                        var newaddress = estateAddress.clone();
                        newaddress.prependTo(result_detail).addClass('popupHeader');
                        Cufon.replace('#amaiboxcontent .popupHeader');
                        
                        var longest=0;
                        result_detail.find('.res-det-c').each( function() {
                          var $this = $(this);
                          if ( $this.height()> longest )
                          {
                            result_detail.find('.res-det-c').css('display', 'none');
                            $this.css('display', 'block');
                            longest=$this.height();
                          }
                        } );
                        
                        var scrollPane = result_detail.jScrollPane( { animateScroll: true,
                                                                      animateEase: 'easeOutCirc',
                                                                      animateDuration: 600 } );
                        
                        var scrollPaneAPI = scrollPane.data('jsp');
                        $('#amaiboxclose').addClass('result-view');
                        
                        //Make 1st image visible
                        result_detail.find('#result-detail-img').children('.img:first').css('display', 'block').addClass('active');
                        
                        //fix image size
                        var wrapper_width=result_detail.find('#result-detail-img').width();
                        var images=result_detail.find('#result-detail-img img');
                        images.removeAttr('height').removeAttr('width');
                        images.each( function() {
                          var image = $(this);
                          var height = image.height();
                          var width = image.width();
                          if ( width > height )
                          {
                            image.width(486);
                          }
                          else
                          {
                            image.height(365);
                          }
                          if (image.width()<wrapper_width)
                          {
                            var temp=((wrapper_width - image.width())/2);
                          }
                        } );
                        
                        //tabs
                        var tabs_a = result_detail.find('#result-detail-ul li a');
                        tabs_a.click(function(e)
                    		{
                    			 e.preventDefault();
                            var getID = $(this).parent('li').index();
                    				switchtabs(getID); 
                    		  scrollPaneAPI.scrollToY(350);                           
                    		});
                        
                        function switchtabs(id)
                    		{
                    			tabs_a.removeClass('active');
                    			tabs_a.each(function(intIndex){
                    				if(intIndex == id){$(this).addClass('active');}
                    			});
                    			result_detail.find(".res-det-c").each(function(intIndex){
                    				if(intIndex == id){$(this).slideDown('normal', function(){
                    					if(intIndex==3)	{
                    						INITresult_gMaps();
                    					}
                    					else{
                    						$('#gMaps').html('');
                    					}                             
                            });}
                    				else{$(this).slideUp('normal', function () {                                               
                            } );}
                    			});                		  
                        }                    		
                    		switchtabs(0);
                      
                        Cufon.replace('#amaiboxcontent #result-detail-ul a');
                        Cufon.replace('#amaiboxcontent h3');
                        Cufon.replace('#amaiboxcontent .printURL');
                        
                        result_detail.find('#result-detail-img a').removeAttr('rel').removeAttr('href');
                        
                        var amaiboxcontent = $('#amaiboxcontent');
                        amaiboxcontent.find('.jspPane').append('<a id="amai_next" href="#">next</a><a id="amai_prev" href="#">prev</a>');
                        amaiboxcontent.find('#amai_next').addClass('results');
                        amaiboxcontent.find('#amai_prev').addClass('results');
                        
                        $('#amai_next').click( function() {
                          nextImg(result_detail.find('#result-detail-img') );
                          $('#amai_next').delay(500).fadeIn();
                          $('#amai_prev').delay(500).fadeIn();
                        } );
                        $('#amai_prev').click( function() {
                          prevImg(result_detail.find('#result-detail-img') );
                          $('#amai_prev').delay(500).fadeIn();
                          $('#amai_next').delay(500).fadeIn();
                        } );                        
                        
                  		  var imageholder=result_detail.find('#result-detail-img');
                        //fix image positioning
                  			imageholder.find('.active img').each( function() {
                          var image = $(this);
                          if ( ! image.hasClass('image-position-fixed'))
                          {
                            if (image.width()!=imageholder.width())
                            {
                              var whitespace = imageholder.width()-image.width();
                              image.css('marginLeft', whitespace/2);
                            }
                            image.addClass('image-position-fixed');
                          }
                        });         
                	    
                      //form inputfields 
                      result_detail.find('input[type=text]').blur(function(){
                				var getID = $(this).attr("id");
                				var getValue = result_detail.find('label[for=' + getID + ']').text() ;
                				$(this).css({backgroundColor:'#edfafa'});
                			 	if ($(this).val() == ""){
                					$(this).val(getValue);
                					$(this).css({color:'#aaa'});
                				}
                			});
                			result_detail.find('input[type=text]').focus(function(){
                				var getID = $(this).attr("id");
                				var getValue = result_detail.find('label[for=' + getID + ']').text();
                				$(this).css({color:'#000', backgroundColor:'#f9f9f9'});
                				if ($(this).val() == getValue){$(this).val("");}
                				return false;
                			});
                      
                      result_detail.find('ul li.c').remove();
                      
                      var images = result_detail.find('#result-detail-img div');
                      images.each( function() {
                        $(this).find('img').appendTo( $(this) );
                        $(this).find('a').remove();
                      } );
                      }	
                			}
                		});
		
		/*
		if (jQuery.browser.msie) {
			$('#amaibox, #amaiboxcontent').css({'display':'block'});
		}
		else { //other browsers
			$('#amaibox, #amaiboxcontent').css({opacity:0,'display':'block'});
			$('#amaibox, #amaiboxcontent').stop().animate({opacity:1}, {queue:false, duration:350, complete:function(){}});
		}
		
		divInnerHeight = $('#amaiboxcontent .con .m').innerHeight();
		*/
		desaturate();
		setTimeout('desaturate(true)', 500);
    bindResize();
	}
	function closeBox()
	{
		
		//store info
		
		//zoekopdracht
		if($("form#zoekopdracht").size())
		{
			var name  	 = $('#zoekopdracht input[name=name]').val();
			var email  	 = $('#zoekopdracht input[name=email]').val();
			var address  = $('#zoekopdracht input[name=address]').val();
			var city 	 = $('#zoekopdracht input[name=address2]').val();
			var phone 	 = $('#zoekopdracht input[name=phone]').val();
			var notes 	 = $('#zoekopdracht textarea').val();
		
			amaiboxdata_form_zoekopdracht = [];
			amaiboxdata_form_zoekopdracht = [name, email, address, city, phone, notes];
		}
		
		//critera
		if($("form#critera").size())
		{
			amaiboxdata_form_criteria = [];
			amaiboxdata_form_criteria = [$('#selectie-mail').val()];
		}
		
		if($("form#delen").size())
		{
			//delen
			var email1  = $('#delen input[name=email1]').val();
			var email2 	= $('#delen input[name=email2]').val();
			var name  	= $('#delen input[name=name]').val();
			var email  	= $('#delen input[name=email]').val();
			
			amaiboxdata_form_delen = [];
			amaiboxdata_form_delen = [email1, email2, name, email];
		}
		
		
		if (jQuery.browser.msie) {
			$('#amaibox, #amaiboxcontent').css({'display':'none'});
			clearamaibox();
		}
		else { //other browsers
			$('#amaibox, #amaiboxcontent').stop().animate({opacity:0}, {queue:false, duration:350,  complete:function()
			{
				$('#amaibox, #amaiboxcontent').css({'display':'none'});
				clearamaibox();
			}});
		}
		
		unbindResize();
		if(copyClip){
			copyClip.destroy();
			copyClip2.destroy();
		}
		reset_img();
		
		clearInterval(amCountdown);
		amCountdownTotal = 4;
	}
	function bindResize()
	{
		$(window).resize(function() {
			//resizeBox();
			if(copyClip){
				copyClip.reposition();
				copyClip2.reposition();
			}
			
		});
	}
	function unbindResize()
	{
		$(window).unbind('resize');
	}
	function resizeBox()
	{
		//check if fixed height or not
		if($('#amaiboxcontent .con .m').hasClass('noscroll'))
		{
			//box has a fixed height -> no scroll + don't resize box
		}
		else
		{
			var amaiboxH = $('#amaiboxcontent').height() - 80;
			var t 		 = $('#amaiboxcontent .con .t').height();
			var b		 = $('#amaiboxcontent .con .b').height();
			var m 		 = divInnerHeight;
			var tb 		 = t+b;
			var tot		 = tb+m;
			var spaceBox = 60 + 80 + 80;
			var windowH  = $(window).height();
			var min	 	 = 340;
			var max 	 = windowH;

			var c		 = $('#amaiboxcontent .con .m');

			if(max < (tot+spaceBox))
			{
				if(max > (min+spaceBox+tb)){
					var val = max - tb - spaceBox;
					c.height(val);
				}
			}
			else{
				c.height(m);
			}
		}

		//center vertically
		var H = $('#amaiboxcontent').height();
		var M = -H/2;
		$('#amaiboxcontent').css({'marginTop':M});
	}
	
	function saturateImages()
	{
		//var paircount = 0;
	
		$("#wrap_main .img").each(function(intIndex)
		{
// 			if($(this).find('img').size())
			if(false)
			{
				/* check if the filter is applied */
				if( ! $(this).find(":nth-child(1)").hasClass('des') ) 
				{
					if( $(this).is('.imgholder')) {
						//add fixed height when relative
						$(this).height($(this).find('img').height());
					}
				    var $newthis = $(this).find('img');
				    if ($.browser.msie){
				      // You need this only if desaturate png with aplha channel
				      $newthis = $newthis.desaturateImgFix();
				    }
				    // class for easy switch between color/gray version
				    //$newthis.addClass("pair_" + ++paircount);
				    var $cloned = $newthis.clone();
				    // add cloned after original image, we will switch between
				    // original and cloned later
				    $cloned.insertAfter($newthis);
				    // desaturate original
					$newthis.addClass("des");
			    	try
			    	{
              $newthis.desaturate();
            }
            catch(err)
            {}
          $(this).find('img').addClass('sat');
				} 	
			}
		});
	}
	function desaturate(onlyMotor)
	{
		//motor
		$('.motor_op').css({'backgroundImage':'none'});
		$('.motor_op').animate({'backgroundColor':'#efefef'}, {queue:false, duration:amBOX,  easing:'easeOutCirc'});
		$('#motor_info').animate({'backgroundColor':'#efefef'}, {queue:false, duration:amBOX,  easing:'easeOutCirc'});		
		$('.motor_op h2').css({'backgroundImage':'url('+base_url+'assets/img/layout/motor/triangle-bw.png)'});
		$('#motor_op1 ul.topmenu li a.active').css({'backgroundImage':'url('+base_url+'assets/img/layout/motor/triangle-bw.png)'});
		$('.ui-widget-content').css({'backgroundImage':'url('+base_url+'assets/img/layout/motor/slider-bg-bw.png)'});
		
		if (!onlyMotor)
    {
      if ($.browser.msie)
  		{
        //$(".img .js-desaturate-fixed:not(.des)").fadeOut(amBOX);
        $(".img .sat").fadeOut(amBOX);
        $(".img .des").fadeIn(amBOX);
      }
      else
      {
        
        $(".img .sat").fadeOut(amBOX);
        $(".img .des").fadeIn(amBOX);
      }
  	
  		$("ul.menu li a").each
  		(
  			function(intIndex){
  				if ($(this).is('.active')){
  					$(this).animate({'backgroundColor':'#efefef'}, {queue:false, duration:amBOX,  easing:'easeOutCirc'});
  				}else{
  					$(this).animate({'backgroundColor':'#f6f6f6'}, {queue:false, duration:amBOX,  easing:'easeOutCirc'});
  				}
  		});
  		
  		
  		$('.result-m p').css({'color':'#ccc'});
  		
  		/* PROJECTEN */
  
  		$('.project-r a').css({'color':'#ccc'});
  		
  		
  		/* INFO  & CONTACT */
  		
  		$("#info-diensten-m li a").each(
  			function(intIndex){
  				if ($(this).is('.active')){}
  				else{
  					$(this).css({'color':'#ccc'});
  				}
  			}
  		);
  		$(".info-gegevens-b-c a").css({'color':'#ccc'});
  		
  		//Cufon.set('color', '#999999').replace("#contact-form h2");
  		//$('#contact-form h2').addClass('desaturate_1');
  		//Cufon.refresh('#contact-form h2');
  		
  		//Cufon.refresh('#info-diensten-m li a');
  		//Cufon.refresh('.info-gegevens-b-c ul li a');
  
  		$('#contact-form input').css({'backgroundColor':'#efefef'});
  		$('#contact-form input.btn').css({'backgroundColor':'#fff', 'color':'#ccc'});
  		$('#contact-form textarea').css({'backgroundColor':'#efefef'});
  		
  		$('#form2 input').css({'backgroundColor':'#efefef'});
  		$('#form2 input.btn').css({'backgroundColor':'#fff', 'color':'#ccc'});
  		$('#form2 textarea').css({'backgroundColor':'#efefef'});
  		
  		$('#contact-position h1').css({'backgroundColor':'#efefef'});
  		$('#contact-position p').css({'backgroundColor':'#efefef'});
  	
  	  $('#result-label').css({'backgroundColor':'#efefef'});
  	  
  	  if ( $('font').attr('color') )
  	  {
        $('font').attr('normal_color', $('font').attr('color') );
        $('font').attr('color', '#666666');
      }
    
      $('#result-poleposition').css({'backgroundColor':'#efefef'});
    }
  }
	function reset_img()
	{
		if ($.browser.msie)
		{
      $(".img .js-desaturate-fixed:not(.des)").fadeIn(amBOX);
      $(".img .sat").fadeIn(amBOX);

    }
    else
    {
      $(".img img:not(.des)").fadeIn(amBOX);
    }
	
		$("ul.menu li a").each(
			function(intIndex){
				if ($(this).is('.active')){
					$(this).animate({'backgroundColor':'#D4F3EE'}, {queue:false, duration:amBOX,  easing:'easeOutCirc', complete:function(){
						$(this).removeAttr('style');
					}});	
				}else{
					$(this).animate({'backgroundColor':'#F7F7F7'}, {queue:false, duration:amBOX,  easing:'easeOutCirc', complete:function(){
						$(this).removeAttr('style');
					}});
				}
			}
		);
	
		$('.motor_op').css({'backgroundImage':'none'});
		$('#motor_info').animate({'backgroundColor':'#D4F3EE'}, {queue:false, duration:amBOX,  easing:'easeOutCirc'});
		$('#motor_op1').animate({'backgroundColor':'#D4F3EE'}, {queue:false, duration:amBOX,  easing:'easeOutCirc'});
		$('#motor_op3').animate({'backgroundColor':'#D4F3EE'}, {queue:false, duration:amBOX,  easing:'easeOutCirc'});
		
		$('#motor_op2').animate({'backgroundColor':'#D9F8F3'}, {queue:false, duration:amBOX,  easing:'easeOutCirc'});
		
		$('.result-m p').css({'color':'#b1cc23'});
		$('.motor_op h2').css({'backgroundImage':'url('+base_url+'assets/img/layout/motor/triangle.png)'});
		$('#motor_op1 ul.topmenu li a.active').css({'backgroundImage':'url('+base_url+'assets/img/layout/motor/triangle.png)'});
		$('.ui-widget-content').css({'backgroundImage':'url('+base_url+'assets/img/layout/motor/slider-bg.png)'});
		
		
		/* PROJECTEN */

		$('.project-r a').css({'color':'#b1cc23'});
		
		
		/* INFO  & CONTACT */
		$("#info-diensten-m li a").each(
			function(intIndex){
				if ($(this).is('.active')){}
				else{
					$(this).css({'color':'#b1cc23'});
				}
			}
		);
		$(".info-gegevens-b-c a").css({'color':'#b1cc23'});
		
		$('#contact-form input').css({'backgroundColor':'#edfafa'});
		$('#contact-form input.btn').css({'backgroundColor':'#fff', 'color':'#b1cc23'});
		$('#contact-form textarea').css({'backgroundColor':'#edfafa'});
		
		$('#form2 input').css({'backgroundColor':'#edfafa'});
		$('#form2 input.btn').css({'backgroundColor':'#fff', 'color':'#b1cc23'});
		$('#form2 textarea').css({'backgroundColor':'#edfafa'});
		
		$('#contact-position h1').css({'backgroundColor':'#FFFF00'});
		$('#contact-position p').css({'backgroundColor':'#FFFF00'});
		
		$('#result-label').css({'backgroundColor':'#FFFF00'});
		
		//result images
		if (resultHideDetail)
		{
      $('#result-overview-holder .result img.des').css('display', 'block');
      $('#result-overview-holder .result img.sat').css('display', 'none');
      
      $('#result-overview-holder .result a[rel='+activeEstateDetail+'] img.sat').css('display', 'block');
    }
	  
	  if ( $('font').attr('normal_color') )
	  {
      $('font').attr('color', $('font').attr('normal_color') );
      $('font').removeAttr('normal_color');
    }
	$('#result-poleposition').css({'backgroundColor':'#ffff00'});
  }

	function amaiboxdata()
	{
		//does #form#zoekopdracht exists?
		if($("form#zoekopdracht").size())
		{
      
      $("#zoekopdracht select").amaiSelect();
      
			$("#zoekopdracht input[type=text], #zoekopdracht textarea").blur(function(){
				var getID = $(this).attr("id");
				var getValue = $('label[for=' + getID + ']').text() ;
				$(this).css({backgroundColor:'#edfafa'});
			 	if ($(this).val() == ""){
					$(this).val(getValue);
					$(this).css({color:'#aaa'});
				}
			});
			$('#zoekopdracht input[type=text], #zoekopdracht textarea').focus(function(){
				var getID = $(this).attr("id");
				var getValue = $('label[for=' + getID + ']').text();
				$(this).css({color:'#000', backgroundColor:'#f9f9f9'});
				if ($(this).val() == getValue){$(this).val("");}
				return false;
			});
			
			//if info -> set info
			if(amaiboxdata_form_zoekopdracht.length > 0)
			{
				$('#zoekopdracht input[name=name]').val(amaiboxdata_form_zoekopdracht[0]);
				$('#zoekopdracht input[name=email]').val(amaiboxdata_form_zoekopdracht[1]);
				$('#zoekopdracht input[name=address]').val(amaiboxdata_form_zoekopdracht[2]);
				$('#zoekopdracht input[name=address2]').val(amaiboxdata_form_zoekopdracht[3]);
				$('#zoekopdracht input[name=phone]').val(amaiboxdata_form_zoekopdracht[4]);
				$('#zoekopdracht textarea').val(amaiboxdata_form_zoekopdracht[5]);
				
				$("#zoekopdracht input[type=text], #zoekopdracht textarea").each(function(intIndex){
					var getID = $(this).attr("id");
					var getValue = $('label[for=' + getID + ']').text();
					
					if ($(this).val() != getValue){
						$(this).css({color:'#000'});
					}
				});
			}
		
			$('#zoekopdracht').submit(function(){
				
        
        var ok=true;
        var input = $(this).find('input[type=text]');
        input.each( function() {
          var id = $(this).attr('id');

          $(this).next('span').removeClass('error');
          if ( $(this).val()==$('label[for='+id+']').text() )
          {
            $(this).next('span').addClass('error');
            ok=false;
          }        
        } );
       
        $('#ppf3').removeClass('error');
        if ( ! echeck($('#ppf3').val()) )
        {
          $('#ppf3').addClass('error');
          $('#ppf3').next('span').addClass('error');
          ok=false;
        }
        
//         $('#ppf6').next('span').removeClass('error');
//         if ( $('#ppf6').val()=='' )
//         {
//           $('#ppf6').next('span').addClass('error');
//           ok=false;
//         }
        
        if (ok)
        {
        //get data form
				var title  	 = $('#zoekopdracht select[name=title]').val();
        var name  	 = $('#zoekopdracht input[name=name]').val();
        var fname  	 = $('#zoekopdracht input[name=fname]').val();
				var email  	 = $('#zoekopdracht input[name=email]').val();
				var address  = $('#zoekopdracht input[name=address]').val();
				var number  = $('#zoekopdracht input[name=number]').val();
				var zip 	 = $('#zoekopdracht input[name=zip]').val();
				var city 	 = $('#zoekopdracht input[name=address2]').val();
				var phone 	 = $('#zoekopdracht input[name=phone]').val();
				var notes 	 = $('#zoekopdracht textarea').val();
				
				//search_array;
				
			  	ajaxClear();
          		ajaxRequest = $.ajax(
               	{
                 	type: "POST",
                  	url: base_url+'register_search',
                  	data: { search: motor_model.getJSON(),
                            title: title,
                            name: name,
                            fname: fname,
                            email: email,
                            address: address,
                            number: number,
                            zip: zip,
                            city: city,
                            phone: phone,
                            notes: notes },
                  	beforeSend: function()
                  					{
                  					},
                 	success: function(data, status, XMLHttpRequest) 
                  					{
                  						if (XMLHttpRequest.status==200)
                  			{
                  						$('#amaiboxcontent').load( base_url+'box_confirmation', function() 
                  						{
                  							$('#amaiboxcontent #bevestiging').css({'display':'none'});
                  							$('#amaiboxcontent #bevestiging').fadeIn(1000);
                  							
                  						  if ( ! $.browser.msie){
                                Cufon.replace('#amaiboxcontent h1');
                  							Cufon.replace('#amaiboxcontent h2');
                  							}
                                amCountdown = setInterval ( "countdown()", 1000);
                  							countdown();
                  						});
                  					}
                  					}
               	});
          }
			  	return false;
			});
		
		}
		
		//does #form#critera exists?
		if($("form#critera").size())
		{
			$("#selectie-mail").blur(function()
			{
				var getValue = $('label[id="selectie-mail_hidden"]').text();
				$(this).css({backgroundColor:'#edfafa'});
			 	if ($(this).val() == ""){
					$(this).val(getValue);
					$(this).css({color:'#aaa'});
				}
			});
			$("#selectie-mail").focus(function()
			{
				var getValue = $('label[id="selectie-mail_hidden"]').text();
				$(this).css({color:'#000', backgroundColor:'#f9f9f9'});
				if ($(this).val() == getValue){$(this).val("");}
				return false;
			});
			
			if(amaiboxdata_form_criteria.length > 0)
			{
				$('#selectie-mail').val(amaiboxdata_form_criteria[0]);

				var getValue = $('label[id="selectie-mail_hidden"]').text();
				
				if ($("#selectie-mail").val() != getValue){
					$("#selectie-mail").css({color:'#000'});
				}
			}
		
		$('form#critera').submit( function (e) {
      e.preventDefault();
      
      $('#selectie-mail').removeClass('error');
      $('#selectie-mail').next('span').removeClass('error');
      
      if ( ! echeck( $('#selectie-mail').val() ) )
      {
         $('#selectie-mail').addClass('error');
         $('#selectie-mail').next('span').addClass('error');
      }
      
      else
      {
      
      $.ajax( {
        url: base_url+'sendCriteria',
        type: 'POST',
        data: { email: $('#selectie-mail').val() }
      } );
      
      $('#amaiboxcontent').load( base_url+'box_confirmation', function() 
                  						{
                  							$('#amaiboxcontent #bevestiging').css({'display':'none'});
                  							$('#amaiboxcontent #bevestiging').fadeIn(1000);
                  							
                  							if ( ! $.browser.msie){
                  						  Cufon.replace('#amaiboxcontent h1');
                  							Cufon.replace('#amaiboxcontent h2');
                  							}
                                amCountdown = setInterval ( "countdown()", 1000);
                  							countdown();
                  						});
      
      }
      
      
    } );
		
    }
		
		if($("form#delen").size())
		{
			$("#delen_header").text(box_delen_header);
			
			
			$("#delen input[type=text]").blur(function()
			{
				var getID = $(this).attr("id");
				var getValue = $('#delen label[for=' + getID + ']').text() ;

				$(this).css({backgroundColor:'#edfafa'});
			 	if ($(this).val() == ""){
					$(this).val(getValue);
					$(this).css({color:'#aaa'});
			 	}
			});
			$('#delen input[type=text]').focus(function()
			{
				var getID = $(this).attr("id");
				var getValue = $('#delen label[for=' + getID + ']').text() ;

				$(this).css({color:'#000', backgroundColor:'#f9f9f9'});
				if ($(this).val() == getValue){$(this).val("");}
				return false;
			});
		
			if(amaiboxdata_form_delen.length > 0)
			{
				$('#delen input[name=email1]').val(amaiboxdata_form_delen[0]);
				$('#delen input[name=email2]').val(amaiboxdata_form_delen[1]);
				$('#delen input[name=name]').val(amaiboxdata_form_delen[2]);  
				$('#delen input[name=email]').val(amaiboxdata_form_delen[3]);
			
				
				$("#delen input[type=text]").each(function(intIndex){
					var getID = $(this).attr("id");
					var getValue = $('label[for=' + getID + ']').text();
					
					if ($(this).val() != getValue){
						$(this).css({color:'#000'});
					}
				});
			}
		
		
			$('#delen').submit(function(e) 
			{
				//get data form
// 				var email1  = $('#delen input[name=email1]').val();
// 				var email2 	= $('#delen input[name=email2]').val();
// 				var name  	= $('#delen input[name=name]').val();  
// 				var email  	= $('#delen input[name=email]').val();
				
				//search_array;
				
			  
      e.preventDefault();
      

      
        var ok=true;
        var input = $(this).find('input[type=text]');
        input.each( function( index, o ) {

          var id = $(o).attr('id');

          $(o).next('span').removeClass('error');
          if ( $(o).val()==$(o).prev('label').text() )
          {
            if ($(o).next('span').hasClass('req') )
            {
              $(o).next('span').addClass('error');
              ok=false;
            }
          }        
        } );
       
        $(this).find('#f1').removeClass('error');
        if ( ! echeck($(this).find('#f1').val()) )
        {
          $(this).find('#f1').addClass('error');
          $(this).find('#f1').next('span').addClass('error');
          ok=false;
        }

        $(this).find('#f2').removeClass('error');
        if ( $(this).find('#f2').val()!=$(this).find('#f2').prev('label').text() )
        {
          if ( ! echeck($(this).find('#f2').val()) )
          {
            $(this).find('#f2').addClass('error');
            $(this).find('#f2').next('span').addClass('error');
            ok=false;
          }
        }


        $(this).find('#f4').removeClass('error');
        if ( ! echeck($(this).find('#f4').val()) )
        {
          $(this).find('#f4').addClass('error');
          $(this).find('#f4').next('span').addClass('error');
          ok=false;
        }

      
      if (ok)
      {
      
      $(this).find('#f2').trigger('focus');
      
      $.ajax( {
        url: base_url+'sendShare',
        type: 'POST',
        data: $('#delen').serialize()
      } );
      
      $('#amaiboxcontent').load( base_url+'box_confirmation', function() 
                  						{
                  							$('#amaiboxcontent #bevestiging').css({'display':'none'});
                  							$('#amaiboxcontent #bevestiging').fadeIn(1000);
                  							
                  						  if ( ! $.browser.msie){
                                Cufon.replace('#amaiboxcontent h1');
                  							Cufon.replace('#amaiboxcontent h2');
                  							}
                                amCountdown = setInterval ( "countdown()", 1000);
                  							countdown();
                  						});
        }
			});
		}
	}
	function clearamaibox()
	{
		$('#amaiboxclose').html('');
		$('#amaiboxcontent').html('');
	}
	function countdown()
	{
		amCountdownTotal--;
		$('#countdown').text(amCountdownTotal);
		if(amCountdownTotal == 0){
			clearInterval(amCountdown);
			closeBox();
		}
	}
	
	
function INITcopypaste()
{
	//does #form#critera exists?
	if($("form#critera").size())
	{	
		//copypaste code
		ZeroClipboard.setMoviePath( base_url+'assets/swf/ZeroClipboard.swf' );
	
		copyClip = new ZeroClipboard.Client();
		copyClip.setText( $("#kopie-url").val() );
		copyClip.setHandCursor( true );
		copyClip.glue('kopie-url', 'kopie-url-container');
		copyClip.addEventListener( 'complete', function(client, text) 
		{
		    $("#kopie-url").css({'display':'none'}).fadeIn(800);
		} );
	
		copyClip2 = new ZeroClipboard.Client();
		copyClip2.setText( $("#rss").val() );
		copyClip2.setHandCursor( true );
		copyClip2.glue('rss', 'rss-container');
		copyClip2.addEventListener( 'complete', function(client, text) 
		{
		     $("#rss").css({'display':'none'}).fadeIn(800);
		} );
		// copyClip.getHTML( 200, 30 );
		// copyClip.show();
		// copyClip2.getHTML( 200, 30 );
		// copyClip2.show();
	}
}	
function INITshadowboxBtns()
{
	$('#amai_close').die().live('click', function(e){ e.preventDefault(); Shadowbox.close()});
	$('#amai_next').die().live('click', function(e){ e.preventDefault(); Shadowbox.next();});
	$('#amai_prev').die().live('click', function(e){ e.preventDefault(); Shadowbox.previous();});
}

function doLoader(show)
{
	if(show){$('#loader').slideDown();}
	else{$('#loader').slideUp();}
}
function INITblankLinks()
{
    $('a.blank').die().live('click', function()
	{
        window.open(this.href);
        return false;
    });
}
function hitTest(o, l)
{
	function getOffset(o){
		for(var r = {l: o.offsetLeft, t: o.offsetTop, r: o.offsetWidth, b: o.offsetHeight};
			o = o.offsetParent; r.l += o.offsetLeft, r.t += o.offsetTop);
		return r.r += r.l, r.b += r.t, r;
	}
	var a = arguments, j = a.length;
	j > 2 && (o = {offsetLeft: o, offsetTop: l, offsetWidth: j == 5 ? a[2] : 0,
	offsetHeight: j == 5 ? a[3] : 0, offsetParent: null}, l = a[j - 1]);
	for(var b, s, r = [], a = getOffset(o), j = isNaN(l.length), i = (j ? l = [l] : l).length; i;
		b = getOffset(l[--i]), (a.l == b.l || (a.l > b.l ? a.l <= b.r : b.l <= a.r))
	&& (a.t == b.t || (a.t > b.t ? a.t <= b.b : b.t <= a.b)) && (r[r.length] = l[i]));
		return j ? !!r.length : r;
};
function split(val) 
{
	return val.split(/,\s*/);
}
function extractLast(term) 
{
	return split(term).pop();
}
function uniqueArray(a)
{
   var r = new Array();
   o:for(var i = 0, n = a.length; i < n; i++){
      for(var x = 0, y = r.length; x < y; x++){
         if(r[x]==a[i]) continue o;
      }
      r[r.length] = a[i];
    }
    return r;
}		
function uppercaseFirst(tempString)
{
	var tmpStr 		= tempString; //.toLowerCase()
	var firstChar 	= tmpStr.slice(0,1);
	var first  		= firstChar.toUpperCase();
	
		if(firstChar != first){
			tmpStr = tmpStr.replace(first.toLowerCase(),first);
		}
		
	return tmpStr;
}
function resetForSearch()
{
	removeActiveMenu();
}

function ajaxClear()
{
	if (typeof(ajaxRequest) != 'undefined'){ajaxRequest.abort();}
}

function INITmotorMenu()
{
  $('#motor_menu a').click( function(e) 
  {
    e.preventDefault();
    
    if ( $(this).attr('rel')=='newestate' )
    {		  
      $.address.value('newestate');
    }
    if ( $(this).attr('rel')=='estate' )
    {
		  $.address.value('estate');      
    }
            
    if ( $(this).attr('rel')=='specialestate' )    
    {      
      $.address.value('specialestate');
    }
  });
  
  $('#wrap_main').append('<div id="motor_overlay"></div>');
}
var tempCallback;
function SETmotorMode_estate(callback)
{
  $('#wmr_menu a').removeClass('active');
  $('#motor_menu a').removeClass('active');
  $('#motor_menu a[rel=estate]').addClass('active');
  if ($('#motor_overlay').css('display')=='block') 
      { 
        $('#motor_overlay').css('display','none').css('opacity',0); 
      }
    if ( $('#motor_op2').is(':hidden'))
		{
      		//ENABLE OPTIONS IF DISABLED
			$('ul.topmenu').slideDown(300);
			$('#motor_op2').slideDown(300);
			$('#motor_op1 .simple').slideDown(300);
			$('#location_address').slideDown(300);
			var doHeight = $('#motor_op1').height() + 40;
			$('#motor_op1').stop().animate({'height':doHeight}, {queue:false, duration:300,  easing:'easeOutCirc', complete: function() {
        
        if(typeof(callback) == 'function'){
          
          if (motorAdvancedActive)
          {
            if ( $('#motor_op4').is(':hidden') )
            {
              tempCallback=callback;
              setTimeout('SETmotorMode_advanced(true, tempCallback )', 100);
            }
          }         
        }
      }  });
		}
		$('#newEstateBuy').slideUp(300);
		$('#search_estateID').slideDown(300);
}

function SETmotorMode_newestate(callback)
{
  $('#wmr_menu a').removeClass('active');
  $('#motor_menu a').removeClass('active');
  $('#motor_menu a[rel=newestate]').addClass('active');
  if ($('#motor_overlay').css('display')=='block') 
      { 
        $('#motor_overlay').css('display','none').css('opacity',0); 
      }
        if ($('ul.topmenu:visible').length > 0)
    		{
    			//DISABLE USELESS OPTIONS (huren/kopen & priceslider & uitgebreid zoeken)
    			$('ul.topmenu').slideUp(300);
    			$('#motor_op2').slideUp(300);
    			$('#motor_op1 .it-arr').slideUp(300);
    			$('#location_address').slideUp(300);
    			
    			$('#newEstateBuy').slideDown(300);
    
    			var doHeight = $('#motor_op1').height() - 40;
    			$('#motor_op1').stop().animate({'height':doHeight}, {queue:false, duration:300,  easing:'easeOutCirc', complete: callback });
    			
    			$('#search_estateID').slideUp(300);
    		}
}
function SETmotorMode_specialestate(callback)
{
  $('#wmr_menu a').removeClass('active');
  $('#motor_menu a').removeClass('active');
  $('#motor_menu a[rel=specialestate]').addClass('active');
//   if ($('#motor_overlay').css('display')=='none') { $('#motor_overlay').css('display','block').css('opacity',0); }
//       $('#motor_overlay').animate( { opacity: 0.7 }, { complete: callback } );

    if ( $('#motor_op2').is(':hidden'))
		{
      		//ENABLE OPTIONS IF DISABLED
			$('ul.topmenu').slideDown(300);
			$('#motor_op2').slideDown(300);
			$('#motor_op1 .simple').slideDown(300);
			$('#location_address').slideDown(300);
			
			
        var doHeight = $('#motor_op1').height() + 40;
  			$('#motor_op1').stop().animate({'height':doHeight}, {queue:false, duration:300,  easing:'easeOutCirc', complete: function() {
          
          if(typeof(callback) == 'function'){
            
            if (motorAdvancedActive)
            {
              if ( $('#motor_op4').is(':hidden') )
              {
                tempCallback=callback;
                setTimeout('SETmotorMode_advanced(true, tempCallback )', 100);
              }
            }
            else
            {
              callback.call();
            }      
          }
        }  });
    
    
      
    
		}
		else
		{
        if(typeof(callback) == 'function'){
          callback.call();             
        }
    }
    $('#newEstateBuy').slideUp(300);
    $('#search_estateID').slideDown(300);
}

function SETmotorMode_advanced(active ,callback)
{
  if ($('#motor_overlay').css('display')=='block') 
      { 
        $('#motor_overlay').css('display','none').css('opacity',0); 
      }
  if (active)
  {  
    if ( $('#motor_op4').is(':hidden') )
    {
      if ( $('#motor_op2').is(':hidden') )
      {
         
        SETmotorMode_estate( function() {
          $('#motor_op1').stop().animate({'height':520}, {queue:false, duration:300,  easing:'easeOutCirc'});
          $('#motor_op1 a.simple').hide();
          $('#motor_op1 a.adv').show();
          $('#motor_op4').slideDown(300, callback );          
          setAdvancedOptions();   
        } );
      }
      else
      {      
        $('#motor_op1').stop().animate({'height':520}, {queue:false, duration:300,  easing:'easeOutCirc'});
        $('#motor_op1 a.simple').hide();
        $('#motor_op1 a.adv').show();
        $('#motor_op4').slideDown(300, callback );
        setAdvancedOptions();   
      }
    }
     
  }
  if (!active)
  {     
    if ( $('#motor_op4').is(':visible') )
    {
      
//         $('#motor_op1').css('height', 200);
        $('#motor_op1').stop().animate({'height':200}, {queue:false, duration:300,  easing:'easeOutCirc'});

      
      $('#motor_op1 a.simple').show();
      $('#motor_op1 a.adv').hide();
  //     $('#motor_op3').fadeIn('slow');
      $('#motor_op4').slideUp(300, callback);    
    }
    else
    {
      $('#motor_op4').slideUp('slow', callback);    
    }
  }
}

function addressFader()
{
  var marknext=false;
  var marked=false;
  $('#wmr_menu h3').each( function() {
    if (marknext) { $(this).addClass('nextactive'); marknext=false; marked=true; return false; }
    if ($(this).hasClass('active')){ marknext=true; }
  });
  if ( ! marked ) { $('#wmr_menu h3').first().addClass('nextactive'); }
    
  $('#wmr_menu h3.active').fadeOut(1200).removeClass('active');
  $('#wmr_menu h3.nextactive').fadeIn(1200).addClass('active').removeClass('nextactive');
}

function addressSlider()
{
  var marknext=false;
  var marked=false;
  $('#wmr_menu h3').each( function() {
    if (marknext) { $(this).addClass('nextactive'); marknext=false; marked=true; return false; }
    if ($(this).hasClass('active')){ marknext=true; }
  });
  if ( ! marked ) { $('#wmr_menu h3').first().addClass('nextactive'); }
    
  $('#wmr_menu h3.active').animate( { top: 30 }, { duration: 1200, easing:'easeOutCirc', complete: function() { $(this).removeClass('active') } } );
  $('#wmr_menu h3.nextactive').css('top', -30).addClass('active').animate( { top: 0 }, { duration: 1200, easing:'easeOutCirc', complete: function() { $(this).removeClass('nextactive') } } );
}

function INITaddressFader()
{
  setInterval( 'addressFader()', 5000 );
}
function INITaddressSlider()
{
  setInterval( 'addressSlider()', 5000 );
}

function INITaddressHover()
{
  var keep_contact_active=false;
  if ($('#wmr_menu a.last').hasClass('active'))
  {
    keep_contact_active=true;
  }
  $('#address-hover').hover( 
      function() 
      {
        //width: 405 height: 192

        $(this).css('width', 330).css('height', 166);
        $('#wmr_menu a.last').css('backgroundColor', '#f3f3f3');
        $('#contact-info').css( { display: 'block', height: 100 } ).animate( { height: 141 }, { duration: 500, easing: 'easeOutCirc' } );
        $('#header-address').css('display', 'none');
        $(this).find('div').css('display', 'block');
      }, 
      function()
      {
        $(this).css('width', 260).css('height', 25);
        if ( ! keep_contact_active)
        {
          $('#wmr_menu a.last').css('backgroundColor', '#F7F7F7');
        }
        //$('#contact-info').animate( { height: 100 }, { duration: 200, complete: function() { $(this).css('display', 'none')}});
        $('#contact-info').slideUp(100);
        $('#header-address').css('display', 'block');
        $(this).find('div').css('display', 'none');
      });
}

function INITsortOptions()
{
  var current=motor_model.getOrderByFields();
  $('#sort-options a').each( function() {
    if ($(this).attr('rel')==current )
    {
      $(this).addClass('active');
    }
  });
  if ( ! $.browser.msie){
  Cufon.refresh('#sort-options');
  }
  
  $('a.sorteer').die().live('click', function(e) {
    e.preventDefault();
    INITsortOptions();
    var options = $('#sort-options');
    if (options.is(':visible'))
    {
      options.slideUp('fast', 'easeOutExpo');
    }
    else
    {
      options.slideDown('slow', 'easeOutExpo');
    }      
  });
  
  $('#wrap-results, #wrap-projecten').live( 'click', function(e) {
    var options = $('#sort-options');
    if (options.is(':visible'))
    {
      options.slideUp('fast', 'easeOutExpo');
    }
  } );
  
  $('#sort-options a').die().live('click', function(e){
    e.preventDefault();
    
    $('#sort-options').slideUp('fast', 'easeOutExpo');
    
    var key = 'OrderByFields';
    
    var rel=$(this).attr('rel');
    var value= new Array();
    value.push(rel);
    
    motor_model.setOrderByFields(value);
//     search_motor_set(key,value);
    
    var posturl=$('#motor_menu a.active').attr('href');
    if ($('a.sorteer').attr('href')!='#')
    {
      posturl=$('a.sorteer').attr('href');
    }
    
    $.address.parameter('param', motor_model.getJSON() );
  });
  
}

function INITsetmotormode()
{
  var found_active=false;
  $('#motor_menu li a.active').each( function() {
    if ($(this).attr('rel')=='newestate')
    {
      motor_model.setMode('newestate');
      SETmotorMode_newestate( function() {} );
      found_active=true;
    }
    if ($(this).attr('rel')=='specialestate')
    {
      motor_model.setMode('specialestate');
      SETmotorMode_specialestate( function() {} );
      found_active=true;
    }
    
  });
  if ((!found_active) && ( ! $('#motor_menu li a.first').hasClass('active') ))
    {
      $('#motor_menu li a.first').addClass('active');
    }
  
}
function INITResetButton()
{
  $('#reset-search').die().live( 'click', function(e) {
    e.preventDefault();
    if ( $(this).hasClass('newestate') )
    {
      $.address.value('reset_newestate');
    }
    else
    {
      $.address.value('reset');
    }  
    
  } );
}

/*
*
* Magazines
* 
*/

$.fn.magazineSlider=function()
{    
    var container = $(this);
    var navigation = container.find('a.nav');
    
    navigation.click( function(e){
      e.preventDefault();
      
      var nav = $(this);
      var nextId = nav.attr('rel');
      var activeSlide = nav.parents('div.magazine-item');
      var nextSlide = $('#'+nextId);      
      
     if (nav.hasClass('month-left'))
     {
        activeSlide.css( {'right': 'auto'} )
                   .animate( { 'left': (container.width()*-1) }, { duration: 500, easing: 'easeInExpo'});
          
     nextSlide.css( { 'right': (container.width()*-1), 'left': 'auto' , 'display': 'block' } )
              .animate( { 'right': 0 }, { duration: 500, easing: 'easeInExpo'});      
     }
     
     if (nav.hasClass('month-right'))
     {
        activeSlide.css( {'left': 'auto'} )
                   .animate( { 'right': (container.width()*-1) }, { duration: 500, easing: 'easeInExpo'});
          
     nextSlide.css( { 'left': (container.width()*-1), 'right': 'auto' , 'display': 'block' } )
              .animate( { 'left': 0 }, { duration: 500, easing: 'easeInExpo'});      
     }
    });
}


/*
*
* Login button
*
*/
$( function() {

  $('#loginButton').die().live('click', function(e){
      
      e.preventDefault();
      
      ajaxClear();
        ajaxRequest = $.ajax(
                      	{
                      		type: 'POST',
                      		url: base_url+'getHistory',
                      		data: $('#loginForm').serialize(),
                      		beforeSend: function() {
                            $('#login-loading').fadeIn();
                            $.scrollTo($('body'), 600, {easing:'easeOutCirc'});
                          } ,
                      		success: function(foo, status, XMLHttpRequest)
                        		{
                        	       	if (XMLHttpRequest.status==200)
                          			{
                                   if (foo!='')
                                   {

                                      if ( $(foo).hasClass('error') )
                                      {
                                        $('#loginForm').before(foo);
                                      }
                                      else
                                      {
                                        $('#amaiboxcontent .amaibox-txt').html(foo);
                                      }                                                                       
                                   }                                   
                                   $('#login-loading').fadeOut();
                                   
                                   $('a.historyMoreResult').click( function(e){
                                    e.preventDefault();
                                    historyNext($(this).attr('rel'));
                                   } );
                                }
                        		}
                      	});
    
  } );

} );

function historyNext(page)
{
                        ajaxClear();
                       ajaxRequest =  $.ajax({
                          type: 'POST',
                          url: base_url+'getHistory/'+page,
                          beforeSend: function() {
                            $('#login-loading').fadeIn();
                            $.scrollTo($('body'), 600, {easing:'easeOutCirc'});
                          } ,
                      		success: function(foo, status, XMLHttpRequest)
                        		{
                        	       	if (XMLHttpRequest.status==200)
                          			{
                                   if (foo!='')
                                   {
                                      $('#amaiboxcontent .amaibox-txt').html(foo);                                 
                                   }                                   
                                   $('#login-loading').fadeOut();
                                   
                                   $('a.historyMoreResult').click( function(e){
                                    e.preventDefault();
                                    historyNext($(this).attr('rel'));
                                   } );
                                }
                        		}
                         });
}

/*
*
* Address handling
* 
*/

$( function() {
  $.address.baseURL(base_url);
    
  $.address.externalChange( function(e) {
    if ((e.path=='/advanced') && ( ! e.parameters.param ))
    {
      SETmotorMode_advanced(false);
    }
  });
  
  $.address.change( function(e){

    
    var ajax=false;
    
    if ((e.value=='/info') || (e.value=='/second_home') || (e.value=='/contact') || (e.value=='/schatting') || (e.value=='/woonkrant') )
    {
      $('#wmr_menu li a').each( function() {
        if ( $(this).attr('rel') == e.value.substring(1, e.value.length ) )
        {
          $(this).addClass('active');
        }
        else
        {
          $(this).removeClass('active');
        }
      } );
     
        ajax=true;
        
        var type='POST';
        var url=base_url+e.value.substring(1, e.value.length );
        var data='';
        var beforeSend=function()
            {
              doLoader(true);

              $.scrollTo($('body'), 600, {easing:'easeOutCirc'});
            };
        var success=function(foo, status, XMLHttpRequest)
                        		{
                        	       	if (XMLHttpRequest.status==200)
                          			{
                                   $('#w_content').html(foo);
                                   INITcufon();
                                   INITpages();
                                   INITtooltip();
                                   Shadowbox.setup();
                                   saturateImages();
                                   $('.magazine-items').magazineSlider();
                                   doLoader(false);
                                   INITContactAndSchattingForm();
                                }
                        		};
   
      
    }
    
    if (e.value=='/')
    {

      if ( ! initialPageLoad)
      {
        $('#motor_menu a').removeClass('active');
        $('#motor_menu a[rel=estate]').addClass('active');
        SETmotorMode_advanced( false, function() {SETmotorMode_estate( function() {} );} );
        resetModelAndMotor(true);  
        
        ajax=true;
        
        var type='POST';
        var url=base_url+e.value.substring(1, e.value.length );
        var data='';
        var beforeSend=function()
            {
              doLoader(true);

              $.scrollTo($('body'), 600, {easing:'easeOutCirc'});
            };
        var success=function(foo, status, XMLHttpRequest)
                        		{
                        	       	if (XMLHttpRequest.status==200)
                          			{
                                   $('#w_content').html(foo);
                                   INITcufon();
                                   INITpages();
                                   INITtooltip();
                                   Shadowbox.setup();
                                   saturateImages();
                                   doLoader(false);
                                }
                        		};      
      }
      initialPageLoad=false;
    }
    
    if (e.value=='/simple')
    {
      motorAdvancedActive = false;
      SETmotorMode_advanced( false, function() {} );
      initialPageLoad=false;
    }
    
    if (e.value=='/close')
    {
            unsetResultListHover();
      
      var total = $('.result-hover').size();
			$('.result-hover').each(function(intIndex){
				$(this).stop().animate({'left':'201px'}, {queue:false, duration:((total - intIndex) * 75), easing:'easeOutCirc'});	
			});
		
			$('#result-detail-holder').slideUp(500, function(){
				//remove content from #result-detail-holder
				INITresultPoleposition();
			});
			$('#result-closebtn').slideUp(500);
		
			$('a.result-l').removeClass('active');
			$("#hovertriangle").hide();
			$("#hovertriangle2").hide();
			
			$('#print_link').attr('href',list_pdf_url);
			
			$('#result-overview-holder').css('top', 0);
			$('#result-label').css('display', 'none');
    
      $('#headerDelen').css('right', 'auto');
      $('#headerPrint').css('right', 'auto');
      $('#headerDelen').css('left', 190);
      $('#headerPrint').css('left', 190);
      $('#wrap-content-head').removeClass('background');
      $('#w_content #wrap-content-head .estateAddress').remove();
      
      $('#headerDelen').show();
    }
    
    if ((e.path=='/advanced') && ( e.parameters.param ))
    {
      motorAdvancedActive = true;
//       $('#motor_menu a').removeClass('active');
//       $('#motor_menu a[rel=estate]').addClass('active');
      SETmotorMode_advanced(true , function() {} );   
      motor_model.setByJSON( e.parameters.param );
      SETrobot();  
      initialPageLoad=false; 
    }
    
    if ((e.value=='/newestate')|| ( e.value=='/nieuwbouw' ))
    {
      motor_model.setMode('newestate');
      SETmotorMode_advanced( false, function() {SETmotorMode_newestate( function() {} );	} );
      
      ajax=true;
      
      var type='POST';
      var url=base_url+'nieuwbouw';
      var data={ search: motor_model.getJSON() };
      var beforeSend=function(){
	   			doLoader(true);   
//            $.scrollTo($('body'), 600, {easing:'easeOutCirc'});               			
	   		};
	   	var success=function(foo, status, XMLHttpRequest){
	   			if (XMLHttpRequest.status==200)
	   			{           
           CALL_search_doCallBack(foo, false); 
           setSliderRange();
          }                     
	   	  	};
	   	  	initialPageLoad=false;
    }
    if (e.value=='/estate')
    {
      motor_model.setMode('estate');
      SETmotorMode_estate( function() {} );
      
      ajax=true;
      
      var type='POST';
      var url=base_url+'estate';
      var data={ search: motor_model.getJSON() };
      var beforeSend=function(){
	   			doLoader(true);   
//            $.scrollTo($('body'), 600, {easing:'easeOutCirc'});               			
	   		};
	   	var success=function(foo, status, XMLHttpRequest){
	   			if (XMLHttpRequest.status==200)
	   			{           
           CALL_search_doCallBack(foo, false); 
           setSliderRange();
          }                     
	   	  	};
	   	  	initialPageLoad=false;
    }
    
    if (e.value=='/specialestate')
    {
      motor_model.setMode('specialestate');
      var href=base_url+'special';     
      
      SETmotorMode_specialestate(function() { 
                                ajaxClear();
                          	    ajaxRequest = $.ajax(
                          	   	{
                          	   		type: "POST",
                          	   		url: href,
                          	   		data: { search: motor_model.getJSON()},
                          	   		beforeSend: function(){
                          	   			doLoader(true);                  			
                          	   		},
                          	   		success: function(foo, status, XMLHttpRequest){
                          	   			if (XMLHttpRequest.status==200)
                          	   			{
                                      CALL_search_doCallBack(foo, false); 
//                                       SETrobot();
//                                       setSliderRange();                                      
                                    }                     
                          	   	  	}
                          	   	});
       });
       initialPageLoad=false;
    }
    
    if ($.address.parameter('param'))
    {
        
        if (e.path=='/')
        {
          SETmotorMode_advanced( false, function() {SETmotorMode_estate( function() {} );} );          
        }
        
        if ($.address.parameter('param') != motor_model.getJSON() )
        {
          motor_model.setByJSON( $.address.parameter('param') );
          SETrobot(true);
        }
        
        setAdvancedOptions();
        
        ajax=true;
        
        var href = base_url+( motor_model.mode=='estate' ? 'estate' :  motor_model.mode=='newestate' ? 'nieuwbouw' : 'special' );
        
        var type = "POST";
        var url = href;
//         var data = {'search': $.address.parameter('param') };
        var data = {'search': motor_model.getJSON() };
        var beforeSend = function()
                      		{
                      			doLoader(true);
//                       			$.scrollTo($('body'), 600, {easing:'easeOutCirc'});
                      		};
        var success = function(foo, status, XMLHttpRequest)
                      		{
                      			if (XMLHttpRequest.status==200)
                          			{
                            CALL_search_doCallBack(foo, true);	
                            }
                      		};
                      		initialPageLoad=false;
    }
    
    
    if (e.value=='/reset')
    {     
      resetModelAndMotor();
      initialPageLoad=false;
    }
    
    if (e.value=='/reset_newestate')
    {     
      resetModelAndMotor(false,true);
      initialPageLoad=false;
    }
    
    if ((e.pathNames[0]=='estate') && (e.pathNames[1]=='detail'))
    {
//         $('#w_content #wrap-content-head .estateAddress').remove();
        if ( $('#result-detail-holder').length ==0 )
        {
          //detailholder doesn't exist
          var param = new Object();
          param.EstateID = e.pathNames[2];       

          ajaxClear();
          ajaxRequest = $.ajax(
                    			{
                    				type: "POST",
                    				url: base_url+'estate',
                    				data: {'search': $.toJSON(param) },
                    				beforeSend: function()
                        		{
                        			doLoader(true);

                        			$.scrollTo($('body'), 600, {easing:'easeOutCirc'});
                        		},
                    				success: function(foo, status, XMLHttpRequest)
                        		{
                        			if (XMLHttpRequest.status==200)
                            			{
                              CALL_search_doCallBack(foo, true);
                              
                              setTimeout( function(){
                                callDetail(e);
                              }, 500);
                              
                              }
                        		}                    
    });
        }
        else
        {
          callDetail(e);
        }

    }
    
    if ((e.pathNames[0]=='nieuwbouw') && (e.pathNames[1]=='detail'))
    {
      current_estate=$('#wrap-project-ul').attr('class');
      
        if (( typeof( current_estate )=='undefined' ) || ( current_estate.substr(7)!=e.pathNames[2] )) 
        {
          SETmotorMode_newestate( function(){} );
          
          ajaxClear();
          ajaxRequest = $.ajax(
                    			{
                    				type: "POST",
                    				url: base_url+ e.pathNames[0] + '/' + e.pathNames[1] + '/' + e.pathNames[2] ,
                    				data: { },
                    				beforeSend: function()
                    				{
    
                              $.scrollTo($('body'), 600, {easing:'easeOutCirc'});
                              doLoader(true);
                    				},
                    				success: function(foo, status, XMLHttpRequest)
                    				{
                    					if (XMLHttpRequest.status==200)
                        			{
                                	doLoader(false);
                      					if (foo=='error')
                      					{
                      	        		  //do some error handling, or nothing
                      			        }
                      			        else
                      			        {
                      			         	$('#w_content').css('overflow', 'hidden');
                                       $('#w_content').html(foo);
      
                          			         	
                          			         	INITprojectMenu();
                           						INITresult_projectFields();
                           						INITnewprojects();
          
                          						if ( ! $.browser.msie){
                                        Cufon.replace('#wrap-content-head', {hover: 'true'});
                                        Cufon.replace('#wrap-project-options ul li a');
                                        Cufon.replace('#wrap-project-c h3');
                                        Cufon.replace('#wrap-project-ul li a');
                           						}
                                       saturateImages();
                                      Shadowbox.setup();
                                      INITresult_projectImgNav();
                          					
                                      if ( e.pathNames[3]=='kavels' )
                                      {
                                          $('#wrap-project-ul a.kavels').trigger('click');
                                      }
                                    }
                      	    		}
                    	    		}
                    
                    	    	});
        initialPageLoad=false;
    }
    }
    
    if (e.pathNames[0]=='newestate_next')
    {
      ajaxClear();
      ajaxRequest = $.ajax(
                			{
                				type: "POST",
                				url: base_url+'newestate_next',
                				data: { search: motor_model.getJSON() ,
                                this_id: e.pathNames[1] },
                				beforeSend: function()
                				{

                          $.scrollTo($('body'), 600, {easing:'easeOutCirc'});
                          doLoader(true);
                				},
                				success: function(foo, status, XMLHttpRequest)
                				{
                					if (XMLHttpRequest.status==200)
                  			{
                          	doLoader(false);
                					if (foo=='error')
                					{
                	        		  //do some error handling, or nothing
                			        }
                			        else
                			        {
                			         	$('#w_content').css('overflow', 'hidden');
                                 $('#w_content').html(foo);

                			         	
                			         	INITprojectMenu();
                 						INITresult_projectFields();
                 						INITnewprojects();

                						if ( ! $.browser.msie){
                            Cufon.replace('#wrap-content-head', {hover: 'true'});
                            Cufon.replace('#wrap-project-options ul li a');
                            Cufon.replace('#wrap-project-c h3');
                            Cufon.replace('#wrap-project-ul li a');
                 						}
                             saturateImages();
                            Shadowbox.setup();
                            INITresult_projectImgNav();
                            SETmotorMode_newestate( function() {} );
                					}		
                	    		}
                	    		}
                
                	    	});
     initialPageLoad=false; 
    }
    
    if ((e.pathNames[0]=='nieuwbouw') && (e.pathNames[1]=='estate'))
    {
     
            ajaxClear();
      ajaxRequest = $.ajax(
                			{
                				type: "POST",
                				url: base_url+e.path,
                				data: { },
                				beforeSend: function()
                				{
                					doLoader(true);
                				},
                				success: function(foo, status, XMLHttpRequest)
                				{
                					if (XMLHttpRequest.status==200)
                  			{
                          	doLoader(false);
                					if (foo=='error')
                					{
                	        		  //do some error handling, or nothing
                			        }
                			        else
                			        {
                			         	CALL_search_doCallBack(foo, false)
                 						
                    						if ( ! $.browser.msie){
                                Cufon.replace('#wrap-content-head', {hover: 'true'});
                                Cufon.replace('#wrap-project-options ul li a');
                                Cufon.replace('#wrap-project-c h3');
                                Cufon.replace('#wrap-project-ul li a');
                     						}
                     						
                                 INITresult_projectImgNav();               						
                                 saturateImages();
                     					   INITprojectMenu();
                     						 INITresult_projectFields();
                     						 INITnewprojects();                               
                    					}		
                	    		}
                	    		}
                
                	    	});
    initialPageLoad=false;
    }
    
    if (((e.pathNames[0]=='estate') || (e.pathNames[0]=='nieuwbouw')) && ((typeof(e.pathNames[1])!='undefined') && (e.pathNames[1]!='detail') ) )
    {
      ajaxClear();
      ajaxRequest = $.ajax(
                			{
                				type: "POST",
                				url: base_url+e.path,
                				data: {'search': motor_model.getJSON() },
                				beforeSend: function()
                				{
//                 					$.scrollTo($('body'), 600, {easing:'easeOutCirc'});
                          doLoader(true);
                				},
                				success: function(foo, status, XMLHttpRequest)
                				{
                        if (XMLHttpRequest.status==200)
                  			{
                					
                          doLoader(false);
                					$('#w_content').css('overflow', 'hidden');
                          $('#w_content').html(foo);
                					removeActiveMenu();
                					INITresults();
                					INITtriangle();				
                					if ( ! $.browser.msie){
                          Cufon.replace('.project-r h2');
                					}
                          //Cufon.replace('#wrap-content-head', {hover: 'true'});
                				}
                        },
                				complete: function()
                				{
                          if (click_first_result)
                          {
                            $('div.result').each( function(index,e) {
                              $(this).find('a').click();  
                              click_first_result=false;                            
                              return false;
                            });
                          }                          
                                $('#headerDelen').css('right', 'auto');
                                $('#headerPrint').css('right', 'auto');
                                $('#headerDelen').css('left', 190);
                                $('#headerPrint').css('left', 190);
                                $('#wrap-content-head').removeClass('background');
                        }
                			});
    initialPageLoad=false;
    }
    
    if ((e.pathNames[0]=='second_home') && ( typeof(e.pathNames[1])!='undefined' ))
    {
            ajaxClear();
      ajaxRequest = $.ajax(
                			{
                				type: "POST",
                				url: base_url+e.path,
                				data: { },
                				beforeSend: function()
                				{
                					doLoader(true);
                				},
                				success: function(foo, status, XMLHttpRequest)
                				{
                					if (XMLHttpRequest.status==200)
                  			{
                          	doLoader(false);
                					if (foo=='error')
                					{
                	        		  //do some error handling, or nothing
                			        }
                			        else
                			        {
                			         	CALL_search_doCallBack(foo, false)
                 						
                						if ( ! $.browser.msie){
                            Cufon.replace('#wrap-content-head', {hover: 'true'});
                            Cufon.replace('#wrap-project-options ul li a');
                            Cufon.replace('#wrap-project-c h3');
                            Cufon.replace('#wrap-project-ul li a');
                 						}
                 						
                             INITresult_projectImgNav();               						
                             saturateImages();
                 					   INITprojectMenu();
                 						 INITresult_projectFields();
                 						 INITnewprojects();
                 						 Shadowbox.setup();

                					}		
                	    		}
                	    		}
                
                	    	});
    initialPageLoad=false;
    }
    
    if (ajax)
    {
    	  ajaxClear();
        ajaxRequest = $.ajax(
                      	{
                      		type: type,
                      		url: url,
                      		data: data,
                      		beforeSend: beforeSend,
                      		success: success
                      	});
    }
  } );
  
} );


        function callDetail(e)
        {
          var estateId=e.pathNames[2];
          ajaxClear();
          ajaxRequest = $.ajax(
                    			{
                    				type: "POST",
                    				url: base_url+"estate/detail",
                    				data: {estateId: estateId,
                                  getDrawing: getDrawing },
                    				beforeSend: function()
                    				{
                    					doLoader(true);                    					
                              
//                     					$('#w_content #wrap-content-head .estateAddress').remove();
                    				},
                    				success: function(foo, status, XMLHttpRequest)
                    				{
                    					
                            if (XMLHttpRequest.status==200)
                      			{
                              doLoader(false);
                              $.scrollTo($('body'), 600, {easing:'easeOutCirc'});
                    					if (foo=='error')
                    					{
                    	        		  //do some error handling, or nothing
                    			        }
                    			        else
                    			        {
                    			         	$('#result-detail-holder').html(foo);
                    			         	INITresultDetailMenu();                 			      
                                    $('#result-poleposition').hide();
                                   	
                    						    INITresult_projectFields();
                    						    Shadowbox.setup();
                                
                    			      		if($('#result-detail-holder').is(':visible')){}
                    			      		else
                    			      		{
                    			      			
                                      $('#result-detail-holder').slideDown(700);
                    			      			$('.result-hover').each(function(intIndex){
                    			      				$(this).stop().animate({'left':-200}, {queue:false, duration:(intIndex * 200), easing:'easeOutCirc'});	
                    			      			});
                    			      		}
                    			      		
                    			      		 $('#result-detail-holder').css('visibility', 'visible');    
                    			
                        						//re-init tabs
                        						$("#result-detail-ul li a").removeClass('active');
                        						$("#result-detail-ul li a:first").addClass('active');
                        						$(".res-det-c").each(function(intIndex){
                        							if(intIndex == 0){$(this).show();}
                        							else{$(this).hide();}
                        						});
                                    
                        						if ( ! $.browser.msie){
                                    Cufon.replace('#result-detail ul li a');
                        						Cufon.replace('#result-detail h3');
                        						Cufon.replace('#result-detail-options ul li a');
                        						Cufon.replace('p.sms');
                        					  }
                        					
                        						saturateImages();
                                    INITresult_projectImgNav();
                                    
                                                                        
                                    //call 2nd time and 3th and ....
                                    setTimeout( '$(\'#result-poleposition\').hide();', 100 );
                                    setTimeout( '$(\'#result-poleposition\').hide();', 200 );
                                    setTimeout( '$(\'#result-poleposition\').hide();', 300 );
                                    setTimeout( '$(\'#result-poleposition\').hide();', 400 );
                                    setTimeout( '$(\'#result-poleposition\').hide();', 500 );
                                    
                                    if( typeof(e.pathNames[3])!='undefined' )
                                    {
                                      $('#result-estate-next').hide();
                                      $('#wrap-content-head a.sorteer').hide();
                                      var header=$('<h1>Project '+decodeURI(e.pathNames[3])+'</h1> <a id="option" class="kavel" href="'+base_url+'nieuwbouw/detail/'+e.pathNames[4]+'">Terug naar project</a>');
                                      header.appendTo('#wrap-content-head');
                                      Cufon.replace('#wrap-content-head h1, #wrap-content-head a#option');
                                      
//                                       $('#wrap-content-head a#option').die().live('click', function(e) {
//                                         e.preventDefault();
//                                         
//                                         var url = $(this).attr('href').substr( base_url.length, ($(this).attr('href').length-base_url.length) )+'/kavels';                                        
//                                         $.address.value(url);
//                                     });
                                      
                                    }else
                                    {
                                      $('#result-closebtn').slideDown(700);
                                    }
                                    
                    					     }
                            }	
                    	    	}
                    
    });
    initialPageLoad=false;
    
    if (getDrawing)
    {
      getDrawing=false;
    }
    
    }
  

function resetModelAndMotor( dontShowResults, newestate )
{

  motor_model.reset();
  if (newestate)
  {
    motor_model.setMode('newestate');
  } 
      $.ajax( {
        url: base_url+'get_motor',
        success: function (html)
        {
          $('#wml_motor').html(html);
          
          $('#motor_overlay').hide();
          
          if ( ! $.browser.msie){
        	Cufon.replace('.menu li a');
        	Cufon.replace('#motor_op1 ul.topmenu li a');
        	Cufon.replace('#motor_opt1_boxes label');
        	Cufon.replace('#motor_op1 .it-arr');
        	Cufon.replace('#motor_op4 .it-arr');
        	Cufon.replace('#motor_op4 p');
        	Cufon.replace('#motor_op1 p');
        	Cufon.replace('#motor_op4 .adv_op_desc');	
        	Cufon.replace('#motor_op4 label');	
        	Cufon.replace('.spr');
        	Cufon.replace('#motor_op3 h2');
        	Cufon.replace('#motor_op3 p');
        	Cufon.replace('#motor_op3 .val-km');
        	Cufon.replace('#motor_op3 a.map');
        	Cufon.replace('#reset-search');
          }
          
          INITmenu();
        	INITcheckboxes();
        	INITselectboxes();
        	INITsliders();
        	INITlocations();
        	INITmotorMenu();
        	INITadvSearch();
        	INITsetmotormode();	
        	
        	if (newestate)
        	{
            SETmotorMode_newestate( function() {} );
          }
        	
        	if ( ! dontShowResults)
        	{
          	if (newestate)
          	{
              url = base_url+'nieuwbouw';
            } 
            else
            {
              url = base_url+'estate';
            }            
            
            ajaxClear();
            ajaxRequest = $.ajax(
                          	{
                          		type: "POST",
                          		url: url,
                          		data: {'search': motor_model.getJSON() },
                          		beforeSend: function()
                          		{
                          	        doLoader(true);
                          	        
                          	        $.scrollTo($('body'), 600, {easing:'easeOutCirc'});
                          		},
                          		success: function(foo, status, XMLHttpRequest)
                          		{
                          	       	if (XMLHttpRequest.status==200)
                            			{
                                     CALL_search_doCallBack(foo, true);
                                  }
                          		}
                          	});
          }
        }
      } );      
}

function setAdvancedOptions()
{
  var adv = $('#motor_op4');
//   var advHeight = adv.height();
//   var op1Height = $('#motor_op1').height();
  if ( adv.is(':visible') )
  {
  var height = 55;
//     var advHeight = adv.height();
    if ( typeof(motor_model.CategoryIDList) =='undefined' )
    {
      adv.find('.garden').slideDown();
      adv.find('.terrace').slideDown();
      adv.find('.parking').slideDown();
      adv.find('.elevator').slideDown();
      adv.find('.pool').slideDown();
      adv.find('.stables').slideDown();
      adv.find('.sidebuilding').slideDown();
      adv.find('.office').slideDown();
      adv.find('.rooms').slideDown();
      adv.find('.bathrooms').slideDown();
      $('#motor-message').slideUp(); 
      //8*25 2*30
      height+= (8*25)+(2*30);
    }
    else
    {
    
      //garden
      if ((motor_model.isCategoryIDset(1)) || (motor_model.isCategoryIDset(2)))
      {
        adv.find('.garden').slideDown();
        height+=25;  
      }
      else
      {
        adv.find('.garden').slideUp();  
        motor_model.unsetGarden();
        motorUnsetAdvOpt('garden');
      }
      
      //terrace
      if ((motor_model.isCategoryIDset(1)) || (motor_model.isCategoryIDset(2)))
      {
        adv.find('.terrace').slideDown();  
        height+=25;
      }
      else
      {
        adv.find('.terrace').slideUp();  
        motor_model.unsetTerrace();
        motorUnsetAdvOpt('terrace');
      }
      
      //parking
      if ((motor_model.isCategoryIDset(1)) || (motor_model.isCategoryIDset(2)) || (motor_model.isCategoryIDset(4)) || (motor_model.isCategoryIDset(5)))
      {
        adv.find('.parking').slideDown();  
        height+=25;
      }
      else
      {
        adv.find('.parking').slideUp();
        motor_model.unsetParking();
        motorUnsetAdvOpt('parking');  
      }
      
      //elevator
      if ((motor_model.isCategoryIDset(1)) || (motor_model.isCategoryIDset(2)) || (motor_model.isCategoryIDset(4)))
      {
        adv.find('.elevator').slideDown();  
        height+=25;
      }
      else
      {
        adv.find('.elevator').slideUp();  
        motor_model.unsetElevator();
        motorUnsetAdvOpt('elevator');  
      }
      
      //pool
      if (motor_model.isCategoryIDset(1))
      {
        adv.find('.pool').slideDown();  
        height+=25;
      }
      else
      {
        adv.find('.pool').slideUp();  
        motor_model.unsetPool();
        motorUnsetAdvOpt('pool');  
      }
      
      //stables
      if (motor_model.isCategoryIDset(1))
      {
        adv.find('.stables').slideDown();  
        height+=25;
      }
      else
      {
        adv.find('.stables').slideUp();
        motor_model.unsetStables();
        motorUnsetAdvOpt('stables');  
      }
      
      //sidebuilding
      if (motor_model.isCategoryIDset(1))
      {
        adv.find('.sidebuilding').slideDown();  
        height+=25;
      }
      else
      {
        adv.find('.sidebuilding').slideUp();  
        motor_model.unsetSidebuilding();
        motorUnsetAdvOpt('sidebuilding');  
      }
      
      //office
      if ((motor_model.isCategoryIDset(6)) || (motor_model.isCategoryIDset(1)))
      {
        adv.find('.office').slideDown();  
        height+=25;
      }
      else
      {
        adv.find('.office').slideUp();  
        motor_model.unsetOffice();
        motorUnsetAdvOpt('office');  
      }
      
      //rooms
      if ((motor_model.isCategoryIDset(1)) || (motor_model.isCategoryIDset(2)))
      {
        adv.find('.rooms').slideDown();  
        height+=30;
      }
      else
      {
        adv.find('.rooms').slideUp();  
        motor_model.setMinRooms(0);
        SETrobot();
      }
      
      //bathrooms
      if ((motor_model.isCategoryIDset(1)) || (motor_model.isCategoryIDset(2)))
      {
        adv.find('.bathrooms').slideDown();  
        height+=30;
      }
      else
      {
        adv.find('.bathrooms').slideUp(); 
        motor_model.setBathRooms(0);
        SETrobot(); 
      }
      
      if (!((motor_model.isCategoryIDset(1)) || (motor_model.isCategoryIDset(2)) || (motor_model.isCategoryIDset(4)) || (motor_model.isCategoryIDset(5)) || (motor_model.isCategoryIDset(6))))
      {
        if ((motor_model.isCategoryIDset(7)) || (motor_model.isCategoryIDset(3)))//garage, grond
        {
          $('#motor-message').slideDown();
          height+=75;          
        }
        else
        {
          $('#motor-message').slideUp(); 
        }
      }
      else
      {
        $('#motor-message').slideUp(); 
      }
      
    }    
//     setTimeout( 'fixAdvHeight('+height+')', 200 );
    $('#motor_op1').animate( { height: (200 + height ) }, function() { $(this).css('overflow', 'visible') } );
  }    
  else
  {
    if ( $('#motor_op2').is(':visible') )
    {
      if (!((motor_model.isCategoryIDset(1)) || (motor_model.isCategoryIDset(2)) || (motor_model.isCategoryIDset(4)) || (motor_model.isCategoryIDset(5)) || (motor_model.isCategoryIDset(6))))
        {
          if ((motor_model.isCategoryIDset(7)) || (motor_model.isCategoryIDset(3)))//garage, grond
          {
            $('#motor_op1 a.simple').fadeOut('fast');           
          }
          else
          {
            $('#motor_op1 a.simple').fadeIn('fast'); 
          }
        }
        else
        {
          $('#motor_op1 a.simple').fadeIn('fast');
        }
    }
  }
}

function CurrencyFormatted(amount)
	{
		var i = parseFloat(amount);
		if(isNaN(i)) { i = 0.00; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		i = parseInt((i + .005) * 100);
		i = i / 100;
		s = new String(i);
		if(s.indexOf('.') < 0) { s += '.00'; }
		if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
		s = minus + s;
		return s;
	}
	
	function CommaFormatted(amount){
		var delimiter = "."; // replace comma if desired
		var a = 0;//'' + amount.split('.',2);
		var d = 0;//a[1];
		var i = amount;
		if(isNaN(i)) { return ''; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		var n = new String(i);
		var a = [];
		while(n.length > 3)
		{
			var nn = n.substr(n.length-3);
			a.unshift(nn);
			n = n.substr(0,n.length-3);
		}
		if(n.length > 0) { a.unshift(n); }
		n = a.join(delimiter);
		if(d.length < 1) { amount = n; }
		else { amount = n; }
		amount = minus + amount;
		return amount;
	}





function INITPoleScroll()
{  
  $(window).scroll( function(e) {

      var top=f_scrollTop();

      var pole = $('#result-poleposition');
      if (pole.length)
      {
        var newpos = (top-326)+100;
        if (newpos<100) { newpos=100; }
        
        var polepos=pole.position();
        if (polepos.top!=newpos)
        {
          if ( pole.width()==200 )
          {
            pole.stop().delay(100).animate( {top:newpos}, {duration: 700, easing: 'easeOutExpo'} );
          }
        }
      }

    
  } );
}

function echeck(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){  return false	}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ return false	}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ return false }
		if (str.indexOf(at,(lat+1))!=-1){ return false }
		if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ return false }
		if (str.indexOf(dot,(lat+2))==-1){ return false }	
		if (str.indexOf(" ")!=-1){ return false }
 		return true					
	}


$.fn.addressField = function(){
  
  var input=this;
  var time=0;
  var timeout;
  var delay=1000;
  var val;
  
  input.keyup( function(e){
    val=$(this).val();
    
    var newtime = new Date().getTime();
    if (!((( newtime - time ) < delay) && ( time!=0 )))    
    {
      time=newtime;
      clearTimeout( timeout );
      timeout = setTimeout( function(){
        submitAddress();
      }, delay );
    }
  } );
  
  var submitAddress = function()
  {
    motor_model.setAddress( val );
    $.address.parameter('param', motor_model.getJSON() );
  }

  return this;

}

$.fn.refField = function(){
  
  var input=this;
  var time=0;
  var timeout;
  var delay=1000;
  var val;
  
  input.keyup( function(e){
    val=$(this).val();
    
    var newtime = new Date().getTime();
    if (!((( newtime - time ) < delay) && ( time!=0 )))    
    {
      time=newtime;
      clearTimeout( timeout );
      timeout = setTimeout( function(){
        submitRef();
      }, delay );
    }
  } );
  
  var submitRef = function()
  {
    motor_model.setRef( val );
    $.address.parameter('param', motor_model.getJSON() );
  }

  return this;

}


function INITIEfixes()
{
  if ($.browser.msie)
  {
//     $('#wml_logo').click( function() {
//       $('#wml_logo a').trigger('click');
//     } );
  }
}

	 /*  
	 *    what the f.
AMAI AMAI AMAI AMAI AMAI AMAI AMAI AMAI
   *	http://amai.be
  */

