"use strict"

var sign_in_open = false,
    eventHolder = new Object,
    startRange,
    rangeCount,
    maxResults = 10,
    randomnumber=Math.floor(Math.random()*11),
    xmlhttp,
    xmlcookie;

eventHolder['run'] = null;

$(function() {


	// DoubleClick Floodlight Action Tags
	
	var randomNum = Math.ceil(Math.random()*100000);
	
	var homesHomePage = '<iframe src="http://fls.doubleclick.net/activityi;src=3341045;type=s1hom572;cat=s1hom614;ord=' + randomNum + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>';
	var homesSearchResultsPage = '<iframe src="http://fls.doubleclick.net/activityi;src=3341045;type=s1hom572;cat=s1hom889;ord=' + randomNum + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>';
	var newhomesHomePage = '<iframe src="http://fls.doubleclick.net/activityi;src=3341045;type=s1hom572;cat=s1new448;ord=' + randomNum + ']?" width="1" height="1" frameborder="0" style="display:none"></iframe>';
	var newhomesSearchResultsPage = '<iframe src="http://fls.doubleclick.net/activityi;src=3341045;type=s1hom572;cat=s1new593;ord=' + randomNum + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>';
	var rentalHomePage = '<iframe src="http://fls.doubleclick.net/activityi;src=3341045;type=s1hom572;cat=s1ren514;ord=' + randomNum + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>';
	
	$("#homeDoubleClickFloodlightTag #doubleClickFloodlightReplace").html(homesHomePage); 
	$("#serachresultsDoubleClickFloodlightTag #doubleClickFloodlightReplace").html(homesSearchResultsPage); 
	$("#newhomesHomeDoubleClickFloodlightTag #doubleClickFloodlightReplace").html(newhomesHomePage); 
	$("#newhomesSearchResultsDoubleClickFloodlightTag #doubleClickFloodlightReplace").html(newhomesSearchResultsPage); 
	$("#rentalHomeDoubleClickFloodlightTag #doubleClickFloodlightReplace").html(rentalHomePage); 
	
	// END: DoubleClick Floodlight Action Tags

	
	var windowWidth = $(window).width(),
        main_content_container_height,
        homepage_blue_left_height,
        buying_guide_blue_left_height;

    setup_bedrooms_range_option();

    var url = window.location.pathname;
    $("#storeProperty").attr("href");
    

    if (windowWidth > '1220'){
        $("#skyscraper_target").show();
    } else {
        $("#skyscraper_target").hide();
    } 

    // Show or hide skyscraper depending on browser width when resized
    var resizeWindow = function (e) {
        if ($(window).width() < '1220') {
            $("#skyscraper_target").hide();
        } else {
            $("#skyscraper_target").show();
        }
    }

    $(window).bind("resize", resizeWindow);

    // ALL PAGES - give the main_content_container div a minimum height to accomodate a skyscraper
     if ($("#main_contant_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");
    });

    $(".search_input_button").hover(function () {
        $(this).css('backgroundColor','#2677e2');
    }, function () {
        $(this).css('backgroundColor','#4392ef');
    });

    // Set correct heights of left blue block
    $("#homepage_blue_left").css('height', $("#homepage_top").height());
    $("#buying_guide_blue_left").css('height', $("#buying-guide-head").height());
    $("#results_blue_left").css('height', $("#blue_left_helper").height());
    $("#details_blue_left").css('height', $("#blue_left_helper").height());

	
	


    // SEARCH RESULTS - related & nearby areas
    $("#similar_properties_link").toggle(function () {
        $("#more_similar_properties").slideDown();
        $("#similar_properties_link").text("Less...");
    }, function () {
        $("#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();
    });

    // 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 - 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
    if ($(".sr_search_result_1").size() <= 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');

        // 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 - 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
        $(".stored_props: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();
                });

        // Search 
        $("#maxprice").change(onChangeMaxPrice);

        // 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();
                }
                );

        //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 );

    // signed-in with a stored property search
    if ($.cookies.get('psearch_eid')) { // stored property search
        $("#latest_title").text("QuickMatch - Properties you may be interested in");
        $("a#last_alert").attr('href', '/property-for-sale/forsale_search_results.cgi?r=' + escape($.cookies.get('psearch_eid')));
        $("#browse_properties_bottom").slideDown();
        $("#browse_properties_view_hide").show();
        $("#browse_properties_bottom_button_open").hide();
        $("#browse_properties_bottom_button_close").show();
        $("#bp_not_signed").css("display","none");
        $("#bp_recent_search").css("display","none");
        $("#bp_member_search").css("display","block"); 
    } else if ($.cookies.get('searchHomes')) { // recent search on the site
        $("#latest_title").text("QuickMatch - Properties you may be interested in");			      
        var patt1 = /back_to_search_nosort&(.*)&page=/i;
        var out   = $.cookies.get('searchHomes').match(patt1);
        var qs    = out[1];
        qs = qs.replace(/bp=[^&]+&/, "");
        $("a#last_search").attr('href', '/property-for-sale/forsale_search_results.cgi?' + qs);
        $("#browse_properties_bottom").slideDown();
        $("#browse_properties_view_hide").show();
        $("#browse_properties_bottom_button_open").hide();
        $("#browse_properties_bottom_button_close").show();
        $("#bp_not_signed").css("display","none");
        $("#bp_recent_search").css("display","block");
        $("#bp_member_search").css("display","none");
    } else {
        $("#latest_title").text("QuickMatch - Latest properties in Scotland");
    }
      
        // browse properties ui actions
        $("#browse_properties_bottom_button_open").click(
                function () {
                $(this).css("display","none");
                $("#browse_properties_bottom").slideDown();
                $("#browse_properties_view_hide").css("display","block");
                $("#browse_properties_bottom_button_close").css("display","block");
                }
                );

        $("#browse_properties_bottom_button_close").click(
                function () {
                $(this).css("display","none");
                $("#browse_properties_bottom").slideUp();
                $("#browse_properties_view_hide").css("display","none");
                $("#browse_properties_bottom_button_open").css("display","block");
                }
                );


        $("#browse_properties_view_hide").click(
                function () {
                $("#browse_properties_view_hide").css("display","none");
                $("#browse_properties_bottom").slideUp();
                $("#browse_properties_bottom_button_close").css("display","none");
                $("#browse_properties_bottom_button_open").css("display","block");
                }
                );

  // if sign in link is clicked then hide the flash (for the overlay)
  $('a.thickbox').click(function() {
                $('#browse_properties_bottom_button_close').click();
            });					
    });

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() {
    var 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 = [];
                var myLabsAr = [];
                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) {
    var reg = new RegExp(cl);
    
    if (target == null) {
        return
    }

    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 modifySignInLink() {
    var test, outString, new_href;
    
    test = /s1homes.com(.+)/i.exec(document.location.href);
    outString = test[1];
    new_href = $("#sign_in_anchor").attr("href") + "?goingto=" + outString + "&amp;KeepThis=true&amp;&TB_iframe=true&amp;height=320&amp;width=480";
    $("#sign_in_anchor").attr("href", new_href);
    $("#notes_sign_in_anchor").attr("href", new_href);
}

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";
        }

        targ = document.getElementById('send-friend-signed-in');
        if(targ){
            targ.style.display = "inline";
        }

        targ = document.getElementById('send-friend-signed-out');
        if(targ){
            targ.style.display = "none";
        }
}

