// Wait until the page has fully loaded before attempting to show the map.
// Hooray for IE!
var lat, lon, marker;

// HP
function validateEmail (emailField)
{
	emailpat = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9-])+(\.[a-zA-Z0-9_-]+)+$/;
	if( !emailpat.test( emailField) )
	{
		return false;
	}
	return true;
}

/* Google ads on SMI Page  */
function smi_google_ad_request_done(google_ads) 
{

	var s = '';
	var i;

	if (google_ads.length == 0) 
	{
		return;
	}

	if (google_ads.length > 1) 
	{
		$("#smi_google_ads_box").show();

		s += '<h2><a target="google_ads" class="heading" href=\"' + google_info.feedback_url + '\">Ads By Google</a></h2>';

		for(i = 0; i < google_ads.length; ++i) 
		{
			s += '<p><a class="title" target="google_ads" href="' +
			google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' +
			google_ads[i].visible_url + '\';return true"> <b>' +
			google_ads[i].line1 + '</b><br /> </a> ' +
			google_ads[i].line2 + ' ' +
			google_ads[i].line3 + ' - <a class="url" class="" target="google_ads" href="' +
			google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' +
			google_ads[i].visible_url + '\';return true">' +
			google_ads[i].visible_url + '</a></p>';
		}
	
		document.write(s);
		return;
	}
}

/**
 * Display alternative images when one fails to load.
 */

var unavailable_images = {};
unavailable_images['large']   = '/images/no_image_large.gif';
unavailable_images['medium']  = '/images/no_image.gif';
unavailable_images['small']   = '/images/no_image_small.gif';

// List of failed images.
var failed_images = Array();


/* 
 * Variable assignments
 */

var rent_google_mode = 'm';
var prices = Array();
prices['minp'] = 0;
prices['maxp'] = 0;
var fade_finished = true;

