var timer3;
var hoveredOverSub = false;

function auto_fill(id, v){
	
    if( ($(id).val()) && ($(id).val()!=v) ) return;
	
    $(id).css({
        color: '#777777'
    }).attr({
        value: v
    }).focus(function(){
        if($(this).val()==v){
            $(this).val('').css({
                color: '#000000'
            });
        }
    }).blur(function(){
        if($(this).val()==''){
            $(this).css({
                color: '#777777'
            }).val(v);
        }
    });
	
    return;
	
}

function auto_fill_livesearch(id, v){
	
    if( ($(id).val()) && ($(id).val()!=v) ) return;
	
    $(id).attr({
        value: v
    }).focus(function(){
        if($(this).val()==v){
            $(this).val('').addClass('focus');
        }
    }).blur(function(){
        if($(this).val()==''){
            $(this).removeClass('focus').val(v);
        }
    });

}


/* Nav popups */
var tab_hovers = [
	'<span class="tab_hover_home">Welcome to Nicholas Humphreys, the East Midlands Estate Agent, covering Leicestershire, Derbyshire and Staffordshire.</span>',
	'<span class="tab_hover_prop_sales">Search for property for sale and find out more about the services we offer in this field.</span>',
	'<span class="tab_hover_prop_lets">Search for property to let and find out more about our landlord and tenant services.</span>',
	'<span class="tab_hover_prop_studentlets">Search for student accommodation and find out more about our landlord and tenant service</span>',
	'<span class="tab_hover_news">All the latest news from Nicholas Humphreys.</span>',
	'<span class="tab_hover_services">A breakdown of all the services we offer within the different disciplines we provide for.</span>',
	'<span class="tab_hover_contact">Visit this section to get in touch with one of offices, as well as find out more about the people behind Nicholas Humphreys Estate Agents.</span>',
	'<span class="tab_hover_my_humphreys">Sign up to save your searches, favourite properties and more...</span>',
	'<span class="tab_hover_iphone">The all new Nicholas Humphreys iPhone App - click here to find out more and download the App.</span>',
]

function tab_text_show(span){
    $('#breadcrumb span').hide();
    $('#breadcrumb span.' + span).show();
}

function tab_text_hide(){
    $('#breadcrumb span').hide();
    $('#breadcrumb span.tab_hover_default').show();

}

/**
 * Implemented from Boothroyd
 */
function do_ajax(form_id){

	//alert("form: " + form_id);
	//console.log($('form#'+form_id).serialize());
	//alert('s' + $('form#' + form_id + ' input[name=search_type]').val());

        if(form_id != "property-for-sale" && form_id != "property-to-let" && form_id != "student-lets")
            return

        var send = {
			min_bedrooms: $('form#' + form_id + ' select[name=min_bedrooms]').val(),
        	max_bedrooms: $('form#' + form_id + ' select[name=max_bedrooms]').val(),
			min_price_sales: $('form#' + form_id + ' select[name=min_price_sales]').val(),
			max_price_sales: $('form#' + form_id + ' select[name=max_price_sales]').val(),
			min_price_lettings: $('form#' + form_id + ' select[name=min_price_lettings]').val(),
			max_price_lettings: $('form#' + form_id + ' select[name=max_price_lettings]').val(),
            min_price_studentlets: $('form#' + form_id + ' select[name=min_price_studentlets]').val(),
			max_price_studentlets: $('form#' + form_id + ' select[name=max_price_studentlets]').val(),
			keywords: $('form#' + form_id + ' input[name=keywords]').val(),
            property_type_id: $('form#' + form_id + ' select[name=property_type_id]').val(),
            university: $('form#' + form_id + ' select[name=university]').val(),
			location: $('form#' + form_id + ' input[name=location]').val()
		}

	$.post('/' + form_id + '/ajax', send,

		function(data){
			$('span.' + form_id + '_results').text(data);
			$('span.' + form_id + '_results').hide();
			$('span.' + form_id + '_results').fadeIn('normal');
			//console.log(data);
			//alert(data);
		}

	);
}

function do_locationAjax(input_id, form_id){
	var location = $('input#' + input_id).val()
	hoveredOverSub = false;
	var type="sales";
	if (form_id == "property-to-let")
	{
		type="let";
	}
	$.post('/ajaxsearch/suggest/'+location+'/'+type+'/'+input_id, function(data){
			$('div#' + input_id+ '-suggest').html(data);
			$('div#' + input_id+ '-suggest').show();
			$('div#' + input_id+ '-suggest span').mouseover(function() {
					hoveredOverSub = true;
					$('div#' + input_id+ '-suggest span.selected').removeClass('selected');
					$(this).addClass('selected');
				}
			);
			$('div#' + input_id+ '-suggest span').mouseout(function() {
					hoveredOverSub = false;
					$('div#' + input_id+ '-suggest span.selected').removeClass('selected');
					$(this).addClass('selected');
				}
			);
		});
}


