﻿

var xml;
var gmap;

var details;

var minZoomGeo = 12;

var hbDivName;

var hbArr;
var hbArrName;
var hbArrCount;


var hostURL = "";
var mapVgId = 0;
var centerMap;
var showRecenter = false;
var removeWrongVendors = 0;
var criteriadevsonly = 0;
var featuredHomebuilder;
var criteriaid = "NULL";

var details;

var debug = false;
var debugDiv;

var offerList = [];

var viewType;

var propSource = "MOPAB";

function debugWrite(line) {
    if (!debug)
        return;
        
    if (!debugDiv) {
        debugDiv = document.getElementById("debugDiv");
        debugDiv.style.visibility = "visible";
    }

    if (debugDiv) {
        var time = new Date();

        debugDiv.innerHTML += "<br />" + fixTime((time.getTime()/1000) + "") + ": " + line;
    }
}

function fixTime(time) {
    while (time.length < 14) {
        time += "0";
    }
    return time;
}

function setMapVendorGroupId(vgid) {
    mapVgId=vgid;
    map_move(gmap);
}

function restoreMapCenter() {
    gmap.setCenter(centerMap,gmap.getZoom());
}

function setStatus(newStatus) {
    var statusDiv = document.getElementById("mapstatus");

    if (!statusDiv)
        return;

    statusDiv.innerHTML = newStatus;
}



function getGeoCategoryCSV() {


    if (gmap.getZoom() < minZoomGeo)
        return "";
        
    var csv = "";
    var geo;
    var first = true;

    for (var num = 0; num < geoCategories.length; num++) {
        geo = document.getElementById(geoCategories[num]);

        if (geo) {
            if (geo.className == 'AmenityBarOn') {
                if (first) {
                    first = !first;
                } else {
                    csv += ", ";
                }
                csv += geoCategories[num].substring(11);
            }
        }
    }

    return csv;
}

function refreshGeoZoom() {

    for (var num = 0; num < geoCategories.length; num++) {
        geo = document.getElementById(geoCategories[num]);
        
        if (geo) {
            if (geo.className == 'AmenityBarOnZoomedOut' && gmap.getZoom() >= minZoomGeo) {
                geo.className = 'AmenityBarOn'
                //geo.title = "";
            } else if (geo.className == 'AmenityBarOn' && gmap.getZoom() < minZoomGeo) {
                geo.className = 'AmenityBarOnZoomedOut';
                //geo.title = "Amenities are disabled until a higher zoom level on the map";
            }
        }

        switch (geo.className) {
            case "AmenityBarOnZoomedOut":
                geo.title = "Amenity is suspended due to zoom level";
                break;
            case "AmenityBarOn":
                geo.title = "Amenity is enabled";
                break;
            case "AmenityBarOff":
                geo.title = "Amenity is disabled";
                break;
        }
    }
}

function map_beginMove(map) {
    if (!map.getInfoWindow().isHidden())
        return;
    if (!(ie7 || ie6))
        return;
    map.clearOverlays();
}



var refreshing = false;
function map_move(map) {

    if (!map.getInfoWindow().isHidden())
        return;

    if (refreshing) {
        return;
    }

    refreshing = true;

    debugWrite("map_move()");

    setStatus("Reading");
    gmap = map;
    gmap.clearOverlays();

    refreshGeoZoom();
    refreshOffersZoom();

    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();

    var geoCategoryCSV = getGeoCategoryCSV();

    if (!xml) {
        if (window.XMLHttpRequest) {
            xml = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            xml = new ActiveXObject("Microsoft.XMLHTTP");
        }
    } else {
        xml.abort();
    }

    var xmlPath = '/sqlxml/map?topleftLat=' + southWest.lat() + '&topleftLong=' + southWest.lng() + '&bottomRightLat=' + northEast.lat() + '&bottomRightLong=' + northEast.lng() + '&geocategorycsv=' + geoCategoryCSV + '&vendorgroupid=' + mapVgId + '&offertypeidcsv=' + getOfferListCSV() + "&zoomlevel=" + gmap.getZoom() + "&removewrongvendors=" + removeWrongVendors + "&criteriadevsonly=" + criteriadevsonly + "&criteriaid=" + criteriaid + "&viewtype=" + viewType;

    if (sessionid) {
        xmlPath += "&sessionid=" + sessionid;
    }

    if (userid!=null && userid!=0) {
        xmlPath += "&userid=" + userid;
    }else if(userid=0){
        xmlPath += "&userid=NULL" 
    }
    
    //alert(xmlPath);

    xml.open("GET", xmlPath, true); //
    xml.onreadystatechange = processMapXml;
    xml.send(null);

    if (showRecenter == true) {
        var tr = document.getElementById("trMapCenter");

        if (tr) {
            if (centerMap == gmap.getCenter()) {
                tr.className = "GoCenter content tdMapCenter Hidden";
            } else {
                tr.className = "GoCenter content tdMapCenter RevealedMapCenter";
            }
        }
    }

    refreshing = false;

    debugWrite("map_move()-finish");
}

