// JavaScript Document utilities.js
// gE(id) replaces document.getElementById('id') 
function gE(id) {return document.getElementById(id)}
// darkens the screen with createLightBox function
function createDim(alpha){
	if(!alpha) alpha = 20; 
	if(isDOM('dim')) document.body.removeChild(gE('dim'));
	var dim = document.createElement('div');
	dim.id = 'dim';
	dim.className = 'dim';
	(typeof dim.style.filter != 'undefined') ? dim.style.filter = 'alpha(opacity='+alpha+')' : dim.style.opacity = alpha/100;
	(document.body.firstChild) ? document.body.insertBefore(dim, document.body.firstChild) : document.body.appendChild(dim);
	if(typeof clearDeleteOverlayTimer == 'undefined'){
		addAnEvent(dim, 'mousedown', deleteLightBox);
	}else{
		addAnEvent(dim, 'mousedown', deleteOverlay);
		addAnEvent(dim, 'mouseover', clearDeleteOverlayTimer);
	}
}

var lightboxHTML = null;

// creates overlay with dimmed screen
function createLightBox(path, type, w, h, center, id, vars, dimAmount, closeButton)
{
	createDim(dimAmount);
	var max_w = (w)? w : 500;
	var max_h = (h)? h : 500;

	//create lightBox container
	var lb = document.createElement('div');
		lb.id = 'lightbox';
		lb.styleName = 'lightbox';

	if(lightboxHTML == null) lightboxHTML = loadContent('/plugins/pages/inv/components/lightbox.jsp', true);
	lb.innerHTML = lightboxHTML;	

	document.body.appendChild(lb);
	
	var close_btn = gE('lb-close');
	var closeImg = gE('close-button');
	var content = gE('lb-content');

	close_btn.style.display = (close_btn)? 'block' : 'none'; 
	if(BrowserDetect.browser == "Explorer" && BrowserDetect.version == "6") closeImg.src = "/plugins/images/inv/default/close.gif";
  
	if (path) {
		switch(type) {
			case 'iframe' :
				var frame = document.createElement('iframe');
				  frame.id = id;
					frame.width = max_w;
					frame.height = max_h;
					frame.scrolling = 'auto';
					frame.style.border = 'none';
					frame.frameBorder = '0';
					frame.marginHeight = '0';
					frame.marginWidth = '0';
					frame.src = path;
				  content.appendChild(frame);
				  frame.focus();
			break;
			case 'img' :
				content.innerHTML = '<img src="' + path + '" onclick="deleteLightBox(); return false;" />';
			break;
			case 'swf' :
				var swfVars = []
					swfVars['width'] = w;
					swfVars['height'] = h;

				attachSWF(path, id, swfVars, content);
			break;
			default :
				loadContent(path, false, content);
		}
	}

	scroll(0,0);   //INV-547

	centerTarget(lb, w , h);
}

function deleteLightBox(){
	var lb = gE('lightbox');
	var dim = gE('dim');
	if(lb){
		document.body.removeChild(lb);
	}
	if(dim) document.body.removeChild(dim);
}

// centers any target by id or object
function centerTarget(target, w, h){
	var scrollValues = scrollOffset();
	var clientValues = getClientSize();
	target = (typeof target == 'object')? target : gE(target);
	if(w)target.style.left = Math.abs(clientValues[0] - w) / 2 + scrollValues[0] + 'px';
	if(h)target.style.top = Math.abs(clientValues[1] - h) / 2 + scrollValues[1] + 'px';
}