$(document).ready(function(){
// These little piggies hover the 5 main tabs
	$('#tab_rental_off').hover(
		function () {
			$(this).attr('src', '/images/tab_rental_on.gif');
		},
		function () {
			$(this).attr('src', '/images/tab_rental_off.gif');
		}
	);
	$('#tab_sharing_off').hover(
		function () {
			$(this).attr('src', '/images/tab_sharing_on.gif');
		},
		function () {
			$(this).attr('src', '/images/tab_sharing_off.gif');
		}
	);
	$('#tab_holiday_off').hover(
		function () {
			$(this).attr('src', '/images/tab_holiday_on.gif');
		},
		function () {
			$(this).attr('src', '/images/tab_holiday_off.gif');
		}
	);
	$('#tab_shortterm_off').hover(
		function () {
			$(this).attr('src', '/images/tab_shortterm_on.gif');
		},
		function () {
			$(this).attr('src', '/images/tab_shortterm_off.gif');
		}
	);
	$('#tab_parking_off').hover(
		function () {
			$(this).attr('src', '/images/tab_parking_on.gif');
		},
		function () {
			$(this).attr('src', '/images/tab_parking_off.gif');
		}
	); 
	$('#submit').hover(
		function () {
			$(this).attr('src', '/images/button_hp_search_on.gif');
		},
		function () {
			$(this).attr('src', '/images/button_hp_search.gif');
		}
	); 
	$('#sr_email_alert_link').hover(
		function () {
			$(this).css('cursor', 'pointer');
			$(this).css('text-decoration', 'underline');
		},
		function () {
			$(this).css('text-decoration', 'none');
		}
	);
	$('#sr_email_alert_link_icon').hover(
		function () {
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).css('cursor', 'default');
		}
	);
	
	var ea_loaded = 0;
	$('#email_alert_email').focus(function() {
		if ($(this).val() == 'john.smith@example.com' && !ea_loaded) // hack to ensure input div is blurred on page load
		{
			$(this).blur();
			ea_loaded = 1;
		}
		else if ($(this).val() == 'john.smith@example.com')
		{
			$(this).val('');
			$(this).css({'color': '#000', 'font-style': 'normal'});
		}
	});
	
	$('#email_alert_email').blur(function() {
		if ($(this).val() == '')
		{
			$(this).val('john.smith@example.com');
			$(this).css({'color': '#888', 'font-style': 'italic'});
		}
	});
	
// These little piggies make the form play nice
	$('#county').change(function() {
		$.get('http://www.rent.ie/rentie_area_lookup.php', {
			'area': $(this).val(),
			'search_type': $('#search_type').val()
		}, function(data){
			$('#area').html(data)
		});
		return false;
	});
	if ( $.browser.opera )
	{
		$('#main_search #area').attr('size', '10');
		$('#button_map').css('margin-top','-294px');
		$('#button_satellite').css('margin-top','-294px');
	}
	if ( $.browser.mozilla && $.browser.version.substr(0,3) < 1.9 )
	{
		$('#carousel').css('margin','14px 9px 20px');
		$('#button_map').css('margin-top','-294px');
		$('#button_satellite').css('margin-top','-294px');
		$('#photo_browser .smi_main_top').css('min-width','0');
	}
	$('#ajax').ajaxStart(function() {
		$(this).css('visibility','visible');
	}).ajaxStop(function() {
		$(this).css('visibility','hidden');
	});

// This little piggy makes Min & Max Rent interact
	prices['minp'] = $('#minp').attr('selectedIndex');
	prices['maxp'] = $('#maxp').attr('selectedIndex');
	$("select").change(function() {
		$('#refine_loading').show();
		prices[this.id] = this.selectedIndex;
		if(this.id=="minp")
		{
			if(prices['minp']>prices['maxp'])
			{
				$('#maxp').attr('selectedIndex',prices['minp']+1);
			}
		}
		else
		{
			if(this.id=="maxp")
			{
				if(prices['minp']>prices['maxp'])
				{
					if(prices['maxp']==0)
						setr = 0;
					else
						setr = prices['maxp']-1;
					$('#minp').attr('selectedIndex',setr);
				}
			}
		}
		$('#refine_loading').hide();
	});
// These little piggies get the carousel going
	$("#carousel").jCarouselLite({
		btnPrev: "#previous",
		btnNext: "#next",
		scroll: 4,
		speed: 1000,
		visible: 4
	}),
	$("#carousel li").css({
		'height': '183px'
	});
// This little piggie displays the carousel page indicator
	var curr_page = 1;
	$(".dots").hide();
	$("#dots1").show();
	$("#previous").click(
		function () {
			if (fade_finished == true)
			{
				fade_finished = false;
				prev_page = curr_page;
				curr_page--;
				if (curr_page == -1) curr_page = 3;
				hp_page = curr_page; // for some reason you need to do this to get it to work - curr_page is undefined in the Timeout
				setTimeout('$("#dots"+prev_page).hide(); $("#dots"+hp_page).show(); fade_finished = true;', 1000);
			}
		}
	);
	$("#next").click(
		function () {
			if (fade_finished == true)
			{
				fade_finished = false;
				prev_page = curr_page;
				curr_page++;
				if (curr_page == 4) curr_page = 0;
				hp_page = curr_page; // for some reason you need to do this to get it to work - curr_page is undefined in the Timeout
				setTimeout('$("#dots"+prev_page).hide(); $("#dots"+hp_page).show(); fade_finished = true;', 1000);
			}
		}
	);
// These little piggies hover the carousel arrows
	$('#previous').hover(
		function () {
			$(this).attr('src', '/images/hp_carousel_arrow_left_on.gif');
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).attr('src', '/images/hp_carousel_arrow_left_off.gif');
		}
	);
	$('#next').hover(
		function () {
			$(this).attr('src', '/images/hp_carousel_arrow_right_on.gif');
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).attr('src', '/images/hp_carousel_arrow_right_off.gif');
		}
	);
