/* 
* GLOBAL FUNCTIONS are shared by all pages of the CMS  
* 
*/


//(function(){ //using the self invoking anonymous function prevents collisions with other users' code - not 100% 

if(typeof Object.create !== 'function'){ //work around for creating objects laymbda
	Object.create = function(o){
		function F(){}
		F.prototype = o;
		return new F();
	}
}


var cms = {}; //Object(); namespace

//})();
cms.ajax = (window.XMLHttpRequest || window.ActiveXObject)? true:false;
cms.loadObject = null; //default is running on all DOM content
cms.prefix = 'cms_'; //this is the prefix used on classes and ids specific to the system. Can be left blank if not required

//configuration variables
cms.conf = {}; //configuration namespace
cms.conf.loadContainer = 'container'; //default container id for loading ajax content
cms.conf.centralImages = 'images/shared'; //shared/imagescms.conf.dragTop = 0; //how close the draggable layer can go to the top of the page (in pixels).
cms.conf.dragTop = 52; //impose a restriction to prevent drag layer from going beyond the top bar

cms.component = {}; //Object(); namespace reserved for the central component scripts == NOT == to be used by component developers 
cms.components = {}; //Object(); namespace for any custom components to be used by component developers

cms.include = function(url){
    var tag = document.createElement("script");
    tag.type="text/javascript";
    tag.src = url;
    document.body.appendChild(tag);
}

cms.loading = '<span class="loading"><img src="'+cms.conf.centralImages+'/loading-sml-blue.gif" /> Loading....</span>'

function is_array(input){  
	return typeof(input)=='object'&&(input instanceof Array);  
}

cms.dragLayer = null;
cms.scrollSize = Array();

cms.typeOf = function(object) { //see http://juhukinners.com/tag/instanceof/ - better way to detecting type of value
    return Object.prototype.toString.call(object).slice(8, -1);
}

