/*
    http://www.abisvmm.nl
    2008-09-18

    Public Domain.

    This file creates a global SYNTEC object containing a complete syntec
	subset of javascript functions

    You are free to copy, modify, or redistribute.
*/

/*global ActiveXObject, SYNTEC */ 

if (!this.SYNTEC) {
    SYNTEC = {};
}
(function () {

	//Private
	var CONTROLLIST = [];
	
	//Test for version
	if (typeof SYNTEC.version !== 'string') {
		SYNTEC.version = '11.0001';
	}

	//Extension methods
    if (typeof String.prototype.trim !== 'function') {
		String.prototype.trim = function () {
			return this.replace(
				/^\s*(\S*(\s+\S+)*)\s*$/, "$1"); 
		};
	}
	
	//Test for onunload
	if (typeof window.onunload !== 'function') {
		window.onunload = function () {
			SYNTEC.gc.collect();
		};
	}

	//Test for onresize
	if (typeof window.onresize !== 'function') {
		window.onresize = function () {
			SYNTEC.controls.resize();
		};
	}

	//Test for xmlHttpRequest
	if (!window.XMLHttpRequest) {
		window.XMLHttpRequest = function () { 
			return new ActiveXObject("Microsoft.XMLHTTP"); 
		};
	}

	//Test for config object
	if (typeof SYNTEC.config !== 'object') {
		SYNTEC.config = {
			sessionId : '',
			skin : '',
			relativeRoot : '',
			set : function (configObject) {
				
				configObject = JSON.parse(configObject);
				var i, k, l, map = ['sessionId', 'skin', 'relativeRoot'];
				if (typeof configObject === 'object') {
					l = map.length;
					for (i = 0; i < l; i++) {
						k = map[i];
						if (typeof configObject[k] === 'undefined') {
							throw new Error('There was no key "' + k + '" in the configObject');
						}
						SYNTEC.config[k] = configObject[k];						
					}
				}
			}
		};
	}

	//Test GC
	if (typeof SYNTEC.gc !== 'object') {
		SYNTEC.gc = {
			collect : function () {
				var d, i, c = CONTROLLIST.length;
				for (i = 0; i < c; i++) {
					d = CONTROLLIST[i];
					if (typeof d.dispose === 'function') {
						d.dispose();
					}
				}
			}
		};
	}
	
	//Helper namespace
	if (typeof SYNTEC.helpers !== 'object') {
		SYNTEC.helpers = {

			getWindowSize : function () {
				var result = { 
					width : 0, 
					height : 0 
				};
				if (self.innerWidth) {
					result.width = self.innerWidth;
					result.height = self.innerHeight;
				}
				else if (document.documentElement && document.documentElement.clientWidth) {
					result.width = document.documentElement.clientWidth;
					result.height = document.documentElement.clientHeight;
				}
				else if (document.body) {
					result.width = document.body.clientWidth;
					result.height = document.body.clientHeight;
				}
				if (result.width < 0) { 
					result.width = 0; 
				}
				if (result.height < 0) { 
					result.height = 0; 
				}
				return result;
			},
			getScrollXY :  function () {
				var scrOfX = 0, 
					scrOfY = 0;
					
				if (typeof window.pageYOffset === 'number') {
					scrOfY = window.pageYOffset;
					scrOfX = window.pageXOffset;
				} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
					scrOfY = document.body.scrollTop;
					scrOfX = document.body.scrollLeft;
				} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
					scrOfY = document.documentElement.scrollTop;
					scrOfX = document.documentElement.scrollLeft;
				}
				return {
					x : scrOfX, 
					y : scrOfY 
				};
			},
			getCookie : function (name) {
				var nameEQ = name + "=";
				var ca = document.cookie.split(';');
				var caLength = ca.length;
				for (var i = 0; i < caLength ;i++) {
					var c = ca[i];
					while (c.charAt(0) === ' ') {
						c = c.substring(1, c.length);
					}
					if (c.indexOf(nameEQ) === 0) {
						return c.substring(nameEQ.length, c.length);
					}
				}
				return null;
			},
			clearCookies : function () {
				var ca = document.cookie.split(';');
				var caLength = ca.length;
				for (var i = 0; i < caLength ;i++) {
					var c = ca[i];
					var parts = c.split('=');
					if (parts[0].toUpperCase() !== 'PHPSESSID') {
						SYNTEC.helpers.deleteCookie(parts[0]);
					}
				}
			},
			saveCookie : function (name, value, days) {
				var expires = "";
				if (days) {
					var date = new Date();
					date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
					expires = "; expires=" + date.toGMTString();
				}
				document.cookie = name + "=" + value + expires + "; path=/";
			},
			deleteCookie : function (name) 
			{
				SYNTEC.helpers.saveCookie(name, "", -1);
			},
			translate : function (key) 
			{
				if (SYNTEC.config.translations[key]) {
					return SYNTEC.config.translations[key];
				}
				return key;
			},
			toggleTab : function (currentTab, tabs, enableCss, disableCss) {
				var i, l, tabHeaderName, tabHeader, tabContainerName, tabContainer;
				l = tabs.length;
				for (i = 0; i < l; i++) {
					tabHeaderName = 'tabHeader_' + tabs[i];
					tabContainerName = 'tabContainer_' + tabs[i];
					tabHeader = document.getElementById(tabHeaderName);
					tabContainer = document.getElementById(tabContainerName);
					if (tabs[i] === currentTab)
					{
						if (tabHeader) {
							tabHeader.className = 'selected';
						}
						if (tabContainer) {
							tabContainer.className = enableCss;
						}
					}
					else
					{
						if (tabHeader) {
							tabHeader.className = 'notselected';
						}
						if (tabContainer) {
							tabContainer.className = disableCss;
						}
					}
				}
			}
		};
	}

	//Dom namespace
	if (typeof SYNTEC.dom !== 'object') {
		SYNTEC.dom = {
			//walkTheDOM
			walkTheDOM : function (node, func) {
		        func(node); 
        		node = node.firstChild; 
				while (node) { 
					SYNTEC.dom.walkTheDOM(node, func); 
					node = node.nextSibling; 
				} 
			}, 
			//purgeEventHandlers
			purgeEventHandlers : function (node) {
				SYNTEC.dom.walkTheDOM(node, function (e) {
					for (var n in e) {            
						if (typeof e[n] === 
								'function') {
							e[n] = null;
						}
					}
				});
			},
			//getElementsByClassName
			getElementsByClassName : function (className) { 
				var results = []; 
				SYNTEC.dom.walkTheDOM(document.body, function (node) { 
					var a, c = node.className, i; 
					if (c) { 
						a = c.split(' '); 
						for (i = 0; i < a.length; i += 1) { 
							if (a[i] === className) { 
								results.push(node); 
								break; 
							} 
						} 
					} 
				}); 
				return results; 
			},
			//createElement
			createElement : function (elementType, id, className, innerHTML, parent) {
				var oElement = document.createElement(elementType);
				if (id) {
					oElement.id = id;
				}
				if (className) {
					oElement.className = className;
				}
				if (innerHTML) { 
					oElement.innerHTML = innerHTML; 
				}
				if (parent) {
					parent.appendChild(oElement);
				}
				return oElement;
			},
			//createInputElement
			createInputElement : function (inputType, id, className, value, parent) {
				var oElement = SYNTEC.dom.createElement('input', id, className);
				oElement.setAttribute('type', inputType);
				if (value) { 
					oElement.value = value; 
				}
				if (parent) {
					parent.appendChild(oElement);
				}
				return oElement;				
			},
			createTable : function (id, cellSpacing, cellPadding, border, className) {
				var tmpTable = document.createElement('table'),
				 	tmpTbody = document.createElement('tbody'),
					result = { table : tmpTable, tbody : tmpTbody };
				if (id) {
					tmpTable.setAttribute('id', id);
				}
				tmpTable.cellSpacing = (cellSpacing) ? cellSpacing : 0;
				tmpTable.cellPadding = (cellPadding) ? cellPadding : 0;
				tmpTable.border = (border) ? border : 0;
				if (className) {
					tmpTable.className = className;
				}
				tmpTable.appendChild(tmpTbody);
				return result;
			}
		};
	}

	//Controls namespace
	if (typeof SYNTEC.controls !== 'object') {
		SYNTEC.controls = {
			register : function (object) {
				CONTROLLIST[CONTROLLIST.length] = object;
			},
			resize : function () {
				var d, i, c = CONTROLLIST.length;
				for (i = 0; i < c; i++) {
					d = CONTROLLIST[i];
					if (typeof d.resize === 'function') {
						d.resize();
					}
				}
			},
			build : function (node, invoke) {
				try {
					invoke = JSON.parse(invoke);
					var i, l, k, map = ['name', 'translations', 'buttons', 'control'];
					l = map.length;
					for (i = 0; i < l; i++) {
						k = map[i];
						if (typeof invoke[k] === 'undefined') {
							throw new Error('The key "' + k + '" is not found in invoke object');
						}
					}
					if (typeof SYNTEC.controls[invoke.control] !== 'function') {
						throw new Error('Control "' + invoke.control + '" could not be loaded.');
					}
					var control = SYNTEC.controls[invoke.control](node, invoke);
					control.buildUi();
				}
				catch (controlBuildException) {
					SYNTEC.debug.showError('SYNTEC.controls.build', controlBuildException);
				}
				return false;
			},
			mockup : function (node, invoke) {
				var that = {};

				//Register control
				SYNTEC.controls.register(that);

				//buildUi
				that.buildUi = function () {
					alert('MOCKUP UI');
				};
				
				//dispose
				that.dispose = function () {
				};
				
				//resize
				that.resize = function () {
				};

				return that;
			}
		};
	}

	//Debug namespace
	if (typeof SYNTEC.debug !== 'object') {
		SYNTEC.debug = {
			showError : function (method, exception) {
				var strError = 'Foutmelding:\n' + exception.message + '\n\nMethod: ' + method + '\n';
				alert(strError);
			}
		};
	}

	//Ajax namespace
	if (typeof SYNTEC.ajax !== 'object') {
		SYNTEC.ajax = {
			//async
			request : function () {
				//Properties
				var that = {};
				var xmlHttpObject;
			
				//Events
				that.oncompleted = function (xmlHttpObject) {};
				that.onerror = function (xmlHttpObject) {};
				
				//Methods
				that.exec = function (url, postData) {
					xmlHttpObject = new XMLHttpRequest();
					xmlHttpObject.onreadystatechange = function () {
						if (xmlHttpObject.readyState === 4) { 
							if (!xmlHttpObject.status || 
								(xmlHttpObject.status >= 200 && 
								  xmlHttpObject.status < 400)) {
								that.oncompleted(xmlHttpObject);
							}
							else {
								that.onerror(xmlHttpObject);
							}
						} 			
					};
					if (postData) {
						xmlHttpObject.open('POST', url, true);		
						xmlHttpObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset:utf-8");
						xmlHttpObject.send(postData);			
					}
					else {
						xmlHttpObject.open('GET', url, true); 
						xmlHttpObject.send(null); 				
					}
				};
				
				//Return
				return that;
			}

		};
	}	
})();

