//
// WYSIWYG FUNCTIONS
//
function getEditorContents(instance)
{
	// Get the editor instance that we want to interact with.
	if(typeof(FCKeditorAPI) != "undefined" && FCKeditorAPI.GetInstance(instance))
	{
		var oEditor = FCKeditorAPI.GetInstance(instance) ;
		// Get the editor contents in XHTML.
		return oEditor.GetXHTML( true ) ;		// "true" means you want it formatted.
	}
	else
		return false;
}

function insertEditorHTML(instance, value)
{
	// Get the editor instance that we want to interact with.
	var oEditor = FCKeditorAPI.GetInstance(instance) ;

	if(oEditor)
	{
		// Check the active editing mode.
		if ( oEditor.EditMode == FCK_EDITMODE_WYSIWYG )
		{
			// Insert the desired HTML.
			oEditor.InsertHtml( value ) ;
		}
		else
			alert( 'You must be on WYSIWYG mode!' ) ;
	}
}

//
// GENERAL FUNCTIONS
//

var Cookie = {

	set: function(name, value, days_to_expire)

	{

		var expire = '';

		if ( days_to_expire != undefined )

		{

			var d = new Date();

			d.setTime(d.getTime() + (86400000 * parseFloat(days_to_expire)));

			expire = '; expires=' + d.toGMTString();

		}

		return (document.cookie = escape(name) + '=' + escape(value || '') + expire);

	},

	

	get: function(name)

	{

		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));

		return (cookie ? unescape(cookie[2]) : null);

	},

	

	erase: function(name)

	{

		var cookie = Cookie.get(name) || true;

		Cookie.set(name, '', -1);

		return cookie;

	},

	

	accept: function()

	{

		if (typeof navigator.cookieEnabled == 'boolean')

		{

			return navigator.cookieEnabled;

		}

		

		Cookie.set('_test', '1');

		return (Cookie.erase('_test') === '1');

	}

};

Array.prototype.inArray = function (value)
{
	for( ii = 0; ii < this.length; ii++ )
	{
		if( this[ii] == value )
		{
			return true;
		}
	}
	return false;
};

Array.prototype.removeElement = function (value)
{
	for( ii = 0; ii < this.length; ii++ )
	{
		if( this[ii] == value )
		{
			this.splice(ii, 1);
			return true;
		}		
	}
	return false;
}

Array.prototype.getIndex = function (value)
{
	for( ii = 0; ii < this.length; ii++ )
	{
		if( this[ii] == value )
		{
			return ii;
		}		
	}
	return false;
}

function sleep(millis)
{
	var date = new Date();
	var curDate = null;

	do
	{
		curDate = new Date();
	} 
	while(curDate-date < millis);
}

function cursorWait(id)
{
	document.body.style.cursor = "wait";
	if( typeof(id) != "undefined" && document.getElementById(id) )
		document.getElementById(id).style.cursor = "wait";
}

function cursorNormal(id)
{
	document.body.style.cursor = "auto";
	if( typeof(id) != "undefined" && document.getElementById(id) )
		document.getElementById(id).style.cursor = "auto";
}

function changeImage(id, src)
{
	document.getElementById(id).src = src;
}

function showAlert(msg)
{
	if( document.getElementById('alertArea').className == "visible")
	{		
		hideAlert();
		window.setTimeout('showAlert("'+msg+'")', 250);
	}
	else
	{
		document.getElementById('alertArea').className = "visible";
		document.getElementById('alertText').innerHTML = msg;
	}
}

function hideAlert()
{
	document.getElementById('alertArea').className = "hidden";
}

function enlargeSelectBox(id)
{
	if( document.getElementById(id) )
	{
		document.getElementById(id).size = 50;
		document.getElementById('icon_'+ id).src = "images/icons/icon-arrow_down.gif";
		document.getElementById('href_'+ id).href = "javascript:shrinkSelectBox('"+ id +"')";
	}
}

function shrinkSelectBox(id)
{
	if( document.getElementById(id) )
	{
		document.getElementById(id).size = 8;
		document.getElementById('icon_'+ id).src = "images/icons/icon-arrow_left.gif";
		document.getElementById('href_'+ id).href = "javascript:enlargeSelectBox('"+ id +"')";
	}
}

