$(document).ready(function () {

$('#weather').weatherfeed(['FRMP0540']);
$('input[type=submit]').addClass('submit');
$('input[type=radio]').addClass('radio');

//////////////////////////////////////////////////////////////////////////////////
// Add focus class to textareas & inputs on focus
//////////////////////////////////////////////////////////////////////////////////
$('input').live('focusin', function() {
	$(this).addClass("focus");			  
});
	
$('input').live('focusout',function() {
	$(this).removeClass("focus");			  
});

$('textarea').live('focusin',function() {
	$(this).addClass("focus");			  					  
});
	
$('textarea').live('focusout',function() {
	$(this).removeClass("focus");			  
});

//////////////////////////////////////////////////////////////////////////////////
// Hide email addresses from bots
//////////////////////////////////////////////////////////////////////////////////

$('.email').defuscate();

//////////////////////////////////////////////////////////////////////////////////
//Init cycle slideshow
//////////////////////////////////////////////////////////////////////////////////
$('#image_slideshow').cycle();
//////////////////////////////////////////////////////////////////////////////////
//Toggle slide up / slide down for FAQs
//////////////////////////////////////////////////////////////////////////////////
$('.faqtoggler').click(function() {
								
	$(this).parents().next('.answer').slideToggle();
	$(this).toggleClass('open');
	return false;

});

$('.opener').click(function() {
			
	$('.answer').slideToggle();
	 if ($(this).text() == 'Open All') {
		 
		 $(this).text('Close All');
	 } else if ($(this).text() == 'Close All'){
		  $(this).text('Open All');
	 }
	 
	
	return false;
});

//////////////////////////////////////////////////////////////////////////////////
//Check that minimum price is lower than max
//////////////////////////////////////////////////////////////////////////////////
$('#search_properties form').submit(function () {
											  
	$('#primary_content').css('opacity','.5');
	var price_min = $('#price_min').val();
	var price_max = $('#price_max').val();
	if (price_max != '') {
		if (price_min > price_max) {
			$('#submit_property_search').css('opacity',1);
			dialog_box('Alert', 'Oops, the minimum price should be less than the maximum');
			$('#primary_content').css('opacity','1');
			return false;
		} 
	}
});

$('.page_navigator,.navigator a').click(function () {
		$('#primary_content').css('opacity','.5');									 
});
//////////////////////////////////////////////////////////////////////////////////
//Init jquery ui tabs
//////////////////////////////////////////////////////////////////////////////////
$('#tabs').tabs();

//////////////////////////////////////////////////////////////////////////////////
//Init jquery ui accordion
//////////////////////////////////////////////////////////////////////////////////
$('#accordion').accordion({
			autoHeight: false,
			navigation: true,
			collapsible: true

});
////////////////////////////////////////////////////////////////////////////////
//Display pop up menu
////////////////////////////////////////////////////////////////////////////////
var config = {    
     over: menu_hover_over,
     timeout: 1000, 
     out: menu_hover_out    
};


$('#primary_navigation ul li.sub_menu').hoverIntent(config);

function menu_hover_over() {

	$(this).find(".drop_down").stop().fadeTo('fast', 1).show();
	$(this).removeClass('active').addClass('active');

}

function menu_hover_out() {
	$(this).find(".drop_down").stop().fadeTo('fast', 0, function() {
      $(this).hide();  
 	 });

	$(this).removeClass('active');
}
//////////////////////////////////////////////////////////////////////////////////
// Animate lang choice buttons
//////////////////////////////////////////////////////////////////////////////////
$('#lang_choice a.inactive_lang').css('opacity', .5);
$('#lang_choice a.inactive_lang').hover(function() {
	$(this).stop().animate({opacity:1}, 100);									 
						 }, function () {
	$(this).stop().animate({opacity:.5}, 300);
});

//////////////////////////////////////////////////////////////////////////////////
// Pre validate forms
//////////////////////////////////////////////////////////////////////////////////
$('form').submit(function() {
	
	$(this).find('input').removeClass('warning');
	$('p.error').remove();
	var errors = false;
	var form = $(this);
	var btn_submit = $(this).find('button');
	
	$(btn_submit).css('opacity','.5');

	
	$(form).find('.required').each(function (i) {
								
		if ($(this).attr('value') == '') { errors = true; $(this).addClass("warning"); }
	});
	
	if (errors == true) {
		//alert('error');
		//alert(this);
		$(form).prepend('<p class="error">Un, ou plusieur champs du formulaire sont manquants. Merci de verifier les donn&eacute;es saisie.</p>');
		
		scrollGo('p.error');
		$(btn_submit).css('opacity','1');

		return false;
	}
});

$('input').focusout(function() {
				if(this.value !== '') { 
					if ($(this).is('.required')) {
$(this).removeClass('warning');
					}
					}	
});

//////////////////////////////////////////////////////////////////////////////////
// Property images
//////////////////////////////////////////////////////////////////////////////////
$('#sub_images a').css('opacity',.6);
$('#sub_images a').hover(function() {
	if (!$(this).hasClass('active')) { $(this).stop().animate({opacity:1}, 100); }									 
						 }, function () {
	if (!$(this).hasClass('active')) { $(this).stop().animate({opacity:.6}, 300); }
});
$('#sub_images a.active').css('opacity',1);
$('#sub_images a').live('click', function() {
										  
							  
		var id = $(this).attr('id');
	
	var image_container_id = 'main_image';//Get id of main image container 
	var filename = $(this).attr('href') + '&width=350';//Get url of image to load	
	
	$('#' +image_container_id+' img.preview').fadeOut('fast');//Fade out image already in place
	//$('#' +image_container_id).addClass('loading');// Add loading class to image container
	$(this).siblings('a').removeClass('active');//Remove active class from sub images
	$(this).addClass('active');	//Add active class to current sub image
	$(this).siblings('a').css('opacity',.6);
	$(this).css('opacity',1);
	

	var img = new Image();
	$(img).hide()
	// On image load, remove old images and loading class and fade in image
	.load(function () {
		
		$('#' + image_container_id + ' img.preview').remove();
		$('#' + image_container_id).removeClass('loading');
		$('#' + image_container_id+ ' a').append(img);
		
		$(img).fadeIn('slow');
		//alert(filename);	
		filename = filename.split('&');
		
		$('#' + image_container_id + ' a, #magnify a').attr('id', 'image_' +id);
		$('#' + image_container_id + ' a, #magnify a').attr('href', filename[0]);				
	})
	// if there was an error loading the image, react accordingly
	.error(function () {
					
		// notify the user that the image could not be loaded
		$('#' + image_container_id + ' img.preview').remove();
		$('#' + image_container_id + ' .error').remove();
		$('#' + image_container_id).removeClass('loading');
		$('#' + image_container_id).append('<p class="error">Image non charg&eacute;e, merci de reessayer</p>');
	})
	.attr('src', filename).addClass('preview').css('display','inline');
return false;
});

//////////////////////////////////////////////////////////////////////////////////
// Init Fancybox
//////////////////////////////////////////////////////////////////////////////////
function formatTitle(title, currentArray, currentIndex, currentOpts) {
var last = currentArray.length - 1;
return '<div id="#fancybox-title-inside"><span><a href="javascript:;" onclick="$.fancybox.pos(0);">first</a> | <a href="javascript:;" onclick="$.fancybox.prev();">previous</a> | <a href="javascript:;" onclick="$.fancybox.next();">next</a> | <a href="javascript:;" onclick="$.fancybox.pos('+last+');">last</a> | <a href="javascript:;" onclick="$.fancybox.close();">[X] Close</a></span></div>';
} 

$('.fancybox').click(function() {
var id = $(this).attr('id');
id = id.split('_');
id = id[1];
if (!parseInt(id)) {
	id =0;
} 

var _items = [];
$.getJSON(site_url + '/fr/properties/get_images_json/', {id: $(this).attr('rel'), cur_image : $(this).attr('id') }, function(response){

    $.each(response, function(key, val) {
        _items.push({'href' : val.href, 'title' : val.title});
		
    });
	
	//$.fancybox.pos(id, _items);

	$.fancybox(_items, {
        'padding'           : 10,
        'titlePosition'     : 'inside', 
        'type'              : 'image',
		'index'				: id,
		'titleFormat'       : formatTitle 
    
    });
});
	
		return false;
});

$('.mortgage_calculator').fancybox({
							 'width' : 600,
							 'height' : 630,
							 'type' : 'iframe'
							 });

$("#show_advanced_search a").click(function() {
										 
	$('.advanced_search').toggle()
	$(this).toggleClass('closed');	
	return false;

});

$('.email_enquiry').fancybox({
							 'width' : 600,
							 'height' : '70%',
							 'type' : 'iframe'
							 });

$('.close_fancybox').click(function() {
	parent.$.fancybox.close();		
	return false;
});
//dialog_box('It works', '...or does it');
//////////////////////////////////////////////////////////////////////////////////
});


//////////////////////////////////////////////////////////////////////////////////
// Call function when user leaves page
//////////////////////////////////////////////////////////////////////////////////
$(window).unload(function() {
  /*$.post(site_url + '/add_stats_ajax.php', function(data) {
  
});*/

});

//////////////////////////////////////////////////////////////////////////////////
//used to apply alternating row styles
//////////////////////////////////////////////////////////////////////////////////
function zebraRows(selector, className)
{
  $(selector).removeClass(className).addClass(className);
}
    

function dialog_box(title, msg)
{
  var $dialog = $('<div></div>')
		.html(msg)
		.dialog({
			autoOpen: true,
			title: title,
			height: 140,
			modal: true,
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}

		});


		

		$dialog.dialog('open');
}

//////////////////////////////////////////////////////////////////////////////////
// Scroll to element on page
//////////////////////////////////////////////////////////////////////////////////
function scrollGo(target) {
   var x = $(target).offset().top - 10; // 100 provides buffer in viewport
   $('html,body').animate({scrollTop: x}, 500);
}
