/*
	TEXT ZOOM SCRIPT
*/

var ts = {
	sizes : ['x-small','small','medium','large','x-large'],
	currSize : 1,
	init : function () 
	{
		var b = document.getElementById ('biggerFont');
		b.onclick = ts.grow;
		
		var s = document.getElementById ('smallerFont');
		s.onclick = ts.shrink;
		
		var r = document.getElementById ('regularFont');
		r.onclick = ts.regular;
	},
	grow : function ()
	{
		var b = document.getElementsByTagName ('body')[0];
		var nextSize = ts.currSize + 1;
		
		if (ts.sizes[nextSize])
		{
			b.style.fontSize = ts.sizes[nextSize];
			ts.currSize = nextSize;
			createCookie ('font',ts.sizes[ts.currSize],365);
		}
		return false;
	},
	shrink : function ()
	{
		var b = document.getElementsByTagName ('body')[0];
		var nextSize = ts.currSize - 1;
		
		if (ts.sizes[nextSize])
		{
			b.style.fontSize = ts.sizes[nextSize];
			ts.currSize = nextSize;
			createCookie ('font',ts.sizes[ts.currSize],365);
		}
		return false;
	},
	regular : function ()
	{
		var b = document.getElementsByTagName ('body')[0];
		b.style.fontSize = ts.sizes[1];
		ts.currSize = 1;
		createCookie ('font',ts.sizes[ts.currSize],365);
		return false;
	}
}

/*
	END TEXT ZOOM SCRIPT
*/

/*
	TEXTAREA RESIZER SCRIPT
*/

var ta = {
	txtArea : null,
	incBtn : null,
	decBtn : null,
	intID : null,
	nextSize : null,
	initSize : 100,
	init : function () {
		
		if (!document.getElementById) {
			return false;
		}
		
		// get elements
		if ($('SFmsg_textarea')) {
			ta.txtArea = $('SFmsg_textarea');
		} else {
			return;
		}
		ta.incBtn = $('ta_enlarger');
		ta.decBtn = $('ta_shrinker');
		// make resize-buttons visible through Javascript. They have no meaning without JS turned on
		ta.incBtn.style.display = ta.decBtn.style.display = 'block';
		// set textarea height
		ta.txtArea.style.height = parseInt(ta.initSize)+'px';
		// add listeners
		addEvent(ta.incBtn,'click',ta.startGrow,false);
		addEvent(ta.decBtn,'click',ta.startShrink,false);
	},
	startGrow : function () {
		var b = ta.convertStyleToNumber();
		// add 25 and set style
		var n = b + 50;
		ta.nextSize = n;
		ta.intID = setInterval(ta.grow,5);
	},
	startShrink : function () {
		var b = ta.convertStyleToNumber();
		// do not allow text area to get smaller than 100px
		if (b <= ta.initSize) return;
		// subtract 25 and set style
		var n = b - 50;
		ta.nextSize = n;
		ta.intID = setInterval(ta.shrink,5);
	},
	grow : function (n) {
		// get converted height declaration
		var a = ta.convertStyleToNumber();
		// as long as textarea is smaller than target height, add 5 pixels
		if (a <= ta.nextSize) {
			a += 5;
			ta.txtArea.style.height = parseInt(a)+'px';
		// if target height is reached, clear interval
		} else {
			clearInterval(ta.intID);
		}
	},
	shrink : function (n) {
		// get converted height declaration
		var a = ta.convertStyleToNumber();
		// as long as textarea is larger than target height, subtract 5 pixels
		if (a >= ta.nextSize) {
			a -= 5;
			ta.txtArea.style.height = parseInt(a)+'px';
		// if target height is reached, clear interval
		} else {
			clearInterval(ta.intID);
		}
	},
	convertStyleToNumber : function () {
		// fetch text area height
		var a = ta.txtArea.style.height;
		// strip 'px' of declaration
		var p = /px/ig;
		var b = ta.txtArea.style.height.replace(p,'');
		// convert string to number
		b = b * 1;
		return b;
	}
}

