var toolTipActive = false;

var eventsCollection = new Array();

function doCalendarEvents() {
  if(!document.getElementById) return false;
  if(!document.getElementsByTagName) return false;
  
  var calendar = document.getElementById("month_view");

  if(calendar) {
    calendarHighlight(calendar);
  }
}

addLoadEvent(doCalendarEvents);

function calendarHighlight(calendar_id) {
  
  if(calendar_id) {
    
    var days = calendar_id.getElementsByTagName("td");
    
    var month; var year;
    
    for(var i = 0; i < days.length; i++) {
      if(days[i].className.match("day") || 
         days[i].className.match("event_day") ||
         days[i].className.match("blank") ||
         days[i].className.match("side_column") || 
         days[i].className.match("frame")) {
           
        if(days[i].className.match("event_day")) {
          timestamp = getEventDate(days[i]);
          
          if(typeof(year) == "undefined" && typeof(month) == "undefined") {
            year = timestamp.substr(0,4);
            month = timestamp.substr(5,2);
          }
        }
        
        
        days[i].onmouseover = function(e) {
          
          removeTT(e);
          
          if(!this.className.match("blank") &&
             !this.className.match("frame") &&
             !this.className.match("side_column")) {
            this.style.backgroundColor = "#FFFFCC";
          }
          
          

          // if there is one or more event on a
          // day and a toolTip isn't already made
          if(this.className.match("event_day")) {
            
            // only display tool tip if none exists
            if(!toolTipActive) {
              
              // set tool tip to active state
              toolTipActive = true;
              
              // Get Coords to diplay tool tip
              var xCoord = findPos(this)[0] + this.offsetWidth;
              var yCoord = findPos(this)[1];
              
              var timestamp = getEventDate(this);
              
              displayToolTip(xCoord,yCoord,timestamp);
            }
          }
        }
        
        days[i].onmouseout = function() {
          if(this.getAttribute("id") == "today") {
            this.style.backgroundColor = "#FFEDDF"
          } else if(this.className.match("blank")) {
            this.style.backgroundColor = "#EFEFEF";
          } else if (this.className.match("event_day")) {
            this.style.backgroundColor = "#DFEBFF";
          } else if (this.className.match("frame") ||
                     this.className.match("side_column")) {
            this.style.backgroundColor = "#cfcfcf";
          } else {
            this.style.backgroundColor = "#FFFFFF";
          }
        }
      }
    }
    loadEvents(month,year);
    
  }
}

function getEventDate(element) {
  // the time stamp of the current day
  var timestamp = element.getElementsByTagName("a")[0].getAttribute("href");
  
  timestamp = timestamp.substr(timestamp.length-10,timestamp.length);
  
  return timestamp;
}

function displayToolTip(xCoord,yCoord,timestamp) {
  
  var toolTipWidth = 200;
  var toolTipHeight = 100;
  
  var toolTip = document.createElement("div");
  toolTip.setAttribute("id","toolTip");
  toolTip.onmouseout = removeTT;
  
  // tool tip frame styles
  toolTip.style.position = "absolute";
  toolTip.style.left = xCoord + "px";
  toolTip.style.top = yCoord - 1 + "px";
  toolTip.style.width = toolTipWidth + "px";
  toolTip.style.minHeight = toolTipHeight + "px";
  toolTip.style.background = "#FFFFCC";
  toolTip.style.border = "1px solid #EFEFEF";
  toolTip.style.padding = "5px";
  
  document.body.appendChild(toolTip);
    
  displayCachedEvents(timestamp);
}

function removeToolTip() {
      
  var currentToolTip = document.getElementById("toolTip");

  if(currentToolTip) {
    document.body.removeChild(currentToolTip);
    
    // once tool tip is removed, reset
    // tool tip status to false
    toolTipActive = false;
  }
}

function removeTT(e) {
  
  if(!e) var e = window.event;
  
  // grab event target element
  var tg = (window.event) ? e.srcElement : e.target;
  
  // fix safari bug, grabs the right target for safari
  if(tg.nodeType == 3) { tg = tg.parentNode; }
  
  var eventType = e.type;
  
  if(tg.nodeName == "A" || tg.nodeName == "P") {
    // do nothing
  } else if(tg.nodeName == "TD" && eventType == "mouseout") {
    
    // do nothing
    
  } else if(tg.nodeName == "TD" && eventType == "mouseover") {
    
    removeToolTip();
    
  } else if (tg.nodeName != "DIV") {
      
    removeToolTip();
    
  } else if(tg.nodeName == "DIV") {
    
    if(mouseInside(tg,e)) {
      removeToolTip();
    }
    
  }
}

function mouseInside(tg,e) {
  currentX = findPos(tg)[0];
  currentY = findPos(tg)[1];
  
  // the minus 12 is for firefox - must be different for IE
  currentWidth = tg.offsetWidth - 12;
  currentHeight = tg.offsetHeight  - 12;
  
  if((e.clientX < currentX) || (e.clientX > (currentX + currentWidth)) ||
     (e.clientY < currentY) || (e.clientY > (currentY + currentHeight))) {

    return true;
               
  } else {
    
    return false;
  }
}

