// preloads
var preload_1 = new Image();
	preload_1.src = html_root+"images/photo/button_on.png";
var preload_2 = new Image();
	preload_2.src = html_root+"images/web/button_on.png";
var preload_3 = new Image();
	preload_3.src = html_root+"images/dvd/button_on.png";
var preload_4 = new Image();
	preload_4.src = html_root+"images/photo/button_off.png";
var preload_5 = new Image();
	preload_5.src = html_root+"images/web/button_off.png";
var preload_6 = new Image();
	preload_6.src = html_root+"images/dvd/button_off.png";
var preload_7 = new Image();
	preload_7.src = html_root+"images/photo/events/overlay_loading.gif";
var preload_8 = new Image();
	preload_8.src = html_root+"images/layout/loading.gif";
var preload_9 = new Image();
	preload_9.src = html_root+"images/layout/loading_small.gif";

function rowhover_on(row_id){
	row_object = document.getElementById(row_id);
	row_object.className+=" row_hover";
}

function rowhover_off(row_id){
	row_object = document.getElementById(row_id);
	row_object.className=row_object.className.replace("row_hover","");
}

function clearField(oVal,oId){
	if(oId=="login_password"){
		oIdcheck = document.getElementById(oId).value;
		if(oVal==oIdcheck){
			document.getElementById(oId).type = "password";
			document.getElementById(oId).value = "";
		}
	} else {
		oIdcheck = document.getElementById(oId).value;
		if(oVal==oIdcheck){
			document.getElementById(oId).value = "";
		}
	}
}

function toggle_table_notes(table_idstring){
	if(document.getElementById(table_idstring+"_extra").style.display=="table-row"){
		document.getElementById(table_idstring+"_extra").style.display="none";
		document.getElementById(table_idstring+"_add").style.display="";
		document.getElementById(table_idstring+"_hide").style.display="none";
	} else {
		document.getElementById(table_idstring+"_extra").style.display="table-row";
		document.getElementById(table_idstring+"_add").style.display="none";
		document.getElementById(table_idstring+"_hide").style.display="";
	}
}

var tnum = 0;
var timeOuts = new Array();
function timeEffect(tId, tLength, tFps, tValue, tInitial, tFinal, tPrefix, tSuffix, tMod){
	tTotalFrames = Math.floor(parseInt(tFps)*parseInt(tLength)/1000);
	tChange = (parseInt(tFinal)-parseInt(tInitial))/tTotalFrames;
	tFrameLength = Math.floor(parseInt(tLength)/parseInt(tTotalFrames));
	for(i=0;i<=tTotalFrames;i++){
		timeOuts[tnum]=window.setTimeout("document.getElementById('"+tId+"')."+tValue+"='"+tPrefix+parseInt(parseInt(tInitial)+(i*parseInt(tChange)))+tSuffix+"';",tMod+parseInt(i*parseInt(tFrameLength)));
		tnum ++;
	}
	timeOuts[tnum]=window.setTimeout("document.getElementById('"+tId+"')."+tValue+"='"+tPrefix+tFinal+tSuffix+"';",tMod+parseInt(tTotalFrames*parseInt(tFrameLength)));
	tnum ++;
}


function imgToggle(img_target){
	var oImg = document.getElementById(img_target);
	var strOver  = "_on"
	var strOff = "_off"
	var strImg = oImg.src
	if(strImg.indexOf(strOver) != -1){ 
		oImg.src = strImg.replace(strOver,strOff);
	} else {
		oImg.src = strImg.replace(strOff,strOver);
	}
}

function toggleDrawer(drawer_id,toggle_id,toggle_text){
	drawer_status = document.getElementById(drawer_id).style.display;
	if(drawer_status=="none"){
		document.getElementById(drawer_id).style.display = "";
		document.getElementById(toggle_id).innerHTML = "Hide "+toggle_text;
	} else {
		document.getElementById(drawer_id).style.display = "none";
		document.getElementById(toggle_id).innerHTML = "Show "+toggle_text;
	}
}

