/**
 * includes/javascript.js
 * Common Javascript functions
 *
 * author    Mark Fullbrook <mark.fullbrook@niddocks.com>
 * copyright 2006 Niddocks Ltd, UK.
 */

function DoCookieTest()
{
	params = GetParameters();
	if (TestCookies() == false)	 {
		if (params.npfAction == 'login' && params.page == 'detector') {
			document.getElementById('result_cookies').src = '/images/cross.gif';
		} else {
			window.location = 'index.php?npfAction=login&page=detector';
		}
	}
}

function openUrl(url)
{
	window.location = url;
}

function openURL(url)
{
	window.location = url;
}

// paramters = url, name, features
function openWindow()
{
	if (arguments.length == 3)
		handle = window.open(arguments[0], arguments[1], arguments[2]);
	else if (arguments.length == 2)
		handle = window.open(arguments[0], arguments[1]);
	else
		handle = window.open(arguments[0]);
	return handle;
}

function confirmURL(url, message)
{
	if (confirm(message)) openURL(url);	
}

function confirmDeleteItems(collection)
{
	var count = 0;
	if (collection.tagName == null) {
		// collection
		for (var i=0; i<collection.length; i++) count += collection[i].checked;
	} else {
		// single input check box
		if (collection.checked) count++;
	}
	if (count == 0) {
		alert('You have not ticked any items to delete.');
		return false;
	} else {
		return confirm('Are you sure you want to delete the selected items?');
	}
}


function GetParameters()
{
    var query=this.location.search.substring(1);
	var pos, name, value;
	var get = new Object();
    if (query.length > 0)
	{
        var params=query.split("&");
        for (var i=0 ; i<params.length ; i++)
		{
			pos = params[i].indexOf("=");
			name = params[i].substring(0, pos);
			value = params[i].substring(pos + 1);
			get[name] = value;
		}
	}
	return get;
}

/**
 * DOM Functions
 */
function removeChildNodes(obj)
{
	if (obj.hasChildNodes())
	{
		for (var x=0; x<obj.childNodes.length; x++)
		{
			obj.removeChild( obj.childNodes[x] );
		}
	}
}


/**
 * IE6 Box Model Fixing Functions
 * Uses arrMarginFixes variable, should be coded in application specific
 * javascript include or HTML head
 */
function ie6BoxModelFixer()
{
	// get the tables, divs and fieldset, and put together in an array
	var objects1 = convertHtmlCollectionArray(document.getElementsByTagName('TABLE'));
	var objects2 = convertHtmlCollectionArray(document.getElementsByTagName('DIV'));
	var objects3 = convertHtmlCollectionArray(document.getElementsByTagName('FIELDSET'));
	var objects = objects1.concat(objects2, objects3);
	
	var obj, classes, i, j, pos, oldClass, newClass;
	var parent, newdiv;
	
	for (i in objects)
	{
		obj = objects[i];
		if (typeof(obj) == 'object')
		{
			if (obj.className.length)
			{
				classes = obj.className.split(" ");
				for (j in arrMarginFixes)
				{
					oldClass = arrMarginFixes[j][0];
					newClass = arrMarginFixes[j][1];
				
					pos = classes.indexOf(oldClass);
					if (pos > -1)
					{
						classes[pos] = null;
						obj.className = classes.join(' ');
						parent = obj.parentNode;
						newdiv = document.createElement("DIV");
						newdiv.className = newClass;
						parent.insertBefore(newdiv, obj);
						newdiv.appendChild(obj);
					}
				}
			}
		}
	}
}

/**
 * Will take and HTML object collection and return the real objects as an array
 */
function convertHtmlCollectionArray(coll)
{
	var arrReturn = new Array();
	for (i in coll) {
		if (typeof(coll[i]) == 'object') {
			arrReturn.push(coll[i]);
		}
	}
	return arrReturn;
}


function copySelectValue(selObj, txtObj)
{
	var val = selObj.options[ selObj.selectedIndex ].value;
	txtObj.value = val;
}


/**
 * Overload the Array object with some methods
 */
// Array.indexOf( value, begin, strict ) - Return index of the first element that matches value
Array.prototype.indexOf = function( v, b, s )
{
	for( var i = +b || 0, l = this.length; i < l; i++ ) {
		if( this[i]===v || s && this[i]==v ) { return i; }
	}
	return -1;
};

// Array.unique( strict ) - Remove duplicate values
Array.prototype.unique = function( b )
{
	var a = [], i, l = this.length;
	for( i=0; i<l; i++ ) {
		if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
	}
	return a;
};


/**
 * Takes a form and builds an object containing all the key/value
 * pairs created by the form
 */
function getPayload(frm)
{
	var payload = new Object();
	for(var i = 0; i < frm.elements.length; i++) {
		if (frm.elements[i].name) {
			payload[frm.elements[i].name] = frm.elements[i].value;
		}
	}
	return payload;
}


/**
 * HTML Select Object functions
 */
function selectClearOptions(refSelect)
{
	while (refSelect.options.length > 0) { refSelect.options[0] = null; }
}


/**
 * Simulates the number_format function in php
 * @see http://mathiasbynens.be/archive/2006/01/js-number-format
 */
function number_format(a, b)
{
	// number_format(number, decimals, decimal_sep, thous_sep)
	c = arguments[2]!=null ? arguments[2] : '.';
	d = arguments[3]!=null ? arguments[3] : ',';
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if(!f[0]) f[0] = '0';
	if(!f[1]) f[1] = '';
	if(f[1].length < b){
		g = f[1];
		for(i = f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j += 3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '': c;
	return f[0] + c + f[1];
}

//////////////////////////////////////////////////////////////////////////////////////////
//*** This code is copyright 2003 by Gavin Kistner, gavin@refinery.com
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
//***Cross browser attach event function. For 'evt' pass a string value with the leading "on" omitted
//***e.g. AttachEvent(window,'load',MyFunctionNameWithoutParenthesis,false);

function AttachEvent(obj,evt,fnc,useCapture){
	if (!useCapture) useCapture=false;
	if (obj.addEventListener){
		obj.addEventListener(evt,fnc,useCapture);
		return true;
	} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
	else{
		MyAttachEvent(obj,evt,fnc);
		obj['on'+evt]=function(){ MyFireEvent(obj,evt) };
	}
} 

//The following are for browsers like NS4 or IE5Mac which don't support either
//attachEvent or addEventListener
function MyAttachEvent(obj,evt,fnc){
	if (!obj.myEvents) obj.myEvents={};
	if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
	var evts = obj.myEvents[evt];
	evts[evts.length]=fnc;
}
function MyFireEvent(obj,evt){
	if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
	var evts = obj.myEvents[evt];
	for (var i=0,len=evts.length;i<len;i++) evts[i]();
}
//////////////////////////////////////////////////////////////////////////////////////////
