/* Utilities.php will include this file */

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

function newHttpRequest()
{
        if (window.XMLHttpRequest)
                return new XMLHttpRequest();
        else if (window.ActiveXObject)
                return new ActiveXObject("Microsoft.XMLHTTP");
}

function mysqlDatestringToJavascriptDate(mysql_datestring)
{
	if(mysql_datestring != null)
	{
		var datetime = mysql_datestring.split(' ');
		var date_string = datetime[0];
		var time_string = datetime[1];

		var date_array = date_string.split('-');
		var time_array = time_string.split(':');

		date = new Date(date_array[0], date_array[1] - 1, date_array[2], time_array[0], time_array[1], time_array[2], 0);
		// subtract one from month value for Javascript 0 indexed month numbers.

		return date;
	}
	else
	{
		return new Date();
	}
}

/*
 * datetimeToString() takes a date string as yyyy-MM-dd hh:mm:ss and returns a string formatted as described in the Greatvine time format spec
 *
 */
function datetimeToString(datetime, format, context)
{
	date = mysqlDatestringToJavascriptDate(datetime);

	var now = new Date();
	now.setHours(0);
	now.setMinutes(0);
	now.setSeconds(0);

	var formats = 
	{
	};

	var num_days_until_date = Math.floor((date.getTime() - now.getTime()) / (1000*60*60*24));

	if(num_days_until_date == 0)
		date_format = '"Today"';
	else if(num_days_until_date == -1)
		date_format = '"Yesterday"';
	else if(num_days_until_date == 1)
		date_format = '"Tomorrow"';
	else if(num_days_until_date < 0 && num_days_until_date > -7)
		date_format = Math.abs(num_days_until_date)+'" days ago"';
	else
		date_format = 'mmmm dS';

	if(context == 'PREPEND_ON' && (num_days_until_date > 1 || num_days_until_date < -1))
		var prestring = '"on "';
	else
		var prestring = '';

	try
	{
		if(format == 'HTML')
			return date.format(prestring+"'<span class=\"timestring\"><span class=\"day\">'"+date_format+"'</span>, <span class=\"time\">'"+'h:MMtt'+"'</span></span>'");
		else if(format == 'PLAINTEXT')
			return date.format(prestring+date_format+", h:MMtt");
		else if(format == 'FORUM_THREAD_LIST')
		{
			if(num_days_until_date < -30)
				return date.format('"previously"');
			else
				return date.format("h:MMtt, "+date_format);
				//return date.format("h:MMtt, "+date_format);
		}
		else if(format == 'FORUM_THREAD_SUMMARY_LIST')
		{
			if(num_days_until_date < -30)
				return date.format('"Previously"');
			else
				return date.format("d/m, h:MMtt");
		}
		else if(format == 'HTML_DATEONLY')
			return date.format(prestring+"'<span class=\"timestring\"><span class=\"day\">'"+date_format+"'</span>'");
	}
	catch(e)
	{
		return '[error - '+e+']';
	}	
}



/* 
 *	timestampToString() takes a UNIX (not Javascript) timestamp and returns a string formatted as described the Greatvine time format spec (when combined with corresponding CSS).
 *		On error it returns the error message 
 */
function timestampToString(timestamp, format, context)
{
	var date = new Date(parseInt(timestamp+'000',10));
	//alert(date.getTimezoneOffset());
	//date.setTime(date.getTime() - (date.getTimezoneOffset()) * 60000000);
	var now = new Date();
	now.setHours(0);
	now.setMinutes(0);
	now.setSeconds(0);

	var formats = 
	{
	};

	var num_days_until_date = Math.floor((date.getTime() - now.getTime()) / (1000*60*60*24));

	if(num_days_until_date == 0)
		date_format = '"Today"';
	else if(num_days_until_date == -1)
		date_format = '"Yesterday"';
	else if(num_days_until_date == 1)
		date_format = '"Tomorrow"';
	else
		date_format = 'mmmm dS';

	if(context == 'PREPEND_ON' && (num_days_until_date > 1 || num_days_until_date < -1))
		var prestring = '"on "';
	else
		var prestring = '';

	try
	{
		if(format == 'HTML')
			return date.format(prestring+"'<span class=\"timestring\"><span class=\"day\">'"+date_format+"'</span>, <span class=\"time\">'"+'h:MMtt'+"'</span></span>'");
		else if(format == 'PLAINTEXT')
			return date.format(prestring+date_format+", h:MMtt");
		else if(format == 'FORUM_THREAD_LIST')
			return date.format("h:MMtt, "+date_format);
		else if(format == 'FORUM_THREAD_SUMMARY_LIST')
			return date.format("d/m, h:MMtt");
		else if(format == 'HTML_DATEONLY')
			return date.format(prestring+"'<span class=\"timestring\"><span class=\"day\">'"+date_format+" yyyy'</span>'");
	}
	catch(e)
	{
		return '[error - '+e+']';
	}
}