// {{{ serialize
function serialize( inp ) {
    // Generates a storable representation of a value
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_serialize/
    // +       version: 804.1712
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'

    var getType = function( inp ) {
        var type = typeof inp, match;
        if(type == 'object' && !inp)
        {
            return 'null';
        }
        if (type == "object") {
            if(!inp.constructor)
            {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };

    var type = getType(inp);
    var val;
    switch (type) {
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (inp ? "1" : "0");
            break;
        case "number":
            val = (Math.round(inp) == inp ? "i" : "d") + ":" + inp;
            break;
        case "string":
            val = "s:" + inp.length + ":\"" + inp + "\"";
            break;
        case "array":
            val = "a";
        case "object":
            if (type == "object") {
                var objname = inp.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            var count = 0;
            var vals = "";
            var okey;
            for (key in inp) {
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(inp[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}// }}}

// {{{ unserialize
function unserialize ( inp ) {
    // Creates a PHP value from a stored representation
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_unserialize/
    // +       version: 804.1712
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Pedro Tainha (http://www.pedrotainha.com)
    // *     example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
    // *     returns 1: ['Kevin', 'van', 'Zonneveld']

    error = 0;
    if (inp == "" || inp.length < 2) {
        errormsg = "input is too short";
        return;
    }
    var val, kret, vret, cval;
    var type = inp.charAt(0);
    var cont = inp.substring(2);
    var size = 0, divpos = 0, endcont = 0, rest = "", next = "";

    switch (type) {
    case "N": // null
        if (inp.charAt(1) != ";") {
            errormsg = "missing ; for null";
        }
        // leave val undefined
        rest = cont;
        break;
    case "b": // boolean
        if (!/[01];/.test(cont.substring(0,2))) {
            errormsg = "value not 0 or 1, or missing ; for boolean";
        }
        val = (cont.charAt(0) == "1");
        rest = cont.substring(2);  //changed...
        break;
    case "s": // string
        val = "";
        divpos = cont.indexOf(":");
        if (divpos == -1) {
            errormsg = "missing : for string";
            break;
        }
        size = parseInt(cont.substring(0, divpos));
        if (size == 0) {
            if (cont.length - divpos < 4) {
                errormsg = "string is too short";
                break;
            }
            rest = cont.substring(divpos + 4);
            break;
        }
        if ((cont.length - divpos - size) < 4) {
            errormsg = "string is too short";
            break;
        }
        if (cont.substring(divpos + 2 + size, divpos + 4 + size) != "\";") {
            errormsg = "string is too long, or missing \";";
        }
        val = cont.substring(divpos + 2, divpos + 2 + size);
        rest = cont.substring(divpos + 4 + size);
        break;
    case "i": // integer
    case "d": // float
        var dotfound = 0;
        for (var i = 0; i < cont.length; i++) {
            cval = cont.charAt(i);
            if (isNaN(parseInt(cval)) && !(type == "d" && cval == "." && !dotfound++)) {
                endcont = i;
                break;
            }
        }
        if (!endcont || cont.charAt(endcont) != ";") {
            errormsg = "missing or invalid value, or missing ; for int/float";
        }
        val = cont.substring(0, endcont);
        val = (type == "i" ? parseInt(val) : parseFloat(val));
        rest = cont.substring(endcont + 1);
        break;
    case "a": // array
        if (cont.length < 4) {
            errormsg = "array is too short";
            return;
        }
        divpos = cont.indexOf(":", 1);
        if (divpos == -1) {
            errormsg = "missing : for array";
            return;
        }
        size = parseInt(cont.substring(1*divpos, 0));  //changed...
        cont = cont.substring(divpos + 2);
        val = new Array();
        if (cont.length < 1) {
            errormsg = "array is too short";
            return;
        }
        for (var i = 0; i + 1 < size * 2; i += 2) {
            kret = unserialize(cont, 1);
            if (error || kret[0] == undefined || kret[1] == "") {
                errormsg = "missing or invalid key, or missing value for array";
                return;
            }
            vret = unserialize(kret[1], 1);
            if (error) {
                errormsg = "invalid value for array";
                return;
            }
            val[kret[0]] = vret[0];
            cont = vret[1];
        }
        if (cont.charAt(0) != "}") {
            errormsg = "missing ending }, or too many values for array";
            return;
        }
        rest = cont.substring(1);
        break;
    case "O": // object
        divpos = cont.indexOf(":");
        if (divpos == -1) {
            errormsg = "missing : for object";
            return;
        }
        size = parseInt(cont.substring(0, divpos));
        var objname = cont.substring(divpos + 2, divpos + 2 + size);
        if (cont.substring(divpos + 2 + size, divpos + 4 + size) != "\":") {
            errormsg = "object name is too long, or missing \":";
            return;
        }
        var objprops = unserialize("a:" + cont.substring(divpos + 4 + size), 1);
        if (error) {
            errormsg = "invalid object properties";
            return;
        }
        rest = objprops[1];
        var objout = "function " + objname + "(){";
        for (key in objprops[0]) {
            objout += "" + key + "=objprops[0]['" + key + "'];";
        }
        objout += "}val=new " + objname + "();";
        eval(objout);
        break;
    default:
        errormsg = "invalid input type";
    }
    return (arguments.length == 1 ? val : [val, rest]);
}// }}}


// ------------------------

function toggleSelects(action) {
    var selects = document.getElementsByTagName('select');
    if(action == 'hide') {
        for(i=0; i < selects.length; i++) {
            selects[i].style.display='none';
        }
    } else if(action == 'show') {
        for(i=0; i < selects.length; i++) {
            selects[i].style.display='';
        }
    }
}

// ------------------------

function getPageHeight() {
	// thanks to 
	// http://www.huddletogether.com/projects/lightbox2/js/lightbox.js
	// for this function which has been adapted below
	var yScroll;

	if (window.innerHeight && window.scrollMaxY) {	
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		yScroll = document.body.offsetHeight;
	}

	var windowHeight;

	if (self.innerHeight) {	// all except Explorer
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowHeight = document.body.clientHeight;
	}	

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	return pageHeight;
}

// ------------------------

function removeItems(array, item) {
    var i = 0;
    while (i < array.length) {
        if (array[i] == item) {
            array.splice(i, 1);
        } else {
            i++;
        }
    }
    return array;
}

// ------------------------

function getViewportHeight(){
    var viewportwidth;
    var viewportheight;
 
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    
    if (typeof window.innerWidth != 'undefined')
    {
        viewportwidth = window.innerWidth,
        viewportheight = window.innerHeight
    }
    
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    
    else if (typeof document.documentElement != 'undefined'
       && typeof document.documentElement.clientWidth !=
       'undefined' && document.documentElement.clientWidth != 0)
    {
         viewportwidth = document.documentElement.clientWidth,
         viewportheight = document.documentElement.clientHeight
    }
    
    // older versions of IE
    
    else
    {
         viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
         viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }
    return viewportheight;
}

// ------------------------

function array_search( needle, haystack, argStrict ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_search('zonneveld', {firstname: 'kevin', middle: 'van', surname: 'zonneveld'});
    // *     returns 1: 'surname'
 
    var strict = !!argStrict;
    var key = '';
 
    for(key in haystack){
        if( (strict && haystack[key] === needle) || (!strict && haystack[key] == needle) ){
            return key;
        }
    }
 
    return false;
}

// ------------------------

function print_r( array, return_val ) {
    // Prints out or returns information about the specified variable  
    // 
    // version: 906.801
    // discuss at: http://phpjs.org/functions/print_r
    // +   original by: Michael White (http://getsprink.com)
    // +   improved by: Ben Bryan
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +      improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: echo
    // *     example 1: print_r(1, true);
    // *     returns 1: 1
    
    var output = "", pad_char = " ", pad_val = 4, d = this.window.document;
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if(!name) {
            return '(Anonymous)';
        }
        return name[1];
    };

    var repeat_char = function (len, pad_char) {
        var str = "";
        for(var i=0; i < len; i++) {
            str += pad_char;
        }
        return str;
    };

    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if (cur_depth > 0) {
            cur_depth++;
        }

        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";

        if (typeof obj === 'object' && obj !== null && obj.constructor && getFuncName(obj.constructor) !== 'PHPJS_Resource') {
            str += "Array\n" + base_pad + "(\n";
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else if(obj === null || obj === undefined) {
            str = '';
        } else { // for our "resource" class
            str = obj.toString();
        }

        return str;
    };

    output = formatArray(array, 0, pad_val, pad_char);

    if (return_val !== true) {
        if (d.body) {
            this.echo(output);
        }
        else {
            try {
                d = XULDocument; // We're in XUL, so appending as plain text won't work; trigger an error out of XUL
                this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">'+output+'</pre>');
            }
            catch(e) {
                this.echo(output); // Outputting as plain text may work in some plain XML
            }
        }
        return true;
    } else {
        return output;
    }
}


// ------------------------

function ajaxFetch(urlString,force_type){
	if(!force_type){
		force_type = site_type;
	}
	/* ajax pages should return a serialized array of the form:
		
		Array(
			"status"=>123,
			"response"=>string
		)
		
		where status is an HTTP response code (eg, 401 not accessible, 404 not found [as in, function not found])
		and where response is a mixed var of the response data
	*/
	try{
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				alert("Error. Please contact the webmaster.");
				return false;
			}
		}
	}
	// make query
	ajax_path = html_root+"includes/"+force_type+"/ajax/";
	ajaxRequest.open("GET", ajax_path+urlString, false);
	ajaxRequest.send(null);
	if(ajaxRequest.status!=200){
		var failed_ajax = new Array();
			failed_ajax['status']="error";
			failed_ajax['response']="The ajax request returned a "+ajaxRequest.status+" error. Please contact the webmaster.";
		return failed_ajax;
	} else {
		// return var
		ajax_return = unserialize(ajaxRequest.responseText);
		if(ajax_return['status']=="success"){
			return ajax_return;
		} else {
			alert("Ajax Error: "+ajax_return['response']);
			return ajax_return['status'];
		}
	}
}

//-------------

function data_change(field){
    var check = true;
    var value = field.value; //get characters
    //check that all characters are digits, ., -, or ""
    for(var i=0;i < field.value.length; ++i)
    {
         var new_key = value.charAt(i); //cycle through characters
         if(((new_key < "0") || (new_key > "9")) && 
              !(new_key == ""))
         {
              check = false;
              break;
         }
    }
    //apply appropriate colour based on value
    if(!check)
    {
        field.value=0;
        alert("You can only use digits in this field.");
    }
}

//-----------------
function check_numerical_field(field){
	field=document.getElementById(field);
    var check = true;
    var value = field.value; //get characters
    //check that all characters are digits, ., -, or ""
    for(var i=0;i < field.value.length; ++i)
    {
         var new_key = value.charAt(i); //cycle through characters
         if(((new_key < "0") || (new_key > "9")) && 
              !(new_key == ""))
         {
              check = false;
              break;
         }
    }
    //apply appropriate colour based on value
    if(!check)
    {
    	return false;
    } else {
    	return true;
    }
}

//------------------------

function array_keys( input, search_value, argStrict ) {
    // Return just the keys from the input array, optionally only for the specified search_value  
    // 
    // version: 905.3122
    // discuss at: http://phpjs.org/functions/array_keys
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} );
    // *     returns 1: {0: 'firstname', 1: 'surname'}
    
    var tmp_arr = {}, strict = !!argStrict, include = true, cnt = 0;
    var key = '';
    
    for (key in input) {
        include = true;
        if (search_value != undefined) {
            if( strict && input[key] !== search_value ){
                include = false;
            } else if( input[key] != search_value ){
                include = false;
            }
        }
        
        if (include) {
            tmp_arr[cnt] = key;
            cnt++;
        }
    }
    
    return tmp_arr;
}

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

