/* ***************************************************************************
 * 
 * Core Functions
 *
 *****************************************************************************/

/**
 * simple wrapper for accessing a portion of a string, using a pattern match
 */
function getId(thisString, pattern) {
	if(pattern) {
		var regEx = new RegExp(pattern);
		var matches = thisString.match(regEx);
		if(matches) {
			if(matches.length == 2) {
				var thisKoId = matches[1];
				return thisKoId;
			} else {
				matches.shift();
				return matches;
			}
		}
	} else {
		return false;
	}
}



/**
 * simple wrapper for replacing a portion of a string
 */
function setId(thisString, pattern, replace) {
	if(pattern) {
		var regEx = new RegExp(pattern);
		return thisString.replace(regEx, replace);
	} else {
		return thisString;
	}
}


/**
 * find and set the x,y and w (width) and h (height) for the element and set them as properties
 */
function setPosition(el) {
	var position = el.cumulativeOffset();
	var dimensions = el.getDimensions();
	
	//console.log(el.getAttribute('id')+': '+position.left+','+position.top+' - '+dimensions.width+'x'+dimensions.height);

	el.x = position.left;
	el.y = position.top;
	el.w = dimensions.width; 
	el.h = dimensions.height;
	
	return el;
}


/**
 * :DEPRECATED:
 *	find and get the x,y and w (width) and h (height) for the element and set them as properties
 */
function getPosition(el) {
	var position = el.cumulativeOffset();
	var dimensions = el.getDimensions();
	
	//console.log(el.getAttribute('id')+': '+position.left+','+position.top+' - '+dimensions.width+'x'+dimensions.height);

	return [position.left, position.top, dimensions.width, dimensions.height];
}


/**
 * Redraws the parent node, to force changes in the dom
 *
 * @access public
 * @return TBD             
 */
function redrawParentElement(thisId) {
	var thisContent = document.getElementById(thisId);
	thisContent.parentNode.replaceChild(thisContent, thisContent);
}


/**
 * loads in html fragments into a given location
 */
function insertHTMLFragment(container,url,onCompleteFunction) {
	var myAjax = new Ajax.Updater (
		container,
		url,
		{ 
			method: 'get',
			onComplete: onCompleteFunction,
		}
	);
}


/**
 * 
 */
function insertAfter(newElement,targetElement) {
  var parent = targetElement.parentNode;
  if (parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  } else {
    parent.insertBefore(newElement,targetElement.nextSibling);
  }
}


/**
 * does element have className - deprecated - uses prototypes method
 */
function hasClass(element,value) {
  return element.hasClassName(value);
}


/**
 * add className - deprecated - uses prototypes method
 */
function addClass(element,value) {
  return element.addClassName(value);
}


/**
 * remove className - deprecated - uses prototypes method
 */
function removeClass(element,value) {
  return element.removeClassName(value);
}


/**
 * getElementsByClassName
 *	- Written by Jonathan Snook, http://www.snook.ca/jonathan
 *  - Add-ons by Robert Nyman, http://www.robertnyman.com
 */
function getElementsByClassName(oElm, strTagName, strClassName) {
    return $$(strTagName+' .'+strClassName);
}


/**
 * removes the element, but keeps the children
 */
function removeSurroundingElement(element) {
	var children = element.childElements();
	for(var i=0;i<children.length;i++) {
		element.parentNode.appendChild(children[i]);
	}
	element.remove();
}


/**
 * parses a url and provides interfaces to the key/values
 *
 * found at: http://www.eggheadcafe.com/articles/20020107.asp
 */
function ParseURL(url) {
	if(url.length > 1) {
		this.url = url.substring(0, url.length);
	} else {
		this.url = null;
	}
	if(this.url.match('/?/')) {
		this.base = this.url.split("?")[0];
		this.path = this.url.split("?")[1];
	} else {
		this.base = this.url;
		this.path = this.url;
	}
	this.keyValuePairs = new Array();
	if(this.path) {
		for(var i=0; i < this.path.split("&").length; i++) {
			this.keyValuePairs[i] = this.path.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s) return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }
}