function show_sorted_by() {
    if (document.getElementById('sortedbyselect')) {
        show_target_nospace(target1);
    }
}

function addEvent(oTarget, sType, fpDest) {
    var oOldEvent;

    sType = 'on' + sType;
    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 onChangeMaxPrice()
{
    $("#sortedby").val("price")
}

function validateForgottenPassword() {
    if ($("input#email").val() == "") {
        $("#error_box_password").show();
        return false;
    } else {
        return true;
    }
}

function getElementsByClass(searchClass, node, tag) {
    var classElements = [],
        els,
        elsLen,
        pattern;

    if (node == null) {
        node = document;
    }
    
    if (tag == null) {
        tag = '*';
    }
    
    els = node.getElementsByTagName(tag);
    elsLen = els.length;
    pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");

    for (var 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(),
        myEmail = $("input#email").val();

    if ((myEmail == "") || (myMessage == "")) {
        $("#contact_all_agents_error").show();
        return false;
    } else {
        return true;
    }
}

function validateMyAccountSignIn() {
    var myEmail = $("input#email").val(),
        myPassword = $("input#password").val();

    if ((myEmail == "") || (myPassword == "")) {
        $("#my_account_sign_in_error_2").show();
        return false;
    } else {
        return true;
    }
}

function validateEAfp() {
    if ($("input#email").val() == "") {
        $("#ea_fp").show();
        return false;
    } else {
        return true;
    }
}

function redirect_sortedby() {
    var searchparams = $("#searchparamsnosort").val(),
        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 != "") {
        var url = script + searchparams + "&sortedby=" + $("#sortedby option:selected").val();
    }

    document.location.href = url;
}

function trim(str) { 
    str.replace(/^\s*/, '').replace(/\s*$/, ''); 
    return str;
}

function isValidEmailAddress(email_address) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return reg.test(email_address); 
}