// These little piggies hover the carousel items
	$('#carousel LI').hover(
		function () {
			$(this).children('.top').css('background-image', 'url(/images/HP_carousel_li_top_on.gif)');
			$(this).children('.prop').css('background', '#474747');
			$(this).children('.bottom').css('background-image', 'url(/images/HP_carousel_li_bottom_on.gif)');
		},
		function () {
			$(this).children('.top').css('background-image', 'url(/images/HP_carousel_li_top.gif)');
			$(this).children('.prop').css('background', '#363636');
			$(this).children('.bottom').css('background-image', 'url(/images/HP_carousel_li_bottom.gif)');
		}
	);

// I'm hungry
	$("#send_mail").hover(
		function () {
			$(this).attr('src', '/images/button_submit_on.gif');
		},
		function () {
			$(this).attr('src', '/images/button_submit.gif');
		}
	);




//SR
// "More info" button hover
	$('.more_info').hover(
		function () {
			if ($(this).attr('src') == '/images/button_sr_more_info_upgrade.gif')
			{
				$(this).attr('src', '/images/button_sr_more_info_on_upgrade.gif');
			}
			else
			{
				$(this).attr('src', '/images/button_sr_more_info_on.gif');
			}
		},
		function () {
			if ($(this).attr('src') == '/images/button_sr_more_info_on_upgrade.gif')
			{
				$(this).attr('src', '/images/button_sr_more_info_upgrade.gif');
			}
			else
			{
				$(this).attr('src', '/images/button_sr_more_info.gif');
			}
		}
	);
// Pagination links hover (as CSS rules don't work for IE6)
	$('.nextprev_on').hover(
		function () {
			$(this).css('background', 'url(/images/pagination_nextprev_on.gif)');
		},
		function () {
			$(this).css('background', 'url(/images/pagination_nextprev_off.gif)');
		}
	);
	$('.page').hover(
		function () {
			$(this).css('background', 'url(/images/pagination_page_on.gif)');
		},
		function () {
			$(this).css('background', 'url(/images/pagination_page_off.gif)');
		}
	);
	$('.page_big').hover(
		function () {
			$(this).css('background', 'url(/images/pagination_page_on_big.gif)');
		},
		function () {
			$(this).css('background', 'url(/images/pagination_page_off_big.gif)');
		}
	);



//SMI
// "Contact advertiser" button hover
	$("#searchreplyform_link").hover(
		function () {
			$(this).attr('src', '/images/button_smi_contact_on.gif');
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).attr('src', '/images/button_smi_contact.gif');
		}
	);
// "Email advertiser" button hover
	$("#ajax_reply, #ajax_reply_pop").hover(
		function () {
			$(this).attr('src', '/images/button_smi_email_on.gif');
		},
		function () {
			$(this).attr('src', '/images/button_smi_email.gif');
		}
	);
// "Cancel" button hover
	$("#cancel").hover(
		function () {
			$(this).attr('src', '/images/button_smi_cancel_on.gif');
		},
		function () {
			$(this).attr('src', '/images/button_smi_cancel.gif');
		}
	);
// Photo browser pop-up
	$("#close").hover(
		function () {
			$(this).attr('src', '/images/button_smi_close_on.gif');
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).attr('src', '/images/button_smi_close.gif');
		}
	);
// Email alert popup
	$("#sr_email_alert_button").hover(
		function () {
			$(this).attr('src', '/images/button_sr_email_alert_on.gif');
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).attr('src', '/images/button_sr_email_alert.gif');
		}
	);
	$("#sr_email_alert_cancel").hover(
		function () {
			$(this).attr('src', '/images/button_smi_cancel_on.gif');
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).attr('src', '/images/button_smi_cancel.gif');
		}
	);
	$("#sr_email_alert_close").hover(
		function () {
			$(this).attr('src', '/images/button_ealert_close_on.gif');
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).attr('src', '/images/button_ealert_close.gif');
		}
	);
	$(".email_alert_frequency").hover(
		function () {
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).css('cursor', 'default');
		}
	);
	$(".email_alert_frequency").click(
		function () {
			var id = $(this).attr('id').split('_');
			var other_id;
			id = id[3];
			$('#email_alert_frequency').val(id);
			if (id == 'daily')
				other_id = 'instantly';
			else
				other_id = 'daily'
			$('#email_alert_frequency_'+id).attr('checked', 'checked');
			$('#email_alert_frequency_'+other_id).attr('checked', '');
		}
	);
