// JavaScript Document

// declare variables
var sign_in_open = false;
var eventHolder = new Object;
eventHolder['run'] = null;
var startRange;
var rangeCount;
var maxResults   = 10; // per page
var randomnumber=Math.floor(Math.random()*11)
// document on ready function
$(document).ready(function() {
	
	// bedrooms
	setup_bedrooms_range_option();
	
	// ALL PAGES - SHOW or HIDE the skyscraper depending on browser width
	var MYnewWindowWidth = $(window).width();
	if ( MYnewWindowWidth > '1220' )
	{
		$("#skyscraper_target").show();
	}
	else
	{
		$("#skyscraper_target").hide();
	}
	
	// ALL PAGES - SHOW or HIDE the skyscraper depending on browser width when the page is resized
	$(window).bind("resize", resizeWindow);
	
	function resizeWindow(e)
	{
		var newWindowWidth = $(window).width();
		if ( newWindowWidth < '1220' )
		{
			$("#skyscraper_target").hide();
		}
		else
		{
			$("#skyscraper_target").show();
		}
	}
	
	// ALL PAGES - give the main_content_container div a minimum height to accomodate a skyscraper
	var main_content_container_height = $("#main_content_container").height();
	if ( main_content_container_height < 650 )
	{
		$("#main_content_container").css('min-height', '600px');
	}
	
	// ALL RELEVANT PAGES - highlight the form field when a user clicks selects it
	$(":input").focus(function()
					{
						$(this).addClass("highlight_form_field");
					}
				).blur(function()
					{
						$(this).removeClass("highlight_form_field");
					}
				);
	
	// HOMEPAGE
	$(".search_input_button").hover(
      function () {
		$(this).css('backgroundColor','#2677e2');
      },
      function () {
        $(this).css('backgroundColor','#4392ef');
      }
    );
	
	
	// HOMEPAGE - get the correct height for the blue left hand bit
	var homepage_blue_left_height = $("#homepage_top").height();
	$("#homepage_blue_left").css('height', homepage_blue_left_height);
	
	// SEARCH RESULTS - get the correct height for the blue left hand bit
	var results_blue_left_height = $("#blue_left_helper").height();
	$("#results_blue_left").css('height', results_blue_left_height);
	
	// SEARCH RESULTS - related & nearby areas
	$("#similar_properties_link").toggle(
      function () {
      	//$("#similar_properties_link").hide();
		$("#more_similar_properties").slideDown();
		$("#similar_properties_link").text("Less...");
      },
      function () {
        //$("#similar_properties_link").hide();
		$("#more_similar_properties").slideUp();
		$("#similar_properties_link").text("More...");
      }
    );
	
	//SEARCH RESULTS - show similar properties info box
	$("#similar_properties_info_link").click(function () {											   	
		$("#similar_properties_info").show();
    });
	$("#similar_properties_info span a").click(function () {
    	$("#similar_properties_info").hide();
    });
	
	
	
	// DETAILS - get the correct height for the blue left hand bit
	var details_blue_left_height = $("#blue_left_helper").height();
	$("#details_blue_left").css('height', details_blue_left_height);
	
	// ESTAE AGENT DIRECTORY
	$("#ajax_loader").hide();
	$("#ea_name").show();
	
	// HOMEPAGE - latest properties - no right margin for the 4th property
	$("#homepage_latest_properties .homepage_latest:nth-child(5)").addClass("no_margin_right");
	
	// HOMEPAGE - no right margin on every 6th agent logo
	$("#homepage_agent_logos span:nth-child(6n)").addClass("no_margin_right");
	
	// HOMEPAGE - SEO cities and towns / regions swap
	$("#homepage_seo_link_1").click(function () {
		$("#homepage_seo_towns_cities").hide();
		$("#homepage_seo_regions").show();
    });
	$("#homepage_seo_link_2").click(function () {
		$("#homepage_seo_regions").hide();
		$("#homepage_seo_towns_cities").show();
    });
	
	
	// HOMEPAGE - scottish property news
	$("#homepage_news_links a").hover(
      function () {
      	$("#homepage_news_links a").removeClass("homepage_news_link_on");
		$(this).addClass("homepage_news_link_on");
      },
      function () {
        
      }
    );
	
	$("#homepage_news_links a").hover(
      function () {
      	var news_link = $(this).attr("name");
		$("#homepage_news_image img").hide();
		$("#"+news_link).show();
      },
      function () {
        
      }
    );
	
	// SEARCH RESULTS PAGE - only show the lower property alerts banner if there's more than one property
	var countSearchResults = $(".sr_search_result_1").size();
	if ( countSearchResults <= 1 )
	{
		$("#sr_search_results_alerts_2").hide();
	}
	
	// SEARCH RESULTS PAGE - show / hide refine search form

	$("#search_again_link").toggle(
      function(){
        var currenttext = $("#search_again_link").text();
        if(currenttext == 'Hide refine search') { currenttext = "<span><span>Refine search</span></span>"; }else{  currenttext = "<span><span>Hide refine search</span></span>";   }
      	$("#sr_refine_search_form").slideToggle("slow", function(){calculate_search_results_top_spacer();showText("search_again_link", currenttext)});
      },
      function(){
        var currenttext = $("#search_again_link").text();
        if(currenttext == 'Refine search') { currenttext = "<span><span>Hide refine search</span></span>"; }else{ currenttext = "<span><span>Refine search</span></span>"; }
        $("#sr_refine_search_form").slideToggle("slow", function(){calculate_search_results_top_spacer();showText("search_again_link", currenttext)});
      }
    );
	
	// SEARCH RESULTS PAGE - show / hide alerts options
	
	$("#sr_alerts_link").toggle(
      function(){
      	$("#sr_alerts_options_div").slideToggle("slow", function(){calculate_search_results_top_spacer();are_alerts_hidden_or_not();});
      },
      function(){
        $("#sr_alerts_options_div").slideToggle("slow", function(){calculate_search_results_top_spacer();are_alerts_hidden_or_not();});
      }
    );
	
	
	// SEARCH RESULTS PAGE - when the "send me new proprties..." button at the bottom of the page is clicked show a new "Hide alert options" button
	
	$("#sr_alerts_link_2").click(function () {
		$("#hide_alert_options_2").show();
		$("#sr_alerts_options_div").slideDown();
    });
	$("#hide_alert_options_2").click(function () {
		$("#hide_alert_options_2").hide();									   
		$("#sr_alerts_options_div").slideUp();
		$("#sr_alerts_link").show();
		$("#sr_alerts_link").html("<span><span>Send me new properties like these</span></span>");
    });
	
	
	
	// SEARCH RESULTS - show sub locations
	var sub_locations_height = $("#sr_refine_search").height();
	//$("#sub_locations").css('height', sub_locations_height);
	$("#sub_locations").css('height', '185px');
	
	/*
	$("#locationSelector4column").live("change", function () {
          
		var sub_locations_height = $("#sr_refine_search").height();
		
		
		if ( $("#sr_refine_search_form").hasClass("search_results_sub_loc") )
		{
			sub_locations_height = sub_locations_height - 51;
		}
		else
		{
			sub_locations_height = sub_locations_height - 20;
		}
		
		//sub_locations_height = sub_locations_height - 20;
	    $("#sub_locations").css('height', sub_locations_height);
		
        }).change();
	*/

	
	
	
	
	
	// SEARCH RESULTS - work out the width for the pagination div
	$("#sr_pagination_numbers a:last").addClass("no_margin_right");
	var aWidth = 0;
	$("#sr_pagination_numbers a").each(function (i) {
		
		var currentWidth = $(this).outerWidth(true);
		aWidth = aWidth + currentWidth;
		
      });
	$("#sr_pagination_numbers").css('width', aWidth+'px');
	
	
	
	// SEARCH RESULTS PAGE - featured agents
	$(".featured_agents span:nth-child(odd)").addClass("no_margin_right");
	
	// ALL PAGES - hide the adverts when a thickbox is opened
	$(".thickbox").click(function()
				{
					$("#right_col_advert").css('visibility','hidden');
					$("#leaderboard_target").css('visibility','hidden');
					$("#mpu_target").css('visibility','hidden');
					$("#skyscraper_target").css('visibility','hidden');
				}
			);
	
	// DETAILS PAGE - show the hand cursor when hovering over the thumbnail images
	$("#details_right_thumbs img").hover(function()
				    {
						$(this).addClass("handCursor");
					},
					function()
					{
						$(this).removeClass("handCursor");
					}
					);
	
	// DETAILS PAGE - hover effect for the search results
	/*
	$(".details_left_search_results_entry_1").live("mouseover", 
      	function()
		{
        	$(this).addClass("details_left_search_results_entry_hover");
      	});
	
	$(".details_left_search_results_entry_1").live("mouseout", 
      	function()
		{
        	$(this).removeClass("details_left_search_results_entry_hover");
      	});
	
	$(".premier_search_result_1").hover(
      	function()
		{
        	$(this).addClass("details_left_search_results_entry_hover");
      	}, 
      	function()
		{
        	$(this).removeClass("details_left_search_results_entry_hover");
      	}
    );
	*/
	
	// SEARCH RESULTS PAGE - hover effect for the search results
	/*
	$(".sr_search_result_1").hover(
      	function()
		{
        	$(this).addClass("sr_search_results_entry_hover");
      	}, 
      	function()
		{
        	$(this).removeClass("sr_search_results_entry_hover");
      	}
    );
	*/
	
	
	// DETAILS PAGE - show the shortlist
	$(".shortlist_button").click(function () {
		$("#details_left_shortlist").show();
    });

    // SERVICES DIRECTORY - hover effect
    $(".services_item").hover(
        function()
        {
            $(this).addClass("services_item_hover");
        },
        function()
        {
            $(this).removeClass("services_item_hover");
        }
    );	
	
	// DETAILS PAGE - give every third thumbnail no right margin
	$("#details_right_thumbs span:nth-child(3n)").addClass("no_margin_right");
	
	// DETAILS PAGE - click a thumbnail and show the bigger pic
	$(".details_right_thumb").click(function () {
        $("#details_right_video").hide();
		$("#details_right_main_image").show();
		$("#details_right_video_thumb").show();
    	var clickedThumb = $(this).attr("name");
		$(".details_right_image").hide();
		$("#"+clickedThumb).show();
    });
	
	// DETAILS PAGE - load the video into the correct place when the video thumbnail is clicked
	$("#details_right_video_thumb").click(function () {
    	$("#details_right_main_image").hide();
		$("#details_right_video_thumb").hide();
		$("#details_right_video").show();
    });
	
	// DETAILS PAGE - make the STORE PROPERTY button the 1st button at the bottom of the page so it has the correct styles
	$("#details_right_bottom .store_property_button").removeClass("pill-c").addClass("pill-l");
	
	// DETAILS PAGE - show SMS info
	$("#alerts_sms").click(function () {
		$("#alerts_container_1 div").appendTo("#alerts_container_2");
        $("#alerts_sms_info_box").appendTo("#alerts_container_1");
    	$("#alerts_sms_info_box").show();
    });
	// DETAILS PAGE - hide SMS info
	$("#alerts_sms_info_box span a").click(function () {
    	$("#alerts_sms_info_box").appendTo("#alerts_container_2");
		$("#alerts_sms_info_box").hide();
    });
	
	// DETAILS PAGE - show RSS info
	$("#alerts_rss").click(function () {
        $("#alerts_container_1 div").appendTo("#alerts_container_2");
    	$("#alerts_rss_info_box").appendTo("#alerts_container_1");
    	$("#alerts_rss_info_box").show();
    });
	// DETAILS PAGE - hide RSS info
	$("#alerts_rss_info_box span a").click(function () {
    	$("#alerts_rss_info_box").appendTo("#alerts_container_2");
		$("#alerts_rss_info_box").hide();
    });
	
	// DETAILS PAGE - show iGoogle info
	$("#alerts_igoogle").click(function () {
    	$("#alerts_container_1 div").appendTo("#alerts_container_2");
		$("#alerts_igoogle_info_box").appendTo("#alerts_container_1");
    	$("#alerts_igoogle_info_box").show();
    });
	// DETAILS PAGE - hide iGoogle info
	$("#alerts_igoogle_info_box span a").click(function () {
    	$("#alerts_igoogle_info_box").appendTo("#alerts_container_2");
		$("#alerts_igoogle_info_box").hide();
    });
	
	// DETAILS PAGE - show more results
	$("#details_left_show_more_link a").click(function () {
		$("#details_left_show_more_link").hide();
		$("#details_left_show_more").slideDown();
		$("#details_left_show_less_link").show();
	});
	
	// DETAILS PAGE - show more / less results
	$("#details_left_show_more_less_link a").toggle(
      function () {
      	$("#details_left_show_more").slideToggle();
		$("#details_left_show_more_less_link a").text("Show less results");
      },
      function () {
        $("#details_left_show_more").slideToggle();
		$("#details_left_show_more_less_link a").text("Show more results");
      }
    );
	
	// MY ACCOUNT PAGE - benefits of membership
	var benefits_label_height = $("#my_account_benefits ul li span").height();
	$("#my_account_benefits ul li label").css('height', benefits_label_height);
	
	// MY ACCOUNT PAGE - info box (tell me more 1)
	$("#tell_me_more_1").click(function () {
		$("#my_account_tell_me_more_1").show();
		$("#tell_me_more_1").hide();
    });
	$("#my_account_tell_me_more_1 span a").click(function () {
		$("#my_account_tell_me_more_1").hide();
		$("#tell_me_more_1").show();
    });
	
	// MY ACCOUNT PAGE - info box (tell me more 2)
	$("#tell_me_more_2").click(function () {
		$("#my_account_tell_me_more_2").show();
		$("#tell_me_more_2").hide();
    });
	$("#my_account_tell_me_more_2 span a").click(function () {
		$("#my_account_tell_me_more_2").hide();
		$("#tell_me_more_2").show();
    });
	
	// MY ACCOUNT PAGE - info box (SMS alerts)
	$("#sms_alerts").click(function () {
		$("#my_account_sms").show();
    });
	$("#my_account_sms span a").click(function () {
		$("#my_account_sms").hide();
    });
	
	// MY ACCOUNT - highlight every odd alert summary
	$("#my_account_alerts li:even").addClass("my_account_li_bg");
	
	// MY ACCOUNT - highlight every odd stored property
	$("#my_account_stored_properties li:even").addClass("my_account_li_bg");
	
	// MY ACCOUNT - SMS alerts & RSS & iGoogle info boxes
	$(".my_account_alerts #alerts_sms").click(function () {
		$("#alerts_rss_info_box").hide();
		$("#alerts_igoogle_info_box").hide();
		$("#alerts_sms_info_box").show();
    });
	$(".my_account_alerts #alerts_rss").click(function () {
		$("#alerts_sms_info_box").hide();
		$("#alerts_igoogle_info_box").hide();
		$("#alerts_rss_info_box").show();
    });
	$(".my_account_alerts #alerts_igoogle").click(function () {
		$("#alerts_sms_info_box").hide();
		$("#alerts_rss_info_box").hide();
		$("#alerts_igoogle_info_box").show();
    });
	
	// MY ACCOUNT - show sub locations
	$("#my_account_location").change(onSelectChangeMyAccount);
	
	// MY ACCOUNT - show / hide Herald & Times info
	$("#herald_times_link").click(function () {
		$("#my_account_herald_times_info").show();
    });
	$("#my_account_herald_times_info p span").click(function () {
		$("#my_account_herald_times_info").hide();
    });
	
	// MY ACCOUNT - select all checkboxes
	$("#select_all_1").click(function()				
	{
		var checked_status = this.checked;
		$("input[name=myAlerts]").each(function()
		{
			this.checked = checked_status;
		});
	});
			
	$("#select_all_2").click(function()				
	{
		var checked_status = this.checked;
		$("input[name=myProps]").each(function()
		{
			this.checked = checked_status;
		});
	});
			
	$("#locationSelector4column").click(function()				
	{
		var checked_status = this.checked;
		$("input[name=myProps]").each(function()
		{
			this.checked = checked_status;
		});
	});
	
    $('#allViewLocal').live("click", function () {
      var checked_status = this.checked;
       if(checked_status === true){
        $("input[name=veryLocal]").each(function()
        {
            this.checked = false;
        });
      }
    });
	
	
	
	// iGoogle WIdget
	$("#spHeader").hover(
      function () {
		$(this).addClass("hover");
      }, 
      function () {
		$(this).removeClass("hover");
      }
    );
	
	$("#spHeader").toggle(
			function ()
			{
				$(this).find('img').attr({src:"/ui/images/widget_arrow_2.gif", alt:"Hide stored properties", title:"Hide stored properties"});
				$("#spTag").show();
			},
			function ()
			{
				$(this).find('img').attr({src:"/ui/images/widget_arrow_1.gif", alt:"Show stored properties", title:"Show stored properties"});
				$("#spTag").hide();
			}
	);

 //Rotating advert
    var k = $("#logo_count").val();
    var r = 13;
    var old_array = new Array(1,2,3,4,5,6,7,8,9,10,11,12);
    for(var i = 0; i < old_array.length; i++)
                        {
                            $("#logo" + old_array[i]).fadeIn("slow");
                        }
    $("#homepage_agent_logos").everyTime(5000, function()
                {
                    if(r > k)
                    {
                        r = 1;
                    }
                    for(var i = 0; i < old_array.length; i++)
                    {
                        $("#logo" + old_array[i]).fadeOut();
                    }
                    setTimeout(function()
                    {
                        var a = new Array();
                        for(var i = 0; i < 12; i++)
                        {
                            if(r > k)
                            {
                                r = 1;
                                i = 12;
                            }
                            else
                            {
                                a[i] = r;
                                r++;
                            }
                        }
                        for(var i = 0; i < a.length; i++)
                        {
                            $("#logo" + a[i]).fadeIn("slow");
                        }
                        old_array = a;}, 500);
                });

//Email alerts update
$(".my_account_alerts_select").change(function(){
				var id = this.id.match( /^alerts(\d+)/ )[1];
				var val = escape($("select#alerts" + id).val());
				var url = 'update_search_freq.cgi?freq=' + val + '&searchid=' + id;
				$.get(url);
			});
	
    addEvent( window, 'load', run_onloading_funcs );
    addLoader( run_onload_funcs );
});


