/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
(function($){

    var settings =
    {
        map:null,
        taburl:'http://eb8730wgrb/monolit_maps/index.php/gps/gps_c/loadView',
        loginurl:'http://eb8730wgrb/monolit_maps/index.php/gps/gps_c/showLogin',
        devicesurl:'http://eb8730wgrb/monolit_maps/index.php/gps/gps_c/getDevices',
        historyurl:'http://eb8730wgrb/monolit_maps/index.php/gps/gps_c/getHistory',
        printurl:'http://eb8730wgrb/monolit_maps/index.php/gps/gps_c/printView',
        jmsurl:'http://192.168.0.93/servletjms/amq',
        tabsid:'gps_panel',
        deviceTab:'tabsDevice',
        appendDiv:'gpsConsolePlacer',
        devicesDiv:'devices_list',
        historyDiv:'history_list',
        imgDevOnUrl:'',
        imgDevOffUrl:'',
        imgTrackUrl :'http://eb8730wgrb/monolit_maps/system/application/addons/images/icons/audi_icon.gif',
        imgTrackHistoryUrl:'http://eb8730wgrb/monolit_maps/system/application/addons/images/icons/audi_icon.gif',
        zoomLabelDisplay : 8
    };

    var map;
    var gpsmarkers;
    var gpshistorymarkers;
  


    var device = function()
    {
        var isauto = false;
        var name;
        var id = 0;
       
        var positions   = [];
        this.addMarker    = addMarker;
        this.removeMarker = removeMarker;
        this.removeAllMarkers = removeAllMarkers;
        this.countMarkers     = countMarkers;
        this.addName          = addName;
        this.getName          = getName;
        this.getBounds        = getBounds;
        this.isAutoZoom       = isAutoZoom;
        this.getAutoZoom      = getAutoZoom;
       

        function getAutoZoom()
        {
            return  this.isauto;
        }

        function isAutoZoom(b)
        {
            this.isauto = b;
        }

       

        function getBounds()
        {
            bounds = new OpenLayers.Bounds();
            for(var i=0; i<positions.length;i++ )
            {
                bounds.extend(positions[i].lonlat);
            }
            return bounds
        }

        function addName(n)
        {
            this.name = n;
        }

        function getName()
        {
            return this.name;
        }

        function addMarker(marker)
        {
            positions.push(marker);
            gpsmarkers.addMarker(marker);
        }

        function countMarkers()
        {
            return positions.length;
        }

        function removeMarker(i)
        {
            if (positions[i] != null)
            {
                gpsmarkers.removeMarker(positions[i]);
                positions[i].destroy();
                positions[i] = null;
                positions.splice(i,1);
            }
        }

        function removeAllMarkers()
        {
            for(var i=0; i<positions.length;i++ )
            {
                this.removeMarker(i);
            }
        }
    }

    // Private Variables and Methods
    var gpsconsole =
    {
        selectDeviceList:document.createElement("select"),
        jmsinterval:null,
        activeDevices:[],
        setTabs:function()
        {
            jQuery.ajax({ url: settings.taburl, async: false, success: function(data){
                    var dom = jQuery(data);
                    jQuery("#"+settings.appendDiv).append(dom);
                    jQuery("#"+settings.tabsid+"> ul").tabs();
                   
            }});
        },
        maplistener:function()
        {
           if (map.getZoom() >= settings.zoomLabelDisplay)
                jQuery(".gpsMarkerLabel").css("visibility","visible");
           else
               jQuery(".gpsMarkerLabel").css("visibility","hidden");

        },
        createDevice:function(dom)
        {

             var streetName = "";
             var deviceDiv = document.createElement('div');
             var onOffDiv  = document.createElement('div');
             var devNameDiv = document.createElement('a');
             var devAddressDiv = document.createElement('span');
             
             var dName = jQuery(dom).find('devicename').text();
             var dId = jQuery(dom).find('deviceident').text();
             var firstEhis = jQuery(dom).find('deviceehis').text();
             var x = jQuery(dom).find('devicex').text();
             var y = jQuery(dom).find('devicey').text();



             var img = jQuery("<img  src='"+settings.imgDevOffUrl+"' />");
             var deviceObj = null;

             o = new Option(dName,dId);

             //gpsconsole.selectDeviceList.add(o);
             jQuery("<option/>").val(dId).text(dName).appendTo(gpsconsole.selectDeviceList);

             caddressArray = firstEhis.split(":");
             if (caddressArray.length  <= 1)
                streetName = firstEhis;
             else
                streetName = caddressArray[1];

             jQuery(devAddressDiv).html(streetName);
            

             jQuery(deviceDiv).attr("id",dId);
             jQuery(devAddressDiv).attr("id",dId+"_address");

             jQuery(onOffDiv).append(img);

             
             //onoff device
             jQuery(img).toggle(function()
             {
                   deviceObj = new device();
                   deviceObj.addName(dName);
                   deviceObj.id = dId;
                 
                   gpsconsole.activeDevices.push(deviceObj);
                   jQuery(img).attr("src",settings.imgDevOnUrl);
                   gpsconsole.connectJMS(dId,"listen",function(s){});
                   gpsconsole.drawPosition(x,y,dId,streetName,"");

                  
             }, function()
             {
                    jQuery("#"+dId+"_address").css("color","#e45325");
                    jQuery(img).attr("src",settings.imgDevOffUrl);                   
                    deviceObj.removeAllMarkers();
                    gpsconsole.removeDevice(dId);
                    gpsconsole.connectJMS(dId,"unlisten",function(s){});
                    
                    deviceObj = null;
                  
             });

             //auto zoom
             jQuery(deviceDiv).toggle(function()
             {
                   if (deviceObj != null)
                   {
                        jQuery(deviceDiv).addClass("deviceDivSelected");
                        jQuery(deviceDiv).removeClass("deviceDiv");
                        deviceObj.isAutoZoom(true);
                        zoom = gpsconsole.autoZoom();
                        
                        if (zoom) map.zoomToExtent(zoom);
                   }

             }, function()
             {
                    if (deviceObj != null)
                    {
                        jQuery(deviceDiv).addClass("deviceDiv");
                        jQuery(deviceDiv).removeClass("deviceDivSelected");
                        deviceObj.isAutoZoom(false);
                    }
             });
            
             jQuery(devNameDiv).html(dName);
             jQuery(deviceDiv).append(onOffDiv);
             jQuery(deviceDiv).append(devNameDiv);
             jQuery(deviceDiv).append(devAddressDiv);
             jQuery("#"+settings.devicesDiv).append(deviceDiv);
             jQuery(deviceDiv).addClass("deviceDiv");
            

        },
        setDevices:function() 
        {
             
             jQuery.get(settings.devicesurl,{},function (data)
             {
               if (data != false)
               {
                 
                   var dom = jQuery.text2xml(data);
                   gpsconsole.setTabs();
                   jQuery("#"+settings.appendDiv).show();
                   jQuery("#"+settings.tabsid).show();

                   jQuery(dom).find('devicelist').each(function(index, value){
                      gpsconsole.createDevice(jQuery(this));
                   });
                     
               }
               else
               {
                    jQuery("#"+settings.appendDiv).hide();
               }
             });  
       },
       connectJMS:function(ident,process,connectResponse)
       {
           //alert(ident+" "+process);
           jQuery.post(settings.jmsurl, {poll:'true',destination:'topic://'+ident,type:process,message:ident,timeout:2000}, function(data)
           {
               
               //alert(gpsconsole.activeDevices.length+" "+gpsconsole.jmsinterval);
               if (gpsconsole.activeDevices.length > 0 && gpsconsole.jmsinterval == null)
               {
                   
                    gpsconsole.jmsinterval = setInterval(function(){gpsconsole.getDataJMS()},2000);
               }
               else if(gpsconsole.activeDevices.length == 0 && gpsconsole.jmsinterval != null)
               {
                   
                    clearInterval ( gpsconsole.jmsinterval );
                    gpsconsole.jmsinterval = null;
                    //alert("off:"+gpsconsole.activeDevices.length);
               }
               connectResponse(process);
           });
           
       },
       getDataJMS:function()
       {
           //alert("retrive data");
            
           jQuery.get(settings.jmsurl,{poll:'true',xml:'true',timeout:2000},function(data){
               
               jQuery(data).find('device').each(function(){

                 x = jQuery(this).find('coordinateX').text();
                 y = jQuery(this).find('coordinateY').text();
                 caddress = jQuery(this).find('address').text();
                 cspeed =  jQuery(this).find('speed').text();
                 ident  =  jQuery(this).attr('ident');
                 time   = jQuery(this).find('time').text();
                 if ( gpsconsole.getDevice(ident) != null )
                 {
                    jQuery("#"+ident+"_address").css("color","green");
                    caddressArray = caddress.split(":");
                    streetName = caddressArray[1];
                    gpsconsole.drawPosition(x,y,ident,streetName,time);
                 }
              });

           });
       },
       removeAllDevices:function()
       {
           for(var i=0; i<gpsconsole.activeDevices.length;i++ )
           {

                    gpsconsole.activeDevices[i].removeAllMarkers();
                    gpsconsole.activeDevices[i] = null;
                    gpsconsole.activeDevices.splice(i,1);
                 
           }
       },
       removeDevice:function(deviceId)
       {
            for(var i=0; i<gpsconsole.activeDevices.length;i++ )
            {
                if(gpsconsole.activeDevices[i].id == deviceId)
                {
                    gpsconsole.activeDevices[i].removeAllMarkers();
                    gpsconsole.activeDevices[i] = null;
                    gpsconsole.activeDevices.splice(i,1);
                 }
            }
       },
       getDevice:function(deviceId)
       {
            var device = null;
            for(var i=0; i<gpsconsole.activeDevices.length;i++ )
            {
                if(gpsconsole.activeDevices[i].id == deviceId)
                {          
                   device = gpsconsole.activeDevices[i];
                  
                }
            }
           
            return device;
       },
       drawPosition:function(x,y,ident,address,time)
       {
           map = settings.map.getMapInstance();
           var device = gpsconsole.getDevice(ident);
           if (device == null) return;
          
           la = new OpenLayers.LonLat(parseFloat(x),parseFloat(y)).transform
           (
                   new OpenLayers.Projection("EPSG:4326"),
                   new OpenLayers.Projection("EPSG:900913")
           );

           var size = new OpenLayers.Size(25,29);
           var offset = new OpenLayers.Pixel(-(size.w/2), -(size.h/2));
           icon = new OpenLayers.Icon(settings.imgTrackUrl,size,offset,null,null);

           markerInfo = "<span>"+device.getName()+"</span>"+time+"<span>"+address+"</span>";
           marker = new OpenLayers.Marker.GPS(la,icon.clone(),markerInfo);
           device.addMarker(marker);
           
           if (map.getZoom() >= settings.zoomLabelDisplay)
                jQuery(".gpsMarkerLabel").css("visibility","visible");
           else
               jQuery(".gpsMarkerLabel").css("visibility","hidden");

           zoom = gpsconsole.autoZoom();
           if (zoom) map.zoomToExtent(zoom);

           if (device.countMarkers() > 1)
           {
                device.removeMarker(0);
           }
           
           if ( jQuery("#"+ident+"_address").attr("id") )
           {
                
                jQuery("#"+ident+"_address").html(address);
           }
       },
       drawHistoryPosition:function(x,y,address,time)
       {
           la = new OpenLayers.LonLat(parseFloat(x),parseFloat(y)).transform
           (
                   new OpenLayers.Projection("EPSG:4326"),
                   new OpenLayers.Projection("EPSG:900913")
           );
           var size = new OpenLayers.Size(25,29);
           var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
           icon = new OpenLayers.Icon(settings.imgTrackHistoryUrl,size,offset,null,null);
           markerInfo = time;
           marker = new OpenLayers.Marker.GPS(la,icon.clone(),markerInfo);
           gpshistorymarkers.addMarker(marker);
           return marker;
       },
       autoZoom:function()
       {
            var isAuto = false;
            var bounds = new OpenLayers.Bounds();
            for(var i=0; i<gpsconsole.activeDevices.length;i++ )
            {
                dev = gpsconsole.activeDevices[i];
                if (dev.getAutoZoom() == true)
                {
                    isAuto = true;
                    bounds.extend(dev.getBounds());
                }
            }
            if (bounds.getSize().w == 0 && bounds.getSize().h == 0) return false;

            if (isAuto) return bounds; else return false;
       }
    };

    // Public Variables and Methods
    jQuery.gpsconsole =
    {

            setup:function(options)
            {
                 settings = jQuery.extend(settings, options);
                 map = settings.map.getMapInstance();
                 gpsmarkers = new OpenLayers.Layer.Markers("gps");
                 gpshistorymarkers = new OpenLayers.Layer.Markers("gps_history");
                 map.addLayer(gpsmarkers);
                 map.addLayer(gpshistorymarkers);
                 map.events.register("zoomend", map, gpsconsole.maplistener);
                 
            },

            showDevicesPanel:function()
            {
                gpsconsole.setDevices();
               
            },
            hideDevicesPanel:function()
            {
                jQuery("#"+settings.tabsid).hide();
               
            },
            hidePanel:function()
            {
               jQuery("#"+settings.appendDiv).hide();
            },
            toogleDevicesPanel:function()
            {
                jQuery("#"+settings.tabsid).toggle();

            },
            getDeviceSelect:function()
            {
                return gpsconsole.selectDeviceList;
            },
            exportCsv:function(devIdent,zdate,startTime,endTime,format)
            {
                  var elemIF = document.createElement("iframe");
                  jQuery(elemIF).attr("id","dliframe");
                  jQuery(elemIF).attr("src",settings.historyurl+"/"+devIdent+"/"+zdate+"/"+startTime+"/"+endTime+"/"+format);
                  jQuery(elemIF).css("display","none");
                  jQuery('body').append(jQuery(elemIF));
            },
            turnOnDemoDevices:function()
            {
               
                jQuery.get(settings.devicesurl,{},function (data)
                {

                   var dom = jQuery.text2xml(data);
                  
                   jQuery(dom).find('devicelist').each(function(index, value){

                      var streetName = "";
                      var dName = jQuery(this).find('devicename').text();
                      var dId = jQuery(this).find('deviceident').text();
                      var firstEhis = jQuery(this).find('deviceehis').text();
                      var x = jQuery(this).find('devicex').text();
                      var y = jQuery(this).find('devicey').text();

                      caddressArray = firstEhis.split(":");
                      if (caddressArray.length  <= 1)
                            streetName = firstEhis;
                      else
                            streetName = caddressArray[1];
                                       
                      deviceObj = new device();
                      deviceObj.addName(dName);
                      deviceObj.id = dId;
                      deviceObj.isAutoZoom(true);
                      
                      gpsconsole.activeDevices.push(deviceObj);
                      gpsconsole.connectJMS(dId,"listen",function(d){});
                      gpsconsole.drawPosition(x,y,dId,streetName,"");
                   });
                });
            },
            getHistory:function(devIdent,zdate,startTime,endTime)
            {
                
                jQuery("#"+settings.historyDiv).addClass("waitSmall");
                jQuery("#"+settings.historyDiv).empty();
                len = gpshistorymarkers.markers.length;
                for (a=0; a < len ;a++ )
                {
                    var m = gpshistorymarkers.markers[0];
                    gpshistorymarkers.removeMarker(m);
                    m.destroy();
                    m = null;
                }
                
                jQuery.get(settings.historyurl+"/"+devIdent+"/"+zdate+"/"+startTime+"/"+endTime,{},function (data)
                {
                       
                        //gpshistorymarkers.clearMarkers()
                        var dom = jQuery.text2xml(data);
                        jQuery(dom).find('devicelist').each(function()
                        {
                          
                             var x = jQuery(this).find('devicex').text();
                             var y = jQuery(this).find('devicey').text();
                             var caddress = jQuery(this).find('deviceehis').text();
                             var cspeed =  jQuery(this).find('devicespeed').text();
                             var time   = jQuery(this).find('devicelpdate').text();

                             timeArray = time.split(" ");
                             timeTime  = timeArray[1].split(".")[0];

                             caddressArray = caddress.split(",");
                             streetName = caddressArray[2];
                             if (jQuery.trim(streetName).length == 0)
                                streetName = caddressArray[1];

                             var addressLine = jQuery("<span title='"+time+"' class='historyRecord'><b>"+timeTime+"</b> "+streetName+"</span>");
                             var marker = null;
                             jQuery("#"+settings.historyDiv).append(addressLine);
                             
                             jQuery(jQuery(addressLine)).toggle
                             (
                                    function(){
                                        jQuery(this).css("background-color","silver");
                                        marker = gpsconsole.drawHistoryPosition(x,y,caddress,time);
                                        
                                    },
                                    function(){
                                        
                                        gpshistorymarkers.removeMarker(marker);
                                        marker.destroy();
                                        marker = null;
                                        jQuery(this).css("background-color","white");
                                    }
                              );
                              
                        });
                        jQuery("#"+settings.historyDiv).removeClass("waitSmall");
                });
            },
            showLogin:function()
            {
                 jQuery.get(settings.loginurl,{},function (data)
                 {
                    if ( ! jQuery('#login_panel').attr("id") )
                    {
                        var dom = jQuery(data);
                        jQuery("#"+settings.appendDiv).show();
                        jQuery("#"+settings.appendDiv).append(dom);
                    }
                  
                 });
            },
            hideLogin:function()
            {
                jQuery("#"+settings.appendDiv).empty();
               
            },
            print:function()
            {
                jQuery.get(settings.printurl,{},function (data)
                {
                   var printp = document.createElement('div');
                   jQuery(printp).addClass("flora");
                   jQuery(printp).append(data);
                   jQuery('body').append(printp);
                   var printMap;
                   var route_markers_print;
                   jQuery(printp).dialog(
                   {
                       open:function()
                       {

                          mapSettingsMini.div         = 'print_sopotnik_map_v';
                          mapSettingsMini.tileBuffer  = '0';
                          
                          OlMapPrint = new OlMiniMap(mapSettingsMini);
                          route_markers_print = new OpenLayers.Layer.Markers( "print_markers_sopotnik" );
                          printMap = OlMapPrint.getMapInstance();
                          printMap.addLayer(route_markers_print);
                          
                          for (m = 0 ; m<gpshistorymarkers.markers.length;m++)
                          {
                               var size = new OpenLayers.Size(25,29);
                               var offset = new OpenLayers.Pixel(-(size.w/2), -(size.h/2));
                               icon = new OpenLayers.Icon(settings.imgTrackHistoryUrl,size,offset,null,null);
                               markerInfo = gpshistorymarkers.markers[m].markerDiv.firstChild.nextSibling.innerHTML;
                               marker = new OpenLayers.Marker.GPS(gpshistorymarkers.markers[m].lonlat,icon,markerInfo);
                               route_markers_print.addMarker(marker);
                          }
                          
                          ze = route_markers_print.getDataExtent();
                          printMap.zoomToExtent(ze);
                          
                       },
                       close:function()
                       {
                            //route_markers_print.destroy();
                            printMap.destroy();
                            jQuery(printp).remove();
                       },
                       minHeight: 500,
                       height:jQuery("body").height(),
                       minWidth: 500,
                       width:jQuery("body").width()
                   });
                   
                });
                
            }

            
    };

})(jQuery);


