/**
 * @author 			Bhasker V Kode
 * @date 			September 7th,2007
 * @description		general purpose utils
 * 
 */
 if(typeof HI == "undefined"){
  	HI = { Classes:{}, UI:{}, LINKS:{} ,XML:{},Apps:{} , Dialog:{} };
 }

 HI.LINKS = {base:'/',g:'/common/get.yaws'};
 
 HI.remote = function(getOrPost,dest,contentTypeisXML,callback,params){
		var req = null;
		if (window.XMLHttpRequest){
 			req = new XMLHttpRequest();
		}else if (window.ActiveXObject){
			try{
				req = new ActiveXObject("Msxml2.XMLHTTP");
			}catch (e){
				try {
					req = new ActiveXObject("Microsoft.XMLHTTP");
				}catch (e){
				}
			}
		}
		req.onreadystatechange = function(){	
			if(req.readyState == 4){	
				if(req.status == 200){
						callback(req);
				}
			}
		};
		
		req.open(getOrPost, dest, false);
		if(getOrPost=="POST"){
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.setRequestHeader("Content-length", params.length);
			req.setRequestHeader("Connection", "close");
			req.send(params);
		}else{
			req.send(null);
		}
		
};
 
/**
 * utility to add html
 */
 HI.addHTML = function ( optionType , parentObj , params ){
	var _new = document.createElement(optionType);
	if(params!=undefined){
		for(var obj in params){
			if(typeof params[obj]=='object'){
				for(var subobj in params[obj]){
					_new[obj][subobj] = params[obj][subobj]
				}
			}else{
				_new[obj] = params[obj];
			}
		}
	}
	
	if(optionType=='option' && document.all){
			parentObj.add(_new);
	}else{
		parentObj.appendChild(_new);
	}
	
	return (_new);
};

function HIfade(obj,callback,curr,final,type){
	/**
 	 * for speed variations,inc/dec the decimal multiplier below.
 	 */
 	if(obj.style.MozOpacity!=undefined){
	 		obj.style.MozOpacity = curr/100;
	 		obj.style.opacity = curr/100 ;
	}else{
 		obj.style.filter = "alpha(opacity="+ curr+")";
 	}
 	
 	var _type = (type!=undefined)? type : ( (curr>final)?'out':'in'  );
 	if(curr==final){
 		//console.log(_type + ' OVER at '+final);
 		return;
 	}
 	
 	var _cont=true;
	if(_type=='in'){
 		curr = curr + (curr * 1);
		_cont = (curr<= final)? true : false;
		
 	}else{
		curr = curr- (curr * 1);
 		_cont = (curr>=final)? true : false;
 	}
 	
 	if(!_cont){
	 	curr =  final;
		//console.log(_type+': fastforward to '+curr+'and callback');
		callback();
	}
	
	var _fn = function(){
		HIfade(obj,callback,curr,final,_type );
	 };
	 window.setTimeout(_fn,100);
 		
}