function validateMiniContact() {
    var myName = trim($("#estate_agent_form input#name").val()),
        myEmail = trim($("#estate_agent_form input#email").val()),
        myPhone = trim($("#estate_agent_form input#phone").val()),
        myMessage = trim($("#estate_agent_form textarea#message").val()),
        returnVal = new Boolean(true);
    
    alert(myPhone);

    $("#estate_agent_error").hide();
    
    if ((myName == "") || ((myEmail == "") || (myPhone == "")) || (myMessage == "")) {
        returnVal = false;
        $("#estate_agent_error").show();
        if (myName == "") {
            $("#estate_agent_error .your_name").show();
            $("#estate_agent_form .your_name span").text("(Required)");
            $("#estate_agent_form .your_name span").show();
        } else {
            $("#estate_agent_error .your_name").hide();
            $("#estate_agent_form .your_name span").hide();
        }

        if ((myEmail == "") && (myPhone == "")) {
            $("#estate_agent_error .your_email").show();
            $("#estate_agent_form .your_email span").text("(Required)");
            $("#estate_agent_form .your_email span").show();
        } else {
            $("#estate_agent_error .your_email").hide();
            $("#estate_agent_form .your_email span").hide();
            if ((isValidEmailAddress(myEmail) === false) && (myPhone = "")){
                $("#estate_agent_error").show();
                $("#estate_agent_error .your_email").show();
                $("#estate_agent_form .your_email span").text("(Invalid email)");
                $("#estate_agent_form .your_email span").show();
            }
        }

        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();
        }
    } else {
        $("#estate_agent_error .your_name").hide();
        $("#estate_agent_form .your_name span").text("");
        $("#estate_agent_error .your_message").hide();
        $("#estate_agent_form .your_message span").text("");
        $("#estate_agent_error .your_email").hide();
        if(isValidEmailAddress(myEmail) === false){
            $("#estate_agent_error").show();
            $("#estate_agent_error .your_email").show();
            $("#estate_agent_form .your_email span").text("(Invalid email)");
            $("#estate_agent_form .your_email span").show();
            returnVal = false;
        }else{
            $("#estate_agent_error").hide();
        }
    }
    alert(returnVal);
    return returnVal;
}

