﻿//initialize/general vars
var lat = 43.397;
var lng = -116.644;
var latlng;
var infowindow;
var marker;
var point;
var geocoder;
var maxMarkers = 100;
var center;
/////////////////

//circle vars
var circle;
var circleRadius = 50;
var doingRadius = false;
var dragListener;
//////

//line vars
var lineColor = '#3b3328';
var lineWidth = 2;
var lineOpacity = .8;
var fillColor = '#5f0606';
var fillOpacity = .3;
//////

//boundary vars
var square;
var squareMaxLat;
var squareMaxLng;
var squareMinLat;
var squareMinLng;
var clickListener;
var doingBoundary = false;
var endLineListener;
var squareClickListener;
var updateListener;
var boundaryClickCount = 0;
var pOne;
var pTwo;
var pThree;
var pFour;
var pFive;
var polyline;
var polyline2;
//////////

var resetCount = 0;
var m_map;
var zoomlevel;


//polyline vars
var options = { maxVertices: 2 };
var lineCounter_ = 0;
var shapeCounter_ = 0;
var markerCounter_ = 0;
var colorIndex_ = 0;
var featureTable_;
/////////////////////

//random temp vars
var a;
var b;
//////////////////

var sizes = [53, 56, 66, 78, 90];
var styles_ = [];

var styles = [[
{
    url: '../m1.png',
    height: 35,
    width: 35,
    opt_anchor: [16, 0],
    opt_textColor: '#FF00FF'
},
      {
          url: '../m1.png',
          height: 45,
          width: 45,
          opt_anchor: [24, 0],
          opt_textColor: '#FF0000'
      },
      {
          url: '../m1.png',
          height: 55,
          width: 55,
          opt_anchor: [32, 0]
}], ];

var markers = [];
var markerClusterer = null;

//postback clientID vars
var lblEndingPointID;
var lblListingInfoID;
var currentradius;
var args;
///////////////

//listing vars
var hostweburl = '';
var hostweburloriginal = '';
var template;
var listingItemCount = 0
var cicon;

var viewingid = 0;

function listing() {
    var id;
    var pt;
    var html;
    var marker;
    var type;
}

var didPaging = false;
///////////////////////

var gIcon1;
var gIcon2;
var gIcon3;

var enablehover = false;
var tabid;
var activeOnly;
var useMLS;
var modid;
var pullFromWebservice;

var itemiconimage = '';
var itemiconimagealt = '';

function loadMap(currentradiusARG, lblEndingPointIDARG, lblListingInfoIDARG, lblTemplateIDARG, itemUrl, itemUrlAlt, clearItemUrl, groupedIcon1Url, groupedIcon2Url, groupedIcon3Url, radiusIconUrl, hostweburlTemp, hostweburloriginalTemp, enablehovertemp, tabidTEMP, activeOnlyTEMP, useMLSTEMP, modidTEMP, pullFromWebserviceTEmp) {
    if (GBrowserIsCompatible()) {
        $.ajaxSetup({ cache: false, contentType: "application/x-www-form-urlencoded;charset=iso-8859-1" });
        gIcon1 = groupedIcon1Url;
        gIcon2 = groupedIcon2Url;
        gIcon3 = groupedIcon3Url;
        hostweburl = hostweburlTemp;
        hostweburloriginal = hostweburloriginalTemp;

        tabid = tabidTEMP;
        activeOnly = activeOnlyTEMP;
        useMLS = useMLSTEMP;
        modid = modidTEMP;
        pullFromWebservice = pullFromWebserviceTEmp;
        
        itemiconimage = itemUrl;
        itemiconimagealt = itemUrlAlt;

        if (enablehovertemp == "true")
            enablehover = true;
        else
            enablehover = false;

        listings = new Array();
        currentradius = document.getElementById(currentradiusARG);
        lblEndingPointID = document.getElementById(lblEndingPointIDARG);
        lblListingInfoID = document.getElementById(lblListingInfoIDARG);
        template = document.getElementById(lblTemplateIDARG).value;

        latlng = new GLatLng(lat, lng);
        //get map div
        var mapD = document.getElementById("map_canvas");

        //return if the map is null
        if (!mapD)
            return;

        var host = window.location.host;

        if (eval("typeof setupicons == 'function'")) {
            setupicons(itemUrl, radiusIconUrl, clearItemUrl);
        }

        if (eval("typeof setupiconswithalt == 'function'")) {
            setupiconswithalt(itemUrl, itemUrlAlt, radiusIconUrl, clearItemUrl);
        }        

        gicon = new GIcon();
        gicon.image = gicon.image = "http://" + host + "/DotNetNuke/DesktopModules/ItemLocater/img/group_icon.png";
        gicon.iconSize = new GSize(14, 15);
        gicon.iconAnchor = new GPoint(7, 15);
        gicon.infoWindowAnchor = new GPoint(14, 0);
        gicon.maxHeight = 15;

        //make a new map in the map div
        m_map = new GMap2(mapD);
        m_map.enableScrollWheelZoom();
        m_map.addControl(new GOverviewMapControl());
        mapControl = new GSmallMapControl();
        m_map.addControl(mapControl);
        m_map.setCenter(latlng, 5);

        geocoder = new GClientGeocoder();

        LoadMarkers(false);

    }
}

