
$(document).ready(function() {

    $SearchBar = {
        searchWrap: $('#searchWrap'),
        search: $('#search'),
        searchNav: $('#searchNav'),
        changeYourSearch: $('#changeYourSearch'),
        submitButton: $('#submitSearch'),
        allLocations: $('#sAL'),
        allOtherLocations: $('#sIS, #sCL, #sHA, #sVI, #sOT'),
        otherAreas: $('#sOT'),
        otherAreasLabel: $('#otherAreasLabel'),
        boxAndLabel: $('#otherAreasLabel, #otherAreas, #sOT'),
        priceRangeMin: $('#minPrice'),
        priceRangeMax: $('#maxPrice'),
        priceRanges: $('#minPrice, #maxPrice'),
        searchType: $('#searchForProperties')
    }

    // GLOBAL INITS **********************/

    consolePlus.init();
    Global.init();	

    $SearchBar.submitButton.click(function() {

        Global.submitSearchForm();
        return false;
    });

    Global.enhanceInput($('#aWPostcode'));
    Global.enhanceInput($('#newsName'));
    Global.enhanceInput($('#newsEmail'));


    // PAGE / DOM SPECIFIC INITS **********************/

    if ($('#searchNav').length > 0) {
        PropertyPage.init();
        Global.Overlay.init();
        Global.Overlay.Contact.init();
        $('#aTwitter a').click(function() {
            Global.twitterShare($(this));
            return false;
        });

        $('#aFacebook a').click(function() {
            Global.facebookShare($(this));
            return false;
        });
    }

    if ($('#searchResults').length > 0) {
        SearchResults.init();
    }

    if ($('#singleSlide').length > 0) {
        Global.singleSlide($('#singleSlide'));
    }

    if ($('#iconIntroNotepad').length > 0) {
        Global.ExpandingLists.init();
    }

    if ($('#mainContact').length > 0) {
        Global.Overlay.init();
        Global.Overlay.Contact.init();
        $('#generalForm').simpleValidate({
            submitButtonID: "#submitEnquiry"
        });
    }

    if ($('#left .officeBar').length > 0) {
        Global.Overlay.init();
        Global.Overlay.Contact.init();
        $('#generalForm').simpleValidate({
            submitButtonID: "#submitEnquiry"
        });
    }

    if ($('#newHomesTable').length > 0) {
        PropertyPage.NewHomes.init();
    }

    if ($('#appForm').length > 0) {
        $('#appraisalForm').simpleValidate({
            submitButtonID: "#aPSubmit"
        });
        MarketAppraisal.init();
    }

    if ($('#featuredProperties').length > 0) {
        Global.enhancePropertyLinks();
    }

    if ($('#homeSlides').length > 0) {
        HomeSlides.init();
		Global.newsletterWidget();
    }

    if ($('#slideShow').length > 0) {
        GallerySlides.init();
    }

    if ($('#manageNav').length > 0) {
        Global.configureSiteSwitch($('#managementSwitch'));
    }

});
/************************* CONFIGURATION *********************/

config = {

    historySupported: null,
    searchHidden: false,
    isIE6: false,
    isIE7: false,
    isIE8: false,

    filters: {
        houses: "fH",
        flats: "fF",
        newHomes: "fNH",
        soldProperties: "fSP",
        underOffer: "fUO"
    },

    orderBy: {
        resultsPerPage: "rPP",
        resultsOrder: "rO"
    },

    ajaxURL: {
        mainResults: "/search-results/results_l",
        locations: "/assets/js/tempData/locations.js",
        floorplans: "/assets/js/tempdata/floorplan.php",
        emailFriend: "/assets/js/tempdata/emailFriend.php",
        submitEmailFriendForm: "/assets/js/tempdata/submitForm.php",
        submitContactForm: "/assets/js/tempdata/submitForm.php",
		mailChimpURL: "/assets/js/tempdata/newsletter.php"
    },
    // add a question mark on the end of these two

    // html5 test url: 
	//resultsURL: "/cleanHTML/searchResultsPage.html?",
    // html4 test url: 
    //html4ResultsURL: "/cleanHTML/searchResultsPage.html#searchResultsPage.html?",

    resultsURL: "/search-results?",
    html4ResultsURL: "/search-results#search-results?",

    maxMapZoom: 10,

    buyPricesMin: [
		["0", "0", "1"],
		["5", "5", "0"],
		["10", "10", "0"]
	],

    buyPricesMax: [
		["5", "5", "0"],
		["10", "10", "0"],
		["234235245", "£20,000,000+", "1"]
	],

    rentPricesMin: [
		["0", "rent0", "1"],
		["1", "rent1", "0"],
		["2", "rent2", "0"]
	],
    rentPricesMax: [
		["1", "rent1", "0"],
		["2", "rent2", "0"],
		["3", "rent3", "1"]
	]
}



/************************* CLASSES + FUNCTIONS *********************/

/*
TODO Update the checkbox functions so deselecting everything is impossible
*/