function validateEstateAgentContact(){
    var myName = $("#estate_agent_form input#name").val(),
        myEmail = $("#estate_agent_form input#email").val(),
        myPhone = $("#estate_agent_form input#phone").val(),
        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("(Email address is 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(),
        myEmailAddress =    $("#my_account_form input#email").val(),
        myPostcode =        $("#my_account_form input#postcode").val(),
        myPassword =        $("#my_account_form input#password").val(),
        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 {
        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(),
        myEmailAddress = $("#my_account_form_2 #my_account_register_form input#email").val(),
        myPostcode = $("#my_account_form_2 #my_account_register_form input#postcode").val(),
        myPassword1 = $("#my_account_form_2 #my_account_register_form input#password1").val(),
        myPassword2 = $("#my_account_form_2 #my_account_register_form input#password2").val(),
        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();
        } 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 {
        $("#adwords-tracking").html("<img height=\"1\" width=\"1\" style=\"border-style:none;\" alt=\"\" src=\"http://www.googleadservices.com/pagead/conversion/1017855653/?label=ZilZCIv4iAIQpf2s5QM&amp;guid=ON&amp;script=0\"/>");
        return true;
    }
}

function validatePremier() {
    var myEmail = $("input#email").val(),
        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(),
        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 = trim($("input#contact_name").val()),
        myTelephone = trim($("input#contact_telephone").val()),
        myEmail = trim($("input#contact_email").val()),
        myMessage = trim($("textarea#contact_message").val()),
        myPropertyToSell = $("input[name='property_to_sell']:checked").val();

    if ((myName == "") || ((myTelephone == "") && (myEmail == "")) || (myMessage == "") || myPropertyToSell == "") {

        $("#contact_seller_error").show();

        if (myPropertyToSell) {
            $("#contact_seller_error .your_prop").hide();
            $("#contact_seller_list .your_prop span").hide();
        } else {
            $("#contact_seller_error .your_prop").show();
            $("#contact_seller_list .your_prop span").show();
            $("#contact_seller_list .your_prop span").text("(Required)");
        }
        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"),
        mySWi = document.getElementById("sw_inner"),
        isScraper = 0,
        isHomes = 0,
        myScraperS = [],
        myScraperF = [];

    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"),
        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.height = docHeight + 'px';
    mySWi.style.left = "20px";
    mySWi.style.top = "160px";
}

function closeSW() {
    var mySW = document.getElementById("scraper_warning"),
        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

function getChildLocationAreasFasterFour() {
    if (window.ActiveXObject ) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // xmlhttp is global
        xmlhttp.onreadystatechange = function () {
            if(xmlhttp.readyState == 4) writeAjaxContent(xmlhttp.responseText, 'sub_locations');
        };
    } else {
        if (window.XMLHttpRequest) {
            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 = "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 writeAjaxContentGeneral(content, targetDiv) {
    var targDivId = document.getElementById(targetDiv);
    if (targDivId) {
        targDivId.innerHTML = content;
    }
}

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),
        list = query.split(desp),
        res = '',
        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;
}

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) {
        xmlcookie = new ActiveXObject("Microsoft.XMLHTTP"); // xmlhttp is global
        xmlcookie.onreadystatechange = function () {
            if (xmlcookie.readyState == 4) writecookiecontent(xmlcookie.responseText);
        };
    } else {
        if (window.XMLHttpRequest) {
            xmlcookie = new XMLHttpRequest() // xmlhttp is global
            xmlcookie.onload = function () { writecookiecontent(xmlcookie.responseText) };
        }
        else return; 
    }

    if (read_cookie('mys1_eid')) {
        var type = 'home';//document.mainform.cookietype.value;
        
        if(type) {
            var id = read_cookie('mys1_eid'),
                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();
    } else {
        modifySignInLink();
    }

    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();
    }
}

