//JavaCalander

function Calendar()
{
	this.sDate = new Date();
	this.eDate = new Date("1/1/2020");
	this.options = new NamedList();
	this.style = new NamedList();
	this.days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
	this.months = ['January', 'February', 'March', 'April',
                     'May', 'June', 'July', 'August', 'September',
                     'October', 'November', 'December'];
	this.daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	
	this.reset = function()
	{
		this.sDate = new Date(); 
		this.onError = function() { };
		this.onComplete = function() { };
	}
	
	this.StartDate = function(tdate)
	{
		this.sDate = tdate;
	}
	
	this.Option = function(name, value)
	{
		if(!value)
		{	//return value of option
			return this.options.Value(name);
		} else {
			this.options.Add(name, value);
			return value;
		}
	}

// Style ({'zindex:50', 'bgcolor:#0000FF', 'opacity:70'});
	this.Classname = function(div, name)
	{
		try
		{
			div.setAttribute("class", name); //For Most Browsers

		} catch (err)
		{
			div.setAttribute("className", name);		
		}
	}
	
	this.ShowCalender = function(div, clickx, clicky, tmonth, tyear)
	{
		if(this.Option('greyout') == true){
			this.GreyOut(true, {'zindex':'99', 'bgcolor':'#555555', 'opacity':'95'});
			div = document.getElementById('darkenScreenObject');
		}
		 
		this.month = tmonth || this.sDate.getMonth();
	  this.year  = tyear || this.sDate.getFullYear();
		var self = this;
		var calDiv = document.createElement('div');
		calDiv.id = "Calendar";
		this.Classname(calDiv, "Calendar");
		
		var headDiv = document.createElement('div');
		headDiv.id = "CalHeader";
		this.Classname(headDiv, "Header");
		this.MakeHeader(headDiv);
		calDiv.appendChild(headDiv);

		var bodyDiv = document.createElement('div');
		bodyDiv.id = "CalBody";
		this.Classname(bodyDiv, "Body");		
		this.MakeBody(bodyDiv);
		calDiv.appendChild(bodyDiv);		
		
		var footDiv = document.createElement('div');
		footDiv.id = "CalFoot";
		this.Classname(footDiv, "Footer");				
		var txt = document.createTextNode("CLOSE");
		addEvent(footDiv, "click", function() {self.Close();});
		footDiv.appendChild(txt);
		calDiv.appendChild(footDiv);
		
		calDiv.zindex = "51";
		div.appendChild(calDiv);
		
		if(clickx) this.MoveDiv(calDiv, clickx, clicky);	
	}

	this.Close = function()
	{
		this.GreyOut(false);
	}

/* Private Functions -----------------------------------------------------------------------------*/
//MoveDiv(x,y) - moves the calenderDiv to the correct.
	this.MoveDiv = function(div, x, y)
	{
		if (parseInt(navigator.appVersion)>3) {
			if (navigator.appName=="Netscape") {
				winW = window.innerWidth;
				winH = window.innerHeight;
			}
			if (navigator.appName.indexOf("Microsoft")!=-1) {
				winW = document.body.offsetWidth;
				winH = document.body.offsetHeight;
			}
		}
		
		div.style.position = "fixed";
		if(x+div.width > winW) div.style.left = (winW - (div.width+10))+"px";
		else div.style.left = x+'px';
		if(y+div.height > winH) div.style.top = (winH - (div.height+10))+"px";
		else div.style.top = y+'px';
	}

//MakeHeader(div) - used return the HTML for the header.
	this.MakeHeader = function(div)
	{
			var self = this;
	    var tbl = document.createElement("table");
      tbl.appendChild(document.createElement("tbody"));

      var row = document.createElement("tr");
			row.appendChild(document.createElement("td"));
      var select = document.createElement("select");
			select.name = "CalMonth"
      for(x = 0; x <  this.months.length; x++)
      {
				var option = document.createElement("option");
        try
        {
            select.add(option); //IE
        }
        catch (ex)
        {
            select.add(option, null); //Firefox et autres
        }
        if(x == this.month) option.selected = 'true';
        option.value = x;
				option.text = this.months[x];
      }
			addEvent(select, "change", function(){
							self.month = this.value;
							self.MakeBody();						
						});
      
      row.lastChild.appendChild(select); 
      row.appendChild(document.createElement("td"));
      
      var select = document.createElement("select");
			select.name = "CalYear"
      for(x = this.year - 2; x < this.eDate.getFullYear(); x++)
      {
				var option = document.createElement("option");
        try
        {
            select.add(option); //IE
        }
        catch (ex)
        {
            select.add(option, null); //Firefox
        }
        if(x === this.year)
        {
        	option.selected = 'true';
        }
        option.value = x;
				option.text = x;
      }
      
			addEvent(select, "change", function(){
					self.year = this.value;
					self.MakeBody();						
				});
      
      row.lastChild.appendChild(select);
			
      tbl.lastChild.appendChild(row);

      // appends <table> into <body>
      div.appendChild(tbl);
	}
	
	this.MakeBody = function(div)
	{
		if(!div)var div = document.getElementById('CalBody');

		if(div.hasChildNodes){
			div.innerHTML = "";
		}

	  var firstDay = new Date(this.year, this.month, 1);
		//Find Month length
		var monthLength = this.daysInMonth[this.month];
		if (this.month == 1) { // February only!
		  if ((this.year % 4 == 0 && this.year % 100 != 0) || this.year % 400 == 0){
		    monthLength = 29;
		  }
		}
		var startingDay = firstDay.getDay();

		var self = this;
    var tbl = document.createElement("table");
    
    var row = document.createElement("tr");
    for(x = 0; x < this.days.length; x++)
    {
    	var cell = document.createElement("td");
			var cellText = document.createTextNode(this.days[x]);
			cell.appendChild(cellText);
			this.Classname(cell,'TblHeader');
			row.appendChild(cell);
    }
    tbl.appendChild(row);
    
    var day = 1;
		// this loop is for is weeks (rows)
		for (var i = 0; i < 9; i++) {
		  // this loop is for weekdays (cells)
		  row = document.createElement("tr");
		  for (var j = 0; j <= 6; j++) { 
		    var cell = document.createElement('td');
				if (day <= monthLength && (i > 0 || j >= startingDay)) {
		      cellText = document.createTextNode(day);
		      addEvent(cell, "click", function(){self.Complete(self.year, parseInt(self.month) + 1, this.innerHTML)});
		      cell.appendChild(cellText);
		      if(i % 2 == 0) this.Classname(cell, "row-b");
		      else this.Classname(cell,"row-a");
		      day++;
		    }
		    cell.style.border = "light solid"
				row.appendChild(cell);
		  }
		  // stop making rows if we've run out of days
		  tbl.appendChild(row);
		  if (day > monthLength) {
		    break;
		  }
		}
		div.appendChild(tbl);			
	}

//Copy Style
	this.copyStyle = function(base, targ)
	{
	    var baseStyle = base.style;
	    var targStyle = targ.style;
	    
	    for(var prop in baseStyle)
	    {
	          var str = "targStyle." + prop + " = baseStyle." + prop + ";";
	
	          try
	          {
	                eval(str);
	          }
	          catch(e)
	          {
	                // Do nothing
	          }
	    }
	}
	
//Greyout(vis, options) - used to deactivate the background.  Only used if greyout option is set
	this.GreyOut = function (vis,  options ) 
	{  
		// Pass true to gray out screen, false to ungray  
		// options are optional.  This is a JSON object with the following (optional) properties  
		// opacity:0-100         
		// Lower number = less grayout higher = more of a blackout   
		// zindex: #             
		// HTML elements with a higher zindex appear on top of the gray out  
		// bgcolor: (#xxxxxx)   
		// Standard RGB Hex color code  
		// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});  
		// Because options is JSON opacity/zindex/bgcolor are all optional and can appear  
		// in any order.  Pass only the properties you need to set.  
		var options = options || {};
		var zindex = options.zindex || 50;  
		var opacity = options.opacity || 80;  
		var opaque = (opacity / 100);  
		var bgcolor = options.bgcolor || '#000000';  
		var dark=document.getElementById('darkenScreenObject');  
		if (!dark) {    
			// The dark layer doesn't exist, it's never been created.  So we'll    
			// create it here and apply some basic styles.    
			// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917    
			var tbody = document.getElementsByTagName("body")[0];    
			var tnode = document.createElement('div');           
			// Create the layer.        
			tnode.style.position='fixed';                 
			// Position absolutely        
			tnode.style.top='0px';                           
			// In the top        
			tnode.style.left='0px';                          
			// Left corner of the page        
			tnode.style.overflow='hidden';                   
			// Try to avoid making scroll bars                    
			tnode.style.display='none';                      
			// Start out Hidden        
			tnode.id='darkenScreenObject';                   
			// Name it so we can find it later    
			tbody.appendChild(tnode);                            
			// Add it to the web page    
			dark=document.getElementById('darkenScreenObject');  
			// Get the object.  
		}  
		if (vis) {    
			// Calculate the page width and height     
			if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {        
				var pageWidth = document.body.scrollWidth+'px';        
				var pageHeight = '500%';    
			} else if( document.body.offsetWidth ) {      
				var pageWidth = document.body.offsetWidth+'px';      
				var pageHeight = document.body.offsetHeight+'px';    
			} else {       
				var pageWidth='100%';       
				var pageHeight='100%';    
			}       
			//set the shader to cover the entire page and make it visible.    
			dark.style.opacity=opaque;                          
			dark.style.MozOpacity=opaque;                       
			dark.style.filter='alpha(opacity='+opacity+')';     
			dark.style.zIndex=zindex;            
			dark.style.backgroundColor=bgcolor;     
			dark.style.width= pageWidth;    
			dark.style.height= pageHeight;    
			dark.style.display='block';
			document.body.scrolling = "No";                         
		} else {     
			document.body.removeChild(dark);
			document.body.scrolling = "Yes";
		}
	};


}


