
// This file just contains several
// generic javascript functions used by all
// pages on the website.

if (typeof(document.getElementById) == "undefined")
	document.getElementById = function (id)
	{
		return document.all[id];
	}
	
if (!window.XMLHttpRequest && window.ActiveXObject)
	window.XMLHttpRequest = function ()
	{
		return new ActiveXObject(navigator.userAgent.indexOf("MSIE 5") != -1 ? "Microsoft.XMLHTTP" : "MSXML2.XMLHTTP");
	};

// Sends a post request to the specific URL.
function sendPostRequest(url, content, callback)
{
	if (!window.XMLHttpRequest) // Shiza, we can't send a request :(.
		return false;
	
	// Create a new request object.
	var requestDoc = new XMLHttpRequest();
	
	// Do we have a callback defined? If so set it up.
	if (typeof(callback) != "undefined")
	{
		// Create a anonymous function.
		// (I hate anonymous functions, to messy and illogical :P)
		requestDoc.onreadystatechange = function ()
		{
			// Check we have completed the request.
			if (requestDoc.readyState != 4)
				return;
		
			// If everything went ok (200 FTW!) return the XML document.
			if (requestDoc.status == 200 && requestDoc.responseXML != null)
				callback(requestDoc.responseXML);
				
			// Dam, what went wrong?
			else
			{
				callback(false);			
			}
		};
	}
	
	// Open a POST request to the server.
	requestDoc.open('POST', url, true);
	
	// Place a header in our call telling the server how the data is encoded.
	if (typeof(requestDoc.setRequestHeader) != "undefined")
		requestDoc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

	// Send the content!
	requestDoc.send(content);
	
	return true;
}

// Converts text to url entites.
// Thanks for this SMF :D.
function textToEntities(text)
{
	var entities = "";
	for (var i = 0; i < text.length; i++)
	{
		if (text.charCodeAt(i) > 127)
			entities += "&#" + text.charCodeAt(i) + ";";
		else
			entities += text.charAt(i);
	}

	return entities;
}

// Trims a string.
function trim(str)
{
	return str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}

// Checks is a string contains any of the given characters.
function contains(password, validChars) 
{
	for (i = 0; i < password.length; i++) 
	{
		var char = password.charAt(i);
		if (validChars.indexOf(char) > -1) 
		{
			return true;
		}
	}
	return false;
}
 
// Caps a number at a maximum number.
function cap(number, max) 
{ 
	if (number > max)
	{ 
		return max; 
	} 
	else 
	{ 
		return number; 
	} 
} 
		
// Nicked this from SMF and modified it a bit, thanks a lot guys :D - Couldn\'t get my old version working.
// Surrounds the selected text with text1 and text2.
function SurroundText(textarea, text1, text2)
{
	if (textarea.readOnly == true) 
		return;

	// Can a text range be created?
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		var caretPos = textarea.caretPos, temp_length = caretPos.text.length;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text1 + caretPos.text + text2 + ' ' : text1 + caretPos.text + text2;

		if (temp_length == 0)
		{
			caretPos.moveStart("character", -text2.length);
			caretPos.moveEnd("character", -text2.length);
			caretPos.select();
		}
		else
			textarea.focus(caretPos);
	}
	// Mozilla text range wrap.
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var selection = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var newCursorPos = textarea.selectionStart;
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text1 + selection + text2 + end;

		if (textarea.setSelectionRange)
		{
			if (selection.length == 0)
				textarea.setSelectionRange(newCursorPos + text1.length, newCursorPos + text1.length);
			else
				textarea.setSelectionRange(newCursorPos, newCursorPos + text1.length + selection.length + text2.length);
			textarea.focus();
		}
		textarea.scrollTop = scrollPos;
	}
	// Just put them on the end, then.
	else
	{
		textarea.value += text1 + text2;
		textarea.focus(textarea.value.length - 1);
	}
}

// Couple of cookie functions I nicked from the net that need replacing.

function setCookie(name, value)
{
	if(name != '')
		document.cookie = name + '=' + value+ '; path=/';
}

function getCookie(name)
{
	if(name == '')
		return('');

	name_index = document.cookie.indexOf(name + '=');

	if(name_index == -1)
		return('');

	cookie_value =  document.cookie.substr(name_index + name.length + 1, 
										   document.cookie.length);

	end_of_cookie = cookie_value.indexOf(';');
	if(end_of_cookie != -1)
	cookie_value = cookie_value.substr(0, end_of_cookie);

	space = cookie_value.indexOf('+');
	while(space != -1)
	{ 
		cookie_value = cookie_value.substr(0, space) + ' ' + 
		cookie_value.substr(space + 1, cookie_value.length);		 
		space = cookie_value.indexOf('+');
	}

	return(cookie_value);
}

function clearCookie(name)
{                  
	expires = new Date();
	expires.setYear(expires.getYear() - 1);
	document.cookie = name + '=null' + '; expires=' + expires; 		 
}
         