/*
	END TEXTAREA RESIZER SCRIPT
*/

/*
	COMMENT VALIDATION SCRIPT
*/

var validator = {
	// Array containing form field errors
	errors : new Array(),
	// the form's id
	formId : 'submitCommentForm',
	// initialization function
	init : function ()
	{
		var W3CDOM = (document.getElementById && document.createElement && document.getElementsByTagName);
		// if browser can't handle the DOM, return
		if (!W3CDOM) return;
		if (document.getElementById (validator.formId))
		{
			var form = document.getElementById (validator.formId);
			// check validity of form fields onsubmit
			form.onsubmit = validator.checkFields;
		}
	},
	checkFields : function (e)
	{
		// empty the 'errors' array in case the dialog must be displayed again
		while (validator.errors.length > 0)
		{
			validator.errors.pop();
		}
		
		// different validity check methods can be added to this list
		validator.checkNameField ('nameField');
		validator.checkMailField ('mailField');
		validator.checkMessageField ('SFmsg_textarea');
		
		// if there are 1 or more errors available, stop form from submitting 
		// and provide an error message
		if (validator.errors.length > 0)
		{
			validator.provideErrorMessage ();
			if (e && e.preventDefault) e.preventDefault();
			return false;
		}
		else
		{
			document.getElementById(validator.formId).submit();
		}
	},
	checkMailField : function (id)
	{
		// check mail field validity
		var mailField = document.getElementById (id);
		var pattern = /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/;
		if (mailField.value == '')
		{
			validator.errors.push(id+'||=||You forgot to provide an email address');
		}
		else if (!pattern.test (mailField.value))
		{
			validator.errors.push(id+'||=||This is not a valid email address');
		}
	},
	checkNameField : function (id)
	{
		// check name field validity
		var nameField = document.getElementById (id);
		if (validator.isEmpty(nameField.value))
		{
			validator.errors.push(id+'||=||You forgot to provide a name');
		}
	},
	checkMessageField : function (id)
	{
		// check message field validity
		var msgField = document.getElementById (id);
		if (validator.isEmpty(msgField.value))
		{
			validator.errors.push(id+'||=||You forgot to provide a message');
		}
		else if (msgField.value.length > 1250)
		{
			validator.errors.push(id+'||=||This message is too long');
		}
	},
	provideErrorMessage : function ()
	{
		// provide a suitable error message
		corrector.init (validator.errors);
	},
	isEmpty : function (s)
	{
		var p = /^\s$/;
		return p.test(s) || s == '';
	}
}