//this function will get called after an ajax postback
//it needs to take vars and reset the client Id's of the inputs
//that hold points on the map for
function resetMapOnPostback(currentradiusARG, lblEndingPointIDARG, lblListingInfoIDARG, lblTemplateIDARG) {
    //check which type of search they did before
    if (doingRadius)
        drawCircleAroundMarker();
    if (doingBoundary) {

    }

    listings = new Array();
    currentradius = currentradiusARG;
    lblEndingPointID = lblEndingPointIDARG;
    lblListingInfoID = lblListingInfoIDARG;
    template = lblTemplateIDARG.value;

    if (didPaging) {
        LoadMarkers(true);
    }
    else if (lblEndingPointID.value == "x")
        LoadMarkers(false);
    else
        LoadMarkers(true);
}

function LoadMarkers(reset) {
    //$.unblockUI();
    if (markerClusterer != null) {
        markerClusterer.clearMarkers();
    }

    if (markers.length > 0) {
        ClearMarkers();
    }

    //get index of lat and lng and strip them out

    //alert(pullFromWebservice);
    if (pullFromWebservice == "true") {
        //alert(hostweburloriginal);

        var ajaxurl = "/desktopmodules/itemlocater/MLS_Map.asmx/GetSearchList";
        //alert(ajaxurl);
        $.blockUI({ message: '<h1><img src="/desktopmodules/itemlocater/img/loader.gif" /> Processing, please wait.</h1>' });
        $.ajax({
            type: "POST",
            url: ajaxurl,
            data: "{'tabid':'" + tabid + "', 'activeOnly':'" + activeOnly + "', 'useMLS':'" + useMLS + "','moduleID':'" + modid + "', 'lblPoints':'" + lblEndingPointID.value + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                //AjaxSucceeded(msg);
                //alert(msg["d"]);
                $.unblockUI();
                FinishMarkers(reset, msg["d"]);
                
            },
            error: function(msg) {
            alert('webrequest failed');
            $.unblockUI();
            }
        });
        //alert(idValue);
    }
    else {
        idValue = lblListingInfoID.value;
        FinishMarkers(reset, idValue);
    }
}

