///-------------------------------------------------------------------------
//  @project    core
//  @version    1.4.6
//  @author     Niel Astle
//  @company    Liquid Edge Solutions
//	@copyright  Copyright 2007 Liquid Edge Solutions. All rights reserved.
//  @desc       Commonly used javascript functions
///-------------------------------------------------------------------------
// General
///--------------------------------------------------------------------------
function getmonth(header, month)
{
	new Ajax.Request('../events/ajax_calendar.php',
	{
		onSuccess : function(response) 
					{},

		onFailure : function(response) 
					{
						alert("error loading " + url + "...");
					},
		
		onComplete : function(response) 
					{
						$("ajax_calendar").innerHTML = response.responseText;
						$("ajax_head").innerHTML = header;
					},
		
		parameters : "month="+month
	});
}

function $(the_element_id) { // get an element object
  	if (typeof the_element_id == 'object') return the_element_id;
  	else if (typeof the_element_id == 'string') return document.getElementById(the_element_id);
  	else return false;
}

///--------------------------------------------------------------------------
function $f(the_form, the_element) { // get a form element object
	return document.forms[the_form].elements[the_element];
}

///--------------------------------------------------------------------------
function $$(the_element_id, the_value) { // get the value of a given element and/or set a new one
  	var the_element = $(the_element_id);
  	var return_value = the_value;
  	
  	if (the_value != null) { // set new value
	  	if (the_element.type != null) the_element.value = the_value; // input tag
	  	else if (the_element.innerHTML != null) the_element.innerHTML = the_value; // default html element
	}
	else { // get value
	  	if (the_element.type != null) { // input tag
	  		switch (the_element.type) {
	  		  	case 'select-one' 	: return_value = the_element.options[the_element.selectedIndex].value; break;
	  		  	default 			: return_value = the_element.value; break;
	  		}
	  	}
	  	else if (the_element.innerHTML != null) return_value = the_element.innerHTML; // default html element
	}
  	
  	return return_value;
}

///--------------------------------------------------------------------------
function $$f(the_form, the_element, the_value) { // get the value of a given form element and/or set a new one
  	var the_element = $f(the_form, the_element);
  	var return_value = the_value;
  	
  	if (the_value != null) { // set new value
	  	the_element.value = the_value;
	}
	else { // get value
  		switch (the_element.type) {
  		  	case 'select-one' 	: return_value = the_element.options[the_element.selectedIndex].value; break;
  		  	default 			: return_value = the_element.value; break;
  		}
	}
  	
  	return return_value;
}

