Wiking.widgets.showAlerts = function()
{
    new Wiking.widgets.Alerts()
};

Wiking.widgets.Alerts = (function(){
    function Alerts(){
        Wiking.widgets.BlackScreen.draw();
        Wiking.getMap().addControl(this);
        this.alerts = {};   
    }
    Alerts.prototype = new GControl();
    Alerts.prototype.selectable = function(){return true;}
    Alerts.prototype.printable = function(){return true;}
    Alerts.prototype.initialize = function(map){ 
        var
          mapsize = map.getSize(),
          width = mapsize.width - 180,
          height = mapsize.height - 90;  
        var select_devices = '';
        var obj = Wiking.getObjects();
        var oname;
        for (var i=0, l = obj.length; i<l; i++){
            if (!obj[i].isActive()) continue;
            oname = obj[i].getName()==obj[i].getImei() ? obj[i].getImei() : obj[i].getName()+" ("+obj[i].getImei()+")";
            select_devices += "<option value=\""+obj[i].getImei()+"\">"+oname+"</option>";
        }
        var html = '<div id="closeHelp" style="cursor:pointer;position:absolute;left:'+(width-17)+'px;top:-9px;width:27px;height:27px;background: url(\'wimg/x.png\')"></div>'+
               '<div>'+
                 '<div style="float:left;width:8px;height:39px;background:url(\'wimg/eclefttop.png\')"></div>'+
                   '<div style="float:left;background:url(\'wimg/ectop.png\');height:39px;width:'+(width-16)+'px">'+
                      '<p style="font-size:14px;font-weight:bold;margin-top:12px;margin-left:5px;">Alerty</p>'+
                   '</div>'+
                 '<div style="float:left;width:8px;height:39px;background:url(\'wimg/ecrighttop.png\')"></div>'+
             
                 '<div style="clear:left;float:left;width:8px;background:url(\'wimg/cleft.png\');height:'+(height-47)+'px"></div>'+
                 '<div style="float:left;overflow:auto;background:#fff;height:'+(height-47)+'px;width:'+(width-16)+'px">'+
                    
                       '<div style="height:38px;margin:0 0px 10px 0px;border-bottom:1px solid #e2e2e2;">'+
                         '<div id="alertsButtonList" style="cursor:pointer;background:url(\'/wimg/bbg2.png\') no-repeat;float:left;padding:11px 0px 8px 0px;width:70px;text-align:center;margin:5px 3px 0 7px">Lista</div>'+
                         '<div id="alertsButtonHistory" style="cursor:pointer;background:url(\'/wimg/bbg1.png\') no-repeat;float:left;padding:11px 0px 8px 0px;width:70px;text-align:center;margin:5px 0 0 0">Historia</div>'+
                         '<div id="alertsButtonPhones" style="cursor:pointer;background:url(\'/wimg/bbg2.png\') no-repeat;float:left;padding:11px 0px 8px 0px;width:70px;text-align:center;margin:5px 0 0 3px">Telefony</div>'+
                         '<div id="alertsButtonAdd" style="cursor:pointer;background:url(\'/wimg/bbg4.png\') no-repeat;float:left;padding:11px 0px 8px 0px;width:103px;text-align:center;margin:5px 7px 0 3px">Zdefiniuj nowy</div>'+
                       '</div>'+
                       //hist
                    '<div style="padding:10px;" id="alertsDivHistory">'+
                        '<strong>Historia zdarzeń:</strong><p>Pobieranie danych...</p>'+
                    '</div>'+
                      //list
                    '<div style="padding:10px;display:none;" id="alertsDivList">'+
                        '<p>Pobieranie listy alertów...</p>'+
                    '</div>'+
                      //tel
                    '<div style="padding:10px;display:none;" id="alertsDivPhones">'+
                        '<strong>Dodaj numer telefonu do konta:</strong><br>'+
                        '<input type="text" id="addPhoneInput" style="padding:2px;width:120px;border: 1px solid #ccc;margin:6px;">'+
                        '<img src="/wimg/savestyle.png" id="addPhoneSubmit" style="vertical-align:-8px;cursor:pointer;margin-right:10px;"><span id="addPhoneInfo"></span>'+
                        '<p style="font-weight:bold">Lista numerów telefonu dodanych do konta:</p>'+
                        '<div id="alertsPhoneList">'+
                            'Pobieranie listy telefonów...'+
                        '</div>'+
                    '</div>'+
                    //add
                    '<div style="padding:10px;display:none;" id="alertsDivAdd">'+
                        '<strong>Zdefiniuj nowy alert:</strong>'+
                        '<p>Urządzenie: '+
                        '<select id="alertsSelectObj">'+
                            select_devices+
                        '</select>&nbsp;&nbsp;'+
                        'Typ: <select id="alertsSelectType"><option value="spd">Prędkość</option><option value="geoc">Obszar</option></select>'+
                        '<img id="alertsDoDefine" src="/wimg/dalej.png" style="vertical-align:-10px;margin-left:15px;cursor:pointer">'+
                        
                        
                        '</p>'+
                        //hidden alerts
                        '<div id="alertsSpd" style="display:none">'+
                            'Alert jeśli obiekt przekroczy prędkość <input type="text" id="alertsSpdValue" value="100" style="text-align:center;padding:2px;width:30px;border: 1px solid #ccc;margin:6px;"> km/h'+
                            '<img id="alertsSpdSave" src="/wimg/savestyle.png" style="vertical-align:-8px;cursor:pointer;margin-left:15px">'+
                        '</div>'+
                        '<div id="alertsGeoc" style="display:none">'+
                            'Oznacz środkowy punkt obszaru na mapie:'+
                            '<div id="alertsGeocMap" style="width:400px; height:200px;border:1px solid #ccc;"></div>'+
                            'Odległość: <input type="text" id="alertsGeocValue" value="500" style="text-align:center;padding:2px;width:45px;border: 1px solid #ccc;margin:6px;"> metrów.<br>'+
                            'Alert jeśli pojazd <select id="alertsGeocType"><option value="enter">wjedzie na</option><option value="leave">opuści</option><option value="both">opuści lub wjedzie na</option></select> obszar.'+
                            '<img id="alertsGeocSave" src="/wimg/savestyle.png" style="vertical-align:-8px;cursor:pointer;margin-left:15px">'+
                        '</div>'+
                        '<div id="alertsSaveStatus" style="padding:15px 0 0 0;">'+
                        '</div>'+
                    '</div>'+                    
                    
                   '<div style="padding:10px;" id="helpContent">'+
                    '</div>'+
                   '</div>'+
                 '</div>'+
                 '<div style="float:left;width:8px;background:url(\'wimg/cright.png\');height:'+(height-47)+'px"></div>'+
               
                 '<div style="float:left;clear:left;width:8px;height:8px;background:url(\'wimg/cleftbottom.png\')"></div>'+
                 '<div style="float:left;background:url(\'wimg/cbottom.png\');height:8px;width:'+(width-16)+'px"></div>'+
                 '<div style="float:left;width:8px;height:8px;background:url(\'wimg/crightbottom.png\')"></div>'+
               '</div>';
              
        var div = document.createElement('div');
        div.innerHTML=html;
        div.style.zIndex="300";
        map.getContainer().appendChild(div);
        
        GEvent.bindDom(document.getElementById('closeHelp'),'click',this,this.clear_);
        
        this.bind_nav();
        
        //async
        var self = this;
        window.setTimeout(function(){
            self.createPhonesList();
            self.createAlertsList();
        },0);
        return div;
    }
    Alerts.prototype.bind_nav = function(){
        var self = this; //for binding/clousure
        GEvent.addDomListener(document.getElementById('alertsButtonList'),'click',function(){
        //turn on list
            document.getElementById('alertsDivHistory').style.display='none';
            document.getElementById('alertsDivAdd').style.display='none';
            document.getElementById('alertsDivPhones').style.display='none';
            document.getElementById('alertsDivList').style.display='block';
            
            document.getElementById('alertsButtonPhones').style.background="url('/wimg/bbg2.png') no-repeat";
            document.getElementById('alertsButtonHistory').style.background="url('/wimg/bbg2.png') no-repeat";
            document.getElementById('alertsButtonAdd').style.background="url('/wimg/bbg4.png') no-repeat";
            document.getElementById('alertsButtonList').style.background="url('/wimg/bbg1.png') no-repeat";
        });
        GEvent.addDomListener(document.getElementById('alertsButtonHistory'),'click',function(){
        //turn on history
            document.getElementById('alertsDivList').style.display='none';
            document.getElementById('alertsDivAdd').style.display='none';
            document.getElementById('alertsDivPhones').style.display='none';
            document.getElementById('alertsDivHistory').style.display='block';
            
            document.getElementById('alertsButtonPhones').style.background="url('/wimg/bbg2.png') no-repeat";
            document.getElementById('alertsButtonHistory').style.background="url('/wimg/bbg1.png') no-repeat";
            document.getElementById('alertsButtonAdd').style.background="url('/wimg/bbg4.png') no-repeat";
            document.getElementById('alertsButtonList').style.background="url('/wimg/bbg2.png') no-repeat";
        });
        GEvent.addDomListener(document.getElementById('alertsButtonAdd'),'click',function(){
        //turn on define niu
            document.getElementById('alertsDivList').style.display='none';
            document.getElementById('alertsDivHistory').style.display='none';
            document.getElementById('alertsDivPhones').style.display='none';
            document.getElementById('alertsDivAdd').style.display='block';
            
            document.getElementById('alertsButtonPhones').style.background="url('/wimg/bbg2.png') no-repeat";
            document.getElementById('alertsButtonHistory').style.background="url('/wimg/bbg2.png') no-repeat";
            document.getElementById('alertsButtonAdd').style.background="url('/wimg/bbg3.png') no-repeat";
            document.getElementById('alertsButtonList').style.background="url('/wimg/bbg2.png') no-repeat";
        });
        GEvent.addDomListener(document.getElementById('alertsButtonPhones'),'click',function(){
        //turn on phones
            document.getElementById('alertsDivList').style.display='none';
            document.getElementById('alertsDivHistory').style.display='none';
            document.getElementById('alertsDivAdd').style.display='none';
            document.getElementById('alertsDivPhones').style.display='block';
            
            document.getElementById('alertsButtonPhones').style.background="url('/wimg/bbg1.png') no-repeat";
            document.getElementById('alertsButtonHistory').style.background="url('/wimg/bbg2.png') no-repeat";
            document.getElementById('alertsButtonAdd').style.background="url('/wimg/bbg4.png') no-repeat";
            document.getElementById('alertsButtonList').style.background="url('/wimg/bbg2.png') no-repeat";
        });
        GEvent.addDomListener(document.getElementById('alertsDoDefine'),'click',function(){
            self.define_next_step();
        });
        
        //submit add phone
        GEvent.addDomListener(document.getElementById('addPhoneSubmit'),'click',function(){
            self.add_phone();
        });
    }
    Alerts.prototype.define_next_step = function(){
        var t = document.getElementById('alertsSelectType');
        t.disabled=true;
        document.getElementById('alertsSelectObj').disabled=true;
        document.getElementById('alertsDoDefine').style.display='none';
        if (t.value=="spd"){
            this.define_speed_alert();
        }else{
            this.define_geocircle_alert();
        }
    }
    Alerts.prototype.define_speed_alert = function(){
        var self = this;
        document.getElementById('alertsSpd').style.display="block";
        var button = document.getElementById('alertsSpdSave');
        var status = document.getElementById('alertsSaveStatus');
        GEvent.addDomListener(button,'click',function(){
            var v = document.getElementById('alertsSpdValue');
            v.disabled=true;
            button.style.display='none';
            status.innerHTML="Trwa zapisywanie alertu...";
            new Ajax.Request("/thingy/alerts?r=define_speed&i="+document.getElementById('alertsSelectObj').value+"&v="+v.value,{'method':'GET',onSuccess:function(e){
                
                status.innerHTML="Alert został zapisany.";
                self.createAlertsList();
            },onFailure:function(){
                status.innerHTML="Nie udało się zapisać alertu.";
            }});
        });
    }
    Alerts.prototype.define_geocircle_alert = function(){//forgive me, voodoo below
        document.getElementById('alertsGeoc').style.display='block';
        var button = document.getElementById('alertsGeocSave');
        var status = document.getElementById('alertsSaveStatus');
        
        var marker; //important
        
        var cmap = new GMap2(document.getElementById('alertsGeocMap'));
        cmap.setCenter(new GLatLng(52.2024283828678,20.94125598), 7);
        cmap.addControl(new GSmallMapControl());
             
        //addControler
        function AddControler() {}
        AddControler.prototype = new GControl();

        AddControler.prototype.initialize = function(map) {
            var container = document.createElement("div");
            container.innerHTML='<button style="padding:2px 6px;">Umieść punkt</button>';
            GEvent.addDomListener(container, "click", function() {
                container.innerHTML="kliknij na mapie by umieścić punkt";
                container.style.background="orange"
                
                GEvent.addListener(cmap,'click',function(_ov,latlng){
                    marker = new GMarker(latlng, {draggable: true});
                    GEvent.clearListeners(cmap, 'click');
                    cmap.addOverlay(marker);
                    container.innerHTML="Podpowiedź: możesz przeciągać marker";
                });
            });

            map.getContainer().appendChild(container);
            return container;
        }

        AddControler.prototype.getDefaultPosition = function() {
            return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
        }
        
        cmap.addControl(new AddControler());

        var self = this;

        GEvent.addDomListener(button,'click',function(){
            if (!marker){
                alert('Musisz określić punkt na mapie!');
                return;
            }
            marker.disableDragging();
            var ll = marker.getLatLng();
            button.style.display='none';
            status.innerHTML="Trwa zapisywanie alertu...";
            //["r","define_geocircle","i",Imei,"lng",Lng,"lat",Lat,"d",Dist,"t",Type]
            var imei = document.getElementById('alertsSelectObj').value;
            var distNode = document.getElementById('alertsGeocValue')
            distNode.disabled=true;
            var tmpDist = String(parseInt(distNode.value));
            var dist = (tmpDist == "Nan" ? 500 : tmpDist)
           
            var typeNode = document.getElementById('alertsGeocType');
            typeNode.disabled=true;
            var type = typeNode.value;
            new Ajax.Request("/thingy/alerts?r=define_geocircle&i="+imei+"&lng="+ll.lng()+"&lat="+ll.lat()+"&d="+dist+"&t="+type,{'method':'GET',onSuccess:function(e){
                
                    status.innerHTML="Alert został zapisany.";
                    self.createAlertsList();
                },onFailure:function(){
                    status.innerHTML="Nie udało się zapisać alertu.";
                }});
            });
    }
    //phones
    Alerts.prototype.add_phone = function(){
        var self = this;
        var phone = document.getElementById('addPhoneInput');
        phone.disabled=true;
        var sub = document.getElementById('addPhoneSubmit');
        sub.style.display='none';
        var info = document.getElementById('addPhoneInfo');
        info.innerHTML="Zapisywanie...";
        new Ajax.Request('/thingy/alerts?r=addphone&v='+phone.value.replace('+48','').replace(' ','','g').replace('-','','g'),{method:'GET',onSuccess:function(e){
            if (e.responseJSON=="OK"){
                info.innerHTML="Numer został dodany poprawnie.";
                self.createPhonesList();
            }else{
                info.innerHTML="Podałeś nie poprawny numer telefonu.";
            }
            phone.disabled=false;
            sub.style.display='inline';
        },onFailure:function(){
            info.innerHTML="Nie udało się dodać numeru.";
            sub.style.display='inline';
            phone.disabled=false;
        }});
    }
    Alerts.prototype.createPhonesList = function(){
        var div = document.getElementById('alertsPhoneList');
        div.innerHTML="Pobieranie listy numerów telefonów...";
        var self = this;
        new Ajax.Request('/thingy/alerts?r=getphone',{method:'GET',onSuccess:function(e){
            var tab = e.responseJSON;
            var txt = ['<ul>'];
            for (var i=0,l=tab.length;i<l;i++){
                txt.push('<li>'+tab[i]+' <a href="#" class="alertsDelPhoneA">(usuń)</a></li>');
            }   
            txt.push('</ul>');
            if (txt.length == 2){
                txt=["Brak dodanych numerów telefonów."];
            }
            div.innerHTML=txt.join('');
            var d = $$('.alertsDelPhoneA');
            var clousure = function(ad){
                return function(){
                    self.del_phone(ad);
                }
            }
            for (var i=0,l=tab.length;i<l;i++){
                GEvent.addDomListener(d[i],'click',new clousure(tab[i]));
            }
            
        },onFailure:function(){
            div.innerHTML="Nie udało się pobierać listy telefonów.";
        }});
    }
    Alerts.prototype.del_phone = function(phone){
        var div = document.getElementById('alertsPhoneList');
        div.innerHTML="Usuwanie wybranego numeru telefonu...";
        var self=this;
        new Ajax.Request('/thingy/alerts?r=delphone&v='+phone,{method:'GET',onSuccess:function(e){
            self.createPhonesList();
        }});
    }
    Alerts.prototype.createAlertsList = function(){
        this.alerts = {};
        var div = document.getElementById('alertsDivList');
        div.innerHTML="<strong>List zdefiniowanych alertów:</strong><p>Pobieranie listy alertów...</p>";
        var self = this;
        new Ajax.Request('/thingy/alerts?r=getlist',{method:'GET',onSuccess:function(e){
            var tab = e.responseJSON;
            if (tab.length==0){
                div.innerHTML="<strong>List zdefiniowanych alertów:</strong><p>Brak zdefiniowanych alertów.</p>";
                self.create_history_list();
                return
            }
            var out = ['<strong>List zdefiniowanych alertów:</strong><table cellpadding="0" cellspacing="0" style="text-align:center;margin-top:6px;width:100%;">'+
                        '<tr style="height:35px;">'+
                                    '<td style="width:10px;background:url(\'wimg/ltable.png\');"></td>'+
                                    '<td style="background:url(\'wimg/whitetablebg.png\')">IMEI</td>'+
                                    '<td style="width:1px;background:url(\'wimg/jointable.png\')"></td>'+
                                    '<td style="background:url(\'wimg/darktablebg.png\')">Id alertu</td>'+
                                    '<td style="width:1px;background:url(\'wimg/jointable.png\')"></td>'+
                                    '<td style="background:url(\'wimg/whitetablebg.png\');">Opis</td>'+
                                    '<td style="width:1px;background:url(\'wimg/jointable.png\')"></td>'+
                                    '<td style="background:url(\'wimg/darktablebg.png\')">Kanały SMS</td>'+
                                    '<td style="width:1px;background:url(\'wimg/jointable.png\')"></td>'+
                                    '<td style="background:url(\'wimg/whitetablebg.png\');">Opcje</td>'+
                                    '<td style="width:10px;background:url(\'wimg/rtable.png\')"></td>'+
                                '</tr>'];
                       //"<tr style=\"font-weight:bold;background:#eee;\"><td>IMEI</td><td>ID alertu</td><td>Opis</td><td>Kanały SMS</td><td>Opcje</td></tr>"];
            for (var i=0,l=tab.length;i<l;i++){
                var el = tab[i];
                var typ;
                if (el.type=="speed"){
                    typ = "Przekroczenie prędkości "+parseFloat(el.data).toFixed(2)+" km/h";
                }else{
                    var geotyp;
                    switch(el.data.type){
                        case "enter":
                            geotyp = "Wjazd na obszar ";
                            break;
                        case "leave":
                            geotyp = "Wyjazd z obszaru ";
                            break;
                        case "both":
                            geotyp = "Wjazd lub wyjazd z obszaru ";
                        
                    }
                    typ = geotyp + el.data.distance.toFixed(2) + " metrów od "+el.data.lat+" "+el.data.lng;
                }
                self.alerts[el.id] = typ;
                var le = el.channelz.length;
                var sms;
                if (le==0) sms = "brak";
                else{
                    sms = [];
                    while(le--){
                        var c = el.channelz[le]
                        sms.push(c.phone+" ("+c.count+")");
                    }
                    sms = sms.join(", ");
                }
                out.push('<tr><td colspan="3" style="padding:6px 0;text-align:center;">'+el.imei+'</td><td colspan="2">'+el.id+'</td><td colspan="2">'+typ+'</td><td style="text-align:center;" colspan="2">'+sms+'</td><td style="text-align:center;" colspan="2"><a href="#" class="alertsDeleteAlert">Usuń</a></td></tr>');
            }
            out.push("</table>");
            div.innerHTML = out.join("");
            var d = $$('.alertsDeleteAlert');
            var clousure = function(ad){
                return function(){
                    self.del_alert(ad);
                }
            }
            for (var i=0,l=tab.length;i<l;i++){
                GEvent.addDomListener(d[i],'click',new clousure(tab[i].id));
            }
            self.create_history_list();
        }});
    }
    Alerts.prototype.create_history_list = function(){
        var div = document.getElementById('alertsDivHistory');
        div.innerHTML="<strong>Historia zdarzeń:</strong><p>Pobieranie danych...</p>";
        var self = this;
        new Ajax.Request('/thingy/alerts?r=gethistory',{method:'GET',onSuccess:function(e){
            var tab = e.responseJSON;
            if (tab.length==0){
                div.innerHTML="<strong>Historia zdarzeń:</strong><p>Brak zdarzeń.</p>";
                return
            }
            var out = ['<strong>Historia zdarzeń:</strong><table cellpadding="0" cellspacing="0" style="text-align:center;margin-top:6px;width:100%;">'+
                       '<tr style="height:35px;">'+
                                    '<td style="width:10px;background:url(\'wimg/ltable.png\');"></td>'+
                                    '<td style="background:url(\'wimg/whitetablebg.png\')">IMEI</td>'+
                                    '<td style="width:1px;background:url(\'wimg/jointable.png\')"></td>'+
                                    '<td style="background:url(\'wimg/darktablebg.png\')">Id alertu</td>'+
                                    '<td style="width:1px;background:url(\'wimg/jointable.png\')"></td>'+
                                    '<td style="background:url(\'wimg/whitetablebg.png\');">Data</td>'+
                                    '<td style="width:1px;background:url(\'wimg/jointable.png\')"></td>'+
                                    '<td style="background:url(\'wimg/darktablebg.png\')">Opis</td>'+
                                    '<td style="width:1px;background:url(\'wimg/jointable.png\')"></td>'+
                                    '<td style="background:url(\'wimg/whitetablebg.png\');">Dane</td>'+
                                    '<td style="width:10px;background:url(\'wimg/rtable.png\')"></td>'+
                                '</tr>'];
                       //"<tr style=\"font-weight:bold;background:#eee;\"><td>IMEI</td><td>ID</td><td>Data</td><td>Opis</td><td>Dane</td></tr>"];
            function extend(s){
                var str = String(s);
                return (str.length === 1 ? "0"+str : str);
            }
            for (var i=0,l=tab.length;i<l;i++){
                var el = tab[i];
                var date = new Date(el.timestamp*1000);
                date = extend(date.getDate())+"-"+extend(date.getMonth()+1)+"-"+date.getFullYear()+" "+extend(date.getHours())+":"+extend(date.getMinutes());
                out.push('<tr><td colspan="3" style="padding:6px 0;">'+el.imei+'</td><td colspan="2">'+el.alert_id+'</td><td colspan="2" style="text-align:center;">'+date+'</td><td colspan="2">'+self.alerts[el.alert_id]+'</td><td colspan="2" style="text-align:center;">'+el.spd+' km/h miejsce: '+el.lat+' '+el.lng+'</td></tr>');
            }
            out.push("</table>");
            div.innerHTML = out.join("");
        }});
    };
    Alerts.prototype.del_alert = function(id){
        var div = document.getElementById('alertsDivList');
        div.innerHTML="Usuwanie wybranego alertu...";
        var self=this;
        new Ajax.Request('/thingy/alerts?r=delete_alert&id='+id,{method:'GET',onSuccess:function(e){
            self.createAlertsList();
        }});  
    }
    Alerts.prototype.clear_ = function(){
        Wiking.widgets.BlackScreen.clear();
        Wiking.getMap().removeControl(this);
    }
    Alerts.prototype.getDefaultPosition = function(){
        return new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(130,60));
    };
    return Alerts;
})();

