/* 
	Library: Gainsborough - web client framework
	Component: common functions
	
	Hextra Digital 
	http://www.hextra-digital.com
*/

// Cross-browser implementation of element.addEventListener()
function addListener( element, type, expression, bubbling ){
	bubbling = bubbling || false;
	if( window.addEventListener ) { // Standard
		element.addEventListener( type, expression, bubbling );
		return true;
	} else if( window.attachEvent ) { // IE
		element.attachEvent( 'on' + type, expression );
		return true;
	} else return false;
}

function hx_image_preloader( _img_src, _callback, _notify ) {
	this.source		= _img_src;
	this.notify		= '';
	this.notifyID	= _notify;
	this.callback	= _callback;
	this.notify		= ge( this.notifyID );	

	re( this.notify, '<img style="margin-right: .5em" src="images/circle_ball.gif />Retrieving image...' );
};

hx_image_preloader.prototype.load = function() {	
	var img 			= new Image;	
	img.onload 			= hx_image_preloader.prototype.imageLoaded;
	img.onerror 		= hx_image_preloader.prototype.imageError;
	img.parent			= this;
	img.src 			= this.source;
};

hx_image_preloader.prototype.imageError = function() {
	re( this.notify, '<strong>Error</strong>' );
	img = null;
};

hx_image_preloader.prototype.imageLoaded = function() {
	this.parent.imageCompleted();
	if( this.parent.callback ) this.parent.callback ( this );
};

hx_image_preloader.prototype.imageCompleted = function() {
	re( this.notify, '' );
	img = null;
};

function cursor_wait()  {
	var cursor = 
	document.layers ? document.cursor :
	document.all ? document.all.cursor :
	document.getElementById ? document.getElementById( 'cursor' ) : null;

	if( cursor ) cursor = 'wait';
};

function cursor_clear() {
	var cursor = 
	document.layers ? document.cursor :
	document.all ? document.all.cursor :
	document.getElementById ? document.getElementById( 'cursor' ) : null;

	if( cursor ) cursor = 'default';
};

/*
	ge( _id ) - useful shortword for getElementById
*/
function ge( _id ) {
    var obj;
    if( document.getElementById ) {
        obj = document.getElementById( _id );
    }else if( document.all ) {
        obj = document.all[ _id ];
    }else if( document.layers ) {
        obj = document.layers[ _id ];
    }
    return obj || null;
};

/*
	gd( xml, node ) - useful shortword for getElementById
*/
function gd( xml, node ) {
    if( !xml ) return '';
    var x = xml.getElementsByTagName( node );
    if( !x ) return '';
    if( !x[ 0 ] ) return '';
    if( !x[ 0 ].firstChild ) return '';
    return x[ 0 ].firstChild.data;    
};

/*
	gds( xml, node ) - useful shortword for getElementsByTagName
*/
function gds( _xml, _node ) {
    return _xml?_xml.getElementsByTagName( _node ):null;
};

/*
	gfc( _node ) - get first node (cross-platform firstchild)
*/
function gfc( _n ) {
	if( !_n ) return null;
	var x = _n.firstChild;
	if( !x ) return null;
	while( x.nodeType != 1 ) x = x.nextSibling;
	return x;
}

/*
	gn( _node ) - get first node with name
*/
function gn( _xml, _node ) {
	var n = gds( _xml, _node );
	if( n ) return n[ 0 ];
	return null;
}

/*
	ga( _xml_node, _attribute ) - retrieves an attribute from a specific node
*/
function ga( _node, _attribute ) {	
	return _node?_node.getAttribute( _attribute ):'';
};

/*
	gc( _xml_node ) - retrieves content from a specific node
*/
function gc( _node ) {		
	if( !_node ) return '';
	if( !_node.firstChild[ 0 ] ) return;
	return _node.firstChild[ 0 ].nodeValue;
};

/*
	clear( _node ) - erases all contents in a specified DOM node
*/
function clear( node ) {

    if( node.childNodes ) {
	
        while( node.childNodes.length > 0 ) {
		
            clear( node.childNodes[ 0 ] );
            if( node.childNodes[ 0 ].nodeName == 'IMG' ) {
                var img = node.childNodes[ 0 ];
                if( img ) img.src = '';
            }
            node.removeChild( node.childNodes[ 0 ] );        
        }
    }
};

/*function clearimg( node )
{    
    var imgs = node.getElementsByTagName( "img" );
    for( i = 0; i < imgs.length; i++ )
    { 
        imgs[ i ].src = ""; 
    }
};*/

/*
	re( _node, _content ) - replaces DOM node content
*/
function re( _node, _content ) {
    /*if( node ) {
        clear( node );
        node.innerHTML = content;
    }*/
	return replaceHtml( _node, _content );
};