var corrector = {
	dropsheet : null,
	dialog : null,
	header : 'The form contains errors',
	errors : null,
	// initialization method
	init : function (errors)
	{
		corrector.errors = errors;
		corrector.show ();
	},
	// build dialog box + dropsheet
	show : function ()
	{
		var body = document.getElementsByTagName ('body')[0];
		var pageDimensions = getPageDimensions();
		var viewportSize = getViewportSize();
		
		if (viewportSize[1] > pageDimensions[1]) {
			pageDimensions[1] = viewportSize[1];
		}
		
		// create dropsheet to cover background
		var dropSheet = document.createElement('div');
		
		dropSheet.setAttribute ('id','dropSheet');
		dropSheet.style.position = 'absolute';
		dropSheet.style.left = '0';
		dropSheet.style.top = '0';
		dropSheet.style.width = pageDimensions[0] + 'px';
		dropSheet.style.height = pageDimensions[1] + 'px';
		body.appendChild(dropSheet);
		
		// assign dropsheet to property of corrector for easy accessing
		corrector.dropsheet = dropSheet;
		
		try {
			
			var dialog = document.createElement('div');
			dialog.className = 'dialog';
			dialog.id = 'dialog';
			dialog.style.visibility = 'hidden';
			dialog.style.position = 'absolute';
			
			body.appendChild(dialog);
			
			// calculate position of dialog
			var scrollingPosition = getScrollingPosition();
			var viewportSize = getViewportSize();
			
			dialog.style.left = scrollingPosition[0] + 
								parseInt(viewportSize[0] / 2) -
								parseInt(dialog.offsetWidth / 2) + 'px';
			dialog.style.top = scrollingPosition[1] +
								parseInt(viewportSize[1] / 2) -
								parseInt(dialog.offsetHeight / 2) + 'px';
			dialog.style.visibility = 'visible';
			
			// assign dialog to property of corrector for easy accessing
			corrector.dialog = dialog;
		
		} catch (error) {
			return true;
		}
		
		corrector.buildHeader ();
		corrector.buildCorrectionForm ();
		
		return false;
	},
	// function for creating the header above the correction form
	buildHeader : function ()
	{
		var header = document.createElement ('h2');
		header.appendChild (document.createTextNode (corrector.header));
		corrector.dialog.appendChild (header);
	},
	// function for creating the correction form
	buildCorrectionForm : function ()
	{
		// create the correction form
		var form = document.createElement ('form');
		var fieldset = document.createElement ('fieldset');
		var legend = document.createElement ('legend');
		var submit_btn = document.createElement ('input');
		submit_btn.value = 'Proceed';
		submit_btn.type = 'submit';
		submit_btn.className = 'submit_btn';
		var back_btn = document.createElement ('input');
		back_btn.value = 'Back';
		back_btn.type = 'button';
		back_btn.className = 'back_btn';
		
		// return to original form on click
		back_btn.onclick = function () { corrector.returnValues (false); }
		
		legend.appendChild (document.createTextNode ('Please correct the following:'));
		fieldset.appendChild (legend);
		form.appendChild (fieldset);
		form.appendChild (submit_btn);
		form.appendChild (back_btn);
		corrector.dialog.appendChild (form);
		
		corrector.cloneErroneousFields (fieldset);
		
		// focus on the first field in the correction form
		if (fieldset.childNodes[1].focus) fieldset.childNodes[1].focus();
		
		// on submitting of the form, the old values should be replaced by the new values
		form.onsubmit = function () { corrector.returnValues (true); }
	},
	// function for cloning the erroneous form fields
	cloneErroneousFields : function (fieldset)
	{
		for (var i = 0; i < corrector.errors.length; i++)
		{
			var fe = corrector.errors[i].split('||=||');
			// create new form field
			var field = document.getElementById (fe[0]).cloneNode (true);
			field.id = fe[0] + '_temp';
			// create label
			var label = getElementsByAttribute ('for', fe[0])[0].cloneNode (true);
			if (label.getAttribute ('htmlFor'))
			{
				label.setAttribute ('htmlFor',field.id);
			}
			else
			{
				label.setAttribute ('for',field.id);
			}
			label.firstChild.nodeValue = fe[1];
			label.className = 'error';
			
			fieldset.appendChild (label);
			//fieldset.appendChild (span);
			fieldset.appendChild (field);
		}
	},
	// return values to the initial form
	returnValues : function (submit_old_form)
	{
		for (var i = 0; i < corrector.errors.length; i++)
		{
			var fe = corrector.errors[i].split('||=||');
			var old_field = document.getElementById (fe[0]);

			old_field.value = document.getElementById (fe[0]+'_temp').value;
		}
		corrector.destroy (submit_old_form);
	},
	// function for removing dialog
	destroy : function (submit_old_form)
	{
		corrector.dropsheet.parentNode.removeChild (corrector.dropsheet);
		corrector.dialog.parentNode.removeChild (corrector.dialog);
		
		if (submit_old_form)
		{
			validator.checkFields ();
		}
		return true;
	}
}