function NamedList()
{
	this.Names = new Array();
	this.Values = new Array();
	this.lenght = -1;
	
	this.reset = function(){
		this.Names = new Array();
		this.Values = new Array();
		this.lenght = -1;
	}
	
	this.Value = function(name)
	{
		var index = -1;
		for(x in this.Names){
			if(this.Names[x] == name) index = x;
		}
		if(index > -1){
			return this.Values[index];
		} else {
			return index;
		}		
	}
	
	this.Add = function(name, value)
	{
		this.lenght += 1;
		this.Names[this.lenght] = name;
		this.Values[this.lenght] = value;

	}
	
	this.RemoveNames = function(name)
	{
		for(x in this.Names)
		{
			if(this.Names[x] == name) {
				this.Names.splice(x,1);
				this.Values.splice(x, 1);
			}
		}
	}
	
	this.RemoveValues = function(value)
	{
		for(x in this.Values)
		{
			if(this.Values[x] == name) {
				this.Names.splice(x,1);
				this.Values.splice(x, 1);
			}
		}	
	}
	
	this.splice = function(start, end)
	{
		if(this.Names.length > start)
		{
			this.Names.splice(start,end);
			this.Values.splice(start, end);
		}
	}
	
	this.join = function(joiner, seperator)
	{
		var output = "";
		if(!joiner) joiner = "=";
		if(!seperator) seperator = ",";
		for(x in this.Names)
		{
			if(output == ""){
				output = output+this.Names[x]+joiner+this.Values[x];
			} else {
				output = output+seperator+this.Names[x]+joiner+this.Values[x];
			}
		}
		return output;
	}
	
	this.findNames = function(value)
	{
		var tNames = new Array();
		for(x in this.Values)
		{
			if(this.Values[x] == value) {
				tNames[tNames.length+1] = this.Names[x];
			}
		}
		return tNames;
	}
	
	this.FindValues = function(name)
	{
		var tValues = new Array();
		for(x in this.Names)
		{
			if(this.Names[x] == name) {
				tValues[tValues.length+1] = this.Values[x];
			}
		}
		return tValues;	
	}
	
	this.sortNames = function()
	{
		var tnames = this.Names;
		var tvalues = new Array();
		
		tnames.sort()
		for(x in tnames)
		{
			for(y in this.Names)
			{
				if(this.Names[y] == tnames[x]){
					tvalues[tvalues.length+1] = this.Values[y];
					this.splice(y, 1);
				}
			}
		}
		this.Names = tnames;
		this.Values = tvalues;
	}
	
	this.sortValues = function()
	{
		var tnames = new Array();
		var tvalues = this.Values;
		
		tvalues.sort()
		for(x in tvalues)
		{
			for(y in this.Names)
			{
				if(this.Values[y] == tvalues[x]){
					tnames[tnames.length+1] = this.Names[y];
					this.splice(y, 1);
				}
			}
		}
		this.Names = tnames;
		this.Values = tvalues;
	}
	
	this.reset();
}