function amenityItem_Click(item) {



    switch (item.className) {
        case "AmenityBarOnZoomedOut":
        case "AmenityBarOn":
            item.className = "AmenityBarOff";
            break;
        case "AmenityBarOff":
            item.className = gmap.getZoom() < minZoomGeo ? "AmenityBarOnZoomedOut" : "AmenityBarOn";
            break;
    }


    if (gmap.getZoom() >= minZoomGeo)
        map_move(gmap);
}

function addHomeBuilder(hb) {
    if (!hb.hasChildNodes)
        return;

    var vgid = 0;
    var count = 0;
    var name = "";

    
    for (var num = 0; num < hb.childNodes.length; num++) {
        var item = hb.childNodes[num];
        switch (item.tagName) {
            case 'vgid':
                vgid = item.firstChild.nodeValue;
                break;
            case 'count':
                count = item.firstChild.nodeValue;
                break;
            case 'name':
                name = item.firstChild.nodeValue;
                break;
        }
    }
    
    var index = hbArr.length;

    hbArr[index] = vgid;
    hbArrCount[index] = count;
    hbArrName[index] = name;
}


var order = 0;
function drawMapIcon(icon) {


    if (!icon.hasChildNodes)
        return;

    var width = 16;
    var height = 16;
    var image;
    var latitude;
    var longitude;
    var id = 0;
    var type = "";
    var desc = "";
    var vgid = 0;
    var visible = 0;
    var critid = 0;
    order = 0;

    for (var num = 0; num < icon.childNodes.length; num++) {
        var item = icon.childNodes[num];
        switch (item.tagName) {
            case 'width':
                width = item.firstChild.nodeValue;
                break;
            case 'height':
                height = item.firstChild.nodeValue;
                break;
            case 'icon':
                image = "/include/images/map/" + item.firstChild.nodeValue;
                break;
            case 'latitude':
                latitude = item.firstChild.nodeValue;
                break;
            case 'longitude':
                longitude = item.firstChild.nodeValue;
                break;
            case 'id':
                id = item.firstChild.nodeValue;
                break;
            case 'type':
                type = item.firstChild.nodeValue;
                break;
            case 'desc':
                desc = item.firstChild.nodeValue;
                break;
            case 'vgid':
                vgid = item.firstChild.nodeValue;
                break;
            case 'visible':
                visible = item.firstChild.nodeValue;
                break;
            case 'criteriaid':
                critid = item.firstChild.nodeValue;
                break;
            case 'order':
                order = item.firstChild.nodeValue;
                break;
        }
    }
  
    if (visible == 0)
        return;

    if (!width)
        width = 16;

    if (!height)
        height = 16;

    var i = new GIcon(G_DEFAULT_ICON);

    i.iconSize = new GSize(width, height);
    i.image = image;
    //i.shadowSize = new GSize(26, 24);
    i.shadow = null;
    i.iconAnchor = new GPoint(width/2, height/2);

    var title = "";
    if (desc) {
        title = desc;

        if (type == 'dev') {
            title += ' (click for more details)'
        }
    }
    /*
    if(type=='geo'){
        order = 0;
    }else{
        order = 1;
    }
    */


    markerOptions = { icon: i,title:title,size:i.iconSize,zIndexProcess:importanceOrder };

    var point = new GLatLng(latitude, longitude);
    var marker = new GMarker(point, markerOptions);

    

    if (type == 'dev') {
        //addlistener for i on click to infowindowhtml
        GEvent.addListener(marker, "click", function() { gicon_click(latitude, longitude, type, id, critid); })
    }
    
    gmap.addOverlay(marker);

}

function importanceOrder(marker, b) {
    return order;
}


