
/**
 * @class Core class for the Mamut JavaScript Library
 *
 * @todo add methods for cookie handling
 */
MJSL = {
	/**
	 * Method used to merge two objects.
	 * Often used when merging default options with input options.
	 *
	 * @param {object} first First object
	 * @param {object} second Second object that will overwrite the properties in the first object if found
	 * @return {object} New object with all the properties from the second and first object
	 */
	MergeObjects: function(first, second)
	{
		var result = first;

			for (var prop in second)
			{
				result[prop] = second[prop];
			}

		return result;
	},

	/**
	 * Retrieves url argument value and sets it as an input elements value
	 *
	 * @param {string} urlArgName Url argument name
	 * @param {string} inputElementId The ID of the element you want to change the value of
	 * @return {boolean} A bool value whether a new value has been set or not
	 */
	GetUrlArgSetVal: function(urlArgName, inputElementId)
	{
		var res = false;
		var val = this.GetUrlArg(urlArgName);

			if (val)
			{
				var e = document.getElementById(inputElementId);
					if (e)
					{
						e.value = val;
						res = true;
					}
			}

		return res;
	},

	/**
	 * Gets url arguments for current url or a specified one
	 *
	 * @param {string} urlArgName The argument name to check for in the url
	 * @param {string} url [Optional] The url to check for arguments, if not given the current url will be checked
	 * @return {string|null} The url argument value or null if not found
	 */
	GetUrlArg: function(urlArgName, url)
	{
		var args = "";

			if (url)
			{
				var qMark = url.indexOf('?');
				var hash = url.indexOf('#');
					if (qMark != -1)
					{
							// dont include hash value
							if (hash != -1)
							{
								args = url.substr(qMark, hash-qMark);
							}
							else
							{
								args = url.substr(qMark);
							}
						args = args.substr(1);
					}
			}
			else
			{
				args = document.location.search.substr(1);
			}

			if (args)
			{
				var split = args.split('&');
				var splitArg;
				var argName;
					for (var i=0; i<split.length; i++)
					{
						splitArg = split[i].split('=');
						argName = splitArg[0];

							if (urlArgName == argName && splitArg.length>0)
							{
								return decodeURIComponent(unescape(splitArg[1]));
							}
					}
			}
		return null;
	},

	/**
	 * Gets text identifier from meta tag
	 *
	 * @return {int} Text identifier or null if not found
	 */
	GetTextId: function()
	{
		var id = null;
		var metaTags = document.getElementsByTagName('meta');

			for (var i=0; i<metaTags.length; i++)
			{
				var meta = metaTags[i];
					if (meta.name == "textIdentifier" && meta.content != undefined)
					{
						id = meta.content;
					}
			}

		return id;
	},

	/**
	 * Gets current ISO code for current country
	 */
	GetCurrentCountry: function()
	{
		var country = MJSL_Cookie.ReadCookie('CountryISO');

		return country;
	}
}

/**
 * @class Class for XML handling
 */
MJSL_Xml = {
	/**
	 * Sends xml http request
	 *
	 * @param {string} url Request url
	 * @param {object} inpOptions Object with options. Option properties with default values: method = "GET", async = false, extraContent = null. Example: var options = { method: "POST" }
	 * @return {xml http request} xml http request object
	 */
	SendRequest: function(url, inpOptions)
	{
		var options = {
			method: "GET",
			async: false,
			extraContent: null
		};

		options = MJSL.MergeObjects(options, inpOptions);

		// Make XML request

		var xmlHttpReq = null;

			// Mozilla/Safari
			if (window.XMLHttpRequest)
			{
				xmlHttpReq = new XMLHttpRequest();
			}
			// IE
			else if (window.ActiveXObject)
			{
				xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			}

		xmlHttpReq.open(options.method, url, options.async);
		xmlHttpReq.send(options.extraContent);

		return xmlHttpReq;
	},

	/**
	 * Gets/parses xml document from xml http request object
	 *
	 * @param {xml http req} xmlHttpReq object retrieved with the SendXMLRequest() method
	 * @param {object} inpOptions Additional options given as anonym object. Options with default values: sanitizeHighAscii = true. Example: var options = { sanitizeHighAscii: false }
	 * @return {xml document object} xml document object
	 */
	GetXMLDocument: function(xmlHttpReq, inpOptions)
	{
		var options = {
			sanitizeHighAscii: true
		};

		options = MJSL.MergeObjects(options, inpOptions);

		var xmlDoc = null;

			if (xmlHttpReq.responseXML && xmlHttpReq.responseXML.documentElement)
			{
				xmlDoc = xmlHttpReq.responseXML.documentElement;
			}
			else
			{
				var responseText = xmlHttpReq.responseText;

					if (options.sanitizeHighAscii)
					{
						var tmpResponse = '';
						var preEscaped = responseText;

							// replace ascii>127 characters with underline
							for (var i=0; i<preEscaped.length; i++)
							{
								var c = preEscaped.charAt(i);

									if (c.charCodeAt(0) > 127) {
										tmpResponse += '_';
									} else {
										tmpResponse += c;
									}
							}

						responseText = tmpResponse;
					}

				if (window.DOMParser)
				{
					var parser=new DOMParser();
					xmlDoc=parser.parseFromString(responseText,"text/xml");
				}
				else // Internet Explorer
				{
					xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
					xmlDoc.async="false";
					xmlDoc.loadXML(responseText);
				}
			}

		return xmlDoc;
	},

	/**
	 * Attempts to retrieve a single value from an element in a node.
	 * If more elements with the name exists then the value from the first element is returned.
	 *
	 * @param {element} elem
	 * @param {string} elemName
	 * @return {string|null} value from the first matched element or null if no elements with the elemName exists in the node.
	 */
	TryGetElementValue: function(elem, elemName)
	{
		var res = null;

		var elems = elem.getElementsByTagName(elemName);

		if (elems.length > 0) {
			var e = elems[0];

				if (e.textContent) {
					res = e.textContent;
				} else if (e.text) {
					res = e.text;
				}
		}

		return res;
	}
}

