
var _isIE6 = navigator.userAgent.indexOf("MSIE 6") != -1;
var flashBasePath = "/_resx/js/flash/";
var flashVersion = 8;
var flashCounter = 0;

/* ============================================================= */
function writeFlash(el, flashFile, w, h, pars, initObj) {

	var embedCode;
	var origHtml;
	el.style.visibility = "visible";	
	
	if(swfobject.getFlashPlayerVersion().major >= flashVersion){

		var replacedContent = el.innerHTML;
		
		var h = h.toString().indexOf("%")>-1 || h.toString() == "auto" ?h:h+"px";
		var w = w.toString().indexOf("%")>-1 || w.toString() == "auto" ?w:w+"px";

		var flashEl = document.createElement("span");
		flashEl.id = "flashobj_" + flashCounter;
		flashEl.style.display = "block";
		el.innerHTML = "";
		
		for(var p in initObj){
			el[p] = initObj[p];
		}
		
		el.appendChild(flashEl);
		
		var rpEl = document.createElement("span");
		rpEl.className = "flash_block_replaced_content";
		rpEl.innerHTML = replacedContent;
		el.appendChild(rpEl);

		flashFile = flashBasePath + flashFile;
		
		if(pars){
			if(pars.flashvars){
				pars.flashvars += "&flashid=" + flashEl.id;
			}else{
				pars.flashvars = "flashid=" + flashEl.id;
			}
		}else{
			pars = {flashvars: "flashid=" + flashEl.id};
		}
		
	  	var att = { data: flashFile, width: w, height: h };
		var flashObject = swfobject.createSWF(att, pars, flashEl.id);
		
		var fv = swfobject.getFlashPlayerVersion;
		if( navigator.userAgent.indexOf("MSIE") != -1 && (fv().major < 9 || (fv().major == 9 && fv().release < 100) ) ){
			//Debug.addLine("utilities.js", "writeflash", "fixexternal");
			window[flashEl.id] = flashObject;
		}			
		
		flashObject.style.display = "block";
		flashObject.className = "flash_block";
		
		flashCounter++;
		
		return flashObject;
	}
	
	return false;
	
}

/* @constructor */
function EventUtils() {
	throw 'RuntimeException: EventUtils is a static utility class ' +
		' and may not be instantiated';
}

/**
 *	@access static
 *	@param HTMLElement target
 *	@param string type
 *	@param Function callback
 *	@param boolean captures
 */
EventUtils.addEventListener = function (target,type,callback,captures) {
	if (target.addEventListener) {
			// EOMB
		target.addEventListener(type,callback,captures);
	} else if (target.attachEvent) {
		// IE
		target.attachEvent('on'+type,callback,captures);
	} else {
		// IE 5 Mac and some others
		target['on'+type] = callback;
	}
}

EventUtils.removeEventListener = function (target,type,callback,captures) {
	if (target.removeEventListener) {
			// EOMB
		target.removeEventListener(type,callback,captures);
	} else if (target.detachEvent) {
		// IE
		target.detachEvent('on'+type,callback);
	} else {
		// IE 5 Mac and some others
		target['on'+type] = null;
	}
}

/* ============================================================= */
/* [ Form Functions ] */
initFormFocus = function() {

	var types = ["input", "textarea"];
	
	for(var t=0; t<types.length; t++){
	var fields = getElementsBySelector(types[t]);

		for (i=0; i<fields.length; i++) {
			var node = fields[i];
			if (node.type == "text" || node.type == "password" || node.type == "textarea") {
				if(node.type == "password"){
					initPasswordField(node);
					initField(node);
				}else{
					initField(node);
				}
			}
			
			if(node.type == "button")node.className += " button";
			if(node.type == "submit")node.className += " submit";
			if(node.type == "file")node.className += " file";
				
			
		}
	}
}

function initField(field){
	EventUtils.addEventListener(field,'focus', focusField);
	EventUtils.addEventListener(field,'blur', blurField);	
}

function initPasswordField(field){

	var initialValue = getInitialValue(field);
	var openField = document.createElement("input");

	with(openField){
		type = "text";
		value = initialValue;
		id = "open_" + field.id;
		className = field.className;
	}
	
	openField.obscuredField = field;
	field.openField = openField;
	field.parentNode.replaceChild(openField, field);
	initField(openField);
}

function getInitialValue(field){

	var initialValue = '';
	var initialValue_attribute = field.attributes["initialvalue"];
	
	if(field.initialvalue){
		initialValue = field.initialvalue;
		return initialValue;
	}

	if(initialValue_attribute != undefined){
		initialValue = initialValue_attribute.value;
		return initialValue;
	}
	
	return initialValue;
}

