/**
 * @author jenik
 * sada funkci umoznujici obsluhu deniku
 * navazani odpovidajicich udalosti a ajax
 * a dale manipulaci s kalendarem
 * pro vztvoreni kalendare je vyuzit lehce upraveny kalendar dynarch - viz calendar.js
 * pro komunikaci mezi prhledovym kalendarem a vlastnim denikem (navigace pomoci tlcitek) je k dispozici trida calendarConector.js  
 */
  
  /*definice zakldnich promenych uzivanych dale
  *cal - globalni promena reprezentujici dynarch calendar
  *initialCaledarRequest - jestli ma byt po nacteni stranky proveden ajax Dotaz
  *ajax Object - pole drzici vsechny XMLhttpRequest objekty - umoznuje jejich zruseni prio vyvolani novy ajax pozadavku
  *ajajHandler - nese obsarava vlastni dotazy a zpracovani vysledku  
  *ErrorMessage - Objekt obsahujic chybive zpravy pro ruzne druhy chyb, ztim pouze v ceske verzi        
  */
   //tady si rozsirim mprototype objektu string o metodu umoynujici oriznuti bylych zanku
  String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g,"");
    }
  //window.onload=init
  $(document).ready(init);
  
  window.onunload=Unload;  
 
  window.userLogged=false;
  var lang='cs';
	var cal;
	var diaryType='diary';
	var ajaxPage='/ajax';
	var initialCalendarRequest=true;
	var ajaxObjects=[];
	var ErrorMessage={}
	    ErrorMessage.cs={}
	    ErrorMessage.en={}
	    ErrorMessage.cs.nodata="Pro danou fazi nejsou k dispozici detailni data";
	    ErrorMessage.cs.DBerror="Chyba pri komunikaci s DB \n pozadovana data nejsou k dispozici";
	    ErrorMessage.cs.ConnError="Chyba pri komunikaci s webovým serverem \n Detail chyby :";
	    ErrorMessage.cs.URLparError="Parametry URL nelze zpracovat dennik bude zobrazen v zakladnim modu \n";
	    ErrorMessage.cs.URLdiarTypeError="Špatně zadaný požadavek na zobrazení deníku, \n deník bude zobrazen v modu tréninkový deník \n"

	//funcke obsluhujici  presmerovani na znaorneni predchoziho obdobi (mesic, tyden den) v ramci deniku
	function prevhighlight(){
	//skryju div planu pokud existuje
	     $('#fazePlan').hide();
	     //urcim typ zobrazene preidou a zvolam odpovidajicim zmenu pomoci objektu calendarCOnector
	     //pomoci metody callHandler() objektu cal nastavim spravne zobrazeni i dynarch kalendare
			if(cal.CalConector.type=="day"){
				cal.CalConector.prevDay();
				cal.callHandler();
			}
			else if(cal.CalConector.type=='week'){
				cal.CalConector.prevWeek();
				cal.callHandler();
			}
			else if(cal.CalConector.type=='month'){
				cal.CalConector.prevMonth();
				cal.callHandler();
			}
		}
