function getAbsolutePosition(element) {
  var r = { x: element.offsetLeft, y: element.offsetTop };
    if (element.offsetParent) {
      var tmp = getAbsolutePosition(element.offsetParent);
      r.x += tmp.x;
      r.y += tmp.y;
    }
    return r;
};  
  
var startDate;
var endDate;
var callbacks = 0;

function getNextHighestZindex(obj){  
  var highestIndex = 0;  
  var currentIndex = 0;  
  var elArray = Array();  
  if(obj){ elArray = obj.getElementsByTagName('*'); }else{ elArray = document.getElementsByTagName('*'); }  
  for(var i=0; i < elArray.length; i++){  
    if (elArray[i].currentStyle){  
      currentIndex = parseFloat(elArray[i].currentStyle['zIndex']);  
    }else if(window.getComputedStyle){  
      currentIndex = parseFloat(document.defaultView.getComputedStyle(elArray[i],null).getPropertyValue('z-index'));  
    }  
    if(!isNaN(currentIndex) && currentIndex > highestIndex){ highestIndex = currentIndex; }  
  }  
  return(highestIndex+1);  
}  

function resetDates() {
	startDate = endDate = null;
}

/*
* Given two dates (in seconds) find out if date1 is bigger, date2 is bigger or
 * they're the same, taking only the dates, not the time into account.
 * In other words, different times on the same date returns equal.
 * returns -1 for date1 bigger, 1 for date2 is bigger 0 for equal
 */
function compareDatesOnly(date1, date2) {
	var year1 = date1.getYear();
	var year2 = date2.getYear();
	var month1 = date1.getMonth();
	var month2 = date2.getMonth();
	var day1 = date1.getDate();
	var day2 = date2.getDate();

	if (year1 > year2) {
		return -1;
	}
	if (year2 > year1) {
		return 1;
	}

	//years are equal
	if (month1 > month2) {
		return -1;
	}
	if (month2 > month1) {
		return 1;
	}

	//years and months are equal
	if (day1 > day2) {
		return -1;
	}
	if (day2 > day1) {
		return 1;
	}

	//days are equal
	return 0;

	/* Can't do this because of timezone issues
	var days1 = Math.floor(date1.getTime()/Date.DAY);
	var days2 = Math.floor(date2.getTime()/Date.DAY);
	return (days1 - days2);
	*/
}

function filterDatesStart(cal) {
	startDate = cal.date;
	/* If they haven't chosen an 
	end date before we'll set it to the same date as the start date This
	way if the user scrolls in the start date 5 months forward, they don't
	need to do it again for the end date.
	*/

	if (endDate == null) { 
		/*
    var today=new Date();
    enddatecalendar.destroy();
    enddatecalendar=false;
    enddatecalendar = new Calendar(1, null, onSelectEnd, onCloseEnd);    
    enddatecalendar.setDateStatusHandler(dateInRangeEnd);
    enddatecalendar.create(document.getElementById('endcalendardiv'));
    */
	}
}
function filterDatesEnd(cal) {
	endDate = cal.date;
}
/*
* Both functions disable and hilight dates.
*/

