$(function()
{	
	// alert( $('.holder').height() );
	
	$('#id_TimeStamp').val(new Date().valueOf());
	
	$('div.site_switch a').addClass('site_switch');
	$('a.site_switch').click(function()
	{
		var link = $(this).attr('href') + '?session=' + $(this).attr('rel');
		//console.info(link);
		//return false;
		//location.href = 'http://google.bg';
		location.href = link;
		return false;
		//$(this).attr('href', link);
	});
	
	$('#id_back_payment').click(function()
	{
		location.href=$(this).attr('rel');
		return false;
	});
	
	$('#header .feedback a').click(function()
	{ 
		var width = 400;
		var height = 600;
		var top = (screen.availHeight - height)/2
		var left = (screen.availWidth - width)/2
		 
		window.open(this.href, '_blank', 'width='+width+',height='+height+',top='+top+',left='+left+',scrollbars=1,directories=0,location=0,menubar=0,resizable=0,status=0,toolbar=0');
		return false;
	});
	
	$('.active_search').click(function(){

		$('.holder .search').addClass('active');
		$('.holder .search input:eq(0)').focus();
		return false;
	});
	
	$("#id_home_postcode_coverage, #id_home_postcode_coverage_down").focus(function()
	{ 
		if ( $(this).val() == __labels.__globals.SITE_LABELS.homes.search_text )
		{		
			$(this).val(''); 
		}
	});
	
	$('#send_to_friend').click(function(){
		$('body').addClass('hide_select');
		$('#window').before('<div class="overlay"></div>');
		$("#window").show();
		$('#window input.cancel, .overlay').click(function(){ $('#window').hide(); $('.overlay').remove(); $('body').removeClass('hide_select'); });
		return false;
	});

	$('#banklogo').click(function(){
		$('body').addClass('hide_select');
		$('#window2').before('<div class="overlay"></div>');
		$("#window2").show();
		$('#window2 input.cancel, .overlay').click(function(){ $('#window2').hide(); $('.overlay').remove(); $('body').removeClass('hide_select'); });
		return false;
	});
	
	$('.icon.delete, .button.delete').click(function()
	{
		return confirm(__labels.__globals.ERRORS.listing_delete) ? true : false;
	});
	
	$('.search #id_truck_type, .search #id_van_type').change(function()
	{
		var val = $('.search #id_brand').children(':eq(0)').html();
		if(val == 'Make'){ $('.search #id_brand').children(':eq(0)').remove(); }
	});
	
	$('.search .cnt #id_truck_type, .cnt #id_van_type').change(function()
	{
		var val = $('.search .cnt #id_brand').children(':eq(0)').html();
		if(val == 'Make'){ $('.search .cnt #id_brand').children(':eq(0)').remove(); }
	});
	
	$('select.bike_type').change(function()
	{
		var val = $(':selected', this).val();
		var $select = $(this).parents('.input:eq(0), .col:eq(0)').next().find('select.brand').children(':gt(0)').remove().end();
		
		var opt1 = 'Any'; //$select.children(':eq(0)').text();
		$('.inner select.brand').children(':eq(0)').text('Loading...');
		
		$.ajax(
		{
			type	: 'GET',
			url		: '?types=1&get_bike_type='+val,
			success	: function(txt)
			{
				$('.inner #id_bike_brand_id').children(':gt(0)').remove().end();
				$('.inner #id_bike_brand').children(':gt(0)').remove().end();
				$('.inner #id_bike_brand_id').append(txt).children(':eq(0)').text(opt1);
				$('.inner #id_bike_brand').append(txt).children(':eq(0)').text(opt1);
				$('.inner #id_bike_model_id').children(':gt(0)').remove();
				$('.inner #id_bike_model').children(':gt(0)').remove();
				if($('.inner #id_bike_brand_id').is('[rel=no-any]')){ $('#id_bike_brand_id').children(':eq(0)').remove(); }
				if($('.inner #id_bike_brand').is('[rel=no-any]')){ $('#id_bike_brand').children(':eq(0)').remove(); }
			}
		});
	});
	
	$('select.brand').change(function()
	{
		var val = $(':selected', this).val();
		var $select = $(this).parents('.input:eq(0), .col:eq(0)').next().find('select.model').children(':gt(0)').remove().end();
		
		var opt1 = 'Any'; //$select.children(':eq(0)').text();
		$select.children(':eq(0)').text('Loading...');
		
		var add_to_url = '';
		var bike_type_val = $('#id_bike_type').val();
		if (bike_type_val)
		{
			add_to_url = '&get_bike_type='+bike_type_val;
		}
		
		$.ajax(
		{
			type	: 'GET',
			url		: '?brands=1&get_models='+val+add_to_url,
			success	: function(txt)
			{
				$select.append(txt).children(':eq(0)').text(opt1);
				if($select.is('[rel=no-any]')){ $select.children(':eq(0)').remove(); }
			}
		});
		
		var $select_towns = $(this).parents('.input:eq(0), .col:eq(0)').next().find('select.town').children(':gt(0)').remove().end();
		if($select_towns.length)
		{
			$select_towns.children(':eq(0)').text('Loading...');
			var opt1_towns = 'Any'; //$select_towns.children(':eq(0)').text();
		
			$.ajax(
			{
				type	: 'GET',
				url		: '?towns=1&get_towns='+val,
				success	: function(txt)
				{
					$select_towns.append(txt).children(':eq(0)').text(opt1_towns);
					if($select_towns.is('[rel=no-any]')){ $select_towns.children(':eq(0)').remove(); }
				}
			});
		}
	});
	
	
	if($('select.town').length)
	{
		$('select.model.district').change(function()
		{
			var val = $(':selected', this).val();
			
			$select_towns = $('select.town');
			
			$select_towns.children(':gt(0)').remove().end().children(':eq(0)').text('Loading...');
			var opt1_towns = 'Any'; //$select_towns.children(':eq(0)').text();
		
			$.ajax(
			{
				type	: 'GET',
				url		: '?towns=1&district='+val,
				success	: function(txt)
				{
					$select_towns.append(txt).children(':eq(0)').text(opt1_towns);
					if($select_towns.is('[rel=no-any]')){ $select_towns.children(':eq(0)').remove(); }
				}
			});
		});
	}	
	
	$price_structure = $('#price_structure').hide();
	$('#price_structure-a').hover(function(){ $price_structure.toggle() }, function(){ $price_structure.toggle() });
	
	$('#id_age_from_year').change(function()
	{
		$select = $('#id_age_to_year');
		val = this.value || 1950;
		
		$select.children().filter(function(){ return this.value < val && this.value > 0; }).remove()
		
		$children = $select.children();
		select_last_val = $children[$children.length-1].value;
		
		if(val < select_last_val)
		{
			html = '';
			for(i = select_last_val-1; i >= val; i--) { html += '<option value="'+i+'">'+i+'</option>'; }
			$select.append(html);
		};
	});
	
	$('#id_age_to_year').change(function()
	{
		$select = $('#id_age_from_year');
		val = this.value || (new Date()).getFullYear();
		
		$select.children().filter(function(){ return this.value > val; }).remove()
		
		$children = $select.children();
		select_first_val = $children[1].value;
		
		if(val > select_first_val)
		{
			html = '';
			for(i = val; i >= parseInt(select_first_val)+1; i--) { html += '<option value="'+i+'">'+i+'</option>'; }
			$($children[0]).after(html);
		};
	});
	
	$('#listing-filter .apply.button').click(function()
	{
		fields = $('input, select', '#listing-filter, .listing_filter').serialize();
		
		fields_names = [];
		t_fields = fields.split('&');
		for(f in t_fields){ fields_names[f] = t_fields[f].split('=')[0]; }
		fields_names = fields_names.join('|');
		
		eval( 'reg = /(?:[A-Za-z0-9_-]+=|page=[0-9]+|(?:(?:^|&)'+fields_names+')=[A-Za-z0-9_%-]+)(?:&|$)/g' )
		url = location.search.substr(1).replace(reg, '').replace(/&*$/, '');
		
		fields = fields.replace(/[A-Za-z0-9_-]+=\+*(&|$)/g, '').replace(/&*$/, '');
		
		url = url + (url && fields ? '&' : '') + fields;
		
		if(this.href.indexOf('?') > 0){ this.href = this.href.substr(0, this.href.indexOf('?')); }
		this.href = this.href.replace('#', '');
		link = this.href.length ? this.href + '?' : '';
		
		if(url){ location.href = link + url; }
		
		return false;
	});
	
	$('textarea#id_requirements').bind('keyup focus blur mouseover change', function()
	{
		max_lenght = 220;
		
		val = this.value;
		if(val.length >= max_lenght){ this.value = val.substr(0, max_lenght); }
	});
	
	$("#login_toggle input").click(function(){ 
		$("h1.contacts, #registration_holder, #login_holder").toggle();
		if( $(this).attr("value") != 'I do not have a buyers4 account'){
			$(this).attr("value",'I do not have a buyers4 account');
		}else {
			$(this).attr("value",'I already have an account');
		}
	});
	
	if($('.datepicker').length > 0){ $(".datepicker").datepicker({ speed: "" }); }

	$("#services tr").each(function ()	
	{
		if ( $(this).find("td").size() < 3 ) {
			var td_count = $(this).find("td").size();
			var tds = 3 - (td_count*1);
			for( var i=0; i<tds; i++)
			{
				if ( i == (tds-1) ){ 	var last_class = ' last'
				}else { 				var last_class = ''	}
				$(this).append('<td class="empty'+last_class+'"></td>');
			}
		}
	});
	
	$autocompleter = $('#id_home_postcode_coverage_id.autocomplete, #id_home_postcode_coverage.autocomplete, #id_home_postcode_town_id.autocomplete, #id_post_town.autocomplete');
	if($autocompleter.length)
	{
		var search_by = $('#id_home_postcode_coverage_id.autocomplete').attr('rel');
		search_by = search_by || 'postcode';
		$('#id_home_postcode_coverage_id.autocomplete').suggest('?towns_autocomplete=1&search_by=' + search_by, {special: 1, check_valid: 'coverage'});

		search_by = $('#id_home_postcode_coverage.autocomplete').attr('rel');
		search_by = search_by || 'postcode';
		$('#id_home_postcode_coverage.autocomplete').suggest('?towns_autocomplete=1&search_by=' + search_by, {check_space: 1});
	
		search_by = $('#id_home_postcode_coverage_down.autocomplete').attr('rel');
		search_by = search_by || 'postcode';
		$('#id_home_postcode_coverage_down.autocomplete').suggest('?towns_autocomplete=1&search_by=' + search_by, {check_space: 1});
	
		search_by = $('#id_home_postcode_town_id.autocomplete').attr('rel');
		search_by = search_by || 'postcode';
		$('#id_home_postcode_town_id.autocomplete').suggest('?towns_autocomplete=1&search_by=' + search_by, {check_valid: 'town', show_hide: '#id_select_all'});
		
		$('#id_post_town.autocomplete').suggest('?user_towns_autocomplete=1');
		
		$('#id_select_all').parents('div.input:eq(0)').hide();
		if ($('#id_select_all:checked')[0]){ $('#id_home_postcode_coverage_id.autocomplete').parents('div.input:eq(0)').css({ visibility: 'hidden', height: '0' }); }
		else { $('#id_home_postcode_coverage_id.autocomplete').parents('div.input:eq(0)').css({ visibility: 'visible', height: 'auto' }); }
		$('#id_select_all').click(function()
		{
			if (this.checked){ $('#id_home_postcode_coverage_id.autocomplete').parents('div.input:eq(0)').css({ visibility: 'hidden', height: '0' }); }
			else{ $('#id_home_postcode_coverage_id.autocomplete').parents('div.input:eq(0)').css({ visibility: 'visible', height: 'auto' });  }
		});
	}
	
	$('a.suggested_towns').click(function()
	{
		//alert($(this).html());
		$('#id_home_postcode_coverage_id').val($(this).html());
		$('div.suggestion').hide();
		return false;
	});
	
	if ($('#id_home_postcode_town_id.autocomplete.invalid')[0]){ $('#id_select_all').parents('div.input:eq(0)').hide(); }
	else { $('#id_select_all').parents('div.input:eq(0)').show(); }
	
	
	$("#id_toggle").change(function()
	{
		var checkboxes = $("#messages_list li:gt(0) :checkbox, #outbox td :checkbox, #requirements-list td :checkbox")
		
		if ($(this).is(':checked')) 
		{
			$("#msgs_select_all").attr('rel', 'active').text("Deselect all");
			$(this).attr("checked","checked");
			checkboxes.attr("checked","checked");
		}
		else
		{
			$("#msgs_select_all").removeAttr('rel').text("Select all");
			$(this).removeAttr("checked");
			checkboxes.removeAttr("checked");
		}
	});
	
	$("#messages_list li:gt(0) :checkbox, #outbox td :checkbox, #requirements-list td :checkbox").change(function()
	{
		if ( !$(this).is(':checked') )
		{
			$("#id_toggle").removeAttr("checked");
			$("#msgs_select_all").removeAttr('rel').text("Select all");
		}
	});
	
	var delete_messages_href;
	$("#delete-messages").unbind('click').click(function()
	{
		if(!delete_messages_href){ delete_messages_href = this.href; }
		
		ids = $('#messages_list :checked[name=record], #outbox :checked[name=record], #requirements-list :checked[name=record]').serialize().replace(/record=/g, '').replace(/&/g, ',');
		if(!ids){ return false; }
				
		if(confirm(__labels.__globals.ERRORS.listing_delete))
		{
			this.href = delete_messages_href + ids
		}
		else
		{
			return false;
		}
	});
	
	$('form').each(function(){ new Validator($(this)); });
	/*
		$("#msgs_select_all").click(function()
		{
			var checkboxes = $("#messages_list li:gt(0) :checkbox, #outbox td :checkbox, #requirements-list li:gt(0) :checkbox");
			if ($(this).attr('rel') != 'active')
			{
				$(this).attr('rel', 'active').text("Deselect all");
				$("#id_toggle").attr("checked","checked");
				checkboxes.attr("checked","checked");
			}
			else
			{
				$(this).removeAttr('rel').text("Select all");
				$("#id_toggle").removeAttr("checked");
				checkboxes.removeAttr("checked");
			}
			return false;
		});
	*/
	
	
});