var quo = {
	quote : false,
	init : function ()
	{
		var W3CDOM = (document.getElementById && document.getElementsByTagName && document.createElement);
		if (!W3CDOM) return;
		if (document.getElementById ('comments'))
		{
			var comments_list = document.getElementById ('comments');
			var dts = comments_list.getElementsByTagName ('dt');
			
			for (var i = 0; i < dts.length; i++)
			{
				var a = document.createElement ('a');
				a.href = '#';
				a.title = 'Quote this comment';
				a.id = 'quote'+dts[i].id.substring (7);
				a.className = 'quote_link';
				a.onclick = quo.createQuote;
				dts[i].appendChild (a);
			}
		}
	},
	createQuote : function ()
	{
		if (quo.quote)
		{
			alert ("You can only quote one comment at a time");
			return false;
		}
		var dt = this.parentNode;
		var x = getXMLHttpRequestObject ();
		x.open ('get','http://www.whatstyle.net/etc/quote.ajax.php?id='+dt.id.substring(7),true);
		x.onreadystatechange = function ()
		{
			if (x.readyState == 4)
			{
				quo.addQuoteToForm (x.responseText);
			}
		}
		x.send (null);
		
		return false;
	},
	addQuoteToForm : function (info)
	{
		quo.quote = true;
		
		var info_array = info.split ('||-||');
		var bq = document.createElement ('blockquote');
		bq.cite = '#comment' + info_array[0];
		var p1 = document.createElement ('p');
		var a = document.createElement ('a');
		a.href = '#comment' + info_array[0];
		a.title = 'View the original comment';
		a.appendChild (document.createTextNode (info_array[1] + ' wrote:'));
		p1.appendChild (a);
		p2 = document.createElement ('p');
		p2.appendChild (document.createTextNode (info_array[2]));
		bq.appendChild (p1);
		bq.appendChild (p2);
		var textarea = document.getElementById ('SFmsg_textarea');
		textarea.parentNode.insertBefore (bq,textarea);
		textarea.focus();
		
		var del_link = document.createElement ('a');
		del_link.href = '#';
		del_link.title = 'Remove quote';
		del_link.appendChild (document.createTextNode ('Remove this quote'));
		del_link.onclick = function ()
		{
			this.parentNode.parentNode.removeChild (this.parentNode);
			quo.quote = false;
			document.getElementById ('input_quote_id').value = '';
			return false;
		}
		bq.appendChild (del_link);
		
		document.getElementById ('input_quote_id').value = info_array[0];
		
	}
}

/*
	HELPER FUNCTIONS
*/

