/*
Author: Tony Ogundipe
title: My  personal Jscript Library
*/

//*************************************************** json class start
function json() {
this.image={title:'json'};
if(arguments.length==1) {
this.image=eval("js={"+arguments[0]+"}");
for(key in this.image) {eval("this."+key+"=\""+this.image[key]+"\"");}}
}

json.prototype.dump=function() {
var sep="\n";
if(this.dump.arguments.length==1) {sep=this.dump.arguments[0];}
var arr=new Array();
for(key in this.image) {
arr[arr.length]=key+"="+this.image[key];
}
return sep+arr.join(sep);
}

json.prototype.loadString=function(str) {
try {
 var r=str.split("|");var retval={title:'json'};
 for(var x=0;x<r.length;x++) {eval("retval."+r[x].split("=")[0]+"='"+r[x].split("=")[1]+"'");}
this.image=retval;
for(key in this.image) {eval("this."+key+"=\""+this.image[key]+"\"");}

} catch(err) {
alert("Invalid string parameter for json conversion.");
}
return;
}

json.prototype.add=function(key,value) {
try {eval("this.image."+key+"='"+value+"';");} catch(err) {alert("Cannot add string to json.");}
}

json.prototype.get=function(key) {try {return eval("this.image."+key);} catch(err) {return "";}}


json.prototype.remove=function(key) {
try {eval("this.image."+key+"='';");} catch(err) {alert("Cannot remove string to json.");}
}

json.prototype.save=function(datakey) {
var key="json_prototype_datastore_"+datakey;
if(document.getElementById(key)==null) {
 var d=document.createElement('INPUT');
 document.body.appendChild(d);  
 d.id=key;  
 d.type="text";  
 d.value=this.toString();
 d.style.cssText="display:none;";
} 
}

json.prototype.load=function(datakey) {
try {
var key="json_prototype_datastore_"+datakey;
var str=document.getElementById(key).value;
this.loadString(str);
} catch(err) {alert("Invalid data pack for json loader");}
}

json.prototype.toString=function() {
var arr=new Array();
for(key in this.image) {
arr[arr.length]=key+"="+this.image[key];
}
return arr.join("|");
}

//*************************************************** json class finish

//*************************************************** collection class finish
function collection() {this.data="";this.count=0;}

collection.prototype.add=function(key,val) {
if(this.exists(key)) {this.replace(key,val);return;}
this.data+=key+"="+escape(val)+"\n";this.dcount();
}
collection.prototype.trim = function(str) {return str.replace(/^\s+|\s+$/g, ''); }
collection.prototype.exists=function(key) {if(this.data.indexOf(key+"=")!=-1) {return true} else {return false;}}

collection.prototype.items=function() {
var s=this.trim(this.data).split("\n");var res=new Array();
for(key in s) {res[res.length]=s[key].split('=')[1];};
return res;
}

collection.prototype.keys=function() {
var s=this.trim(this.data).split("\n");var res=new Array();
for(key in s) {res[res.length]=s[key].split('=')[0];}
return res;
}

collection.prototype.dcount=function() {
this.count=this.trim(this.data).split("\n").length;
}

collection.prototype.item=function(key) {
var s=this.trim(this.data).split("\n");var res=new Array();
for(keyb in s) {
if(s[keyb].split('=')[0]==key) {return unescape(s[keyb].split('=')[1]);}
}
return "";
}


collection.prototype.remove=function(key) {
var s=this.trim(this.data).split("\n");var res=new Array();
for(keyb in s) {
if(s[keyb].split('=')[0]==key) {continue;}
res[res.length]=s[keyb];
}
this.data=res.join("\n");
}


collection.prototype.removeAll=function() {this.data="";}

collection.prototype.replace=function(key,val) {
var s=this.trim(this.data).split("\n");var res=new Array();
for(keyb in s) {
if(s[keyb].split('=')[0]==key) {s[keyb]=key+"="+escape(val);}
}
this.data=s.join("\n");
}
//*************************************************** collection class finish





