﻿function refreshT() {
	dateChange(document.getElementById("date1").value,1);
}

function getWeekNr(theDate)
{
	var tmpDate = theDate;
	tmpDate = tmpDate.split(",")
	var today = new Date(parseInt(tmpDate[0]),parseInt(tmpDate[1])-1,parseInt(tmpDate[2]));
	Year = takeYear(today);
	Month = today.getMonth();
	Day = today.getDate();
	now = Date.UTC(Year,Month,Day+1,0,0,0);
	var Firstday = new Date();
	Firstday.setYear(Year);
	Firstday.setMonth(0);
	Firstday.setDate(1);
	then = Date.UTC(Year,0,1,0,0,0);
	var Compensation = Firstday.getDay();
	if (Compensation > 3) Compensation -= 4;
	else Compensation += 3;
	NumberOfWeek =  Math.round((((now-then)/86400000)+Compensation)/7);
	return NumberOfWeek;
	
}

function takeYear(theDate)
{
	x = theDate.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return y;
}

function clearOut(theNode) {
	if(document.getElementById(theNode)) {
		var oNodeToRemove = document.getElementById(theNode);
		oNodeToRemove.parentNode.removeChild(oNodeToRemove);		
	}
}

function clearInner(theNode) {
	if(document.getElementById(theNode)) {
		document.getElementById(theNode).style.display = "none";
		document.getElementById(theNode).innerHTML = "";
	}
}

function dateChange(theDate,forced) {
	var selectedDate = theDate;
	if(selectedDate) {
		selectedDate = selectedDate.split("-");
		var selectedDay = parseFloat(selectedDate[1]);
		var selectedMonth = selectedDate[0];
		var selectedYear = selectedDate[2];
		
		//GET MONDAY OF WEEK TO FIX BUG FOR DISPLAYING WRONG MONTH WHEN YEAR CHANGE
		var myDate=new Date();
		
		strDateMonth = parseFloat(selectedMonth)-1;
		strDateDay = parseFloat(selectedDay);
		strDateYear = parseFloat(selectedYear);
		
		if(strDateYear<10){
			strDateYear = "0"+strDateYear
		}
		if(strDateMonth<10){
			strDateMonth = "0"+strDateMonth
		}
		if(strDateDay<10){
			strDateDay = "0"+strDateDay
		}
		
		myDate.setFullYear('20'+strDateYear,strDateMonth,strDateDay);
		
		strDateAdd = 0;
		if(myDate.getDay()==0){
			strDateAdd = 6;
		}else if(myDate.getDay()==1){
			strDateAdd = 0;
		}else if(myDate.getDay()==2){
			strDateAdd = 1;
		}else if(myDate.getDay()==3){
			strDateAdd = 2;
		}else if(myDate.getDay()==4){
			strDateAdd = 3;
		}else if(myDate.getDay()==5){
			strDateAdd = 4;
		}else if(myDate.getDay()==6){
			strDateAdd = 5;
		}
		
		strDateMonth = parseFloat(selectedMonth)-1;
		strDateDay = parseFloat(selectedDay)-strDateAdd;
		strDateYear = parseFloat(selectedYear);
		
		if (strDateMonth == 0) strMaxDateDay = 31;//januar
		if (strDateMonth == 1) {
			if (( strDateYear == 08) || ( strDateYear == 12) || ( strDateYear == 16) || ( strDateYear == 18) || ( strDateYear == 22) || ( strDateYear == 26)) {
				strMaxDateDay = 29;//februar skudår
			}
			else {
				strMaxDateDay = 28;//februar
			}
		}
		if (strDateMonth == 2) strMaxDateDay = 31;//marts
		if (strDateMonth == 3) strMaxDateDay = 30;//april
		if (strDateMonth == 4) strMaxDateDay = 31;//maj
		if (strDateMonth == 5) strMaxDateDay = 30;//juni
		if (strDateMonth == 6) strMaxDateDay = 31;//juli
		if (strDateMonth == 7) strMaxDateDay = 31;//august
		if (strDateMonth == 8) strMaxDateDay = 30;//september
		if (strDateMonth == 9) strMaxDateDay = 31;//oktober
		if (strDateMonth == 10) strMaxDateDay = 30;//november
		if (strDateMonth == 11) strMaxDateDay = 31;//december
		
		if (strDateDay<1){
			strDateDay = strDateDay+strMaxDateDay;
			strDateMonth = strDateMonth-1;
		}
		if (strDateMonth<0){
			strDateMonth = strDateMonth+12;
			strDateYear = strDateYear-1;
		}
		
		if(strDateYear<10){
			strDateYear = "0"+strDateYear
		}
		if(strDateMonth<10){
			strDateMonth = "0"+strDateMonth
		}
		if(strDateDay<10){
			strDateDay = "0"+strDateDay
		}
		
		myDate.setFullYear('20'+strDateYear,strDateMonth,strDateDay);
		
		strYear = myDate.getFullYear();
		
		strMonth = myDate.getMonth();
		
		strDay = myDate.getDate();
		
		
		var switchDate = strYear + ", " + String(strMonth) + ", " + strDay;
		selectedDate = strYear + "," + String(strMonth) + "," + strDay;
		
		var selectedWeek = getWeekNr(selectedDate);
		if((selectedWeek!=currWeek || forced == 1) && document.getElementById("weekTable")) {

		clearOut("weekTable");	
		clearInner("addDiv");	
		clearInner("addDivShadow");
		
		initWeek(switchDate);
		currWeek = selectedWeek;
		}

	}	
}