function Queue()
{
	var self = this;
	var types = new Array();
	var functions = new Array();
	var args = new Array();

	this.addWithCallback = function()
	{
		types.push('callback');
		functions.push(arguments[0]);
		args.push(Array.prototype.slice.call(arguments).slice(1));
	}

	this.addWithoutCallback = function()
	{
		types.push('return');
		functions.push(arguments[0]);
		args.push(Array.prototype.slice.call(arguments).slice(1));
}

	this.runNextInQueue = function()
{
		var type = types.shift();
		var f = functions.shift();
		var x = args.shift();
		if(type == 'return')
		{
			f.apply(self, x);
			self.runNextInQueue();
		}
		else if(type == 'callback')
	{
			x.push(self.runNextInQueue);
			f.apply(self, x);
		}
	}
}

var Animate = new function()
{
	this.makeTransparent = function(object, callbackFunction)
	{
		var opacity = 0;
		setOpacity(object, opacity);
		if(callbackFunction !== undefined)
			callbackFunction();
	}
	this.makeNotTransparent = function(object, callbackFunction)
	{
		var opacity = 1;
		setOpacity(object, opacity);
		if(callbackFunction !== undefined)
			callbackFunction();
	}
	this.fadeIn = function(object, callbackFunction)
	{
		var opacity = 0;
		setTimeout(doFade, 1);
		function doFade()
		{
			if(opacity < 1)
			{
				opacity += 0.1;
	//				object.style.opacity = opacity;
				setOpacity(object, opacity);
				setTimeout(doFade, 33);
			}
			else
			{
				if(callbackFunction !== undefined)
					callbackFunction();
			}
		}
	}

	this.fadeOut = function(object, callbackFunction)
	{
		var opacity = 1;

		setTimeout(doFade, 1);

		function doFade()
		{
			if(opacity > 0)
			{
				opacity -= 0.1;
	//				object.style.opacity = opacity;
				setOpacity(object, opacity);
				setTimeout(doFade, 33);
			}
			else
			{
				if(callbackFunction !== undefined)
					callbackFunction();
			}
		}
	}

	this.slideOpen = function(object, callbackFunction)
	{
		var target_height = object.offsetHeight;
		var current_height = 0;
		
		object.style.position = 'static';
		object.style.visibility = 'inherit';
		object.style.height = '0px';
		
		setTimeout(doSlide, 1);
		
		function doSlide()
		{
			if(current_height < target_height)
			{
				current_height += 25;
				object.style.height = (current_height > target_height) ? "auto" : current_height+'px';
				setTimeout(doSlide, 50);
			}
			else
			{
				if(callbackFunction !== undefined)
					callbackFunction();
			}
		}
	}

	this.slideClosed = function(object, callbackFunction)
	{
		var current_height = object.offsetHeight;
		setTimeout(doSlide, 1);

		function doSlide()
		{
			if(current_height > 0 && object.style.visibility != 'hidden')
			{
				object.style.height = current_height+'px';
				current_height -= 25;
				setTimeout(doSlide, 50);
			}
			else
			{
				object.style.height = 'auto';
				object.style.position = 'absolute';
				object.style.visibility = 'hidden';
				if(callbackFunction !== undefined)
					callbackFunction();
			}
		}	
	}

	this.flicker = function(object)
	{
		var numberOfFlashes = 6;
		setTimeout(hide, 1);
		function hide()
		{
			object.style.visibility = 'hidden';
			setTimeout(show, 50);
		}
		function show()
		{
			object.style.visibility = 'inherit';
			if(numberOfFlashes > 0)
				setTimeout(hide, 75);
			numberOfFlashes--;
		}
	}	

	function setOpacity(obj, opacity)
	{
		var win_opacity = (opacity == 1)?99.999:(opacity*100);

		// IE/Win
		obj.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+ win_opacity + ");";

		// Safari less than 1.2, Konqueror
		//obj.style.KHTMLOpacity = opacity;

		// Older Mozilla and Firefox
		//obj.style.MozOpacity = opacity;

		// Safari 1.2, newer Firefox and Mozilla, CSS3
		obj.style.opacity = opacity;
	}
}




function createElem(type, id, className, onclick, innerHTML)
{
	var element = document.createElement(type);
	element.id = id;
	element.className = className;
	element.onclick = onclick;
	element.innerHTML = innerHTML;
	if(type == 'a')
		element.href="";

	return element;
}