// Photo browser pop-up
	$("#button_satellite").hover(
		function () {
			if (rent_google_mode != 's')
			{
				$(this).attr('src', '/images/button_smi_satellite_on.gif');
				$(this).css('cursor', 'pointer');
			}
		},
		function () {
			if (rent_google_mode != 's')
				$(this).attr('src', '/images/button_smi_satellite_off.gif');
		}
	);
	$("#button_map").hover(
		function () {
			if (rent_google_mode != 'm')
			{
				$(this).attr('src', '/images/button_smi_map_on.gif');
				$(this).css('cursor', 'pointer');
			}
		},
		function () {
			if (rent_google_mode != 'm')
				$(this).attr('src', '/images/button_smi_map_off.gif');
		}
	);
	
// The following controls the reply form
	$("#searchreplyform_fixed #ajax_reply").click(function(){
		var search_type = document.getElementById("fsearch_type").value;
		var id = document.getElementById("fad_id").value;
		ajax_reply('#searchreplyform_fixed ','');
	});
	
	function ajax_reply(div,pid) { // the use of div here is to prevent naming conflicts
		var email = document.getElementById("femail"+pid).value;
		var frm_name = document.getElementById("fname"+pid).value;
		var message_txt = document.getElementById("fcontact_textarea"+pid).value;
		message_txt = message_txt.replace(/(\r\n|\r|\n)/g, "  ");
		var phone = document.getElementById("fcontact_number"+pid).value;
		var search_type = document.getElementById("fsearch_type"+pid).value;
		var id = document.getElementById("fad_id"+pid).value;
		var data = "";
		if(frm_name=="")
		{
			data = "Please enter your name";
			$(div+'#searchmoreinfo_contact_error'+pid).html(data);
			$(div+'#searchmoreinfo_contact_error'+pid).show();														
		}
		else if(email=="")
		{
			data = "Please enter your email address";
			$(div+'#searchmoreinfo_contact_error'+pid).html(data);
			$(div+'#searchmoreinfo_contact_error'+pid).show();
		}
		else if (!validateEmail(email))
		{
			data = "That is not a valid email address";
			$(div+'#searchmoreinfo_contact_error'+pid).html(data);
			$(div+'#searchmoreinfo_contact_error'+pid).show();
		}
		else if(message_txt=="")
		{
			data = "Please enter your message";
			$(div+'#searchmoreinfo_contact_error'+pid).html(data);
			$(div+'#searchmoreinfo_contact_error'+pid).show();								
		}
		else
		{
			var prop_type_string = "property-for-sale";
			if(search_type=="sharing")
			{
					prop_type_string = "rooms-to-rent";	
			}
			else if(search_type=="holiday_homes")
			{
					prop_type_string = "holiday-homes";	
			}	
			else if(search_type=="shortterm")
			{
					prop_type_string = "short-lets";	
			}
			else if(search_type=="parking")
			{
					prop_type_string = "parking-spaces";	
			}
			else
			{
					prop_type_string = "houses-to-let";	
			}

			$(div+'#searchmoreinfo_sending'+pid).html("<img src='/images/ajax-loader-email.gif' alt='sending_reply' style='margin-bottom: 0px;' /><h2>Sending Reply</h2>");
			$(div+'#smi_content'+pid).hide();
			$(div+'#searchmoreinfo_sending'+pid).show();

			$.post('/ajax_endpoint.php',
			        {'action'  :'reply',
			         'from'    : frm_name,
			         'email'   : email,
			         'message' : message_txt,
			         'phone'   : phone,
			         'type'    : search_type,
			         'id'      : id},
			         function(data){
                        //on success
                        if(data.status == 'success')
                        {
                            $(div+'#searchmoreinfo_sending'+pid).html(data.message);
                            $(div+'#searchmoreinfo_contact_error'+pid).html(data.message);
                            if (div == '#searchreplyform_hover ')
                                setTimeout("$('#searchreplyform_hover').hide();$.unblockUI();", 3000);
                            else
                            {
                                setTimeout("$('#searchreplyform_fixed #searchmoreinfo_sending').hide(); $('#searchreplyform_fixed #smi_content').show();$('#searchreplyform_fixed #searchmoreinfo_contact_error').show();", 3000);
                            }
                            
                            // Track successful reply in GAnalytics
                            pageTracker._trackEvent('reply_sent', search_type, id);
                        }
                        else
                        {
                            $(div+'#searchmoreinfo_sending'+pid).hide();
                            // What was the error?
                            $(div+'#searchmoreinfo_contact_error'+pid).html(data.message);
                            $(div+'#smi_content'+pid).show();
                            $(div+'#searchmoreinfo_contact_error'+pid).show();
                            $(div+'#ajax_reply'+pid).show();
                        }
			        },
			        'json');
			return;
		}
	}

    // Email notice bounce 
	
	$('#fname, #femail, #fcontact_textarea, #fcontact_number').focus(function() {
		$(this).css({background: '#ffff99', border: '1px solid #ffcc00'});
	});
	$('#fname, #femail, #fcontact_textarea, #fcontact_number').blur(function() {
		$(this).css({background: '#ffffff', border: '1px solid #cccccc'});
	});
	
	$("#searchreplyform_link").click(function(){
		window.location = '#reply_form';
		$('#fname').focus();

	});
	
	$('#close_pop').hover(
		function () {
			$(this).attr('src', '/images/button_smi_close_on.gif');
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).attr('src', '/images/button_smi_close.gif');
		}
	).click(
		function(){
			$('#searchreplyform_hover').hide();
			$.unblockUI();
		}
	);
	$("#searchreplyform_hover #cancel").click(function(){
		$('#searchreplyform_hover').hide();
		$.unblockUI();
	});
	
	//email alert popup
	$("#sr_email_alert_cancel").click(function(){
		$(this).attr('src', '/images/button_smi_cancel.gif'); // wasn't re-setting to default image
		$.unblockUI();
	});
	$("#sr_email_alert_link").click(function(){
		$.blockUI({message: $('#sr_email_alert_box'), css: {margin: '160px 0 0 -275px', width: '550px', height: '293px', background: '#efefef'}});
	});
	$("#sr_email_alert_link_icon").click(function(){
		$('#sr_email_alert_box').show();
		$.blockUI({message: $('#sr_email_alert_box'), css: {margin: '160px 0 0 -275px', width: '550px', height: '293px', background: '#efefef'}});
		$('#sr_email_alert_close_pop').attr('src', '/images/button_ealert_close.gif');
	});
	$('#sr_email_alert_button').click(function() {
		if (!validateEmail($('#email_alert_email').val()))
		{
			$('#sr_email_alert_error').text('* Invalid');
		}
		else if ($('#email_alert_email').val() == '' || $('#email_alert_email').val() == 'john.smith@example.com')
		{
			$('#sr_email_alert_error').text('* Required');
		}
		else
		{
			$('#sr_email_alert_main_content').css('display', 'none');
			$('#sr_email_alert_sending').css('display', 'block');
			//insert ajax post here!
			var frequency = '';
			if ($('#email_alert_frequency_daily').attr('checked') == true)
				frequency = 'daily'
			else
				frequency = 'instantly';
			$.post('http://www.rent.co.uk/alerts.php',
				{
					'email_address': $('#email_alert_email').val(),
					'frequency': frequency,
					'affiliate': $('#affiliate').val(),
					'search_url': $('#search_url').val(),
					'search_text': $('#search_text').val(),
					'ip_address': $('#ip_address').val()
				},
				function (data) {
					var resp = $(data).find('resp').text();
					$('#sr_email_alert_sending').css('display', 'none');
					if (resp == 'bad email')
					{
						$('#sr_email_alert_error').html('* Invalid');
						$('#sr_email_alert_main_content').css('display', 'block');
					}
					else if (resp == 'ok')
					{
						$('#sr_email_alert_main_content').html("Congratulations! You have successfully set up your email alert.<p>A verification email will be sent to <b>"+$('#email_alert_email').val()+"</b> shortly.<br/>Please click on the link in this email in order to activate your email alert.</p><p>You may cancel your email alert at any stage by clicking on the deactivate link in the alert emails.</p><div class=\"divider\"></div><div style=\"float:right; margin-top: 14px;\"><img src=\"/images/button_ealert_close.gif\" onclick=\"javascript:$.unblockUI();\" onmouseover=\"javascript:$(this).css(\'cursor\', \'pointer\'); $(this).attr(\'src\', \'/images/button_ealert_close_on.gif\');\" onmouseout=\"javascript:$(this).css(\'cursor\', \'default\'); $(this).attr(\'src\', \'/images/button_ealert_close.gif\');\" /></div>");
						$('#sr_email_alert_main_content').css({'padding': '20px', 'display': 'block'});
					}
					else
					{
						$('#sr_email_alert_main_content').html("There has been an error with setting up this email alert. Please try again later.<br/><div style=\"float:right; margin-top: 14px;\"><img src=\"/images/button_smi_close.gif\" onclick=\"javascript:$.unblockUI();\" onmouseover=\"javascript:$(this).css(\'cursor', \'pointer\'); $(this).attr(\'src\', \'/images/button_ealert_close_on.gif\');\" onmouseout=\"javascript:$(this).css(\'cursor\', \'default\'); $(this).attr(\'src\', \'/images/button_ealert_close.gif\');\" /></div>");
						$('#sr_email_alert_main_content').css({'padding': '20px', 'display': 'block'});
					}
				}, 'xml');
		}
	});