// returns 2 element array with x and y coords of element
function findPos(obj) {
  
	var curleft = curtop = 0;
	
	if (obj.offsetParent) {
  	
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		
		while (obj = obj.offsetParent) {
  		
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
			
		}
	}
	
	return [curleft,curtop];
	
}

/* ---------------- ToolTip Ajax Functions Below -------- */

var xmlHttpToolTip;

function handleToolTip(){
    if (xmlHttpToolTip.readyState == 4){
        if (xmlHttpToolTip.status == 200){
            parseToolTip();
        }
    } else if (xmlHttpToolTip.readyState == 1) {
      showLoadAnimation();
    } else if (xmlHttpToolTip.readyState == 2 ) {
      clearLoadAnimation();
    }
}

function parseToolTip(){
  
  var allResults = xmlHttpToolTip.responseXML.getElementsByTagName("event");
  
  var result = null;
  
  if(allResults.length > 0) {
  
    for(var i = 0; i < allResults.length; i++) {
        
      result = allResults[i];
      eventUrl = result.getElementsByTagName("url")[0];
      title = result.getElementsByTagName("title")[0];
      info = result.getElementsByTagName("info")[0];
      timestamp = result.getElementsByTagName("start_date")[0];
      
      eventUrl = (eventUrl.hasChildNodes()) ? eventUrl.firstChild.nodeValue : "";
      title = (title.hasChildNodes()) ? title.firstChild.nodeValue : "";
      if( lang=='fr' ) {
	      info = (info.hasChildNodes()) ? info.firstChild.nodeValue + "..." : "Suivez le lien pour en savoir plus sur cette activit\u00e9.";
	  } else {
      	info = (info.hasChildNodes()) ? info.firstChild.nodeValue + "..." : "Follow the link to read more about this event.";
      }
      timestamp = (timestamp.hasChildNodes()) ? timestamp.firstChild.nodeValue.substr(0,10) : "";
      
      eventsCollection.push([timestamp,eventUrl,title,info]);
    }
  }
}

function checkEventCache(timestamp) {
  
  eventsLoaded = false;
  
  for(var i = 0; i < eventsCollection.length; i++) {
    if(eventsCollection[i][0] == timestamp) {
      eventsLoaded = true;
    }
  }
  
  return eventsLoaded;
  
}

function displayCachedEvents(timestamp) {
  
  var toolTip = document.getElementById("toolTip");
  
  var limit = 3;
  var eventCount = 0;
  
  if(eventsCollection.length) {
  
    for(var i = 0; i < eventsCollection.length; i++) {
      
      if((eventsCollection[i][0] == timestamp) && (eventCount < limit)) {
      
        eventLink = document.createElement("a");
        eventLink.setAttribute("href",eventsCollection[i][1]);
        eventLinkText = document.createTextNode(eventsCollection[i][2]);
        eventLink.appendChild(eventLinkText);
        toolTip.appendChild(eventLink);
        
        info = document.createElement("p");
        info.appendChild(document.createTextNode(eventsCollection[i][3]));
        toolTip.appendChild(info);
        
        eventCount++;        
      }
    }
    
    if(eventCount >= limit) {
      
      var url = eventsCollection[0][1].substr(0,eventsCollection[0][1].lastIndexOf("&"));
      url = url + "&date=" + timestamp;
      
      var allEventsLink = document.createElement("a");
      allEventsLink.setAttribute("href",url);
      //allEventsLinkText = document.createTextNode("View all events...");
      
      if( lang=='fr' ) {
      	allEventsLinkText = document.createTextNode("Pour voir toutes les activit\u00e9s...");
      } else {
      	allEventsLinkText = document.createTextNode("View all events...");
      }
      allEventsLink.appendChild(allEventsLinkText);
      
      toolTip.appendChild(allEventsLink);
    }
    
  } else {
    
    message = document.createElement("p");
    if( lang=='fr' ) {
    	message.appendChild(document.createTextNode("Veuillez attendre pendant le chargement des \u00e9v\u00e9nements..."));
    } else {
    	message.appendChild(document.createTextNode("Please Wait while events are loaded...")); 
    }
    //message.appendChild(document.createTextNode("Veuillez attendre pendant le chargement des événements..."));
    
    toolTip.appendChild(message);
    
  }
}

function loadEvents(month, year) {
	if( month==undefined || year==undefined ) return;
  
  var accountID = document.getElementById("account_id").value;
  
  //var url = XMLRequestParamsURL('GetEvents','account_id',accountID,'month',month,'year',year);
  var url = "/__webservices/?method=getEvents&arg1="+accountID+"&arg2="+year+"&arg3="+month+"&arg4=0";
  
  //document.body.appendChild(document.createTextNode(url));
  
  xmlHttpToolTip = createXMLHttpRequest();
  xmlHttpToolTip.onreadystatechange = handleToolTip;
  xmlHttpToolTip.open("GET", url, true);
  xmlHttpToolTip.send(null);
}