function focusField(){

	if(window.event){
		//IE Only
		el = window.event.srcElement;
	}
	else{
		el = this;
	}
	
	if(el.obscuredField && el.parentNode){
		el.parentNode.replaceChild(el.obscuredField, el);
		el = el.obscuredField;
		el.focus();
	}
	
	if(navigator.userAgent.toLowerCase().indexOf("safari") == -1){el.className += " focus";}

	var initialValue = getInitialValue(el);
	if(el.value == initialValue)el.value = "";
		
	el.select();
	
}

function blurField(){

	if(window.event){
		//IE Only
		el = window.event.srcElement;
	}
	else
		el = this;
			
	var initialValue = getInitialValue(el);
	
	if(el.value == "" && initialValue != undefined){

		if(el.openField && el.parentNode){
			el.parentNode.replaceChild(el.openField, el);
			el = el.openField;
			el.blur();
			//initField(el);
		}
		
		el.value = initialValue;
	}
	
	el.className = el.className.replace(/focus/g, "");
}

EventUtils.addEventListener(window,'load',initFormFocus);

/* =============================================================================== */
/* { Helper Functions ] */

function getInnerText(e){
  var strText = "";
  var node;
  for(var i=0; i<e.childNodes.length; i++ ) {
	  node = e.childNodes[i];
	  switch(node.nodeType) {
	    case 1: // elements
    		strText += getInnerText(node);
		    break;
	    case 3: // text
		    strText += node.nodeValue;
		    break;
	    default: // comments etc
		    break;
	  }
  }
	
	// Strip leading and trailing spaces.
	var regEx = /[\r\n\t]+|[ ]{2}/g;
	strText = strText.replace(regEx, " ");
	
	var regEx = /[ ]+/g;
	strText = strText.replace(regEx, " ");
	
	return strText;
}


function getInnerHtml(e){
	 var strText = "";
	 var node;
	 for(var i=0; i<e.childNodes.length; i++ )
	 {node = e.childNodes[i];
	  switch(node.nodeType)
	  {
	   case 1: // elements
			var atts = node.attributes;
			var ta = "";
			for (var k = 0; k < atts.length; k++)
			{
				var att = atts[k];
				if(att.specified)
					ta += att.nodeName.toLowerCase() + '="' + att.nodeValue + '" '; 
			}
			if(node.childNodes.length > 0)
				strText += "<" + node.nodeName.toLowerCase() + " " + ta + ">" + getInnerHtml(node) + "</" + node.nodeName.toLowerCase() + ">";
			else
				strText += "<" + node.nodeName.toLowerCase() + " " + ta + " />"
		break;
	   case 3: // text
		strText += node.nodeValue;
		break;
	   default: // comments etc
		break;
	  }
	 }
	 
	//Strip leading and trailing spaces.
	var regEx = /[\r\n\t]+|[ ]{2}/g;
	strText = strText.replace(regEx, " ");
	
	var regEx = /[ ]+/g;
	strText = strText.replace(regEx, " ");

	return strText;
}