function gicon_click(latitude, longitude, type, id, critid) {

   /*
    if (!(ie6 || ie7) || true) {
        if (window.XMLHttpRequest) {
            details = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            details = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    */

    var detailPath = '/map/details.aspx?type=' + type + '&id=' + id;

    if (viewType) {
        detailPath += '&viewtype=' + viewType;
    }

    if (critid != 0 && critid != null) {
        detailPath += '&criteriaid=' + critid;
    }

    detailPath += '&source=' + propSource;
    
	detailPath += '&offertype=' + getOfferListCSV();

    var pos = new GLatLng(latitude, longitude);
    var iframe = '<iframe class="infoWindowFrame" frameborder="0" scrolling="no" src="' + detailPath + '" ></iframe>';

    gmap.openInfoWindow(pos, iframe, null);

    /*
    
        gmap.openInfoWindowHtml(pos, '<div class="infoWindowFrame" id="divpropholder">Loading Development...</div>', null);
    
        details.open("GET", detailPath, true); //
        details.onreadystatechange = function() { openInfoWindow(pos); };
        details.send(null);
    
    */
    
}

function openInfoWindow(pos) {
    if (details.readyState == 4) {
        var res = details.responseText;
        var div = document.getElementById("divpropholder");
        div.innerHTML = res;
        //gmap.openInfoWindowHtml(pos, '<div class="infoWindowFrame">' + res + '</div>', null);
    }
}

var processing = false;
function processMapXml() {
    if (xml.readyState == 4 && !processing) {
        debugWrite("processMapXml()");

        processing = true;

        setStatus("Adding items to map");

        hbArr = null;
        hbArrName = null;
        hbArrCount = null;
        
        hbArr = [];
        hbArrName = [];
        hbArrCount = [];
        
        var res = xml.responseXML;


        if (res) {
            if (res.childNodes.length > 0) {
                for (var num = 0; num < res.childNodes.length; num++) {
                    if (res.childNodes[num].tagName == 'options') {
                        if (res.childNodes[num].hasChildNodes) {
                            var items = res.childNodes[num];

                            for (var index = 0; index < items.childNodes.length; index++) {
                                if (items.childNodes[index].tagName == 'mapitem') {
                                    drawMapIcon(items.childNodes[index]);
                                    //if (index == 100) { return; }//remove
                                } else if (items.childNodes[index].tagName == 'vendor') {
                                    addHomeBuilder(items.childNodes[index]);
                                }
                            }
                        }
                    }
                }
            }

            DrawHomeBuilders()
            setStatus("Ready");
        } else {
            setStatus("Processing...")
            debugWrite("processMapXml()-(no data)");
        }
        processing = false;
        debugWrite("processMapXml()-finish");
        xml.abort();
    }
}














/////////////////////////////////////////////////////////////////////////////////////////////////


function navNextMapProperty(jump) {

    var pView;

    if (window.XMLHttpRequest) {
        pView = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        pView = new ActiveXObject("Microsoft.XMLHTTP");
    }

    currentPropIndex += jump;

    if (currentPropIndex >= propList.length)
        currentPropIndex = 0;

    if (currentPropIndex < 0)
        currentPropIndex = propList.length - 1;

    var xmlPath = '/sqlxml/propertyview?viewtype=' + viewType + '&propertyids=' + propList[currentPropIndex] + '&sessionid=' + sessionid;

    //alert(xmlPath);

    pView.open("GET", xmlPath, true);
    pView.send(null);

    var table;
    var maincell;//ie fix for borders showing through invisibility

    for (var num = 0; num < propList.length; num++) {
        table = document.getElementById('pbTable' + propList[num]);
        table.className = num == currentPropIndex ? 'propertybox RevealedPBox' : 'propertybox Hidden';

        if (ie6 || ie7) {
            maincell = document.getElementById('DevBoxMain' + propList[num]);
            maincell.className = num == currentPropIndex ? 'DevBoxMain' : 'DevBoxMainHidden';
        }
    }

    var span = document.getElementById('PropertyNo');

    if (span) {
        span.innerHTML = (currentPropIndex + 1) + ' of ' + propList.length + ' properties';
    }
}


