Wiking.widgets.DatePicker = (function(){
    function DatePicker(){
        Wiking.widgets.BlackScreen.draw();
        Wiking.getMap().addControl(this);
    } 
    DatePicker.prototype = new GControl(); 
    DatePicker.prototype.selectable = function(){return true;}
    DatePicker.prototype.printable = function(){return true;}
    DatePicker.prototype.initialize = function(map){
        var html='<div id="pickdatex" style="cursor:pointer;float:right;margin:-8px -8px 0 0;width:27px;height:27px;background: url(\'wimg/x.png\')"></div>'+
                 '<div style="background:url(/wimg/datepickerbg.png);padding:10px;width:289px;height:178px;">'+   // TODO : alpha image for ie
                 '<p style="font-size:14px;font-weight:bold;margin-top:8px;margin-bottom:19px;">Wybierz przedział czasowy</p>'+
                 '<div>Od dnia: <input id="fromdate" type="text" style="width:120px;border:1px solid #ccc" /> <img id="calFrom" src="wimg/calendar.png" style="cursor:pointer;vertical-align:-8px;" /> <input id="fromtime" type="text" size="5" style="border:1px solid #ccc" /></div>'+
                 '<div style="height:22px;margin-left:60px;"><div style="float:left;width:170px;">dd-mm-rrrr</div><div style="float:left;width:50px;">hh:mm</div></div>'+
                 '<div style="clear:left;">Do dnia: <input id="todate" type="text" style="width:120px;border:1px solid #ccc" /> <img src="wimg/calendar.png" id="calTo" style="vertical-align:-8px;cursor:pointer;" /> <input id="totime" type="text" size="5" style="border:1px solid #ccc" /></div>'+
                 '<div style="height:22px;margin-left:60px;"><div style="float:left;width:170px;">dd-mm-rrrr</div><div style="float:left;width:50px;">hh:mm</div></div>'+
                 '<img id="pickdate" src="/wimg/dalej.png" style="cursor:pointer;float:right" />'+
                 '</div>';
        var div = document.createElement('div');
        div.innerHTML=html;
        div.style.zIndex="300";
        
        map.getContainer().appendChild(div);
        
        var self = this; //clousure
        GEvent.addDomListener(document.getElementById('pickdatex'),'click',function(){
            Wiking.getMap().removeControl(self);
            Wiking.widgets.BlackScreen.clear();
        });
        
        GEvent.addDomListener(document.getElementById('pickdate'),'click',function(){
            self.pickDate();
        });
        
        var d = Wiking.DataLoader.getPeriod();
        document.getElementById('todate').value=this.dateFromTimestamp(d[1]);
        document.getElementById('fromdate').value=this.dateFromTimestamp(d[0]);
        document.getElementById('fromtime').value=this.timeFromTimestamp(d[0]);
        document.getElementById('totime').value=this.timeFromTimestamp(d[1]);
        
        GEvent.addDomListener(document.getElementById('calFrom'),'click',function(){
            self.openCalendarFrom();
        });
        GEvent.addDomListener(document.getElementById('calTo'),'click',function(){
            self.openCalendarTo();
        });
        
        this.div_ = div;
        return div;         
    }
    //DatePicker.prototype.remove = function(){
   //     console.debug('rem');
    //    this.div_.parentNode.removeChild(this.div_);
   //     Wiking.widgets.BlackScreen.clear();
   // };
    DatePicker.prototype.getDefaultPosition = function(){
        var size = Wiking.getMap().getSize();
        return new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(size.width/2-199,size.height/2-99));
    };
    DatePicker.prototype.disable_ = function(){
        this.div_.style.zIndex="99";
    }
    DatePicker.prototype.enable_ = function(){
        this.div_.style.zIndex="300";
    }
    DatePicker.prototype.openCalendarFrom=function()
    {
        var fd = document.getElementById('fromdate').value;
        var ft = document.getElementById('fromtime').value;
        var date = new Date(this.createTimestamp(fd,ft)*1000);
        
        if (!date.getDate())
        {
            date = new Date();
        }
        new Wiking.widgets.DatePickerCalendar(date,"fromdate",this);
    }
    DatePicker.prototype.openCalendarTo=function()
    {
        var fd = document.getElementById('todate').value;
        var ft = document.getElementById('totime').value;
        var date = new Date(this.createTimestamp(fd,ft)*1000);
        
        if (!date.getDate())
        {
            date = new Date();
        }
        new Wiking.widgets.DatePickerCalendar(date,"todate",this);
    }
    DatePicker.prototype.timeFromTimestamp=function(timestamp)
    {
        var date = new Date(timestamp*1000)
        return this.extend(date.getHours())+":"+this.extend(date.getMinutes());
    }
    DatePicker.prototype.dateFromTimestamp=function(timestamp)
    {
        //rozszerzamy timestamp z sec do milisec
        var date = new Date(timestamp*1000);
        return this.extend(date.getDate())+"-"+this.extend(date.getMonth()+1)+"-"+date.getFullYear();
    }
    DatePicker.prototype.extend=function(input)
    {
        var str = String(input);
        return (str.length === 1 ? "0"+str : str);
    }
    DatePicker.prototype.pickDate=function()
    {
        if (this.dynCheckDate('fromdate') && this.dynCheckTime('fromtime') && this.dynCheckDate('todate') && this.dynCheckTime('totime'))
        {
            var fd = document.getElementById('fromdate').value;
            var ft = document.getElementById('fromtime').value;
            var f = this.createTimestamp(fd,ft)
            
            
            var td = document.getElementById('todate').value;
            var tt = document.getElementById('totime').value;
            var t = this.createTimestamp(td,tt);
            
            //dodajemy opcje :-)
            var len = document.getElementById('historySelect').length;
            var y = document.createElement('option');
            y.text = fd + " - " + td; // TODO , żeby to łądniej jakoś było...
            y.value=String(f)+"x"+String(t)
            try
            {
                x = document.getElementById('historySelect');
                var sel=x.options[x.selectedIndex]; //omg ;-)
                x.add(y,sel);
            }
            catch(e)
            {
                document.getElementById('historySelect').add(y,len-1); //IE only, TODO: sprawdzić
            }
            document.getElementById('historySelect').selectedIndex=len-1;
            Wiking.getMap().removeControl(this);
            Wiking.widgets.BlackScreen.clear();
            Wiking.tools.historySelect.handle();
        }
    }
    DatePicker.prototype.dynCheckTime=function(field)
    { // szybkie sprawdzanie formatu czasu
      // format: hh:mm
        var value = document.getElementById(field).value;
        if (value.length == 5 && value.charAt(2) == ":")
        {
            var s = value.split(":");
            if (parseInt(s[0],10) > -1 && parseInt(s[0],10) < 25 && parseInt(s[1],10) < 60 && parseInt(s[1],10) > -1)
            {
                document.getElementById(field).style.background="#fff"
                document.getElementById(field).style.border="1px solid #ccc"
                return true;
            }
        }
        document.getElementById(field).style.background="#e5b2b2"
        document.getElementById(field).style.border="1px solid #f00"
        return false;
    }
    DatePicker.prototype.dynCheckDate=function(field)
    { // format: rrrr-mm-dd
        var value = document.getElementById(field).value;
        var s = value.split('-');
        if (s.length==3)
        {
            s[0]=this.extend(s[0]); // jeśli s[0] ma długość jeden, extend
            s[1]=this.extend(s[1]); // jw
            value=s[0]+"-"+s[1]+"-"+s[2];
            document.getElementById(field).value=value;
            if (value.length == 10 && value.charAt(2) == "-" && value.charAt(5) == "-")
            {
                if (parseInt(s[2],10) > 1000 && parseInt(s[1],10) > 0 && parseInt(s[1],10) < 13)
                {
                    // a teraz parsujemy sobie dzień
                    var d = new Date();
                    d.setFullYear(s[2],s[1]-1,s[0]);
                    if (d.getMonth() == (s[1]-1)) // TODO lepsze zabezpieczenie..
                    {
                        document.getElementById(field).style.background="#fff"
                        document.getElementById(field).style.border="1px solid #ccc"            
                        return true;
                    }
                }
            }
        }
        document.getElementById(field).style.background="#e5b2b2"
        document.getElementById(field).style.border="1px solid #f00"
        return false;
    }  
    DatePicker.prototype.createTimestamp=function(fd,ft)
    {
        try
        {
            var fda = fd.split('-');
            var fta = ft.split(':');
            var d = new Date();       
            d.setFullYear(parseInt(fda[2],10),parseInt(fda[1],10)-1,parseInt(fda[0],10));    // TODO !
            d.setHours(fta[0]);
            d.setMinutes(fta[1]);
            return Math.round(d.getTime()/1000);
        }
        catch(e)
        {
            return false;
        }
    }      
    return DatePicker; 
})();
