﻿/// k2c global variables
var anox_url,
    anox_provider,
    anox_remark,
    anox_timer;

/// General scripts for day to day running on site.
var Peach = {

    /// <summary> 
    /// Utilizes jQuery feature detection to return the Internet Explorer browser number.
    /// </summary> 
    GetIEVersion: function () {
        var $browser = 0;
        // The browser is IE 6 - 8.
        if (!jQuery.support.leadingWhitespace) {

            // IE 6 & 7.
            if (!jQuery.support.boxModel) {

                !jQuery.support.opacity && !window.XMLHttpRequest ? $browser = 6 : $browser = 7;
            }
            else {
                $browser = 8;
            }
        }
        return $browser;
    },

    /// <summary> 
    /// Utilizes the jquery twitter plugin to retrieve the latest tweets from the client.
    /// </summary> 
    LaunchTwitter: function () {
        if (jQuery(".tweet").length > 0) {
            jQuery(".tweet").tweet({
                join_text: "auto",
                username: "SMilneHomes",
                avatar_size: null,
                count: 1,
                auto_join_text_default: "",
                loading_text: "loading tweets..."
            });
        }
    },

    /// <summary> 
    /// Grab development dids and showbanners
    /// </summary> 

    ShowBanners: function () {

        if (jQuery(".homeFlashBanner").length > 0) {
            var banners = [],
            today = new Date(),
            day = (today.getDate() < 10 ? "0" : "") + today.getDate(),
            month = (today.getMonth() < 9 ? "0" : "") + (today.getMonth() + 1),
            year = today.getFullYear(),
            checkDate = day + month + year,
            $container = jQuery("#container"),
            dataDevId = $container.attr("data-devid"),
            $bannerContainer = jQuery(".homeFlashBanner"),
            $bannerCode = jQuery("<div/>"),
            getMonth = function (m) {
                return m-1;
            };
			
			// Grampian Developments PX Banner
			 banners.push({
                "devid": "53",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
			
			 banners.push({
                "devid": "12",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
			
			 banners.push({
                "devid": "1",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
			
			 banners.push({
                "devid": "8",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
			
			 banners.push({
                "devid": "17",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
			
			 banners.push({
                "devid": "14",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
					
			 banners.push({
                "devid": "16",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
			
			 banners.push({
                "devid": "9",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
			
			 banners.push({
                "devid": "10",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
			
			 banners.push({
                "devid": "6",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
			
			 banners.push({
                "devid": "11",
                "image": "/images/px/Grampian_PX_Banner-18th_19th_Feb.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 20)
            });
			
			
			
			
            // px banners
            banners.push({
                "devid": "25",
                "image": "/images/px/PXBanner-11Feb-Linenfields.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(1), 12)
            });

            banners.push({
                "devid": "29",
                "image": "/images/px/PXBanner-12Feb-HopefieldView.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 13)
            });

            banners.push({
                "devid": "33",
                "image": "/images/px/PXBanner-18Feb-Beechtrees.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 19)
            });

            banners.push({
                "devid": "25",
                "image": "/images/px/PXBanner-18Feb-Linenfields.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 19)
            });

            banners.push({
                "devid": "38",
                "image": "/images/px/PXBanner-10Mar-LairdsGate.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(3), 11)
            });

            banners.push({
                "devid": "26",
                "image": "/images/px/PXBanner-18Mar-MorningsideGardens.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(3), 19)
            });

            banners.push({
                "devid": "32",
                "image": "/images/px/PXBanner-1April-WallaceGardens.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(4), 2)
            });

            banners.push({
                "devid": "24",
                "image": "/images/px/PXBanner-22Apr-GreenwoodManor.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(4), 23)
            });

            banners.push({
                "devid": "36",
                "image": "/images/px/PXBanner-22Apr-PattertonCourt.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(4), 23)
            });

            banners.push({
                "devid": "43",
                "image": "/images/px/PXBanner-05May-Ardgowan Rise.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(5), 6)
            });

            banners.push({
                "devid": "34",
                "image": "/images/px/PXBanner-13May-DrumpellierLawns.jpg",
                "url": "http://www.stewartmilnehomes.com/part-exchange-event.aspx",
                "alt": "Part Exchange Event",
                "startdate": "",
                "enddate": new Date(2012, getMonth(5), 14)
            });

            // /px banners

            // grampian banners

            banners.push({
                "devid": ["53", "1", "8", "17", "14", "16", "9", "10", "6", "11", "12"],
                "image": "/images/union-square-banner.jpg",
                "url": "",
                "alt": "Come along and see us at Union Square, Aberdeen - Sat 11th and Sun 12th February",
                "startdate": "",
                "enddate": new Date(2012, getMonth(2), 13)
            });

            // /grampian banners

            // display banners
            jQuery.each(banners, function (index, value) {
                var $img = jQuery("<img/>"),
                $anch = jQuery("<a/>"),
                thisDev = value.devid,
                showBanner = false,
                startDate = value.startdate === "" ? today : value.startdate,
                endDate = value.enddate === "" ? today : value.enddate,
                i = 0,
                thisDevLen = 0;

                if (typeof thisDev === "object") {
                    thisDevLen = thisDev.length;
                    for (i = 0; i < thisDevLen; i += 1) {
                        if (thisDev[i] === dataDevId) {
                            showBanner = true;
                        }
                    }
                }
                else if (typeof thisDev === "string" && thisDev === dataDevId) {
                    showBanner = true;
                }

                if (startDate <= today && endDate >= today && showBanner === true) {

                    $img.attr({
                        src: value.image,
                        alt: value.alt
                    });

                    if (value.url !== "") {
                        $anch.attr({
                            href: value.url
                        });
                        $anch.append($img);
                        $bannerCode.append($anch);
                    }
                    else {
                        $bannerCode.append($img);
                    }
                    // show first instance
                    return false;

                }
            });

            $bannerContainer.append($bannerCode.contents());
        }
    },
    /// <summary>
    ///  Grab URL parameters
    /// </summary>

    getUrlParams: function () {
        /// <summary>
        ///     Returns the value of the all the location query-string parameters.
        ///     Based on work from:
        ///     http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
        ///      & http://ejohn.org/blog/search-and-dont-replace/
        /// </summary>
        ///	<returns type="Array" />
        var map = {}, parts;

        // The JavaScript string replace function is used as a means of traversing a string for values, 
        // rather than as an actual search-and-replace mechanism.
        parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (match, key, value) {
            map[key] = decodeURIComponent(value.replace(/\+/g, " "));
        });
        return map;
    },

    /// <summary>
    ///  Get Single URL parameter
    /// </summary>
    getUrlParam: function (id) {
        /// <summary>
        ///     Returns the value of the location query-string parameter that matches the given id.
        /// </summary>
        ///	<param name="id" type="String">
        ///		The id of the query-string parameter to return the value.
        ///	</param>
        ///	<returns type="String" />
        return Peach.getUrlParams()[id];
    },



    /// <summary> 
    /// Postcode anywhere functionality
    /// </summary> 
    postcodeAnywhere: {
        defaultSettings: {
            "pc": "BJ59-CA46-WB96-PX36",
            "url": "//services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/Find/v1.10/json.ws?",
            "detailurl": "//services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/RetrieveById/v1.10/json.ws?",
            "trigger": ".pctrigger",
            "search": ".pcsearch",
            "select": ".pcselect",
            "address": ".pcaddress",
            "town": ".pctown",
            "region": ".pcregion",
            "postcode": ".pcpostcode",
            "step1": ".pc1",
            "step2": ".pc2",
            "step3": ".pc3",
            "reset": ".pcreset",
            "skip": ".pcskip"
        },
        getAddress: function (searchterm) {
            //console.log(searchterm);

            if (searchterm && searchterm !== "") {
                var settings = Peach.postcodeAnywhere.defaultSettings,
                    protocol = document.location.protocol,
                    url = settings.url,
                    pc = settings.pc,
                    callback = "Peach.postcodeAnywhere.loadAddress",
                    fullUrl = [];

                fullUrl.push(
                    protocol,
                    url,
                    "callback=?"
                );

                jQuery.ajax({
                    url: fullUrl.join(""),
                    type: "GET",
                    dataType: "json",
                    contentType: "application/json",
                    data: { Key: pc, SearchTerm: searchterm, CallbackFunction: callback }
                });

            }
            else {
                alert("Sorry, please provide a postcode");
            }
        },
        loadAddress: function (response) {
            //console.log(response);

            var settings = Peach.postcodeAnywhere.defaultSettings,
                $select = jQuery(settings.select),
                $options = jQuery("<select/>"),
                $firstOption = jQuery("<option/>");

            $firstOption.attr({
                "value": "0",
                "selected": true
            });

            $firstOption.text("Please select");

            $options.append($firstOption);

            // Test for an error
            if (response.length == 1 && typeof (response[0].Error) != "undefined") {
                // Show the error message
                console.log(response[0].Description);
                alert("Sorry, we were unable to complete your address, please try again later");
            }
            else {
                // Check if there were any items found
                if (response.length == 0) {
                    alert("Sorry, there were no results, please update your postcode and try again");
                }
                else {
                    // PUT YOUR CODE HERE
                    //FYI: The output is an array of key value pairs (e.g. response[0].Id), the keys being:
                    //Id
                    //StreetAddress
                    //Place

                    jQuery.each(response, function (index, value) {

                        var $this = response[index],
                            $op = jQuery("<option/>");

                        $op.attr("value", $this.Id);
                        $op.text($this.StreetAddress + ", " + $this.Place);

                        $options.append($op);

                    });

                    $select.empty().append($options.contents());
                    Peach.postcodeAnywhere.switchStep(2);
                    if (Peach.GetIEVersion() === 7 || Peach.GetIEVersion() === 8) {
                        $select.fixSelect();
                    }

                }
            }
        },
        getDetailedAddress: function (id) {
            if (id && id !== "" && id !== "0") {
                var settings = Peach.postcodeAnywhere.defaultSettings,
                    protocol = document.location.protocol,
                    url = settings.detailurl,
                    pc = settings.pc,
                    callback = "Peach.postcodeAnywhere.updateAddress",
                    fullUrl = [];

                fullUrl.push(
                    protocol,
                    url,
                    "callback=?"
                );

                jQuery.ajax({
                    url: fullUrl.join(""),
                    type: "GET",
                    dataType: "json",
                    contentType: "application/json",
                    data: { Key: pc, Id: id, CallbackFunction: callback }
                });

            }
            else {
                if (console && console.log) {
                    console.log("no id");
                }
            }
        },
        updateAddress: function (response) {
            var settings = Peach.postcodeAnywhere.defaultSettings,
                $address = jQuery(settings.address),
                $town = jQuery(settings.town),
                $region = jQuery(settings.region),
                $postcode = jQuery(settings.postcode);

            // Test for an error
            if (response.length == 1 && typeof (response[0].Error) != "undefined") {
                // Show the error message
                //alert(response[0].Description);
                alert("Sorry, we were unable to complete your address, please try again later");
            }
            else {
                // Check if there were any items found
                if (response.length == 0) {
                    alert("Sorry, there were no results, please update your postcode and try again");
                }
                else {
                    // PUT YOUR CODE HERE
                    //FYI: The output is an array of key value pairs (e.g. response[0].Udprn), the keys being:
                    //Udprn
                    //Company
                    //Department
                    //Line1
                    //Line2
                    //Line3
                    //Line4
                    //Line5
                    //PostTown
                    //County
                    //Postcode
                    //Mailsort
                    //Barcode
                    //Type
                    //DeliveryPointSuffix
                    //SubBuilding
                    //BuildingName
                    //BuildingNumber
                    //PrimaryStreet
                    //SecondaryStreet
                    //DoubleDependentLocality
                    //DependentLocality
                    //PoBox
                    //PrimaryStreetName
                    //PrimaryStreetType
                    //SecondaryStreetName
                    //SecondaryStreetType
                    //CountryName
                    if ($address) {
                        $address.val(response[0].Line1);
                    }

                    if ($town) {
                        $town.val(response[0].PostTown);
                    }

                    if ($region) {
                        $region.val(response[0].County);
                    }

                    if ($postcode) {
                        $postcode.val(response[0].Postcode);
                    }

                    Peach.postcodeAnywhere.switchStep(3);

                }
            }


        },
        findAddress: function () {
            var settings = Peach.postcodeAnywhere.defaultSettings,
                $search = jQuery(settings.search),
                searchTermArray = [];

            if ($search.length > 0 && $search.val() !== "") {
                searchTermArray.push($search.val());
            }

            if (searchTermArray.length > 0) {
                Peach.postcodeAnywhere.getAddress(searchTermArray.join());
            }
            else {
                alert("Sorry, please provide your postcode to search against");
            }
        },
        resetForm: function () {
            var settings = Peach.postcodeAnywhere.defaultSettings,
                $address = jQuery(settings.address),
                $town = jQuery(settings.town),
                $region = jQuery(settings.region),
                $postcode = jQuery(settings.postcode),
                $search = jQuery(settings.search),
                $select = jQuery(settings.select);

            $address.val("");
            $town.val("");
            $region.val("");
            $postcode.val("");
            $search.val("");
            $select.empty();

            Peach.postcodeAnywhere.switchStep(1);

        },
        switchStep: function (step) {
            var settings = Peach.postcodeAnywhere.defaultSettings,
                $step1 = jQuery(settings.step1),
                $step2 = jQuery(settings.step2),
                $step3 = jQuery(settings.step3),
                fadeSpeed = 800;

            switch (step) {
                case 1:
                    //$step1.fadeIn(fadeSpeed);
                    //$step2.hide();
                    //$step3.hide();
                    break;
                case 2:
                    //$step1.hide();
                    //$step2.fadeIn(fadeSpeed);
                    //$step3.hide();
                    $step2.slideDown();
                    break;
                case 3:
                    //$step1.hide();
                    //$step2.hide();
                    //$step3.fadeIn(fadeSpeed);
                    break;
            }
        },
        init: function () {
            var settings = Peach.postcodeAnywhere.defaultSettings,
                $trigger = jQuery(settings.trigger),
                $select = jQuery(settings.select),
                $reset = jQuery(settings.reset),
                $skip = jQuery(settings.skip);

            $trigger.click(function (e) {
                e.preventDefault();
                Peach.postcodeAnywhere.findAddress();
            });

            $select.change(function (e) {
                var $this = jQuery(this);
                Peach.postcodeAnywhere.getDetailedAddress($this.val());
            });

            $reset.click(function (e) {
                e.preventDefault();
                Peach.postcodeAnywhere.resetForm();
            });

            $skip.click(function (e) {
                e.preventDefault();
                Peach.postcodeAnywhere.switchStep(3);
            });
        }
    },
    devPage: {
        mainTabs: function () {
            var showMap = Peach.getUrlParam("bShowMap"),
                $imageContent = jQuery("#imageContent"),
                $devContent = jQuery("#developmentContent"),
                $plotmapLink = jQuery(".subHeaderOneRight .plotmap"),
                $devLink = jQuery(".subHeaderOneRight .development"),
                $houseLink = jQuery(".subHeaderOneRight .housetype"),
                $locationLink = jQuery(".subHeaderOneRight .locationDirections"),
                $container = jQuery("#container"),
                dataPageType = $container.attr("data-pagetype");

            switch (dataPageType) {
                case "development":
                    if (showMap === "1") {
                        $devContent.hide();
                        $imageContent.show();
                        $plotmapLink.closest("li").addClass("selected");

                        if (typeof sIFR !== "undefined") {
                            sIFR.replace(tradegothic, {
                                selector: '#imageContent h1',
                                transparent: true,
                                ratios: [8, 1.41, 11, 1.31, 15, 1.29, 25, 1.25, 28, 1.23, 32, 1.22, 33, 1.23, 39, 1.22, 56, 1.21, 91, 1.2, 92, 1.19, 97, 1.2, 98, 1.19, 101, 1.2, 103, 1.19, 104, 1.2, 109, 1.19, 110, 1.2, 114, 1.19, 115, 1.2, 1.19]
    , css: '.sIFR-root { color: #003e5a; font-size:22px; }'
                            });
                        }
                    }
                    else {
                        $devLink.closest("li").addClass("selected");
                    }
                    break;
                case "house":
                    $houseLink.closest("li").addClass("selected");
                    break;
                case "location":
                    $locationLink.closest("li").addClass("selected");
                    break;
            }



        },
        devTabs: function () {
            var $tabs = jQuery(".development_tabs"),
                $content = jQuery(".development_tabs_content div.parent_tab"),
                $li = $tabs.find("li"),
                $links = $tabs.find("a");

            $links.click(function (e) {
                e.preventDefault();

                var $this = jQuery(this),
                    thisRel = $this.attr("rel"),
                    $thisContent = jQuery("#" + thisRel);

                $li.removeClass("selected");
                $this.closest("li").addClass("selected");

                if ($thisContent.is(':visible') === false) {
                    $content.hide();
                    $thisContent.show();
                }
            });

            $li.filter(":first").addClass("selected");
            $content.hide();
            $content.filter(":first").show();

            /*if (jQuery('#tab_testimonials').is(":empty") === true) {
            jQuery('a[rel=tab_testimonials]').closest("li").hide();
            }*/
        },
        bannerRotate: {
            action: function () {
                // Select the currently active div (if there is one) if not then get the first one.
                var currentDiv = jQuery('.development_banner div.active_banner') ? jQuery('.development_banner div.active_banner') : jQuery('.development_banner div:first');

                // Get the next div in the list. If there are none there return to the first.
                var nextDiv = ((currentDiv.next().length) ? ((currentDiv.next().hasClass('active_banner')) ? jQuery('.development_banner div:first') : currentDiv.next()) : jQuery('.development_banner div:first'));

                // Hide the current div
                currentDiv.fadeOut(500);
                currentDiv.removeClass('active_banner');

                // Show the next one
                nextDiv.fadeIn(1000);
                nextDiv.addClass('active_banner');
            },
            init: function () {
                // Select the currently active div (if there is one) if not then get the first one.
                var currentDiv = jQuery('.development_banner div.active_banner') ? jQuery('.development_banner div.active_banner') : jQuery('.development_banner div:first');

                if (currentDiv.next().length > 0 || currentDiv.prev().length > 0) {

                    // In 4 seconds time, and every 4 seconds thereafter fire the doRotate function to change image.
                    setInterval('Peach.devPage.bannerRotate.action()', 4000);

                }
            }
        },
        callus: function () {
            // updates the phone number on the RHS with the number in hidden div in content area
            jQuery(document).ready(function () {
                if (jQuery(".callUsContent").length > 0) {
                    jQuery(".callUs").each(function () {
                        jQuery(this).show();
                        jQuery(this).find(".callUsNumber").text(jQuery(".callUsContent").html());
                    });
                }
            });
        },
        generic: function () {
            var devID = Peach.getUrlParam("DevelopmentID");

            if (devID === "32") {
                jQuery("#freedomHomesImage").show();
            }
        },
        init: function () {
            this.mainTabs();
            this.devTabs();
            this.bannerRotate.init();
            this.callus();
            this.generic();
        }
    },
    callback: {
        init: function () {
            var $trigger = jQuery(".callBackTrigger"),
                $container = jQuery("#container"),
                devID = $container.attr("data-devid"),
                callbackDevs = [],
				i = 0,
				arrayLen = 0;

            callbackDevs.push(
                "15",
                "13",
                "16",
                "17"
            );
			
			arrayLen = callbackDevs.length;
			
            if (typeof devID !== "undefined") {
				for(i=0; i<arrayLen; i+=1){
					if(callbackDevs[i] === devID){
						$trigger.show();
						return;
					}
				}
            }
        }
    },
    gallery: {
        init: function () {
            var $trigger = jQuery(".galleryOverlay"),
                $container = jQuery("#container"),
                devID = $container.attr("data-devid"),
                galleryDevs = [],
				i = 0,
				arrayLen = 0;

            galleryDevs.push(
                "24"
            );

            arrayLen = galleryDevs.length;

            if (typeof devID !== "undefined") {
                for (i = 0; i < arrayLen; i += 1) {
                    if (galleryDevs[i] === devID) {
                        $trigger.show();
                        return;
                    }
                }
            }
        }
    },
    deals: {
        init: function () {
            if (jQuery(".offers .fc").length > 0) {
                jQuery(".dealsHidden").show();
            }
        }
    },
    k2c: {
        // klick2contact code

        /*
        // original code
        var anox_provider = 'SMBeechTreesLanark';
        var anox_url      = document.location.protocol + '//' + 'www.klick2contact.com';
        var anox_remark   = 'any_remark';
        var anox_timer    = 10000;
        (function() {
        var ens   = document.createElement('script');
        ens.type  = 'text/javascript'; ens.async = true; ens.id = "anox_static";
        ens.src   = anox_url + '/integrated/static_js.php?p=' + anox_provider;
        var first = document.getElementsByTagName('script')[0];
        first.parentNode.insertBefore(ens, first);
        })();
        */
        enabled: true,
        load: function () {
            var $container = jQuery("#container"),
                dataPageType = $container.attr("data-pagetype"),
                showMap = Peach.getUrlParam("bShowMap"),
                devID = $container.attr("data-devid"),
                provider = "",
                ens,
                first;

            if (dataPageType === "development" && showMap !== "1") {
                switch (devID) {
                    case "23":
                        provider = "SMAllandaleSaltcoats";
                        break;
                    case "43":
                        provider = "SMArdgowanRiseInverkip";
                        break;
                    case "27":
                        provider = "SMAthenaCourt";
                        break;
                    case "33":
                        provider = "SMBeechTreesLanark";
                        break;
                    case "8":
                        provider = "SMBroadshadeWesthill";
                        break;
                    case "20":
                        provider = "SMCampsieMeadowsRobroyston";
                        break;
                    case "28":
                        provider = "SMCheerytrees";
                        break;
                    case "2":
                        provider = "SMChurchfieldsErrol";
                        break;
                    case "34":
                        provider = "SMDrumpellierLawnsBargeddie";
                        break;
                    case "50":
                        provider = "SMFarringtonParkBuckshaw";
                        break;
                    case "24":
                        provider = "SMGreenWoodManorNewtonMearns";
                        break;
                    case "48":
                        provider = "SMHeathfieldsTarporley";
                        break;
                    case "49":
                        provider = "SMHighGroveSaughall";
                        break;
                    case "31":
                        provider = "SMHighFieldsViewDunblane";
                        break;
                    case "29":
                        provider = "SMHopefieldViewBonnyrigg";
                        break;
                    case "1":
                        provider = "SMKepplestoneAberdeen";
                        break;
                    case "38":
                        provider = "SMLairdsGateStewarton";
                        break;
                    case "25":
                        provider = "SMLinenFieldsCumbernauld";
                        break;
                    case "46":
                        provider = "SMMillgreenMarple";
                        break;
                    case "26":
                        provider = "SMMorningsideGardensWishaw";
                        break;
                    case "36":
                        provider = "SMPattertonCourtNewtonMearns";
                        break;
                    case "9":
                        provider = "SMSilverBirchesAlford";
                        break;
                    case "30":
                        provider = "SMStrathallanParkStirling";
                        break;
                    case "4":
                        provider = "SMStrathearnViewCrieff";
                        break;
                    case "17": // The Meadows
                        provider = "SMLeathanFields";
                        break;
                    case "14": // The Rise
                        provider = "SMLeathanFields";
                        break;
                    case "16": // The Wood
                        provider = "SMLeathanFields";
                        break;
                    case "22":
                        provider = "SMThorntonGrangeEastKilbride";
                        break;
                    case "10":
                        provider = "SMVisionAberdeen";
                        break;
                    case "32":
                        provider = "SMWallaceGardensStirling";
                        break;
                    case "6":
                        provider = "SMWellsideBraeKemnay";
                        break;
                    case "11":
                        provider = "SMWest1Kingswells";
                        break;
                    case "53": // The Fairways
                        provider = "SMLeathanFields";
                        break;
                }

                if (provider !== "") {
                    anox_provider = provider;
                    anox_url = document.location.protocol + '//' + 'www.klick2contact.com';
                    anox_remark = 'any_remark';
                    anox_timer = 10000;
                    ens = document.createElement('script');
                    ens.type = 'text/javascript'; 
                    ens.async = true; 
                    ens.id = "anox_static";
                    ens.src = anox_url + '/integrated/static_js.php?p=' + anox_provider;
                    first = document.getElementsByTagName('script')[0];
                    first.parentNode.insertBefore(ens, first);
                }
            }
        },
        init: function () {
            if (Peach.k2c.enabled === true) {
                Peach.k2c.load();
            }
        }

    },
    generic: {
        equalCols: function () {
            jQuery(".updateHeightLeft").each(function () {
                var $left = jQuery(this),
                    $right = $left.next(".updateHeightRight"),
                    leftHeight = 0,
                    rightHieght = 0;

                if ($left) {
                    leftHeight = $left.height();
                }

                if ($right) {
                    rightHeight = $right.height();
                }

                if (leftHeight < rightHeight) {
                    $left.css("min-height", rightHeight + "px");
                }
            });
        },
        init: function () {
            this.equalCols();







        }
    }

};

/// <summary> 
/// Launch the scripts when all elements are loaded in the DOM.
/// </summary>
jQuery(document).ready(function () {
    Peach.ShowBanners();

    Peach.postcodeAnywhere.init();

    Peach.devPage.init();
    Peach.callback.init();
    Peach.gallery.init();

    Peach.deals.init();
    Peach.generic.init();

    Peach.k2c.init();

});

/*
jquery.fixSelect

Fixes an whereby IE chops long options in a select box with fixed width. It does this by
surrounding the element within a span of the same width with overflow-x set to hidden,
and setting the select width to auto on a mousedown or keyup event then back to its
previous value on blur.

Syntax:

$jQueryCollection.fixSelect([minWidth]);

The minWidth parameter is optional, but can be used to hard set a width for the elements.
If the result doesn't look quite right, you can use CSS to fix the result: the added span
wrapping the select element has the class "selectFix" to make this possible.

Two custom events are exposed:

- "initfix" will recompute the natural width of the element; and
- "applyfix" will resize the select element (e.g. after assigning focus programmatically).

(Merciful heavens, IE should just be taken outside and *shot*. This apparently simple code
involved more obscure bug workarounds than I have time or space to document.)
*/

(function ($) {

    $.fn.fixSelect = function (minWidth) {
        /* Fix only applies to IE 8 and below. */
        return (!($.browser.msie && $.browser.version < 9)) ? this : this.each(function () {
            if (this.tagName.toLowerCase() == 'select') { // Also only applies to select elements.

                var el = this,
            $this = $(this),
            minWidth = minWidth ? minWidth : el.offsetWidth, // Current width used as minimum.
            elementWidth = $this.outerWidth(),
            $wrapper = $('<div class="selectFix"></div>').css({ // Wraps the select element.
                display: ($this.css('display') == 'block') ? 'block' : 'inline',
                "float": $this.css('float'),
                overflowX: 'hidden',
                overflowY: 'visible',
                width: minWidth
            }),
            naturalWidth;

                /* Set up element margins on wrapper instead. (For more complex styles, use CSS.) */
                $.each('marginTop marginRight marginBottom marginLeft'.split(' '), function (i, prop) {
                    $wrapper.css(prop, $this.css(prop));
                    $this.css(prop, 0);
                });

                if ($this.is(':visible')) { // Doesn't work for invisible elements, they have zero width!
                    /* Determine what the "natural" (i.e. automatic) width would be. */
                    $this.width('auto');
                    naturalWidth = $this.outerWidth();
                    $this.width(minWidth);

                    if($this.parent(".selectFix").length === 0){
                        $this
                        .wrap($wrapper)
                        .bind('mousedown keyup applyfix', function () {
                            /* Use "auto" or fixed width, whichever is biggest. */
                            //$this.width((naturalWidth < elementWidth) ? minWidth : 'auto');
                            $this.width("auto").css({"position":"relative","z-index":"1"});
                            /* Horribly, IE 6 will ignore the overflow anyway unless some part of the
                            select element is already hidden before the options list is displayed. */
                            if ($.browser.version == 6) $this.css('marginLeft', 1);
                        })
                        .bind('change blur', function () {
                            /* Reset the element to fixed width. */
                            $this.width(minWidth);
                            if ($.browser.version == 6) $this.css('marginLeft', 0);
                        })
                        .bind('initfix', function () {
                            /* Recalculate "natural" width. */
                            $this.width('auto');
                            naturalWidth = $this.outerWidth();
                            $this.width(minWidth);
                        });
                    }
                }
            }
        });
    }

})(jQuery);

/* crazy egg code */

(function(){
    jQuery(function(){
        var crazy = [],
			pageHref = document.location.href,
			crazyLen = 0,
			i = 0,
            documentProtocol = document.location.protocol;
		
		crazy.push({
			"url": "http://www.stewartmilnehomes.com/ardgowan-rise-ardmore.aspx?did=102&developmentid=0&hid=0&&housetypeid=1109&pricerange=0&bedrooms=0&hometypeid=0&townid=0&regionid=0",
			"src": documentProtocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0009/0388.js?"+Math.floor(new Date().getTime()/3600000)
		});

        crazy.push({
			"url": "http://www.stewartmilnehomes.com/ardgowan-rise-ardmore.aspx?developmentid=0&hid=0&&pricerange=0&bedrooms=0&hometypeid=0&townid=0&regionid=0",
			"src": documentProtocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0009/0388.js?"+Math.floor(new Date().getTime()/3600000)
		});
		
		crazy.push({
			"url": "http://www.stewartmilnehomes.com/contact-us.aspx",
			"src": documentProtocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0009/0388.js?"+Math.floor(new Date().getTime()/3600000)
		});
		
		crazy.push({
			"url": "http://www.stewartmilnehomes.com/homes-search-results.aspx?Page=13&RegionID=11&TownID=0&HomeTypeID=0&Bedrooms=0&PriceRange=0&DevelopmentID=0&dID=0",
			"src": documentProtocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0009/0388.js?"+Math.floor(new Date().getTime()/3600000)
		});
		
		crazy.push({
			"url": "http://timbersystems.stewartmilne.com",
			"src": documentProtocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0009/0388.js?"+Math.floor(new Date().getTime()/3600000)
		});	

        crazy.push({
			"url": "http://timbersystems.stewartmilne.com/timber-systems.aspx",
			"src": documentProtocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0009/0388.js?"+Math.floor(new Date().getTime()/3600000)
		});

		crazyLen = crazy.length;
		
		for(i=0; i<crazyLen; i+=1){
            (function(){
                var crazyUrl = crazy[i].url,
                    crazySrc = crazy[i].src,
                    compareUrl,
                    noQS,
                    noPage,
                    inHref;
                if(typeof crazyUrl !== "undefined" && typeof crazySrc !== "undefined") {      
                    crazyUrl = crazyUrl.toLowerCase();
                    pageHref = pageHref.toLowerCase();
                    compareUrl = crazyUrl === pageHref;
                    noQS = crazyUrl.indexOf("?") === -1;
                    noPage = pageHref.indexOf(".aspx") === -1;
                    inHref = pageHref.indexOf(crazyUrl) > -1;
                
                   if(compareUrl === true || (noPage && noQS && inHref)){
                        (function(){
					        var a=document.createElement("script");
					        var b=document.getElementsByTagName('script')[0];
					        a.src=crazySrc;
					        a.async=true;
					        a.type="text/javascript";
					        b.parentNode.insertBefore(a,b);
				        })();
			        }
                }
            })();
		}
    });
})();