/* 
* Can't choose days after the
* end date if it is choosen, hilights start and end dates with one style and dates between them with another
*/
function dateInRangeStart(date) {
	if (endDate != null) {
		// Disable dates after end date
		var compareEnd = compareDatesOnly(date, endDate);
		if  (compareEnd < 0) {
			//return true;
		}
    if (bookablestartdays[date.getDay()]==0) return true;
		// Hilight end date with "edges" style
		if  (compareEnd == 0) {
			{return "edges";}
		}
		// Hilight inner dates with "between" style
		if (startDate != null){
			var compareStart = compareDatesOnly(date, startDate);
			if  (compareStart < 0 && compareEnd>0) {
				return "between";
			} 
		} 
	}

	//disable days prior to today
	var today = new Date();
	var compareToday = compareDatesOnly(date, today);
	if (compareToday > 0) {
		return true;
	}  
  
	//all other days are enabled
	return false;
	//alert(ret + " " + today + ":" + date + ":" + compareToday + ":" + days1 + ":" + days2);
}
/* 
* Can't choose days before the
* start date if it is choosen, hilights start and end dates with one style and dates between them with another
*/
function dateInRangeEnd(date) {
  if (startDate != null) {
		// Disable dates before start date
    var compareDays = compareDatesOnly(startDate, date);
    if  (compareDays < 0) {
			return true;
		}
    if (bookableenddays[date.getDay()]==0) return true;
		// Hilight end date with "edges" style
		if  (compareDays == 0) {
			return "edges";
		}
    // Hilight inner dates with "between" style
		if ((endDate != null) && (date > startDate) && (date < endDate)) {
			return "between";
		} 
	} 
	var now = new Date();
	if (compareDatesOnly(now, date) < 0) {
		return true;
	}
	//all other days are enabled
	return false;
}
function onSelectStart(calendar, date) {
  filterDatesStart(calendar);
  var input_field = document.getElementById("startDate");
  input_field.value = date;
  if (calendar.dateClicked) {
    calendar.callCloseHandler(); // this calls "onClose" (see above)
  }
};
function onCloseStart(calendar) {
  var today=new Date();
  var sdate=startDate;
  var edate=endDate;
  if (edate<sdate) edate=sdate;
  if (typeof edate == 'undefined') edate=sdate; 
  startdatecalendar.destroy();
  startdatecalendar=false;
  startdatecalendar = new Calendar(1, sdate, onSelectStart, onCloseStart);   
  startdatecalendar.setDateFormat("%d.%m.%Y");
  startdatecalendar.setTtDateFormat("%d.%m.%Y");
  startdatecalendar.setDateStatusHandler(dateInRangeStart);
  startdatecalendar.create(document.getElementById('startcalendardiv'));
  enddatecalendar.destroy();
  enddatecalendar=false;
  enddatecalendar = new Calendar(1, edate, onSelectEnd, onCloseEnd);  
  enddatecalendar.setDateFormat("%d.%m.%Y");
  enddatecalendar.setTtDateFormat("%d.%m.%Y");
  enddatecalendar.setDateStatusHandler(dateInRangeEnd);
  enddatecalendar.create(document.getElementById('endcalendardiv'));
  document.getElementById('endcalendardiv').style.left=document.getElementById('startcalendardiv').style.left;
  document.getElementById('endcalendardiv').style.top=document.getElementById('startcalendardiv').style.top;
  if (document.getElementById('startcalendardiv').style.setAttribute){
    document.getElementById('startcalendardiv').style.setAttribute('display','none');
  }else{
    document.getElementById('startcalendardiv').style.display='none';
  }
  if (document.getElementById('endcalendardiv').style.setAttribute){
    document.getElementById('endcalendardiv').style.setAttribute('display','');
  }else{
    document.getElementById('endcalendardiv').style.display='';
  }
  var newpos=getAbsolutePosition(document.getElementById('endDate'));

  moveto('endcalendardiv',newpos.x, newpos.y+20);
  parsedatetoinputfields();
};    
function onSelectEnd(calendar, date) {
  filterDatesEnd(calendar);
  var input_field = document.getElementById("endDate");
  input_field.value = date;
  if (calendar.dateClicked) {
    calendar.callCloseHandler(); // this calls "onClose" (see above)
  }
};
function onCloseEnd(calendar) {
  var sdate=startdatecalendar.date;
  var edate=enddatecalendar.date;
  startdatecalendar.destroy();
  startdatecalendar=false;
  startdatecalendar = new Calendar(1, sdate, onSelectStart, onCloseStart);    
  startdatecalendar.setDateStatusHandler(dateInRangeStart);
  startdatecalendar.setDateFormat("%d.%m.%Y");
  startdatecalendar.create(document.getElementById('startcalendardiv'));
  enddatecalendar.destroy();
  enddatecalendar=false;
  enddatecalendar = new Calendar(1, edate, onSelectEnd, onCloseEnd);    
  enddatecalendar.setDateStatusHandler(dateInRangeEnd);
  enddatecalendar.setDateFormat("%d.%m.%Y");
  enddatecalendar.create(document.getElementById('endcalendardiv'));
  fadeOut('endcalendardiv');
  parsedatetoinputfields();
  //alert(startDate+"end"+endDate);
};
function showStartDateChooser(){
  fadeOut('endcalendardiv');
  var newpos=getAbsolutePosition(document.getElementById('startDate'));
  document.getElementById('startcalendardiv').style.left=(newpos.x-origposstartcalendar.x)+"px";
  document.getElementById('startcalendardiv').style.top=(newpos.y-origposstartcalendar.y+20)+"px";
  fadeIn('startcalendardiv');
  
  
  
}