function FinishMarkers(reset, idValue) {
    idValue = idValue.replace("[", "").replace("]", "");
    var west = null;
    var east = null;
    var north = null;
    var south = null;

    var tempLst = idValue.split("^");

    //alert(idValue);

    if (tempLst.length < 2) {
        if (tempLst.length == 1) {
            if (tempLst[0].length < 10) {
                return;
                //there could be one listing in the list, if there is but its not a real listing it will be less
                //than 10 chars long, otherwise there is one real item in the list and we'll map it
            }
        }
        else {
            return;
        }
    }

    markers = new Array(tempLst.length);

    for (i = 0; i < tempLst.length; i++) {
        var listingvals = tempLst[i].split("|");

        if (listingItemCount == 0)//counts how many items of the listing the code behind passed in
            listingItemCount = listingvals.length;

        listings[i] = new listing();
        listings[i].id = listingvals[0];
       
        var latlngT = new GLatLng(listingvals[1], listingvals[2]);

        listings[i].pt = latlngT;

        var markerT = new GMarker(latlngT, { icon: cicon });

        if (eval("typeof il_markerevent1 == 'function'")) {
            il_markerevent1(markerT);
        }

        if (eval("typeof il_markerevent2 == 'function'")) {
            il_markerevent2(markerT);
        }

        if (eval("typeof il_iconevent == 'undefined'")) {
            GEvent.addListener(markerT, "click", findAndOpen);
        }
        else
            GEvent.addListener(markerT, iconevent, findAndOpen);

        if (eval("typeof setaltimage != 'undefined'")) {
            GEvent.addListener(markerT, "mouseover", function() { markerT.setImage(itemiconimagealt); });
            GEvent.addListener(markerT, "mouseout", function() { markerT.setImage(itemiconimage); });
        } 

        markers[i] = markerT;
        listings[i].marker = markerT;

        if (west == null || west.lng() > latlngT.lng()) {
            west = latlngT;
        }
        if (east == null || east.lng() < latlngT.lng()) {
            east = latlngT;
        }
        if (north == null || north.lat() < latlngT.lat()) {
            north = latlngT;
        }
        if (south == null || south.lat() > latlngT.lat()) {
            south = latlngT;
        }
    }

    if (!reset) {
        if (listings.length > 0) {
            var edges;
            edges = new Array(4);
            edges[0] = west;
            edges[1] = east;
            edges[2] = south;
            edges[3] = north;
            // alert(edges);
            center = new GLatLng(south.lat() + (north.lat() - south.lat()) / 2,
                    east.lng() + (west.lng() - east.lng()) / 2);

            //alert("set Center line 327");
            m_map.setCenter(center, 13);
            for (var x = 0; x < edges.length; x++) {
                latlngT = edges[x];


                //alert(latlngT);
                if (!m_map.getBounds().contains(latlngT)) {

                    var zoomlevel = m_map.getZoom();
                    if (zoomlevel <= 4) {
                        continue;
                    }
                    m_map.zoomOut();
                    x--;
                }
            }
        }
    }

    var zoom = -1;
    var size = -1;
    var style = -1;

    if (listings.length > maxMarkers) {
        markerClusterer = new MarkerClusterer(m_map, sizes, styles_, markers);
    }
    else {
        PutMarkersOnMap();
    }
    
     var sval = "ssid";
     var rval = "";
     sval = sval.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
     var regexS = "[\\?&]" + sval + "=([^&#]*)";
     var regex = new RegExp(regexS);
     var results = regex.exec(window.location.href);
     if (results == null)
	 rval = "";
     else
	 rval = results[1];
     rval = decodeURI(rval);

     //alert(rval);

     if(rval != ""){
	    $.blockUI({ message: $('.ssActivate') });
     }
     
     if (eval("typeof il_endmarkers == 'function'")) {
            il_endmarkers();
        }
         

}


function ClearMarkers() {
    // alert("here");
    for (var i = 0; i < markers.length; i++) {
        m_map.removeOverlay(markers[i]);
    }
}

function PutMarkersOnMap() {
    for (var i = 0; i < markers.length; i++) {
        m_map.addOverlay(markers[i]);
    }
}

function createListingPopoutHtml(vals) {
    var returnHtml = template;
    for (var i = 0; i < vals.length; i++) {
        var tempStr = "[" + i + "]";
        if (returnHtml.match(tempStr)) {
            returnHtml = returnHtml.replace(tempStr, vals[i]);
        }
    }
    return returnHtml;
}

