if (typeof(SolidCMS) == "undefined") var SolidCMS = {};
if (typeof(SolidCMS.Utilities) == "undefined") SolidCMS.Utilities = {};



function loadScriptComplete() {

	var result = true;

	var scripts = YAHOO.solidcms.utilities.loadedScripts;
	if (scripts) {
		if (scripts.length > 0) {
			for (var i=(scripts.length-1); i>=0; i--) {
				if (scripts.loaded == false) {
					result = false;
					break;
				}
			}
		}
	}
	return result;
}

//Check if the specified script/style is loaded
function loadIndexOf(arr, id) {
	var result = false;
	if (arr) {
		if (arr.length > 0) {
			for (var i=(arr.length-1); i>=0; i--) {
				if (arr[i].id == id) {
					result = arr[i];
					break;
				}
			}
		}
	}
return result;
}

//Dynamically loads the specified javascript file ensuring it doesn't get loaded more than once
function loadScript(url) {
	var loaded = false;
	if (YAHOO.solidcms.utilities.loadedScripts) {
		var script = loadIndexOf(YAHOO.solidcms.utilities.loadedScripts, url);
		if (script) { loaded = script.loaded; }
	} else {
		YAHOO.solidcms.utilities.loadedScripts = new Array();
	}

	if (!loaded) {
		var e = document.createElement("script");
		e.id = url;
		e.src = YAHOO.site.root + url;
		e.type = "text/javascript";
		document.getElementsByTagName("head")[0].appendChild(e);
		YAHOO.solidcms.utilities.loadedScripts.push({id: url, loaded: false});

		e.onload = function() {
							var script = loadIndexOf(YAHOO.solidcms.utilities.loadedScripts, this.id);
							if (script) { script.loaded = true; }
						}
	}
}
//Dynamically loads the specified CSS file ensuring it doesn't get loaded more than once
function loadCss(url) {
	var loaded = false;
	if (YAHOO.solidcms.utilities.loadedStyles) {
		var style = loadIndexOf(YAHOO.solidcms.utilities.loadedStyles, url);
		if (style) { loaded = style.loaded; }
	} else {
		YAHOO.solidcms.utilities.loadedStyles = new Array();
	}

	if (!loaded) {
		var e = document.createElement("link");
		e.id = url;
		e.rel = 'stylesheet';
		e.href = YAHOO.site.root + url;
		e.type = "text/css";
		document.getElementsByTagName("head")[0].appendChild(e);

		YAHOO.solidcms.utilities.loadedStyles.push({id: url, loaded: false});

		e.onload = function() {
							var style = loadIndexOf(YAHOO.solidcms.utilities.loadedStyles, this.id);
							if (style) { style.loaded = true; }
						}
	}
}

//Add the ".indexOf" method to the Array object if JS<1.5
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(val, fromIndex) {
		if (typeof(fromIndex) != 'number') fromIndex = 0;
		for (var index = fromIndex,len = this.length; index < len; index++)
			if (this[index] == val) return index;
		return -1;
	}
}

//Writes a cookie to the browser
/// @param name [string] the cookie name.
/// @param value [string] the cookie value.
/// @param domain [string, optional] the cookie domain.
/// @param path [string, optional] the cookie path.
/// @param exp_days [number, optional] number of days of cookie validity.
function writeCookie(name, value, domain, path, exp_days) {
	value = escape(value);
	var ck = name + "=" + value, exp;
	if (domain)
		ck += ";domain=" + domain;
	if (path)
		ck += ";path=" + path;
	if (exp_days) {
		exp = new Date();
		exp.setTime(exp_days * 86400000 + exp.getTime());
		ck += ";expires=" + exp.toGMTString();
	}
	document.cookie = ck;
}

function getCookie(name) {
	var pattern = name + "=";
	var tokenPos = 0;
	while (tokenPos < document.cookie.length) {
		var valuePos = tokenPos + pattern.length;
		if (document.cookie.substring(tokenPos, valuePos) == pattern) {
			var endValuePos = document.cookie.indexOf(";", valuePos);
			if (endValuePos == -1) { // Last cookie
				endValuePos = document.cookie.length;
			}
			return unescape(document.cookie.substring(valuePos, endValuePos));
		}
		tokenPos=document.cookie.indexOf(" ",tokenPos)+1;
		if (tokenPos == 0) { // No more tokens
			break;
		}
	}
	return null;
}