/************************************
 functions below
*************************************/

function showHiddenOptions()
{

	if (document.body.clientWidth > 895)
	{
		var targ = document.getElementById('advanced1024');
		if(targ)
		{
			targ.style.display = "none";
		}
		var targ2 = document.getElementById('hiddenOptions1024');
		if(targ2)
		{
			targ2.style.display = "block";
		}

	}
	else
	{
	   var targ = document.getElementById('advanced800');
	   if(targ)
	   {
	       targ.style.display = "none";
	   }
	   var targ2 = document.getElementById('hiddenOptions800');
	   if(targ2)
	   {
	       targ2.style.display = "block";
       }
	}
}

function checkHidden()
{
  if(document.stepOne)
  {
	if(	document.stepOne.garage && document.stepOne.garden && document.stepOne.centralheating &&document.stepOne.whenpropadded)
	{
	    if(document.stepOne.garage.checked || document.stepOne.garden.checked ||
    	   document.stepOne.centralheating.checked || document.stepOne.whenpropadded.value)
	    {
	  	    showHiddenOptions();
	    }
	}

	if(document.stepOne.keywords.value)
	{
	    showHiddenOptions();
	}
  }
}

function are_alerts_hidden_or_not()
{

	if ( $("#sr_alerts_options_div").is(':hidden') )
	{
		$("#sr_alerts_link").html("<span><span>Send me new properties like these</span></span>");
	}
	else
	{
		$("#sr_alerts_link").html("<span><span>Hide alert options</span></span>");
	}
}