///--------------------------------------------------------------------------
// Extend: Date
///--------------------------------------------------------------------------
Date.month_names = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
Date.month_days = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
Date.day_names = new Array('Sunday', 'Monday', 'Thuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

///--------------------------------------------------------------------------
Date.prototype.get_date = function(the_separator) { // returns date in format YYYY-MM-DD
	if (the_separator == null) the_separator = '-';
  	return cr.string.leadzero(this.getFullYear() + the_separator + cr.string.leadzero(this.getMonth()+1) + the_separator + this.getDate());
}

///--------------------------------------------------------------------------
Date.prototype.get_datefull = function() {
    return this.getDate() + ' ' + this.get_monthname() + ' ' + the_date.getFullYear();
}

///--------------------------------------------------------------------------
Date.prototype.get_time = function() { // returns time in format HH:MM
  	return cr.string.leadzero(this.getHours()) + ':' + cr.string.leadzero(this.getMinutes());
}

///--------------------------------------------------------------------------
Date.prototype.get_style = function(the_selected_date) { // returns the type of day: weekend or today
	if (typeof the_selected_date != 'undefined')
		if (this.getFullYear() == the_selected_date.getFullYear() && this.getMonth() == the_selected_date.getMonth() && this.getDate() == the_selected_date.getDate()) return '-selected';

  	var date_today = new Date();
  	var date_today_year = date_today.getFullYear();
  	var date_today_month = date_today.getMonth();
  	var date_today_date = date_today.getDate();
  
    var the_year = this.getFullYear();
    var the_month = this.getMonth();
    var the_weekday = this.getDate();
    var the_day = this.getDay();
    
    var style = '';
    if (the_day == 0 || the_day == 6) style = '-weekend';
    if (date_today_year == the_year && date_today_month == the_month && date_today_date == the_weekday) style = '-today';
    
    return style;
}

///--------------------------------------------------------------------------
Date.prototype.get_startday = function() { // get month start day of week
    var the_date = new Date(this.getFullYear(), this.getMonth(), 1);
    return the_date.getDay();
}

///--------------------------------------------------------------------------
Date.prototype.get_endday = function() { // get month end day
    return Date.month_days[this.getMonth()];
}

///--------------------------------------------------------------------------
Date.prototype.get_monthname = function() { // returns the month name: january, february ...
  	return Date.month_names[this.getMonth()];
}

///--------------------------------------------------------------------------
Date.prototype.get_dayname = function() { // returns the day name: sunday, monday ...
  	return Date.day_names[this.getDay()];
}

///--------------------------------------------------------------------------
Date.parse_date = function(the_datestr, the_seperator) { // creates a date object from a string in DD-MM-YYYY format
	if (typeof the_separator == 'undefined') the_separator = '-';
    var date_arr = the_datestr.split(the_separator, 3);
    var the_date = new Date(date_arr[0], date_arr[1]-1, date_arr[2]);
    return the_date;
}

///--------------------------------------------------------------------------
// Core framework
///--------------------------------------------------------------------------
var cr = {
	version: '1.0.0', // core version
	uid: 0, // next unique id
	
	///--------------------------------------------------------------------------
	cache: { // temporary storage
	},
	
	///--------------------------------------------------------------------------
	array: { // manipulates arrays
	  	///--------------------------------------------------------------------------
	  	from_string: function(the_string) { // convert string into array
	  	  	var new_arr = new Array();
	  	  	new_arr[0] = the_string;
	  	  	return new_arr;
	  	}
	  	
	  	///--------------------------------------------------------------------------
	},
	
	///--------------------------------------------------------------------------
	element: { // manipulates elements
	  	///--------------------------------------------------------------------------
	  	over: function(the_element) { // adds '-hover' to element's class name
		    var the_element = $(the_element);
		    var over_signature = the_element.className.substr(the_element.className.length-6, 6);
		    if (over_signature != '-hover') the_element.className = the_element.className + '-hover';
	  	},

		///--------------------------------------------------------------------------
	  	out: function(the_element) { // removes '-hover' from element's class name
		    var the_element = $(the_element);
		    var over_signature = the_element.className.substr(the_element.className.length-6, 6);
		    if (over_signature == '-hover') the_element.className = the_element.className.slice(0, the_element.className.length-6);
		},
	
		///--------------------------------------------------------------------------	  	
		hide: function (the_element) { // hide element
		    var the_element = $(the_element);
			if (the_element.style.display != 'none') the_element.style.display = 'none';
		},
		
		///--------------------------------------------------------------------------	  	
		show: function (the_element, the_style) { // show element
			if (the_style == null) the_style = 'block';
		    var the_element = $(the_element);
			if (the_element.style.display != the_style) the_element.style.display = the_style;
		},
		
		///--------------------------------------------------------------------------	  	
		toggle: function (the_element, the_style) { // toggle element visibility
			if (the_style == null) the_style = 'block';
		    var the_element = $(the_element);
			if (the_element.style.display == the_style || the_element.style.display == null) cr.element.hide(the_element);
			else cr.element.show(the_element, the_style);
		},
		
		///--------------------------------------------------------------------------	  	
		toggle_chk: function (the_element, the_checkbox, the_style) { // toggle element visibility by checkbox
			if (the_style == null) the_style = 'block';
		    var the_element = $(the_element);
		    var the_checkbox = $(the_checkbox);
			if (the_element.style.display == the_style || the_element.style.display == null) {
			  	cr.element.hide(the_element);
			  	the_checkbox.checked = false;
			}
			else {
			  	cr.element.show(the_element, the_style);
			  	the_checkbox.checked = true;
			}
		},
		
		///--------------------------------------------------------------------------	  	
		disable: function(the_element) { // disable element
			var the_element = $(the_element);
			the_element.disabled = true;
		},

		///--------------------------------------------------------------------------	  	
		enable: function(the_element) { // enable element
			var the_element = $(the_element);
			the_element.disabled = false;
		},

		///--------------------------------------------------------------------------	  	
		extend: function(obj1, obj2) { // adds all properties from obj1 to obj2 overwriting if found
		  for (property in obj1) obj2[property] = obj1[property];
		  return obj2;
		}
		
		///--------------------------------------------------------------------------	  	
	},
	
	///--------------------------------------------------------------------------
	nav : { // manipulate browser
		popup_count: 0, // keep track of how many popups created
	
		///--------------------------------------------------------------------------
		open: function(the_url, the_message) { // gives the user a confirmation box before directing to a url
		  	var proceed = (the_message == null ? true : window.confirm(the_message));
			if (proceed) document.location = the_url;
		},
		
		///--------------------------------------------------------------------------
		submit: function(the_form, the_url, the_message, the_onsubmit) { // Gives the user a confirmation box before submitting the form to an url
		  	var proceed = (the_message == null ? true : window.confirm(the_message));
		  	if (proceed) {
		  	  	var the_form = document.forms[the_form];
		  	  	if (the_url != null) the_form.action = the_url;
		  	  	if (the_onsubmit != null) the_form.onsubmit = the_onsubmit;
		  	  	var proceed = (the_form.onsubmit == null ? true : the_form.onsubmit());
		  	  	if (proceed) the_form.submit();
			}
		},
		
		///--------------------------------------------------------------------------
		popup: function(the_url, the_width, the_height, the_position, the_scrollbars) { // opens an url in a new popup
		  	// init defaults
		  	var the_width = (the_width == null ? 'max' : the_width);
		  	var the_height = (the_height == null ? 'max' : the_height);
		  	var the_position = (the_position == null ? 'center' : the_position);
		  	var the_scrollbars = (the_scrollbars == null ? 'no' : the_scrollbars);
		  	
		    // keep track of how many popups where opened
		    cr.nav.popup_count++;
		    
		    // convert 'max' meta to maximum value
		    if (the_width == 'max') the_width = window.screen.width-10;
		    if (the_height == 'max') the_height = window.screen.height-120;
		
		    // create window
		    var the_popup = window.open(the_url ,'cr_popup_' + cr.nav.popup_count,'toolbar=no,status=yes,resizable=no,directories=no,location=no,menubar=no,scrollbars='+the_scrollbars+',width='+the_width+',height='+the_height);
		
		    // movie window to specified position
		    var start_x = 0;
		    var start_y = 0;
		    switch (the_position) {
		      	case 'right'  : start_x = Math.floor(window.screen.width - the_width - 10); break;
		      	case 'center' :     
					start_x = Math.floor(window.screen.width / 2 - the_width / 2);
		    		start_y = Math.floor(window.screen.height / 2 - the_height / 2);
		    		break;      	
		    }
		    the_popup.moveTo(start_x, start_y);
		},
		
		///--------------------------------------------------------------------------
		popup_image: function(the_image, the_image_name, the_width, the_height) { // opens an image in a new popup
		    // keep track of how many popups where opened
		    cr.nav.popup_count++;
		
		    // Scale image to fit on user's screen
		    var max_width = window.screen.width-10;
		    var max_height = window.screen.height-120;
		    if (the_width > max_width) {
		        the_height = Math.floor((max_width / the_width) * the_height);
		        the_width = the_width;
		
		    }
		    if (the_height > max_height) {
		        the_width = Math.floor((max_height / the_height) * the_width);
		        the_height = max_height;
		    }
		    
		    // Create window
		    image_window = window.open('', 'cr_popup_'+cr.nav.popup_count, 'toolbar=no,status=no,resizable=no,directories=no,location=no,menubar=no,scrollbars=no,width='+the_width+',height='+the_height);
		    image_window.document.writeln('<html>');
		    image_window.document.writeln('<head><title>'+the_image_name+'</title></head>');
		    image_window.document.writeln('<style type="text/css">body { font: 12px Arial; color: #696969; margin: 0px; padding: 0px; background-color: #FFFFFF; }</style>');
		    image_window.document.writeln('<body><img src="'+the_image+'" width="'+the_width+'" height="'+the_height+'" /></body>');
		    image_window.document.writeln('</html>');
		    
		    // Move window to center of screen
		    var start_x = Math.floor(window.screen.width / 2 - the_width / 2);
		    var start_y = Math.floor(window.screen.height / 2 - the_height / 2);
		    image_window.moveTo(start_x, start_y);
		}

		///--------------------------------------------------------------------------		
	},
	
	///--------------------------------------------------------------------------
	string: { // manipulate strings
	  	leadzero: function(the_number, the_max) { // adds leading zeros to number
	  	  	if (the_max == null) the_max = 10;
	  	  	
	  	  	var the_string = the_number;
	  	  	do {
	  	  	  if (the_number < the_max) the_string = '0' + the_string;
	  	  	  the_max /= 10;
	  	 	}
	  		while (the_max > 1);
	  		
	  		return the_string;
	  	},
	  	
	  	///--------------------------------------------------------------------------
	  	password: function(the_length) { // generate a random set(0-9a-zA-Z) of characters
		  	var the_password = '';
		  	for (i = 0; i < the_length; i++) {
		  	  	var the_charcode = cr.number.random(62);
				
				var the_charoffset = 48; // 0..9
				if (the_charcode > 9) the_charoffset += 7; // A..Z
				if (the_charcode > 35) the_charoffset += 6; // a..z
				
				the_charcode += the_charoffset;
				
				the_password += String.fromCharCode(the_charcode); 
			}
			return the_password;	
	  	}

	  	///--------------------------------------------------------------------------
	},
	
	///--------------------------------------------------------------------------
	number: { // manipulate numbers
	  	random: function(the_max) { // generate a random number between 0 and the_max
	  	  	return (Math.floor(Math.random() * the_max));
	  	}
	  	
	  	///--------------------------------------------------------------------------
	},
	
	///--------------------------------------------------------------------------
	limit: { // event->onkeypress handling to limit input
	  	e_hex: function() { // event->onkeypress: limit to hex chars 0-9 and A-F
		  	// convert a-f to A-F
		  	if (event.keyCode >= 97 && event.keyCode <= 102) event.keyCode -=32;
		  	
		  	if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 65 && event.keyCode <= 70)) return true;
		  	else return false;
	  	},

		///--------------------------------------------------------------------------  	
	  	e_numeric: function() { // event->onkeypress: limit to chars 0-9
		  	if (event.keyCode >= 48 && event.keyCode <= 57) return true;
		  	else return false;
	 	},
	
		///--------------------------------------------------------------------------
		e_fraction: function() { // event->onkeypress: limit to chars 0-9 and .
		  	if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode == 46)) return true;
		  	else return false;
		},

		///--------------------------------------------------------------------------
		e_date: function() { // event->onkeypress: limit to chars 0-9 and -
		  	if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode == 45)) return true;
		  	else return false;
		}
		
		///--------------------------------------------------------------------------
	},

	///--------------------------------------------------------------------------
	mouse: { // mouse manipulation
	  	x: 0, // mouse pointer x co-ordinate when capturing is enabled
	  	y: 0, // mouse pointer y co-ordinate when capturing is enabled

		///--------------------------------------------------------------------------
		capture: function() { // enables capturing of mouse pointer co-ordinates
			document.onmousemove = cr.mouse.e_capture;
		}, 

		///--------------------------------------------------------------------------
		e_capture: function() { // event->onmousemove: capture mouse pointer co-ordinates
			cr.mouse.x = event.clientX + document.body.scrollLeft;
			cr.mouse.y = event.clientY + document.body.scrollTop;
		} 

		///--------------------------------------------------------------------------
	},

	///--------------------------------------------------------------------------	
	regex : { // regular expression function
	  	tag_script : '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)' // <script></script>
	},
	
	///--------------------------------------------------------------------------	
	ajax : { // ajax engine
		request_count: 0, // open ajax requests
		
		///--------------------------------------------------------------------------		
		get_http_request : function() { // returns a cross-browser XMLHttpRequest object
		  	var http_request = false;

			try { // XMLHttpRequest object
				http_request = new XMLHttpRequest();
			} catch (e) {
				try { // Microsoft
			    	http_request = new ActiveXObject('Msxml2.XMLHTTP');
			  	} catch (e2) {
			    	try { // Other microsoft
			      		http_request = new ActiveXObject('Microsoft.XMLHTTP');
			    	} catch (e3) {
			      		http_request = false; // not supported
			    	}
			  	}
			}
			
		  	return http_request;
		},
		
		///--------------------------------------------------------------------------
		send : function(the_url, json) { // send a ajax request to the server
		  	/// init
		  	var json = cr.element.extend(json,
				{
				  	url			: the_url, 		// the url to send ajax request to
			  	  	block		: null, 		// the element in which to display the returned result
			  	  	method		: 'GET', 		// the http method to use when sending data
			  	  	callback	: null, 		// the callback function to trigger when request completed
			  	  	message		: 'Loading',	// the message text to display when loading 
			  	  	evaljs		: true,			// should javascript in the response be executed
			  	  	form		: null,			// send form information with request
			  	  	confirm		: false,		// confirmation message
			  	  	postdata	: null			// data to send as post data
			  	}
		  	);
		  	
		  	if (json.confirm && !confirm(json.confirm)) return false;

		  	if (json.block != null) {
				json.block = $(json.block);
				json.callback = 'cr.ajax.set_html';
			}
			
			if (json.postdata) json.method = 'POST';
		  	
		  	var http_request = cr.ajax.get_http_request();
			
			cr.uid++;
			cr.ajax.request_count++; 
			
		  	/// process
			http_request.onreadystatechange = function() {
			  	switch (http_request.readyState) {
			  	  	case 0 : break; // uninitialized
			  	  	case 1 : break; // loading
			  	  	case 2 : break; // loaded
			  	  	case 3 : break; // interactive
			  	  	case 4 : // completed
			  	  		cr.ajax.request_count--;
						if (http_request.status == 200) eval(json.callback + '(http_request.responseText, json.block, json.evaljs)');
						// !Display Error
						break; 
			  	}
		    }
		   
		  	// post request
		  	var post_vars = (json.form != null && json.method == 'POST' ? cr.ajax.get_form_url(json.form) : (json.postdata ? json.postdata : null));
		  	http_request.open(json.method, json.url);
		  	if (post_vars) {
				http_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	      		http_request.setRequestHeader('Content-length', post_vars.length);
		  	}
			http_request.send(post_vars);
			if (json.message) cr.ajax.set_message(json.block, json.message);
		},
		
		///--------------------------------------------------------------------------
		set_message : function(the_block, the_message) { // display loading text
		  	var html = '<img src="./themes/default/icon_loading.gif" /> <span class="ajax-loading">' + the_message + ' ...</span>';
		  	$$(the_block, html)
		},
		
		///--------------------------------------------------------------------------
		set_html : function(the_html, the_block, the_evaljs) { // default handler to display response in block
		  	$$(the_block, the_html);
		  	if (the_evaljs) cr.ajax.eval_js(the_html);
		},
		
		///--------------------------------------------------------------------------
		eval_js : function(html_source) { // execute javascript code contained in html_source
			var regex = new RegExp(cr.regex.tag_script, 'ig');
			while (js = regex.exec(html_source)) eval(js[1]);		  	
		},
	
		///--------------------------------------------------------------------------
		get_form_url: function(the_form_arr) { // converts a form to encoded url
			if (typeof the_form_arr == 'string') the_form_arr = cr.array.from_string(the_form_arr); // make sure parameter is array
			
			var the_elements = new Array();
			var the_index = 0;
			var the_length = the_form_arr.length;
			for (var k = 0; k < the_length; k++) {
			  	var the_form = document.forms[the_form_arr[k]];
				var the_element_count = the_form.elements.length;
				
				for (var i = 0; i < the_element_count; i++) {
				  	var the_element = the_form.elements[i];
				  	if (the_element.name != null) {
				  	  	switch (the_element.type) {
				  	  	  	case 'hidden' :
				  	  	  	case 'text' :
				  	  	  	case 'password' :
				  	  	  	case 'textarea':
				  	  	  	case 'select-one' : 
								the_elements[the_index] = the_element.name + '=' + encodeURIComponent(the_element.value); 
								the_index++;
								break;
				  	  	  	case 'checkbox' :
				  	  	  	case 'radio' :
								if (the_element.checked) {
								  	the_elements[the_index] = the_element.name + '=' + encodeURIComponent(the_element.value);
								  	the_index++;
								}
								break;
							case 'select-multiple' : 
								var the_options = the_element.options;
								var the_option_count = the_options.length;
								for (j = 0; j < the_option_count; j++)
									if (the_options[j].selected) {
									  	the_elements[the_index] = the_element.name + '=' + encodeURIComponent(the_element.options[j].value);
										the_index++;
									}
								break;
				  	  	  	default : /* unsupported element type */ break;
				  	  	}	  	  	
					}
				}
			}
			
			var the_url = the_elements.join('&');
			return the_url;
		},
		
		///--------------------------------------------------------------------------
		runback: function(json) { // runs custom code based on parameters
		  	/// init
		  	var json = cr.element.extend(json,
				{
				  	type	: false, 	// Runback type: tab
				  	element	: null,		// Element or id of element on which action should be performed
				  	params	: null		// Custom parameter
			  	}
		  	);
		  	
		  	switch (json.type) {
		  	  	case 'tab'	: json.element.select(json.params[0], json.params[1], json.params[2]); break;
		  	  	case 'list'	: json.element.refresh(); break;
		  	}
		}
		
		///--------------------------------------------------------------------------
	}

	///--------------------------------------------------------------------------
}

///--------------------------------------------------------------------------