//Check the JSON response for errors
function jsonValidate(success, response) {
	var result = false;
	
	if (!success) {
		alert('There was an error while communicating with the server. Please try again later.');
	} else {
		
		//Process the JSON response
		var json = null;
		try {
			json = Ext.util.JSON.decode(response.responseText);
		} catch (SyntaxError) {
			json = null;
		}
		
		if (json == null) {
			alert('Invalid response received from the server');
		} else {
			var hasSuccess = (json.success || false);
			if (hasSuccess == false) {
				alert(json.error);
			} else {
				return json;
			}
		}
	}
	
return result;
}
function jsonValidateForm(action) {
	switch (action.failureType) {
	case Ext.form.Action.CLIENT_INVALID:
	  alert('Please check your form entries are correct and try again.');
	  break;
	case Ext.form.Action.CONNECT_FAILURE:
	  alert('Error while connecting to server - please check your connection.');
	  break;
	case Ext.form.Action.LOAD_FAILURE:
	case Ext.form.Action.SERVER_INVALID:
		  if (action.result) {
				if (action.result.login) {
					//Show a login prompt - allows the user to login and continue without losing any work

					//Load the login script
					var e = document.createElement("script");
					e.id = item.url;
					e.src = YAHOO.site.root + 'admin/js/login.js';
					e.type = "text/javascript";
					
					//Watch for when it's loaded
					e.onload = this.onLoginLoaded;
					
					//Add it to the document
					document.getElementsByTagName("head")[0].appendChild(e);							
					
				} else if (action.result.error) {
					alert(action.result.error);
				} else {
					alert('The server returned an error. Please try again.');
				}
		  } else {
				alert('The server returned an error. Please try again.');
		  }
	  break;
	default:
		return true;
	}

return false;
}
function onLoginLoaded() {
	//Show the login dialog
	LoginDialog.init();
}

//Parse a URI into an accessible format
function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};
parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};


//Check if the 'error' tag exists in the XML tree
function xmlErrors(o) {
	if (!o.responseXML) {
		alert('Invalid response [' + o.responseText + ']');
		return false;
	} else {
		var errors = o.responseXML.getElementsByTagName('error');
		for (var i=0; i<errors.length; i++) {
			alert(errors.item(i).firstChild.nodeValue);
		}

		if (errors.length > 0) {
			return true;
		} else {
			return false;
		}
	}
}

//Fetch the first child element for the passed node
function getFirstChildElement(parentNode) {
	if (parentNode) {
		var node = parentNode.firstChild;
		while(node && node.nodeType != 1){
			node = node.nextSibling;
		}
		return node;
	} else {
		return null;
	}
}

function getNextSiblingElement(startNode) {
	var node = startNode.nextSibling;
	while(node && node.nodeType != 1){
		node = node.nextSibling;
	}
	return node;
}

function getNodeValue(node) {
	if (node) {
		if (node.firstChild) {
			return node.firstChild.nodeValue;
		}
	}
return null;
}

function findParent(node, idPrefix, exactMatch) {
	if (node) {
		if (!exactMatch) { exactMatch = false; }

		var idPrefixLength = idPrefix.length;
		var current = node;
		while (current) {
			if (current.id) {
				if (exactMatch ? (current.id == idPrefix) : (current.id.substr(0, idPrefixLength) == idPrefix)) {
					return current;
				}
			}
			current = current.parentNode;
		}
	}
return null;
}

if (typeof YAHOO != "undefined") {
	YAHOO.namespace('solidcms.utilities');
}

SolidCMS.Utilities.test = function() {
	return {
		isEmpty: function(v) {
			var varType = typeof(v);
			switch (varType) {
			case 'object':
					for(var i in v) { return false; }
					return true;
				break;
			case 'string':
				return (v == '' ? true : false);
				break;
			case 'array':
				return (v.length <= 0 ? true : false);
				break;
			}
			
		return true;
		}
	}
}();


SolidCMS.Utilities.format = function() {
	return {
		htmlEncode : function(value){
			 return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
		},
		htmlDecode: function(value) {
			return !value ? value : String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
		},
		
		rangeToString: function(v) {
			if (typeof(v) == 'object') {
				var display = [];
				for(var i=0; i<v.length; i++) {
					if (typeof(v[i]) == 'object') {
						if (v[i].length == 2) {
							display.push(v[i][0] + '-' + v[i][1]);
						} else {
							display.push(v[i][0]);
						}
					} else {
						display.push(v[i]);
					}
				}
				
				//Text sort
				display.sort();
				
				return display.join(',');
			} else {
				return '';
			}
		},
		
		stringToRange: function(v) {
			var result = [];
			if (v != '') {
				var sections = v.split(',');
				for(var i=0; i<sections.length; i++) {
					var range = sections[i].split('-');
					if (range.length == 1) {
						var item = Number(range[0]);
						if (isNaN(item)) {
							return false;
						} else {
							result.push(item);
						}
					} else if (range.length >= 2) {
						var from = Number(range[0]), to = Number(range[1]);
						if (isNaN(from) || isNaN(to)) {
							return false;
						} else if (from > to) {
							return false;
						} else {
							result.push([from, to]);
						}
					}
				}
			}
			
		return result;
		}
		
	};
}();