//funcke obsluhujici  presmerovani na znaorneni nasledujiciho obdobi (mesic, tyden den) v ramci deniku	
//detailni popis obdobny funkci prevhighlight	
	function nexthighlight(){
	     $('#fazePlan').hide();
			if(cal.CalConector.type=="day"){
				cal.CalConector.nextDay();
				cal.callHandler();
			}
			else if(cal.CalConector.type=='week'){
				cal.CalConector.nextWeek();
				cal.callHandler();
			}
			else if(cal.CalConector.type=='month'){
				cal.CalConector.nextMonth();
				cal.callHandler();
			}
		}


		//obsluha chyby pri ajax requestu
		//param
		//XHTMLReq - odkazy na ajax objekt
    //textStatus -staovy kod
    //errorThrown - ppis cyby
		function Error(XHTMLReq,textStatus,errorThrown){
			$('#LoadingMessage').css('display','none');
			//sestaveni popisu chyby
		
      if(textStatus)var errstr=textStatus;
			if(errorThrown)var errstr=errorThrown;
			if(XHTMLReq.responseText) var errorText=XHTMLReq.responseText;
			if(XHTMLReq.responseXML) var errorText=XHTMLReq.responseXML;   
			var err='<p style="color:red">'+ErrorMessage[lang].ConnError+" "+errstr;
			destructCrossRef.call($('#BigCal').get(0));
			$('#BigCal').empty();
			//pridani chyby do hlavniho divu deniku
			$('#BigCal').html(err);
		}
		//osetreni chyb pro ajax dotazy vraceji dotazy ve forme json ktere nechci zobrazit v ramci hlavniho divu deniku
		function ErrorPOP(XHTMLReq,textStatus,errorThrown){
		  location.hash='#type=faze&diaryType='+window.diaryType+'&fid='+window.actualID+'&date='+window.codeDate(cal.CalConector.date,0)
			$('#LoadingMessage').css('display','none');
      if(textStatus)var errstr=textStatus;
			if(errorThrown)var errstr=errorThrown;
			if(XHTMLReq.responseText)var errorText=XHTMLReq.responseText;
			if(XHTMLReq.responseXML)var errorText=XHTMLReq.responseXML;
			alert(ErrorMessage[lang].ConnError+" "+errstr)
		}
	
		//obsluha udalosti klinkuti na tlacitka
		//evt - objekt udalosti
		//umoznuje prepinani mezi rezimem den tyden mesic
		function handle(evt){
			if(this.id=="day" || this.id=="week" || this.id=="month"){
			$('#fazePlan').hide();
				if(this.id=="day"){
				  cal.CalConector.setType("day");
				  cal.callHandler()
				}
				else if(this.id=="month"){
						cal.CalConector.setType("month");
						cal.callHandler()
				}
				else if(this.id=="week"){
						cal.CalConector.setType("week");
						cal.callHandler()
				}
			}
		  else if(this.id=="loginButton"){
		      var user=$('#user').attr("value");
		      var pass=$('#password').attr("value");
		      $('#ErroLogin').css("display","none");
		      //alert($(this).parent().parent().parent().html());
		      if(user.trim()=='')  { $('#ErroPovine').css("display","block");
                    return false };
		      if(pass.trim()=='') {$('#ErroPovine').css("display","block");;
                  return false }; 
          //alert('ok');
         	$('#currSetting').attr("value",location);      
           //$(this).parent().parent().parent().trigger("submit");
          //ajaxReq.LoggUser(user,pass);
        }
      else if(this.id=='loginShow'){
			        var pom1=$(this).attr('langattr');
              var pom2=$(this).attr('title');
              $(this).attr('title',pom1);
              $(this).attr('alt',pom1);
              $(this).attr('langattr',pom2);
              if(!this.loginShow){
          
                  this.loginShow=true;
                  $(this).parent().parent().find('div').show();
                  $(this).attr('src','/obr/knob_download.png');
            }
            else{
               this.loginShow=false;
               $(this).parent().parent().find('div').hide();
               $('#ErroPovine').hide();
               $(this).attr('src','/obr/knob_forward.png');
            }
        }
		}
		
		
		//nastveni pozice elementu informujicho o tom ze se stranka nacita
		function setLoadingMessage(){
        var width=(window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth);
        //left=width/2-parseFloat($('#LoadingMessage').css("width"))/2;
        //$('#LoadingMessage').css("left",left+'px');
      }
    //genericka funkce umoznujici spocit jakej je X a Y scrool dane stranky
    function getScrollXY() {
        var x = 0, y = 0;
        if( typeof( window.pageYOffset ) == 'number' ) {
           // Netscape
          x = window.pageXOffset;
          y = window.pageYOffset;
        } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
         // DOM
          x = document.body.scrollLeft;
          y = document.body.scrollTop;
        } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
             // IE6 standards compliant mode
             x = document.documentElement.scrollLeft;
            y = document.documentElement.scrollTop;
        }
        return [x, y];
      }
   
   //fuknkce sledujici pohyb misi a nastavujic pozici elementu podle pozice misi
   //e - objekt udalosti
   //divvOff - offset  elementu v ramci stranky
    function move(e,divOff){
    
      var scrollOffXY=getScrollXY();
      var xpos=e.clientX+scrollOffXY[0]-divOff[0];
      var ypos=e.clientY+scrollOffXY[1]-divOff[1];
      //alert(xpos)
      $('#fazePlan').css('left',xpos);
      $('#fazePlan').css('top',ypos)
    }
    
    /*
    *funkce obsluhujici nnavazani udalosit na div predstavujici okno detailu faze pri rezimu plan
    *navaze odpoviudajici udalosti, ktere umoznuji aby div byl dragable    
    */
    function setPlanFazeMessage(){
        //var width=(window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth);
        //left=width/2-500/2;
        //$('#fazePlan').css("left",left+'px');
        $('#fazePlanHeader').bind('mousedown',function(e){this.isDragable=true;
          scrollXY=getScrollXY();
          this.profile=$('#fazePlan').get(0);
          var xOffset=0;
          var yOffset=0;
          //vypocet offsetu v ramci stranky
          if(this.profile.offsetParent){
          var obj=this.profile;
          do{
            xOffset += obj.offsetLeft;
			     yOffset += obj.offsetTop;
          }while(obj=obj.offsetParent)
          }
          var innerOffset=[e.clientX+scrollXY[0]-xOffset,e.clientY+scrollXY[1]-yOffset];
          $('body').bind('mousemove',{divOffset:innerOffset},function(e){
            var divOffset=e.data.divOffset
            move(e,divOffset)})
          });
        $('body').bind('mouseup',function(){
            $('body').unbind('mousemove');
          });
        
        $('#fazePlanClose').bind("mouseover",function(){$(this).css('cursor','pointer');});
        $('#fazePlanClose').bind("mouseleave",function(){$(this).css('cursor','pointer');});
        $('#fazePlanClose').bind('click',function(){
          $('#fazePlan').css({
            display:"none",
            width:"500px",
            height:"20px"
            }); 
          $('#fazePlanTextCont').empty();
          })
      }
    
    //obsluha pohybu vyskakujiciho okenka
     function setLoginMessage(){
        //var width=(window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth);
        //left=width/2-500/2;
        //$('#fazePlan').css("left",left+'px');
        $('#winHeader').bind('mousedown',function(e){
          this.isDragable=true;
          scrollXY=getScrollXY();
          this.profile=$('#rezervDetailWindow').get(0);
          var xOffset=0;
          var yOffset=0;
          //vypocet offsetu v ramci stranky
          var relativeDoc=document.getElementById('BigCalContainer')
          if(this.profile.offsetParent){
            var obj=this.profile;
            do{
                if(relativeDoc==obj) break;
                xOffset += obj.offsetLeft;
			         yOffset += obj.offsetTop;
              }while(obj=obj.offsetParent)
            }
          var innerOffset=[e.clientX+scrollXY[0]-xOffset,e.clientY+scrollXY[1]-yOffset];
          //vazu mouseup na body aby reagoval cely dokument
          $('body').bind('mousemove',{divOffset:innerOffset},function(e){
            var divOffset=e.data.divOffset
            move(e,divOffset)})
          });
        $('body').bind('mouseup',function(){
            $('body').unbind('mousemove');
          });
        $('#winHeader').bind("mouseover",function(){$(this).css('cursor','move');});
        $('#winHeader').bind("mouseleave",function(){$(this).css('cursor','move');});
      }
    
    //pomocne funke pro ovladai drag drop
    //funkce pocita  offset strankz pomoci sroll baru
  function getScrollXY() {
        var x = 0, y = 0;
        if( typeof( window.pageYOffset ) == 'number' ) {
           // Netscape
          x = window.pageXOffset;
          y = window.pageYOffset;
        } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
         // DOM
          x = document.body.scrollLeft;
          y = document.body.scrollTop;
        } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
             // IE6 standards compliant mode
             x = document.documentElement.scrollLeft;
            y = document.documentElement.scrollTop;
        }
        return [x, y];
      }
   
   //fuknkce sledujici pohyb misi a nastavujic pozici elementu podle pozice misi
   //e - objekt udalosti
   //divvOff - offset  elementu v ramci stranky
    function move(e,divOff){
    
      var scrollOffXY=getScrollXY();
      var xpos=e.clientX+scrollOffXY[0]-divOff[0];
      var ypos=e.clientY+scrollOffXY[1]-divOff[1];
      //alert(xpos)
      $('#rezervDetailWindow').css('left',xpos);
      $('#rezervDetailWindow').css('top',ypos)
    }
    
    
    //fuknce volana po nacteni stranky
    //inicializace vsech dulezitych hodnot
		function init(){
		var ajaxReq=new ajaxHandler(window.fitnessID,window.lang,"month")
			//navazni zakladnich udalosti pro tlacitka
			//alert($('#pica').get())
			//nastaveni spravnych location hodnot
			ajaxReq.setRefLinkForLoging();
			$('.loginenter').find('img').bind('mouseover',function(){$(this).addClass('hover');});
			$('.loginenter').find('img').bind('mouseout',function(){$(this).removeClass('hover');});
			$('.loginenter').find('img').bind('click',function(){
			    var pom1=$(this).attr('langattr');
          var pom2=$(this).attr('title');
          $(this).attr('title',pom1);
          $(this).attr('alt',pom1);
          $(this).attr('langattr',pom2);
          if(!this.loginShow){
          
              this.loginShow=true;
              $(this).parent().parent().find('div').show();
              $(this).attr('src','/obr/knob_download.png');
            }
          else{
               this.loginShow=false;
               $(this).parent().parent().find('div').hide();
               $('#ErroPovine').hide();
               $(this).attr('src','/obr/knob_forward.png');
            }
        })
			$('#day').bind("mouseover",function(){$(this).addClass('hover');});
			$('#day').bind("mouseout",function(){$(this).removeClass('hover');});
			$('#week').bind("mouseover",function(){$(this).addClass('hover');});
			$('#week').bind("mouseout",function(){$(this).removeClass('hover');});
			$('#month').bind("mouseover",function(){$(this).addClass('hover');});
			$('#month').bind("mouseout",function(){$(this).removeClass('hover');});
			
			//alert(location.hash);
			//tato fuknce je volan pri kliknuti na nektery z elementu
			//je volana pri kazde zmene data v dynarch kalendari
			//kalendare dynarch menici datum 
			//predava parametr reprezentujic odkaz na kalendar
			function dateChanged(calendar) {   
			//alert(calendar.CalConector.type)
			  $('#fazePlan').hide();
			  $('#fazeButtons').css('display','none');
				$('#calButtons').css('display','block');
				//alert(calendar.CalConector.type);
				//zjistuje z caledarCOnectoru jaky typ zobrazeni je proi denik nastven
        if(calendar.CalConector.type=="month"){
			$('#day').removeClass('active');
			$('#week').removeClass('active');
			$('#month').addClass('active');
			// informace o datumech (tydnech mesic roku atd) ktere byly nastaveny pri minulem vyberu
			//aby se pri pokaovanem kliknuti na stejny datum nenacital kalendar opetvne znoviu se stejnymi daty
         calendar.CalConector.BeforeDay=null;
         calendar.CalConector.BeforeWeekNum=null;
         calendar.CalConector.BeforeWeekMonth=null;
         calendar.CalConector.BeforeWeekYear=null;
         calendar.CalConector.BeforeDayMonth=null;
         calendar.CalConector.BeforeDayYear=null;
        //pokuid je nasteven predchozi mesic
          if(calendar.CalConector.BeforeMonth){
              var bM=calendar.CalConector.BeforeMonth.getMonth();
              var bY=calendar.CalConector.BeforeMonth.getFullYear();
              //nastaveni novych hodnot pro predhoczi mesic
              calendar.CalConector.BeforeMonth=new Date();
              calendar.CalConector.BeforeMonth.setFullYear(calendar.date.getFullYear());
              calendar.CalConector.BeforeMonth.setMonth(calendar.date.getMonth());
              calendar.CalConector.BeforeMonth.setDate(calendar.date.getDate());
              //pokud je predchozi mesic stejny jako aktulani
              if(bM==calendar.date.getMonth() && bY==calendar.date.getFullYear()){
                  //nic noveho nenacitam prootze ty data uz jsou jednou nacteny
                  return false;
                }
            }
            //nastaveni minuleho mesice (co se tyce calendarCOnecotu)
            calendar.CalConector.BeforeMonth=new Date();
            calendar.CalConector.BeforeMonth.setFullYear(calendar.date.getFullYear());
            calendar.CalConector.BeforeMonth.setMonth(calendar.date.getMonth());
            calendar.CalConector.BeforeMonth.setDate(calendar.date.getDate());
          }
          //obdobny postup pro tyden
         if(calendar.CalConector.type=="week"){
			$('#day').removeClass('active');
			$('#week').addClass('active');
			$('#month').removeClass('active');
            calendar.CalConector.BeforeDay=null;
            calendar.CalConector.BeforeDayMonth=null;
            calendar.CalConector.BeforeDayYear=null;
            calendar.CalConector.BeforeMonth=null;
            if(calendar.CalConector.BeforeWeekNum && calendar.CalConector.BeforeWeekMonth && calendar.CalConector.BeforeWeekYear){
              if(calendar.CalConector.BeforeWeekNum==calendar.CalConector.actualWeek && calendar.date.getMonth()==calendar.CalConector.BeforeWeekMonth && calendar.date.getFullYear()==calendar.CalConector.BeforeWeekYear){
                  calendar.CalConector.BeforeWeekNum=calendar.CalConector.actualWeek;
                  calendar.CalConector.BeforeWeekMonth=calendar.date.getMonth();
                  calendar.CalConector.BeforeWeekYear=calendar.date.getFullYear();
                  return;
                }
              }
            calendar.CalConector.BeforeWeekNum=calendar.CalConector.actualWeek;
            calendar.CalConector.BeforeWeekMonth=calendar.date.getMonth();
            calendar.CalConector.BeforeWeekYear=calendar.date.getFullYear();
          }
          //obdobny postup pro den
       if(calendar.CalConector.type=="day"){
			$('#day').addClass('active');
			$('#week').removeClass('active');
			$('#month').removeClass('active');
            calendar.CalConector.BeforeWeekNum=null;
            calendar.CalConector.BeforeMonth=null;
            calendar.CalConector.BeforeWeekMonth=null;
            calendar.CalConector.BeforeWeekYear=null;
            if(calendar.CalConector.BeforeDay && calendar.CalConector.BeforeDayMonth && calendar.CalConector.BeforeDayYear){
                if(calendar.date.getDate()==calendar.CalConector.BeforeDay && calendar.date.getMonth()==calendar.CalConector.BeforeDayMonth && calendar.date.getFullYear()==calendar.CalConector.BeforeDayYear ){
                    calendar.CalConector.BeforeDay=calendar.date.getDate();
                    return;
                  }
              }           
            calendar.CalConector.BeforeDay=calendar.date.getDate()
            calendar.CalConector.BeforeDayMonth=calendar.date.getMonth();
            calendar.CalConector.BeforeDayYear=calendar.date.getFullYear();
          }
        //pokud vse prosli zavolam ajax request s datumem nastavenym v racmi dynarchcalendaru a typu nastavenem v calendarCOnectoru
        ajaxReq.ajaxRequest(calendar.CalConector.type,calendar.date) 
    }

      //vytvoreni objektu calendarConector (viz calendarCOnectot.js)
      var CalendarConnector=new CalConector("week",new Date());
    //vytvoreni kaledare dynarch - je upraven pro me potreby
      cal=Calendar.setup(
       {
            flat         : "CalendarSpace", // ID of the parent element
            flatCallback : dateChanged,          // our callback function
            firstDay  : 1,
            showOthers: true,
            dateStatusFunc: dateStatusHandler,
            range: [1970,2030],
            CalConector: CalendarConnector
            }
      )
       
    //tato funkce je volana pri zmene data v dynarch kalednari
    //vytvari pole dn ktere maji byt specilane zbyrazneni v ramic dynarch kalendaru
    
     function dateIsSpecial(date,year, month, day) {
      if(CalendarConnector.SpecialDays){
      var m = CalendarConnector.SpecialDays[date.getMonth()];
      if (!m) return false;
      //alert(m+' m'+date.getMonth())
      for (var i=0;i<m.length;i++) {
        if(m[i] == day ) return true;      
        }
        return false
      }
       else return false
      }
      //tohle nevyuzivam
      function dateStatusHandler(date, y, m, d) {
      if (dateIsSpecial(date,y, m, d)){
        return "special";
        }
     else return false;
      }	
      
      //navzani obsluznych udalosti pro tlacikta		
			$("#day").bind("click",handle);
			$("#month").bind("click",handle);
			$("#week").bind("click",handle);
			//$('#loginButton').bind('click',handle)
			$("#nextbut").bind("click",prevhighlight);
			$("#prevbut").bind("click",nexthighlight);
			//$("#todaybut").bind("click",today);
			
			/*$('#logOut').bind('click',function(){
			   $('#currSetting').attr("value",location);    
        })*/
			
			//navazani udalosti pro tlacitko zpet do kalendare
			$('#kalendarbut').bind('click',function(){ 
			    //vracim se do typu z ktereho jsem prisel
          if(this.calendarType=='day'){
            cal.CalConector.setType("day");
			      cal.CalConector.BeforeDay=null;
			      cal.callHandler();
			    }
			    else if(this.calendarType=='week'){
            cal.CalConector.setType("week");
			      cal.CalConector.BeforeWeekNum=null;
			      cal.callHandler();
            }
          else{
            cal.CalConector.setType("month");
			      cal.CalConector.BeforeMonth=null;
			      cal.callHandler();        
          }			    
					$('#fazeButtons').css('display','none');
					$('#calButtons').css('display','block');
					})
			//$("input[type='checkbox']").bind("click",function(){window.getGraph(); alert('clicked')})
			//navazani udalosti clikc na policka inout fimrmulare
			window.setLoadingMessage()
			$('#LoadingMessage').ajaxStart(function(){$(this).show()});
			$('#LoadingMessage').ajaxStop(function(){$(this).hide();});
			//kontrola jazykove verze
			//zatim jen ceska
      if(lang=='cs'){
        $('#langModEN').bind('click',function(){
           	$('#fazeIMG').remove();
           var pom=location.href;
           pom=location.href.split("/");
           var URL=pom[2]+"/en/";
           pom[0]=null;
           for(var i=3;i<pom.length;i++){
              URL=URL+pom[i]+'/';
            }
            URL=URL.substring(0,URL.length-1)
            alert(URL);
           //var pom='http://'+location.hostname+location.pathname+'?lang=en'+location.hash;
           //location.replace(pom);
          })
        }
      if(lang=='en'){
        $('#langModCS').bind('click',function(){
           	$('#fazeIMG').remove();
           	 var pom=location.href;
            pom=location.href.split("/");
            var URL=pom[2];
             for(var i=4;i<pom.length;i++){
              URL=URL+pom[i]+'/';
            }
            URL=URL.substring(0,URL.length-1)
            alert(URL);
           //var pom='http://'+location.hostname+location.pathname+'?lang=cs'+location.hash;
           //location.replace(pom);
          })
        }
      //zisakni objektu URL nesouci informace o parametrech predavanych z URL
      //volam funkci getURLparams
      var pom=ajaxReq.getURLparams();
      //z hodnot ziskane objektu inicializuji zkladni vlasntosti deniku
      //a nasledne volam ajax dotaz
			if(pom){
				if(pom.type=='detail'){
				  cal.CalConector.setDate(pom.date)
					cal.CalConector.setType('day');
					//cal.Highlight(pom.date,'day');
					ajaxReq.lekceID=pom.lekceID;
					$('#fazeButtons').show();
					$('#calButtons').hide();
					ajaxReq.ajaxRequest('detail',pom.date);
					//cal.callHandler();
				}
				else{
					window.diaryType=pom.diaryType;
					cal.CalConector.setDate(pom.date)
          cal.CalConector.setType(pom.type);
					cal.callHandler();	
					}			
			}
			else{
			 
					cal.callHandler();
				}

		}
		//funkc ktera rusi objekty a obsluhy udalosti pri odchodu ze stranky
		function Unload(){
         CalConector.calenda=null;
		    cal.CalConector=null;
        CalConector=null;
        cal=null;
        ajaxObjects=null;
      }
		
		
		