function showEndDateChooser(){
  fadeOut('startcalendardiv');
  var newpos=getAbsolutePosition(document.getElementById('endDate'));
  document.getElementById('endcalendardiv').style.left=(newpos.x-origposendcalendar.x)+"px";
  document.getElementById('endcalendardiv').style.top=(newpos.y-origposendcalendar.y+20)+"px";
  fadeIn('endcalendardiv');  
}
var startdatecalendar;
var enddatecalendar;
var origposstartcalendar;
var origposendcalendar;
function initCalendar(){
  if (document.getElementById('startcalendardiv') != null && document.getElementById('endcalendardiv')!= null && document.getElementById('startDate')!= null){
    var caldivx=document.getElementById('startcalendardiv');
    var calparent=caldivx.parentNode;
    calparent.removeChild(caldivx);
    document.body.appendChild(caldivx);
    var caldivx=document.getElementById('endcalendardiv');
    var calparent=caldivx.parentNode;
    calparent.removeChild(caldivx);
    document.body.appendChild(caldivx);
    var highestzindex=getNextHighestZindex(document.body);
    document.getElementById('startcalendardiv').style.zIndex=highestzindex;
    document.getElementById('endcalendardiv').style.zIndex=highestzindex;
    document.getElementById('startcalendardiv').style.left="0px";
    document.getElementById('startcalendardiv').style.top="0px";
    document.getElementById('endcalendardiv').style.left="0px";
    document.getElementById('endcalendardiv').style.top="0px";
    //origposstartcalendar=getAbsolutePosition(document.getElementById('startcalendardiv'));
    //origposendcalendar=getAbsolutePosition(document.getElementById('endcalendardiv'));
    var startdateelap=getAbsolutePosition(document.getElementById('startDate'));
    origposstartcalendar={x:0,y:0};
    origposendcalendar={x:0,y:0};
    if (typeof bookablestartdays == 'undefined') bookablestartdays=new Array(1,1,1,1,1,1,1);
    if (typeof bookableenddays == 'undefined') bookableenddays=new Array(1,1,1,1,1,1,1);
  	var today=new Date();
  	var thestartdatearr=document.getElementById('startDate').value.split('.');
  	if (thestartdatearr.length==3){
  	  var thestartdate=new Date(thestartdatearr[2], thestartdatearr[1]-1, thestartdatearr[0]);
    }else{
      var thestartdate=today;
    }
    startDate=thestartdate;
    var theenddatearr=document.getElementById('endDate').value.split('.');
  	if (theenddatearr.length==3){
  	  var theenddate=new Date(theenddatearr[2], theenddatearr[1]-1, theenddatearr[0]);
    }else{
      var theenddate=today;
    }
    if (theenddate<thestartdate) theenddate=thestartdate;
    endDate=theenddate;
    startdatecalendar = new Calendar(1, thestartdate, onSelectStart, onCloseStart);    
    startdatecalendar.setDateStatusHandler(dateInRangeStart);
    startdatecalendar.setDateFormat("%d.%m.%Y");
    startdatecalendar.setTtDateFormat("%d.%m.%Y");
    startdatecalendar.create(document.getElementById('startcalendardiv'));
    startdatecalendar.setDate(thestartdate);
    enddatecalendar = new Calendar(1, theenddate, onSelectEnd, onCloseEnd);    
    enddatecalendar.setDateStatusHandler(dateInRangeEnd);
    enddatecalendar.setDateFormat("%d.%m.%Y");
    enddatecalendar.setTtDateFormat("%d.%m.%Y");
    //enddatecalendar.setDate(theenddate);
    enddatecalendar.create(document.getElementById('endcalendardiv'));
    document.getElementById('startDate').onchange=function(){ changeinputstartdate(); };
    document.getElementById('endDate').onchange=function(){ changeinputenddate(); };
    document.getElementById('startDate').onkeyup=function(){ trytoparseinputstartdate(); };
    document.getElementById('endDate').onkeyup=function(){ trytoparseinputenddate(); };
  }
}
function parsedatetoinputfields(){
  if (document.getElementById("from_day")!=null) document.getElementById("from_day").value=startdatecalendar.date.getDate()<10 ? "0"+startdatecalendar.date.getDate() : startdatecalendar.date.getDate();
  if (document.getElementById("from_month")!=null) document.getElementById("from_month").value=startdatecalendar.date.getMonth()+1<10 ? "0"+(startdatecalendar.date.getMonth()+1) : (startdatecalendar.date.getMonth()+1);
  if (document.getElementById("from_year")!=null) document.getElementById("from_year").value=startdatecalendar.date.getFullYear();
  if (document.getElementById("to_day")!=null) document.getElementById("to_day").value=enddatecalendar.date.getDate()<10 ? "0"+enddatecalendar.date.getDate() : enddatecalendar.date.getDate();
  if (document.getElementById("to_month")!=null) document.getElementById("to_month").value=enddatecalendar.date.getMonth()+1<10 ? "0"+(enddatecalendar.date.getMonth()+1) : (enddatecalendar.date.getMonth()+1);
  if (document.getElementById("to_year")!=null) document.getElementById("to_year").value=enddatecalendar.date.getFullYear();
}
function trytoparseinputstartdate(){
  startdatecalendar.parseDate(document.getElementById('startDate').value);
}
function trytoparseinputenddate(){
  enddatecalendar.parseDate(document.getElementById('endDate').value);
}
function changeinputstartdate(){
  startdatecalendar.parseDate(document.getElementById('startDate').value);
  parsedatetoinputfields();
 }
