/*  Migrated the main.js file and contents in the index page to here!

In doing so we can properly separate different scripts by activity, making an easy to manage heirarchy.

For example, the window.onload function is a "main" process, it does more than just the cookies process.

Similarily the instantz javascript model class is a model for all instantz website activities, not just cookies.

So they too have been migrated to this main.js file.

This leaves the cookies.js with just the javascript cookie handler, as it should be.

*/


// Original main.js Script

function main_ajaxxmlhttp(url,div,data){
		try {
			xmlhttp = new XMLHttpRequest();
		}
		catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (failed) {
				xmlhttp = null;
			}
		}
		if (xmlhttp != null) {
			xmlhttp.onreadystatechange = function state_change() {
													if (xmlhttp.readyState == 4) {
														if (xmlhttp.status== 200) {
															div.innerHTML = xmlhttp.responseText;
														}
													}
												};
			xmlhttp.open("POST" , url,true);
			jsonstring = JSON.stringify(data);
			param = "jstring="+ escape(jsonstring);
			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlhttp.setRequestHeader("Content-length", param.length);
			xmlhttp.setRequestHeader("Connection", "close");
			xmlhttp.send(param);
		}
	}

function changesearch(value) {
	if (value.trim().length >= 3) {
		main_ajaxxmlhttp('/ajax/automation.php?search='+ value.trim(),document.getElementById('searchresult'),'');	
		document.getElementById('searchresult').style.backgroundColor = '#aaaaaa';
	} else {
		document.getElementById('searchresult').innerHTML = '';
	}
}



// Imported from the index.php file

function resize(image,sizew,sizeh) {
		var width = image.width;
		var height = image.height;
		if (image.width > sizew || image.height > sizeh) {
			var proportion = sizew/image.width;
			if ((sizeh/image.height) < proportion) {
				proportion = sizeh/image.height;
			}
			image.height = height*proportion;
			image.width = width*proportion;
		}
			image.originalWidth = width;
			image.originalHeight = height;
		if (sizew == 300 && sizeh == 300) {
			image.onclick = originalsize;
		}
}
function originalsize() {
	if (this.width == this.originalWidth && this.height == this.originalHeight && this.parentNode.style.width == '700px') {
		if (this.width > 300 || this.height > 300) {
			var p = 300/this.width;
			if ((300/this.height) < p) {
				p = 300/this.height;
			}
			this.height = this.originalHeight*p;
			this.width = this.originalWidth*p;
		}
		this.parentNode.style.width = '350px';
		this.parentNode.style.display = 'inline-block';
	} else if( this.originalWidth < 700 && this.originalHeight < 700) {
		this.width = this.originalWidth;
		this.height = this.originalHeight;
		this.parentNode.style.width = '700px';
		this.parentNode.style.display = 'block';
	} else {
		window.open(this.src,'image');
	}
}
function insert(aTag, eTag) {
	var input = document.forms['newsform'].elements['news'];
	input.focus();
	if (typeof document.selection != 'undefined') {
		var range = document.selection.createRange();
		var insText = range.text;
		range.text = aTag + insText + eTag;
		range = document.selection.createRange();
		if (insText.length == 0) {
			range.move('character', -eTag.length);
		} else {
			range.moveStart('character', aTag.length + insText.length + eTag.length);      
		}
		range.select();
	}
	else if (typeof input.selectionStart != 'undefined')
	{
		var start = input.selectionStart;
		var end = input.selectionEnd;
		var insText = input.value.substring(start, end);
		input.value = input.value.substr(0, start) + aTag + insText + eTag + input.value.substr(end);
		var pos;
		if (insText.length == 0) {
			pos = start + aTag.length;
		} else {
			pos = start + aTag.length + insText.length + eTag.length;
		}
		input.selectionStart = pos;
		input.selectionEnd = pos;
	}
	else
	{
		var pos;
		var re = new RegExp('^[0-9]{0,3}$');
		while (!re.test(pos)) {
			pos = prompt("Einfügen an Position (0.." + input.value.length + "):", "0");
		}
		if (pos > input.value.length) {
			pos = input.value.length;
		}
		var insText = prompt("Bitte geben Sie den zu formatierenden Text ein:");
		input.value = input.value.substr(0, pos) + aTag + insText + eTag + input.value.substr(pos);
	}
}

  // General Purpose trim Function (may already exist among the instantz library but necessary for testing)