function DrawHomeBuilders() {
    if (!hbDivName)
        return;

    var div = document.getElementById(hbDivName);

    if (!div)
        return;

    setStatus("Drawing Homebuilders");

    div.innerHTML = "";
    div.className = "featuredhomebuilder";

    if (hbArr.length < 1)
        return;

    setStatus("Drawing " + hbArr.length + " Homebuilders");

    var html = "";

    //html += '\t<h1>Visible Homebuilders</h1>\n';
    html += '\t<div class="container">\n';

    if (mapVgId != 0) {
        html += '\t<div style="text-align:center" >';
        html += '\t<strong>Currently Viewing:</strong>\n<br />\n';
        html += '\t<img src="http://img.smartnewhomes.com/media/homebuilder/large/' + mapVgId + '.gif" class="featimg1" />\n';

        html += '\t<a style="cursor:pointer;" onclick="setMapVendorGroupId(0)" >\n<br /><br />\n';
        html += '\t<b>Show all Homebuilders</b>\n';
        html += '\t</a>\n';
        html += '\t</div>';
    }

    for (var num = 0; num < hbArr.length; num++) {
        html += '\t\t<div class="feathb0">\n';

        html += '\t\t\t<a style="cursor:pointer;" onclick="setMapVendorGroupId(' + hbArr[num] + ')" >\n';

        html += '\t\t\t\t<img title="' + hbArrName[num] + ' (' + hbArrCount[num] + ' development' + (hbArrCount[num] == 1 ? '' : 's') + ')" src="' + hostURL + '/media/homebuilder/small/' + hbArr[num] + '.gif" class="featimg0" />\n';

        html += '\t\t\t</a>\n';

        html += '\t\t\t<br class="separator0" />\n';

        html += '\t\t</div>\n';

        hbArr[num] = null;
        hbArrName[num] = null;
        hbArrCount[num] = null;
    }

    hbArr = null;
    hbArrName = null;
    hbArrCount = null;
    
    html += '\t\t<br class="separator1" />\n';
    html += '\t</div>\n';

    div.innerHTML = html;
}

function refreshOffersZoom() {
    if (!offerList)
        return;

    if (offerList.length == 0)
        return;

    for (var num = 1; num < offerList.length; num++) {

        var image = document.getElementById("offerimg" + num);
        var idHolder = document.getElementById("offerid" + num);
        var text = document.getElementById("offertext" + num);
        var minzoom = document.getElementById("minzoomvisibility" + num);


        if (minzoom.value > gmap.getZoom()) {
            text.className = "MapOfferTextZoomedOut";
        } else {
            if (text && idHolder) {
                if (offerList[num]) {
                    text.className = "MapOfferTextEnabled";
                } else {
                    text.className = "MapOfferTextDisabled";
                }
            }
        }
    }
}

function AllOffersSelected() {
    var allSelected = true;

    for (var num = 0; num < offerList.length; num++) {
        if (document.getElementById("offerid" + num))
            if (!offerList[num]) {
                allSelected = false;
            }
    }

    return allSelected;
}

function FlipMapOffer(offerindex) {
    if (!offerList)
        return;

    if (offerList.length == 0)
        return;

    if (!AllOffersSelected()) {
        flipOffer(offerindex, !offerList[offerindex]);
    } else {
        for (var num = 0; num < offerList.length; num++) {
            if (document.getElementById("offerid" + num))
                flipOffer(num, num == offerindex);
        }
    }
    

    map_move(gmap);


}

function flipOffer(offerindex, newVal) {
    var image = document.getElementById("offerimg" + offerindex);
    var idHolder = document.getElementById("offerid" + offerindex);
    var text = document.getElementById("offertext" + offerindex);
    var minzoom = document.getElementById("minzoomvisibility" + offerindex);

    if (minzoom.value > gmap.getZoom()) {
        if(!AllOffersSelected())
            alert("This Offer type will not become available until the map is zoomed in more");
        return;
    }

    offerList[offerindex] = newVal;

    if (image && idHolder) {
        if (offerList[offerindex]) {
            image.src = "/include/images/map/DevC" + idHolder.value + ".gif";
        } else {
            image.src = "/include/images/map/DevC0.gif";
        }
    }

    if (text && idHolder) {
        if (offerList[offerindex]) {
            text.className = "MapOfferTextEnabled";
        } else {
            text.className = "MapOfferTextDisabled";
        }
    }
}


function getOfferListCSV() {

    if (!offerList)
        return "";//"NULL"?
        
    if (offerList.length == 0)
        return ""; //"NULL"?

    var csv = "";
    var first=true;
    var idHolder;
    var minzoom;

    for (var num = 0; num < offerList.length; num++) {
            if (offerList[num] != null) {
                if (offerList[num]) {
                    idHolder = document.getElementById("offerid" + num);
                    minzoom = document.getElementById("minzoomvisibility" + num);
                    if (idHolder && minzoom.value <= gmap.getZoom()) {

                        if (first) {
                            first = false;
                        } else {
                            csv += ",";
                        }

                        csv += idHolder.value;
                    }
                }
            }
    }
    return csv;
}