﻿/// <reference path="jquery-vsdoc.js" />
// text replacement
Cufon.replace("h1");
Cufon.replace("h2");
Cufon.replace("#featuredproperties h3");
Cufon.replace("ul#menu li a");
Cufon.replace("p#actiontext");
Cufon.replace("span#headNumber");

// jquery stuff
$(document).ready(function() {

    // swap colour and bw nav icons
    $("#submenu li").hover(
                    function() {
                        $(this).find("img.bwicon").hide();
                        $(this).find("img.colouricon").show();
                    },
                    function() {
                        $(this).find("img.colouricon").hide();
                        $(this).find("img.bwicon").show();
                    });
                    
    // setup input clear on focus
    $.fn.search = function() {
        return this.focus(function() {
            $(this).addClass("hasData");
            if (this.value == this.defaultValue) {
                this.value = "";
            }
        }).blur(function() {
            if (!this.value.length) {
                this.value = this.defaultValue;
                $(this).removeClass("hasData");
            }
        });
    };
    $("input#Area").search();

    // create dialog for viewing request
    $("#dialog").dialog({
        autoOpen: false,
        bgiframe: true,
        resizable: false,
        height: 200,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            'OK': function() {
                $(this).dialog('close');
                return true;
            },
            Cancel: function() {
                $(this).dialog('close');
                return false;
            }
        }
    });

    // show viewings request dialog
    $("a.view").click(function(ev) {
        ev.preventDefault();
        if ($("#dialog").dialog("open")) {
            window.location = $(this).attr("href");
        }
    });

    // show additional property images
    $(".additionalImage").click(function() {
        $("#mainImage img.property").attr("src", $(this).attr("src"));
    });

    // datepicker
    $("#PreferredDate").datepicker({ minDate: 0, beforeShowDay: function(date) { if (date.getDay() == 0) { return [false, '']; } else { return [true, '']; } } });

    // hide hidden options
    if ($("#corAdd input:radio:checked").val() == 'same') {
        $(".hiddenOption").hide();
    }

    $("#corAdd input:radio").click(function() {
        if ($(this).val() == "diff") {
            $(".hiddenOption").show("slow");
        } else {
            $(".hiddenOption").hide("slow");
        }
    });


    //mortgage calculator
    calculate();

    $("#amount").keyup(function() {
        calculate();
    });
    $("#term").keyup(function() {
        calculate();
    });
    $("#apr").keyup(function() {
        calculate();
    });
    $("#total").keyup(function() {
        calculate();
    });
    $("#totalint").keyup(function() {
        calculate();
    });
    $("#monthly").keyup(function() {
        calculate();
    });



});// end $(document).ready

// Use load for script that should run after the DOM, CSS and all images have loaded.
$(window).load(function(){

    //featured property function interval
    setInterval("slideSwitch()", 6000);

    // property ticker
    setInterval("propertySlider()", 4000);

})// end $(window).load


/**
functions
**/

//featured property slideshow
var test1 = false;
function slideSwitch() {
    test1 = !test1;
    $("#featuredproperties .fproperty").animate({ top: '-200' }, 800, function() {
        if (test1) {
            $("#featuredproperties").append($("#featuredproperties .fproperty:first"));
            test1 = !test1;
        }
        $("#featuredproperties .fproperty").css({ top: 0 })
    });
}


//featured property ticker
var test = false;
function propertySlider() {
    test = !test;
    $("#fpinnerwrapper .fproperty").animate({ left: '-145' }, 1000,function(){
                if(test){
                    $("#fpinnerwrapper").append($("#fpinnerwrapper .fproperty:first"));
                     test = !test;
                }
                $("#fpinnerwrapper .fproperty").css({left:0})
            });
}

function calculate() {
    if (($("#amount").val() != "") && ($("#apr").val() != "") && ($("#term").val() != "")) {
        var amount = $("#amount").val();
        var apr = $("#apr").val();
        var term = $("#term").val() * 12;

        var qfactor = Math.pow((1 + apr / 1200), term);
        var monthly = (amount * apr * qfactor) / (1200 * (qfactor - 1));
        var total = monthly * term;
        var totalint = total - amount;
        var yearlyint = amount * (apr / 100);
        var monthlyint = yearlyint / 12;
        $("#monthly").html("£" + monthly.toFixed(2));
        $("#intonly").html("£" + monthlyint.toFixed(2));
        $("#results").show();
    } else {
        $("#monthly").html("");
        $("#intonly").html("");
        $("#results").hide();
    }
}


// google maps functions