function findAndOpen() {
    $.ajaxSetup({ cache: false, contentType: "application/x-www-form-urlencoded;charset=iso-8859-1" });
    for (var i = 0; i < listings.length; i++) {
        if (listings[i].marker.getLatLng() == this.getLatLng()) {
            TempID = listings[i].id;

            var tID = TempID + '';
            var path = '';
            for (xx = 0; xx < tID.length; xx++) {
                //path += tID[xx] + "/";
                path += tID.charAt(xx) + "/";
            }

            var baseurl = hostweburl + path + "jsondata_" + TempID + ".txt?callback=?";
            $.getJSON(baseurl, function(data) {
            //nothing here, the function readjson gets called from the data in the file.
            });
            
            if (eval("typeof il_endfindAndOpen == 'function'")) {
                il_endfindAndOpen(TempID);
            }
        }
    }
}

function SetHoverClass(tr, evenorodd) {
    if (evenorodd == 'even') {
        $(tr).attr('class', 'IL_ListTableRow2');
    }
    else if (evenorodd == 'odd') {
        $(tr).attr('class', 'IL_ListTableRow');
    }
}

var tempMarker;
var TempID = 0;

function SetHoverClassInitial(tr) {
    $(tr).attr('class', "IL_ListTableRowHover");
}

function FindAndShowInfowindowNoHover(itemid) {
    $.ajaxSetup({ cache: false, contentType: "application/x-www-form-urlencoded;charset=iso-8859-1" });
    TempID = itemid;
    var tID = TempID + '';
    var path = '';
    for (i = 0; i < tID.length; i++) {
        //path += tID[i] + "/";
        path += tID.charAt(i) + "/";
    }

    var baseurl = hostweburl + path + "jsondata_" + itemid + ".txt?callback=?";
    //console.log(baseurl);
    $.getJSON(baseurl, function(data) {
    //nothing here, the function readjson gets called from the data in the file.
    });
    
    if (eval("typeof il_endFindAndShowInfowindowNoHover == 'function'")) {
                il_endFindAndShowInfowindowNoHover(itemid);
    }
}

function FindAndShowInfowindow(itemid, tr) {
    $.ajaxSetup({ cache: false, contentType: "application/x-www-form-urlencoded;charset=iso-8859-1" });
    SetHoverClassInitial(tr);
    TempID = itemid;
    var tID = TempID + '';
    var path = '';
    for (i = 0; i < tID.length; i++) {
        //path += tID[i] + "/";
        path += tID.charAt(i) + "/";
    }

    var baseurl = hostweburl + path + "jsondata_" + itemid + ".txt?callback=?";
    //console.log(baseurl);
    $.getJSON(baseurl, function(data) {
        //nothing here, the function readjson gets called from the data in the file.
    });
    
    if (eval("typeof il_endFindAndShowInfowindow == 'function'")) {
                il_endFindAndShowInfowindow(itemid);
    }
}

function readjson(jsondata) {    
    if (tempMarker) {
        m_map.removeOverlay(tempMarker);
    }

    var match = template.match(/\[(\d)*\]/g);
    var matchstr = match + '';
    var matcharr = matchstr.split(',');
    var tempTemplate = template;
    for (mm = 0; mm < matcharr.length; mm++) {
        var nestedint = matcharr[mm].replace("[", "").replace("]", "");
        //console.log(tempTemplate + '-----nestedint: ' + nestedint);
        tempTemplate = tempTemplate.replace(matcharr[mm], jsondata[nestedint].replace("[HOSTWEBURL]", hostweburloriginal));
    }

    var tempStr = jsondata;
    //alert(TempID);

    var didFind = false;
    for (var i = 0; i < listings.length; i++) {
        if (listings[i].id == TempID) {
            //alert('found');
            tempMarker = new GMarker(listings[i].pt, { icon: bicon });
            m_map.addOverlay(tempMarker);
            tempMarker.openInfoWindowHtml(tempTemplate);
            viewingid = listings[i].id;
            didFind = true;
        }
    }
    if (didFind) {
        if (eval("typeof il_endreadjson == 'function'")) {
                    il_endreadjson(viewingid);
        }
       // m_map.setZoom(12);
    }
}