function List(container)
{
	var self = this;

	this.numItemsToShow = 6;
	this.totalNumItems = 0;
	this.totalNumNewItems = 0;
	this.currentPage = 0; // counting from zero
	this.paged = true;
	this.zebraStripes = true;
	this.listItems = new Array();

	container.className = 'list_container';

	var listHeader = document.createElement('h2');
	listHeader.className = 'message_list';
	var listHeading = document.createElement('span');
	var listSubheading = document.createElement('span');
	listSubheading.className = 'subheading';
	listHeader.appendChild(listHeading);
	listHeader.appendChild(listSubheading);
	var pager_container = document.createElement('span');
	var listBody = document.createElement('div');
	var listBody = document.createElement('div');
	var listFooter = document.createElement('div');

	var infoBox = document.createElement('p');
	infoBox.className = 'informational';
	infoBox.style.display = 'none';

	container.appendChild(listHeader);
	container.appendChild(infoBox);
	container.appendChild(listBody);
	container.appendChild(listFooter);
	listSubheading.appendChild(pager_container);

//	var element = document.createElement('div');
//	element.style.clear = 'both';
//	container.appendChild(element); // to space out bottom

	this.setHeading = function(object)
	{
		listSubheading.appendChild(object);
	}

	this.setTitle = function(text)
	{
		listHeading.innerHTML = text;
	}

	this.setSubtitle = function(text)
	{
		listSubheading.innerHTML = text;
	}

/*
	this.setSubtitle = function(element)
	{
		listSubheading.innerHTML = '';
		listSubheading.appendChild(pager_container);
		listSubheading.appendChild(document.createTextNode(' - '));
		listSubheading.appendChild(element);
	}
*/

	this.appendInFooter = function(element)
	{
		listFooter.innerHTML = '';
		listFooter.appendChild(element);
	}

	this.showMessage = function(message)
	{
		listBody.innerHTML = '';

		listBody.innerHTML = '<p class="emptyList">'+message+'</p>';
	}

	this.showInfoBox = function(text)
	{
		infoBox.innerHTML = text;
		infoBox.style.display = 'block';
	}

	this.showList = function()
	{
		listBody.innerHTML = '';

		for(var i=0; i < self.listItems.length; i++)
		{
			listBody.appendChild(self.listItems[i].getDomElement());
		}

		if(this.paged && self.totalNumItems > 0 && self.numItemsToShow != null)
		{
			pager_container.innerHTML = '';
			pager_container.appendChild(generatePagerButtons());
		}
		else
		{
			var container = createElem('div', '', '', '', '');
			container.style.cssFloat = "right";
			container.style.margin = "1em";
			listBody.appendChild(container);
		}
//		listFooter.appendChild(a);
	}

	this.hide = function()
	{
		container.style.display = 'none';
	}

	this.show = function()
	{
		container.style.display = 'block';
	}

	this.hideHeader = function()
	{
		listHeader.style.display = 'none';
	}

	this.showHeader = function()
	{
		listHeader.style.display = 'block';
	}

	this.showDeleteButton = function(callBack)
	{
		var a = document.createElement('div');
		var deleteMessagesButton = document.createElement('a');
		deleteMessagesButton.className = 'delete_messages_button';
		deleteMessagesButton.onclick = function() { callBack(); return false; };
		a.appendChild(deleteMessagesButton);
		listBody.appendChild(a);
	}

	this.showUntrackThreadsButton = function()
	{
		var a = document.createElement('div');
		var untrackThreadsButton = document.createElement('a');
		untrackThreadsButton.className = 'btn_stop_tracking_selected';
		untrackThreadsButton.onclick = function() { untrackMarkedItems(); return false; };
		a.appendChild(untrackThreadsButton);
		listBody.appendChild(a);
	}

	this.setPaged = function(paging)
	{
		if(paging == true)
			self.paged = true;
		else
			self.paged = false;
	}

	this.setNumberItemsToShow = function(numItemsToShow)
	{
		self.numItemsToShow = numItemsToShow;
	}

	this.paintZebraStripes = function()
	{
//		for (i=0; i<self.listItems.length; i=i+2)
//		{
//			self.listItems[i].();
//		}
	}

	this.setZebraStripes = function()
	{
		
	}

	this.clearZebraStripes = function()
	{
	}

	function generatePagerButtons()
	{
		var container = document.createElement('span');
		container.className = 'list_pager_control';

		if((self.currentPage * self.numItemsToShow) > 0)
			var prev = createElem('a', '', '', gotoPreviousPage, 'Prev');
		else
			var prev = createElem('span', '', 'inactive', '', 'Prev');

		if(((self.currentPage * self.numItemsToShow)+self.numItemsToShow) > self.totalNumItems)
			var last_message_shown = self.totalNumItems;
		else
			var last_message_shown = ((self.currentPage * self.numItemsToShow)+self.numItemsToShow);

		var mid = document.createElement('span');
		mid.className = 'page_count_display';
		mid.innerHTML =	'Showing '+ ((self.currentPage * self.numItemsToShow)+1)+'-'+last_message_shown +' of '+self.totalNumItems;

		if((self.currentPage * self.numItemsToShow) + self.numItemsToShow < self.totalNumItems)
			var next = createElem('a', '', '', gotoNextPage, 'Next');
		else
			var next = createElem('span', '', 'inactive', '', 'Next');

		container.appendChild(prev);
		container.appendChild(document.createTextNode(' | '));
		container.appendChild(mid);
		container.appendChild(document.createTextNode(' | '));
		container.appendChild(next);

		return container;
	}

	function gotoNextPage()
	{
		self.currentPage++;
		self.getListItems();
		return false;
	}

	function gotoPreviousPage()
	{
		self.currentPage--;
		self.getListItems();
		return false;
	}

/*
	function deleteMarkedItems()
	{
		var messageIdList = '';

		for (i=0; i<self.listItems.length; i++)
		{
			if(self.listItems[i].isMarked())
				messageIdList += '-'+ self.listItems[i].getId();
		}

		var http_request = newHttpRequest();

		http_request.onreadystatechange = function()
		{
			if (http_request.readyState == 4)
			{
				if (http_request.status == 200)
				{
					self.getListItems();
				}
				else
				{

				}
			}
			else
			{
			}
		};

		http_request.open('GET', TEMPLATE_PATH+'/includes/messaging/delete_messages.php?messageIdList='+messageIdList, true);
		http_request.send('');
	}
*/

	function untrackMarkedItems()
	{
		var itemIdList = '';

		for (i=0; i<self.listItems.length; i++)
		{
			if(self.listItems[i].isMarked())
				itemIdList += '-'+ self.listItems[i].getId();
		}

		var http_request = newHttpRequest();

		http_request.onreadystatechange = function()
		{
			if (http_request.readyState == 4)
			{
				if (http_request.status == 200)
				{
					self.getListItems();
				}
				else
				{

				}
			}
			else
			{
			}
		};

		http_request.open('GET', TEMPLATE_PATH+'/includes/forums/untrack_threads.php?threadIdList='+itemIdList, true);
		http_request.send('');
	}

	this.closeOtherItems = function(callingItem)
	{
		for(i=0; i < self.listItems.length; i++)
		{
			if(self.listItems[i] != callingItem)
				self.listItems[i].unselect();
		}
	}

	this.deselectOtherItems = function(callingItem)
	{
		for(i=0; i < self.listItems.length; i++)
		{
			if(self.listItems[i] != callingItem)
				self.listItems[i].deselectMessage();
		}
	}

	this.getName = function()
	{
		return this.getId();
	}

	this.clearList = function()
	{
		self.listItems = new Array();
		listBody.innerHTML = '';
		//self.showList();
	}
}