cms.$ = function() { //same principle as the prototype function as a shortcut to finding the element on the page.  
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

cms.escapeHtml = function(unsafe) {  
	return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
} 

/**
*   Add an event listener to an object
*   @param      object
*   @param      evt  / event
*   @param      func            function
*   @param      capture
*   @return     boolean
*/

cms.addEvent = function(object, evt, func, capture){
	if(typeof func != 'function'){
		return false;
	}
	if(object.addEventListener){
		object.addEventListener(evt, func, capture);
		return true;
	}else if(object.attachEvent){
		object.attachEvent('on'+evt, func);
		return true;
	}
	return false;
}

/**
*   Removes an event listener
*   @param      object
*   @param      evt         event
*   @param      func            function
*   @param      capture
*   @return     boolean
*/

cms.removeEvent = function(object, evt, func, capture){
	if(typeof func != 'function'){
		return false;
	}
	if(object.removeEventListener){
		object.removeEventListener(evt, func, capture);
		return true;
	}else if(object.detachEvent){
		object.detachEvent('on' + evt, func);
		return true;
	}
	return false;
}



/**
*   Find all elements by class name
*   @param      c = class name
*   @param      p = parent element (optional)
*   @param      t = tag name (optional)
*   @param      f = Callback function
*   @return     boolean
*/
cms.getElementsByClassName = function(c,p,t,f){

  var found = new Array();
  var re = new RegExp('\\b'+c+'\\b', 'i');
  var p = p || document;
  
  
  var list = cms.getElementsByTagName(t,p);
  if(list.length==0) list[0] = p; //no matches so maybe it's the parent element itself
  for (var i = 0; i < list.length; ++i) {
     
   if (list[i].className && list[i].className.search(re) != -1) {
	 found[found.length] = list[i];
      if (f) f(list[i]);
    }
  }
  return found;
}


/**
*   findPosX : finds the x coordinate position of a none positioned page element 
*   @param      obj = page element 
*/
cms.findPosX = function(obj){
    var curleft = 0;
	if(obj.offsetParent)
        while(1){
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}

/**
*   findPosY : finds the y coordinate position of a none positioned page element 
*   @param      obj = page element 
*/
cms.findPosY = function(obj){
    var curtop = 0;
    
	//this 'extra' var below is required as IE in only browser that seems to count the margin on the HTML element. 
	$extra = ($.browser.msie)? 0 :(($(obj).css('position')!='absolute')? parseFloat($('html').css('marginTop')) : 0); //if positioned then don't add the html margin top. But if not positioned then add the margin top

	if(obj.offsetParent)
        while(1){
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop+$extra;
}


/**
*   urlObj (constructor)
*   @param      url : the url string
*/
cms.urlObj = function(url) { // optionally pass a querystring to parse
	
	var params = {};
	var page,qs;
	var noQuestionMark = false;
	
	if(url!==null){
		if(typeof(url) != "string") return; //only continue if the URL is a string
		if(url.indexOf('?')==-1){ //no question mark found
			if(url.indexOf('=')==-1){ //if url doesn't contain '=' then must be a URL without query string
				qs = ''; 
				page=url;	
			}else{ //must be query string
				qs=url;
			}
			noQuestionMark = true;
		}else{
			qs=url.substring(url.indexOf('?')+1, url.length);
			page = url.substring(0,url.indexOf('?')+1);
		}
		//make sure the query string contains a '=' sign
		
	}else{ //assume it is the current page URL
		qs = location.search.substring(1, location.search.length);
	}
	if (qs.length == 0) return;
	
	this.qs = qs; //make public
	this.page = page; //make public
	
	qs = qs.replace(/\+/g, ' '); // covert <plus> to <space>
	var args = qs.split('&');
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		var value = (pair.length==2)? decodeURIComponent(pair[1]) : name;
		params[name] = value;
	}
	
	this.appendVars = function(name,value){ //add more to the query string
		if(qs.length==0 && noQuestionMark){
			url = page+'?'+encodeURIComponent(name)+'='+encodeURIComponent(value);
		}else{
			url = url+'&'+encodeURIComponent(name)+'='+encodeURIComponent(value);	
		}
		return url; //return the new URL;
	}
	
	this.getUrl = function(){
		return url;
	}
	
	this.get = function(name, defaultVar) {
		var value = params[name];
		return (value != null) ? value : defaultVar;
	}
	
	this.contains = function(name) {
		var value = params[name];
		return (value != null)? true : false;
	}
	
}

// rework of xGetElementsByTagName, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
cms.getElementsByTagName = function(t,p){
  if(typeof(p) === "string"){
	p = document.getElementById(p);
  }
  var list = null;
  t = t || '*';
  p = p || document;
	
  if (document.all) {
    if (t == '*') list = p.all;
    else list = p.all.tags(t);
  }else if(p.getElementsByTagName){
	  list = p.getElementsByTagName(t);
  }
  return list || new Array();
}

/* 
* function below retrieves the actual style applied to an element
* rework from http://www.oreillynet.com/pub/a/javascript/excerpt/JSDHTMLCkbk_chap5/index5.html
*/
cms.getComputedStyle = function(obj, IEStyleProp, CSSStyleProp) {
	if(obj){
		if (obj.currentStyle) {
			return obj.currentStyle[IEStyleProp];
		} else if (window.getComputedStyle) {
			if(!arguments[2]) CSSStyleProp = IEStyleProp;  
			var compStyle = window.getComputedStyle(obj, "");
			return compStyle.getPropertyValue(CSSStyleProp);
		}
	}
    return "";
}

/**
*   Get all styles acting on a page element
*   @param      obj = page element 
*   @return     getComputedStyle object on success
*/
cms.getComputedStyleFull = function(obj) {
    if (obj.currentStyle) {
        return obj;
    } else if (window.getComputedStyle) {
        var compStyle = window.getComputedStyle(obj, "");
        return compStyle;
    }
    return "";
}


//consider http://blog.motane.lu/2007/09/20/elementprototype-in-ie/

/*
*   cms.addClassName
*   Description : adds a class to the class attribute of a DOM element
*   @param      objElement = page element 
*   @param      strClass = class name to add 
*/
cms.addClassName = function(objElement, strClass){
	
   var classExists = false;
   if(objElement.className){ // if there is already a class
     var arrList = objElement.className.split(' ');
	 var strClassUpper = strClass.toUpperCase();
	 for(var i = 0; i < arrList.length; i++ ){ // find all instances and remove them
		if(arrList[i].toUpperCase()==strClassUpper){ // if class found
		   classExists = true;
		   break;
		}
	 }
	 if(!classExists){
       arrList[arrList.length] = strClass; // add the new class to end of list
       objElement.className = arrList.join(' ');
	 }
   }else{ //no existing class  
      objElement.className = strClass;
   }
}


/*
*   cms.removeClassName
*   Description : removes a class to the class attribute of a DOM element
*   @param      objElement = page element 
*   @param      strClass = class name to add 
*/
cms.removeClassName = function(objElement, strClass){

   // if there is a class
   if (objElement.className){
      var arrList = objElement.className.split(' ');
      var strClassUpper = strClass.toUpperCase();
      for ( var i = 0; i < arrList.length; i++ ){
         if( arrList[i].toUpperCase() == strClassUpper){
            arrList.splice(i, 1); // remove array item
            i--; // decrement loop counter as we have adjusted the array's contents
         }
      }
      objElement.className = arrList.join(' ');
   }
}

/*
*   cms.containsClass
*   Description : checks to see if the className attribute contains the class name being searched for
*   @param      objElement = page element 
*   @param      strClass = class name to search for 
*/
cms.containsClass = function(objElement, strClass){

   // if there is a class
   if(objElement.className){
      var arrList = objElement.className.split(' ');
      var strClassUpper = strClass.toUpperCase();
      for ( var i = 0; i < arrList.length; i++ ){
         if( arrList[i].toUpperCase() == strClassUpper){
				return true;
         }
	  }
   }
   return false;
}

cms.setStyleByClass = function(t,c,p,obj){
	var elements;
	var str;
	var v = obj;

	if(t == '*') {
		// '*' not supported by IE/Win 5.5 and below
		elements = (document.all) ? document.all : document.getElementsByTagName('*');
	}else{
		elements = document.getElementsByTagName(t);
	}
	
	for(var i = 0; i < elements.length; i++){
		var node = elements.item(i);
		for(var j = 0; j < node.attributes.length; j++){
			if(node.attributes.item(j).nodeName == 'class'){
				if(node.attributes.item(j).nodeValue.indexOf(c) != -1){
					eval('node.style.' + p + " = '" + v + "'");
					
				}
			}
		}
	}
}

/**
*   Get the opacity of a page element
*   @param      element = the Document Object
*   @param      value  = range from 0 - 100 : 100 being opaque
*/
cms.getOpacity = function(o){
	if(typeof(o) === 'object'){
		//return object.style.opacity;
		return document.all ? (RegExp("opacity=[0-9]+").test(o.style.filter) ? parseInt(RegExp("opacity=([0-9]+)").exec(o.style.filter)[1], 10) : null) : (o.style.opacity ? o.style.opacity * 100 : null);
	}else{
		return false;	
	}
}

/**
*   Set the opacity of a page element
*   @param      element = the Document Object
*   @param      value  = range from 0 - 100 : 100 being opaque
*/
cms.setOpacity = function(element,value){
	if(typeof(element) === "string"){
    	element = document.getElementById(element);
  	}
	if(value==100){
		element.style.opacity = '';
		element.style.MozOpacity = '';
		element.style.KhtmlOpacity = '';
		element.style.filter='';
	}else{
		element.style.opacity = (value / 100); 
		element.style.MozOpacity = (value / 100); 
		element.style.KhtmlOpacity = (value / 100); 
		element.style.filter = "alpha(opacity=" + value + ")"; 
	}
}

cms.fadeIn = function(element,callback) {
   	cms.setOpacity(element,1);	
	element.style.display="block";
	var timer = 0;
	for (var i=1; i<=100; i++) {   
		(function(){ //closure
			var count = i;
			setTimeout(function(){
				cms.setOpacity(element,count);
				if(count==100 && callback) callback(element); 
			}, timer * 3);
        	
	   })();
       timer++;
    }
	
}
cms.fadeOut = function(element,callback) {
    var timer = 0;
    for (var i=100; i>=1; i--) {
        (function(){ //closure
			var count = i;
			setTimeout(function(){
				cms.setOpacity(element,count);
				if(count ==1){
					if(callback){
						callback(element); //callback function
					}else{ //default action
						element.style.display="none";
						cms.setOpacity(element,100);	
					}
				}
			}, timer * 3);
        	
	   })();
	   timer++;		
    }
}



/*
*   cms.addDomLoad
*   Description : checks to see if the className attribute contains the class name being searched for
*   @param      func = function to be called  
*   @param      argument[1] = if set then add function passed to cms.loadInit stack which can be optionally called each time ajax content is loaded  
*	NOTE: 		init is run on the first page load & loadInit stack can optionally be run when content is subsequently loaded using AJAX

*/
cms.addDomLoad = function(func){
  		
	if (!document.getElementById | !document.getElementsByTagName) return;
	if (typeof cms.init != 'function'){
		cms.init=func;
	}else{
		var oldInit=cms.init;
		cms.init=function(){
			oldInit();
			func();
		}
	}
	if(arguments[1]==true){
		if (typeof cms.loadInit != 'function'){
			cms.loadInit=func;
		}else{
			var oldLoadInit=cms.loadInit;
			cms.loadInit=function(){
				oldLoadInit();
				func();
			}
		}
	}	
}

cms.addOnload = function(func) {
  if (!document.getElementById | !document.getElementsByTagName) return
	var oldonload=window.onload
	if (typeof window.onload != 'function') { window.onload=func }
	else {
		window.onload=function() { oldonload(); func() }
	}
}


/*
cms.onContentLoad is designed to run all unobtrusive scripts when a new bit of content is loaded to the page using ajax
This function sets the variable 'cms.loadedObject' which all functions within 'cms.init()' can access. This allows the functions within init() to just apply to new content instead of the whole page    
*/
cms.onContentLoad = function(element){
	if(typeof cms.loadInit == 'function'){
		if(typeof(element) === "string"){
			element = document.getElementById(element);
		}
		cms.loadObject = element || window;
		cms.loadInit();
		cms.loadObject = null; //after completed reset object to null
	}
}


/* *************************************************************************
 * Set external links in open in new window (standards compliant)
 * Makes use of "rel" attribute.
 * e.g. <a href="" title="" rel="external"></a>
 */
cms.setExtLinkTarget = function() {
	var anchors = cms.getElementsByTagName('a',cms.loadObject);
	for (var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute('href') && anchor.getAttribute('rel') == 'external') {
			anchor.target = '_blank';
		}
	}
}

/* *************************************************************************
 * Change the bg colour of all input fields when onfocus onblur (standards compliant)
 */

/**
*   change an object to an array so that array methods can be used - useful when using getElementsByTagName which returns a nodelist instead of an array
*   @param      obj = the Object to be converted to an array
*/
cms.convertToArray = function(obj) {
   if (!obj.length) {return [];} // length must be set on the object, or it is not iterable
   var a = [];
   var x = 0;
   for(var i in obj){
		a[x++] = obj[i];
   }
   return a;
};


cms.page = new function(){ 
	
	var that = this; //fix for accessing this inside private functions
	var maxScroll = null;
	var stopScroll = false;
		
	this.scrollPage = function(){ //automatically scroll the page when near the page edge
		//find out if the cursor is at the edge of the page - if so then slowly scroll the page.
		var dy1 = cms.findPosY(cms.dragLayer);
		var dx1 = cms.findPosX(cms.dragLayer);
		
		var winSize = this.windowSize();
		var scrolls = this.scrollXY();
		
		if(!maxScroll) maxScroll = cms.scrollHeight(document.body); //cms.scrollHeight(document.body);
		
		if(maxScroll){ //not supported by Opera 6 but works in other browsers
			if(winSize.height+scrolls.y>maxScroll) var stopScroll=true;
		}
		if(!stopScroll){	
			if(winSize.height>150){ //only scroll for windows larger than 150px 
				var top = winSize.height+scrolls.y;
				if((dy1+50)>top){ //move down when 50px from bottom
					//alert(scrolls[1]);
					if(document.body.scrollTop){
						var temp = document.body.scrollTop;
						document.body.scrollTop = temp+10;
					}else{
						var temp = document.documentElement.scrollTop;
						document.documentElement.scrollTop = temp+10;
					}
				}else if((dy1-50)<scrolls.y){
					//alert(dy1-50);
					if(document.body.scrollTop){
						var temp = document.body.scrollTop;
						document.body.scrollTop = temp-10;
					}else{
						var temp = document.documentElement.scrollTop;
						document.documentElement.scrollTop = temp-10;
					}
				}
			}
		}
	}
	
	this.windowSize = function(){ //find the viewable window dimensions (viewport size)
		  var myWidth = 0, myHeight = 0;
		  if(typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		  }
		  return {width:myWidth, height:myHeight};
	}
	
	this.pageSize = function(){ //find the size of the whole page (inc. the hidden bits). If the document is smaller than the viewport then it returns the viewport size
		var w=0;
		var h=0;
		var d = document;
		
		w = Math.max(
			Math.max(d.body.scrollHeight, d.documentElement.scrollHeight),
			Math.max(d.body.offsetHeight, d.documentElement.offsetHeight),
			Math.max(d.body.clientHeight, d.documentElement.clientHeight)
		);
		h = Math.max(
			Math.max(d.body.scrollWidth, d.documentElement.scrollWidth),
			Math.max(d.body.offsetWidth, d.documentElement.offsetWidth),
			Math.max(d.body.clientWidth, d.documentElement.clientWidth)
		);
		return {width:w,height:h};
	}
	
	this.scrollXY = function(){ //find the current amount the page has been scrolled
		  var scrOfX = 0, scrOfY = 0;
		  if( typeof( window.pageYOffset ) == 'number' ) {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		  }
		  return {x:scrOfX, y:scrOfY};
	}
	
	/*
	*   scrollToXY
	*   Description : scrolls the current page to the specified amounts {top:value;left:value}
	*	@class cms_tabgallery_group : the class given to a layer surrounding all the buttons and content for a tab system 
	*/
	
	this.scrollToXY = function(data){
		if(data.top){
			if(document.body.scrollTop){
				document.body.scrollTop = data.top;
			}else{
				document.body.scrollTop = data.top; //required for Google Chrome to work
				document.documentElement.scrollTop = data.top;
			}	
		}
		if(data.left){
			if(document.body.scrollLeft){
				document.body.scrollLeft = data.left;
			}else{
				document.documentElement.scrollLeft = data.left;
			}		
		
		}
		
	}
	
	this.reloadPage = function(){
		document.location.reload(true);	
	}
}



cms.formEvents = function() {
	
	var inputs = cms.convertToArray(cms.getElementsByTagName('input',cms.loadObject));
	var textareas = cms.convertToArray(cms.getElementsByTagName('textarea',cms.loadObject));
	var anchors = inputs.concat(textareas); //combine inputs and textareas 
	
	for(var i in anchors){	
		if(typeof anchors[i] == 'object' && $(anchors[i]).attr('type')!='submit' && $(anchors[i]).attr('type')!='button'){ //had to include this to avoid an exception error in Firefox
			(function(){ //closure
				var element = anchors[i];
				var prevColBG = $(element).css('background-color');  //cms.getComputedStyle(element, 'backgroundColor', 'background-color');
				var prevCol = $(element).css('color');//cms.getComputedStyle(element, 'color');
				var initVal = element.value;
				var emptyStartText = cms.containsClass(element,'empty'); //if has class empty then hide the initial text on focus
				if(prevColBG && prevCol){
					cms.addEvent(element,'focus', function (e) {
						element.style.backgroundColor="#FFFF80";
						element.style.color="#000000";
						if(emptyStartText && element.value===initVal && (element.tagName.toLowerCase()==='textarea' || (element.tagName.toLowerCase()==='input' && element.type.toLowerCase()==='text'))) element.value=''; //accessibility checkpoint 10.4 - input/textfields are prepopulated
					});
					cms.addEvent(element,'blur', function (e) {
						element.style.backgroundColor=prevColBG;
						element.style.color=prevCol;
						if(emptyStartText && element.value==='' && initVal) element.value =initVal;
					});
				}			
			})();
		}
	}
}

/**
*   load content using ajax
*   @param      url = path to the script
*   @param      targetPath  = parent layer into which to load the content
*   @param      boolean init = (optional) if 'true' runs cms.onContentLoad which runs init() on the ajax loaded content 
*/
cms.ajaxLoadContent = function(url,target,init){
	var target = target || cms.conf.loadContainer //detault container where content can be loaded
	var init = init || true;
	cms.ajaxLoad(url,target,init); //true: make sure cms.onContentLoad is run on new loaded content 
}

/**
*   load ajax - simple script that performs most ajax tasks
*   @param      string url = path to the script
*   @param      function | htmlElement | string target = (optional) if id or htmlElement then load content directly or if function then the function manipulates the response text
*   @param      boolean init = (optional) if 'true' runs cms.onContentLoad which runs init() on the ajax loaded content 
*/
cms.ajaxLoad = function(url,target,init) {
	

	$('#cms_loading').css('display','block');
	if(typeof(target) === "string"){
		target = document.getElementById(target);
	}
	
	(function(){ //closure - added this to allow multiple ajax loads to run symultaneously without any risk of 'target' changing
		var initSet = init || false;
		var http = null;
		var xmlDoc = null;
		var value = null;
		if(window.XMLHttpRequest) { // branch for native XMLHttpRequest object
			http = new XMLHttpRequest();
		} else if(window.ActiveXObject) { // branch for IE/Windows ActiveX version
			try{
				http = new ActiveXObject("Msxml2.XMLHTTP");
			}catch(e) {
				http = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		if(http) {
			//$('#cms_loading').fadeIn('fast');
			
			http.onreadystatechange = function(){
				xmlDoc = null;
				if (http.readyState == 4){
					if(http.status == 200){ // only if "OK"
						if(http.responseText=='reloadpage'){ //session timed out so reload parent page incase login is required
							document.location.reload(true);
						}else{
							if(cms.typeOf(target)==='Function'){ //if a function passed then execute callback function 
								target(http.responseText);
							}else if(target){
								target.innerHTML = http.responseText;
								if(initSet){
									cms.onContentLoad(target); //run unobrusive script to set onload events for new content
								}
							}
						}
						$('#cms_loading').fadeOut('fast');
					}else{
						//had to check for http.status to stop an exception being thrown in firefox when the clipboard was cleared - very odd behaviour
						if(http.status !==0){
							if(cms.typeOf(target)==='Function'){ //if a function passed then execute callback function 
								target(http.statusText);
							}else{
								alert("There was a problem retrieving the XML data:\n" + http.statusText);
							}
						}
					}
				}	
			}
			
			http.open("POST", url, true); //true means asynchronous
			http.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); 
			http.send("");
		}
	})();
}

cms.form = {}

/*
*   cms.form.queryString : creates a query string from form variables to submit using ajax. But won't work for multipart forms
*   @param  obj theForm = the form object
*/

cms.form.queryString =function(theForm){
	var reqStr = "";

	for(i=0; i < theForm.elements.length; i++){
		isFormObject = false;

		switch (theForm.elements[i].tagName){
			case "INPUT":

				switch (theForm.elements[i].type){
					case "text":
					case "password": /* not sure if this even works for passwords??? */
					case "hidden":
						reqStr += theForm.elements[i].name + "=" + encodeURIComponent(theForm.elements[i].value);
						isFormObject = true;
						break;
					case "checkbox":
						if(theForm.elements[i].checked){
							reqStr += theForm.elements[i].name + "=" + theForm.elements[i].value;
						}else{
							reqStr += theForm.elements[i].name + "=";
						}
						isFormObject = true;
						break;

					case "radio":
						if (theForm.elements[i].checked){
							reqStr += theForm.elements[i].name + "=" + theForm.elements[i].value;
							isFormObject = true;
						}
				}
				break;

			case "TEXTAREA":
				reqStr += theForm.elements[i].name + "=" + encodeURIComponent(theForm.elements[i].value);
				isFormObject = true;
				break;

			case "SELECT":
				var sel = theForm.elements[i];
				reqStr += sel.name + "=" + sel.options[sel.selectedIndex].value;
				isFormObject = true;
				break;
		}

		if ((isFormObject) && ((i+1)!= theForm.elements.length)){
			reqStr += "&";
		}
	}
	return reqStr;
}


/**
*   makeIframe : simple script to generate an hidden iframe. Couldn't use the DOM method as not all browsers support it
*/
cms.makeIframe = function() { 
	if(!document.getElementById('hiddenfr')){
		var divTag = document.createElement('div');
		divTag.innerHTML = '<iframe id="hiddenfr" frameBorder="0" style="display:none;"  marginHeight="0" marginWidth="0"  name="hiddeniframe" scrolling="no" ></iframe>';
		//var e = divTag.childNodes; 
		document.body.appendChild(divTag);
	}
} 
cms.addDomLoad(cms.makeIframe);

//excellent tool for creating DOM code http://www.smelzo.it/html2js/

// DF1.1 :: domFunction 
// *****************************************************
// DOM scripting by brothercake -- http://www.brothercake.com/
// GNU Lesser General Public License -- http://www.gnu.org/licenses/lgpl.html
//******************************************************

/*//DOM-ready watcher
cms.domFunction1 = function(f, a){

	var n = 0;
	var test = "hello";
	var t = setInterval(function(){
		var c = true;
		n++;
		if(typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null)){
			c = false;
			if(typeof a == 'object'){
				for(var i in a){
					if(
						(a[i] == 'id' && document.getElementById(i) == null)
						||
						(a[i] == 'tag' && document.getElementsByTagName(i).length < 1)
					){ 
						c = true; 
						break; 
					}
				}
			}
			if(!c) { 
				//alert('test')
				f();
				clearInterval(t);
			}
		}
		if(n >= 60){
			//clear the timer
			clearInterval(t);
		}
	}, 250);
};*/

$(document).ready(function(){ cms.init(); });

cms.checkpass = function(){
	obj1 = MM_findObj("password");
	obj2 = MM_findObj("repassword");
	if(obj1.value != obj2.value ){
		obj2.value = "";
		obj1.value = "";
		alert("Sorry the password you entered was not the same in both boxes please try again");
	}
}

//cmsEntryContentInner
cms.findContainer = function(target,name){
	if (document.all) {
    do 
      //if (target.className == 'draglayer')
      if(target.className.indexOf(name)!=-1)
	  	return target;
    while ((target = target.parentElement));
    return null;
  }
  else if (document.getElementById) {
    do
      if(target.className.indexOf(name)!=-1)	
	  	return target;
    while ((target = target.parentNode));
    return null;
  }
}

/*
* onLoad events
*/
cms.addDomLoad(cms.setExtLinkTarget,true);
cms.addDomLoad(cms.formEvents,true);

/**
*   cms.setScrollReload : this function to save the current scroll before reloading the page. It populates the $_SESSION['scroll']['y'] variable 
*/
cms.setScrollReload = function(){

	var curScroll = cms.page.scrollXY();
	var path = document.location.href
	var urlObj = new cms.urlObj(document.location.href);
	urlObj.appendVars('cmsScrollY',curScroll.y);
	urlObj.appendVars('cmsScrollX',curScroll.x);
	urlObj.appendVars('cmsSetScrollOnly',1);
	cms.ajaxLoadContent(urlObj.getUrl(),function(){
		document.location.href = path;											 
	});
	return;
}


/**
*   cms.switchViewScroll : this function saves the current scroll position before reloading the page. It populates the $_SESSION['scroll']['y'] variable 
*/
$('document').ready(function(){
	
	//find the position of all entries
	$('#cms_toggle_view a').click(function(){
		
		var curScroll = cms.page.scrollXY();
		var pos = 1;
		var storedDiff, diff, storedPos, past;
		if(curScroll.y>100){
			var elements = cms.getElementsByClassName('cmsEntryContent',cms.$('cmsEntryContainer')); //interate through all divs with class componentPanels
			for(var i in elements){	
				var element = elements[i];
				y = cms.findPosY(element);
				if((curScroll.y+cms.conf.dragTop)<y){
					diff = y-(curScroll.y+cms.conf.dragTop);
					direction = '-';
				}else{
					diff = (curScroll.y+cms.conf.dragTop)-y;	
					direction = '+';
				}
				
				if(typeof(storedDiff)=='undefined' || diff<storedDiff){
				   storedPos = pos;
				   storedDiff = diff;
				   storedDir = direction;
				}
				pos++;   
			}
			//alert(storedPos+' : '+storedDir+' '+storedDiff);
			
			var path = document.location.href
			var urlObj = new cms.urlObj(document.location.href);
			urlObj.appendVars('cmsStoredPos',storedPos);
			urlObj.appendVars('cmsStoredOffset',storedDir+storedDiff);
			urlObj.appendVars('cmsSetScrollOnly',1);
			cms.ajaxLoadContent(urlObj.getUrl(),function(data){										 
				document.location.href = $('#cms_toggle_view a').attr('href') ;											 
			});
			return false;
		}
	});
});


cms.loadInBackground = function(){
	
	var elements = cms.getElementsByClassName(cms.prefix+'load_bg',cms.loadObject); //interate through all divs with class componentPanels
	
	
	var iframe = cms.$('hiddenfr');
	iframe.onload=null;

	for(var i in elements){	
	
		var cmsloadbg = 'cmsloadbg=1';
		
		if(elements[i].tagName=='A'){ //use an AJAX call
			(function(){ //closure 
				var el = elements[i];
				var page = el.href;
				//alert(el.href);
				page += (page.indexOf('?')==-1)? '?'+cmsloadbg : '&'+cmsloadbg;
				
				el.onclick = function(){	
					
					cms.ajaxLoadContent(page,function(text){
						if(text){							
							if($.trim(text)=='cmsreload'){ //reload the current page to display the changes
								cms.setScrollReload();
								//location.href=document.location.href;
								//location.href  = cms.appendScrollToLink(document.location.href);
							}else{
								var entryArea = cms.findContainer(el,'cmsEntryContentInner');  //cmsEntryContentInner
								entryArea.innerHTML = text;
								cms.onContentLoad(entryArea);
							}
						}
					});
					return false;
				};			
			})();
		}else if(elements[i].tagName=='FORM'){ //use a hidden iFrame to load the content
 			
			(function(){ //closure 
				
				var el = elements[i];
				el.target = "hiddeniframe";
				var action = el.action;
				cmsloadbg += '&cmsloadiframe=1'; //need to know if it's loaded via iframe so can auto create <body></body> tag to stop IE stripping out the FORM tag  
				el.action += (action.indexOf('?')==-1)? '?'+cmsloadbg : '&'+cmsloadbg;
				
				cms.addEvent(el,'submit', function (e) {	
					
					cms.addEvent(iframe,'load', function (e) {						
					//iframe.onload=function(){									
							
							var text = iframe.contentWindow.document.body.innerHTML;	
							if(text=='cmsreload'){ //reload the current page to display the changes
								//console.log('hello');
								cms.setScrollReload();
								//location.href=document.location.href;
								//location.href  = cms.appendScrollToLink(document.location.href);
								
							}else{
								var entryArea = cms.findContainer(el,'cmsEntryContentInner'); 
	/*							var newdiv = document.createElement("div");
								newdiv.innerHTML = text;
								var container = entryArea;
								container.innerHTML = '';
								container.appendChild(newdiv);*/
								entryArea.innerHTML = text;	
								cms.onContentLoad(entryArea); //entryArea
							}
							//this.removeEventListener('load',arguments.callee,false);
							cms.removeEvent(iframe,'load',arguments.callee);
							//e.currentTarget.removeEventListener('load', this, false); 
							//http://www.howtocreate.co.uk/tutorials/javascript/domevents
							
					//}
					});
					return true; //stop the link from firing
				});
			})();		  
		}
	}	
}
cms.addDomLoad(cms.loadInBackground,true);

/**
*   cms.appendScrollToLink : this function gets the current page scroll and appends it to the link 
*   @example class="cms_scroll"   this can be used to reposition the page on reload. Used by the compomponent panel 
*/
cms.appendScrollToLinkSet = function(){
		
	var elements = cms.getElementsByClassName(cms.prefix+'scroll',cms.loadObject); //interate through all divs with class componentPanels
	for(var i in elements){	
		(function(){ //closure 
			var el = elements[i];
			//cms.addEvent(el,'click', function (e) {	
			$(el).click(function(){
				cms.appendScrollToLink(el);
				//console.log($(el).attr('href'));
				return true; 
			});			
		})();
	}	
}
cms.addDomLoad(cms.appendScrollToLinkSet,true);

cms.appendScrollToLink = function(obj){
	
	var curScroll = cms.page.scrollXY();
	var theUrl = (cms.typeOf(obj)==='String')? obj : obj.href; 
	//console.log(theUrl)
	var urlObj = new cms.urlObj(theUrl);
	urlObj.appendVars('cmsScrollY',curScroll.y);
	urlObj.appendVars('cmsScrollX',curScroll.x);
	var href = urlObj.getUrl();
	if(cms.typeOf(obj)==='String'){
		return href;
	}else{ //is an object
		obj.href=urlObj.getUrl();
		return;
	}
}



//http://www.json.org/json2.js - size reduced using http://fmarcia.info/jsmin/test.html
//JSON.parse(text, reviver) - This method parses a JSON text to produce an object or array.
//JSON.stringify(value, replacer, space) - used to convert to string ready for sending as a get
if(!this.JSON){this.JSON={};}(function(){function f(n){return n<10?'0'+n:n;}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}if(typeof rep==='function'){value=rep.call(holder,key,value);}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v;}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}return str('',{'':value});};}if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}return reviver.call(holder,key,value);}cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}throw new SyntaxError('JSON.parse');};}}());


