﻿
var mCalendar = new Class({
    initialize: function(options) {
        var options = options || {};
        this.localMCalendars=options.localMCalendars;
        var lng = new Object();
        this.input=options.el;
        options.date=options.date || new Date();
        this.isFirst=options.isFirst;
        this.isLast=options.isLast;
        this.readOnly=options.readOnly || false;
        this.single=options.single || false;
        this.clickHandler=options.clickHandler || this.selectThisWeek;
        this.we=options.we||false;
        if(this.single){
            this.clickHandler=function(idx){
                idx=idx.substring("single".length,idx.length);
                myDate=new Date(idx);
                if(myDate.getDay()!=this.config.Lng.first)//go back to first day of week
                    myDate.setDate(myDate.getDate()-myDate.getDay()-7+this.config.Lng.first);
                if(this.we){
                    myDate.setDate(myDate.getDate()+6);//go to next friday
                }
                outDateString=myDate.getDate()+"/"+(myDate.getMonth()+1)+"/"+myDate.getFullYear();
                this.input.value=outDateString;
                try{
                    if($('durata').value=="")
                        $('durata').value=7;
                }catch(e){}
                this.div.remove();
                try{this.iframe.remove();}catch(e){}
            }
        }
        // Firefox? IE ?
        try {  
            var nav = navigator.language.substr(0,2); }
        catch (e)    { var nav = navigator.userLanguage;}
        var thiso=this;
        lng['en'] = {
            month : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
            day : ['S','S','M','T','W','T','F'],
            first: 6 // First day of week => Saturday
        };
        lng['it'] = {
            month : ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'],
            day : ['S','D','L','M','M','G','V'],
            first: 6 // First day of week => Sabato
        };
        lng['es'] = {
            month : ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
            day : ['S','D','L','M','M','J','V'],
            first: 6 // First day of week => Saturday
        };
        lng['de'] = {
            month : ['Januar', 'Februar', 'M&auml;rz', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
            day : ['S','D','L','M','M','G','V'],
            first: 6 // First day of week => Sabato
        };

        //lng = (!lng[nav])? lng['it'] : lng =  lng[nav] ;
        lng = lng[globalLang];
        
        /* configuration */
        if (!options.Config)
            this.config = {
                Lng: lng,
                imgNext: '/images/calendar/next.gif',
                imgPrev: '/images/calendar/prev.gif',
                imgCancel: '/images/calendar/cancel.gif'
            };

        this.month_name = this.config.Lng.month;
        this.day_name =  this.config.Lng.day;
      
        this.container=$(options.idContainer) || document.body;
          
        this.create_calendar(options);
    },
    create_calendar: function(options) {
        var options = options || {};
        var idX   = options.id || "mdiv";
        var dateX   = options.date || new Date();
        // content divs  //
        if(this.single){
            var styleTop=(this.input.getPosition().y+20)+'px';
            var styleLeft=(this.input.getPosition().x)+'px';
            this.div = new Element('div').setStyles({'top':styleTop, 'left':styleLeft}).setProperty('id', idX).injectInside(document.body);
            if(window.ie6)
                this.iframe = new Element('iframe').setStyles({position:'absolute','z-index':'2000',top:styleTop, left:styleLeft, width:'159px', height:'148px', border:'0px'}).injectInside(document.body);
        }else{
            this.div = new Element('div').setStyles({position:'relative'}).setProperty('id', idX);
        }
        //this.div.setOpacity(0);
        this.div.injectInside(this.container);      
        this.div.className = options.className || "mcalendar";
        if(this.single){
            thiso=this;
            this.div.makeDraggable({onDrag:function(divo){
                if(window.ie6)
                    thiso.iframe.setStyles({left:divo.style.left,top:divo.style.top});
            }});
        }
        this.nav(this.div);
          
        this.setdate(dateX);
        this.effect(this.div,'show');
    } ,
    nav: function (div) {
        // nav
        this.calendardiv = new Element('div').injectInside(div);
        this.calendardiv.id="titlediv";
        this.title = new Element('div').injectInside(this.calendardiv);
        this.title.id="title";
        var localThis=this;
        if(this.single){
            this.next = new Element('img').setProperty('src', this.config.imgNext).injectAfter(this.title);
            this.before = new Element('img').setProperty('src', this.config.imgPrev).injectBefore(this.title);
            this.close = new Element('img').setProperty('src', this.config.imgCancel).injectAfter(this.next);
            this.close.addClass('calImgClose');
            
            this.next.addEvent('click', function(e) {
                localThis.goToNextDate();
            });
            this.before.addEvent('click', function(e) {
                localThis.goToPrevDate();
            });
            this.close.addEvent('click', function(e) {
                localThis.div.remove();
                if(localThis.single)
                try{localThis.iframe.remove();}catch(e){}
            });
        }
        this.center = new Element('center').injectInside(div);
        this.table = new Element('table').injectInside(this.center);
        var thead = new Element('thead').injectInside(this.table);
        var tr = new Element('tr').injectInside(thead);

        this.day_name.each(function (day) {
            var td = new Element('th').appendText(day).injectInside(tr);
        });
    },
    goToNextDate:function(){
        var localThis = this;
        var date = localThis.today;
        date.setMonth(localThis.next_m,1);
        localThis.tbody.remove();
        localThis.setdate(date);
    },
    goToPrevDate:function(){
        var localThis = this;
        var date = localThis.today;
        date.setMonth(localThis.next_m-2,12);
        localThis.tbody.remove();
        localThis.setdate(date);
    },
    setdate : function(date) {
        // reset event nav
        this.today = date;

        this.next_m = this.today.getMonth()+1;

        try { 
            this.title.innerHTML = this.month_name[this.today.getMonth()]+' ' + this.today.getFullYear(); 
        } catch (e) { this.title.innerText = this.month_name[this.today.getMonth()]+' ' + this.today.getFullYear(); }
        var localThis = this;
                      
        this.tbody = new Element('tbody');
        //this.tbody.setOpacity(0);
        this.tbody.injectInside(this.table);
        
        var first_day = new Date(this.today.getFullYear(),this.today.getMonth(),this.today.getDate(),0,0,0);
        var last_day = this.today;
        this.month = this.today.getMonth();
        var tr = new Element('tr').injectInside(this.tbody);

        /* first day week */
        first_day.setDate(1);
        
        var LastMonth = new Date(this.today.getFullYear(),this.next_m-2,1,0,0,0);
        LastMonth.setMonth(LastMonth.getMonth()+1);
        LastMonth.setDate(LastMonth.getDate()-1);
        
        if(LastMonth.getDay()!=this.config.Lng.first-1){
            while(LastMonth.getDay()!=this.config.Lng.first){
                LastMonth.setDate(LastMonth.getDate()-1);
            }
            while(LastMonth<first_day){
                var cssClass='noday';
                if(localThis.isFirst){
                    cssClass="visibleNoday";
                }
                this.create_td(tr,LastMonth.getDate(),LastMonth,cssClass);
                LastMonth.setDate(LastMonth.getDate()+1);
            }
        }
        
        brea_k=this.config.Lng.first;
        
        
        /* everydays */
        var date_s = this.today;
        var class_Css;
        var daycounter = 0;
        for (var i = 1; i <= 31; i++) {
            date_s.setDate(i);
            if (date_s.getMonth() == this.month) {
                daycounter++;
                if (date_s.getDay() == brea_k) {
                    var tr = new Element('tr').injectInside(this.tbody);
                }
                class_Css = (!date_s.getDay())? 'sunday' : '';
                this.create_td(tr,i,date_s,class_Css);
            }
        }
        this.today.setMonth(this.month);
        this.today.setMonth(this.month);

        this.today.setDate(daycounter);
           
        // finish month
        if(this.today.getDay()!=this.config.Lng.first-1){
            var NextMonth = new Date(this.today);
            NextMonth.setDate(NextMonth.getDate()+1);
            while(NextMonth.getDay()!=this.config.Lng.first){
                var cssClass='noday';
                if(localThis.isLast){
                    cssClass="visibleNoday";
                }
                this.create_td(tr,NextMonth.getDate(),NextMonth,cssClass);
                NextMonth.setDate(NextMonth.getDate()+1);    
            }
        }
        this.effect(this.tbody,'show');
    },
    create_td: function(tr,i,date,class_Css) {
        var localThis = this;
        var td = new Element('td');
        if (date) {
            var today = new Date();
            var dia = date.getDate();
            var mes = (date.getMonth()+1);
            var stringDay=date.getFullYear() + '/'+ mes +'/'+ dia;
            idx=stringDay;
            var todayStartWeek= new Date();
            todayStartWeek.setDate(todayStartWeek.getDate()-todayStartWeek.getDay()+this.config.Lng.first-1);
            if(this.localMCalendars.reservedDays[stringDay]){
                class_Css+=" reserved";
            }
            if(date < todayStartWeek){
                class_Css+= " beforeToday";
            }
            if(this.single){
                td.setProperty('id', "single"+idx);
            }else{
                if(class_Css=="noday"){
                    td.setProperty('id', "n"+idx);
                }else{
                    td.setProperty('id', idx);
                    if(this.localMCalendars.selectedArray[idx])
                        td.addClass('dayselected');
                }
            }
        }
        if (class_Css) td.addClass(class_Css);
        // Today ??
        var today = new Date();
        today = today.getDate() + "/" + (today.getMonth()+1) + "/" + today.getFullYear();
        if (date) var date_td = date.getDate() + "/" + (date.getMonth()+1) + "/" + date.getFullYear();
        if (today == date_td) td.addClass('isToday');

        td.appendText(i);
        td.injectInside(tr);
        if(class_Css.indexOf("beforeToday")==-1 && !localThis.readOnly){
            td.addEvent('click', function(e) {
                 localThis.clickHandler(td.id);
            });
            td.addEvent('mouseover', function(e) {
                 localThis.addClassThisWeek(td.id,'dayhover');
            });
            td.addEvent('mouseout', function(e) {
                 localThis.addClassThisWeek(td.id,'dayhover',true);
            });
        }
    },
    effect: function(div,op) {
      div.style.display='';
      /*
          var ef = new Fx.Style(div, 'opacity', {
                duration: 50,
                transition: Fx.Transitions.quartInOut
            });
            ef.start(1);
        */
    },
    validate_date: function (date) {
          var regex = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
          return date.test(regex);
    },
    selectThisWeek: function(idx){
        var myDate=new Date(idx);
        if(myDate.getDay()!=this.config.Lng.first)
            myDate.setDate(myDate.getDate()-myDate.getDay()-7+this.config.Lng.first);
        if(this.we){
            myDate.setDate(myDate.getDate()+6);//go to next friday
        }
        if(!this.localMCalendars.weekOnlyMonths[myDate.getMonth()+1]){
            this.selectDay(idx);
        }else{
             if(this.localMCalendars.selectedArray.length>0){
                 var firstSelectedDate=new Date(this.localMCalendars.selectedArray[0]);
                 var lastSelectedDate=new Date(this.localMCalendars.selectedArray[this.localMCalendars.selectedArray.length-1]);
                 var lastMyDate=new Date(myDate);
                 lastMyDate.setDate(lastMyDate.getDate()+7);
                 lastSelectedDate.setDate(lastSelectedDate.getDate()+1);
                 if($(idx).hasClass('dayselected')){
                     if(!(lastSelectedDate.getTime()==lastMyDate.getTime() || firstSelectedDate.getTime()==myDate.getTime()))
                         return;
                 }else{
                     if(!(lastSelectedDate.getTime()==myDate.getTime() || firstSelectedDate.getTime()==lastMyDate.getTime()))
                         return;
                 }
             }
             /*
             var endDate=new Date(myDate);
             endDate.setDate(endDate.getDate()+7);
             endDateIdx=endDate.getFullYear() + '/'+ (endDate.getMonth()+1) +'/'+ endDate.getDate();
             if()*/
             for(j=0;j<7;j++){
                var xId=myDate.getFullYear() + '/'+ (myDate.getMonth()+1) +'/'+ myDate.getDate();
                   if(!this.localMCalendars.reservedDays[xId]){
                       this.selectDay(xId);
                   }
                   myDate.setDate(myDate.getDate()+1);
             }
             this.localMCalendars.selectedArray.sort(function(a,b){
                 var dateA=new Date(a);
                 var dateB=new Date(b);
                 return dateA.getTime()-dateB.getTime();
             });
        this.localMCalendars.updateCart();
         }
    },
    selectDay:function(idx){
        if($(idx).hasClass('dayselected')){
             this.localMCalendars.selectedArray.remove(idx);
             this.localMCalendars.selectedArray[idx]=null;
             $(idx).removeClass('dayselected');
        }else{
               $(idx).addClass('dayselected');
               this.localMCalendars.selectedArray.push(idx);
               this.localMCalendars.selectedArray[idx]=idx;
        }
        //this.localMCalendars.updateCart();
    },
    /*updateCart:function(){
        mPrenota.cart.updateCart({'selectedDays':this.localMCalendars.selectedArray});
    },*/
    addClassThisWeek: function(idx,className,remove){
        var idxDate=idx;
        if(this.single){
            idxDate=idx.substring("single".length,idx.length);
        }
        try{
            var myDate=new Date(idxDate);
            
            if(myDate.getDay()!=this.config.Lng.first){//go back to first day of week
                myDate.setDate(myDate.getDate()-myDate.getDay()-7+this.config.Lng.first);
            }
            if(this.we){
                myDate.setDate(myDate.getDate()+6);//go to next friday
            }
            var numerOfDaysToSelect=this.we?3:7;
            
            if(!this.localMCalendars.weekOnlyMonths[myDate.getMonth()+1]){
                if(!this.localMCalendars.reservedDays[idxDate]){
                    if(remove)
                           $(idx).removeClass(className);
                   else
                       $(idx).addClass(className);
                   }
            }else{
                 if(this.localMCalendars.selectedArray.length>0){
                     var firstSelectedDate=new Date(this.localMCalendars.selectedArray[0]);
                     var lastSelectedDate=new Date(this.localMCalendars.selectedArray[this.localMCalendars.selectedArray.length-1]);
                     var lastMyDate=new Date(myDate);
                     lastMyDate.setDate(lastMyDate.getDate()+7);
                     lastSelectedDate.setDate(lastSelectedDate.getDate()+1);
                     if($(idx).hasClass('dayselected')){
                         if(!(lastSelectedDate.getTime()==lastMyDate.getTime() || firstSelectedDate.getTime()==myDate.getTime()))
                             return;
                     }else{
                         if(!(lastSelectedDate.getTime()==myDate.getTime() || firstSelectedDate.getTime()==lastMyDate.getTime()))
                             return;
                     }
                 }
                 for(i=0;i<numerOfDaysToSelect;i++){
                    var xId="";
                    if(this.single){
                        xId+="single";
                    }
                    xId+=myDate.getFullYear() + '/'+ (myDate.getMonth()+1) +'/'+ myDate.getDate();
                       if(!this.localMCalendars.reservedDays[xId]){
                           if(remove){
                               if($(xId).hasClass("dayselected")){
                                   $(xId).style.color="#000000";
                               }else{
                                   $(xId).style.color="#FFFFFF";
                               }
                               $(xId).removeClass(className);
                               if(this.single && i==0){
                                   $(xId).removeClass("dayselected");
                                   $(xId).style.color="#FFFFFF";
                               }
                           }else{
                               if($(xId).hasClass("dayselected")){
                                $(xId).style.color="#D3D3D3";
                               }else{
                                   $(xId).style.color="#000000";
                               }
                               var xclass=className;
                               if(this.single){
                                   $(xId).style.color="#FFFFFF";
                                   if(i==0){
                                       xclass="dayselected";
                                       $(xId).style.color="#000000";
                                   }
                               }
                               $(xId).addClass(xclass);
                           }
                       }
                       myDate.setDate(myDate.getDate()+1);
                 }
             }
         }catch(e){}
     },
     reset:function(){
         var localThis=this;
         this.tbody.getElements('td').each(function(element){
             if(element.hasClass("dayselected"))
                 element.style.color="#FFFFFF";
             element.removeClass('dayselected');
         });
         this.localMCalendars.updateCart();
     }
});

//var localMCalendars;
var mCalendars = new Class({
    selectedArray :new Array(),
    initialize: function(options) {
        var localThis=this;
          this.readOnly = options.readOnly || false;
          this.container=$(options.idContainer) || document.body;
          this.reservedDays = options.reservedDays || new Array();
          this.weekOnlyMonths = options.weekOnlyMonths || new Array();
          this.selectedArray = options.preSelectedArray || new Array();
           var today=options.date || new Date();
          var single=options.single || false;
          this.singleCal=null;
          if(single){
                this.singleCal=new mCalendar({localMCalendars:this,single:true,isFirst:true,isLast:true,el:options.el,className:'mcalendarSingle',date:today,readOnly:false,we:options.we});
              return;
          }
          
          var todayTemp = new Date(today.getTime());
          var nextMonth =new Date(todayTemp.setMonth(today.getMonth()+1,1));
          var todayTemp = new Date(today.getTime());
          var nextNextMonth =new Date(todayTemp.setMonth(today.getMonth()+2,1));
          //console.log(nextNextMonth);
      
          this.prev = new Element('div').setStyles({'width':'49px','padding-top':'50px','text-align':'center'}).setProperty('id', 'arrowLeft').injectInside(this.container);      
          this.prev.innerHTML='<img src="/images/arrow_left.gif"/>';
          this.prev.setOpacity(0.3);
          this.prev.addEvent('click', function(e) {
              localThis.goPrev();
          });
      
          var options1={localMCalendars:this,idContainer:options.idContainer,date:today,isFirst:true,readOnly:this.readOnly};
        this.cal1=new mCalendar(options1);
          
        var options2={localMCalendars:this,idContainer:options.idContainer,date:nextMonth,readOnly:this.readOnly};
        this.cal2=new mCalendar(options2);
        
        var options3={localMCalendars:this,idContainer:options.idContainer,date:nextNextMonth,isLast:true,readOnly:this.readOnly};
        this.cal3=new mCalendar(options3);
        
        this.next = new Element('div').setStyles({width:'49px','padding-top':'50px','text-align':'center'}).setProperty('id', 'arrowLeft').injectInside(this.container);
        this.next.innerHTML='<img src="/images/arrow_right.gif"/>';
        this.next.addEvent('click', function(){
            localThis.goNext();
        });
        this.next = new Element('div').setProperty('id', 'mCalLegenda').injectInside(this.container);
        var assetLegend={
            'it':{legenda:"Legenda",disp:"disponibile",sel:"selezionato",occ:"occupato"},
            'si':{legenda:"Legenda",disp:"disponibile",sel:"selezionato",occ:"occupato"},
            'en':{legenda:"Legend",disp:"available",sel:"selected",occ:"busy"},
            'de':{legenda:"Legende",disp:"vorhanden",sel:"ausgew&auml;hlt",occ:"besetzt"}
        }
        if(this.readOnly){
            this.next.innerHTML='<span>' +eval("assetLegend."+globalLang+".legenda")+ ':&nbsp;&nbsp;&nbsp;</span><span><img src="/images/mcallegavailable2.png"></span><span>&nbsp;- ' +eval("assetLegend."+globalLang+".disp")+ '&nbsp;&nbsp;&nbsp;</span><span><img src="/images/mcallegbusy2.png"></span><span>&nbsp;- ' +eval("assetLegend."+globalLang+".occ")+ '&nbsp;&nbsp;&nbsp;</span>';
            if(this.selectedArray.length>0){
                this.next.innerHTML+='<span><img src="/images/mcallegselected.png"></span><span>&nbsp;- ' +eval("assetLegend."+globalLang+".sel")+ '</span>';
            }
        }else{
            this.next.innerHTML='<span>' +eval("assetLegend."+globalLang+".legenda")+ ':&nbsp;&nbsp;&nbsp;</span><span><img src="/images/mcallegavailable.png"></span><span>&nbsp;- ' +eval("assetLegend."+globalLang+".disp")+ '&nbsp;&nbsp;&nbsp;</span><span><img src="/images/mcallegbusy.png"></span><span>&nbsp;- ' +eval("assetLegend."+globalLang+".occ")+ '&nbsp;&nbsp;&nbsp;</span><span><img src="/images/mcallegselected.png"></span><span>&nbsp;- ' +eval("assetLegend."+globalLang+".sel")+ '</span>';
        }
      },
      goNext: function(){
        var date = new Date(this.cal1.today.getFullYear(),this.cal1.today.getMonth(),1,0,0,0);
        var today=new Date((new Date()).getFullYear(),(new Date()).getMonth(),1,0,0,0);
          if(date>=today)
              this.prev.setOpacity(1);
          this.cal1.goToNextDate();
        this.cal2.goToNextDate();
        this.cal3.goToNextDate();
      },
      goPrev: function(){
          
          var date = new Date(this.cal1.today.getFullYear(),this.cal1.today.getMonth(),1,0,0,0);
        var today=new Date((new Date()).getFullYear(),(new Date()).getMonth(),1,0,0,0);
          
          if(date <= today){
              this.prev.setOpacity(0.3);
              return;
          }          
          this.prev.setOpacity(1);
          this.cal1.goToPrevDate();
        this.cal2.goToPrevDate();
        this.cal3.goToPrevDate();
      },
      reset: function(){
          this.cal1.reset();
        this.cal2.reset();
        this.cal3.reset();
        this.selectedArray=null;
        this.selectedArray=new Array();
        this.updateCart();
      },
      updateCart: function(){
          mPrenota.cart.updateCart({'selectedDays':this.selectedArray}); 
      }
});
var currCalendarSingle=null;
var calendarSingle = new Class({
    initialize: function(options) {
        var options=options||{};
        var weekOnlyMonths=new Array();
        weekOnlyMonths[1]=1;
        weekOnlyMonths[2]=2;
        weekOnlyMonths[3]=3;
        weekOnlyMonths[4]=4;
        weekOnlyMonths[5]=5;
        weekOnlyMonths[6]=6;
        weekOnlyMonths[7]=7;
        weekOnlyMonths[8]=8;
        weekOnlyMonths[9]=9;
        weekOnlyMonths[10]=10;
        weekOnlyMonths[11]=11;
        weekOnlyMonths[12]=12;
        if(currCalendarSingle){
        try{
            currCalendarSingle.singleCal.div.remove();
            currCalendarSingle.singleCal.iframe.remove();
        }catch(e){}
    }
        currCalendarSingle=new mCalendars({single:true,el:$(options.el.id),weekOnlyMonths:weekOnlyMonths,date:options.date,we:options.we})
    }
});