function RotatingPanel(container)
{
	var panes = new Array();
	var tabs = new Array();
	var current_pane_id = 0;
	var timeout = null;
	var in_transition = false;
	var pending_pane_transition_timeout = null;

	container.onmouseover = stop_animation;
	container.onmouseout = start_animation;

	var tabs_container = document.createElement('span');
	tabs_container.className = 'tabs_container';

	for(i in container.childNodes)
	{
		if(container.childNodes[i].className == 'pane')
		{
			panes.push(container.childNodes[i]);
			tabs.push(create_tab(tabs.length));
			tabs_container.appendChild(tabs[tabs.length-1]);
			tabs_container.appendChild(document.createTextNode(' '));
		}
	}

	container.insertBefore(tabs_container, container.firstChild);

	tabs[0].innerHTML = '&#9679';
	timeout = setTimeout(display_next_pane, 8000);

	this.set_style_off = function()
	{
		container.style.padding = '0px';
		container.style.background = 'none';
		container.style.border = 'none';
		container.style.borderRadius = '0';
		container.style.MozBorderRadius = '0';
		container.style.WebkitBorderRadius = '0';
		tabs_container.style.display = 'none';
	}

	function display_next_pane()
	{
		var new_pane =	current_pane_id + 1;
		if(new_pane > (panes.length - 1))
			new_pane = 0;

		transition_to_pane(new_pane);

		timeout = setTimeout(display_next_pane, 8000);
	}

	function transition_to_pane(new_pane_id)
	{
		if(new_pane_id != current_pane_id && in_transition == false)
		{
			stop_animation();
			abort_pending_pane_transition();
			panes[new_pane_id].style.opacity = 0;

			in_transition = true;

			var queue = new Queue();
			queue.addWithCallback(Animate.fadeOut, panes[current_pane_id]);
			queue.addWithoutCallback(function() {
				panes[current_pane_id].style.display = 'none';
				panes[new_pane_id].style.display = 'block';
				tabs[current_pane_id].innerHTML = '&#9675;';
				tabs[new_pane_id].innerHTML = '&#9679;';
			});
			queue.addWithCallback(Animate.fadeIn, panes[new_pane_id]);
			queue.addWithoutCallback(function() {
				current_pane_id = new_pane_id;
				in_transition = false;
			});
			queue.runNextInQueue();
		}
	}

	function display_pane(new_pane_id)
	{
		abort_pending_pane_transition();
		stop_animation();
		panes[current_pane_id].style.display = 'none';
		panes[new_pane_id].style.display = 'block';
		panes[new_pane_id].style.opacity = 1;
		tabs[current_pane_id].innerHTML = '&#9675;';
		tabs[new_pane_id].innerHTML = '&#9679;';
		current_pane_id = new_pane_id;
	}

	function start_animation()
	{
		timeout = setTimeout(display_next_pane, 8000);
	}

	function stop_animation()
	{
		clearTimeout(timeout);
	}

	function queue_pane_transition(pane_id, timeout)
	{
		pending_pane_transition_timeout = setTimeout(function() {transition_to_pane(pane_id)}, timeout);
	}

	function abort_pending_pane_transition()
	{
		clearTimeout(pending_pane_transition_timeout);
		in_transition = false;
		panes[current_pane_id].style.display = 'block';
		panes[current_pane_id].style.opacity = 1;
	}

	function create_tab(tab_id)
	{
		var tab = document.createElement('a');
		tab.innerHTML = '&#9675;';
		tab.href = '';
		tab.style.color = '#aaaaaa';
		eval('tab.onmouseover = function() {display_pane('+tab_id+');}');
		eval('tab.onclick = function() {display_pane('+tab_id+'); return false;}');
		return tab;
	}
}