/* ============================================================= */
/*
	Finds elements on page that match a given CSS selector rule. Some
	complicated rules are not compatible.
	Based on Simon Willison's excellent "getElementsBySelector" function.
	Original code (with comments and description):
	http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
*/
function getElementsBySelector(selector)
{
	var tokens = selector.split(' ');
	var currentContext = new Array(document);
	for(var i=0;i<tokens.length;i++)
	{
		token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
		if(token.indexOf('#') > -1)
		{
			var bits = token.split('#');
			var tagName = bits[0];
			var id = bits[1];
			var element = document.getElementById(id);
			if(tagName && element.nodeName.toLowerCase() != tagName)
				return new Array();
			currentContext = new Array(element);
			continue;
		}

		if(token.indexOf('.') > -1)
		{
			var bits = token.split('.');
			var tagName = bits[0];
			var className = bits[1];
			if(!tagName)
				tagName = '*';

			var found = new Array;
			var foundCount = 0;
			for(var h=0;h<currentContext.length;h++)
			{
				var elements;
				if(tagName == '*')
					elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
				else
					elements = currentContext[h].getElementsByTagName(tagName);

				for(var j=0;j<elements.length;j++)
					found[foundCount++] = elements[j];
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			for(var k=0;k<found.length;k++)
			{
				if(found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b')))
					currentContext[currentContextIndex++] = found[k];
			}

			continue;
	    }

		if(token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/))
		{
			var tagName = RegExp.$1;
			var attrName = RegExp.$2;
			var attrOperator = RegExp.$3;
			var attrValue = RegExp.$4;
			if(!tagName)
				tagName = '*';

			var found = new Array;
			var foundCount = 0;
			for(var h=0;h<currentContext.length;h++)
			{
				var elements;
	        	if(tagName == '*')
					elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
				else
					elements = currentContext[h].getElementsByTagName(tagName);

				for(var j=0;j<elements.length;j++)
					found[foundCount++] = elements[j];
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			var checkFunction;
			switch(attrOperator)
			{
				case '=':
					checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
					break;
				case '~':
					checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
					break;
				case '|':
					checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
					break;
				case '^':
					checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
					break;
				case '$':
					checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
					break;
				case '*':
					checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
					break;
				default :
					checkFunction = function(e) { return e.getAttribute(attrName); };
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			for(var k=0;k<found.length;k++)
			{
				if(checkFunction(found[k]))
					currentContext[currentContextIndex++] = found[k];
			}

			continue;
		}

		tagName = token;
		var found = new Array;
		var foundCount = 0;
			for(var h=0;h<currentContext.length;h++)
			{
				//alert(currentContext[h]);
				if(currentContext[h]){
					var elements = currentContext[h].getElementsByTagName(tagName);
					for(var j=0;j<elements.length; j++)
						found[foundCount++] = elements[j];
				}
			}

		currentContext = found;
	}

	return currentContext;
}
/* ============================================================= */
/* [ Form default button actions ] */
function searchSubmit(clicked, e){
	var search = false;
	var q = document.getElementById ? document.getElementById('query').value : query.value;
	search = submitForm(e);
	if (search || clicked) {
	window.location = "/net/search/?q=" + escape(q);
	return true;
	}
	return false;
}

function submitForm(e) {
    var toSubmit = false;
    var evt;
    
    // IE
    if(document.all) {
      evt = window.event;
    // Other
    } else {
      evt = e;
    }
  		
    var key = evt.keyCode ? evt.keyCode : (evt.which ? evt.which : evt.charCode);
    
    if (key == 13) {
      // Cancel postback
      toSubmit = true;
  		
      if(document.all) {
        if (window.opera) {
          evt.preventDefault();  // opera, currently this does not work.
        } else {
          evt.returnValue=false; //ie
          evt.cancel = true;
        }
  			
      } else {
        evt.preventDefault(); //geko
      }
    }

    return toSubmit;

}

/* ============================================================= */
/**
 * A class to parse color values
 * @author Stoyan Stefanov <sstoo@gmail.com>
 * @link   http://www.phpied.com/rgb-color-parser-in-javascript/
 * @license Use it if you like it
 */
function RGBColor(color_string)
{
	
    this.ok = false;
    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
    color_string = color_string.toLowerCase();

    // array of color definition objects
    var color_defs = [
        {
            re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
            example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
            process: function (bits){
                return [
                    parseInt(bits[1]),
                    parseInt(bits[2]),
                    parseInt(bits[3])
                ];
            }
        },
        {
            re: /^(\w{2})(\w{2})(\w{2})$/,
            example: ['#00ff00', '336699'],
            process: function (bits){
                return [
                    parseInt(bits[1], 16),
                    parseInt(bits[2], 16),
                    parseInt(bits[3], 16)
                ];
            }
        },
        {
            re: /^(\w{1})(\w{1})(\w{1})$/,
            example: ['#fb0', 'f0f'],
            process: function (bits){
                return [
                    parseInt(bits[1] + bits[1], 16),
                    parseInt(bits[2] + bits[2], 16),
                    parseInt(bits[3] + bits[3], 16)
                ];
            }
        }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }

    }
	
    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
	
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }

}

/* ============================================================= */
/* [ Simple javascript debug console ] */
function Debug(){
		throw 'RuntimeException: Debug is a static utility class ' +
		' and may not be instantiated';
}

Debug.addLine = function(jsFile, method, message){

	var debugEl = document.getElementById("debug");

	if(debugEl == null){
		debugEl = document.createElement("div");
		debugEl.id = "debug";
		with(debugEl.style){
			position = "fixed";
			top = 0;
			left = 0;
			width = "500px";
			height = "300px";
			overflow = "scroll";
			background = "#FFFFFF";
			color = "#000000";
			fontSize = "10px";
			border = "1px solid #000000";
			zIndex = "10000";
		}
		document.getElementsByTagName("body")[0].appendChild(debugEl);
		
	}
	
	debugEl.innerHTML += jsFile + " :: " + method + " > " + message + "<br />";
}
			
			