Global = function() {

    config.historySupported = supports_history_api();

    function init() {
        // moves search form back to the top of the page.
        $('#headerWrap').after($SearchBar.searchWrap);

        if ($SearchBar.searchWrap.attr('data-hidden') == 'true') {
            config.searchHidden = true;
            hideSearchInitially();
        }

        // test for the disfunctional family...

        if ($.browser.msie) {
            if ($.browser.version == "6.0") {
                config.isIE6 = true;
            }

            if ($.browser.version == "7.0") {
                config.isIE7 = true;
            }

            if ($.browser.version == "8.0") {
                config.isIE8 = true;
            }
        }

        goToForm();
        OtherAreas.init();
        locationCheckBoxes();
        PriceRangeSwap.init();
    }


    function configureSiteSwitch($el) {
        $el.remove().addClass('on');
        $('#siteSwitch ul').children('li').removeClass('on').end().prepend($el);
    }

    function hideSearchInitially() {
        $SearchBar.search.hide();
        $SearchBar.searchWrap.height(0);
        $SearchBar.changeYourSearch.click(function() {
            searchSlideOpen();
            return false;
        });
    }

    function searchSlideOpen() {
        $SearchBar.changeYourSearch.fadeOut(300);
        $SearchBar.searchWrap.addClass('searchBorder');
        $SearchBar.searchNav.addClass('searchNavBorders');
        $SearchBar.searchWrap.animate({ height: 121 }, { easing: "easeOutQuint" }, { duration: 300 });
        setTimeout(function() {
            $SearchBar.search.fadeIn(300);
        }, 130);
    }

    function singleSlide(slideWrap) {
        var topOffSet = 86;
        var text = slideWrap.children('div');
        var textHeight = text.height();
        var image = slideWrap.children('img');
        topOffSet = Math.round((251 - parseFloat(textHeight)) / 2 + 10);

        text.css({ top: topOffSet + 45, opacity: 0 });
		if(image[0].complete) {
			doAnimation();
		} else {
			image.load(function() {
				doAnimation();
	        });
		}

		function doAnimation() {
			setTimeout(function() {
                text.animate({ opacity: 0.99 }, { queue: false, duration: 1000 }).animate({ top: topOffSet }, { queue: false, easing: "easeOutQuint", duration: 1600 });
            }, 200);
		}
    }

    function supports_history_api() {
        return !!(window.history && history.pushState);
    }

    function windowOpener(windowHeight, windowWidth, windowName, windowUri) {
        var centerWidth = (window.screen.width - windowWidth) / 2;
        var centerHeight = (window.screen.height - windowHeight) / 2;

        newWindow = window.open(windowUri, windowName, 'resizable=0,width=' + windowWidth +
	        ',height=' + windowHeight +
	        ',left=' + centerWidth +
	        ',top=' + centerHeight);

        newWindow.focus();
        return newWindow.name;
    }

    function twitterShare(el) {
        var url = el.attr('data-url');
        var text = el.attr('data-text');
        var url = "http://twitter.com/share?url=" + url + "&text=" + text;

        windowOpener(300, 500, "Twitter Share Window", url);
    }

    function facebookShare(el) {
        var url = el.attr('data-url');
        var url = "http://www.facebook.com/sharer.php?u=" + url;
        windowOpener(300, 500, "Twitter Share Window", url);
    }

    PriceRangeSwap = function() {

        var buyPriceListMin,
		buyPriceListMax,
		rentPriceListMin,
		rentPriceListMax,
		buyListOn;

        function init() {

            buyPriceListMin = buildOptionList(config.buyPricesMin);
            buyPriceListMax = buildOptionList(config.buyPricesMax);
            rentPriceListMin = buildOptionList(config.rentPricesMin);
            rentPriceListMax = buildOptionList(config.rentPricesMax);
            configureSelects();


            bindEvents();
        }

        function configureSelects() {
            if ($SearchBar.searchType.val() == "b") {
                configureBuyingPrices();
            } else {
                configureLettingPrices();
            }
        }

        function bindEvents() {
            $SearchBar.searchType.change(function() {
                if ($(this).val() == "b") {
                    if (!buyListOn) {
                        configureBuyingPrices();
                    }
                } else {
                    if (buyListOn) {
                        configureLettingPrices();
                    }
                }
            });
        }

        function configureBuyingPrices() {
            $SearchBar.priceRangeMin.html(buyPriceListMin);
            $SearchBar.priceRangeMax.html(buyPriceListMax);
            configurePriceLabel(true);
            buyListOn = true;
        }

        function configureLettingPrices() {
            $SearchBar.priceRangeMin.html(rentPriceListMin);
            $SearchBar.priceRangeMax.html(rentPriceListMax);
            configurePriceLabel(false);
            buyListOn = false;
        }

        function configurePriceLabel(buyingLabel) {
            if (buyingLabel) {
                $('#minPriceLabel').children('strong').html("Price Range");
            } else {
                $('#minPriceLabel').children('strong').html("Price Range (Per Week)");
            }
        }

        function buildOptionList(opts) {
            var optionList = [];
            var j = 0;
            var optsLength = opts.length;

            for (var i = 0; i < optsLength; i++) {
                optionList[j++] = '<option ';
                optionList[j++] = 'value="';
                optionList[j++] = opts[i][0];
                if (opts[i][2] == "1") {
                    optionList[j++] = '" selected="selected">';
                } else {
                    optionList[j++] = '">';
                }
                optionList[j++] = opts[i][1];
                optionList[j++] = '</option>';
            };

            return optionList.join('');
        }


        return {
            init: init,
            configureSelects: configureSelects
        }
    } ();

    function submitSearchForm() {
        var slug;
        if (config.historySupported) {
            slug = config.resultsURL;
        } else {
            slug = config.html4ResultsURL;
        }

        var qs = slug + $SearchBar.search.children('form').serialize() + constructDefaultQueryValues();
		
		
        window.location.href = qs;


        function constructDefaultQueryValues() {
            var defaultString = [];
            var j = 0;
            defaultString[j++] = "&";
            defaultString[j++] = config.filters.houses;
            defaultString[j++] = "=on&";
            defaultString[j++] = config.filters.flats;
            defaultString[j++] = "=on&";
            defaultString[j++] = config.filters.newHomes;
            defaultString[j++] = "=on&";
            defaultString[j++] = config.filters.underOffer;
            defaultString[j++] = "=on&";
            defaultString[j++] = config.orderBy.resultsPerPage;
            defaultString[j++] = "=10&";
            defaultString[j++] = config.orderBy.resultsOrder;
            defaultString[j++] = "=2&";
            defaultString[j++] = "aX=0";

            return defaultString.join('');
        }
    }

    function locationCheckBoxes() {

        var $remainingInput;

        configureOtherAreas();

        $SearchBar.allLocations.change(function() {
            if ($(this).prop('checked')) {
                $SearchBar.allOtherLocations.prop('checked', false);
                OtherAreas.tickAllBoxes();
            }
            configureOtherAreas();
        });

        $SearchBar.allOtherLocations.change(function() {

            if ($(this).prop('checked') == true) {
                $SearchBar.allLocations.prop('checked', false);
            }
            configureOtherAreas();
        });

        function configureOtherAreas() {
            if ($SearchBar.otherAreas.prop('checked') == true) {
                OtherAreas.enable();
            } else {
                OtherAreas.disable();
            }

        }
    }

    OtherAreas = function() {
        var $otherAreas,
		$warningBox,
		$areas,
		enabled = false;

        function init() {
            $otherAreas = $('#otherAreas');
            $areas = $otherAreas.children('div').children('table');
            $otherAreas.hide();
            $otherAreas.find('input').hide().before('<span><!-- --></span>');
            bindEvents();
        }

        function bindEvents() {
            $SearchBar.boxAndLabel.hover(function() {
                $otherAreas.show();
            }, function() {
                $otherAreas.hide();
            });
        }

        function enableOtherAreas() {
            if (!enabled) {
                $otherAreas.find('input').show();
                $otherAreas.find('span').hide();

                enabled = true;
            }
        }

        function disableOtherAreas() {
            if (enabled) {
                $otherAreas.find('input').hide();
                $otherAreas.find('span').show();
                enabled = false;
            }
        }

        function tickAllBoxes() {
            $otherAreas.find(':input').prop('checked', true);
        }

        return {
            init: init,
            disable: disableOtherAreas,
            enable: enableOtherAreas,
            tickAllBoxes: tickAllBoxes
        }

    } ();

    Overlay = function() {
        var hoverLay = false,
		multipleContent = false,
		stopEvents = false,
		floorplanActive = false,
		newHomesRequest = false,
		originalPropertyName = "";

        var $overlay,
		$close,
		$overlayInitialWrap,
		$overlayContent,
		$overlayBox,
		$overlayHeader,
		$formSubmitting,
		$overlayInitialHeaderContent;

        function init() {
            $overlay = $('#overlay');
            $close = $('#contactClose');
            $overlayBox = $('#overlayBox');
            $overlayInitialWrap = $('#overlayInitialWrap');
            $overlayContent = $('#overlayContent');
            $overlayHeader = $('#overlayHeader');
            $overlayInitialHeaderContent = $('#overlayInitialHeaderContent');

            $overlay.hide().addClass('overlayWithJS');
            bindEvents();

            // tests if overlay activates automatically
            var theURL = window.location.href;
            var patt = /activateoverlay/;
            if (patt.test(theURL)) {
                var triggerType = theURL.match(/activateoverlay=([^&]*)/);
                if (triggerType[1]) {
                    triggerSwitch(triggerType[1]);
                }
            }

        }

        function bindEvents() {
            $overlayBox.hover(function() {
                hoverLay = true;
            }, function() {
                // if statement is fix for Chrome 9.x
                //	if(event.target == this) {
                hoverLay = false;
                //	}
            });

            $overlay.click(function() {
                if (hoverLay == false && stopEvents == false) {
                    $overlay.fadeOut('fast');
                    restoreInitialContents();
                    return false;
                }
            });

            $close.click(function() {
                if (!stopEvents) {
                    $overlay.fadeOut('fast');
                    restoreInitialContents();
                    return false;
                }
            });

            $('.overlayTrigger').click(function() {
                var overlayType = $(this).attr('data-overlay-type');
                triggerSwitch(overlayType, $(this));
                return false;
            });

        }

        function triggerSwitch(overlayType, el) {
            $overlayBox.css('marginTop', $(document).scrollTop() + 40 + "px");

            switch (overlayType) {
                case "general":
                    Contact.showCorrectForm("general");
                    multipleContent = false;
                    break;

                case "request":
                    Contact.showCorrectForm("request", el);
                    multipleContent = false;
                    break;

                case "floorplan":
                    Floorplans.showFloorPlan(el.attr('data-property-title'), el.attr('href'));
                    multipleContent = true;
                    break;

                case "floorplanMulti":

                    FloorplansMulti.showFloorPlan(el.attr('data-property-title'), el.attr('href'));
                    multipleContent = true;
                    break;

                case "emailFriend":
                    EmailFriend.showEmailForm(el.attr('data-property-title'));
                    multipleContent = true;

                    break;

                case "generalEnquiry":
                    multipleContent = false;

                    break;
                default:
                    alert('overlay trigger not functioning correctly');
            }
            $overlay.fadeIn('300');
        }

        function hideInitialContents() {

            $overlayInitialWrap.hide();
            $overlayInitialHeaderContent.hide();

            if (config.isIE7 || config.isIE6) {
                $('#contactOverlayRight').css({ visibility: "hidden" });

            }
        }

        function restoreInitialContents() {

            if (multipleContent) {
                // reset various overlay type booleans
                floorplanActive = false;
                $overlayContent.removeClass('overlayLoading');
                $overlayContent.children().hide();
                if (config.isIE7 || config.isIE6) {
                    $('#contactOverlayRight').css({ visibility: "visible" });
                }
                $overlayInitialWrap.show();
                $overlayHeader.children('div').not($overlayInitialHeaderContent).remove();
                $overlayBox.removeClass().addClass('clearfix');
                $overlayInitialHeaderContent.show();

            }

            if (newHomesRequest) {

                $('#rPropName').html(originalPropertyName);
                $overlayContent.find('.propertyID').val('');
                newHomesRequest = false;
            }

            if (!Contact.formIsReset) {
                Contact.resetContactForm();
            }



        }


        Contact = function() {

            var $leftCol,
			$generalEnquiry,
			$requestAppointment,
			$requestBox,
			$generalBox,
			$viaTelephone,
			$viaEmail,
			$viaControls,
			$whenCallWrap,
			$contactDetailLabel,
			$contactDetail;

            var formSubmittingMessage = "Form is being submitted; please wait...",
			formIsReset = true;

            function init() {
                $generalEnquiry = $('#generalEnquiry');
                $requestAppointment = $('#requestAppointment');
                $typeControls = $('#generalEnquiry, #requestAppointment');
                $requestBox = $('#requestBox');
                $generalBox = $('#generalBox');
                $viaTelephone = $('#viaTelephone');
                $viaEmail = $('#viaEmail');
                $viaControls = $('#viaEmail, #viaTelephone');
                $whenCallWrap = $('#whenCallWrap');
                $contactDetailLabel = $('#contactDetailLabel');
                $leftCol = $('#contactOverlayLeft');
                $contactDetail = $('#contactDetail');

                $formSubmitting = $('<span>').attr('class', 'formSubmitting').html(formSubmittingMessage).hide();
                $overlayBox.prepend($formSubmitting);

                bindEvents();
            }

            function showCorrectForm(t, el) {
                $generalBox.show();
                $requestBox.show();

                if (t == "request") {
                    if (el.attr('data-property-id')) {
                        newHomesRequest = true;
                        originalPropertyName = $('#rPropName').html();
                        $('#rPropName').html(el.attr('data-unit-title'));
                        $overlayContent.find('.propertyID').val(el.attr('data-property-id'));
                    }
                    $generalBox.hide();
                    $requestAppointment.prop('checked', true);
                } else {
                    $requestBox.hide();
                    $generalEnquiry.prop('checked', true);
                }
            }

            function alterGeneralForm(telephoneIsOn) {
                if (telephoneIsOn) {
                    $whenCallWrap.slideDown('fast');
                    $contactDetailLabel.children('span:first').html('Contact Number');
                    $contactDetail.removeClass('valEmail');


                } else {
                    $whenCallWrap.slideUp('fast');
                    $contactDetailLabel.children('span:first').html('Email Address');
                    $contactDetail.addClass('valEmail');
                }
            }

            function bindEvents() {

                $typeControls.change(function() {
                    if ($generalEnquiry.prop('checked') == true) {
                        $requestBox.fadeOut('fast', function() {
                            $generalBox.fadeIn('fast');
                        });
                    } else {
                        $generalBox.fadeOut('fast', function() {
                            $requestBox.fadeIn('fast');
                        });
                    }
                });

                $viaControls.change(function() {
                    if ($viaTelephone.prop('checked') == true) {
                        alterGeneralForm(true);
                    } else {
                        alterGeneralForm(false);
                    }
                });

                $generalBox.children('form').submit(function() {
                    submitForm($(this), config.ajaxURL.submitContactForm, { top: "380px", left: "136px" });
                    return false;
                });

                $requestBox.children('form').submit(function() {
                    submitForm($(this), config.ajaxURL.submitContactForm, { top: "380px", left: "136px" });
                    return false;
                });

            }

            function submitForm(theForm, submitURL, msgPosition) {
                stopEvents = true;
                formIsReset = false;

                $leftCol.css("height", $leftCol.height());

                theForm.parent().fadeOut('fast', function() {
                    $formSubmitting.css(msgPosition).fadeIn('fast');
                });

                var formData = theForm.serialize();

                $.ajax({
                    url: submitURL,
                    data: formData,
                    dataType: "json",
                    success: function(formResponse) {
                        successfulSubmission(formResponse);
                    },
                    failure: function() {
                        alert('ajax request failed');
                        stopEvents = false;
                    }
                });

                function successfulSubmission(formResponse) {
                    $formSubmitting.fadeOut(100, function() {
                        $(this).addClass("noBg").html(formResponse[1]).fadeIn(100);
                        stopEvents = false;
                    });

                    if (formResponse[0] == true) {
                        setTimeout(function() {
                            resetContactForm();
                        }, 2400);
                    }

                }
            }

            function resetContactForm() {
                $overlay.fadeOut('fast', function() {
                    $formSubmitting.removeClass('noBg').html(formSubmittingMessage).hide();
                    restoreInitialContents();
                    $leftCol.css("height", "auto");
                    formIsReset = true;
                });
            }


            return {
                init: init,
                showCorrectForm: showCorrectForm,
                submitForm: submitForm,
                formIsReset: formIsReset,
                resetContactForm: resetContactForm
            }

        } ();

        Floorplans = function() {

            var firstLoad = true,
			contentLoaded = false;

            var $floorplanWrap,
			$floorplanTitle;

            function init(propertyTitle, floorplanLocation) {
                $overlayContent.addClass('overlayLoading');


                $.ajax({
                    url: floorplanLocation,
                    success: function(r) {
                        if (floorplanActive) {
                            $floorplanTitle = $('<div>').attr('id', 'floorplanTitle').html('<span>' + propertyTitle + '</span> Floorplans');
                            $overlayHeader.prepend($floorplanTitle);
                            $overlayContent.append(r);
                            $('.cloud-zoom').CloudZoom();
                            $floorplanWrap = $('#floorplanWrap');
                            contentLoaded = true;
                            $overlayContent.removeClass('overlayLoading');
                            firstLoad = false;
                        }
                    }
                });
            }

            function showFloorPlan(propertyTitle, floorplanLocation) {
                floorplanActive = true;
                hideInitialContents();
                $overlayHeader.prepend($floorplanTitle);


                if (firstLoad) {
                    init(propertyTitle, floorplanLocation);
                } else {
                    if (contentLoaded) {
                        $('.cloud-zoom').CloudZoom();
                        $floorplanWrap.show()
                    }
                }
            }

            return {
                init: init,
                showFloorPlan: showFloorPlan
            }

        } ();

        FloorplansMulti = function() {
            var requestCounter = 0,
			contentLoaded = false;

            var $floorplanWrap,
			$floorplanTitle;

            function init(propertyTitle, floorplanLocation) {
                $overlayContent.addClass('overlayLoading');
                //$overlayHeader.prepend();

                $.ajax({
                    url: floorplanLocation + '&aX=' + requestCounter,
                    success: function(r) {
                        $r = $(r);
                        if ($r.attr('data-requestCounter') == requestCounter && floorplanActive) {
                            $floorplanTitle = $('<div>').attr('id', 'floorplanTitle').html('<span>' + propertyTitle + '</span> Floorplans');
                            $overlayHeader.prepend($floorplanTitle);
                            $overlayContent.append(r);
                            $('.cloud-zoom').CloudZoom();
                            $floorplanWrap = $('#floorplanWrap');
                            contentLoaded = true;
                            $overlayContent.removeClass('overlayLoading');
                        }
                    }
                });
            }

            function showFloorPlan(propertyTitle, floorplanLocation) {
                floorplanActive = true;
                requestCounter++
                hideInitialContents();
                $overlayHeader.prepend($floorplanTitle);
                init(propertyTitle, floorplanLocation);


            }

            return {
                init: init,
                showFloorPlan: showFloorPlan
            }

        } ();

        EmailFriend = function() {

            var firstLoad = true,
			emailSubmittingMessage = "Thank you - email successfully delivered.<br /><br /><span>(This window will close automaticaly)</span>",
			contentLoaded = false;


            var $emailFriendWrap,
			$emailFriendTitle;

            function init(propertyTitle) {
                $overlayContent.addClass('overlayLoading');
                $emailFriendTitle = $('<div>').html('Send details of <strong>' + propertyTitle + '</strong>');
                $overlayHeader.prepend($emailFriendTitle);

                $.ajax({
                    url: config.ajaxURL.emailFriend,
                    success: function(r) {

                        $overlayContent.append(r);
                        $emailFriendWrap = $('#emailFriendWrap');

                        $('#eFMessage').height($('#heightMeasure').height() - 15);
                        contentLoaded = true;
                        $overlayContent.removeClass('overlayLoading');
                        $('#emailFriendForm').simpleValidate({
                            submitButtonID: "#eFSendEmail"
                        }).submit(function() {
                            $emailFriendWrap.height($emailFriendWrap.height());
                            $formSubmitting.addClass('formSubmittingEmail');
                            Contact.submitForm($(this), config.ajaxURL.submitEmailFriendForm, { top: "50%", left: "180px" });
                            return false;
                        });
                    }
                });
            }

            function showEmailForm(propertyTitle) {
                hideInitialContents();
                $overlayHeader.prepend($emailFriendTitle);
                $overlayBox.addClass('emailFriendBox');


                if (firstLoad) {
                    init(propertyTitle);
                    firstLoad = false;
                } else {
                    if (contentLoaded) {
                        $emailFriendWrap.children('div').show().end().show()
                    }
                }
            }




            return {
                init: init,
                showEmailForm: showEmailForm
            }

        } ();

        return {
            init: init,
            Contact: Contact,
            Floorplans: Floorplans
        }

    } ();

    ExpandingLists = function() {
        var $lists;
        var listCounter = 0;

        function init() {
            $lists = $('.expandingList');

            $lists.each(function() {
                var initialShow = $(this).attr('data-initial-visible');
                var theItems = $(this).children('li');
                var noOfItems = theItems.length;

                if (noOfItems >= initialShow) {
                    var linkText = $(this).attr('data-link-text');
                    var hideItems = theItems.slice(initialShow, noOfItems + 1);
                    var tag = "expander" + listCounter;
                    hideItems.wrapAll('<ul id="' + tag + '">');
                    $(this).append('<a href="#" class="expandLink" data-target="' + tag + '">' + linkText + '</a>');
					listCounter++;	
                }
            });

            $lists.children('ul').hide();
            bindEvents();
        }

        function bindEvents() {
            $('.expandLink').click(function() {
                var $targetList = $('#' + $(this).attr('data-target'));

                $('#' + $(this).attr('data-target')).slideDown('fast');
                $(this).remove();
                return false;
            });

        }

        return {
            init: init
        }
    } ();

    function goToForm() {
        $('.openForm').click(function(e) {
            $('html, body').animate({
                scrollTop: 0
            },
			1100,
			"easeOutCubic"

			);
            setTimeout(function() {
                searchSlideOpen();
            }, 800);
            setTimeout(function() {
                $('#searchColOne').children('label').effect("highlight", { color: "#002c63" }, 800);
            }, 1100);
            e.preventDefault();
            return false;
        });
    }

    function enhanceInput(theInput) {
        if (!theInput.is('textarea')) {
            var orig = theInput.attr('value');
            theInput.focus(function() {
                if ($(this).val() == orig) {
                    $(this).val('');
                }
            }).blur(function() {
                if ($(this).val() == "") {
                    $(this).val(orig);
                }
            });
        } else {
            var orig = theInput.html();
            theInput.focus(function() {
                if ($(this).html() == orig) {
                    $(this).html('');
                }
            }).blur(function() {
                if ($(this).html() == "") {
                    $(this).html(orig);
                }
            });
        }

    }

    function enhancePropertyLinks() {
        $('#featuredProperties .featuredPic').hover(function() {

            $(this).next('h3').addClass('removeUnderline');

        }, function() {
            $(this).next('h3').removeClass('removeUnderline');

        });
    }
	
	function scrollToTop() {
		$('html, body').animate({ 
		   scrollTop: 0}, 
		   1400, 
		   "easeOutQuint"
		);
	}

	function newsletterWidget() {
		var $newsSlideOne,
		$newsSlideTwo,
		$newsSlideThree;
		
		var fadeSpeed = 200,
		errorBoxCreated = false;
		
		
		function init() {
			$newsSlideOne = $('.newsSlideOne');
			$newsSlideTwo = $('.newsSlideTwo');
			$newsSlideThree = $('#newsSlideThree');
			
			$newsSlideTwo.hide();
			$newsSlideThree.hide();
			$('#newsContentWrap').css({height: $('#newsContentWrap').height() + "px"});
			
			bindEvents();
		}
		
		function bindEvents() {
			$('#newsSignUp').click(function() {
				if(validateForm()) {
					$('#newsErrors').fadeOut(fadeSpeed);
					$newsSlideOne.fadeOut(fadeSpeed, function() {
						$newsSlideTwo.fadeIn(fadeSpeed);
					});
				}

				return false;
			});
			
			$('#newsForm').submit(function() {
				
				submitForm($(this));
				
				return false;
			});
		}
		
		function submitForm(theForm) {
			var formData = theForm.serialize();
			$newsSlideTwo.fadeOut(fadeSpeed, function() {
				$newsSlideThree.fadeIn(fadeSpeed);
			});
			
			$.post(config.ajaxURL.mailChimpURL, formData,  function(response) {
				$newsSlideThree.children('p').fadeOut(fadeSpeed, function() {
					$(this).html(response);
					$(this).fadeIn(fadeSpeed);
				});
				
			});
			
		}
		
		function validateForm() {
			var valid = true,
			listItems = "",
			$errors;

			var newsNameVal = $('#newsName').val();
			if(newsNameVal == "" || newsNameVal == "Your Name") {
				valid = false;
				listItems += "<li>Please fill in your name</li>";
			}
			
			var newsEmailVal = $('#newsEmail').val();
			if(newsEmailVal == "" || newsEmailVal == "Your Email Address") {
				valid = false;
				listItems += "<li>Please fill in your email address</li>";
			}
			
			if(!valid) {
				if(!errorBoxCreated) {
					$errors = $('<ul>').attr({id: "newsErrors"}).hide().html(listItems);
					$('#newsletterSignUp').append($errors);
					$errors.slideDown(fadeSpeed);
					errorBoxCreated = true;
				} else {
					$('#newsErrors').html(listItems);
				}
			}
			

			
			return valid;
		}

		
		init();
	}

    return {
        init: init,
        singleSlide: singleSlide,
        supports_history_api: supports_history_api,
        submitSearchForm: submitSearchForm,
        Overlay: Overlay,
        ExpandingLists: ExpandingLists,
        goToForm: goToForm,
        enhanceInput: enhanceInput,
        twitterShare: twitterShare,
        facebookShare: facebookShare,
        enhancePropertyLinks: enhancePropertyLinks,
        configureSiteSwitch: configureSiteSwitch,
        OtherAreas: OtherAreas,
		scrollToTop : scrollToTop,
		newsletterWidget : newsletterWidget
    }

} ();