//*************************************************** jcookies class start
function jcookies() {}
jcookies.prototype.online=function() {return location.href.indexOf("http")==-1 ? false : true;}
jcookies.prototype.set=function (cname,cvalue) { 
  if(this.online()) {document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;path=/;";}
  else {document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;";}
}
jcookies.prototype.erase=function(cname) {
  if(this.online()) {document.cookie = cname + "=" + "" + "; expires=Mon, 31 Dec 1899 23:59:59 UTC;path=/;";}
  else {document.cookie = cname + "=" + "" + "; expires=Mon, 31 Dec 1899 23:59:59 UTC;";}
}
jcookies.prototype.get=function(sName) { var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)   {
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
      return unescape(aCrumb[1]);
  }
  return "";
}
//*************************************************** jcookies class finish


//*************************************************** jselect class start
function jselect() {
this.target=null;
}

jselect.prototype.select=function(targetId) {

if(isObject(targetId)) {
 try {if(targetId.id!="") {targetId=targetId.id} else {targetId=targetId.name;}} catch(err) {void(0);}
}

var s=document.getElementsByTagName("SELECT");
for(i=0;i<s.length;i++) {
if(s[i].id==targetId||s[i].name==targetId) {this.target=s[i];}
}
if(this.target==null) {alert(targetId+"could not be selected.");}
return true;
}

jselect.prototype.trim = function(str) {return str.replace(/^\s+|\s+$/g, ''); }
jselect.prototype.add=function(val,text) {var opt=document.createElement("OPTION");this.target.appendChild(opt);opt.value=this.trim(val);opt.text=this.trim(text);}

jselect.prototype.loadString=function() {
var sep="\n";var str="";
switch(this.loadString.arguments.length) {
case 1:
str=this.loadString.arguments[0];
break;
case 2:
str=this.loadString.arguments[0];
sep=this.loadString.arguments[1];
break;
}

var s=str.split(sep);
for(var i=0;i<s.length;i++) {
if(s[i].indexOf("=")==-1) continue;
this.add(s[i].split("=")[0],s[i].split("=")[1]);
}
return;
}

jselect.prototype.removeItem=function(index) {
if(this.target==null) {return false;}
try {
 var opt=this.target.options[index];	
 this.target.removeChild(opt);
  return true;
} catch(err) {
 return false; 
}
}

jselect.prototype.erase=function(val) {
return this.removeItem(this.findValue(val));
}


jselect.prototype.findValue=function(val) {
for(var i=0;i<this.target.length;i++) {
 var opt=this.target.options[i];
 if(opt.value==val) {return i}
}
return -1;
}

jselect.prototype.dump=function() {
var sep="\n";
if(this.dump.arguments.length==1) {sep=this.dump.arguments[0];}

var d="";
for(var i=0;i<this.target.length;i++) {
 var opt=this.target.options[i];
 d+=sep+opt.value+"="+opt.text;
}
return d;
}


jselect.prototype.cls=function() {
for(var i=this.target.length;i>-1;i--) {
this.removeItem(i);
}
}


jselect.prototype.fill=function(pval,pstart,pend,title) {
	var h=this.target;
	if(title!="") {this.add('',title);}
	for(var i=pstart;i<=pend; i++)
		h.options[h.options.length]=new Option(i,i);
	h.selectedIndex=0;
}


jselect.prototype.fillMonths=function(title) {
	var h=this.target;
	if(title!="") {this.add('',title);}
	var m= new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	for(var i=1; i <= 12;i++) {
		h.options[h.options.length]=new Option(m[i-1],i);
	}
	h.selectedIndex=0;
}

//*************************************************** jselect class stops


//Prototype class 1.00
function jproto() {
this.boot(arguments);
}


jproto.prototype.online=function() {return location.href.indexOf("http")==-1 ? false : true;}


jproto.prototype.ajaxRequest= function() {
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}


jproto.prototype.boot = function(arguments) {
//declare global variables.
  this.arguments=arguments; //store for loadParams
  this.initialized=false;   
  this.runOnce=false;
  this.isReady=false;
  
  //attach classes to it
  this.cookie=new jcookies();

  //register event handlers  
  var events="oninit|onload|downloadSuccess|downloadFailure|downloadComplete|onloadLoadParams";

  //setup blank handlers
  this.createHandlers(events);
  
  
  this.instanceID=this.createInstanceID();
  this.createEvent('load',window,this.jstart);
  return this.instanceID;
}

jproto.prototype.jstart = function() {
this.instance_pos=this.getInstanceID();
  this.createDataBox();
}

jproto.prototype.createHandlers=function(events) {var s=events.split("|");for(var i=0;i<s.length;i++) {eval("this."+s[i]+"=null;");}}


jproto.prototype.createDataBox = function () {
//create databox
if(document.getElementById("prototype_databox")==null) {
 var d=document.createElement('INPUT');
 document.body.appendChild(d);  
 d.id="prototype_databox";  
 d.type="text";  
 d.style.cssText="display:none;";
}
}

jproto.prototype.setData = function(text) {
document.getElementById("prototype_databox").value=text;
}

jproto.prototype.getData = function() {
return document.getElementById("prototype_databox").value;
}

jproto.prototype.getDataEx=function(s) {
try {var ret=eval("this.getData().exsplit()."+s);if(typeof(ret)!="string") ret='';} catch(err) {ret="";}
return ret;
}


jproto.prototype.jinit=function() {
this.initialized=true;
this.parseParams();
this.loadParams();
this.init();
this.runEvent('onload');

with(this) {
setTimeout(
function() {
runEvent('oninit');
},200
);
}

//this.jalert("Initialized and ready for action");
}



jproto.prototype.createEvent=function(evt,target,handler) {
	if(this.createEvent.arguments.length!=3) {return false;}	
	  with(this) 
		{
		e=function() {jeval(handler);}
		try {if(window.addEventListener){target.addEventListener(evt, e, false);} else {target.attachEvent('on'+evt,e);}} catch(err) 
		{if(document.all) {alert("Cannot create event '"+evt+"':"+err.number+":"+err.description);} else {alert("Cannot create event '"+evt+"'\n"+err);}}
		}
}

jproto.prototype.toggleSelect=function(node,cstate) {
try {
  var visible = (cstate) ? "visible" : "hidden";
  coll = node.getElementsByTagName("SELECT");  
  for(i=0;i<coll.length;i++) {coll[i].style.visibility=visible;}
} catch(err) {
alert("Cannot toggle select menu");
}

}


jproto.prototype.removeEvent=function(evt,target,handler) {
	//if(this.createEvent.arguments.length!=3) {return false;}	
	  with(this) 
		{
		e=function() {jeval(handler);}
		try {if(window.addEventListener){target.removeEventListener(evt, e, false);} else {target.detachEvent('on'+evt,e);}} catch(err) 
		{if(document.all) {alert("Cannot remove event '"+evt+"':"+err.number+":"+err.description);} else {alert("Cannot detach event '"+evt+"'\n"+err);}}
		}
}


jproto.prototype.createInstanceID=function () {
var s=(this.constructor.toString());i=s.indexOf(" ");j=s.indexOf("(");
var base=s.substring(i+1,j);
base+="_instance";var wbase="window."+base;
if(eval(wbase)==null) {eval(wbase+"=Array()");}
//instantiate
var arr=[this,0];
var warray=eval(wbase);
warray[warray.length]=arr;
return warray.length;
}

jproto.prototype.getInstanceID=function() {
 var s=(this.constructor.toString());i=s.indexOf(" ");j=s.indexOf("(");
 var base=s.substring(i+1,j);
 base+="_instance";var wbase="window."+base;
 var warray=eval(wbase);var retval={target:'0', key: '-1'};
 for(key=0;key<warray.length;key++) {
 if(warray[key][1]==0) {
 warray[key][1]=1;
 retval.target=warray[key][0]; retval.key=key;
 var wb=(wbase+"["+key+"][0]");
 retval.target.instance=retval;
 retval.target.wbase=wb;
 eval(wb+".jinit()")
 }
 }
 return retval;
}

jproto.prototype.urldecode = function(str) {re=/\+/g;str = str.replace(re, " ");str=unescape(str);return str;}
jproto.prototype.trim = function(str) {return str.replace(/^\s+|\s+$/g, ''); }


jproto.prototype.parseParams=function() {this.commandLine="";for(i=0;i<this.arguments.length;i++) {this.commandLine+="<li>"+this.arguments[i];}
}

jproto.prototype.jeval=function(fx) {
with(this) {
if(typeof(fx)=="string") {
if(fx.indexOf('on')!=0) {fx='on'+fx;}
try {var e=eval("this."+fx);if(typeof(e)!="function") return false;} catch(err) {return false;}
} else {
if(typeof(fx)=="function") {var e=fx;} else {return false;}
}
//conversion
var ef=e+"";i=ef.indexOf("{");j=ef.lastIndexOf("}");ef=ef.substring(i+1,j);
try {eval(ef);} catch(err) {void(0);return false;}
}
return true;
}
 
jproto.prototype.runEvent=function(handler) {return this.jeval(handler);}

jproto.prototype.jalert=function(message) {this.jmessage=message;this.runEvent("jalert");}

//start coding from here
jproto.prototype.version = function() {
return("#Tony Ogundipe's Prototype Class 1.0");
}

jproto.prototype.versionEx = function() {
alert(this.version());
}



jproto.prototype.loadMedia = function(filename) {
	var i=filename.lastIndexOf(".");
	var ext=filename.substr(i+1,filename.length);
	switch(ext) {
	case "css":
	var fileref=document.createElement("link")
	fileref.setAttribute("rel", "stylesheet")
	fileref.setAttribute("type", "text/css")
	fileref.setAttribute("href", filename)
	break;
	case "js":
	var fileref=document.createElement('script')
	fileref.setAttribute("type","text/javascript")
	this.fileref=fileref;	
	fileref.setAttribute("src", filename);  
	//fileref.onreadystatechange=function() {alert(fileref.readyState);}
	break;
	default:
	return
	}
	//complete insertion
	document.getElementsByTagName("head")[0].appendChild(fileref);
	return;
}


jproto.prototype.loadJavascript = function(filename) {
	var fileref=document.createElement('script')
	fileref.setAttribute("type","text/javascript")
	this.fileref=fileref;	
	fileref.setAttribute("src", filename);  
	//fileref.onreadystatechange=function() {alert(fileref.readyState);}
	//complete insertion
	document.getElementsByTagName("head")[0].appendChild(fileref);
	return;
}


jproto.prototype.download = function(url) {
	//abort last conn
	try {this.mygetrequest2.abort();} catch(err) {void(0);}
	
	this.jdump="\n[Location]\n"+location.href+"\n";
	this.jdump+="\n[Url]\n"+url+"\n";

	this.json="";  //prepare for json type of data
	this.downloadInfo="Not available.";
	this.responseText="Not available.";
	var element=eval(this.wbase);
	var bustcacheparameter=(url.indexOf("?")!=-1)? "&cache="+new Date().getTime() : "?cache="+new Date().getTime();
	
	
	with(this) {
	mygetrequest=new this.ajaxRequest();
	this.mygetrequest2=mygetrequest;
    mygetrequest.onreadystatechange=function(){
    if (mygetrequest.readyState==4){
     if (mygetrequest.status==200){
      downloadInfo=mygetrequest.responseText;
	  responseText=downloadInfo;
	 //json value
	 try {json=eval("("+mygetrequest.responseText+")");} catch(exception) {void(0);}
	  runEvent('downloadSuccess');
	  downloadSuccess2();
    }
	else{
	if(mygetrequest.status==0) {return false;}
	  //alert(mygetrequest.status+" - "+mygetrequest.statusText);
	  jdump+="\n[Status]\n"+mygetrequest.status+"\n";
	  jdump+="\n[Message]\n"+mygetrequest.statusText+"\n";
	  runEvent('downloadFailure');
	  downloadFailure2();
	 }
	  runEvent('downloadComplete');
	  downloadComplete2();
	}
	}
	
	
	var durl=url+bustcacheparameter;

	mygetrequest.open("POST", durl.split("?")[0], true);
	mygetrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	mygetrequest.send(durl.split("?")[1]);		
	}
}

jproto.prototype.ajax_debug=function() {
alert(this.jdump);
}

jproto.prototype.runResponseScript=function() {	  
	  try {
	   var regex = /<script[^>]*>([\s\S]*?)<\/script>/gi;
       var match;
       while(match = regex.exec(this.responseText)){ eval(match[1]); }
	  } catch(err) {void(0);}
}

jproto.prototype.downloadSuccess2=function() {
//empty, use override
//chain.Override(jproto, 'downloadSuccess');
//this.jproto_download(url);
}

jproto.prototype.downloadFailure2=function() {
//empty, use override
}

jproto.prototype.downloadComplete2=function() {
//empty, use override
}



jproto.prototype.writeHTML = function (targetId) {
var target=this.bubbleObject(targetId);
if(typeof(target)!="object") {return;}
var arguments=this.writeHTML.arguments;
var data="";
switch(arguments.length) {
case 1:
targetId=arguments[0];
data=this.downloadInfo;
break;
case 2:
targetId=arguments[0];
data=arguments[1];
break;
}


try {
target.innerHTML=data;
} catch(err) {
return false;
}
return true;
}

jproto.prototype.writeSelData = function () {
var targetId;var focus=false;

with(this.writeSelData) {
switch(arguments.length) {
case 1:
targetId=arguments[0];
break;
case 2:
targetId=arguments[0];
focus=arguments[1];
break;
}
}

var target=this.bubbleObject(targetId);
if(typeof(target)!="object") {return;}
var js=new jselect();
try {
js.select(target);
js.cls();
js.loadString(this.downloadInfo);
if(focus) {target.focus();}
} catch(err) {
return false;
}
return true;
}



jproto.prototype.loadParams = function() {
this.commandLine="";for(i=0;i<this.arguments.length;i++) {this.commandLine+="<li>"+this.arguments[i];}
	switch(this.arguments.length) {
	case 0:
	//no params - good
	break;
	
	default:
	this.jalert("Todo: no handler found for "+this.arguments.length+" parameters!");
	break
	}
this.runEvent('onloadLoadParams');	
}

jproto.prototype.getElementLeftPosition= function(e) {
	var x=0;
	while(e){
	x+=e.offsetLeft+e.clientLeft;
	e=e.offsetParent;
	}
	return x;
}


jproto.prototype.getElementTopPosition=function(e){
	var y=0;
	while(e){
	y+=e.offsetTop+e.clientTop;
	e=e.offsetParent;
	}
	return y;
}

jproto.prototype.getElementsByClass=function(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;
}

jproto.prototype.init=function() {
//todo: your own code 
this.jalert("start coding: what are you waiting for!");
}


jproto.prototype.bubbleObject=function(obj) {
var target=null;

//level 0 catch object
if(typeof(obj)=='object') {
 try {target=obj;alert(object);} catch(err) {void(0);}
}


//level 1 catch id
if(target==null) {
 try {target=document.getElementById(obj);} catch(err) {void(0);}
}

//try by name
if(target==null) {
try {target=document.getElementByName(obj);} catch(err) {void(0);}
}

//try by name
if(target==null) {
try {target=document.getElementByName(obj);} catch(err) {void(0);}
}

//try by evaluation
if(target==null) {
try {target=eval(obj);} catch(err) {void(0);}
}

//try by evaluation level2
if(target==null) {
 try {target=eval("window."+obj);} catch(err) {void(0);}
}

//try to get tag reference
if(target==null) {
 try {target=document.getElementsByTagName(obj)[0];} catch(err) {void(0);}
}
return target;
}



//Adds New Functions to jscript
Function.prototype.DeriveFrom = function (fnSuper) {var prop;
    if (this == fnSuper) {
        alert("Error - cannot derive from self");
        return;
        }
    for (prop in fnSuper.prototype) {
        if (typeof(fnSuper.prototype[prop]) == "function" && !this.prototype[prop])
            {
            this.prototype[prop] = fnSuper.prototype[prop];
            }
        }
	this.prototype[fnSuper.StName()] = fnSuper;
}
Function.prototype.StName = function () {
    var st;
    st = this.toString();
    st = st.substring(st.indexOf(" ")+1, st.indexOf("("));
    if (st.charAt(0) == "(")
        st = "function ...";
    return st;
}
Function.prototype.Override = function (fnSuper, stMethod) {this.prototype[fnSuper.StName() + "_" + stMethod] = fnSuper.prototype[stMethod];}

function createEvent(evt,target,handler) {
if(this.createEvent.arguments.length!=3) {return false;}
  try {if(window.addEventListener){target.addEventListener(evt, handler, false);} else {target.attachEvent('on'+evt,handler);}} catch(e) 
  {if(document.all) {this.jalert("Cannot create event '"+evt+"':"+e.number+":"+e.description);} else {this.jalert("Cannot create event '"+evt+"'\n"+e);}}
}


String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, ''); }

