﻿function Mashup() {

    var map;            //the map object that is used to access the maps api
    var geocoder;       //geocoder object used to lookup an address via the maps api
    var xhtml;          //used across the mashup object to build dynamic html for the maps api
    var pan = false;    //this is used to keep track of the pan that each search should do
    var point;
    var precount;
    var postcount;
    var marketlat;  //used to set center of map based on market
    var marketlong;  //used to set center of map based on market
    var market = document.getElementsByName("txtFindMe");
    
    //market = getCookie('IAHomesForSale');
    //marketlat = 41.976662;
    //marketlong = -91.673155;

    marketlat = 41.95;
    marketlong = -93;

    if (market == "WC") {
        marketlat = 42.55;
        marketlong = -92.40;
    }
    
    if (market == "DM") {
        marketlat = 41.6;
        marketlong = -93.65;
    }
         
    this.initialize = function() {
        map = new GMap2(document.getElementById("map"));
        geocoder = new GClientGeocoder();
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        //currently set to Cedar Rapids, but this could be dynamic based on user preference
        map.setCenter(new GLatLng(marketlat, marketlong), 8);

    }

    function preGeoCodeLookup(_xaddr, _xid, _xindex, _xhtml, _xstatus) {
        addPreCount();

        //don't change this timeout as it was the lowest timeout that still worked w/ the api
        var timeout = parseInt(precount) * 225;

        window.setTimeout(function() { geoCodeLookup(_xaddr, _xid, _xindex, _xhtml, _xstatus); }, timeout);
    }

    function geoCodeLookup(addr, _id, _index, _html, _status) {
        geocoder.getLatLng(addr, function(point) {
            if (point) {
                var icon = new GIcon();
                icon.shadow = "../images/shadow.png";
                icon.iconSize = new GSize(12, 20);
                icon.shadowSize = new GSize(22, 20);
                icon.iconAnchor = new GPoint(6, 20);
                icon.infoWindowAnchor = new GPoint(5, 1);
                icon.infoShadowAnchor = new GPoint(10, 5);

                //this type is based on For Sale, Pending, Sold
                if (_status == 1) {
                    icon.image = "../images/green.png";
                } else if (_status == 2) {
                    icon.image = "../images/yellow.png";
                } else if (_status == 4) {
                    icon.image = "../images/red.png";
                }

                map.setZoom(11);
                
                var marker = new GMarker(point, { icon: icon });
                //GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(_html); });
                GEvent.addListener(marker, 'mouseover', function() { marker.openInfoWindowHtml(_html); });
                map.addOverlay(marker);
                    
                if (pan == false) {
                    map.panTo(point);
                    pan = true;
                }
            }
        });
    }

    this.getMarkers = function(obj, search) {
        obj.blur();
        map.clearOverlays();
        pan = false;  //reset this on each search

        var city = document.getElementById('selCity').value;
        var type = document.getElementById('selType').value;
        var min = document.getElementById('selMinPrice').value;
        var max = document.getElementById('selMaxPrice').value;
        var bed = document.getElementById('selBedrooms').value;
        var bath = document.getElementById('selBathrooms').value;
        var status = "1";

        $.ajax({
            type: "POST",
            url: "Mashup.aspx",
            data: { city: city, type: type, min: min, max: max, bed: bed, bath: bath, status: status },
            dataType: "xml",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.responseText);
            },
            success: function(xml) {
                mashup.insertMarkers(xml, obj);
            }
        });
    }

    function cleanXMLData(xml) {
        markerID = xml.getElementsByTagName('lid').item(x).firstChild.data;
        //each conditional below is to make sure we have a valid (not null or empty)
        //address,city,state,zip - else the maps api will throw an exception

        if (xml.getElementsByTagName('address').item(x).firstChild == null) {
            return;
        } else {
            markerAddress = xml.getElementsByTagName('address').item(x).firstChild.data;
        }

        if (xml.getElementsByTagName('city').item(x).firstChild == null) {
            return;
        } else {
            markerCity = xml.getElementsByTagName('city').item(x).firstChild.data;
        }

        if (xml.getElementsByTagName('state').item(x).firstChild == null) {
            return;
        } else {
            markerState = xml.getElementsByTagName('state').item(x).firstChild.data;
        }

        if (xml.getElementsByTagName('zip').item(x).firstChild == null) {
            return;
        } else {
            markerZip = xml.getElementsByTagName('zip').item(x).firstChild.data;
        }

        //now the additional info for the details section
        markerURL = 'http://www.iahomesforsale.com/listingdetail.asp?Listing=' + markerID;
        markerStatus = xml.getElementsByTagName('status').item(x).firstChild.data;
        markerPrice = xml.getElementsByTagName('price').item(x).firstChild.data;
        markerPrice = formatCurrency(markerPrice);
        markerBed = xml.getElementsByTagName('bed').item(x).firstChild.data;
        markerBath = xml.getElementsByTagName('bath').item(x).firstChild.data;
        fullAddress = markerAddress + ' ' + markerCity + ' ' + markerState + ' ' + markerZip;
        //xhtml = "<table><tr><td><img src='http://www.iahomesforsale.com/images/" + markerID + "-0.jpg'/></td><td><b>Price: " + markerPrice + "</b><br />" + markerAddress + "<br />" + markerCity + "<br />Bed: " + markerBed + "<br />Bath: " + markerBath + "<br /><a href='listingdetail.asp?Listing=" + markerID + "' target='_blank'>View Listing</a></td></tr></table>";
        xhtml = "<table><tr><td><img src='http://www.iahomesforsale.com/images/" + markerID + "-0.jpg'/></td><td><b>Price: " + markerPrice + "</b><br />" + markerAddress + "<br />" + markerCity + "<br />Bed: " + markerBed + "<br />Bath: " + markerBath + "<br /><a href='listingdetail.asp?Listing=" + markerID + "' target='_blank'>View Listing</a></td></tr></table>";
        preGeoCodeLookup(fullAddress, markerID, x, xhtml, markerStatus);
    }

    this.insertMarkers = function(xml, obj) {
        resetPreAndPostCount();

        //for each location xml object clean the data and add a marker to the map
        for (x = 0; x < xml.getElementsByTagName('location').length; x++) {
            cleanXMLData(xml);
        }
    }

    function addPreCount() {
        precount = precount + 1
    }

    function addPostCount() {
        postcount = postcount + 1
    }

    function resetPreAndPostCount() {
        precount = 0;
        postcount = 0;
    }

}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num);
}