HI.Event = {
  stdDOM : (navigator.userAgent.indexOf("MSIE")<0) ? 1:0,
  readyList : [],
  addEvent  : function (obj,type,listener, waitObj){	
    if(waitObj!=undefined){
	  /**
	   * This is how you set how many seconds to wait for the sustained or deferred events
	   */
	 HI.Event.addIdempotentEvent(obj,type,listener, waitObj);
	}else{
	  /**
	   * Follow normal event handling
	   */
	  if (navigator.userAgent.indexOf("MSIE")<0) {
		/* Std DOM Events*/	
	    obj.addEventListener(type, listener, false);
	  }else{
		obj.attachEvent('on'+type, listener);
	  }
	}
  
  },
  addIdempotentEvent : function (obj,type,listener, waitObj){	
		var _len = HI.Event.readyList.length;
	    HI.Event.readyList.push({obj:obj,listenTo:type,wait:waitObj,callBack:listener,done:-1});
		 var _call = function(ev){
			 if (HI.Event.stdDOM) {
			 	  HI.Event.readyList[_len].ev={};
				  for(var obj in ev){
					HI.Event.readyList[_len].ev[obj] = ev[obj];
				  }
			 }else{
			  		HI.Event.readyList[_len].ev =document.createEventObject(ev);
			 }
			 HI.Event.updateTimer(_len ,HI.Event.readyList[_len].ev);
		};
		
		if (HI.Event.stdDOM) {
			obj.addEventListener(type, _call, false);
		}else{
			obj.attachEvent('on'+type, _call );
		}
  
   },
   
   updateTimer : function(_index,e){
   	 var ev = (HI.Event.stdDOM)? e:event;
     var _config = HI.Event.readyList[_index];
     
	  if(_config.wait.wait!=undefined){
	  	 
		  /**
		   * wait for n seconds ,then activate
		   */
		  if(_config.done==-1){
			 _config.done=false; 
		  }
		  if(!_config.done){
		    //wait
			//ignore this event
			_config.done=true;
			var a = function(){
			  		 HI.Event.updateTimer( _index, HI.Event.readyList[_index].ev);
			  };
			  window.setTimeout(a,_config.wait.wait);
		  }else{
		  	//done is true ,ready to activate
			//waited long enough.Ready to activate
			  var a = function(){
			  		_config.callBack(HI.Event.readyList[_index].ev);
			  };
			  window.setTimeout(a,_config.wait.wait);
			  _config.done=false; 
		  }
		
	  }else{
		  /**
		   * activate, then ignore for n seconds
		   */
	      if(_config.done==-1){
			  _config.done=true;
		  }
	      if(_config.done){
			  //activate
			  //Activate first,then ignore for some time');
			  _config.callBack(ev);
			  _config.done=false;
			  //then wait
			  var _setDoneTrue= function(){
				 _config.done=true;
				// now ok to catch events again
			  }
			  window.setTimeout(_setDoneTrue,_config.wait.ignore);
			  
		  }else{
		  	 //going on ,so dont call
			 // ignore this event
			 //console.log('ignore');
		  }
		  
	  }
	 
   }
   
};

HI.log = function(msg,br){
	if(HI.DEBUG){
	 logdiv.innerHTML += ( (br)?'<BR>' : '&nbsp;' )+ msg;
	}
};
HI.forcelog = function(msg,br){
	 logdiv.innerHTML += ( (br)?'<BR>' : '&nbsp;' )+ msg;
};

if(typeof console =="undefined"){
	console = {log:HI.log};
}

HI.Classes.getXMLTree = function(xmlStr,nodeName){
	 this.xml =  null;
	 this.load = function (nodeName){

		   if (window.ActiveXObject){
				var XMLParserList = new Array ( "Microsoft.XMLHTTP", "MSXML2.XMLHTTP", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.5.0","MSXML2.DOMDocument");
				
				var type="none";
				for ( var i = XMLParserList.length; i>0;i--) {
					var type='none';
					  try {
					   // Test for MSXML obj
						  this.xml = new ActiveXObject( XMLParserList[i-1] );
						  break;
					  }
					  catch(e) {
						//  alert('getXMLerro '+e);
					 }
				}		
			  	this.xml.loadXML(xmlStr);
				this.xml.async="false";
				
				
			  }else if (document.implementation && document.implementation.createDocument){
					var vParser = new DOMParser();
					this.xml= vParser.parseFromString(xmlStr,"text/xml");
			  }
		
			if(nodeName!=undefined){
				 this.length = this.xml.getElementsByTagName(nodeName).length;
				 this.xml.getElementsByTagName(nodeName);
			}
	}	 
	
	this.load(nodeName);
};

function getAllChildren(e){return e.all?e.all:e.getElementsByTagName('*');}
document.getElementsBySelector=function(selector){if(!document.getElementsByTagName){return new Array();}
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=getAllChildren(currentContext[h]);}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=getAllChildren(currentContext[h]);}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++){var elements=currentContext[h].getElementsByTagName(tagName);for(var j=0;j<elements.length;j++){found[foundCount++]=elements[j];}}
currentContext=found;}
return currentContext;}
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=Base64._utf8_encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}output=output+this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4);}return output;},decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2);}if(enc4!=64){output=output+String.fromCharCode(chr3);}}output=Base64._utf8_decode(output);return output;},_utf8_encode:function(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}return utftext;},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++;}else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode(((c&31)<<6)|(c2&63));i+=2;}else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}return string;}};