function Scroller(root_element)
{
	var in_transition = false;
	var children = root_element.childNodes;
	var top_element = children[0];
	var margin_top = 0;

	var pause = false;

	root_element.onmouseover = function()
	{
		pause = true;
	};

	root_element.onmouseout = function()
	{
		pause = false;
	};

	function do_scrolls()
	{
//		if(new_pane_id != current_pane_id && in_transition == false)
//		{
//			in_transition = true;
//		}

		if(pause == false)
		{
			var aaa = root_element.removeChild(top_element);
			aaa.style.marginTop = '0px';
			margin_top = 0;
			root_element.appendChild(aaa);

			children = root_element.childNodes;
			top_element = children[0];

			do_scroll();
		}


		window.setTimeout(do_scrolls, 5000);
	}

	function do_scroll()
	{
		if(Math.abs(parseInt(getStyle(top_element, 'margin-top'))) < parseInt(getStyle(top_element, 'height')))
		{
			if(pause == false)
			{
				top_element.style.marginTop = -margin_top+'px';

				margin_top += 2;
			}

			window.setTimeout(do_scroll, 15);
		}
	}

/*	var img = document.createElement('img');
	img.src = "/images/gradients/white-bottom-fade-out.png";
	img.style.position = 'absolute';
	img.style.top = '0px;'
	img.style.border = '1px solid green';
	root_element.parentNode.appendChild(img);
*/
	do_scrolls();
}

function checkForNewMessagesAndAppointments()
{
	if(EXTRANET_USER_ID == '')
		return;

	var http_request = newHttpRequest();

	http_request.onreadystatechange = function()
	{
		if (http_request.readyState == 4)
		{
			if (http_request.status == 200)
			{
				var result = eval("("+http_request.responseText+")");

				document.getElementById('tabbar_num_new_messages').innerHTML = '';
				document.getElementById('tabbar_num_new_messages').appendChild(document.createTextNode(result['unread_messages']));
				if(result['unread_messages'] > 0)
					document.getElementById('tabbar_num_new_messages_container').style.display = 'inline';
				else
					document.getElementById('tabbar_num_new_messages_container').style.display = 'none';

				document.getElementById('tabbar_num_appointments').innerHTML = '';
				document.getElementById('tabbar_num_appointments').appendChild(document.createTextNode(result['outstanding_confirmed_appointments']));
				if(result['outstanding_confirmed_appointments'] > 0)
					document.getElementById('tabbar_num_appointments_container').style.display = 'inline';
				else
					document.getElementById('tabbar_num_appointments_container').style.display = 'none';

				//self.getListItems();
			}
		}
	};

	http_request.open('GET', TEMPLATE_PATH+'/includes/messaging/get_message_appointment_stats.php/', true);
	http_request.send('');	
}