function do_keypress(keyPress, input_id)
{
	if (keyPress == 38)
	{
	 id = 0;
	 numObjects = $('div#' + input_id+ '-suggest span').size();
	 $('div#' + input_id+ '-suggest span').each(function(index)
	 {
		 if ($(this).hasClass('selected'))
		 {
			 
			 $(this).removeClass('selected');
			 if (id == 0)
			 {
				// console.log("here");
				 $('div#' + input_id+ '-suggest span').last().addClass('selected');
			 }
			 else
			 {
				$('div#' + input_id+ '-suggest span').eq(id-1).addClass('selected');
			 }
			 return false;
		 }
		 id++;
	 });
	}
	else if (keyPress == 40)
	{
	 id = 0;
	 numObjects = $('div#' + input_id+ '-suggest span').size();
	 $('div#' + input_id+ '-suggest span').each(function(index)
	 {
		 
		 if ($(this).hasClass('selected'))
		 {
			 
			 $(this).removeClass('selected');
			 if ((id+1) == numObjects)
			 {
				 //alert(numObjects);
				 $('div#' + input_id+ '-suggest span').eq(0).addClass('selected');
			 }
			 else
			 {
				$('div#' + input_id+ '-suggest span').eq(id+1).addClass('selected');
			 }
			 return false;
		 }
		 id++;
	 });
	}	
}

function initiate_ajax(){

	// Bind an event handler on the appropriate form elements
	$('form#property-for-sale select, form#property-to-let select, form#student-lets select').change(function(){
		do_ajax($(this).parents('form').attr('id'));
	});
	
	
	$('form#property-for-sale input[name="location"], form#property-to-let input[name="location"], form#student-lets input[name="location"], form#student-lets input[name="keywords"]').keyup(function(event) {
		
		//ignore arrow presses
		if (event.which != 37 && event.which != 38 && event.which != 39 && event.which != 40 && event.which != 13)
		{
			if ($(this).val() != $(this).lastValue && ($(this).val().length>1 || $(this).val().length==0)) {
				if($(this).timer) clearTimeout($(this).timer);
				if($(this).timer2) clearTimeout($(this).timer2);
				$(this).timer = setTimeout('do_ajax("' + $(this).parents('form').attr('id') + '")', 350);
				$(this).timer2 = setTimeout('do_locationAjax("' + $(this).attr('id') + '", "' +$(this).parents('form').attr('id') + '")', 350);
				$(this).lastValue = $(this).val();
			}
			
		}
	});
	
	$('form#property-for-sale input[name="location"], form#property-to-let input[name="location"], form#student-lets input[name="location"], form#student-lets input[name="keywords"]').blur(function() {
		if (!hoveredOverSub)
		{
			$('div#'+$(this).attr('id')+'-suggest').hide();		
		}
	});
	
	$('form#property-for-sale input[name="location"], form#property-to-let input[name="location"], form#student-lets input[name="location"]').keydown(
		function(event) 
		{
			if (event.which != 13)
			{
				firedID = $(this).attr('id');
				if(timer3) clearTimeout(timer3);
				timer3 = setTimeout(function() { do_keypress(event.which,firedID); }, 50);
			}
			else
			{
				if(timer3) clearTimeout(timer3);
				id = $(this).attr('id');
				if ($('div#'+id+'-suggest').css('display') != 'none')
				{
					$('input#'+id).val($('div#'+id+'-suggest span.selected').html());
					$('div#'+$(this).attr('id')+'-suggest').css('display', 'none');
					do_ajax($(this).parents('form').attr('id'));
					return false;
				}
			}
		}
	);
	
	
}



$(document).ready(function(){
						   
    //embed tab_hovers
    $.each(tab_hovers, function(index, value){
        $('#breadcrumb').append(value);
    })

    //hide all except default
    tab_text_hide();

    $('#header_tabs li a').mouseover(function(){
        tab_text_show($(this).attr('id'));
    });


    $('#header_tabs li a').mouseout(function(){
        tab_text_hide();
    });

    // Make rel="external" links open in a new tab
    $('a[rel=external]').each(function(){
        this.target = '_blank';
    });
	
    // Livesearch stuff
    auto_fill_livesearch($('#search'), 'Keyword e.g. street name or feature');

    $('#search').autocomplete('/ajaxsearch/search/', {
	 
        minChars: 3,
        mustMatch: false,
        selectFirst: false,
        autoFill: false,
        dataType: 'json',
        matchSubset: false,
        scroll: false,
        width: 302,
	  
        parse: function(jdata) {
            var parsed_data = [];
			
            if (typeof jdata.length === 'undefined') {
                
				// handle no results case specially
                parsed_data[0] = {
                    data: {
                        id:-1,
                        url:'#'
                    }
                };
        }
        else{
			
            for (var i=0; i<jdata.length; i++){
                obj = jdata[i];
                parsed_data[i] = {
                    data: obj,
                    id: obj.id
                };
            }
			
        }
        return parsed_data;
    },
	 
    formatItem: function(property, i, n){
       	//alert(property +','+ i +','+ n);

        if(property.id==-1){
            return '<a href="#"><span>Sorry, no results<\/span></a>';
        }

        var html = '<a href="' + property.url + '" title="'+property.address+'">';
        html += property.address1+'<br /><span class="txt-red">'+property.town+'</span><br/>';
        if(property.bedrooms>1) html += +property.bedrooms +' bedrooms<br />';
        html += '<span class="price">' + property.price_str + '<\/span>';

        if(property.directory){
            html += '<img src="\/images\/properties\/' + property.directory + '\/thumb.jpg" \/><br \/>';
        }
        else{
            html += '<img src="\/images\/awaiting\/thumb.jpg" \/><br \/>';
        }

        html += '<\/a>';

        return html;
	  
    }
	
    }).result(function(event, item){
    location.href = item.url;

    
});

    initiate_ajax();

    //instead of blindly wasting 3 http requests, we'll check to make sure the spans exist
    if($("span.property-for-sale_results").length > 0)
        do_ajax('property-for-sale');
    if($("span.property-to-let_results").length > 0)
        do_ajax('property-to-let');
    if($("span.student-lets_results").length > 0)
        do_ajax('student-lets')
});
