﻿com.timmons.srl.findRequestEsri = function() {

    // JScript source code
    var srlRequestJSON;
    var map;
    var srlRequestPosition;
    var bounds;
    var srlFindRequestsMapSettings;
    //var timer = null;
    var panZoomMapControl;
    var _configurationSettings = null;
    var _dataManager = null;
    
    var _initialize = function(configurationSettings, dataManager){
        _configurationSettings = configurationSettings; 
        initializeESRIMap(_configurationSettings);
        
        _dataManager = new com.timmons.srl.dataManager();
        _dataManager.initialize();
        
        /* Initialize Dialog / Modal */
        $("#srlModal").dialog({
            modal: true,
            autoOpen: false,
            height: $(window).height() - 50,
            width: $(window).width() - 50,
            minHeight: 580,
            minWidth: 780,
            zIndex: 5,
            resizable: true,
            show: 'blind',
            hide: 'blind',
            resizeStop: resizeModal
        });      
       $('#srlFindRequestButton').click(function() {
            $('#srlModal').dialog('open');
            if (!map) createFindRequestMap(srlFindRequestsMapSettings);
            else map.resize();
        });

        /* On search close / hide results and comments */

        $("#tbxSearchInput").keypress(function(e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                $('#btnSearch').click();
                return false;
            } else {
                return true;
            }
        });

        $('#btnSearch').click(function() {

            clearESRIMap();
            $('#frComments').hide();
            $('#frResults').hide();

            var email = $('#tbxSearchInput').val();

            if (com.timmons.srl.Utility.isValidEmailAddress(email)) {
            
                showFindRequestLoading();
            
                $.ajax({
                    url: 'WebMethods/SRL_WS.asmx/GetRequestByEmail',
                    data: '{ "emailIn": "' + email + '" }',
                    success: function(msg) {

                        var requests = eval('(' + msg + ')');

                        for (var i = 0; i < requests.length; i++) {

                            requests[i].SrlCommentsList = eval('(' + requests[i].SrlCommentsList + ')');
                            
                        }

                        //renderRequestData(requests);
                        
                        if (requests.length > 0) {

                            hideFindRequestLoading(this, renderRequestData, requests);

                        } else {

                            //var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(20, 80));
                            //movePanZoomControl(topLeft);
                            hideFindRequestLoading();
                            alert('No requests were found that correspond to the email address you entered.\n\nPlease enter a different email address and try again.');
                        }                    
                    }
                });
                
            } else {

                alert('Please enter a valid email address.');
            }
        });

        /* When the window is resized we want to resize the Modal */
        $(window).resize(function() {

            resizeWindow();
        });

        com.timmons.srl.Utility.initializeGenericButtons('#srlModal button');                  
    };



        /* Move Modal element inside of Form so that form submits will work */
        //$("#srlModal").parent().appendTo($("form:first"));
        /* Bind launch of Find Request Modal to click of Find Request Link and initialize ESRI Map */

    function resizeWindow() {
        //console.log("Enter resizeWindow() in findRequestsEsri.js");

        var newModalWidth = $(window).width() - 50;
        var newModalHeight = $(window).height() - 50;

        $("#srlModal").dialog('option', 'height', newModalHeight);
        $("#srlModal").dialog('option', 'width', newModalWidth);

        resizeModal();
        
        //console.log("Exit resizeWindow() in findRequestsEsri.js");
    }

    function resizeModal() {
        //console.log("Enter resizeModal() in findRequestsEsri.js");
        
        $('#srlModal').css('width', $('#srlModal').parent().width() + 'px');
        $('#srlModal').css('height', $('#srlModal').parent().height() - 50 + 'px');

        $('#map_canvas').css('width', $('#srlModal').parent().width() + 'px');
        $('#map_canvas').css('height', $('#srlModal').parent().height() - 50 + 'px');

        $('#srlModal').dialog('option', 'position', 'center');
        
        //console.log("Exit resizeModal() in findRequestsEsri.js");
    }

    function unloadESRIMaps() {
        //console.log("Enter unloadESRIMaps() in findRequestsEsri.js");
        
        //GUnload(); //TODO
        //console.log("Exit unloadESRIMaps() in findRequestsEsri.js");    
    }

    $(document).unload(function() {
        //console.log("Enter unload() in findRequestsEsri.js");
        
        unloadESRIMaps();
        //console.log("Exit unload() in findRequestsEsri.js");
    });

    function initializeESRIMap(_configurationSettings) {
        //console.log("Enter initializeESRIMap() in findRequestsEsri.js");
        
        srlFindRequestsMapSettings = _configurationSettings;    
        //console.log("Exit initializeESRIMap() in findRequestsEsri.js");    
    }

    function showFindRequestLoading() {
        //console.log("Enter showFindRequestLoading() in findRequestsEsri.js");
        
        //$('#srlPageLoadingModal').dialog('open');
        $('#srlPageLoadingModal').show();
        
        //console.log("Exit showFindRequestLoading() in findRequestsEsri.js");
    }

    function hideFindRequestLoading(obj, callback, param) {
        //console.log("Enter hideFindRequestLoading() in findRequestsEsri.js");

        $('#srlPageLoadingImage').fadeTo(1000, 1, function() {

            //$('#srlPageLoadingModal').dialog('close');
            $('#srlPageLoadingModal').hide();

            if (callback) callback.call(obj, param);
        });
        
        //console.log("Exit hideFindRequestLoading() in findRequestsEsri.js");
    }

    function createFindRequestMap(_configurationSettings) {
        //console.log("Enter createFindRequestMap() in findRequestsEsri.js");

        esriConfig.defaults.map.slider = { left: "20px", top: "80px", width: null, height: "100px" };

        dojo.style("map_canvas", "backgroundColor", "white");
        
        //map = new esri.Map("map_canvas");
        map = new esri.Map(
            "map_canvas",
            {
                extent : new esri.geometry.Extent(_configurationSettings.extent)
            }                    
        );
        if(map.loaded == false){
            map.reposition();
        }else{
            dojo.connect(
                map,
                "onLoad",
                function(){
                    map.reposition();
                }
            );
        }
        
        connectCoordinateDisplay();
                    
        var imageParameters = new esri.layers.ImageParameters();
        imageParameters.format = "png24";    
            
        dojo.forEach(
            _configurationSettings.mapServices,
            function(item){
                try{
                    if(item.layerType == com.timmons.srl.configManager.layerType.dynamicMapServiceLayer){
                        var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(
                            item.url, 
                            { "imageParameters": imageParameters , "opacity": item.opacity }
                        );
                        map.addLayer(dynamicMapServiceLayer);
                    }else if(item.layerType == com.timmons.srl.configManager.layerType.tiledMapServiceLayer){
                        var tiledMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(
                            item.url
                        );
                        map.addLayer(tiledMapServiceLayer);
                    }
                }catch(ex){
                    console.warn(ex);
                }
            }
        );

        //console.log("Exit createFindRequestMap() in findRequestsEsri.js");
    }

    function connectCoordinateDisplay(){
        return;
        
         dojo.connect(map, "onMouseMove", function(evt){
        //get mapPoint from event and display the mouse coordinates
        var mp = evt.mapPoint;
        dojo.byId("coordinates").innerHTML = mp.x + ", " + mp.y;
    });
    }

    function clearESRIMap() {
        //console.log("Enter clearESRIMap() in findRequestsEsri.js");
        
        if (map && map != null) {
        
            if(map.graphics && map.graphics != null){
                map.graphics.clear();
            }
            
            if (map.infoWindow && map.infoWindow != null) {
                map.infoWindow.hide();
            }
        }
    }

    function addESRIMarker(latitude, longitude, html) {
        var infoTemplate = new esri.InfoTemplate("&nbsp;", $($('<div></div>').html(html.clone())).html());

        var point = new esri.geometry.Point(longitude, latitude, map.spatialReference);

        var symbol = new esri.symbol.PictureMarkerSymbol(
            "images/ExistingRequest.png", 
            30, 
            30
        );
                        
        var graphic = new esri.Graphic(
            point,
            symbol,
            null,
            infoTemplate
        );

        map.graphics.add(graphic);

        var dojoShape = graphic.getDojoShape();
        if(dojoShape){
            dojo.style(dojoShape.getNode(), "cursor", "pointer");
        }else{
            return;
        }
                
        dojo.connect(
            dojoShape.getNode(),
            "onmousedown",
            function(e) {

                map.disablePan();
                var resultId = $(html).find('.resultId').text();

                $("#frResults .results .result").eq(parseInt(resultId)).click();
            }
        );

        dojo.connect(
            dojoShape.getNode(),
            "onmouseup",
            function(e) {

                map.enablePan();
            }
        );
        
        
        connectCoordinateDisplay();
        
        //zoomShowAllESRIMarkers();
    }

    function addCommentToRequestJSON(commentJSON, commentPosition, requestPosition) {
        var commentsLength = srlRequestJSON[requestPosition].SrlCommentsList.length;

        for (var p = commentsLength; p > commentPosition; p--) {

            srlRequestJSON[requestPosition].SrlCommentsList[p] = srlRequestJSON[requestPosition].SrlCommentsList[p - 1];
        }

        srlRequestJSON[requestPosition].SrlCommentsList[commentPosition] = commentJSON;
        
    }

    function renderNewComment(commentJSON) {
        
        var requestComment = $('#frComments .requestCommentTemplate').html();

        var commentsElem = $('#frComments .comments');

        $(commentsElem).prepend('<div class="requestCommentTemplate" style="display:none">' + requestComment + '</div>');

        $(commentsElem).prepend('<div class="comment">' + requestComment + '</div>');

        var comment = $('#frComments .comments .comment').eq(0);

        $(comment).find('.commentAgo').html('');
        $(comment).find('.commentDate').html(commentJSON.CommentDate);
        $(comment).find('.commentDetails').html(commentJSON.Comment);
        $(comment).find('.commentPostedBy').html(commentJSON.CommentBy);
        $(comment).find('.commentTime').html(commentJSON.CommentTime);

        $(commentsElem).animate({ scrollTop: 0 }, 500, function() {
            $(comment).effect('pulsate', 500);
        });

        addCommentToRequestJSON(commentJSON, 0, srlRequestPosition);
        
        //console.log("Exit renderNewComment() in findRequestsEsri.js");    
    }

    function renderRequestData(requestJSON) {
        //console.log("Enter renderRequestData() in findRequestsEsri.js");
        
        srlRequestJSON = requestJSON;

        var requestResult = $('#frResults .requestResultTemplate').html();
        
        $('#frResults .results').empty();

        $('#frResults .results').append('<div class="requestResultTemplate" style="display:none">' + requestResult + '</div>');
        $('#frResults .results').find('.resultTip').attr('id', '');

        $('#frResultsNumMatches').text(requestJSON.length);
        $('#frResultsSearchText').text($('#tbxSearchInput').val());

        //$('#frResults').dialog('open');

        $('#frResults').fadeIn('fast', function() {

            //$('#srlModal #lmc3d').css('cssText', 'position: absolute; left: 340px !important; top: 80px !important;');

            $('#map_canvas_zoom_slider').css('left', 340);
            $('#map_canvas_zoom_slider').css('top', 80);

            for (p in requestJSON) {
                $('#frResults .results').append('<div class="result">' + requestResult + '</div>');
            }

            $('#frResults .results .result').hide();

            var points = new esri.geometry.Multipoint();
            var lastX=0;
            var lastY=0;
            $('#frResults .results .result').each(
                function(i) {

                    $(this).find('.ago').html('');
                    $(this).find('.requestDateValue').html(requestJSON[i].InitDate);
                    $(this).find('.requestDescription').html(requestJSON[i].DESCRIPTION);

                    $(this).attr('rel', '#resultTip' + (i + 1));
                    $(this).children('.resultTip').attr('id', 'resultTip' + (i + 1));
                    if (requestJSON[i].Status != "CLOSED") {
                        if (requestJSON[i].WORKORDERID > 0) {
                            $(this).children('.resultTip').find('.requestWorkOrder').find('.field').html("Work Order");
                            $(this).children('.resultTip').find('.requestWorkOrder').find('.value').html("***Assigned***");
                        }
                    }
                    $(this).children('.resultTip').find('.requestStatus').find('.value').html(requestJSON[i].Status);
                    $(this).children('.resultTip').find('.requestId').find('.value').html(requestJSON[i].REQUESTID);

                    var newElem = $(this).children('.resultTip').clone();
                    $(newElem).append('<span class="resultId" style="display: none;">' + i + '</span>');
                    $(newElem).attr('id', '');
                    $(newElem).attr('class', 'gTipContent');
                    
                    addESRIMarker(srlRequestJSON[i].SRY, srlRequestJSON[i].SRX, newElem);
                    
                    lastX = srlRequestJSON[i].SRX;
                    lastY = srlRequestJSON[i].SRY;
                    
                    $(newElem).show();

                    var point = new esri.geometry.Point(srlRequestJSON[i].SRX, srlRequestJSON[i].SRY, map.spatialReference);
                    points.addPoint(point);
                    
                }
            );        
            
            if(points.points.length>1){
                map.setExtent(points.getExtent().expand(3));
            }else{
            if(points.points.length == 1)
                var point = new esri.geometry.Point(lastX-10, lastY-10, map.spatialReference);
                points.addPoint(point);

                map.setExtent(points.getExtent().expand(100));
            }
                                        
            bindRequestEvents();
        });

        //zoomShowAllESRIMarkers();
        
        //console.log("Exit renderRequestData() in findRequestsEsri.js");
    }

    function bindRequestEvents() {
        //console.log("Enter bindRequestEvents() in findRequestsEsri.js");
        
        /*$("#frResults").hover(
        function() {
                
        },
        function() {
        $(this).find('.result').removeClass('ui-state-hover');
        }
        );*/

        $("#frResults .results .result").hover(
            function() {
                $("#frResults .results .result").removeClass('ui-state-hover');
                $(this).addClass('ui-state-hover');
            },
            function() {
                $(this).removeClass('ui-state-hover');
            }
        );

        $("#frResults .results .result").each(function(i) {

            $(this).click(function() {

                if (!$(this).hasClass('ui-state-active')) {

                    //var newElem = $(this).children('.resultTip').clone();
                    //$(newElem).attr('id', '');
                    //$(newElem).attr('class', 'gTipContent');

                    //map.setCenter(new GLatLng(srlRequestJSON[i].Lng, srlRequestJSON[i].Lat), 16);
                    //map.openInfoWindow(map.getCenter(), $(newElem).get(0));
                    //$(newElem).show();

    //                var pext = new esri.geometry.Extent({ "xmin": srlRequestJSON[i].Lng, "ymin": srlRequestJSON[i].Lat, "xmax": srlRequestJSON[i].Lng, "ymax": srlRequestJSON[i].Lat, "spatialReference": map.spatialReference });
    //                pext.xmin = pext.xmin - 5;
    //                pext.xmax = pext.xmax + 5;
    //                pext.ymin = pext.ymin - 5;
    //                pext.ymax = pext.ymax + 5;
    //                map.setExtent(pext.expand(100.0));

                    $("#frResults .results .result").removeClass('ui-state-active');
                    $(this).addClass('ui-state-active');

                    showRequestComments(this, i);
                }
            });
        });

        $("#frResults .results .result").each(function(i) {
            $(this).fadeIn("slow", function() {

                $(this).cluetip({
                    local: true,
                    cursor: 'pointer',
                    showTitle: false,
                    arrows: true,
                    cluetipClass: 'jtip',
                    mouseOutClose: true,
                    fx: {
                        open: 'show', // can be 'show' or 'slideDown' or 'fadeIn'
                        openSpeed: 'fast'
                    }
                });
            });
        });
        connectCoordinateDisplay();
        //console.log("Exit bindRequestEvents() in findRequestsEsri.js");
    }

    function showRequestComments(elem, i) {
        //console.log("Enter showRequestComments() in findRequestsEsri.js");
        
        srlRequestPosition = i;

        $('#frAddCommentForm').slideUp('slow');

        var requestId = $(elem).find('.requestId .value').text();

        $('#HFRequestID').val(requestId);

        var requestComment = $('#frComments .requestCommentTemplate').html();

        $('#frComments .comments').empty();

        $('#frComments .comments').append('<div class="requestCommentTemplate" style="display:none">' + requestComment + '</div>');


        if (srlRequestJSON[i].RecordLocked == true) {
            $('#frAddCommentLink').hide();
            $('#frRequestLocked').show();
            $('#frRequestLocked').html('The ability to add comments is currently disabled. This request is currently assigned for resolution. Please check back later for an update.');
        }
        else {
            $('#frAddCommentLink').show();
            $('#frRequestLocked').html('');
            $('#frRequestLocked').hide();
        }

        for (p in srlRequestJSON[i].SrlCommentsList) {

            $('#frComments .comments').append('<div class="comment">' + requestComment + '</div>');
        }

        // Comment, CommentBy, CommentDate, RequestId
        // commentPostedBy commentDate commentAgo commentDetails

        $('#requestIdComments').html(requestId);

        $('#requestDescription').html(' - ' + srlRequestJSON[i].DESCRIPTION);

        $('#frComments .comments .comment').each(function(j) {

            if (srlRequestJSON[i].SrlCommentsList[j]) {

                $(this).find('.commentAgo').html('');
                $(this).find('.commentDate').html(srlRequestJSON[i].SrlCommentsList[j].CommentDate);
                $(this).find('.commentDetails').html(srlRequestJSON[i].SrlCommentsList[j].Comment);
                $(this).find('.commentPostedBy').html(srlRequestJSON[i].SrlCommentsList[j].CommentBy);
                $(this).find('.commentTime').html(srlRequestJSON[i].SrlCommentsList[j].CommentTime);
            }
        });

        $('#frComments').show();
        $('#frComments').css('visibility', 'hidden');
        $(elem).effect("transfer", { to: "#frComments2" }, 400, function() {

            $('#frComments').hide().css('visibility', 'visible').fadeIn('fast');
        });

        $('#frAddCommentLink').html('Add a Comment');
        $('#frAddCommentForm').stop().hide();
        $('#frAddCommentLink').unbind();

        $('#frAddCommentLink').click(function() {

            if ($("#frAddCommentForm").is(":hidden")) {

                $('#frAddCommentForm').stop().slideDown('slow');
                $('#frAddCommentLink').html('Close add a comment');

            } else {

                $('#frAddCommentForm').stop().slideUp('slow');
                $('#frAddCommentLink').html('Add a Comment');
            }
        });

        $('#frAddCommentSubmit').unbind();

        $('#frAddCommentSubmit').click(function() {

            var comment = $('#frAddCommentText').val();

            if (comment) {
                $.ajax({
                    url: 'WebMethods/SRL_WS.asmx/AddNewComment',
                    data: '{ "commentIn": "' + comment + '", "requestId":' + requestId + '}',
                    success: function(msg) {

                        var commentJSON = eval('(' + msg + ')');
                        renderNewComment(commentJSON);
                        $('#frAddCommentText').val('')
                    }
                });
            } else {

                alert('Please enter a comment.');
            }
        });

        //console.log("Exit showRequestComments() in findRequestsEsri.js");
    }

    function hideRequestComments() {
        //console.log("Enter hideRequestComments() in findRequestsEsri.js");
        
        $('#frComments').hide();
        
        //console.log("Exit hideRequestComments() in findRequestsEsri.js");
    }

    //    var markerStyle = esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE;
    //    var lineStyle = esri.symbol.SimpleLineSymbol.STYLE_SOLID;
    //    var lineColor = new dojo.Color("white");
    //    var lineSymbol = new esri.symbol.SimpleLineSymbol(lineStyle, lineColor, 1);
    //    var fillColor = new dojo.Color([245, 128, 37, 1]);
    //    var symbol = new esri.symbol.SimpleMarkerSymbol(markerStyle, 15, lineSymbol, fillColor);

    return {
        //Declare public properties here
        //Declare public methods here
        initialize: function(configurationSettings) {
            _initialize(configurationSettings);
        }
    };

};