/**
 * 
 */
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
    	oldonload();
      func();
    }
  }
  // this helps with a bug where the controllers are not redrawn after resizing
  // i've commented this out for now, because when IE loads, this causes it to fire several times - dwc
  //window.onresize = window.onload
}


/**
 * finds baseurl in document and returns it
 */
function getBaseURL() {
	var baseurl = $('baseurl').firstChild.nodeValue;
	if(baseurl) {
		return baseurl;
	} else {
		return '';
	}
}

/**
 * Sets up an event for all ajax calls to display an indicator
 *
 *  based upon: /http://dobrzanski.net/index.php?s=oncreate 
 */
function prepareAjaxIndicator() {	
	if(!$('ajaxIndicator')) {
		var circleAnimation = document.createElement('img');
		 circleAnimation.setAttribute('id','ajaxIndicator');
		 //circleAnimation.setAttribute('src',getBaseURL()+'lib/Core/C1Object/images/circle_animation.gif');
		 circleAnimation.setAttribute('src',getBaseURL()+'lib/Core/C1Object/images/ajax-loader.gif');
		 circleAnimation.setAttribute('alt','progress animation');
		 $$('BODY')[0].appendChild(circleAnimation);
		 
		 Element.hide('ajaxIndicator') 
	}
	
	Ajax.Responders.register({
			onCreate: ajaxOnCreate,
			onComplete: ajaxOnComplete,
    	onFailure: showFailureMessage,
    	onException: showException
	});
}


/**
 * handles creation from ajax request
 */
function ajaxOnCreate(requestObj) {
	//console.log('showing ajax indicator'); 
	Element.show('ajaxIndicator');
}


/**
 * handles completion from ajax request
 */
function ajaxOnComplete(requestObj) {
	//console.log('hiding	 ajax indicator'); 
	Element.hide('ajaxIndicator');
}


/**
 * handles failure from ajax request
 */
function showFailureMessage(requestObj) {
	console.log('Ajax Failure: '+requestObj.statusText);
	return true;
}


/**
 * handles exception from ajax request
 */
function showException(requestObj, exception) {
	console.log('Ajax Exception: '+exception);
	return true;
}


/**
 * loads js and css files dynamically - must be called within an onload function
 */
function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
  
 //console.log('loaded '+filetype+' file: '+filename);
}


/**
 *
 */
function createjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 //console.log('created '+filetype+' file: '+filename);
 
 return fileref
}


/**
 *
 */
function replacejscssfile(oldfilename, newfilename, filetype){
 var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
 var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
 var allsuspects=document.getElementsByTagName(targetelement)
 for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
  if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
   var newelement=createjscssfile(newfilename, filetype)
   allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
  }
 }
}


/**
 *
 */
function setDebugLevel(level) {
	DebugLevel = level;
}
var DebugLevel = 1;


/**
 *
 */
function debug(message, level) {
	if(!level) level = 1;
	if(level <= DebugLevel) {
		console.log(message);
	}
}


/* ***************************************************************************/
// Open Code


/**
 * Returns true if the passed value is found in the
 * array.  Returns false if it is not.
 */
Array.prototype.inArray = function (value){
	var i;
	for (i=0; i < this.length; i++) {
			// Matches identical (===), not just similar (==).
			if (this[i] === value) {
					return true;
			}
	}
	return false;
};


/**
 * check to make sure getElementById is defined, otherwise create the method
 * - used for IE
 */
/*if(!HTMLDocument.prototype.getElementById) {
	HTMLDocument.prototype.getElementById = function (value) {
		return document.all[value];
	}
}*/


/**
 * code yanked from the Yahoo media player. Thanks, Yahoo.
 */
if (! ("console" in window) || !("firebug" in console)) {
	var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
	window.console = {};
  for (var i = 0; i <names.length; ++i) window.console[names[i]] = function() {};
}

if(jQuery) {
     var $j = jQuery.noConflict();
}

/* ***************************************************************************/

addLoadEvent(prepareAjaxIndicator);