/* #######################################################################
# mylib.js version 1.3b
#
# MyDB companion : general functions and object processing (Javascript)
# mylib.js Created at 08-03-2001
# Copyright Andrei Boros (C) 2001-2009
###########################################################################
#
#    This program may be used only with the website design and functionality
#    with which it was delivered.
#    Owner of said website may run the website and make use of this script
#    without other limitations, but only for that website.
#
#    This program may NOT be copied, sold, distributed in any way or modified.
#    Portions of this program, or the whole program may NOT be used for
#    other websites, as part of any other program using it or being derived
#    from it to any extent.
#
#    All of the above restrictions apply unless with written permission
#    from the author.
#
#    Websites based on this program may be used freely, however modifications
#    to the pages that use this program may only be done the author of this
#    program or by a another person with written permission from the author.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
#    Copyright Andrei Boros (C) 2001-2008
#
#    Signing key fingerprint :
#    C898 1B25 44BA 1E57 CA56  BAD3 D37D EDEF 9451 51E5
#
####################################################################### */

// ############## Basic ##################################################
// -----------------------------------------------------------------------
// DOM improvements

// Extend Array object with inArray method, returns true if value exists as one of the array elements
Array.prototype.inArray = function(value) {
  for (i = 0; i < this.length; i++) {
    if (this[i] === value) return true;
  }
  return false;
}

// DOM extension : insert node after a reference node
function insertAfter(parent, node, refNode) {
  if (refNode.nextSibling)
    parent.insertBefore(node, refNode.nextSibling);
  else
    parent.appendChild(node);
}

// Return an object or an array of objects
function $() {
    var elems = new Array();
    for (var i = 0; i < arguments.length; i++) {
        // For each argument passed to $()
        var elem = arguments[i];
        if (typeof elem == 'string')
            elem = document.getElementById(elem);
        if (arguments.length == 1)
            return elem;
        elems.push(elem);
    }
    return elems;
}
// Examples :
// var textbox = $('mytextbox');
// var images = $(objImage1, 'myimg', 'badimage', objImagePlaceHolder);

// DOM extension : return array of elements having given class
function getElementsByClass(findclass, node, tag) {
    var classElems = new Array();
    if (node == null)
        node = document;
    if (tag == null)
        tag = '*';
    var elems = node.getElementsByTagName(tag);
    var pattern = new RegExp('(^|\\\\s)'+finclass+'(\\\\s|$)');
    var j = 0;
    for (i = 0; i < elems.length; i++) {
        if (pattern.test(elems[i].className)) {
            classElems[j] = elems[i];
            j++;
        }
    }
    return classElems;
}
// Example :
// var foos = getElementsByClassName('foo', document, 'a');

// -----------------------------------------------------------------------
// Event handling

// Attach an event handler
function addEvent(obj, eventtype, functn, usecapture) {
    if (obj.addEventListener) {
        obj.addEventListener(eventtype, functn, usecapture);
        return true;
    } else if (obj.attachEvent) {
       return obj.attachEvent('on' + eventtype, functn);
    } else {
        obj['on' + eventtype] = functn;
        return true;
    }
}
// Example :
// addEvent(window, 'load', functn1, false);

// Remove an event handler
function delEvent(obj, eventtype, functn, usecapture) {
  if (obj.removeEventListener) {
    obj.removeEventListener(eventtype, functn, usecapture);
    return true;
  } else if (obj.detachEvent) {
    return obj.detachEvent('on'+eventtype, functn);
  } else {
    obj['on'+eventtype] = null;
    return true;
  }
}

//addEvent(window,'error',alertError,false);
//window.onerror=alertError;
// Error handler. Alert with debug output on JS errors
function alertError(msg,url,l) {
  var txt="There was an error on this page.\n\n";
  txt+="Error: " + msg + "\n";
  txt+="URL: " + url + "\n";
  txt+="Line: " + l + "\n\n";
  txt+="Click OK to continue.\n\n";
  alert(txt);
  return true;
}

// -----------------------------------------------------------------------
// Utilities