function imgPopup(mypage,myname,w,h,pos,infocus){
	sw = window.screen.width;
	sh = window.screen.height;

	w = w+20; //allow for image border
	h = h+20;
	maxwidth = sw - 40;
	maxheight = sh - 30;
	scroller = 'no';
	if(w > maxwidth){
		w = maxwidth;
		scroller = 'yes';
	}	
	if(h > maxheight){
		h = maxheight;
		scroller = 'yes';
	}
	
	if(pos=='random'){
	LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;
	TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
	if(pos=='center'){
	LeftPosition=(screen.width)?(screen.width-w)/2:100;
	TopPosition=(screen.height)?(screen.height-h)/2:100;}
	else if((pos!='center' && pos!='random') || pos==null){LeftPosition=100;TopPosition=100;}settings='width='+ w + ',height='+ h + ',top=' + TopPosition + ',left=' + LeftPosition + ',location=no,directories=no,menubar=no,toolbar=no,status=yes,scrollbars='+scroller+',resizable=no,dependent=no';
	lgflPopupWindow=window.open('',myname,settings);
	if(infocus=='front'){lgflPopupWindow.focus();lgflPopupWindow.location=mypage;}
}


/*
------------------------------- OLD FUNCTIONS BELOW ------------------------------------------------------
*/

//think all the cars below can be deleted
//var req;
//var contentPath;
//var conf = new Array();
//var targetPath="";
//conf['target'] = document.getElementById('content'); //default layer to load content into

/* 
LEAGACY FUNCTIONS - ALL NEED DELETING
*/

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}