function hide_target( t ) { t.style.visibility = 'hidden' }
function focus_target( t ) { t.focus() }
function show_target( t ) { t.style.visibility = 'visible' }
function show_target_nospace( t ) { t.style.display = 'block' }
function hide_target_nospace( t ) { t.style.display = 'none' }

function setup_bedrooms_range_option()
{
 target = document.getElementById('bedrooms');
   if ( target != null && target.nodeName == 'SELECT' )
   {
    addEvent( target, 'change', bedroomCheck );
    if ( target.options[target.options.length-1].value != '5 or more' )
    {
       target.options[target.options.length] = new Option ( 'Enter range...','Enter range...', 0,0);
    }
    else
    {
           target.options[target.options.length] = new Option ( 'Enter range...','Enter range...', 0,0);
    }
   }
}

function bedroomCheck(e)
{
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    if ( targ.options[targ.selectedIndex].value == 'Enter range...' )
    {
       s1homes_search_getUserBedroomsRange( targ );
    }
}

function s1homes_search_getUserBedroomsRange (popup) {
    var lowRange = prompt('Enter the minimum number of bedrooms:','1');
    if (lowRange == null) {
        popup.selectedIndex = 0;
        return true;
    }
    else {
        lowRange = parseInt(lowRange);
        if (isNaN(lowRange)) {
            lowRange = 1;
            if (! confirm("Please enter numbers only.\n\nYour minimum bedrooms\n    has been set to 1.")) {
                popup.selectedIndex = 0;
                return true;
            }
        }
        if (lowRange < 0) lowRange = 0;
        var highRange = prompt('Enter the maximum number of bedrooms:',lowRange);
        if (highRange == null) {
            if (lowRange <= 5) {
                popup.selectedIndex = lowRange + 2;
                return true;
            }
            else {
                popup.selectedIndex = 0;
                return true;
            }
        }
        else {
            if (isNaN(highRange)) {
                highRange = 5;
                if (! confirm("Please enter numbers only.\n\nYour maximum bedrooms\n    has been set to 5.")) {
                    popup.selectedIndex = 0;
                    return true;
                }
            }
            if (highRange < lowRange) {
                alert("You have entered a maximum lower than your minimum!\nSelect 'Enter Range...' to try again.");
                popup.selectedIndex = 0;
                return true;
            }
            else {
                var myLabel  = '';
                var myValue  = '';
                if (highRange == lowRange) {
                    myLabel = lowRange + ' (only)';
                    myValue = lowRange + '-' + lowRange;
                }
                else {
                    myLabel = lowRange + '-' + highRange;
                    myValue = myLabel;
                }
                var myValsAr = new Array ();
                var myLabsAr = new Array ();
                for (var i=0; i<popup.options.length && (i==0 || popup.options[i-1].value != 'Enter range...') ; ++i) {
                    myValsAr[i] = popup.options[i].value;
                    myLabsAr[i] = popup.options[i].value;
                }
                myValsAr[myValsAr.length] = myValue;
                myLabsAr[myLabsAr.length] = myLabel;
				repopulateMultipleSelect(popup,myValsAr,myLabsAr);
            }
        }
    }
    return true;
}

function repopulateMultipleSelect (s,av,al) {
  s.options.length = 0;
  for (var i=0; i<av.length; ++i) {
      var selectedI = i == av.length-1 ? 1 : 0;
      s.options[s.options.length] = new Option (al[i],av[i],0,selectedI);
  }
  return true;
}

function apply_to_child_class( target, cl, fun )
{
    if ( target == null ) { return }

    var reg = new RegExp(cl);

    if ( target.className && target.className.match(reg) ) { fun( target ) }

    for ( var i = 0; i<target.childNodes.length; i++ )
	{
	    apply_to_child_class( target.childNodes[i], cl, fun );
	}

}


 function showSignOut()
 {
   var targ = document.getElementById('signout');
   if(targ)
   {
     targ.style.display = "inline";
   }

   var targ1 = document.getElementById('signInHolder');
   if(targ1)
   {
     targ1.style.display = "none";
   }

   targ = document.getElementById('signedInOnlyLinks');
   if(targ)
   {
     targ.style.display = "inline";
   }

   targ = document.getElementById('igoogle');
   if(targ)
   {
     targ.style.display = "inline";
   }
 }

 function show_sorted_by()
{

  var target1 = document.getElementById('sortedbyselect');
  if (target1)
  {
    show_target_nospace(target1);
  }

}