// Return a random integer
function randomRange(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Toggle visibility of an object
function toggle(objID) {
  var obj = document.getElementById(objID);
  if (obj && obj.style) {
    obj.style['display'] = (obj.style['display'] == 'none') ? '' : 'none';
  }
}

// replace special characters in URL strings
function escapeURL(url) {
   return encodeURIComponent(url);
}

// -----------------------------------------------------------------------
// Cookie handling

// Return the value of a cookie
function getCookie(name) {
    var start = document.cookie.indexOf(name + '=');
    var len = start + name.length + 1;
    if (!start && name != document.cookie.substring(0, name.length)) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf( ';', len );
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
}

// Set a cookie
function setCookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    if (expires)
        expires = expires * 1000 * 60 * 60 * 24;
    var expires_date = new Date(today.getTime() + expires);
    document.cookie = name + '=' + escape(value) +
        (expires ? ';expires=' + expires_date.toGMTString() : '') +
        (path ? ';path=' + path : '') +
        (domain ? ';domain=' + domain : '') +
        (secure ? ';secure' : '' );
}

// Delete a cookie (actually forcing it to expire)
function delCookie(name, path, domain) {
    if (getCookie(name))
        document.cookie = name + '=' +
        (path ? ';path=' + path : '') +
        (domain ? ';domain=' + domain : '') +
        ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

// ############ Browser ##################################################
//

// Return object named "n" in document "d" (optional)
// can identify objects in forms and will parse layers too.
function findObject(n, d) {
	var i,x;
	if(!d) {
		d=document;
	}
        // Object is a form element ? (we prefer form elements first)
	for (i=0; !x && i<d.forms.length; i++) {
		x = d.forms[i][n];
	}
// Browser mayhem : object may be inside a layer, so dive in
	for(i=0; !x && d.layers && i<d.layers.length; i++)
		x=findObject(n,d.layers[i].document);

        // standard way of getting an element
	if(!x && document.getElementById)
		x = document.getElementById(n);
// More browser mayhem
	if(!(x || x == d[n]) && d.all)
		x = d.all[n];
	return x;
}
// Dreamweaver compatibility
// Note: "f" is not used
function MM_findObj(n, d, f) {
        return findObject(n,d);
}

// Open a new browser window
// openBrowserWindow(window_url [, window_name, window_features, window_object])
// Returns the new window object reference.
// Set focus to window_name if it already exists (and reloads, but does not set features)
function openBrowserWindow() {
        var x, window_name, window_features, window_object;
        if (arguments.length-1 < 0 || arguments.length-1 > 3) { throw new Error("Invalid number of arguments ("+arguments.length+")"); }
        var window_url = arguments[0];
        if (arguments.length-1 >= 1) { window_name = arguments[1]; }
        if (window_name.indexOf(' ')>0) { throw new Error("Window name may not contain spaces!"); }
        window_name = window_name.value;
        if (arguments.length-1 >= 2) { window_features = arguments[2]; }
        if (arguments.length-1 == 3) {
            var window_object = arguments[3];
            if (window_object == null || window_object.closed) {
                   x = window.open(window_url, window_name, window_features);
                   if (!x) { throw new Error("Unable to open new browser window, possibly pop-up blocker?"); }
                   return x;
            } else {
                   window_object.location = window_url;
                   window_object.focus();
                   return window_object;
            }
        }  else {
            x = window.open(window_url, window_name, window_features);
            if (!x) { throw new Error("Unable to open new browser window, possibly pop-up blocker?"); }
            x.focus();
            return x;
        }
/*
Supported features:
* most browsers
- left, right, width, height, location
* most browsers, except Opera
- menubar, toolbar, directories, status, resizable, scrollbars
* Mozilla only
- screenX, screenY, centerscreen, outerHeight, outerWidth, innerHeight, innerWidth, personalbar, dependent,
dialog, minimizable, chrome, modal, titlebar, alwaysRaised, alwaysLowered, z-lock, close
* IE only
- fullscreen
*/
}
// Dreamweaver compatibility
function MM_openBrWindow(url,winName,features) {
	openBrowserWindow(url,winName,features);
}

// Set focus of object named "object_name"
function focusObject(object_name) {
  var obj = findObject(object_name);
  if (obj)
   obj.focus();
}
// Dreamweaver compatibility
function MM_focus(objName) {
   focusObject(objName)
}

// Dreamweaver compatibility
// Useless call to alert
function MM_popupMsg(msg) {
 alert(msg);
}

// ############ Content ##################################################

// -----------------------------------------------------------------------
// Rollover images
var preloadFlag = false;

// Introduce a new image into the DOM
function newImage(arg) {
	if (document.images) {
		var rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
	return null;
}

// Change the source of an image element (for rollover effect)
function changeImages() {
	if (document.images && (preloadFlag == true)) {
		for (var i=0; i<arguments.length; i+=2) {
			document[arguments[i]].src = arguments[i+1];
		}
	}
}

// Preload images for the rollover effect
function preloadImages() {
	if (document.images) {
    for (var i=0; i<arguments.length; i++) {
      var _image = newImage(arguments[i]);
    }
		preloadFlag = true;
	}
}

// encode a string using a random key and return both the key and encoded string
// use for encoded email links
function encodeEmail(_email) {
 var v1='',v2='',_rnd;
 for (var i=0; i<_email.length; i++) {
  v1+=String.fromCharCode(parseInt(randomRange(32,127)));
  v2+=String.fromCharCode(v1.charCodeAt(i)^_email.charCodeAt(i));
 }
 return encodeURIComponent(v1 + v2);
}

// decode a string encoded with encodeEmail(_email)
function decodeEmail(_code) {
  var _email='';
  var v1='';
  v1=decodeURIComponent(_code);
  if (v1.length%2 != 0) { throw new Error('Invalid encoded email ('+_code.length+'): '+_code); }
  for (var i=0; i<v1.length/2; i++) {
    _email+=String.fromCharCode(v1.charCodeAt(i)^v1.charCodeAt(v1.length/2+i));
  }
  return _email;
}

// generate an encoded email link (requires the use of encodeEmail(_email) to supply a valid code)
function decodeEmailLink(_code,_text,_subj) {
  var _email = decodeEmail(_code);
  if (_subj!='') { _subj = '?subject='+encodeURIComponent(_subj); }
  if (_text=='') { _text = _email; }
  document.write('<a href="javascript:;" onClick="window.location=\'mail'+'to:'+_email+_subj+'\'; return true;">'+_text+'</a>');
}

// Set property of an element
function setProperty(objID,_theProperty,_value) {
  var obj = document.getElementById(objID);
  if (obj) {
    obj[_theProperty]=_value;
  }
}

// Set style of an element, optionally to it's children as well
function setStyle(_obj,_style,_value,_children) {
  if (typeof _obj == 'string') { var obj = document.getElementById(_obj); } else { var obj=_obj; }
  if (obj && obj.style) {
    obj.style[_style]=_value;
  }
  if (_children == 1 && obj.hasChildNodes()) {
    var children = obj.childNodes;
    for (var i=0; i<children.length; i++) {
      if (children[i] && children[i].style) {
        children[i].style[_style]=_value;
      }
      setStyle(children[i],_style,_value,1);
    }
  }
}

// ########### Forms #####################################################
//

// Set the selected property of a drop down "obj1Name" to the item with same value as "obj2Name"
function setSelect(obj1Name,obj2Name) {
	var obj1 = findObject(obj1Name);
	var obj2 = findObject(obj2Name);
	var i;
	if (obj1 && obj1.type == 'select-one') {
		for (i=0; i<=obj1.length-1; i++) {
			if ( obj1.options[i].value==obj2.value ) {
				obj1.selectedIndex=i;
				break;
			}
		}
	}
}

// Set the checked property of radio group "obj1Name" to the item with same value as "obj2Name"
function setRadio(obj1Name,obj2Name) {
	var obj1 = findObject(obj1Name);
	var obj2 = findObject(obj2Name);
	var i;
	if (obj1 && obj1.type == 'radio' && obj1.value==obj2.value) {
		obj1.checked=true;
	}
	if (obj1 && obj1[0].type == 'radio') {
		for (i=0; i<=obj1.length-1; i++) {
			if ( obj1[i].value==obj2.value ) {
				obj1[i].checked=true;
				break;
			}
		}
	}
}

// Set the checked property of a checkbox group "obj1Name" to the item with same value as "obj2Name"
function setCheckbox(obj1Name,obj2Name) {
	var obj1 = findObject(obj1Name);
	var obj2 = findObject(obj2Name);
	var i;
	if (obj1 && obj1.type == 'checkbox' && obj1.value==obj2.value) {
		obj1.checked=true;
	}
	if (obj1 && obj1[0].type == 'checkbox') {
		for (i=0; i<=obj1.length-1; i++) {
			if ( obj1[i].value==obj2.value ) {
				obj1[i].checked=true;
				break;
			}
		}
	}
}