/**
 * @class Class for queuing up scripts and manipulating the queue
 */
MJSL_ScriptHandler = {
	Scripts: {},
	ScriptHandles: {},

	/**
	 * Runs all the scripts assigned to run in the footer
	 */
	RunFooterScripts: function() {
		var scripts = this.Scripts;
		var handles = this.ScriptHandles;

			for (var type in handles) {
					for (var handle in handles[type]) {
							if (scripts[type] != undefined) {
								scripts[type].Callback(handles[type][handle].data);
							}
					}
			}
	},

	/**
	 * Registers script
	 */
	RegisterScript: function(type, func, options) {
		this.Scripts[type] = {
			Callback: func,
			Options: options
		}
	},

	/**
	 * Queues up script
	 */
	Add: function(type, handle, data) {
			if (this.ScriptHandles[type] == undefined) {
				this.ScriptHandles[type] = {};
			}

		this.ScriptHandles[type][handle] = {
			data: data
		};
	},

	/**
	 * Checks if a script with the given type and handle is queued up
	 */
	Exists: function(type, handle) {
			if (this.ScriptHandles[type] != undefined) {
				if (this.ScriptHandles[type][handle] != undefined) {
					return true;
				}
			}

		return false;
	},

	/**
	 * Removes queued up script from queue
	 */
	Remove: function(type, handle) {
			if (handle == undefined)
			{
				delete this.ScriptHandles[type];
			}
			else
			{
					if (this.Exists(type, handle)) {
						delete this.ScriptHandles[type][handle];
					}
			}
	}
}

/**
 * @class Simple cookiehandler class
 *
 * Inspired (copy pasted) by quirksmode.org
 */
MJSL_Cookie = {
	/**
	 * Creates cookie
	 */
	CreateCookie: 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=/";
	},

	/**
	 * Reads cookie
	 */
	ReadCookie: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');

			for(var i=0;i < ca.length;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;
	},

	/**
	 * Erases cookie
	 */
	EraseCookie: function(name) {
		CreateCookie(name,"",-1);
	}
}

if (jQuery)
{
	jQuery(document).ready(function($) {
		// init chatform
		//////////////////////

		$('#chatform').submit(function() {
			var fields = [];

			fields.push($('#chatform #nickName'));
			fields.push($('#chatform #chatId'));
			fields.push($('#chatform #chatIssue'));

			var fieldsLen = fields.length;
			var formHasError = false;

				// validate
				for (var i=0; i<fieldsLen; i++)
				{
					var $field = fields[i];

					var placeholderValue = $field.attr('data-placeholder-value');
					var value = $field.val();

					var $fieldValidation = $field.parents('tr').first().find('.chatform-validation');

					var hasError = false;
					var errorMessage = '';

						if (value == '' || value == placeholderValue) {
							errorMessage = 'Feltet må være fylt ut.'
							hasError = true;
						}

						if (hasError) {
							$field.addClass('has-error');
							$fieldValidation.find('.chatform-validation-message').text(errorMessage);
							$fieldValidation.removeClass('hidden');
							formHasError = true;
						} else {
							$field.removeClass('has-error');
							$fieldValidation.addClass('hidden');
						}
				}

				if (!formHasError) {
					window.open('', 'chatwindow', 'width=500,height=680,status=yes,resizable=yes,scrollbars=yes');
					return true;
				} else {
					return false;
				}
		});

		$('#chatform .placeholder-field').click(function() {
			var $this = $(this);
			var value = $this.val();
			var placeholderValue = $this.attr('data-placeholder-value');

				if (value == placeholderValue) {
					$this.removeClass('using-placeholder-value');
					$this.val('');
				}
		})

		$('#chatform .placeholder-field').change(function() {
			var $this = $(this);
			var value = $this.val();
			var placeholderValue = $this.attr('data-placeholder-value');

				if (value != placeholderValue || value != '') {
					$this.removeClass('using-placeholder-value');
				}
		})

		$('#chatform .placeholder-field').blur(function() {
			var $this = $(this);
			var value = $this.val();
			var placeholderValue = $this.attr('data-placeholder-value');

				if (value == '' || value == placeholderValue) {
					$this.addClass('using-placeholder-value');
					$this.val(placeholderValue);
				}
		})

		$('#chatform .chatform-validation-message-box').click(function() {
			var $this = $(this);

			$this.addClass('hidden');

			var $input = $this.parents('tr').first().find('input').first();

			$input.click();
			$input.focus();
		});

		// quote rotation
		//////////////////////

		$('.quote-rotation').each(function() {
			var $quoteRotation = $(this);
			var $quotes = $quoteRotation.find('.quote-rotation-quotes').first();
			//var link = $quoteRotation.find('.quote-rotation-link').first().get(0);

			var $items = $quotes.children();

				if ($items.length > 1) {

					var current = 0;
					var next = 1;

					// prepare first item
					var $curItem = $($items[current]);
					$curItem.show();
					//link.href = $curItem.attr('data-link');

					setInterval(function() {
						$curItem = $($items[current]);

						next = current+1 > $items.length-1 ? 0 : current+1;

						var $nextItem = $($items[next]);

						$curItem.hide(0, function() {
							$nextItem.show(0);
						});

						//link.href = $nextItem.attr('data-link');

						current = next;
					}, 6000);
				}
		});
	});
}