function getClientSize(){
	var w = 0, h = 0;

	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		w = window.innerWidth;
		h = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		w = document.body.clientWidth;
		h = document.body.clientHeight;
	}
	arrayClientSize = [w,h];
	return arrayClientSize;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		
		return [curleft,curtop];
	}
}
// shortcut for array contains
function aHas(array, arrayValue){
	if(array && arrayValue){
	  for(var j=0; j < array.length; j++) if(array[j] == arrayValue)return true;
	  return false;
	}
}
// unique(array) removes all non-unique array members
function unique(array){
	var tmp = new Array(0);
	for(var i=0; i < array.length; i++){
		if(!contains(tmp, array[i])){
			tmp.length += 1;
			tmp[tmp.length - 1] = array[i];
		}
	}
	return tmp;
}
// setFieldValue(whichField, newValue) whichField can be an id or an object
function setFieldValue(whichField, newValue){(typeof whichField == 'object')? whichField.value = newValue : gE(whichField).value = newValue;}
// getFieldValue(whichField) whichField can be an id or an object
function getFieldValue(whichField){
  returnValue = (typeof whichField == 'object')? whichField.value : gE(whichField).value;
	return returnValue;
}
// dimTextArray(theArray, cssValue) takes an array and sets the text to be the color of the second parameter
function dimTextArray(theArray, cssValue){for(var t=0;t<theArray.length;t++)document.getElementById(theArray[t]).style.color = cssValue;}
// Parses JSON Objects
function parseJson(jsonText){if(jsonText)return eval('(' + jsonText + ')');}
// QueryString(key) is used with QueryString_parse()
QueryString.keys = []; 
QueryString.values = [];
function QueryString(key){ 
	var value = null; 
	for (var i=0;i<QueryString.keys.length;i++) { 
		if (QueryString.keys[i]==key){ 
		value = QueryString.values[i]; 
		return value;
		}
	}
	return null;
} 
// Used with QueryString(key) like this QueryString('debug'); returns value of that param or null
function QueryString_parse(){ 
	var query = window.location.search.substring(1); 
	var pairs = query.split("&"); 
	for (var i=0;i<pairs.length;i++){ 
		var pos = pairs[i].indexOf('='); 
		if (pos >= 0){
			var argname = pairs[i].substring(0,pos); 
			var value = pairs[i].substring(pos+1); 
			QueryString.keys[QueryString.keys.length] = argname.toLowerCase(); 
			QueryString.values[QueryString.values.length] = value; 
		} 
	}
}
// attatches events regardless of browser
function addAnEvent(el, evname, func) {(el.attachEvent)?el.attachEvent("on" + evname, func):(el.addEventListener)?el.addEventListener(evname, func, true):el["on" + evname] = func;}
// returns userAgent
function getUserAgent(){return navigator.userAgent;}
// dims any id to a certain alpha and 
function dimObject(elem, alpha){
	if(elem) {
		if(navigator.userAgent.match('MSIE')){
			elem.style.cursor = (alpha==100)?'pointer':'default';
			elem.style.filter = 'alpha(opacity=' + alpha + ')';
		}else{
			alpha = (alpha/100);
			elem.style.cursor = (alpha==1)? 'pointer':'default';
			elem.style.opacity = alpha;
		}
	}
}

function display(id, _display){gE(id).style.display = _display;}

function rowClass(id, _class) {gE(id).className = _class;}

function scrollOffset(){
  var x, y;
  if (self.pageYOffset) {
    // all except Explorer
    x = self.pageXOffset;
    y = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {
    // Explorer 6 Strict
    x = document.documentElement.scrollLeft;
    y = document.documentElement.scrollTop;
  } else if (document.body) {
    // all other Explorers
    x = document.body.scrollLeft;
    y = document.body.scrollTop;
  }
  if (!x) x = 0;
  if (!y) y = 0;
  arrayScrollOffset = [x,y];
  return arrayScrollOffset;
}

/*/ Omniture code implemented by DJ Watson /*/
function omnitureClickTrack(target, linkName) {
	s.tl(target,'o',linkName);
}

function popup (url, target, width, height, options) {
	var _options = options + ",width=" + width + ",height=" + height;
	var top = (screen.height/2)-(height/2);
	var left = (screen.width/2)-(width/2);
	_options += ",top=" + top + ",left=" + left;
	var popupWindow = window.open(url, target, _options);
}

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 ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	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() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
		
	//console.log(name, value, expires, path, domain, secure);
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function CheckLink(e){
    var url = null;
    if (e) {
        if(e.type == 'click'
        && e.target.tagName == 'A') {
            url = e.target.href;
        }
    }
    else {
        if(event.type == 'click'
        && event.srcElement.tagName == 'A') {
            url = event.srcElement.href;
        }
    }
    if (url) console.log("Target URL = "+url);
    return true;
}

function toCamelCase(str){
	var arr = str.replace("_"," ");
	arr = str.split(" ");
	var returnStr = "";
	for(var i = 0; i<arr.length; i++){
		arr[i] = arr[i].substr(0,1).toUpperCase() + arr[i].substr(1,arr[i].length);
	}
	return arr.join(" ");	
}