function strip(streng) {
	var tmpReturn = streng;
	if(tmpReturn!="") {
		tmpReturn = tmpReturn.replace(/%/g,"%25");
		tmpReturn = tmpReturn.replace(/&/g,"%26");
		tmpReturn = tmpReturn.replace(/\n/g,"||BR||");
		tmpReturn = tmpReturn.replace(/'/g,"%27");
		tmpReturn = tmpReturn.replace(/"/g,"%22");
		tmpReturn = tmpReturn.replace(/#/g,"%23");
		
	}
	return tmpReturn;
}


function repDate(theDate,delimiter) {
	var tmpDate = theDate;
	if(tmpDate.indexOf(",") != 0) {
		var dtArr = tmpDate.split(",")
		if(dtArr.length==3) {
			var dtYear = dtArr[0].replace(" ","")
			var dtMonth = String(parseInt(dtArr[1].replace(" ",""))+1);
			if(dtMonth.length==1) {
				dtMonth = "0" + dtMonth;
			}
			var dtDay = dtArr[2].replace(" ","");
			if(dtDay.length==1) {
				dtDay = "0" + dtDay;
			}
			tmpDate = dtYear + delimiter + dtMonth + delimiter + dtDay;
			return tmpDate;
		} else {
			return "err";
		}
	}
	
}


function formHours(theHours) {
	var tmpHours = String(theHours);
	if(tmpHours.length != 4) {
		if(tmpHours.length==1) {
			tmpHours = "000" + tmpHours;
		}
		if(tmpHours.length==3) {
			tmpHours = "0" + tmpHours;
		}
	} 
	tmpHours = tmpHours.substring(0,2) + ":" + tmpHours.substring(2,4);
	return tmpHours;
}


function getFirstDateOfWeek(theDate) {
	var tmpDate = theDate;
	tmpDate = tmpDate.split(",")
	var today = new Date(parseInt(tmpDate[0]),parseInt(tmpDate[1]),parseInt(tmpDate[2]));	
	var day = today.getDate();
	var month = today.getMonth();
	var year = today.getYear();
	if (year < 2000)
	year = year + 1900;
	var offset = today.getDay();
	var week;
	
	if(offset != 0) {
		day = day - offset;
		if ( day < 1) {
			if (month == 1) day = 31 + day;//januar
			if (month == 2) {
				if (( year == 08) || ( year == 12) || ( year == 16) || ( year == 18) || ( year == 22) || ( year == 26)) {
					day = 29 + day;//februar skudår
				}
				else {
					day = 28 + day;//februar
	 			}
			}
			if (month == 3) day = 31 + day;//marts
			if (month == 4) day = 30 + day;//april
			if (month == 5) day = 31 + day;//maj
			if (month == 6) day = 30 + day;//juni
			if (month == 7) day = 31 + day;//juli
			if (month == 8) day = 31 + day;//august
			if (month == 9) day = 30 + day;//september
			if (month == 10) day = 31 + day;//oktober
			if (month == 11) day = 30 + day;//november
			if (month == 12) day = 31 + day;//december
			if (month == 1) {
				month = 12;
				year = year - 1;
			}
			else {
				month = month - 1;
				if (month < 0) {
					month = 0;
					day = 31 + day;
					year = year - 1;
				}
			}
		}
	}
	week = year + "," + month + "," + day; // i.e. 10-31-99
	week = dateAdd("d",1,repDate(week,"/"));
	return week;
}

var daysArr = "Man,Tirs,Ons,Tors,Fre,Lør,Søn";
daysArr = daysArr.split(",");


function calcTDwidth() {
	// get div width
	var divWidth = document.getElementById('weekView').offsetWidth;
	// subtract the mini calendar and the hours TD
	var availableSpace = parseInt(divWidth) - 20;
	// dividide by 7 days
	availableSpace = parseInt(availableSpace/7);
	
	return availableSpace;
}

var useClass;
var browser;

function initDay(showDate) {
	
}


function initWeek(showDate) {
	document.getElementById("popDiv").style.display = "none";
	document.getElementById("popDivShadow").style.display = "none";
	document.getElementById("popDiv").innerHTML = "";
	var startDate = getFirstDateOfWeek(showDate.replace(/ /g,""));
	//var tmpDate = repDate(showDate,"-");
	var tdWidth = calcTDwidth();
				
	tmpDate = showDate.split(",");
	theDate = new Date(parseInt(tmpDate[0]), parseInt(tmpDate[1]), parseInt(tmpDate[2]));
	//check if the looping date is today
	theDateYear = theDate.getFullYear();
	theDateMonth = theDate.getMonth();
	theDateDay = theDate.getDate();
	var weekNr = "";	
	var currentId;
	
	//create table
	
	// detect browser
	browser = navigator.appName;
	browser = browser.toLowerCase();
	if(browser=="microsoft internet explorer") {
		browser = "ie";
		useClass = "className";
	} else {
		browser = "ok";
		useClass = "class";
	}
	
  // get the reference for the body
  //var mybody = document.getElementsByTagName("body")[0];
  var container = document.getElementById("weekView");
  var todayMarker = "";
	tmpDate = "";
  // creates <table> and <tbody> elements
  mytable     = document.createElement("table");
  mytablebody = document.createElement("tbody");		


	//initiate datesArray
	var datesArr = [];
  // creating all header cells
  mycurrent_row = document.createElement("tr");
	//periods
  for(var i = 0; i < 8; i++) {
      // creates a <th> element
      mycurrent_cell = document.createElement("th");
			
			if(i>0) {     
				// days
				
      	theDate = new Date(dateAdd("d",i-1,startDate));
		
				//check if the looping date is today
      	theDateYear = theDate.getFullYear();
      	theDateMonth = theDate.getMonth();
      	theDateDay = theDate.getDate();
      	datesArr[i] = theDateYear + "-" + String(parseInt(theDateMonth)+1) + "-" + theDateDay;
      	nowDate = new Date();
      	nowDateYear = nowDate.getFullYear();
      	nowDateMonth = nowDate.getMonth();
      	if(nowDateMonth==12) {
      		nowDateYear++;
      		nowDateMonth = 1;
     	}
      	nowDateDay = nowDate.getDate();
      	var calcDate1 = theDateDay + "-" + theDateMonth + "-" + theDateYear;
      	var calcDate2 = nowDateDay + "-" + nowDateMonth + "-" + nowDateYear;

      	if(calcDate1==calcDate2) {
      		var theClass = "calToday";
      		todayMarker = i;
      	} else {
      		var theClass = "cal";
      	}
      	// end check if today
      	
      	var theTextDate = theDate.getDate() + "/" + String(parseInt(theDate.getMonth())+1);
        // creates a Text Node
        currenttext = document.createTextNode(theTextDate);
        var dayName=document.createTextNode(daysArr[i-1] + " ");
        // appends the Text Node we created into the cell <td>
        mycurrent_cell.appendChild(dayName);
        mycurrent_cell.appendChild(currenttext);
        mycurrent_cell.setAttribute("width",tdWidth);
        mycurrent_cell.setAttribute(useClass,theClass);
        
        var syntaxDate = theDate.getFullYear() + "," + theDate.getMonth() + "," + theDate.getDate();
        
				if(browser=="ie") {
		      func_addEvent(mycurrent_cell, "cdbllick", "initDay('" + syntaxDate + "');");
				} else {
					mycurrent_cell.setAttribute("oncdbllick","initDay('" + syntaxDate + "')");
				}        
      } else {
      	// hours
        // creates a Text Node
        
        currenttext = document.createTextNode(weekNr);
        // appends the Text Node we created into the cell <td>
        mycurrent_cell.appendChild(currenttext);
        mycurrent_cell.setAttribute(useClass,"calHours");
				if(browser=="ie") {
		      func_addEvent(mycurrent_cell, "click", "refreshT();");
				} else {
					mycurrent_cell.setAttribute("onclick","refreshT()");
				}            

      }
      	
      

      // appends the cell <td> into the row <tr>
      
      mycurrent_row.appendChild(mycurrent_cell);
  }
  // appends the row <tr> into <tbody>
  mytablebody.appendChild(mycurrent_row);

  // creating all rows
  var hours = 800;
  var strIDs = "";
  for(var j = 12; j < 42; j++) {
      // creates a <tr> element
      mycurrent_row = document.createElement("tr");
			
			// the cells
      for(var i = 0; i < 8; i++) {
          // creates a <td> element
          mycurrent_cell = document.createElement("td");
          
          if(i>0) {
	        	if(j%2==0) {
	        		if(i==todayMarker) {
	        			var theClass = "calTop_today";
	        		} else {
	        			var theClass = "calTop";
	        		}
	          // defines the TD id
	          currentId = "cell_" + datesArr[i] + "-" + hours;	
			  
	        	} else {
	        		if(i==todayMarker) {
	        			var theClass = "calBottom_today";
	        		} else {
	        			var theClass = "calBottom";
	        		}	        		
	          // defines the TD id
	          currentId = "cell_" + datesArr[i] + "-" + (hours-50);
			  
	        	}          	
	          // appends the cell <td> into the row <tr>
	          mycurrent_cell.setAttribute("width",tdWidth);
	          mycurrent_cell.setAttribute(useClass,theClass);
	          mycurrent_cell.setAttribute("id",currentId);
	          
	          
	        } else {
	        	
	        	if(j%2==0) {
	        		var theText = formHours(hours);
        			var theClass = "calHoursTop";
	        	} else {
	        		var theText = "";
	        		hours = hours + 100;
        			var theClass = "calHoursBottom";
	        	}
	          // creates a Text Node
	          currenttext = document.createTextNode(theText);
	          // appends the Text Node we created into the cell <td>
	          mycurrent_cell.appendChild(currenttext);
	          // appends the cell <td> into the row <tr>
	          mycurrent_cell.setAttribute(useClass,theClass);
	        }
	        // put content in
          if(currentId != "") {
			if(strIDs.indexOf(currentId+",")>0){
				
			}else{
				strIDs += currentId+",";
				checkForEvent(currentId);
			}
          }	        
          mycurrent_row.appendChild(mycurrent_cell);

          
          
      }
	  
      // appends the row <tr> into <tbody>
      mytablebody.appendChild(mycurrent_row);
  }
  
  // appends <tbody> into <table>
  mytable.appendChild(mytablebody);
  // appends <table> into <body>
  container.appendChild(mytable);
  // sets the border attribute of mytable to 2;
  mytable.setAttribute("id","weekTable");
  mytable.setAttribute("border","0");
  mytable.setAttribute("cellPadding","0");    
  mytable.setAttribute("cellSpacing","1");    
  mytable.setAttribute(useClass,"calTable");    
	

	


	//end create table
}


function func_addEvent(elm, evt, func){
  if(elm.addEventListener)elm.addEventListener(evt, function(){eval(func)}, false);
  else if(elm.attachEvent)elm.attachEvent("on"+evt, function(){eval(func)});
  else elm["on"+evt] = eval(func);
}


function Left(str, n)
{
   if (n <= 0)
         return "";
   else if (n > String(str).length)
         return str;
   else
         return String(str).substring(0,n)+"...";
}  
//var ost = 0;

function checkForEvent(theId) {
	var strTimeForEvent = "";
	strTheId = theId;
	if(strTheId!=null){
	strTimeForEvent = strTheId.substring(strTheId.indexOf("-",13)+1,strTheId.length);
	}

	getArrValues(theId);	
	if(foundItems.length>0) {
		for(i=0;i<foundItems.length;i++) {	
			var strDirection = "d";
			if (strTimeForEvent>=1700){
				strDirection = "u";
			}
			var newId = "event-"+strDirection+"_" + foundItems[i];
			var div = document.createElement("div");
			
			//var span = document.createElement("span")
			//currenthour = document.createTextNode(events[1][foundItems[i]])
			//span.appendChild(currenthour)
			//div.appendChild(span);
		
			currenttext = document.createTextNode(" "+Left(events[2][foundItems[i]], 14));
			div.appendChild(currenttext);
	
			mycurrent_cell.appendChild(div);

			div.setAttribute("id",newId);
			div.setAttribute(useClass,"event");
			div.setAttribute("title",events[1][foundItems[i]]);
			
			
			
			if(browser=="ie") {
	      		func_addEvent(div, "click", "popThis('event-"+strDirection+"_"+ foundItems[i] + "');");
				div.style.backgroundColor = events[4][foundItems[i]];
			} else {
				div.setAttribute("onclick","popThis('event-"+strDirection+"_"+ foundItems[i] + "')");
				div.setAttribute("style","background-color:"+ events[4][foundItems[i]]);
			}
			
			div = null;
		}
	} 
}

var activeAdd = "";
var activeOldBg = "";



var activePop = "";

function popThis(theId) {
	var extra = 0;
	var currId = theId.substring(theId.indexOf("_")+1,theId.length);
	var direction = theId.substring(theId.indexOf("-")+1,theId.indexOf("-")+2);
	
	
	if(document.getElementById("popDiv").style.display=="block" && activePop == theId) {
		document.getElementById("popDiv").style.display = "none";
		document.getElementById("popDivShadow").style.display = "none";
		document.getElementById("popDiv").innerHTML = "";
	} else {
		if(document.getElementById("popDiv").style.display=="block" && activePop != theId) {
			document.getElementById("popDiv").style.display = "none";
			document.getElementById("popDivShadow").style.display = "none";
			document.getElementById("popDiv").innerHTML = "";
		}
		
		//close addPop as well if it's open
		if(document.getElementById("addDiv").style.display=="block") {
			document.getElementById("addDiv").style.display = "none";
			document.getElementById("addDivShadow").style.display = "none";
			document.getElementById("addDiv").innerHTML = "";
			document.getElementById(activeAdd).style.backgroundColor = activeOldBg;
		}
		//addpop closed		
		
		activePop = theId;
    var locationWhenClickedImage = 0;    
    if (typeof window.pageYOffset == "number") locationWhenClickedImage = window.pageYOffset;
    else if (document.documentElement && document.documentElement.scrollTop)
  		locationWhenClickedImage = document.documentElement.scrollTop;
  	else if (document.body && document.body.scrollTop) 
  		locationWhenClickedImage = document.body.scrollTop; 
  	else if (window.scrollY) locationWhenClickedImage = window.scrollY;
 		
  				
		document.getElementById("popDiv").style.display = "block";
		document.getElementById("popDivShadow").style.display = "block";
		var div = document.getElementById(theId);
		var popDiv = document.getElementById("popDiv");
		
		
		if(div.offsetTop-document.getElementById("popDiv").offsetHeight < 0)  {
			var posTop = 0;
		} else {
			var posTop = div.offsetTop-document.getElementById("popDiv").offsetHeight;
		}
		if(div.offsetLeft-document.getElementById("popDiv").offsetWidth < 0)  {
			var posLeft = 0;
		} else {
			var posLeft = div.offsetLeft-document.getElementById("popDiv").offsetWidth-5;
		}		
		
		if(div.offsetTop<document.getElementById("popDiv").offsetHeight) {
			posTop = locationWhenClickedImage;
		} else {
			posTop = div.offsetTop-document.getElementById("popDiv").offsetHeight;
		}
		if(posTop<locationWhenClickedImage) {
			posTop = posTop + (locationWhenClickedImage-posTop);
		}
		
		if(direction=="d"){
			posTop = document.getElementById(theId).offsetTop+document.getElementById(theId).offsetHeight-4;
			posLeft = document.getElementById(theId).offsetLeft+document.getElementById(theId).offsetWidth-20;
		}else{
			posTop = document.getElementById(theId).offsetTop-document.getElementById(theId).offsetHeight-170;
			posLeft = document.getElementById(theId).offsetLeft+document.getElementById(theId).offsetWidth-20;
		}
		
		document.getElementById("popDiv").style.top = posTop + "px";
		document.getElementById("popDiv").style.left = posLeft + "px";
		document.getElementById("popDivShadow").style.top = (posTop+5) + "px";
		document.getElementById("popDivShadow").style.left = (posLeft+5) + "px";		
		
		
	
		var tmpArr = events[3][currId];
		var tmpArrHeader = events[2][currId];
		var tmpArrTime = events[1][currId];
		if(tmpArr!="") {
			if(tmpArr.indexOf("||BR||") > 0) {
				tmpArr = tmpArr.split("||BR||");
				popDivContent = document.createElement("DIV");
				popspan = document.createElement("SPAN");
				popspan.innerHTML = "<img src='/includes/pages/calendar/close.gif'>";
				popspan.setAttribute(useClass,"spanClose");
				if(browser=="ie"||browser=="ok") {
					func_addEvent(popspan, "click", "popThis('event-"+direction+"_"+ currId + "');");
				} else {
					popspan.setAttribute("onclick","popThis('"+currId+"')");
				}
				strPopDivContent = "<span>"+tmpArrTime+" - "+tmpArrHeader+"</span>";
				//tmpArrHeader = tmpArrHeader.split("||BR||");
				//popDivHeader = document.createTextNode(tmpArrHeader);
				//br = document.createElement("BR");
				//popDiv.appendChild(popDivHeader);
				//popDiv.appendChild(br);
				for(i=0;i<tmpArr.length;i++) {
					strPopDivContent = strPopDivContent + "<br>"+tmpArr[i];
					//popDivText = document.createTextNode(tmpArr[i]);
					
					//popDiv.innerHTML = popDivHeader+br+popDivText+br;
					//popDiv.appendChild(popDivText);
					//popDiv.appendChild(br);
				}
				popDivContent.innerHTML = strPopDivContent;
				popDiv.appendChild(popspan);
				popDiv.appendChild(popDivContent);
			} else {
				popDivContent = document.createElement("DIV");
				//popDivHeader = document.createElement("SPAN");
				//popDivHeader.innerHTML = tmpArrHeader;
				//br = document.createElement("BR");
				//popDivText = document.createTextNode(tmpArr);
				popspan = document.createElement("SPAN");
				popspan.innerHTML = "<img src='/includes/pages/calendar/close.gif'>";
				popspan.setAttribute(useClass,"spanClose");
				if(browser=="ie"||browser=="ok") {
					func_addEvent(popspan, "click", "popThis('event-"+direction+"_"+ currId + "');");
				} else {
					popspan.setAttribute("onclick","popThis('"+currId+"')");
				}
				popDivContent.innerHTML = "<span>"+tmpArrTime+" - "+tmpArrHeader+"</span><br>"+tmpArr+"";
				popDiv.appendChild(popspan);
				popDiv.appendChild(popDivContent);
				//popDiv.appendChild(popspan);
				//popDiv.appendChild(popDivHeader);
				//popDiv.appendChild(br);
				//popDiv.appendChild(popDivText);			
			}
		}
	}
}




var foundItems = [];

function getArrValues(theId) {
	foundItems = [];
	var index = events[0].indexOf(theId)
	while (index != -1)
	{  
		foundItems.push(index);  
		index = events[0].indexOf(theId, ++index);
	}	
}




function jStrip(thestring) {
	var tmpString = thestring;
	if(tmpString!="") {
		tmpString = tmpString.replace(/%22/g,"\"");
		tmpString = tmpString.replace(/%26/g,"\&");
		tmpString = tmpString.replace(/%27/g,"\'");
		tmpString = tmpString.replace(/%3C/g,"");
		tmpString = tmpString.replace(/%3E/g,"");
		tmpString = tmpString.replace(/</g,"");
		tmpString = tmpString.replace(/>/g,"");

	}	
	return tmpString;
}