function addEvent(oTarget, sType, fpDest) {
  sType = 'on'+sType;
  var oOldEvent = oTarget[sType];
  if (typeof oOldEvent != "function") {
    oTarget[sType] = fpDest;
  } else {
    oTarget[sType] = function(e) {
      oOldEvent(e);
      fpDest(e);
    }
  }
}

function onSelectChangeMyAccount()
{
	var selected = $("#my_account_location option:selected");
	if ( selected.val() != "-" )
	{
		$("#my_account_edit_search_sub_locations").show();
		$(".my_account_more_local_areas").hide();
		$("#"+selected.val()).show();
		$("#my_account_more_local_area_display").text("More local areas for "+selected.text())
	}
}

function validateForgottenPassword()
{
	var myEmail = $("input#email").val();
	
	if ( myEmail == "" )
	{
		$("#error_box_password").show();
		return false;
	}
	else
	{
		return true;
	}
}



function getElementsByClass(searchClass,node,tag)
{
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


function selectAll(searchClass)
{
 var checkboxes = getElementsByClass(searchClass);
 for (i=0; i < checkboxes.length; i++)
 {
  checkboxes[i].checked = true;
 }
}

function unselectAll(searchClass)
{
 var checkboxes = getElementsByClass(searchClass);
 for (i=0; i < checkboxes.length; i++)
 {
  checkboxes[i].checked = false;
 }
}



function validate_contact_all_agents()
{
	var myMessage = $("textarea#details").val();
	var myEmail = $("input#email").val();
	
	if ( (myEmail == "") || (myMessage == "") )
	{
		$("#contact_all_agents_error").show();
		return false;
	}
	else
	{
		return true;
	}
}


function validateMyAccountSignIn()
{
	var myEmail = $("input#email").val();
	var myPassword = $("input#password").val();
	if ( (myEmail == "") || (myPassword == "") )
	{
		$("#my_account_sign_in_error_2").show();
		return false;
	}
	else
	{
		return true;
	}
}


function validateEAfp()
{
	var myEmail = $("input#email").val();
	if ( myEmail == "" )
	{
		$("#ea_fp").show();
		return false;
	}
	else
	{
		return true;
	}
}


function redirect_sortedby()
{
    var searchparams = document.mainform.searchparamsnosort.value;
    var script;
    if(document.getElementById('mapPage'))
    {
        script = "/property-for-sale/forsale_search_results_onmap.cgi?";
    }
    else
    {
        script = "/property-for-sale/forsale_search_results.cgi?";
    }
    if(searchparams != "")
    {
        //if (document.mainform.sortedby)
        
//        alert( document.sortedbyform.sortedby.options[document.sortedbyform.sortedby.selectedIndex].value  + ' -  ' + document.sortedbyform.sortedby.selectedIndex);
        if (document.mainform.sortedby)
        {
	        var url = script + searchparams + "&sortedby=" + document.mainform.sortedby.options[document.mainform.sortedby.selectedIndex].value;
        }
        else
        {
            var url = script + searchparams + "&sortedby=" + document.mainform.sortedby.options[document.mainform.sortedby.selectedIndex].value;
        }
        document.location.href=url;
    }
}



function validateEstateAgentContact()
{
	//alert("here i am");
	var myName = 			$("#estate_agent_form input#name").val();
	var myEmail = 			$("#estate_agent_form input#email").val();
	var myMessage = 		$("#estate_agent_form textarea#message").val();
	
	if ( (myName == "") || (myEmail == "") || (myMessage == "") )
	{
		$("#estate_agent_error").show();
		
		if (myName == "")
		{
			$("#estate_agent_error .your_name").show();
			$("#estate_agent_form .your_name span").show();
			$("#estate_agent_form .your_name span").text("(Required)");
		}
		else
		{
			$("#estate_agent_error .your_name").hide();
			$("#estate_agent_form .your_name span").hide();
		}
		
		if (myEmail == "")
		{
			$("#estate_agent_error .your_email").show();
			$("#estate_agent_form .your_email span").show();
			$("#estate_agent_form .your_email span").text("(Required)");
		}
		else
		{
			$("#estate_agent_error .your_email").hide();
			$("#estate_agent_form .your_email span").hide();
		}
		
		if (myMessage == "")
		{
			$("#estate_agent_error .your_message").show();
			$("#estate_agent_form .your_message span").show();
			$("#estate_agent_form .your_message span").text("(Required)");
		}
		else
		{
			$("#estate_agent_error .your_message").hide();
			$("#estate_agent_form .your_message span").hide();
		}
		
		return false;
	}
	else
	{
		return true;
	}
}



function validateMyAccountSettings()
{
	var myName = 			$("#my_account_form input#name").val();
	var myEmailAddress =	$("#my_account_form input#email").val();
	var myPostcode = 		$("#my_account_form input#postcode").val();
	var myPassword = 		$("#my_account_form input#password").val();
	var myPassword2 = 		$("#my_account_form input#password2").val();
	
	if ( (myName == "") || (myEmailAddress == "") || (myPostcode == "") || (myPassword != myPassword2) )
	{
		$("#my_account_settings_errors").show();
		
		if (myName == "")
		{
			$("#my_account_settings_errors .acc_name").show();
			$("#my_account_form .acc_name span").show();
			$("#my_account_form .acc_name span").text("(Required)");
		}
		else
		{
			$("#my_account_settings_errors .acc_name").hide();
			$("#my_account_form .acc_name span").hide();
		}
		
		if (myEmailAddress == "")
		{
			$("#my_account_settings_errors .acc_email").show();
			$("#my_account_form .acc_email span").show();
			$("#my_account_form .acc_email span").text("(Required)");
		}
		else
		{
			$("#my_account_settings_errors .acc_email").hide();
			$("#my_account_form .acc_email span").hide();
		}
		
		if (myPostcode == "")
		{
			$("#my_account_settings_errors .acc_postcode").show();
			$("#my_account_form .acc_postcode span").show();
			$("#my_account_form .acc_postcode span").text("(Required)");
		}
		else
		{
			$("#my_account_settings_errors .acc_postcode").hide();
			$("#my_account_form .acc_postcode span").hide();
		}
		
		if ( myPassword != myPassword2 )
		{
			$("#my_account_settings_errors .acc_passwords_match").show();
		}
		else
		{
			$("#my_account_settings_errors .acc_passwords_match").hide();
		}
		return false;
	}
	else
	{
		//$("#my_account_settings_success").show();
		return true;
	}
}


function validateUnsubscribe()
{
	var myPassword = $("input#password").val();
	
	if ( myPassword == "" )
	{
		$("#my_account_unsubscribe_error").show();
		return false;
	}
	else
	{
		return true;
	}
}

function validateMyAccountRegister()
{
	var myName = 			$("#my_account_form_2 #my_account_register_form input#name").val();
	var myEmailAddress =	$("#my_account_form_2 #my_account_register_form input#email").val();
	var myPostcode = 		$("#my_account_form_2 #my_account_register_form input#postcode").val();
	var myPassword1 = 		$("#my_account_form_2 #my_account_register_form input#password1").val();
	var myPassword2 = 		$("#my_account_form_2 #my_account_register_form input#password2").val();
	var myPP = 				$("#my_account_form_2 #my_account_register_form .ppCheck input:checked").length;
	
	if ( (myName == "") || (myEmailAddress == "") || (myPostcode == "") || (myPassword1 == "") || (myPassword2 == "") || (myPassword1 != myPassword2) || (myPP == 0) )
	{
		$("#my_account_register_errors").show();
		
		if (myName == "")
		{
			$("#my_account_register_errors .acc_name").show();
			$("#my_account_register_form .acc_name span").show();
			$("#my_account_register_form .acc_name span").text("(Required)");
		}
		else
		{
			$("#my_account_register_errors .acc_name").hide();
			$("#my_account_register_form .acc_name span").hide();
		}
		
		if (myEmailAddress == "")
		{
			$("#my_account_register_errors .acc_email").show();
			$("#my_account_register_form .acc_email span").show();
			$("#my_account_register_form .acc_email span").text("(Required)");
		}
		else
		{
			$("#my_account_register_errors .acc_email").hide();
			$("#my_account_register_form .acc_email span").hide();
		}
		
		if (myPostcode == "")
		{
			$("#my_account_register_errors .acc_postcode").show();
			$("#my_account_register_form .acc_postcode span").show();
			$("#my_account_register_form .acc_postcode span").text("(Required)");
		}
		else
		{
			$("#my_account_register_errors .acc_postcode").hide();
			$("#my_account_register_form .acc_postcode span").hide();
		}
		
		if (myPassword1 == "")
		{
			$("#my_account_register_errors .acc_password").show();
			$("#my_account_register_form .acc_password span").show();
			$("#my_account_register_form .acc_password span").text("(Required)");
		}
		else
		{
			$("#my_account_register_errors .acc_password").hide();
			$("#my_account_register_form .acc_password span").hide();
		}
		
		if (myPassword2 == "")
		{
			$("#my_account_register_errors .acc_password_again").show();
			$("#my_account_register_form .acc_password_again span").show();
			$("#my_account_register_form .acc_password_again span").text("(Required)");
		}
		else
		{
			$("#my_account_register_errors .acc_password_again").hide();
			$("#my_account_register_form .acc_password_again span").hide();
		}
		
		if ( myPassword1 != myPassword2 )
		{
			$("#my_account_register_errors .acc_passwords_match").show();
			//alert("Password 1="+myPassword1);
			//alert("Password 2="+myPassword2);
		}
		else
		{
			$("#my_account_register_errors .acc_passwords_match").hide();
		}
		
		if ( myPP == 0 )
		{
			$("#my_account_register_errors .acc_privacy_policy").show();
			$("#my_account_register_form .acc_privacy_policy span").show();
			$("#my_account_register_form .acc_privacy_policy span").text("(Required)");
		}
		else
		{
			
			$("#my_account_register_errors .acc_privacy_policy").hide();
			$("#my_account_register_form .acc_privacy_policy span").hide();
		}
		
		return false;
	}
	else
	{
		return true;
	}
}



function validatePremier()
{
	var myEmail = $("input#email").val();
	var myPassword = $("input#password").val();
	
	if ( (myEmail == "") || (myPassword == "") )
	{
		$("#post_premier_errors").show();
		
		if (myEmail == "")
		{
			$("#post_premier_errors .post_email").show();
			$("#post_premier_ol_2 .post_email span").show();
			$("#post_premier_ol_2 .post_email span").text("(Required)");
		}
		else
		{
			$("#post_premier_errors .post_email").hide();
			$("#post_premier_ol_2 .post_email span").hide();
		}
		
		if (myPassword == "")
		{
			$("#post_premier_errors .post_password").show();
			$("#post_premier_ol_2 .post_password span").show();
			$("#post_premier_ol_2 .post_password span").text("(Required)");
		}
		else
		{
			$("#post_premier_errors .post_password").hide();
			$("#post_premier_ol_2 .post_password span").hide();
		}
		
		return false;
	}
	else
	{
		return true;
	}
}



function validateSendFriend()
{
	var myName = $("input#name").val();
	var myEmail = $("input#email").val();
	
	if ( (myName == "") || (myEmail == "") )
	{
		$("#error_box_friend").show();
		
		if (myName == "")
		{
			$("#error_box_friend .your_friends_name").show();
			$(".send_to_a_friend .your_friends_name span").show();
			$(".send_to_a_friend .your_friends_name span").text("(Required)");
		}
		else
		{
			$("#error_box_friend .your_friends_name").hide();
			$(".send_to_a_friend .your_friends_name span").hide();
		}
		
		if (myEmail == "")
		{
			$("#error_box_friend .your_friends_email").show();
			$(".send_to_a_friend .your_friends_email span").show();
			$(".send_to_a_friend .your_friends_email span").text("(Required)");
		}
		else
		{
			$("#error_box_friend .your_friends_email").hide();
			$(".send_to_a_friend .your_friends_email span").hide();
		}
		
		
		return false;
	}
	else
	{
		return true;
	}
	
}




function validateContactSeller()
{
	var myName = $("input#name").val();
	var myTelephone = $("input#telephone").val();
	var myEmail = $("input#email").val();
	var myMessage = $("textarea#comments").val();
	
	if ( (myName == "") || ((myTelephone == "") && (myEmail == "")) || (myMessage == "") )
	{
		$("#contact_seller_error").show();
		
		if (myName == "")
		{
			$("#contact_seller_error .your_name").show();
			$("#contact_seller_list .your_name span").show();
			$("#contact_seller_list .your_name span").text("(Required)");
		}
		else
		{
			$("#contact_seller_error .your_name").hide();
			$("#contact_seller_list .your_name span").hide();
		}
		
		if ( (myTelephone == "") && (myEmail == "") )
		{
			$("#contact_seller_error .your_telephone_email").show();
			$("#contact_seller_list .your_telephone_email span").show();
			$("#contact_seller_list .your_telephone_email span").text("(Either telephone or email is required)");
		}
		else
		{
			$("#contact_seller_error .your_telephone_email").hide();
			$("#contact_seller_list .your_telephone_email span").hide();
		}
		
		if (myMessage == "")
		{
			$("#contact_seller_error .your_message").show();
			$("#contact_seller_list .your_message span").show();
			$("#contact_seller_list .your_message span").text("(Required)");
		}
		else
		{
			$("#contact_seller_error .your_message").hide();
			$("#contact_seller_list .your_message span").hide();
		}
		return false;
	}
	else
	{
		return true;
	}
}


// SCRAPER WARNING

function checkReferrer(ref) {

  var mySW = document.getElementById("scraper_warning");
  var mySWi = document.getElementById("sw_inner");
  var isScraper = 0;
  var isHomes = 0;
  var myScraperS = new Array();
  var myScraperF = new Array();

  myScraperS[0] = "oodle.co.uk";
  myScraperF[0] = "Oodle";

  myScraperS[1] = "oodle.com";
  myScraperF[1] = "Oodle";

  myScraperS[2] = "vast.com";
  myScraperF[2] = "Vast";

  myScraperS[3] = "local.thesun.co.uk";
  myScraperF[3] = "The Sun Local";

  myScraperS[4] = "wheresmyproperty.com";
  myScraperF[4] = "Where's My Property";

  myScraperS[5] = "pickupaproperty.com";
  myScraperF[5] = "PickUpAProperty";

  myScraperS[6] = "renovatealerts.com";
  myScraperF[6] = "Renovate Alerts";

  myScraperS[6] = "gg.idev.s1now.com";
  myScraperF[6] = "Test Site";

  for (x=0; x<myScraperS.length; x++) {
    if (ref.indexOf(myScraperS[x]) != -1) {
	  friendlyName = myScraperF[x];
	  isScraper ++;
    }
  }
  if (location.pathname.indexOf('/buying/') != -1) isHomes = 1;

  if (isScraper && isHomes) showScraperWarning(friendlyName);
}

function showScraperWarning(friendlyName) {
  var mySW = document.getElementById("scraper_warning");
  var mySWi = document.getElementById("sw_inner");

  mySW.style.display = "block";
  mySWi.style.display = "block";
  
  alert("I'm doing it now!");

  document.getElementById("sSiteName").innerHTML = friendlyName + ", ";

  var docHeight = (document.height !== undefined) ? document.height + 50 : document.body.offsetHeight + 50;
  var docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
  //mySW.style.width = "100%";
  mySW.style.height = docHeight + 'px';
  mySWi.style.left = "20px";
  mySWi.style.top = "160px";
}

function closeSW() {
  var mySW = document.getElementById("scraper_warning");
  var mySWi = document.getElementById("sw_inner");

  mySW.style.display = "none";
  mySWi.style.display = "none";

  document.getElementById("skyscraper_target").style.display = "block";
  document.getElementById("button_target").style.display = "block";
  document.getElementById("banner_target").style.display = "block";

}

// END SCRAPER WARNING







// SEARCH RESULTS PAGE - slider functions
/*
function handleSliderChange(e, ui)
{
  var maxScroll = $("#sr_pagination .sr_prev_next_ul_2").attr("scrollWidth") -
                  $("#sr_pagination .sr_prev_next_ul_2").width();
  				  $("#sr_pagination .sr_prev_next_ul_2").animate({scrollLeft: ui.value * (maxScroll / 100) }, 1000);
}

function handleSliderSlide(e, ui)
{
  var maxScroll = $("#sr_pagination .sr_prev_next_ul_2").attr("scrollWidth") -
                  $("#sr_pagination .sr_prev_next_ul_2").width();
  				  $("#sr_pagination .sr_prev_next_ul_2").attr({scrollLeft: ui.value * (maxScroll / 100) });
}
*/

function getChildLocationAreasFasterFour()
{
    if ( window.ActiveXObject ) // if it's ie
    {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // xmlhttp is global
       xmlhttp.onreadystatechange = function ()
       {
          if(xmlhttp.readyState == 4) writeAjaxContent(xmlhttp.responseText, 'sub_locations');
       };
    }
    else
    {
       if (window.XMLHttpRequest) // if it's firefox etc.
       {
         xmlhttp        = new XMLHttpRequest() // xmlhttp is global
         xmlhttp.onload = function () { writeAjaxContent(xmlhttp.responseText, 'sub_locations') };
       }
       else return; //
    }
    if(document.stepOne.location)
    {
        var locationid = document.stepOne.location.options[document.stepOne.location.selectedIndex].value;
    }
    else if (document.stepOne)
    {
        var locationid = document.stepOne.area_id.options[document.stepOne.area_id.selectedIndex].value;
    }

    if(locationid != "")
    {
       var url = '';
       url = "http://" + document.location.hostname  +"/ssi/very-local-locations/" + locationid + ".html";
       xmlhttp.open("GET", url , true);
       xmlhttp.send(null);
       document.getElementById('more_local_areas_text').style.display = 'block';   
       document.getElementById('sub_locations').style.display = 'block';
    }
    else
    {
        writeAjaxContent('', 'sub_locations');
        document.getElementById('sub_locations').style.display = 'none';
        document.getElementById('more_local_areas_text').style.display = 'none';   
    }
}

function writeAjaxContent(content, targetDiv)
{
    var targDivId = document.getElementById(targetDiv);
    if(targDivId){
        //$("#mpu_target").hide();
		targDivId.innerHTML = content;
	    var selected = $("#locationSelector4column option:selected");
	    $(".sub_locations_first_span label").text("Anywhere in "+selected.text());
		uncheckALLVIEWLOCAL();
    }
}


function showText(divId, text)
{
    $("#" + divId).html(text);
}

function calculate_search_results_top_spacer()
{
	
	var search_results_top_spacer = $("#blue_left_helper").height();
	
	if (search_results_top_spacer > "130")
	{
		var search_results_top_spacer = search_results_top_spacer + 20;
		$("#sr_right_col_top_spacer").css('height', search_results_top_spacer);
	}
	else
	{
		$("#sr_right_col_top_spacer").css('height', '0');
	}
}


function give_search_results_top_spacer_a_fixed_height()
{
	$("#sr_right_col_top_spacer").css('height', '285px');
}


function read_cookie( name )
{
    return read_query_type( name, document.cookie, ';' );
}

function read_query_type( name, query, delim )
{
    var desp = new RegExp( delim );
    var list = query.split(desp);

    var res = '';
    var test = new RegExp('^\\s*'+name+'\\s*$');

    for ( var x = 0; x< list.length;  x++ )
	{
	    var sp = list[x].split("=");
	    if ( sp[0].match(test) )
		{
		    res = unescape(sp[1]);
		    break;
		}
	}
    return res;
}
// document loading functions below

var junk = ( navigator.userAgent.indexOf('MSIE') != -1 && navigator.userAgent.indexOf('Mac') != -1 );

function clean( target )
{
   if ( junk )
   {
      target.innerHTML = '';
   }
   else
   {
      while ( target.childNodes.length > 0 )
      {
         target.removeChild(target.firstChild)
      }
   }
}

function writeRange(start, maxCount )
{
    var target = document.getElementById('rangeBlock');
    if ( ! target || ! rangeCount || ! start || ( rangeCount < maxResults ) || maxCount > 40000)
    {
        var target1 = document.getElementById('pageSelect');

	if(target1){target1.style.display = 'inline';}
        return false;
    }

    var select = document.createElement('select');
    select.name='base';

    var target1 = document.getElementById('pageSelect');
    hide_target_nospace(target1);

    clean(target);
    var detailspage = document.getElementById('baseval');
    if(detailspage)
    {
        addEvent(select,'change', details_range_redirect);
    }
    else
    {
        addEvent(select,'change', search_range_redirect);
    }
    target.appendChild(select);

    var counter = 1;

    for ( 1; counter <= maxCount; counter = counter + maxResults )
    {
        var exit = ( counter + maxResults ) - 1;
        if ( exit >= maxCount ) { exit = maxCount }

        var opt = new Option( counter + ' to ' + exit, counter );
        if ( counter == exit ) opt = new Option( counter , counter );


        select.options[select.options.length] = opt;
        if ( counter == start )
        {
            select.options[select.options.length -1].selected = true;
        }
    }
}


function getCookieData ()
{
    if ( window.ActiveXObject ) // if it's ie
    {
       xmlcookie = new ActiveXObject("Microsoft.XMLHTTP"); // xmlhttp is global
       xmlcookie.onreadystatechange = function ()
       {
          if(xmlcookie.readyState == 4) writecookiecontent(xmlcookie.responseText);
       };
    }
    else
    {
       if (window.XMLHttpRequest) // if it's firefox etc.
       {
         xmlcookie        = new XMLHttpRequest() // xmlhttp is global
         xmlcookie.onload = function () { writecookiecontent(xmlcookie.responseText) };
       }
       else return; //
    }

	if(read_cookie( 'mys1_eid' ))
	{
	   // changes in this loop to force the page returning the name on all pages
	   //if(document.mainform && document.mainform.cookietype)
	   //{
	     var type = 'home';//document.mainform.cookietype.value;
	     if(type)
	     {
	      var id = read_cookie( 'mys1_eid' )
          var url = "";
		  if(id != 'undefined')
		  {
	        url = "http://" + document.location.hostname + "/get_cookie_data.cgi?type=" + type + "&membersid=" + id;

            xmlcookie.open("GET", url , true);
            xmlcookie.send(null);
	      }
		 }
	   //}
	}
}

function checkHidden()
{
  if(document.stepOne)
  {
	if(	document.stepOne.garage && document.stepOne.garden && document.stepOne.centralheating &&document.stepOne.whenpropadded)
	{
	    if(document.stepOne.garage.checked || document.stepOne.garden.checked ||
	    document.stepOne.centralheating.checked || document.stepOne.whenpropadded.value)
	    {
	  	    showHiddenOptions();
	    }
	}

	if(document.stepOne.keywords.value)
	{
	    showHiddenOptions();
	}
  }
}

function showHiddenOptions()
{
    if (document.body.clientWidth > 895)
    {
        var targ = document.getElementById('advanced1024');
        if(targ)
        {
            targ.style.display = "none";
        }
        var targ2 = document.getElementById('hiddenOptions1024');
        if(targ2)
        {
            targ2.style.display = "block";
        }

    }
    else
    {
       var targ = document.getElementById('advanced800');
       if(targ)
       {
           targ.style.display = "none";
       }
       var targ2 = document.getElementById('hiddenOptions800');
       if(targ2)
       {
           targ2.style.display = "block";
       }
    }
}

function run_onloading_funcs()
{
    //show advance option if values in them
    checkHidden();

    //show the sorted by drop down as we know js is enabled
    // show_sorted_by();
    //write the range 1-5 etc. drop down
    if(startRange && rangeCount)
    {
        writeRange(startRange, rangeCount);
    }


    if(read_cookie( 'mys1_eid' )) { getCookieData(); showSignOut(); }
    if (Get_Cookie( 'advanced' )) { showHiddenOptions(); }

    var targ = document.getElementById('locationSelector');
    if(targ)
    {
        addEvent( targ, 'change', getChildLocationAreasFaster);
    }

    var targ = document.getElementById('locationSelector4column');
    if(targ)
    {
        addEvent( targ, 'change', getChildLocationAreasFasterFour);
    }
    var targ = document.getElementById('refine');
    if(targ)
    {
        populate_search_form_with_cookie();
    }
    if( typeof getSearchResultsOnDetailsPage == 'function')
    {   
        getSearchResultsOnDetailsPage();
    }

// showHideExplorer();
}


function run_onload_funcs()
{
    //create and hide the mini signin dropdown form
//    create_sign_in_form();
    //add the range option to the bedrooms dropdown
    setup_bedrooms_range_option()
    //add an on change event to the location dropdown
    var targ = document.getElementById('locationSelector');
    if(targ)
    {
        addEvent( targ, 'change', getChildLocationAreasFaster);
        //show the very local option if location dropdown selected
    }

    var targ = document.getElementById('locationSelector4column');
    if(targ)
    {
        addEvent( targ, 'change', getChildLocationAreasFasterFour);
        //show the very local option if location dropdown selected
    }

    var targ = document.getElementById('locationSelectorAlter');
    if(targ)
    {
        addEvent( targ, 'change', getChildLocationAreasAlter);
        //show the very local option if location dropdown selected
    }

    var targ = document.getElementById('refine');
    if(targ)
    {
        populate_search_form_with_cookie();
    }

    var targ = document.getElementById('signInForm');
    if(targ)
    {
        if(targ.email)  { targ.email.focus(); }
    }

}

function addLoader( func )
{
    if ( eventHolder['run'] && eventHolder['run'] != null )
    {
        var oldRun = eventHolder['run'];
        eventHolder['run'] = function(e) { oldRun(e); func(e) }
    }
    else
    {
        eventHolder['run'] = function(e) { func(e) }
    }
    //    alert("addLoader" + eventHolder['run'] + '-' + func);
}

function delCookie (NameOfCookie)
{
 // The function simply checks to see if the cookie is set.
 // If so, the expiration date is set to Jan. 1st 1970.
  if (Get_Cookie(NameOfCookie))
  {
    // Change the past date from strign to jsut puting a date as cookie expire is set to older date
    //results in the expiration/deletion
    var cookie_date = new Date ( );  // current date & time
    cookie_date.setTime ( cookie_date.getTime() - 1 );
    document.cookie = NameOfCookie += "=; expires=" + cookie_date.toGMTString() + "; path=/";
    /*
    WARNING: Do not assume the Cookie has actually been deleted during that session, both Opera and IE have
    in some of their browser versions maintained the cookie until you restart your browser even if you have
    deleted it in the script. If script functionality depends on the delete action having happened, make sure
    you do another Get_Cookie test on the deleted cookie to make sure it's actually deleted.
    */
    document.cookie = NameOfCookie += "=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

function setCookie(sName, sValue)
{
    document.cookie = sName + "=" + escape(sValue) + "; path=/;";
}

function getCookie(sName)
{
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) return unescape(aCrumb[1]);
  }
  return 0;
}

function create_remember_search_cookie(f)
{
    var fields = new Array('minprice', 'maxprice', 'type', 'bedrooms', 'location', 'keywords', 'whenpropadded');

	for (var i=0; i< fields.length; i++)
	{
	    delCookie("search-" + fields[i]);
		delCookie("search-map-" + fields[i]);
		if (f[fields[i]] && f[fields[i]].selectedIndex)
		{
		    setCookie("search-" + fields[i], f[fields[i]].selectedIndex);
		    setCookie("search-map-" + fields[i], f[fields[i]].options[f[fields[i]].selectedIndex].value);
		}
		else
		{
		    setCookie("search-" + fields[i], f[fields[i]].value);
		    setCookie("search-map-" + fields[i], f[fields[i]].value);
		}
	}

	fields = new Array('garage', 'garden', 'centralheating', 'newhomes', 'soldstcm');
	for (var i=0; i< fields.length; i++)
	{
        delCookie("search-" + fields[i]);
		if (f[fields[i]] && f[fields[i]].checked)
		{
		     setCookie("search-" + fields[i], f[fields[i]].value);
		}
	}

	var veryLocal = f['veryLocal'];
	var veryLocalString = '';
	if (veryLocal)
	{
		for (var i=0; i< veryLocal.length; i++)
		{
			if(veryLocal[i].checked)
			{
				veryLocalString += 'veryLocal=' + veryLocal[i].value + '&';
			}
		}

		setCookie("search-veryLocal", veryLocalString);
	} else {
		delCookie("search-veryLocal");
	}
   return true;
}

function populate_search_form_with_cookie()
{
  if(document.stepOne)
  {
	  var fields = new Array('minprice', 'maxprice', 'keywords');

	  for (var i=0; i < fields.length; i++)
	  {
		if (getCookie('search-' + fields[i]) && document.stepOne)
		{
		    if(document.stepOne[fields[i]])
		    {
		        document.stepOne[fields[i]].value = getCookie('search-' + fields[i]);
		    }
		}
	  }

	  var fields = new Array('type', 'bedrooms', 'location', 'whenpropadded');
	  for (var i=0; i < fields.length; i++)
	  {
	    if (getCookie('search-' + fields[i]) && document.stepOne)
		{
		  if(document.stepOne[fields[i]])
		  {
		    document.stepOne[fields[i]].selectedIndex = getCookie('search-' + fields[i]);
	      }
		}
	  }


      //var checkedfields = new Array('garage', 'garden', 'centralheating', 'newhomes', 'soldstcm' );
      var checkedfields = new Array('newhomes', 'soldstcm' );
	  for (var i=0; i < checkedfields.length; i++)
	  { 
        if(getCookie('search-' + checkedfields[i]))
		{
		    document.stepOne[checkedfields[i]].checked = true;
		}else{
			document.stepOne[checkedfields[i]].checked = false;
		}
      }

	  if (getCookie('search-keywords') && document.stepOne)
	  {
		var kys = getCookie('search-keywords');
		if (!kys || kys == 'undefined') { kys = ''; }
		document.stepOne.keywords.value = kys;
	  }

	  if( (document.stepOne['location'].selectedIndex && document.stepOne) || (document.getElementById('refine').value=="1") )
	  {
	    var veryLocal = getCookie('search-veryLocal');
        var isRefineSearch = document.getElementById('refine').value; 
        if (isRefineSearch === "1"){
            showText("search_again_link", "<span><span>Hide refine search</span></span>");
            //hideMPU();
			give_search_results_top_spacer_a_fixed_height();
            var targ = document.getElementById('sr_refine_search_form').style.display = 'block';
            if ( veryLocal && veryLocal != '' ) { 
                
				document.getElementById('more_local_areas_text').style.display = 'block';   
				
	            var sub_locations_height = $("#sr_refine_search").height();
            	//$("#sub_locations").css('height', sub_locations_height);
				$("#sub_locations").css('height', '185px');
				
				document.stepOne.verylocals.value = veryLocal;
				
//                var text = document.getElementById('sr_refine_search_form').innerHTML(); 
            }
        }
	    if ( veryLocal && veryLocal != '' )
		{
			document.stepOne.verylocals.value = veryLocal;
		}
	    getChildLocationAreasAlter();
	  }

  }
}







function hideMPU()
{
    $("#right_col_advert").css('visibility','hidden');
    $("#leaderboard_target").css('visibility','hidden');
    $("#mpu_target").css('visibility','hidden');
    $("#skyscraper_target").css('visibility','hidden');
    $("#home_reports_container").css('visibility','hidden');
	$("#google_ad_sense_300x250").css('visibility','hidden');
}

function getChildLocationAreasAlter ()
{
    if ( window.ActiveXObject ) // if it's ie
    {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // xmlhttp is global
       xmlhttp.onreadystatechange = function ()
       {
          if(xmlhttp.readyState == 4) writeAjaxContent(xmlhttp.responseText, 'sub_locations');
       };
    }
    else
    {
       if (window.XMLHttpRequest) // if it's firefox etc.
       {
         xmlhttp        = new XMLHttpRequest() // xmlhttp is global
         xmlhttp.onload = function () { writeAjaxContent(xmlhttp.responseText, 'sub_locations') };
       }
       else return; //
    }

	if(document.stepOne)
	{
//        var locationid = document.mainform.location_id.value;;
		if(document.stepOne.verylocals)
		{
	        var locationid = document.stepOne.location.options[document.stepOne.location.selectedIndex].value;
            var verylocals = document.stepOne.verylocals.value;
        }
	}
	if(document.getElementById('sub_locations'))
	{
	    var targ = document.getElementById('sub_locations').style.display = 'block';
        document.getElementById('more_local_areas_text').style.display = 'block';
	}
	if(locationid != "")
	{
	   var url = "http://" + document.location.hostname + "/property-for-sale/get-child-locations.cgi?locationid=" + locationid + "&" + verylocals;
       xmlhttp.open("GET", url , true);
       xmlhttp.send(null);
	}
	else
	{
	   var targ = document.getElementById('sub_locations');
	   if(targ)
	    {
	       targ.style.display = 'none';
		}
	}
}

function showScraperWarning(friendlyName) {
  var mySW = document.getElementById("scraper_warning");
  var mySWi = document.getElementById("sw_inner");

  mySW.style.display = "block";
  mySWi.style.display = "block";

  document.getElementById("sSiteName").innerHTML = friendlyName + ", ";

  var docHeight = (document.height !== undefined) ? document.height + 50 : document.body.offsetHeight + 50;
  var docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
  //mySW.style.width = "100%";
  mySW.style.height = docHeight + 'px';
  mySWi.style.left = "20px";
  mySWi.style.top = "160px";
}

function read_cookie( name )
{
    return read_query_type( name, document.cookie, ';' );

}

function writecookiecontent (content)
{
    var targ = document.getElementById('cookieText');
	if(targ && !content.match(/.error./))
	{
        document.getElementById('cookieText').innerHTML = content;
    }
}

function details_range_redirect()
{
    var searchparams = document.mainform.searchparams.value;
    var script;
    if(document.getElementById('mapPage'))
    {
        script = "/property-for-sale/forsale_search_results_onmap.cgi?";
    }
    else
    {
        script = "/property-for-sale/forsale_search_results.cgi?";
    }
    var url = script + searchparams + "&base=" + this.options[this.selectedIndex].value;
    if(document.mainform.fromnewhomes)
    {
        var fromnewhomes = document.mainform.fromnewhomes.value;
        url = "/newhomes/newhomes_search_results.cgi?" + searchparams + "&base=" + this.options[this.selectedIndex].value;
    }
    document.location.href=url;
}

function search_range_redirect()
{
    var searchparams = document.mainform.searchparams.value;
    var script;
    if(document.getElementById('mapPage'))
    {
        script = "/property-for-sale/forsale_search_results_onmap.cgi?";
    }
    else
    {
       script = "/property-for-sale/forsale_search_results.cgi?";
    }
    var url = script + searchparams + "&base=" + this.options[this.selectedIndex].value;
    if(document.mainform.fromnewhomes)
    {
        var fromnewhomes = document.mainform.fromnewhomes.value;
        url = "/newhomes/newhomes_search_results.cgi?" + searchparams + "&base=" + this.options[this.selectedIndex].value;
    }
    document.location.href=url;
}

function Get_Cookie( name )
{
   var start = document.cookie.indexOf( name + "=" );
   var len = start + name.length + 1;
   if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
   {
      return null;
   }
   if ( start == -1 ) return null;
   var end = document.cookie.indexOf( ";", len );
   if ( end == -1 ) end = document.cookie.length;
   return unescape( document.cookie.substring( len, end ) );
}

function createCookie()
{
    var ExpireDate = new Date ();
    var tmp = new Date();
    ExpireDate.setTime(ExpireDate.getTime() + 10000);
    var curCookie = "advanced=true" + "; expires=" + ExpireDate.toGMTString() + "; path=/";
    document.cookie = curCookie;
}

// we need to send across the prop_id, this count of this prop and the showing X of this prop
function createThisPropCountCookie( value )
 {
   var ExpireDate = new Date ();
   var tmp = new Date();
   ExpireDate.setTime(ExpireDate.getTime() + 6000000);
   var curCookie = "thispropcount=" + value + "; expires=" + ExpireDate.toGMTString() + "; path=/";
   document.cookie = curCookie;
 }
function sortedby_redirect()
{
    var searchparams = document.mainform.searchparamsnosort.value;
    if(searchparams != "")
    {
        var script;
        if(document.getElementById('mapPage'))
        {
            script = "/property-for-sale/forsale_search_results_onmap.cgi?"
        }
        else
        {
            script = "/property-for-sale/forsale_search_results.cgi?";
        }
        document.location.href=url;
	    var url = script + searchparams + "&sortedby=" + document.mainform.mainform.options[document.mainform.mainform.options.selectedIndex].value;
    }
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function checkReferrer(ref) {

  var mySW = document.getElementById("scraper_warning");
  var mySWi = document.getElementById("sw_inner");
  var isScraper = 0;
  var isHomes = 0;
  var myScraperS = new Array();
  var myScraperF = new Array();

  myScraperS[0] = "oodle.co.uk";
  myScraperF[0] = "Oodle";

  myScraperS[1] = "oodle.com";
  myScraperF[1] = "Oodle";

  myScraperS[2] = "vast.com";
  myScraperF[2] = "Vast";

  myScraperS[3] = "local.thesun.co.uk";
  myScraperF[3] = "The Sun Local";

  myScraperS[4] = "wheresmyproperty.com";
  myScraperF[4] = "Where's My Property";

  myScraperS[5] = "pickupaproperty.com";
  myScraperF[5] = "PickUpAProperty";

  myScraperS[6] = "renovatealerts.com";
  myScraperF[6] = "Renovate Alerts";
  myScraperS[6] = "gg.idev.s1now.com";
  myScraperF[6] = "Test Site";

  for (x=0; x<myScraperS.length; x++) {
    if (ref.indexOf(myScraperS[x]) != -1) {
      friendlyName = myScraperF[x];
      isScraper ++;
    }
  }
  if (location.pathname.indexOf('/buying/') != -1) isHomes = 1;

  if (isScraper && isHomes) showScraperWarning(friendlyName);
}

function showScraperWarning(friendlyName) {
  var mySW = document.getElementById("scraper_warning");
  var mySWi = document.getElementById("sw_inner");

  mySW.style.display = "block";
  mySWi.style.display = "block";

  document.getElementById("sSiteName").innerHTML = friendlyName + ", ";

  var docHeight = (document.height !== undefined) ? document.height + 50 : document.body.offsetHeight + 50;
  var docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
  //mySW.style.width = "100%";
  mySW.style.height = docHeight + 'px';
  mySWi.style.left = "20px";
  mySWi.style.top = "160px";
}


function closeSW() {
  var mySW = document.getElementById("scraper_warning");
  var mySWi = document.getElementById("sw_inner");

  mySW.style.display = "none";
  mySWi.style.display = "none";

  document.getElementById("skyscraper_target").style.display = "block";
  document.getElementById("button_target").style.display = "block";
  document.getElementById("banner_target").style.display = "block";
}

function checkLocation()
{
  if(document.mainform.noagents.value == 1)
  {
    alert("Sorry we have no agents listed for this location.");
    return false;
  }

  if(!document.mainform.locationid.value.match(/[A-Za-z0-9]/))
  {
    alert("Please select a location first");
    return false;
  }

  if(document.mainform.locationid.value == 7)
  {
    document.location.href = '/selling/glasgow-select.shtml';
    return true;
  }
  else if (document.mainform.locationid.value == 5)
  {
    document.location.href = '/selling/edinburgh-select.shtml';
    return true;
  }
  else
  {
    document.location.href = '/selling/contact_agents.cgi?location=' + document.mainform.locationid.value;
    return true;
  }
}

// sub locations - uncheck 'Anywhere' check box if a sub location is checked
function uncheckALLVIEWLOCAL()
{
	var n = $("input[name='veryLocal']:checked").length;
    //alert(n + (n <= 1 ? " is" : " are") + " checked!");
	  
	if ( n >= 1 )
	{
		$("#allViewLocal").removeAttr("checked");
	}
}