/* This is much faster than using (el.innerHTML = value) when there are many
existing descendants, because in some browsers, innerHTML spends much longer
removing existing elements than it does creating new ones. */
function replaceHtml(el, html) {
	var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
	if( !oldEl ) return null;	
	/*@cc_on // Pure innerHTML is slightly faster in IE
	oldEl.innerHTML = html;
	return oldEl;
	@*/
	var newEl = oldEl.cloneNode( false );	
	newEl.innerHTML = html;
	
	oldEl.parentNode.replaceChild( newEl, oldEl );
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
};

/*
	http://www.dustindiaz.com/top-ten-javascript/
*/

function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function show( _el, _show ) {
	var el = (typeof _el === "string" ? document.getElementById( _el ) : _el );
	if( !el ) return;
	el.style.display = ( _show?'':'none' );
}

function toggle( _el ) {
	var el = (typeof _el === "string" ? document.getElementById( _el ) : _el );
	el.style.display = ( ( el.style.display === 'none' )?'':'none' );
}

function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

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' : '' );
}

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';
}

/*
	Bind arguments
*/

function bargs( _fn ) {
  var args = [];
  for( var n = 1; n < arguments.length; n++ )
    args.push( arguments[ n ] );
  return function () { return _fn.apply( this, args ); };
}

function sv( _el, _value ) {
	var el = ( typeof _el === "string" ? ge( _el ) : _el );
	if( !el ) return;
	el.value = _value;
}

function gv( _el ) {
	var el = ( typeof _el === "string" ? ge( _el ) : _el );
	if( !el ) return null;
	return el.value;
}

function busy( _state ) {
	/*var cursor = 
	document.layers ? document.cursor :
	document.all ? document.all.cursor :
	document.getElementById ? document.getElementById( 'cursor' ) : */
	document.body.style.cursor = _state?'wait':'default';
}

function sprintf() {
	var str = sprintf.arguments[ 0 ];
	if( !str ) return 'MISSING STRING';
	var pos = -1;
	var count = 1;
	while( ( pos = str.indexOf( '%s' ) ) >= 0 ){
		var p1 = str.slice( 0, pos );
		var p2 = str.slice( pos + 2, str.length );
		str = p1 + sprintf.arguments[ count ] + p2; 
		count++;
	}
	return str;
}

function capitalize( _string ) {
	if( _string.length == 0 ) return '';
	return _string.slice( 0, 1 ).toUpperCase() + _string.slice( 1, _string.length );
}


/*
  var trunc = p.innerHTML;

  if (trunc.length> len) {
 
    // Truncate the content of the P, then go back to the end of the
    // previous word to ensure that we don't truncate in the middle of
    // a word 
	   
    trunc = trunc.substring(0, len);
    trunc = trunc.replace(/\w+$/, '');
	
    // Add an ellipses to the end and make it a link that expands
    // the paragraph back to its original size
    trunc += '<a href="#" ' +
      'onclick="this.parentNode.innerHTML=' +
      'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
      '...<\/a>';
    p.innerHTML = trunc;
  }
}
*/

function gt( _el ) { 
	if( document.all ) return _el.innerText; 
    else return _el.textContent;     
}

function st( _el, _v ) {
    if( document.all ) _el.innerText = _v; 
    else _el.textContent = _v; 
} 

function gp( _e ) {

	var l = 0;
	var t = 0;

	while( _e.offsetParent ){
		l += _e.offsetLeft;
		t += _e.offsetTop;
		_e = _e.offsetParent;
	}

	l += _e.offsetLeft;
	t += _e.offsetTop;

	return { x: l, y: t };
}

/*
	chn ( _o, _n, _m )
	Chain( object, name, method )
*/
function chn( _o, _n, _m ) {

    if( _o && typeof _o == 'object' && _n && typeof _n == 'string' && _m && typeof _m == 'function') {
	
        var old = _o[ _n ];
        if( old && typeof old == 'function' ){
            var oldArgs = [];
            var newArgs = [];
            for( var i = 0; i < old.length; i++ ){
                oldArgs[ i ] = 'arg' + i;
            }
            for( var i = 0; i0 < newMethod.length; i++ ){
                newArgs[ i ] = 'arg' + i;
            }
            oldArgs = oldArgs.join( ', ' );
            newArgs = newArgs.join( ', ' );
            var args = old.length > _m.length ? oldArgs : newArgs;
            _o[ _n ] = eval( 'function(' + args + '){\n' +
            '   old.call(' + oldArgs + ');\n' +
            '   _m.call(' + newArgs + ');\n' +
            '}\n');
        }else{
            _o[ _n ] = _m;
        }
    }
}

function isset( _var ) {
	return( typeof( _var ) != 'undefined' && _var != null );
}