function getXMLHttpRequestObject ()
{
	var http_request = null;
	if (window.XMLHttpRequest)
	{
		http_request = new XMLHttpRequest();
	}
	else if	(window.ActiveXObject)
	{
		try	{ http_request = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) {
			try	{ http_request = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch (e) {}
		}
	}
	return http_request;
}

function addEvent(obj, evType, fn, useCapture){
	if(obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	}else if(obj.attachEvent){
		var r = obj.attachEvent('on' + evType, fn);
		return r;
	}else{
		obj['on' +  evType] = fn;
	}
}

function $() {
	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;
}

function addClass (target, classValue) {
	var pattern = new RegExp("(^| )" + classValue + "( |$)");
	
	if (!pattern.test(target.className)) {
		if (target.className == "") {
			target.className = classValue;
		} else {
			target.className += " " + classValue;
		}
	}
	
	return true;
}

function getElementsByAttribute(attribute, attributeValue)
{
  var elementArray = new Array();
  var matchedArray = new Array();

  if (document.all)
  {
    elementArray = document.all;
  }
  else
  {
    elementArray = document.getElementsByTagName("*");
  }

  for (var i = 0; i < elementArray.length; i++)
  {
    if (attribute == "class")
    {
      var pattern = new RegExp("(^| )" + attributeValue + "( |$)");

      if (elementArray[i].className.match(pattern))
      {
        matchedArray[matchedArray.length] = elementArray[i];
      }
    }
    else if (attribute == "for")
    {
      if (elementArray[i].getAttribute("htmlFor") || elementArray[i].getAttribute("for"))
      {
        if (elementArray[i].htmlFor == attributeValue)
        {
          matchedArray[matchedArray.length] = elementArray[i];
        }
      }
    }
    else if (elementArray[i].getAttribute(attribute) == attributeValue)
    {
      matchedArray[matchedArray.length] = elementArray[i];
    }
  }

  return matchedArray;
}

function getEventTarget(e) {
	var targ;
	if (!e) {
		e = window.event;
	}
	if (e.target) {
		targ = e.target;
	} else if (e.srcElement) {
		targ = e.srcElement;
	}
	if (targ.nodeType == 3) { // defeat Safari bug
		targ = targ.parentNode;
	}

	return targ;
}

function getScrollingPosition()
{
  //array for X and Y scroll position
  var position = [0, 0];

  //if the window.pageYOffset property is supported
  if(typeof window.pageYOffset != 'undefined')
  {
    //store position values
    position = [
        window.pageXOffset,
        window.pageYOffset
    ];
  }

  //if the documentElement.scrollTop property is supported
  //and the value is greater than zero
  if(typeof document.documentElement.scrollTop != 'undefined'
    && document.documentElement.scrollTop > 0)
  {
    //store position values
    position = [
        document.documentElement.scrollLeft,
        document.documentElement.scrollTop
    ];
  }

  //if the body.scrollTop property is supported
  else if(typeof document.body.scrollTop != 'undefined')
  {
    //store position values
    position = [
        document.body.scrollLeft,
        document.body.scrollTop
    ];
  }

  //return the array
  return position;
}

function getViewportSize()
{
  var size = [0,0];

  if (typeof window.innerWidth != 'undefined')
  {
    size = [
        window.innerWidth,
        window.innerHeight
    ];
  }
  else if (typeof document.documentElement != 'undefined'
      && typeof document.documentElement.clientWidth != 'undefined'
      && document.documentElement.clientWidth != 0)
  {
    size = [
        document.documentElement.clientWidth,
        document.documentElement.clientHeight
    ];
  }
  else
  {
    size = [
        document.getElementsByTagName('body')[0].clientWidth,
        document.getElementsByTagName('body')[0].clientHeight
    ];
  }

  return size;
}

function getPageDimensions () {
	var body = document.getElementsByTagName('body')[0];
	var bodyOffsetWidth = 0;
	var bodyOffsetHeight = 0;
	var bodyScrollWidth = 0;
	var bodyScrollHeight = 0;
	var pageDimensions = [0,0];
	
	if (typeof document.documentElement != 'undefined' &&
		typeof document.documentElement.scrollWidth != 'undefined') {
		pageDimensions[0] = document.documentElement.scrollWidth;
		pageDimensions[1] = document.documentElement.scrollHeight;
	}
	
	bodyOffsetWidth = body.offsetWidth;
	bodyOffsetHeight = body.offsetHeight;
	bodyScrollWidth = body.scrollWidth;
	bodyScrollHeight = body.scrollHeight;
	
	if (bodyOffsetWidth > pageDimensions[0]) {
		pageDimensions[0] = bodyOffsetWidth;
	}
	
	if (bodyOffsetHeight > pageDimensions[1]) {
		pageDimensions[1] = bodyOffsetHeight;
	}
	
	if (bodyScrollWidth > pageDimensions[0]) {
		pageDimensions[0] = bodyScrollWidth;
	}
	
	if (bodyScrollHeight > pageDimensions[1]) {
		pageDimensions[1] = bodyScrollHeight;
	}
	
	return pageDimensions;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/*
	END HELPER FUNCTIONS
*/

function generalInit ()
{
	quo.init () // initialize the quote creator
	ta.init (); // initialize the textarea resizer script
	ts.init (); // initialize the text zoom script
	validator.init (); // initialize the comment validator script
}

addEvent (window, 'load', generalInit, false);