function zeroPad(number)
{
	if(number < 10)
		return String(0)+String(number);
	else
		return String(number);
}

function truncateStringWithEllipses(string, max_number_characters)
{
	if(string.length > max_number_characters)
	{
		string = string.substring(0, max_number_characters - 2);

		if(string.charAt(string.length - 1) == ' ')
			string = string.replace(/ *$/, '');
		else
			string = string.replace(/ \S+$/, '');
		string += '...';
	}

	return string;
}

function login(username, password)
{
	var http_request = newHttpRequest();

	http_request.onreadystatechange = function()
	{
		if (http_request.readyState == 4)
		{
			if (http_request.status == 200)
			{
				return 'SUCCESS';
			}
			else
			{
			}
		}
		else
		{
		}
	};

	http_request.open('GET', '/web-client-api/sign_in.php?username='+username+'&password='+password, false);
	http_request.send('');	
}

/*
var login_dialog = '<div class="title" style="margin: 0px;"><h1>You need to log back in</h1></div>\
<div style="padding: 1.25em; background-color: #f9f7f4;"> \
	<p style="padding: 1em 0px 1em 0px; font-weight: bold;">\
		Your session has timed out.<br />\
		Please log back in to continue.\
	</p>\
	<div style="margin: auto; width: 300px;">\
		<p style="padding: 1em 0px 1em 0px; color: #EF8E17;">\
			<table style="border-spacing: 1em;">\
			<tbody>\
				<tr><td>Email:</td><td><input type="text" style="width: 100%;" id="username" /></td></tr>\
				<tr><td>Password:</td><td><input type="text" style="width: 100%;" id="password" /></td></tr>\
			</tbody>\
			</table>\
		</p>\
		<p style="padding: 1em 0px 1em 0px; color: #EF8E17;">\
			<a class="btn_login" href="" onclick="if(login(document.getElementById(\'username\').value, document.getElementById(\'password\').value)) == \'SUCCESS\') TINY.box.hide(); return false;"></a>\
			<a class="btn_cancel" href="" onclick="TINY.box.hide(); return false;" style=""></a>\
		</p>\
		<div style="clear: both;"></div>\
	</div>\
</div>';
*/


function get_login_dialog_html(message, page)
{
	return '<div class="popup">\
			<h2>Log in required</h2>\
				<p>\
					You need to log in to '+message+'.\
				</p>\
				<table style="width: 100%;">\
				<tr>\
					<td colspan="2" style="text-align: right;">\
						<a href="/account/sign-in?requested_destination='+encodeURIComponent(page)+'" class="button">Login</a>\
						<a href="" onclick="TINY.box.hide(); return false;" class="button">Cancel</a>\
					</td>\
				</tr>\
				</table>\
			</div>';
}

function get_done_dialog_html(message)
{
	return '<div class="popup">\
			<h3>Done!</h3>\
				<p>\
					'+message+'\
				</p>\
				<table style="width: 100%;">\
				<tr>\
					<td colspan="2" style="text-align: right;">\
						<a href="" onclick="TINY.box.hide(); return false;" class="button">OK</a>\
					</td>\
				</tr>\
				</table>\
			</div>';
}

function http_request_set_success_callback(http_request, success_action, failure_action)
{
	http_request.onreadystatechange = function()
	{
		if (http_request.readyState == 4)
		{
			if (http_request.status == 200)
			{
				if(http_request.responseText == 'USER_NOT_LOGGED_IN' && failure_action == 'SIGNIN_PROMPT')
				{
					TINY.box.show(login_dialog, 0, 0, 0, 0, 0);
				}
			}
			else if (http_request.status == 200)
			{
				if(typeOf(success_action == 'function'))
					success_action(http_request.responseText);
			}
			else
			{

			}
		}
	}
}

function like_item(item_type, item_id, element)
{
	var http_request = newHttpRequest();

	http_request.onreadystatechange = function()
	{
		if (http_request.readyState == 4 && http_request.status == 200)
		{
			if(http_request.responseText == 'USER_NOT_LOGGED_IN')
			{
				TINY.box.show(get_login_dialog_html('like items', window.location), 0, 0, 0, 0, 0);
			}
			else if(http_request.responseText == 'ALREADY_LIKED')
			{
				TINY.box.show(get_done_dialog_html('You have liked this already.'), 0, 0, 0, 0, 0);
			}
			else
			{
				TINY.box.show(get_done_dialog_html('Thanks.  Your vote has been recorded.'), 0, 0, 0, 0, 0);
			}
		}
		else
		{
		}
	};

//	function on_success()
//	{
//		element.innerHTML = parseInt(element.innerHTML) + 1;
//	}

//	http_request_set_success_callback(http_request, on_success)

	http_request.open('GET', '/public-api/like_item.php?item_type='+item_type+'&item_id='+item_id, true);
	http_request.send('');	
}