// Gmap custom controls
	$('#button_map').click(
		function () {
			toggle_map_view(google.maps.MapTypeId.ROADMAP);
			$(this).css('cursor', 'default');
			$('#button_satellite').css('cursor', 'pointer');
			$(this).attr('src', '/images/button_smi_map_on.gif');
			$('#button_satellite').attr('src', '/images/button_smi_satellite_off.gif');
			rent_google_mode = 'm';
		}
	);
	$('#button_satellite').click(
		function () {
			toggle_map_view(google.maps.MapTypeId.HYBRID);
			$(this).css('cursor', 'default');
			$('#button_map').css('cursor', 'pointer');
			$(this).attr('src', '/images/button_smi_satellite_on.gif');
			$('#button_map').attr('src', '/images/button_smi_map_off.gif');
			rent_google_mode = 's';
		}
	);

// Refine bar controls
    var sr_extra = 0;
	$('#aso, #aso_indicator').hover(
		function () {
			$('#aso').css({'cursor': 'pointer', 'text-decoration': 'underline'});
			$('#aso_indicator').css({'cursor': 'pointer'});
		},
		function () {
			$('#aso').css({'cursor': 'default', 'text-decoration': 'none'});
			$('#aso_indicator').css({'cursor': 'default'});
		}
	).click(
		function () {
            if ( 0 == sr_extra )
            {
                $('#refine_loading').show();
                $('#sr_extra').slideDown(250, function() {
                    sr_extra = 1;
                    $('#aso_indicator').attr({'src': '/images/b_arrow_aso_u.gif', 'alt': 'Hide', 'title': 'Hide'});
                    $('#refine_loading').hide();
                });
            }
            if ( 1 == sr_extra )
            {
                $('#refine_loading').show();
                $('#sr_extra').slideUp(250, function() {
                    sr_extra = 0;
                    $('#aso_indicator').attr({'src': '/images/b_arrow_aso_d.gif', 'alt': 'Display', 'title': 'Display'});
                    $('#refine_loading').hide();
                });
            }
	});
	
	$('#refine_search #field').focus(function() {
		$(this).css({border: '2px solid #ffcc00'});
	}).blur(function() {
		$(this).css({border: '2px solid #fefefe'});
	});
	
	$('#refine_button').hover(
		function () {
			$(this).attr('src', '/images/button_sr_search_on.png');
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).attr('src', '/images/button_sr_search.png');
		}
	);
});