function clearCookies()
{
	Cookies = document.cookie;
	Cookie = Cookies;
	expires = new Date();
	expires.setYear(expires.getYear() - 1);

	while(Cookie.length > 0)
	{
		Cookie = Cookies.substr(0, Cookies.indexOf(';'));
		Cookies = Cookies.substr(Cookies.indexOf(';') + 1, Cookies.length);
	
		if(Cookie != '')
			document.cookie = Cookie + '; expires=' + expires;
		else
			document.cookie = Cookies + '; expires=' + expires;			  			  	  
	}		 		 
}

// Gets the position of an element relative to the page.
function GetElementGlobalPosition(obj) 
{
	var curLeft = obj.offsetLeft;
	var curTop = obj.offsetTop;	
	if (obj.offsetParent) 
	{
		while (obj = obj.offsetParent) 
		{
			curLeft += obj.offsetLeft;
			curTop += obj.offsetTop;
		} 
	}
	return [curLeft, curTop];
}

// Calculates a passwords strength on a scale between
// 0 to 100, the highest being the most strong.
function CalculatePasswordStrength(password)
{
	var points = 0.0;
	var maxPoints = 6.0;
	
	var lowerCase = "abcdefghijklmnopqrstuvwxyz";
	var upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var numbers = "0123456789";
	var punctuation = "¬!\"£$%^&*()_+-=`¦{}[]:@~;'#<>?,./|\\";

	// Has it got lowercase?
	if (contains(password, lowerCase) > 0)
		points++;

	// Has it got uppercase?
	if (contains(password, upperCase) > 0)
		points++;
	
	// Has it got a number?
	if (contains(password, numbers) > 0)
		points++;

	// Has it got punctuation?
	if (contains(password, punctuation) > 0)
		points++;

	// Is it longer than 8?
	if (password.length > 8)
		points++;
	
	// Is it longer than 10?
	if (password.length > 10)
		points++;
	
	return (points / maxPoints) * 100.0;
}

// Handy function, simply asks the user to confirm an operation, if true, the user will be directed to the given url.
function ConfirmURL($reason, $url)
{
	if (confirm($reason))
		window.location = $url;
}

// Returns the number of milliseconds since the epoch.
function GetTickCount()
{
	return (new Date().getTime());
}

// Both of these stolen from the web, can't be arsed to write them myself. Thanks to the author :).
function URLEncode (clearString) 
{
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function URLDecode (encodedString) 
{
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}

function isValidEmail(str) 
{
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function isAlphaNumeric(alphane)
{
	var numaric = alphane;
	for(var j=0; j<numaric.length; j++)
	{
		var alphaa = numaric.charAt(j);
		var hh = alphaa.charCodeAt(0);
		if(!((hh > 47 && hh<58) || (hh > 64 && hh<91) || (hh > 96 && hh<123)))
			return false;
	}
	return true;
}

function isValidIP(inputString)
{
	var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;

	if (re.test(inputString)) 
	{
		var parts = inputString.split(".");
		if (parseInt(parseFloat(parts[0])) == 0) 
		{
			return false;
		}
		for (var i=0; i<parts.length; i++) 
		{
			if (parseInt(parseFloat(parts[i])) > 255) 
			{
				return false;
			}
		}
		return true;
	}
	else 
	{
		return false;
	}
}

function IsValidDomain(nname)
{
	var arr = new Array(
	'.com','.net','.org','.biz','.coop','.info','.museum','.name',
	'.pro','.edu','.gov','.int','.mil','.ac','.ad','.ae','.af','.ag',
	'.ai','.al','.am','.an','.ao','.aq','.ar','.as','.at','.au','.aw',
	'.az','.ba','.bb','.bd','.be','.bf','.bg','.bh','.bi','.bj','.bm',
	'.bn','.bo','.br','.bs','.bt','.bv','.bw','.by','.bz','.ca','.cc',
	'.cd','.cf','.cg','.ch','.ci','.ck','.cl','.cm','.cn','.co','.cr',
	'.cu','.cv','.cx','.cy','.cz','.de','.dj','.dk','.dm','.do','.dz',
	'.ec','.ee','.eg','.eh','.er','.es','.et','.fi','.fj','.fk','.fm',
	'.fo','.fr','.ga','.gd','.ge','.gf','.gg','.gh','.gi','.gl','.gm',
	'.gn','.gp','.gq','.gr','.gs','.gt','.gu','.gv','.gy','.hk','.hm',
	'.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.io','.iq',
	'.ir','.is','.it','.je','.jm','.jo','.jp','.ke','.kg','.kh','.ki',
	'.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li',
	'.lk','.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.mg',
	'.mh','.mk','.ml','.mm','.mn','.mo','.mp','.mq','.mr','.ms','.mt',
	'.mu','.mv','.mw','.mx','.my','.mz','.na','.nc','.ne','.nf','.ng',
	'.ni','.nl','.no','.np','.nr','.nu','.nz','.om','.pa','.pe','.pf',
	'.pg','.ph','.pk','.pl','.pm','.pn','.pr','.ps','.pt','.pw','.py',
	'.qa','.re','.ro','.rw','.ru','.sa','.sb','.sc','.sd','.se','.sg',
	'.sh','.si','.sj','.sk','.sl','.sm','.sn','.so','.sr','.st','.sv',
	'.sy','.sz','.tc','.td','.tf','.tg','.th','.tj','.tk','.tm','.tn',
	'.to','.tp','.tr','.tt','.tv','.tw','.tz','.ua','.ug','.uk','.um',
	'.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu','.ws',
	'.wf','.ye','.yt','.yu','.za','.zm','.zw');

	var mai = nname;
	var val = true;

	var dot = mai.lastIndexOf(".");
	var dname = mai.substring(0,dot);
	var ext = mai.substring(dot,mai.length);

	if(dot > 2 && dot < 57)
	{
		for(var i = 0; i < arr.length; i++)
		{
			if(ext == arr[i])
			{
				val = true;
				break;
			}	
			else
				val = false;
		}
		if(val == false)
			return false;
		else
		{
			for(var j = 0; j < dname.length; j++)
			{
				var dh = dname.charAt(j);
				var hh = dh.charCodeAt(0);
				if((hh > 47 && hh < 59) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123) || hh == 45 || hh == 46)
				{
					if((j == 0 || j == dname.length-1) && hh == 45)	
						return false;
				}
				else	
					return false;
			}
		}
	}
	else
		return false;

	return true;
}

function ScrollToElement(theElement)
{
  var selectedPosX = 0;
  var selectedPosY = 0;
              
  while(theElement != null)
  {
    selectedPosX += theElement.offsetLeft;
    selectedPosY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }
                        		      
  window.scrollTo(selectedPosX,selectedPosY);
}


function rawurlencode( str ) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Michael Grier
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: rawurlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin%20van%20Zonneveld%21'
    // *     example 2: rawurlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: rawurlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
 
    var histogram = {}, unicodeStr='', hexEscStr='';
    var ret = str.toString();
 
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
 
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A'; 
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';
 
 
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
 
    for (unicodeStr in histogram) {
        hexEscStr = histogram[unicodeStr];
        ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing
    }
 
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
}