function bookmark_item(item_type, item_id, element)
{
	var http_request = newHttpRequest();

	http_request.onreadystatechange = function()
	{
		if (http_request.readyState == 4 && http_request.status == 200)
		{
			if(http_request.responseText == 'USER_NOT_LOGGED_IN')
			{
				TINY.box.show(get_login_dialog_html('add items to your favourites', window.location), 0, 0, 0, 0, 0);
			}
			else
			{
				TINY.box.show(get_done_dialog_html('This item has been added to your favourites.'), 0, 0, 0, 0, 0);
			}
		}
		else
		{
		}
	};
	http_request.open('GET', '/public-api/bookmark_item.php?item_type='+item_type+'&item_id='+item_id, true);
	http_request.send('');	
}

function remove_from_favourites(item_type, item_id)
{
	var http_request = newHttpRequest();

	http_request.onreadystatechange = function()
	{
		if(http_request.readyState == 4)
		{
			if(http_request.status == 200)
			{
				if(http_request.responseText == 'SUCCESS')
					window.location.reload();
			}
		}
		else
		{
		}
	};



	http_request.open('GET', '/web-client-api/remove_item_from_favourites.php?item_type='+item_type+'&item_id='+item_id, true);
	http_request.send('');
}

function dismiss_notification(notification_id)
{
	var http_request = newHttpRequest();

	http_request.onreadystatechange = function()
	{
		if(http_request.readyState == 4)
		{
			if(http_request.status == 200)
			{
				if(http_request.responseText == 'SUCCESS')
					window.location.reload();
			}
		}
		else
		{
		}
	};
	http_request.open('GET', '/web-client-api/dismiss_notification.php?id='+notification_id, true);
	http_request.send('');	
}




function submitenter(element, event)
{
	var keycode;
	if(window.event)
		keycode = window.event.keyCode;
	else if(event)
		keycode = event.which;

	if(keycode == 13)
	{
		this.submit();
	}
}

function addLoadEvent(func)
{
/*
	if(typeof window.onload == 'undefined')
	{
		alert('a');
	}
	else
	{
		alert('b');
	}
*/


	var oldonload = window.onload; 
	if (typeof window.onload != 'function')
	{
		window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			if (oldonload)
			{
				oldonload(); 
			} 
			func(); 
		} 
	} 

} 
	 
function TopicMenu(tab, menu)
{
	var timeout_id = null;

	function start_hide_menu()
	{
		//alert('out');
		//clearTimeout(timeout_id);
		timeout_id = setTimeout(hide_menu, 200);
	}

	function hide_menu()
	{
		menu.style.display = 'none';
	}

	function show_menu()
	{
		if(timeout_id != null)
		{
			clearTimeout(timeout_id);
		}

		menu.style.display = 'block';
	}

	tab.onmouseover = show_menu;
	menu.onmouseover = show_menu;

	tab.onmouseout = start_hide_menu;
	menu.onmouseout = start_hide_menu;
}

function initialise_input_element(element)
{
	if(element.className.match(/(^| )unused($| )/))
	{
		element.className = element.className.replace(/unused/, '');
		element.value='';
		element.onfocus = null;
	}
}

function getStyle(element, property)
{
	if(element.currentStyle)
		return element.currentStyle[property];
	else if(window.getComputedStyle)
		return document.defaultView.getComputedStyle(element, null).getPropertyValue(property);
	else
		return null;
}

function show_preview(documentId)
{
	window.open('/web-client-api/documents/preview.php?id='+documentId, 'ContentPreview'+documentId, 'menubar=no,location=no,resizable=yes,scrollbars=yes,status=no,height=900,width=700');
}