PropertyPage = function() {
    var self = this;

    function init() {
        $('#generalForm').simpleValidate({
            submitButtonID: "#submitEnquiry"
        });

        $('#requestForm').simpleValidate({
            submitButtonID: "#requestAppointmentSubmit"
        });

        //Gallery.init();
    }

    NewHomes = function() {

        var $newViewAll,
		$newHomesTable;

        function init() {
            $newViewAll = $('#newViewAll');
            $newHomesTable = $('#newHomesTable');
            $newHomesTable.children('table').children().children('tr').not('.newHomeOriginial').hide();
            bindEvents();
        }

        function bindEvents() {
            $newViewAll.toggle(function() {
                $(this).children().children().html('Hide extra Properties').addClass('upArrow');
                $newHomesTable.children('table').children().children('tr').not('.newHomeOriginial').show('fast');
                return false;
            }, function() {
                $(this).children().children().html('View all Properties').removeClass('upArrow');
                $newHomesTable.children('table').children().children('tr').not('.newHomeOriginial').hide('fast');
                return false;

            });
        }

        return {
            init: init
        }

    } ();


    /*
    Gallery = function() {
		
		var $slideFader,
    $slideshow,
    $slideMain,
    $slideThumbs;
		
		var $loadedImages = {};
		
		function init() {
    $slideshow = $('#slideShow');
    $slideMain = $('#slideMain');
    $slideThumbs = $('#slideThumbs');
    $slideFader = $('<div>').attr('id', 'slideFader').hide();
    $slideMain.prepend($slideFader);
    $loadedImages['0'] = $('<img>').attr({src: $slideThumbs.children(':first').children('img').attr('data-main-image-url')});
    bindEvents();
    }
		
		function changeSlide(el) {
    var imgSrc = el.children('img').attr('data-main-image-url');
    var thumbIndex = el.index();
			
    if($loadedImages[thumbIndex]) {
    console.log('preloaded');
    $slideMain.html($loadedImages[thumbIndex]);
    } else {
    console.log('new slide');
    $slideFader.fadeTo(100, 0.8);
    $loadedImages[thumbIndex] = $('<img>').attr({src: imgSrc}).load(function() {
    $slideMain.html($(this));
    $slideFader.fadeTo(100, 0).hide();
    });
    }			
    }
		
		function bindEvents() {
			
    $slideThumbs.children('li').each(function() {
    if($(this).children().size() > 0) {
    $(this).addClass('activeThumb');
    }
    });
			
    $slideThumbs.children('li.activeThumb').click(function() {
    changeSlide($(this));				
    });
    }
		
		return {
    init: init
    }
		
		
    }();
	
	*/

    return {
        init: init,
        NewHomes: NewHomes
    }

} ();