//URL handling
SolidCMS.Utilities.url = function() {
	return {
		getParameters: function(url) {
			var params = url  || window.location.toString();
			var result = {};
			
			var startPos = params.indexOf('?');
			if (startPos >= 0) {
				params = params.substr(startPos+1);

				//Split the parameter list into key/value pairs
				var list = [];
				if (params.indexOf('&') == -1) {
					list = [params];
				} else {
					list = params.split('&');
				}
				
				//Put the pairs on an object
				for (var i=(list.length-1); i>=0; i--) {
					var equalPos = list[i].indexOf('=');
					if (equalPos >= 0) {
						result[ list[i].substr(0, equalPos) ] = list[i].substr(equalPos+1);
					}
				}
				
			}
			
		return result;
		}
	};
}();



//Data handling
SolidCMS.Utilities.data = function() {
	return {
		jsonResponse: function(success, response, showAlert) {
			var result = false;
			showAlert = (typeof(showAlert) == "undefined" ? true : showAlert);
			
			if (!success) {
				alert('There was an error while communicating with the server. Please try again later.');				
			} else {
				
				//Process the JSON response
				var json = null;
				try {
					json = Ext.util.JSON.decode(response.responseText);
				} catch (SyntaxError) {
					json = null;
				}

				if (json == null) {
					if (showAlert)
						alert('Invalid response received from the server');
				} else {
					var hasSuccess = (json.success || false);
					if (hasSuccess == false) {
						if (json.login) {
							this.loginLoad();
						} else if (json.error) {						
							if (showAlert)
								alert(json.error);
						} else {
							if (showAlert)
								alert('There was an error while communicating with the server. Please try again.');
						}
					} else {
						return json;
					}
				}
			}
	
		return result;
		},
		
		formResponse: function(action) {
			switch (action.failureType) {
			case Ext.form.Action.CLIENT_INVALID:
			  alert('Please check your form entries are correct and try again.');
			  break;
			case Ext.form.Action.CONNECT_FAILURE:
				switch (action.response.status) {
				case 401: //Unauthorised
					//Show a login prompt - allows the user to login and continue without losing any work
					this.loginLoad();						 
					break;
				default:
				  alert('Error while connecting to server - please check your connection.');
				  break;
				}
			  break;
			case Ext.form.Action.LOAD_FAILURE:
			case Ext.form.Action.SERVER_INVALID:
			default:
				if (action.result) {
					if (typeof(action.result.success) != "undefined") {
						if (action.result.success == true) {
							return true;
						} else {
							if (action.result.login) {
							  //Show a login prompt - allows the user to login and continue without losing any work
								this.loginLoad();						 
							} else if (action.result.error) {
								alert(action.result.error);
							} else {
								alert('The server returned an unknown error. Please try again.');
							}
						}
					} else {
						alert('Unknown response received from the server.');
					}
				} else {
					 alert('The server returned an error. Please try again.');
				}
			  break;
			}
		
		return false;
		},
		
		onLoadException: function(a, conn, response) {
			switch (response.status){
			case 401: //Authorisation required
				//Load the login prompt
				SolidCMS.Utilities.data.loginLoad();
				break;
			case 200:
				//Check for generic error response
				var json = Ext.util.JSON.decode(response.responseText);
				if (typeof(json) == "undefined") {
					alert('Invalid response from the server');
				} else if (typeof(json.success) == "undefined") {
					alert('Invalid response status from the server');
				} else if (json.success == false) {
					if (typeof(json.error) == "undefined") {
						alert('Error while fetching data list from the server');
					} else {
						alert(json.error);
					}
				} else {
					//Data appears ok
					return true;
				}				
				break;
			default:
				alert('Communications error while fetching data. Please check your connection and try again. (Error #' + response.status + ')');
				break;
			}
		return false;
		},
		
		loginLoad: function() {
			//Load the login script
			var e = document.createElement("script");
			e.id = 'login_js';
			e.src = SolidCMS.site.root + 'admin/js/login.js';
			e.type = "text/javascript";
			
			//Watch for when it's loaded
			e.onload = SolidCMS.Utilities.data.onLoginLoaded;
			
			//Add it to the document
			document.getElementsByTagName("head")[0].appendChild(e);							
		},
		onLoginLoaded: function() {
			//Show the login dialog
			if (LoginDialog.init() == false) {
				alert('Cannot display the login dialog - you must log out and back in again.');
			}
		}
	};
}();