function changeinputenddate(){
  enddatecalendar.parseDate(document.getElementById('endDate').value);
  parsedatetoinputfields();
}
browser = undefined;
if(navigator.userAgent.indexOf("MSIE")!=-1)
  browser = "IE";
else
  browser = "Mozilla";
function getOpacity(element){
  var opacity = null;  
  if(browser=="IE") {
    filter = element.style.filter;
    if(filter) {
      alpha = filter.split("alpha(opacity=");
      opacity = alpha[1].substr(0,(alpha[1].length-1))/100;
    }
  }else{
    opacity = element.style.opacity;
  }    
  return opacity;
}
function setOpacity(element, o){
  if(browser=="IE") {
    element.style.filter = "alpha(opacity=" + (o*100) + ")";
  }
  else {
    element.style.opacity = o;
  }
}
var fadetimeouts=Array();
function fadeIn(who) {
    var whoobj=document.getElementById(who);
    whoobj.style.display="";
    opac=getOpacity(whoobj)*100;
    if(opac < 100){
      opac+=10;
      setOpacity(whoobj,opac/100);
      fadetimeouts[who]=setTimeout('fadeIn("'+who+'")', 50);
    }else{
      window.clearTimeout(fadetimeouts[who])
    }
}
function fadeOut(who) {
    var whoobj=document.getElementById(who);    
    opac=getOpacity(whoobj)*100;
    if(opac > 0){
        opac-=10;
        setOpacity(whoobj,opac/100);
        fadetimeouts[who]=setTimeout('fadeOut("'+who+'")', 50);
    }else{
      whoobj.style.display="none";
      window.clearTimeout(fadetimeouts[who]);
    }
}
function moveto(who,endposx,endposy) {
    var whoobj=document.getElementById(who);
    whoobj.style.display="";
    setOpacity(whoobj,1);
    var theposx=parseFloat(whoobj.style.left);
    var theposy=parseFloat(whoobj.style.top);
    if(theposx!=endposx ||  theposy!=endposy){
        newposx=Math.round(theposx+((endposx-theposx)/2));
        newposy=Math.round(theposy+((endposy-theposy)/2));
        whoobj.style.left=newposx+"px";
        whoobj.style.top=newposy+"px";
        setTimeout('moveto("'+who+'",'+endposx+','+endposy+')', 50);
    }else{
      
    }
}
if(window.onload) {
  var temp = window.onload;
  window.onload=function(e) {
    temp(e);
    initCalendar();
  };
}else{
  window.onload=function(e) {
    initCalendar();
  };
}

function ischildof(thechild, theparent){
  if (thechild==theparent) return true;
  while (thechild=thechild.parentNode) {
    if (thechild==theparent) return true;
  }
  return false;
}

//if (window.location.href.indexOf('test=true')!==-1){

  if(window.onclick) {
    var temp = window.onclick;
    window.onclick=function(e) {
      temp(e);
      if (window.event) { 
        which = window.event.srcElement;      
      } else if (e.target) { 
        which = e.target;      
      } else { 
        return;
      }
      //if (which!=document.getElementById('startcalendardiv') && which!=document.getElementById('endcalendardiv')){
      if (!ischildof(which, document.getElementById('startcalendardiv')) && !ischildof(which, document.getElementById('endcalendardiv'))){
        if (getOpacity(document.getElementById('startcalendardiv'))==1) fadeOut('startcalendardiv');
        if (getOpacity(document.getElementById('endcalendardiv'))==1) fadeOut('endcalendardiv');
      }
    };
  }else{
    window.onclick=function(e) {
      if (window.event) { 
        which = window.event.srcElement;      
      } else if (e.target) {
        which = e.target;      
      } else { 
        return;
      }
      if (!ischildof(which, document.getElementById('startcalendardiv')) && !ischildof(which, document.getElementById('endcalendardiv'))){
        if (getOpacity(document.getElementById('startcalendardiv'))==1) fadeOut('startcalendardiv');
        if (getOpacity(document.getElementById('endcalendardiv'))==1) fadeOut('endcalendardiv');
      }
    };
  }
//}