//<![CDATA[
function initialize() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"),
		{ size: new GSize(700, 400) });

        map.setCenter(new GLatLng(53.396986, -2.919002), 11);
        map.setUIToDefault();
    }
    
    localSearch = new GlocalSearch();
    
    // Create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
    baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.shadow = "/content/images/houseiconshadow.png";
    baseIcon.iconSize = new GSize(32, 32);
    baseIcon.shadowSize = new GSize(60, 32);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);

    var MultiIcon = new GIcon(baseIcon);
    MultiIcon.image = "/content/images/houseiconmulti.png";

    clusterer = new Clusterer(map);
    clusterer.SetMaxVisibleMarkers(8);
    clusterer.SetMinMarkersPerCluster(3);
    clusterer.SetMaxLinesPerInfoBox(6);
    clusterer.SetIcon(MultiIcon);
    
    next();
    
}
//]]>

function next() {
    if (cnt >= points.length) {
        //var newArr = cluster(markers,50,11);
        //addMarkers(newArr);
        //addMarkers(markers);
        return
    } else {
        usePointFromPostcode(points[cnt].postcode,points[cnt].markerText)
        cnt++;
    }
}

function usePointFromPostcode(postcode, markerText)
{
    localSearch.setSearchCompleteCallback(null, function() {
        if (localSearch.results[0]) {
            var point = new GLatLng(localSearch.results[0].lat, localSearch.results[0].lng);
            
            var point2 = new objLatLng(localSearch.results[0].lat, localSearch.results[0].lng, markerText);
            markers.push(point2);
            
            var Icon = new GIcon(baseIcon);
            Icon.image = "/content/images/houseicon.png";
            markerOptions = { icon: Icon };
            opts = {
                //"icon": Icon,
                "clickable": true,
                "labelText": "t",
                "labelOffset": new GSize(-16, -16)
            };

            var marker = new GMarker(point, markerOptions);

            GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowHtml(markerText);
            });
            //map.addOverlay(marker);
            clusterer.AddMarker(marker, markerText)
            next();
        }
    });
    localSearch.execute(postcode + ", UK");
}

function aPoint(postcode, markerText) {
  this.postcode=postcode;
  this.markerText=markerText;
}

function objLatLng(lt,ln,d){
    this.lat = lt;
    this.lng = ln;
    this.details = d;
}

function cluster(markers, distance, zoom) {
    var clustered = new Array();

    // Loop until all markers have been compared.
    while (markers.length > 0) {
        marker  = markers.pop();
        
        var cluster = new Array();
        
        // Compare against all markers which are left.
        for (var i=0; i<markers.length; ++i){
                pixels = pixelDistance(marker.lat, marker.lng, markers[i].lat, markers[i].lng, zoom);
                // If two markers are closer than given distance remove target marker from array and add it to cluster.
                if (distance > pixels) {
                    // alert("Distance between " + marker.lat + "," + marker.lng + " and " + markers[i].lat + "," + markers[i].lng + " is " + pixels + " pixels.");
                    var targetMarker = markers.splice(i,1);
                    cluster.push(targetMarker);
                }
        }

        // If a marker has been added to cluster, add the one we were comparing it to and remove the original from array.
        if (cluster.length > 0) {
            //cluster.push(marker);
            clustered.push(cluster);
        } else {
            clustered.push(marker);
        }
    }
    return clustered;
}

function createMarkerClickHandler(marker, text) {
    return function() {
        marker.openInfoWindowHtml(text);
        return false;
    };
}


function addMarkers(markers){
    var Icon = new GIcon(baseIcon);
    Icon.image = "/content/images/houseicon.png";
    markerOptions = { icon:Icon };
    var marker;
    var markerText;
    for (var i=0, len=markers.length; i<len; ++i ){
        marker = new GMarker(new GLatLng(markers[i].lat,markers[i].lng), markerOptions);
        markerText = markers[i].details;

        GEvent.addListener(marker, "click", createMarkerClickHandler(marker,markerText));
        map.addOverlay(marker);
    }
}


/*maths*/
var OFFSET = 268435456; // half of the earth circumference in pixels at zoom level 21
var RADIUS = 85445659.4471; // offset / pi

function haversineDistance(lat1, lon1, lat2, lon2) {
    latd = deg2rad(lat2 - lat1);
    lond = deg2rad(lon2 - lon1);
    a = Math.sin(latd / 2) * Math.sin(latd / 2) +
         Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
         Math.sin(lond / 2) * Math.sin(lond / 2);
         c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return 6371.0 * c;
}

function deg2rad(d) {
    return (d*(Math.PI/180));
}
    
function lonToX(lon) {
    return Math.round(OFFSET + RADIUS * lon * Math.PI / 180);        
}

function latToY(lat) {
    return Math.round(OFFSET - RADIUS * Math.log((1 + Math.sin(lat * Math.PI / 180)) / (1 - Math.sin(lat * Math.PI / 180))) / 2);
}

function pixelDistance(lat1, lon1, lat2, lon2, zoom) {
    x1 = lonToX(lon1);
    y1 = latToY(lat1);

    x2 = lonToX(lon2);
    y2 = latToY(lat2);
        
    return Math.sqrt(Math.pow((x1-x2),2) + Math.pow((y1-y2),2)) >> (21 - zoom);
}