function MM_changeProp(objName,x,theProp,theValue) { //v6.0
  var obj = MM_findObj(objName);
  if (obj && (theProp.indexOf("style.")==-1 || obj.style)){
    if (theValue == true || theValue == false)
      eval("obj."+theProp+"="+theValue);
    else eval("obj."+theProp+"='"+theValue+"'");
  }
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}



var lgflPopupWindow=null;
function lgflPopup(mypage,myname,w,h,pos,infocus,scroller){
	if(!scroller) scroller = 'yes';
	if(pos=='random'){
	LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;
	TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
	if(pos=='center'){
	LeftPosition=(screen.width)?(screen.width-w)/2:100;
	TopPosition=(screen.height)?(screen.height-h)/2:100;}
	else if((pos!='center' && pos!='random') || pos==null){LeftPosition=100;TopPosition=100;}settings='width='+ w + ',height='+ h + ',top=' + TopPosition + ',left=' + LeftPosition + ',location=no,directories=no,menubar=no,toolbar=no,status=yes,scrollbars='+scroller+',resizable=no,dependent=no';
	lgflPopupWindow=window.open('',myname,settings);
	if(infocus=='front'){lgflPopupWindow.focus();lgflPopupWindow.location=mypage;}	
	return false;
}

function cms_addOnloadEvents(func) {
  if (!document.getElementById | !document.getElementsByTagName) return
	var oldonload=window.onload
	if (typeof window.onload != 'function') { window.onload=func }
	else {
		window.onload=function() { oldonload(); func() }
	}
}