function run_onload_funcs() {
    //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) }
    }
}

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');

    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'],
        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() {
   
    var fields = [],
        checkedfields = [];

    if (document.stepOne) {
        fields = ['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]);
                }
            }
        }

        fields = ['minprice', 'maxprice', '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]);
                }
            }
        }

        checkedfields = ['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;
			if(document.getElementById('refine')){
				isRefineSearch = document.getElementById('refine').value; 
			}
            if (isRefineSearch == "1"){
				showText("search_again_link", "<span><span>Hide refine search</span></span>");
                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', '185px');
                    document.stepOne.verylocals.value = veryLocal;
                }
            }

            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) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4) writeAjaxContent(xmlhttp.responseText, 'sub_locations');
        };
    } else {
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onload = function () { writeAjaxContent(xmlhttp.responseText, 'sub_locations') };
        }
        else return;
    }

    if (document.stepOne) {
        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"),
        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.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,
        script,
        url; 

    if (document.getElementById('mapPage')) {
        script = "/property-for-sale/forsale_search_results_onmap.cgi?";
    } else {
        script = "/property-for-sale/forsale_search_results.cgi?";
    }
    
    url = script + searchparams + "&base=" + this.options[this.selectedIndex].value;
    
    if (document.mainform.fromnewhomes) {
        url = "/newhomes/newhomes_search_results.cgi?" + searchparams + "&base=" + this.options[this.selectedIndex].value;
    }
    document.location.href = url;
}

function search_range_redirect(){
    var searchparams = $("#searchparams").val(),
        script,
        url;

    if (document.getElementById('mapPage')) {
        script = "/property-for-sale/forsale_search_results_onmap.cgi?";
    } else {
        script = "/property-for-sale/forsale_search_results.cgi?";
    }

    url = script + searchparams + "&base=" + this.options[this.selectedIndex].value;

    if (document.mainform.fromnewhomes) {
        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 + "="),
        len = start + name.length + 1,
        end;

    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    
    if (start == -1) return null;
    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(),
        tmp = new Date();

    ExpireDate.setTime(ExpireDate.getTime() + 10000);
    document.cookie = "advanced=true" + "; expires=" + ExpireDate.toGMTString() + "; path=/";
}

function createThisPropCountCookie(value) {
    var ExpireDate = new Date();

    ExpireDate.setTime(ExpireDate.getTime() + 6000000);
    document.cookie = "thispropcount=" + value + "; expires=" + ExpireDate.toGMTString() + "; path=/";
}

function sortedby_redirect() {
    var searchparams = document.mainform.searchparamsnosort.value,
        script, 
        url;

    if (searchparams != "") {
        if (document.getElementById('mapPage')) {
            script = "/property-for-sale/forsale_search_results_onmap.cgi?";
        } else {
            script = "/property-for-sale/forsale_search_results.cgi?";
        }
        url = script + searchparams + "&sortedby=" + document.mainform.mainform.options[document.mainform.mainform.options.selectedIndex].value;
        document.location.href = url;
    }
}

function gup(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

    var regexS = "[\\?&]"+name+"=([^&#]*)",
        regex = new RegExp(regexS),
        results = regex.exec(window.location.href);

    if (results == null) {
        return "";
    } else {
        return results[1];
    }
}

function checkReferrer(ref) {
    var mySW = document.getElementById("scraper_warning"),
        mySWi = document.getElementById("sw_inner"),
        isScraper = 0,
        isHomes = 0,
        myScraperS = [],
        myScraperF = [];

    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 (var 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"),
        mySWi = document.getElementById("sw_inner"),
        docHeight,
        docWidth;

    mySW.style.display = "block";
    mySWi.style.display = "block";

    document.getElementById("sSiteName").innerHTML = friendlyName + ", ";

    docHeight = (document.height !== undefined) ? document.height + 50 : document.body.offsetHeight + 50;
    docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
    mySW.style.height = docHeight + 'px';
    mySWi.style.left = "20px";
    mySWi.style.top = "160px";
}

function closeSW() {
    document.getElementById("scraper_warning").style.display = "none";
    document.getElementById("sw_inner").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() {
    if ($("input[name='veryLocal']:checked").length >= 1) {
        $("#allViewLocal").removeAttr("checked");
    }
}