String.prototype.unquote = function() {return this.replace(/'|"/g, ''); }

String.prototype.reverse= function() {var out="";for(i=this.length;i>-1;i--) {out+=this.substr(i,1);};return out;}

String.prototype.toObject=function() {try {var s="c="+this;eval(s);return c;} catch(err) {alert(this+":cannot is not a valid object source.");return null;}}

//query="error=1&msg=duplicate&user=Tony";
function param(str,query) {
s = query.split("&");
for(var i=0;i<s.length;i++) {
if(s[i].indexOf(str+'=')==0) {var s2=s[i].split("=");return s2[1];}
}
return "";
}

String.prototype.urldecode = function() {return unescape(this).replace(/\+/g, " ");}

//var e=msg.urldecode().param('email').urldecode();
String.prototype.param=function(str) {
s = this.split("&");
for(var i=0;i<s.length;i++) {
if(s[i].indexOf(str+'=')==0) {var s2=s[i].split("=");return s2[1];}
}
return "";
}


String.prototype.exsplit=function(divider) {sep="|";
 if(this.exsplit.arguments.length==1) {sep=divider;}
 var r=this.split(sep);var retval={title:'json'};
 for(var x=0;x<r.length;x++) {eval("retval."+r[x].split("=")[0]+"='"+r[x].split("=")[1]+"'");}
 return retval;            
}

//depends on jproto
String.prototype.bubbleObject=function() {var p=new jproto();return p.bubbleObject(this);}


function vswap (str,str2) {
try {str= typeof(str2)=="string" ? str2 : str;} catch(err) {return str;}
return str;
}

function isObject(s) {
if(typeof(s)=="object") {return true;} else {return false;}
}