function doRadiusSearch(p) {
    //alert(p);
    lblEndingPointID.value = p.lat() + "," + p.lng();
    setUpAjaxSearch();
}

function doMapAddress(address) {
    geocoder.getLatLng(address, function(point) {
        if (!point) {
            alert(address + "address not found");
        }
        else {
            //remove marker before we replace it with the new address
            if (marker) {
                m_map.removeOverlay(marker)
                if (dragListener != null)
                    m_map.removeListener(dragListener);
            }

            lblEndingPointID.value = point.lat() + "," + point.lng();
            m_map.setCenter(point);
            marker = new GMarker(point, { draggable: true, bouncy: true, icon: ricon });
            m_map.addOverlay(marker);

            GEvent.addListener(marker, "dragend", function(p) {
                doRadiusSearch(p);
            });

            drawCircleAroundMarker();
            marker.openInfoWindowHtml(address);
        }
    }
  );
}



//this function gets called right before an ajax postback
//DoAjaxSearch is located on the ViewValiceMap.aspx page
function setUpAjaxSearch() {
    DoAjaxSearch();
}

//This function resets the map to its original !postback state when the page
//first loads, this should be called when they click to start a radius or boudary search
function resetMap() {
    if (marker) {
        if (dragListener != null)
            m_map.removeListener(dragListener);

        m_map.removeOverlay(marker);
    }
    if (square) {
        square.disableEditing();
        m_map.removeOverlay(square);
    }
    if (circle)
        m_map.removeOverlay(circle);
    if (polyline) {
        polyline.disableEditing();
        m_map.removeOverlay(polyline);
    }
    pOne = null;
    pTwo = null;
    pThree = null;
    pFour = null;

    boundaryClickCount = 0;
    if (clickListener != null)
        GEvent.removeListener(clickListener);

    if (updateListener != null)
        GEvent.removeListener(updateListener);

    doingBoundary = false;
    doingRadius = false;

    lblEndingPointID.value = "x";
}

//this function should be called to initialize the radius circle polygon if it needs it
function initRadius() {
    doingRadius = true;
    var tempPoint = m_map.getCenter();
    marker = new GMarker(tempPoint, { draggable: true, bouncy: true, icon: ricon });
    m_map.addOverlay(marker);
    lblEndingPointID.value = tempPoint.lat() + "," + tempPoint.lng();
    GEvent.addListener(marker, "dragend", function(p) {
        doRadiusSearch(p);
    });

    var ddl = $('#SSRadiusDropDownList')
    if (ddl != null) {


        var zoomlvl = m_map.getZoom();
        if (zoomlvl <= 3) {
            //ddl.value = 50;
            $(ddl).val('50');
            circleRadius = 50;
            currentradius.value = 50;
            //10 miles
        }
        if (zoomlvl <= 7 && zoomlvl >= 4) {
            // ddl.value = 25;
            $(ddl).val('25');
            circleRadius = 25;
            currentradius.value = 25;
            //10 miles
        }
        if (zoomlvl <= 11 && zoomlvl >= 8) {
            //ddl.value = 10;
            $(ddl).val('10');
            circleRadius = 10;
            currentradius.value = 10;
            //10 miles
        }
        if (zoomlvl <= 13 && zoomlvl >= 12) {
            //ddl.value = 3;
            $(ddl).val('3');
            circleRadius = 3;
            currentradius.value = 3;
            //5 miles
        }
        if (zoomlvl >= 14) {
            //ddl.value = 1;
            $(ddl).val('1');
            circleRadius = 1;
            currentradius.value = 1;
            //5 miles
        }

    }



    drawCircleAroundMarker();
}