/*
TODO potential bug when aX is set on the init() function - if there is no aX?
*/
/*
TODO IE7: onstatechange fires on first load of url? this occasionally messes up the first form request from the homepage. FIX.
*/

SearchResults = function() {
    var $filterForm,
    $resultsWrap,
    $resultsNav,
    $resultsNavForm,
    $paginateTop,
    $paginateBottom,
    $relatedSearches,
    $faderBottom,
    $toggleLinks,
    $mapWrap,
    $map,
    $mapLegend,
	$newHomesFilter,
	$soldFilter,
	$right;

    var firstLoad = true,
    currentPage,
    disableAjaxClicks = true,
    // gives an ID to the response so I cant test for which one is the most recent 
    aX = 0,
    noQueryString = false,
    reformTitle = false,
    results = [],
    cState = "listView",
    map = null,
    mapMarkers = [],
    infoWindows = [],
    invalidMap = true, // A way of telling the map it needs to update itself
    pageWidth, // Stores the width of the #left div for the sliding animation between states
	pageHeight = 0,
    errors = false;

    // filter numbers
    var houseNo,
    flatNo,
    newNo,
    soldNo;

    function init() {
        // bind to elements
        $filterForm = $('#filterForm');
        $resultsWrap = $('#resultsWrap');
        $resultsNav = $('#searchResultsNav');
        $resultsNavForm = $('#resultsNavForm');
        $paginateTop = $('#paginateTop');
        $paginateBottom = $('#paginateBottom');
        $relatedSearches = $('#relatedSearches');
        $newHomesFilter = $('#newHomesFilter');
        $soldFilter = $('#soldPropertiesFilter');
        $right = $('#right');

        $faderHover = $('#faderHover'); // NOTE: Is this supposed to be declared globally? No definition for it above...
        $mapLegend = $('#mapLegend').hide();

        pageWidth = $('#left').width();

        var qs = retrieveQueryString();

        if (config.isIE7 || config.isIE8) {
            $filterForm.addClass('arialText');
        }

        // Setup toggle links to change between view states
        $toggleLinks = $('#resultsToggle a').click(function() {

            if (errors) return false;

            $toggleLinks.removeClass('on');
            changeState($(this).addClass('on').parent().attr('id'));
            return false;

        });

        if (noQueryString) {
            // show 'no query string message'
            $.ajax({
                url: config.ajaxURL.mainResults,
                dataType: "json",
                success: function(jsonResults) {
                    $filterForm.css({ opacity: 0.2 });
                    $resultsNav.children('h1').html(jsonResults.pageTitle);
                    $resultsWrap.css({ opacity: 0 }).html(constructError(jsonResults)).fadeTo(200, 1);
                    $faderHover.fadeTo(300, 0, function() {
                        $faderHover.hide();
                    });
                }
            });

        } else {

            // tests to see if a non html4 url (without a hash) has been used. If so, redirect to the hashed version.
            if (!config.historySupported) {
                var str = /#/;
                var url = window.location.href;
                if (!str.test(url)) {
                    window.location.href = config.html4ResultsURL + qs;
                }
            }

            //set the aX value to the one given in the query string so it passes the replaceResults test
            var qsPairs = parseQueryString(qs);
            aX = qsPairs['aX'];
			
            replaceResults(qs, true);
            configureFilterOptions(qs);
            $resultsNav.children('div').hide();
            $paginateBottom.hide();
            //	$filterForm.css({opacity: 0.2});			
            firstLoad = false;

            // configure search form based on querystring for html4 browsers
            if (!config.historySupported) {
                configureSearchForm(qsPairs);
            }
        }

        // history.js stuff...
        var History = window.History;

        History.Adapter.bind(window, 'statechange', function() {
            var State = History.getState();

            var nvP = parseQueryString(retrieveQueryString());

            // handles the aX value for when back and forward buttons are clicked...
            var historyaX = nvP['aX'];
            if (historyaX == (aX - 1)) { // if back button is clicked
                aX = aX - 1;
            } else if (historyaX == aX + 1) { // if forward button is clicked
                aX = aX + 1;
            }

			// statechange fires on the search form submit for HTML4 browsers, so there will be no state data passed. This tests if it exists: if not, use the query string
			if(State.data.theQ == null) {
				replaceResults(retrieveQueryString(), false);
			} else {
				replaceResults(State.data.theQ, false);
	            
			}

        });

        // bind handlers
        filterResults();
        orderResults();
    }

    function filterResults() {
        $filterForm.find(':checkbox').click(function(e) {

            if (disableAjaxClicks) {
                e.preventDefault();
            } else {
                makeHistory(true);
            }

        });
    }

    function orderResults() {
        $resultsNavForm.children().change(function() {
            makeHistory();
        });

    }

    function pageinate() {
        // top Pagination
        $paginateTop.children('li').children('a').click(function() {
            travelToPage($(this));
            return false;
        });

        // bottom pagination
        $paginateBottom.children('li').children('a').click(function() {
            travelToPage($(this));
			Global.scrollToTop();
            return false;
        });

        function travelToPage(el) {
            currentPage = el.attr('data-targetPage');
            makeHistory();
        }

    }

    function makeHistory(isFilterForm) {
        var qString = createQueryString(isFilterForm);
        History.pushState({ "theQ": qString }, "Currell Property Search Results", "?" + qString);
    }

    function replaceResults(theData, firstResults) {

        errors = false;

        $faderHover.fadeTo(200, 0.9);

        var theX = $.ajax({
            url: config.ajaxURL.mainResults,
            data: theData,
            dataType: "json"
        });

        theX.success(function(jsonResults) {

            if (jsonResults.errorBox) {

                $resultsNav.children('h1').html(jsonResults.pageTitle).removeClass('jResultsTitle');
                $resultsWrap.css({ opacity: 0 }).html(constructError(jsonResults)).fadeTo(200, 1);
                $faderHover.fadeTo(300, 0, function() {
                    $faderHover.hide();
                });

                $('#listView a').click();
                errors = true;

            } else if (jsonResults.returnedResults) {
				
                // if its the latest query (deals with rapid ajax requests)
                if (jsonResults.aX == aX) {
                    results = jsonResults.allResults;
                    invalidMap = true;

                    pageHeight = jsonResults.noOfResults.totalNo * 230;
                    if (cState == "listView") {
                        $faderHover.height(pageHeight);
                    } else {
                        $faderHover.height($mapWrap.height() + 20);
                        positionMap();
                    }

                    $resultsWrap.html(constructResults(jsonResults));
                    $faderHover.fadeTo(300, 0, function() {

                        $faderHover.hide();
                        if (firstResults) {

                            loadTitle(jsonResults.noOfResults.total);
                            loadPagination(jsonResults);
                            // no longer using related searches for now.
                            //loadRelatedSearches(jsonResults);
                            disableAjaxClicks = false;
                            // if error box preceded this request, reload the title fresh.	
                        } else if (!$resultsNav.children('h1').hasClass('jResultsTitle')) {
                            loadTitle(jsonResults.noOfResults.total);
                            refreshPagination(jsonResults);
                        } else {
                            replaceTitle(jsonResults.noOfResults.total);
                            refreshPagination(jsonResults);
                        }
                        refreshPropertyTypeNumbers(jsonResults);


                        $filterForm.fadeTo(200, 0.99);
                        if (!firstLoad) {
                            $resultsNav.children('div').fadeTo(200, 1);
                        }
                    });
                }
				
            } else {
				
                $resultsWrap.html('<div id="noResults" class="clearfix"><p>Sorry, there has been a processing error. Please contact Currell for advice on our portfolio and we\'ll be happy to help.</p></div>').fadeTo(200, 1);

                $('#listView a').click();
                errors = true;
            }
        });
    }

    function loadRelatedSearches(jsonResults) {
        var resultsHTML = [];
        var j = 0;

        for (var i = 0; i < jsonResults.relatedSearches.length; i++) {
            resultsHTML[j++] = '<li';
            resultsHTML[j++] = '><a href="';
            resultsHTML[j++] = jsonResults.relatedSearches[i].url;
            resultsHTML[j++] = '">';
            resultsHTML[j++] = jsonResults.relatedSearches[i].placeName;
            resultsHTML[j++] = '</a></li>';
        };
        $relatedSearches.children('ul').html(resultsHTML.join(''));
    }

    function loadTitle(resultsNumber) {
        $resultsNav.children('h1').html('<strong>' + resultsNumber + '</strong> found matching your search criteria').addClass('jResultsTitle');
    }

    function replaceTitle(resultsNumber) {
        $('#searchResultsNav').children('h1').children('strong:first').html(resultsNumber).effect("highlight", { color: "#002c63" }, 800);
    }

    function constructResults(jsonResults) {
        var resultsHTML = [];
        var j = 0;
        var jsonLength = jsonResults.results.length;
        for (var i = 0; i < jsonLength; i++) {
            var priceClass = "";
            if (jsonResults.results[i].newHome) {
                priceClass = ' class="newHomePrice"';
            }

            if (i == jsonLength - 1) {
                resultsHTML[j++] = '<div class="result lastResult clearfix"><a href="';
            } else {
                resultsHTML[j++] = '<div class="result clearfix"><a href="';
            }
            resultsHTML[j++] = jsonResults.results[i].url;
            resultsHTML[j++] = '" class="resultLeft"><img src="';
            resultsHTML[j++] = jsonResults.results[i].image.imageSrc;
            resultsHTML[j++] = '"  border="0" alt="';
            resultsHTML[j++] = jsonResults.results[i].image.imageAlt;
            resultsHTML[j++] = '"/>';
            resultsHTML[j++] = jsonResults.results[i].image.banner;
            resultsHTML[j++] = '</a>';
            resultsHTML[j++] = '<div class="resultRight"><div' + priceClass + '><h3><a href="';
            resultsHTML[j++] = jsonResults.results[i].url;
            resultsHTML[j++] = '">';
            resultsHTML[j++] = jsonResults.results[i].propertyName;
            resultsHTML[j++] = '</a></h3><span>';
            resultsHTML[j++] = jsonResults.results[i].price;
            resultsHTML[j++] = '</span></div><p>';
            resultsHTML[j++] = jsonResults.results[i].propertyDescription;
            resultsHTML[j++] = '</p><a href="';
            resultsHTML[j++] = jsonResults.results[i].url;
            resultsHTML[j++] = '" class="button">View Full Details</a><ul>';

            for (var k = 0; k < jsonResults.results[i].propertyAttributes.length; k++) {
                resultsHTML[j++] = '<li class="';
                resultsHTML[j++] = jsonResults.results[i].propertyAttributes[k].theClass;
                resultsHTML[j++] = '">';
                resultsHTML[j++] = jsonResults.results[i].propertyAttributes[k].theLabel;
                resultsHTML[j++] = '</li>';
            };

            resultsHTML[j++] = '</ul></div></div>';
        };
        return resultsHTML.join('');
    }

    /************************* pagination & filter options *********************/

    function loadPagination(jsonResults) {
        var paginationItems = constructPaginationItems(jsonResults);
        currentPage = jsonResults.pagination.currentPage;
        // top pagination
        $paginateTop.html(paginationItems);
        $resultsNav.children('div').fadeIn(200);

        //bottom pagination
        $paginateBottom.hide().html(paginationItems).fadeIn(200);

        // bind handlers to new paginate items
        pageinate();
    }

    function refreshPagination(jsonResults) {
        var paginationItems = constructPaginationItems(jsonResults);
        currentPage = jsonResults.pagination.currentPage;
        var topDone = false;
        var bottomDone = false;

        // top pagination
        $resultsNav.children('div').fadeOut(200, function() {
            $paginateTop.html(paginationItems);
            $resultsNav.children('div').fadeIn(200);
            topDone = true;
        });

        //bottom pagination
        $paginateBottom.fadeOut(200, function() {
            $(this).html(paginationItems).fadeIn(200);
            bottomDone = true;
        });

        // binds handlers to pagination items once succesfully inserted.
        function bindPagination() {
            setTimeout(function() {
                if (topDone && bottomDone) {
                    // bind handlers to new paginate items
                    pageinate();
                } else {
                    bindPagination();
                }
            }, 50);
        }
        bindPagination();
    }

    function constructPaginationItems(jsonResults) {
        var resultsHTML = [];
        var j = 0;

        for (var i = 0; i < jsonResults.pagination.pages.length; i++) {

            if (jsonResults.pagination.pages[i].theClass == "noLink") {
                resultsHTML[j++] = '<li class="noLink">';
                resultsHTML[j++] = jsonResults.pagination.pages[i].number;
                resultsHTML[j++] = '</li>';
            } else {
                resultsHTML[j++] = '<li';
                if (jsonResults.pagination.pages[i].theClass == "on") {
                    resultsHTML[j++] = ' class="on"';
                }
                resultsHTML[j++] = '><a href="';
                resultsHTML[j++] = jsonResults.pagination.pages[i].url;
                resultsHTML[j++] = '" data-targetPage="';
                resultsHTML[j++] = jsonResults.pagination.pages[i].number;
                resultsHTML[j++] = '">';
                resultsHTML[j++] = jsonResults.pagination.pages[i].number;
                resultsHTML[j++] = '</a></li>';
            }

        };
        return resultsHTML.join('');

    }

    function retrieveQueryString() {
        var str;

        if (config.isIE6) {
            // if there is a query string...
            if (window.location.href.match(/\?(.*)/) != null) {
                str = window.location.href.match(/\?(.*)/)[1];

            } else if (window.location.href.match(/%3F(.*)/) != null) {
                str = window.location.href.match(/%3F(.*)/)[1];
                str = unescape(str);
            } else {
                str = "";
                noQueryString = true;
            }
        } else {
            // if there is a query string...
            if (window.location.href.match(/\?(.*)/) != null) {
                str = window.location.href.match(/\?(.*)/)[1];

            } else {
                str = "";
                noQueryString = true;
            }
        }

        return str;
    }

    function createQueryString(isFilterForm) {
        aX++;
        var cCurrentPage = 1;
        if (!isFilterForm) {
            cCurrentPage = currentPage;
        }

        var mainFormData = $SearchBar.search.children('form').serialize();
        var filterFormData = $filterForm.serialize();
        var resultsNavFormData = $resultsNavForm.serialize();
        var formData = mainFormData + "&" + filterFormData + "&" + resultsNavFormData + "&cP=" + cCurrentPage + "&aX=" + aX;
        return formData;
    }

    function configureFilterOptions(qs) {
        var q = parseQueryString(qs);

        // if it's not a buy search, hide the new homes and sold inputs plus the map icons
        if (q['sFP'] != "b") {
            $newHomesFilter.hide();
            $soldFilter.hide();
            $('#soldMapIcon,#newHomesMapIcon').hide();
        }

        configureFilterBox(q);
        configureResultsDropdowns(q);

        function configureFilterBox() {
            if (q[config.filters.houses]) {
                tickBox(config.filters.houses);
            }
            if (q[config.filters.flats]) {
                tickBox(config.filters.flats);
            }
            if (q[config.filters.newHomes]) {
                tickBox(config.filters.newHomes);
            }
            if (q[config.filters.soldProperties]) {
                tickBox(config.filters.soldProperties);
            }
            if (q[config.filters.underOffer]) {
                tickBox(config.filters.underOffer);
            }

            function tickBox(inputName) {
                $filterForm.children().children('input[name="' + inputName + '"]').prop("checked", true);
            }
        }

        function configureResultsDropdowns() {
            selectBox(config.orderBy.resultsPerPage);
            selectBox(config.orderBy.resultsOrder);

            function selectBox(inputName) {
                $resultsNavForm.children('select[name="' + inputName + '"]').val(q[inputName]);
            }
        }
    }

    function configureSearchForm(qs) {
        $mainForm = $SearchBar.search.children('form');
        // selects		
        selectBox("sFP");
        PriceRangeSwap.configureSelects();

        selectBox("sB");
        selectBox("sMnP");
        selectBox("sMxP");
        function selectBox(inputName) {
            $mainForm.find('select[name="' + inputName + '"]').val(qs[inputName]);
        }

        //areas
        $('#searchColTwo').find('input').each(function() {
            $(this).prop('checked', false);
            if (qs[$(this).attr('name')] != null) {
                $(this).prop('checked', true);
            }
        });

        if ($('#sOT').prop('checked') == true) {
            Global.OtherAreas.enable();
        }
    }

    function refreshPropertyTypeNumbers(jsonResults) {
        if (houseNo != jsonResults.noOfResults.houses) {
            houseNo = jsonResults.noOfResults.houses;
            flashReplace("filterHouses", houseNo);
        }
        if (flatNo != jsonResults.noOfResults.flats) {
            flatNo = jsonResults.noOfResults.flats;
            flashReplace("filterFlats", flatNo);
        }
        if (newNo != jsonResults.noOfResults.newHomes) {
            newNo = jsonResults.noOfResults.newHomes;
            flashReplace("filterNewHomes", newNo);
        }
        if (soldNo != jsonResults.noOfResults.sold) {
            soldNo = jsonResults.noOfResults.sold;
            flashReplace("filterSoldProperties", soldNo);
        }

        function flashReplace(forName, n) {
            $filterForm.children().children('label[for="' + forName + '"]').children('span').html(n).effect("highlight", { color: "#002c63" }, 800);
        }
    }

    function parseQueryString(qs) {
        var nvPairs = {};
        var pairs = qs.split('&');
        $.each(pairs, function(i, v) {
            var pair = v.split('=');
            nvPairs[pair[0]] = pair[1];
        });
        return nvPairs;
    }

    function constructError(jsonResults) {
        var errorHTML = [];
        var j = 0;

        errorHTML[j++] = '<div id="noResults" class="clearfix"><p>';
        errorHTML[j++] = jsonResults.message;
        errorHTML[j++] = '</strong></p>';

        if (jsonResults.relatedAreas) {
            var le = jsonResults.relatedAreas.length;

            errorHTML[j++] = '<ul>';
            for (var i = 0; i < le; i++) {

                errorHTML[j++] = '<li><a href="';
                errorHTML[j++] = jsonResults.relatedAreas[i].url;
                errorHTML[j++] = '">';
                errorHTML[j++] = jsonResults.relatedAreas[i].locationName;
                errorHTML[j++] = '</a></li>';
            };
            errorHTML[j++] = '</ul>';
        }

        errorHTML[j++] = '</div>';

        return errorHTML.join('');
    }



    function changeState(newState) {

        if (newState == cState) return;

        cState = newState;
        var transDuration = 500;
        var wrapHeight = Math.max($right.height() + 30, 550);

        switch (newState) {
            case "listView":

                $resultsWrap.show();
                $resultsNavForm.show();
                $paginateTop.show();
                $paginateBottom.show();

                $mapLegend.hide();

                $mapWrap.css({ left: 0 }).show().animate({ left: pageWidth }, { queue: false, duration: transDuration, easing: 'easeInOutCubic' });
                $resultsWrap.css({ left: -pageWidth }).show().animate({ left: 0, height: pageHeight }, { queue: false, duration: transDuration, easing: 'easeInOutCubic' });

                break;
            case "mapView":

                $resultsWrap.hide();
                $resultsNavForm.hide();
                $paginateTop.hide();
                $paginateBottom.hide();

                $mapLegend.show();

                initMap();
                positionMap();

                $mapWrap.css({ left: pageWidth }).show().animate({ left: 0 }, { queue: false, duration: transDuration, easing: 'easeInOutCubic' });
                $resultsWrap.css({ left: 0 }).show().animate({ left: -pageWidth, height: wrapHeight }, { queue: false, duration: transDuration, easing: 'easeInOutCubic' });


                break;
            default:
                return;
                break;
        }

    }

    //////////// Map specific stuff ////////////

    function initMap() {

        if (map != null) return;

        $mapWrap = $('<div id="mapWrap"></div>').appendTo($('#left')).hide();
        $map = $('<div id="map"></div>').appendTo($mapWrap);

        var startLatlng = new google.maps.LatLng(51.535018, -0.103683);
        var mapOptions = {
            scrollwheel: false,
            mapTypeControl: false,
            zoom: 7,
            center: startLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        map = new google.maps.Map($map[0], mapOptions);
        $mapLoader = $('<div id="mapLoader"></div>').appendTo($mapWrap);

    }

    function clearMap() {

        // Clear markers
        var item;
        while (mapMarkers.length > 0) {
            item = mapMarkers.pop();
            if (typeof (item) != 'undefined') {
                item.setMap(null);
            }
        }

        // Clear info windows
        while (infoWindows.length > 0) {
            item = infoWindows.pop();
            item.close();
        }

        $mapLoader.stop(true, false).show();

    }

    function positionMap() {

        // Moves the map into the right position for the set of property markers

        if (!invalidMap || map == null) return;

        clearMap();

        var bounds = new google.maps.LatLngBounds();
        var resultsLength = results.length;

        for (var i = 0; i < resultsLength; i++) {

            var cResult = results[i];
            if (typeof (cResult.latLng) == 'undefined') continue;

            var cCoords = cResult.latLng.replace(/ /g, '').split(',');
            var cLatlng = new google.maps.LatLng(parseFloat(cCoords[0]), parseFloat(cCoords[1]));
            bounds.extend(cLatlng);

        }

        map.fitBounds(bounds);

        invalidMap = false;

        $mapLoader.delay(500).fadeOut(300, insertMapMarkers);

    }

    function insertMapMarkers() {

        // Called after the map's visible tiles have finished loading. makes the whole thing look a lot smoother this way

        if (cState != "mapView") return;

        var resultsLength = results.length;

        for (var i = 0; i < resultsLength; i++) {

            var cResult = results[i];
            if (typeof (cResult.latLng) == 'undefined') continue;

            var cCoords = cResult.latLng.replace(/ /g, '').split(',');
            var cLatlng = new google.maps.LatLng(parseFloat(cCoords[0]), parseFloat(cCoords[1]));

            var cMarkerOptions = {
                'position': cLatlng,
                'map': map,
                'visible': true,
                'title': cResult.propertyName,
                'icon': getMapIcon(results[i].type),
                'animation': google.maps.Animation.DROP,
                'clickable': true
            };

            cMarker = new google.maps.Marker(cMarkerOptions);
            createInfoWindow(cMarker, cResult);
            mapMarkers[i] = cMarker;

        }

    }

    function createInfoWindow(marker, result) {

        // Put all the info from the result together and inject it into a new InfoWindow
        var atts = [];
        var attsLength = result.propertyAttributes.length;
        for (var j = 0; j < attsLength; j++) {
            atts.push(result.propertyAttributes[j].theLabel);
        }
        var infoWindow = new google.maps.InfoWindow({
            content: '<div class="mapInfo"><strong><a href="' + result.url + '">' + result.propertyName + '</a></strong><span><em>' + result.price + '</em> ' + atts.join(', ') + '</span><a href="' + result.url + '"><img src="' + result.image.imageSrc + '" /></a></div>'
        });

        // Setup mouse events for the given marker
        google.maps.event.addListener(marker, 'click', function() {
            closeAllInfoWindows();
            infoWindow.open(map, marker);
        });

        infoWindows.push(infoWindow);

    }

    function closeAllInfoWindows() {

        var infoLength = infoWindows.length;
        for (var i = 0; i < infoLength; i++) {
            infoWindows[i].close();
        }

    }

    function getMapIcon(type) {

        switch (type) {
            case "newHome":
                return "/assets/images/resultsPage/mapIcons/newHome.png";
                break;
            case "underOffer":
                return "/assets/images/resultsPage/mapIcons/underOffer.png";
                break;
            case "sold":
                return "/assets/images/resultsPage/mapIcons/sold.png";
                break;
            default:
                return "/assets/images/resultsPage/mapIcons/default.png";
                break;
        }

    }

    //////////// End map specific stuff ////////////

    return {
        init: init
    }
} ();


MarketAppraisal = function() {
    var $viaControls,
	$viaTelephone,
	$apWhenWrap;


    function init() {
        $viaControls = $('#aPViaTelephone, #aPViaEmail');
        $viaTelephone = $('#aPViaTelephone');
        $apWhenWrap = $('#apWhenWrap');
        bindEvents();
    }

    function bindEvents() {
        $viaControls.change(function() {
            if ($viaTelephone.prop('checked') == true) {
                $apWhenWrap.slideDown('fast');
            } else {
                $apWhenWrap.slideUp('fast');

            }
        });

    }


    return {
        init: init
    }

} ();

GallerySlides = function() {

    var $slideMain;
    var cNum = -1, slides = [], fadeDuration = 400;
	var $originalBadge;
	
    function init() {
        $slideMain = $('#slideShow #slideMain');
		$originalBadge = $('.badge');
        $('#slideShow #slideThumbs a').each(function(i) {

            var cSlide = new Slide($(this), i);
            slides.push(cSlide);
			
        });
		$originalBadge.hide();
        gotoSlide(0);

    }

    function gotoSlide(num) {

        if (num == cNum) return;
        cNum = num;
        slides[num].show();

    }

    function cleanUp() {

        var len = slides.length;
        for (var i = 0; i < len; i++) {
            if (i != cNum) {
                slides[i].remove();
            }
        }

    }

    function Slide($thumbLink, num) {

        var self = this, $wrap = $('<div class="slide"></div>'), $inner = $('<div></div>').appendTo($wrap).hide(), $innerInner = $('<div></div>').appendTo($inner), $img = $('<img src="" alt="" />').appendTo($innerInner).load(onLoad), $badge =  $originalBadge.clone().prependTo($innerInner);
        var loaded = false;

        function init() {
            $thumbLink.click(function() {
                gotoSlide(num);
                return false;
            });
        }

        self.show = function() {
            // Fade in here, if loaded. Otherwise trigger a load
            $wrap.appendTo($slideMain);
            if (loaded) {
                $inner.stop(true, false).hide().fadeIn(fadeDuration, onFadedIn);

            } else {
                load();
            }
        }

        self.remove = function() {
            $wrap.detach();
        }

        function load() {
            $img.attr('src', $thumbLink.attr('href'));
        }

        function onLoad() {
            loaded = true;
            if (cNum == num) self.show();
        }

        function onFadedIn() {
            if (cNum == num) cleanUp();
        }

        init();

    }

    return {
        init: init
    }

} ();

HomeSlides = function() {

    var $slidesWrap, $slides, $nav;
    var slideWidth, slides = [], cNum = 0, numSlides, slideInterval, slideDuration = 5000, animDuration = 600;

    function init() {

        $slidesWrap = $('#homeSlides .slides');
        $slides = $('#homeSlides .slide');
        slideWidth = $slides.eq(0).width();
        $slidesWrap.width(slideWidth * $slides.length);

        slideDuration += animDuration;

        buildNav();

        $slides.each(function(i) {

            var $el = $(this).css({ position: 'absolute', top: 0, left: (i * slideWidth) });
            var cSlide = new Slide($el, i);
            slides.push(cSlide);

        });

        // If there's a splash screen, wait until it's clicked.
        if (!_cameFromOutside) {
            loadSlide(0);
        }

    }

    function loadSlide(num) {

        if (num >= $slides.length) return;
        if (num == 1) startRotating();

        slides[num].load();

    }

    function startRotating() {
        slideInterval = setInterval(nextSlide, slideDuration);
    }

    function gotoSlide(num) {

        if (num == cNum) return;

        var cDuration = animDuration;
        var diff = Math.abs(num - cNum);
        if (diff > 1) {
            cDuration = animDuration + ((animDuration / 2) * (diff - 1));
        }

        $slidesWrap.stop(true, false).animate({ left: -(num * slideWidth) }, { duration: cDuration, easing: 'easeInOutCubic' });

        cNum = num;

    }

    function nextSlide() {

        var nextNum = cNum + 1;
        if (nextNum >= $slides.length) nextNum = 0;
        gotoSlide(nextNum);

    }

    function buildNav() {

        var navHtml = ['<ul class="nav">'];
        var len = $slides.length;
        for (var i = 0; i < len; i++) {
            navHtml.push('<li><a href="#"></a></li>');
        }
        navHtml.push('</ul>');

        // We set the width here to make the layout bulletproof in older browsers
        $nav = $(navHtml.join('')).css({ width: (i * 27) });

        $('a', $nav).each(function(i) {

            $(this).click(function() {
                clearInterval(slideInterval);
                gotoSlide(i);
                return false;
            });

        });

    }

    function Slide($wrap, num) {

        var self = this, $img = $('img', $wrap).css({ opacity: 0, visibility: 'hidden' });

        function init() {

            var $slideNav = $nav.clone(true);
            $('li', $slideNav).eq(num).addClass('on');

            $wrap.append($slideNav);

        }

        self.load = function() {
            $img.load(onLoad).attr('src', $img.attr('data-src'));
        }

        function onLoad() {
            $img.css({ visibility: 'visible' }).animate({ opacity: 1 }, { duration: 300 });
            loadSlide(num + 1);
        }

        init();

    }

    return {
        init: init,
        loadSlide: loadSlide
    }

} ();



consolePlus = function() {
    var firstLoad = true;
    var $consoleBox;

    function init() {
	
        if (!window.console) {
            console = { log: log };
        }
    }
	

    function initBox() {
        var clearButton = $('<a>').css({
            position: "absolute",
            top: "4px",
            left: "450px",
            fontSize: "12px",
            color: "#000000",
            fontWeight: "bold",
            cursor: "pointer"
        }).html('clear');

        $consoleBox = $('<div>').css({
            position: "fixed",
            top: "0px",
            left: "0px",
            width: "500px",
            background: "#ddd",
            padding: "15px 5px 10px 10px",
            fontSize: "12px",
            color: "#000000",
            fontFamily: "arial",
            opacity: 0.9
        }).html(clearButton);

        if ($.browser.msie && $.browser.version == "6.0") {
            $consoleBox.css({
                position: "absolute"
            });
        }

        $('body').prepend($consoleBox);
        bindClear();
        firstLoad = false;
    }

	function initStamp() {
		var stamp = $('<div>').css({
			position: "absolute",
			height: "15px",
			width: "15px",
			top: "0px",
			left: "0px",
			zIndex: "100",
			backgroundColor: "#ff0000"
		});
		
		$('body').prepend(stamp);
	}

    function bindClear() {
        $consoleBox.children('a').click(function() {
            $consoleBox.children('p').remove();
        });
    }

    function log(str) {
        if (firstLoad) {
            initBox();
		//	initStamp();
        }
        var newStr = $('<p>').css({ marginBottom: "6px" }).html(str);
        $consoleBox.append(newStr);
    }

    return {
        init: init
    }

} ();




// image rollovers

SwapImage = {};

SwapImage.rollover =
{
    init: function() {
        this.preload();

        $('.hover').css('cursor', 'pointer').hover(function() {
            $(this).attr('src', SwapImage.rollover.newimage($(this).attr('src')));
        }, function() {
            $(this).attr('src', SwapImage.rollover.oldimage($(this).attr('src')));
        });
    },

    preload: function() {
        $(window).bind('load', function() {
            $('.hover').each(function(key, elm) { $('<img>').attr('src', SwapImage.rollover.newimage($(this).attr('src'))); });
        });
    },

    newimage: function(src) { return src.replace(/\.(\w{3})/g, "Hover.$1"); },
    oldimage: function(src) { return src.replace(/Hover\.(\w{3})/g, ".$1"); }
};

//form validation
(function($) {

    $.fn.extend({

        //pass the options variable to the function  
        simpleValidate: function(options) {

            //Set the default values, use comma to separate the settings, example:  
            var defaults = {
                submitButtonID: "#formSubmit",
                decorateTheLabels: true
            }

            var emailTest = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,9}\b/;
            // merges options that are passed in with the defaults (wooo!)
            var options = $.extend(defaults, options);

            // for each element that the plugin is called on...
            return this.each(function() {
                var theForm = $(this);
                var o = options;


                function init() {
                    if (o.decorateTheLabels) {
                        decorateLabels();
                    }
                    errors = false;
                    var errorBox = $('<div>').attr('class', 'formErrors').html("<p>Please complete the following fields before continuing:</p><ul></ul>").hide();
                    theForm.after(errorBox);

                    $(o.submitButtonID).click(function() {
                        errors = false;
                        errorBox.hide().children('ul').html('');
                        theForm.find('.req').each(function() {
                            if ($(this).val() == "") {
                                errors = true;
                                var thisID = $(this).attr('id');
                                var errorMessage = theForm.find('label[for="' + thisID + '"]').html();
                                var Litem = $('<li>').html(errorMessage);
                                errorBox.children('ul').append(Litem);
                            }
                        });

                        theForm.find('.valEmail').each(function() {
                            var theVal = $(this).val();
                            if (theVal != "") {
                                if (emailTest.test(theVal) != true) {
                                    errors = true;
                                    var thisID = $(this).attr('id');
                                    var errorMessage = theForm.find('label[for="' + thisID + '"]').html();
                                    var Litem = $('<li>').html("The email address in the '" + errorMessage + "' input appears to be invalid - please check.");
                                    errorBox.children('ul').append(Litem);
                                }
                            }

                        });

                        if (errors) {
                            errorBox.show();
                            return false;
                        }
                    });
                }

                function decorateLabels() {
                    theForm.find('.req').each(function() {
                        var thisID = $(this).attr('id');
                        theForm.find('label[for="' + thisID + '"]').append('<span> *</span>');
                    });
                }

                //initialise 

                init();

            });
        }
    });

})(jQuery);