function addEvent(elm, evType, fn, useCapture)
{
	if( elm.addEventListener )
	{
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if( elm.attachEvent )
	{
		var r = elm.attachEvent('on'+ evType, fn);
		return r;
	}
	else
		elm['on'+ evType] = fn;
}

function getParentElement(el, tag_name)
{
	parent = el.parentNode;
	while( parent.tagName.toLowerCase() != tag_name.toLowerCase() )
	{
		parent = parent.parentNode;
		if(parent.tagName.toLowerCase() == "html")
			return false;
	}
	return parent;
}

function getPreviousSiblingElement(el, tag_name)
{
	if( sibling = el.previousSibling )
	{
		while( typeof(sibling.tagName) == "undefined" || sibling.tagName.toLowerCase() != tag_name.toLowerCase() )
		{
			sibling = sibling.previousSibling;
			if( sibling == null )
				return false;
		}
		return sibling;
	}
	else
		return false;
}

function getNextSiblingElement(el, tag_name)
{
	if( sibling = el.nextSibling )
	{
		while( typeof(sibling.tagName) == "undefined" || sibling.tagName.toLowerCase() != tag_name.toLowerCase() )
		{
			sibling = sibling.nextSibling;
			if( sibling == null )
				return false;
		}
		return sibling;
	}
	else
		return false;
}

// Inserts an ajax response using DOM
// This function only inserts rows
function insertResponse_rows(row, html)
{
	html = html.substr(html.indexOf('<tr'));
	
	table = row.parentNode;
	for(i = 0; i < table.childNodes.length; i++)
	{
		if(table.childNodes[i] == row)
		{
			if( i != (table.childNodes.length - 1) )
				sibling = table.childNodes[i + 1];
			else
				sibling = false;
			break;
		}
	}
	
	rows = parseResponse_rows(html);
	for(i = 0; i < rows.length; i++)
	{
		if( !sibling )
			table.appendChild(rows[i]);
		else
			table.insertBefore(rows[i], sibling);
	}
}

// Looks for a given HTML attribute in a given string and returns that attribute value
function getAttributeValue(str, attr)
{
	attr_index = str.indexOf(attr + "=");
	if(attr_index != -1)
	{
		at_len = attr.length + 2;
		ic_index = str.indexOf('"', attr_index + at_len);
		if(ic_index == -1)					
			ic_index = str.indexOf('\'', attr_index + at_len);
			
		if(ic_index != -1)
		{
			attribute = str.substring(attr_index + at_len, ic_index);
			return attribute;
		}		
	}
	return false;
}

function autoGrow(element)
{
	if( element.value.length > (element.rows - 1) * element.cols )
		++element.rows;
}

// Parses an HTML response into DOM row objects and adds the rows to an array to be returned
// Cannot deal with nested tables further than one level
function parseResponse_rows(result)
{
	// Deal with nested tables
	table_count = 0;
	tables = new Array();
	while( result.indexOf('<table') != -1 )
	{
		table_open = result.indexOf('<table');
		table_close = result.indexOf('</table>', table_open) + 8;
		tables.push(result.substring(table_open, table_close));
		result = result.substring(0, table_open) + '{table_'+ table_count +'}' + result.substring(table_close);
		table_count++;
	}
	
	rows = result.split('<tr');
	arr = new Array();
	for(i = 1; i < rows.length; i++)
	{
		// Create the row object
		row = document.createElement('tr');
		// Set the row attributes
		tr_close = rows[i].indexOf('>');
		if( tr_close > 0 )
		{
			attr = rows[i].substring(0, tr_close);
			if( id = getAttributeValue(attr, "id") )
				row.id = id;
			if( cls = getAttributeValue(attr, "class") )
				row.className = cls;
		}
		
		cells = rows[i].split("<td");
		for(j = 1; j < cells.length; j++)
		{
			// Create the cell object
			cell = document.createElement('td');
			
			// Set the cell attributes
			td_close = cells[j].indexOf('>');
			if(td_close > 0)
			{
				attr = cells[j].substring(0, td_close);
				if( id = getAttributeValue(attr, "id") )
					cell.id = id;
				if( cls = getAttributeValue(attr, "class") )
					cell.className = cls;
				if( align = getAttributeValue(attr, "align") )
					cell.align = align;
				if( nowrap = getAttributeValue(attr, "nowrap") )
					cell.nowrap = nowrap;
				if( colspan = getAttributeValue(attr, "colspan") )
					cell.colSpan = colspan;
				if( bgcolor = getAttributeValue(attr, "bgcolor") )
					cell.bgColor = bgcolor;
			}
			
			// Set innerHTML
			cell.innerHTML = cells[j].substring(td_close + 1, cells[j].indexOf('</td>'));
			
			// Check for nested table and insert html if found
			while( cell.innerHTML.indexOf('{table_') != -1 )
			{
				inner_html = cell.innerHTML;
				tag_open = inner_html.indexOf('{table_');
				tag_close = inner_html.indexOf('}', tag_open);
				tag = inner_html.substring(tag_open,tag_close);
				table_number = tag.substring(tag.indexOf('_') + 1, tag_close);
				inner_html = inner_html.substring(0, tag_open) + tables[table_number] + inner_html.substring(tag_close + 1);
				cell.innerHTML = inner_html;
			}

			// Add the cell to the row
			row.appendChild(cell);
		}
		
		// Add the row to the array
		arr.push(row);
	}
	return arr;
}

//  --------------------------------------------------------------------------------------
//	--------------------------------- AJAX FUNCTIONS -------------------------------------
//  --------------------------------------------------------------------------------------

function AjaxOld() {
	this.request = null;
	this.url = null;
	this.method = 'GET'; // Default request method
	this.async = true;
	this.status = null;
	this.status_text = '';
	this.data = null;
	this.ready_state = null;
	this.response_text = null;
	this.response_xml = null;
	this.response_format = null;
	this.handleResponse = null; // function that will handle the response
	this.mime_type = null;
	this.timeout = null;
	
	this.init = function()
	{
		if( !this.request )
		{
			this.request = TryOld(
				function() { return new XMLHttpRequest(); }, // Firefox, Safari, IE7
				function() { return new ActiveXObject('MSXML2.XMLHTTP'); }, // Later versions of IE
				function() { return new ActiveXObject('Microsoft.XMLHTTP'); } // Early versions of IE
			);
																																
			return this.request;
		}
		else
			return true;
	};
	
	this.doRequest = function()
	{
		var request = null;
		var head_array = [];
    
    if( !this.init() )
		{
      alert('Could not create XMLHttpRequest object.');
      return;
    }
		
    request = this.request;
    request.open(this.method, this.url, this.async);
		
    if( this.method == 'POST' )
		{
      request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
		
    var self = this; // Fix loss of scope issue
		
    request.onreadystatechange = function()
		{
      var response = null;
      self.readyState = request.readyState;
			
      if( request.readyState == 4 )
			{
				clearTimeout(self.timeout);
        try
				{
					self.status = request.status;
					self.status_text = request.statusText;
				}
				catch( e ) { }
        self.response_text = request.responseText;
        self.response_xml = request.responseXML;
        
        switch( self.response_format ) {
          case 'text':
            response = self.response_text;
            break;
          case 'xml':
            response = self.response_xml;
            break;
          case 'object':
            response = request;
            break;
        }
        
        if( self.status > 199 && self.status < 300 )
				{
          if( !self.handleResponse )
					{
            alert('No response handler defined for this XMLHttpRequest object.');
            return;
          }
          else
					{
            self.handleResponse(response);
          }
        }
        else
				{
          self.handleError(response);
        }
      }
    }
    request.send(this.data);
  };
	
  this.abort = function()
	{
    if( this.request )
		{
      this.request.onreadystatechange = function() { };
      this.request.abort();
      this.request = null;
    }
  };

  this.handleError = function()
	{
    try
		{
			if( AjaxOld.responseText )
			{
      	var error_window = window.open('', 'errorWin');
      	error_window.document.body.innerHTML = AjaxOld.responseText;
			}
    }
    catch(e) // Deal with blocked popup
		{
      alert('An error occurred, but the error message cannot be displayed because of your browser\'s pop-up blocker.\nPlease allow pop-ups from this Web site.');
    }
  };
	
	this.handleTimeout = function()
	{
		this.abort();
		alert('Error: A timeout occured with the request. Please try again.');
	};
	
	this.doGet = function(url, handler, format)
	{
    this.url = url;
    this.handleResponse = handler;
    this.response_format = format || 'text';
    this.doRequest();
	};
	
	this.doPost = function(url, data, handler, format)
	{
    this.url = url;
    this.data = data;
    this.handleResponse = handler;
    this.response_format = format || 'text';
    this.method = 'POST';
    this.doRequest();
	};
	
	this.tokenizeResponse = function(response)
	{
		if( response.indexOf('||') != -1 )
			return response.split('||');
		else
			return [response];
	};
	
	this.setMimeType = function(mime_type)
	{
		this.mime_type = mime_type;
	};
	
	this.setResponseHandler = function(func)
	{
		this.handleResponse = func;
	};
	
	this.setErrorHandler = function(func)
	{
		this.handleError = func; 
	};
	
	this.setHandlerBoth = function(func)
	{
		this.handleResponse = func;
		this.handleError = func;
	};
	
	this.setRequestHeader = function(name, value)
	{
		this.headers.push(name + ': ' + value);
	};
}

function doNothing(result)
{
	// Do nothing
}

function makeAjaxPostRequest(url, parameters, handler, timeoutHandler)
{
	var ajax = new AjaxOld();
	var requestTimer = null;
	
	// Deals with a request timeout
	// Generic function added here to avoid having to change the old code for the new Ajax class
	var requestTimeout = function()
	{
		ajax.abort();
			
		if( timeoutHandler )
			timeoutHandler();
			
		alert('Error: A timeout occured with the request. Please try again.');
		clearTimeout(requestTimer);
	}
	
	// Deals with request completion
	// Generic function added here to avoid having to change the old code for the new Ajax class
	// Needed to run the handler and clear the timeout after request completion
	var requestComplete = function(result)
	{
		handler(result);
		clearTimeout(requestTimer);
	}
	
	ajax.doPost(url, parameters, requestComplete);
	requestTimer = setTimeout(requestTimeout, 60000);
}

function makeAjaxRequest(url, handler, timeoutHandler)
{
	var ajax = new AjaxOld();
	var requestTimer = null;
	
	// Deals with a request timeout
	// Generic function added here to avoid having to change the old code for the new Ajax class
	var requestTimeout = function()
	{
		ajax.abort();
			
		if( timeoutHandler )
			timeoutHandler();
			
		alert('Error: A timeout occured with the request. Please try again.');
		
		clearTimeout(requestTimer);
	}
	
	// Deals with request completion
	// Generic function added here to avoid having to change the old code for the new Ajax class
	// Needed to run the handler and clear the timeout after request completion
	var requestComplete = function(result)
	{
		handler(result);
		clearTimeout(requestTimer);
	}
	
	ajax.doGet(url, requestComplete);
	requestTimer = setTimeout(requestTimeout, 60000);
}

function buildFormQuery(obj)
{
	var query_string = "";
	for (i=0; i<obj.elements.length; i++)
	{
		if (obj.elements[i].tagName == "TEXTAREA")
		{
			query_string += obj.elements[i].name + "=" + encodeURIComponent( obj.elements[i].value ) + "&";
		}
		if (obj.elements[i].tagName == "INPUT")
		{
			if (obj.elements[i].type == "password")
			{
				query_string += obj.elements[i].name + "=" + encodeURIComponent( obj.elements[i].value ) + "&";
			}
			if (obj.elements[i].type == "text")
			{
				query_string += obj.elements[i].name + "=" + encodeURIComponent( obj.elements[i].value ) + "&";
			}
			if (obj.elements[i].type == "hidden")
			{
				if(obj.elements[i].name != "")
				{
					value = getEditorContents(obj.elements[i].name)
				
					if(!value)
						value = obj.elements[i].value;
					
					query_string += obj.elements[i].name + "=" + encodeURIComponent( value ) + "&";
				}
			}
			if (obj.elements[i].type == "checkbox")
			{
				if (obj.elements[i].checked)
				{
					query_string += obj.elements[i].name + "=" + obj.elements[i].value + "&";
				}
				else
				{
					query_string += obj.elements[i].name + "=&";
				}
			}
			if (obj.elements[i].type == "radio")
			{
				if (obj.elements[i].checked)
				{
					query_string += obj.elements[i].name + "=" + obj.elements[i].value + "&";
				}
			}
		}   
		if (obj.elements[i].tagName == "SELECT")
		{
			var sel = obj.elements[i];
			if(!obj.elements[i].disabled)
			{
				if(sel.multiple == true)
				{
					for(var ii = 0; ii < sel.length; ii++)
					{
						
						if(sel.options[ii].selected)
							query_string += sel.name+"_"+ sel.options[ii].value + "=" +"1&";
						else
							query_string += sel.name +"_"+ sel.options[ii].value+ "=" +"0&";
					}
					
				}
				else {
					if( sel.selectedIndex >= 0 )
						query_string += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
				}
			}
		}
	}
	return query_string;
}

function isArray(a) {
    return isObject(a) && a.constructor == Array;
}
function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}
function isFunction(a) {
    return typeof a == 'function';
}

/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
var bustcachevar = 1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects= ""
var rootdomain = "http://" + window.location.hostname
var bustcacheparameter = ""


function showLoading( containerid, loading_text)
{
	if(	typeof(loading_text) == "undefined" )
		loading_text = "Loading";
		
	document.getElementById(containerid).innerHTML = 
	'<br><br><br><table align="center" cellpadding="0" cellspacing="0" style="border: 1px solid #CCCCCC; background-color: #FFFFFF;"><tr><td align="center" style="padding: 30px 50px 30px 50px;"><table border="0" cellspacing="0" cellpadding="0"><tr><td>&nbsp;<img src="images/icons/loading.gif" width="32" height="32" name="loading_img" id="loading_img"></td><td>&nbsp;&nbsp;&nbsp;</td><td style="font-size: 25px;">'+ loading_text +'&nbsp;</td></tr></table></td></tr></table><br><br><br>';
}

function ajaxpage(url, containerid, show_loading, timeout, loading_text)
{
	if(	typeof(show_loading) != "undefined" )
	{
		showLoading( containerid, loading_text);
	}
	
	if( typeof(timeout) != "undefined" )
		window.setTimeout('ajaxpage("'+url+'", "'+containerid+'")', timeout);		
	else
	{
		var page_request = false;
		if ( window.XMLHttpRequest ) // if Mozilla, Safari etc	
			page_request = new XMLHttpRequest();
		else if( window.ActiveXObject ) // if IE
		{
			try 
			{
				page_request = new ActiveXObject("Msxml2.XMLHTTP");
			} 
			catch(e)
			{
				try
				{
					page_request = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(e){}
			}
		}
		else
			return false;
			
		page_request.onreadystatechange = function()
		{
			loadpage(page_request, containerid);
		}
		
		if (bustcachevar) //if bust caching of external page
			bustcacheparameter = (url.indexOf("?") != -1) ? "&" + new Date().getTime() : "?" + new Date().getTime();
		page_request.open('GET', url + bustcacheparameter, true);
		page_request.send(null);
	}
}

function loadpage(page_request, containerid)
{
	try
	{
		if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
		{
			document.getElementById(containerid).innerHTML = page_request.responseText;
			locked = false;
		}
	}
	catch(e)
	{
		locked = false;	
	}
}

function loadobjs()
{
	if ( !document.getElementById )
		return
	for ( i = 0; i < arguments.length; i++ )
	{
		var file = arguments[i]
		var fileref = ""
		if(loadedobjects.indexOf(file)==-1)
		{ //Check to see if this object has not already been added to page before proceeding
			if (file.indexOf(".js")!=-1)
			{ //If object is a js file
				fileref=document.createElement('script')
				fileref.setAttribute("type","text/javascript");
				fileref.setAttribute("src", file);
			}
			else if (file.indexOf(".css")!=-1)
			{ //If object is a css file
				fileref=document.createElement("link")
				fileref.setAttribute("rel", "stylesheet");
				fileref.setAttribute("type", "text/css");
				fileref.setAttribute("href", file);
			}
		}
		if (fileref!="")
		{
			document.getElementsByTagName("head").item(0).appendChild(fileref)
			loadedobjects += file + " "; //Remember this object as being already added to page
		}
	}
}

function calendar_clear(cal)
{
	if(confirm('Do you want to clear this date?'))
	{
		document.getElementById(cal).value = "";
	}
}

function initToolbar()
{
	if( $('toolbar_div') )
	{
		self.setInterval('moveToolbarAndEditBar()', 50);
	}
}


function moveToolbarAndEditBar()
{
	var offsets = document.viewport.getScrollOffsets();
	var offset = offsets.top;
	
	if( offset > 113 )
	{
		$('toolbar_div').setStyle({position: 'fixed', padding: '0px 5px 5px 5px', backgroundColor: '#FFFFFF'});
	}
	else
	{
		$('toolbar_div').setStyle({position: 'static', padding: '10px 5px 0px 0px', backgroundColor: ''});
	}
}

function TryOld()
{
	var value;
	
	for ( var i = 0, length = arguments.length; i < length; i++ )
	{
		var func = arguments[i];

		try
		{
			value = func();
			break;
		}
		catch (e) { }
	}
	return value;
}