//this function should be clled to initialize the boundary square polygon
function initBoundary() {
    doingBoundary = true;
    clickListener = GEvent.addListener(m_map, "click", function(a, b) {
        boundaryClickCount++;

        //we are setting the corners of the square, point 1 and point 3, they are then used
        //on the "endline" event of the polyline to make the reset of the box
        if (boundaryClickCount == 1) {
            pOne = b;
        }
        else if (boundaryClickCount == 2) {

            pThree = b;
            if (clickListener != null)
                GEvent.removeListener(clickListener);
        }
    });
}

function startRadiusSearch() {
    resetMap();
    initRadius();
    drawCircleAroundMarker();
}

function startBoundarySearch() {
    resetMap();
    initBoundary();
    startLine();
}

function doChangeRadius(tempNum) {
    circleRadius = tempNum;
    drawCircleAroundMarker();
}

function drawCircleAroundMarker() {
    if (circle) {
        m_map.removeOverlay(circle);
    }

    var bounds = new GLatLngBounds();

    var circlePoints = Array();
    var radiuscenter = marker.getPoint();

    with (Math) {
        var d = circleRadius / 3963.189; // radians

        var lat1 = (PI / 180) * radiuscenter.lat(); // radians
        var lng1 = (PI / 180) * radiuscenter.lng(); // radians

        for (var a = 0; a < 361; a++) {
            var tc = (PI / 180) * a;
            var y = asin(sin(lat1) * cos(d) + cos(lat1) * sin(d) * cos(tc));
            var dlng = atan2(sin(tc) * sin(d) * cos(lat1), cos(d) - sin(lat1) * sin(y));
            var x = ((lng1 - dlng + PI) % (2 * PI)) - PI; // MOD function
            var point = new GLatLng(parseFloat(y * (180 / PI)), parseFloat(x
* (180 / PI)));
            circlePoints.push(point);
            bounds.extend(point);
        }

        if (d < 1.5678565720686044) {
            circle = new GPolygon(circlePoints, lineColor, lineWidth, lineOpacity,
fillColor, fillOpacity);
        }
        else {
            circle = new GPolygon(circlePoints, lineColor, lineWidth, lineOpacity);
        }

        m_map.addOverlay(circle);
    }
}

function startLine() {
    polyline = new GPolyline([], lineColor);
    m_map.addOverlay(polyline);
    polyline.enableDrawing(options);

    endLineListener = GEvent.addListener(polyline, "endline", function() {
        this.setStrokeStyle({ color: "##5f0606", opacity: 0.0 }); //make the line disappear
        drawSquare();
    });

}

//takes the two points point 1 and point 3 and creates two new points by reversing the lat 
//and lng of the first
//two points and creates a box
function drawSquare() {
    pTwo = new GLatLng(pOne.lat(), pThree.lng());
    pFour = new GLatLng(pThree.lat(), pOne.lng());
    var linepoints = [];
    linepoints[0] = pOne;
    linepoints[1] = pTwo;
    linepoints[2] = pThree;
    linepoints[3] = pFour;
    linepoints[4] = pOne;

    square = new GPolygon(linepoints, lineColor, 2, 0.7, fillColor, 0.1);
    m_map.addOverlay(square);
    square.enableEditing({ onEvent: "mouseover" });
    square.disableEditing({ onEvent: "mouseout" });

    GetAndSetSquareVertexes();
    updateListener = GEvent.addListener(square, "lineupdated", function() {
        GetAndSetSquareVertexes();
    });

    GEvent.removeListener(endLineListener);
}

function GetAndSetSquareVertexes() {
    var count = square.getVertexCount();
    var str = "";
    for (i = 0; i < count - 1; i++) {
        var num1 = roundNumbers(square.getVertex(i).lat());
        var num2 = roundNumbers(square.getVertex(i).lng());
        if (str == "") {
            str = num1 + "," + num2;
        }
        else {
            str = str + "^" + num1 + "," + num2;
        }
    }
    lblEndingPointID.value = str;
}

var numTemp = 0;
function roundNumbers(number) {
    numTemp = number;
    return Math.round(numTemp * 10000) / 10000
}