function trim1(str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

// Start of a new ajax library to automate and unify all ajax calls throughout the system
function ajlib() {
	var self = this;
	self.x;// Ajax Object

	self.dojax = function(url, callback, params) {
		if (typeof XMLHttpRequest !== 'undefined') self.x = new XMLHttpRequest();
		else {
			var versions = ["MSXML2.XmlHttp.5.0",
							"MSXML2.XmlHttp.4.0",
							"MSXML2.XmlHttp.3.0",
							"MSXML2.XmlHttp.2.0",
							"Microsoft.XmlHttp"]
			for(var i = 0, len = versions.length; i < len; i++) {
				try {
					self.x = new ActiveXObject(versions[i]);
					break;
				}
				catch(e){}
			} // end for
		}
		self.x.onreadystatechange = ensureReadiness;

		function ensureReadiness() {
			if (self.x.readyState < 4) {
				return;
			}
			if (self.x.status !== 200) {
				return;
			}

			if (self.x.readyState === 4) {// all is well
				callback.innerHTML = self.x.responseText;
			}
		}

		if (params) {
			self.x.open('POST', url, true);
			self.x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			self.x.send(params);
		} else {
			self.x.open('GET', url, true);
			self.x.send('');
		}
	}

	self.init = function() {
		// Initialization function for the ajax class
	}

	// Call initialization function
	self.init();
}


// Chatbox code for new chatbox system
function ChatBox() {
	var self = this;
	self.vsacb;
	self.count;
	self.run = false;

	if (typeof ajlib == 'function') self.aj = new ajlib;// Create the Ajax Object Class

	self.setEv = function() {
		self.run = true;
		setTimeout(self.getMsg, 10000)
	}

	self.setTimer = function() {
		if (this.value == 'Click here to chat!') this.value = '';
		self.count = 7;
		self.getMsg();
	}

	self.sendMsg = function() {
		var msg = document.getElementById('vsacb').getElementsByTagName('input')[0];
		if (msg.value != 'Click here to chat!')
			self.aj.dojax("/ajax/chatbox.php", document.getElementById('messages'), ("vsa_chatbox=" + escape(msg.value)));
		msg.value = '';
		self.count = 6;
		if (!self.run) self.setEv();
	}

	self.getMsg = function() {
		self.aj.dojax("/ajax/chatbox.php", document.getElementById('messages'));
		self.count--;
		self.run = false;
		if (self.count > 0) self.setEv();
	}

	self.load = function() {// Initialization function
		self.vsacb = document.getElementById('vsacb');// Get form
		self.vsacb.onsubmit = function() { return false; }// Stop form from submitting
		self.vsacb.getElementsByTagName('input')[1].onclick = self.sendMsg;// Set submit button to send message
		var msg = document.getElementById('vsacb').getElementsByTagName('input')[0];
		msg.onfocus = self.setTimer;
	}

	self.load();// Initializer
}

  // Cookie Handler Class
function cookieHandler() {
	var self = this;

	  // Methods
	self.setCookie = function(cookieName, cookieValue, lifeTime) {// Sets a cookie, lifetime is in years (- for delete), null for expire after current session (aka when browser is closed)
		var ret;
		if (!cookieName) ret = false;
		if (lifeTime) var expires = new Date(new Date().getTime() + (lifeTime * 1000 * 60 * 60 * 24)).toUTCString();
		document.cookie = escape(cookieName) + "=" + escape(cookieValue) + (expires ? ";expires=" + expires : '');
		if ((lifeTime < 0) && (!self.getCookie(cookieName))) ret = true;// Confirms deletion
		if (self.getCookie(cookieName)) ret = true;// Confirms has been set
		return ret;
	}
	self.getCookie = function(cookieName) {// Checks the array for a matching name and returns its value
		var ret = false; var t = self.getValues();// Grabs all values from the cookie into an array
		for (var x = 0;x<t.length;x++) {
			if (trim1(unescape(t[x][0])) == cookieName) ret = trim1(unescape(t[x][1]));
		}
		return ret;
	}
	self.getValues = function() {// Retreives an multi-dimensional array of all cookie values, and returns it
		var ret = new Array(); var c = document.cookie.split(';');
		for (var x = 0;x<c.length;x++) {
			ret[x] = c[x].split('=');
		}
		return ret;
	}
}


  // Instantz Model/Controller
function Instantz() {
	var self = this;// Self assignment to retain scope within object

	  // Attributes
	self.hsHead;// Stores hide/show header
	self.hsArr;// stores hide/show objects
	self.tabmenu;
	self.tabs;// Stores page tabs

	  // Objects
	if (typeof cookieHandler == 'function') self.CH = new cookieHandler();// Conditionally assigns new cookieHandler - Since it is not a part of this object

	  // Methods
	self.toggleHS = function(o,e) {// Toggles the display of o, and innerHTML of e
		var ret = false;
		if (self.CH) self.CH.setCookie(o,'',-1);// Unsets cookie if cookie handler is present.
		var obj = document.getElementById(o);// Grabs object by its ID
		if (obj) {
			// Activities here!
			if (obj.style.display == "none") {
				e.innerHTML = '-';
				obj.style.display = '';
			} else {
				e.innerHTML = '+';
				obj.style.display = 'none';
				if (self.CH) self.CH.setCookie(o,'hide',2);// Sets cookie to value of hide
			}
		} else {
			ret = true;// Error causes page to reload
		}
		return ret;
	}
	self.tabSelected = function() {
		if (self.CH) self.CH.setCookie('optType', x,　-1);// Unsets the cookie at the beginning - Also temporarily disabled for testing
		for (var x=0;x<self.tabs.length;x++) {
			if (self.tabs[x] == this) {
				this.style.zIndex = 20;
				this.className = 'current';
				if (typeof newstabs == 'function') {// Temporarily modified to ensure cookie handler only fires on news changetabs existence
					newstabs(x);// Ajax Call if function exists
					// Old Function, sets for 2 years - if (self.CH) self.CH.setCookie('optType', x, 2);// Sets the cookie if the cookie handler exists - Temporarily disabled due to variable naming incompatibility
					if (self.CH) self.CH.setCookie('optType', x);// Sets the cookie if the cookie handler exists - Temporarily disabled due to variable naming incompatibility
				}
				if (typeof changechar == 'function') {
					changechar(x+1);
				}
				if (typeof changepolls == 'function') {
					changepolls(x);
				}
				/*if (typeof changetabs == 'function') {
					changetabs(x);
				}/*Disabled until I have time to figure out how to implement for the ajax search*/
			} else {// Resets all others
				self.tabs[x].className = '';
				self.tabs[x].style.zIndex = (20-x);
			}
		}
	}

	  // Custom Loading Functions
	self.loadHandlers = function() {
		var t; var y;
		for (var x=0;x<self.hsArr.length;x++) {
			y = self.hsHead + self.hsArr[x];
			t = document.getElementById(y);
			t.onclick = function() {
				return self.toggleHS(this.id.split('-')[1], this);
			}
		}
	}

	self.loadTabs = function() {
		// Sets up the tabs system!
		var t;
		for (var x = 0;x<self.tabs.length;x++) {
			t = self.tabs[x];
			t.onclick = self.tabSelected;// Sets onclick function
			if (t.className != 'current') t.style.zIndex = (20-x);// Sets display order
		}
	}

	self.load = function() {// Constructor
		  // Set some default values (changes are allowed/prefered here)
		self.hsHead = 'hs-';
		self.hsArr = new Array('banner');
		self.tabmenu = 'tabs';
		if (document.getElementById(self.tabmenu)) {
			 self.tabs = document.getElementById(self.tabmenu).getElementsByTagName('li');// If news.js has loaded, this can run!
			self.loadTabs();
		}
		  // runs some setup functions here
		self.loadHandlers();
	}

	  // Constructor call at end of object creation
	self.load();
}


// Add javascript for the news search function
function newssearch(value) {
	var t = document.getElementById('nsresults');
	if (value.trim().length >= 3) {
		main_ajaxxmlhttp('/ajax/newsearch.php?search=' + value.trim(), t, '');
	} else {
		t.innerHTML = '';
	}
}