function rawurldecode( str ) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: rawurldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin+van+Zonneveld!'
    // *     example 2: rawurldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: rawurldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    // *     example 4: rawurldecode('-22%97bc%2Fbc');
    // *     returns 4: '-22—bc/bc'
 
    var histogram = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
 
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
 
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
 
 
    for (unicodeStr in histogram) {
        hexEscStr = histogram[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
 
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = ret.replace(/%([a-fA-F][0-9a-fA-F])/g, function (all, hex) {return String.fromCharCode('0x'+hex);}); // These Latin-B have the same values in Unicode, so we can convert them like this
    ret = decodeURIComponent(ret);
 
    return ret;
}

function in_array(needle, haystack, argStrict) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
 
    var key = '', strict = !!argStrict;
 
    if (strict) 
	{
        for (key in haystack) 
		{
            if (haystack[key] === needle) 
			{
                return true;
            }
        }
    } 
	else 
	{
        for (key in haystack) 
		{
            if (haystack[key] == needle) 
			{
                return true;
            }
        }
    }
 
    return false;
}

// Replaces all instances of the given substring.
String.prototype.replaceAll = function( 
	strTarget, // The substring you want to replace
	strSubString // The string you want to replace in.
	){
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );
	 
	// Keep looping while an instance of the target string
	// still exists in the string.
	while (intIndexOfMatch != -1){
		// Relace out the current instance.
		strText = strText.replace( strTarget, strSubString )
		 
		// Get the index of any next matching substring.
		intIndexOfMatch = strText.indexOf( strTarget );
	}
	 
	// Return the updated string with ALL the target strings
	// replaced out with the new substring.
	return( strText );
}

Array.prototype.removeItems = function(itemsToRemove) 
{
    if (!/Array/.test(itemsToRemove.constructor)) 
	{
        itemsToRemove = [ itemsToRemove ];
    }

    var j;
    for (var i = 0; i < itemsToRemove.length; i++) 
	{
        j = 0;
        while (j < this.length) 
		{
            if (this[j] == itemsToRemove[i]) 
			{
                this.splice(j, 1);
            } 
			else 
			{
                j++;
            }
        }
    }
}


Array.prototype.contains = function (element) 
{
	for (var i = 0; i < this.length; i++) 
	{
		if (this[i] == element) 
		{
		return true;
		}
	}
	return false;
}

var OnLoadFunctions = new Array();

window.onload = function(e)
{
	for (var i = 0; i < OnLoadFunctions.length; i++)
		eval(OnLoadFunctions[i]);
}