function show_notification_popup(consultant_user_id, consultant_phone_number, consultant_first_name, consultant_last_name, consultant_professional_title, consultant_sex, consultant_image_url)
{
	var http_request = newHttpRequest();

	http_request.open('GET', '/api/public/get_availability_notification_id?consultant_user_id='+consultant_user_id+'&consultant_phone_number='+consultant_phone_number, false);
	http_request.send();

	if(http_request.responseText.substring(0,6) == 'ERROR:')
	{
//		document.getElementById('messageBox').innerHTML = 'There is an error in your details, please check them and try again.';
//		document.getElementById('messageBox2').innerHTML = 'There is an error in your details, please check them and try again.';
//		document.getElementById('messageBox2').style.color = 'red';
//		document.getElementById('update_billing_btn').disabled = false;
	}
	else if(http_request.responseText == 'SUCCESS')
	{
		
	}

	var confirmationMessage = '<h3 style="text-align: center; margin: 0px 0px 0.75em 0px;">Request a call with '+consultant_first_name+'</h3>\
		<hr />\
			<table><tr>\
			<td style="width: 70px;"><img src="'+consultant_image_url+'" class="consultant_image" /></td>\
			<td><h4 class="consultant" style="line-height: 180%;">'+consultant_first_name+' '+consultant_last_name+'<br /><span class="professional_title">'+consultant_professional_title+'</span></h4></td>\
			</tr></table>\
		<hr />\
		<div style="padding: 1.25em 0px 0px 0px; text-align: center;">\
			<p id="popup_instruction_box" style="font-size: 19px; margin: 0px;">\
				Please enter your mobile number\
			</p>\
			<p style="font-size: 15px; margin: 0px;">\
				We\'ll send you a <strong>free</strong> text as soon as '+consultant_first_name+'\'s available.\
			</p>\
			<div id="popup_control_box" style="margin: 1em 0px 0px 0px;">\
				<div style="margin: 0px 0px 0.5em 0px;">\
					<input type="text" id="mobile_number" name="mobile_number"  style="width: 200px; `font-size: 150%;" />\
					&nbsp;&nbsp;<button onclick="request_notification('+parseInt(http_request.responseText)+', document.getElementById(\'mobile_number\').value);" style="font-size: 150%;">Request call</button><br />\
				</div>\
				<div>\
					or <a href="#" onclick="TINY.box.hide(); return false;">Cancel</a>\
				</div>\
				<div id="popup_error_box"></div>\
			</div>\
		</div>';

	TINY.box.show(confirmationMessage,0,500,0,0,0);

//((consultant_sex == 'FEMALE') ? 'she' : 'he' )
}

function request_notification(availability_notification_id, user_phone_number)
{
	var http_request = newHttpRequest();

	http_request.onreadystatechange = function()
	{
		if(http_request.readyState == 4 && http_request.status == 200)
		{
			if(http_request.responseText == 'VALID')
			{
				document.getElementById('popup_instruction_box').innerHTML = 'Thank you.';
				document.getElementById('popup_control_box').innerHTML = '<button onclick="TINY.box.hide()" style="font-size: 150%;">OK</button>';
			}
			else
			{
				document.getElementById('popup_error_box').innerHTML = '<div style="margin: 1em 0px; color: red;">The number you endered does not appear to be a valid mobile phone number.  Please try again.</div>';
			}
		}
	};

	dataString = 'availability_notification_id='+availability_notification_id+'&user_phone_number='+user_phone_number;

	http_request.open('POST', '/bapi/request_consultant_availability_notification', true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", dataString.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(dataString);
}


function add_to_newsletter_list(email_address)
{
	var http_request = newHttpRequest();

	http_request.onreadystatechange = function()
	{
		if(http_request.readyState == 4 && http_request.status == 200)
		{
			if(http_request.responseText == 'VALID')
			{
				TINY.box.show(confirmation_message);
			}
			else
			{
				TINY.box.show(error_message);
			}
		}
	};

	var error_message = '<h3 style="text-align: center; margin: 0px 0px 0.75em 0px;">There appears to be an error in your email address</h3>\
		<div style="padding: 1.25em 0px 0px 0px; text-align: center;">\
			<p id="popup_instruction_box" style="font-size: 19px; margin: 0px;">\
				Please check it and try again.\
			</p>\
			<div id="popup_control_box" style="margin: 1em 0px 0px 0px;">\
				<a href="#" onclick="TINY.box.hide(); return false;" class="button">OK</a>\
			</div>\
		</div>';

	var confirmation_message = '<h3 style="text-align: center; margin: 0px 0px 0.75em 0px;">Thank you</h3>\
		<div style="padding: 1.25em 0px 0px 0px; text-align: center;">\
			<p id="popup_instruction_box" style="font-size: 19px; margin: 0px;">\
				You have been added to the mailing list.\
			</p>\
			<div id="popup_control_box" style="margin: 1em 0px 0px 0px;">\
				<a href="#" onclick="TINY.box.hide(); return false;" class="button">OK</a>\
			</div>\
		</div>';

	dataString = 'email_address='+email_address;

	http_request.open('POST', '/bapi/add_to_newsletter_list', true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", dataString.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(dataString);
}

