/** Global Objects for GJS */
window.gjs = typeof(gjs)=='undefined'?{}:gjs||{};
window.gsso = typeof(gsso)=='undefined'?{}:gsso||{};
window.params={};


/**
 * MD5 on the browser
 * Copyright (C) Paul Johnston (http://pajhome.org.uk/crypt/md5)
 */
var hexcase=0;function hex_md5(a){return rstr2hex(rstr_md5(str2rstr_utf8(a)))}function hex_hmac_md5(a,b){return rstr2hex(rstr_hmac_md5(str2rstr_utf8(a),str2rstr_utf8(b)))}function md5_vm_test(){return hex_md5("abc").toLowerCase()=="900150983cd24fb0d6963f7d28e17f72"}function rstr_md5(a){return binl2rstr(binl_md5(rstr2binl(a),a.length*8))}function rstr_hmac_md5(c,f){var e=rstr2binl(c);if(e.length>16){e=binl_md5(e,c.length*8)}var a=Array(16),d=Array(16);for(var b=0;b<16;b++){a[b]=e[b]^909522486;d[b]=e[b]^1549556828}var g=binl_md5(a.concat(rstr2binl(f)),512+f.length*8);return binl2rstr(binl_md5(d.concat(g),512+128))}function rstr2hex(c){try{hexcase}catch(g){hexcase=0}var f=hexcase?"0123456789ABCDEF":"0123456789abcdef";var b="";var a;for(var d=0;d<c.length;d++){a=c.charCodeAt(d);b+=f.charAt((a>>>4)&15)+f.charAt(a&15)}return b}function str2rstr_utf8(c){var b="";var d=-1;var a,e;while(++d<c.length){a=c.charCodeAt(d);e=d+1<c.length?c.charCodeAt(d+1):0;if(55296<=a&&a<=56319&&56320<=e&&e<=57343){a=65536+((a&1023)<<10)+(e&1023);d++}if(a<=127){b+=String.fromCharCode(a)}else{if(a<=2047){b+=String.fromCharCode(192|((a>>>6)&31),128|(a&63))}else{if(a<=65535){b+=String.fromCharCode(224|((a>>>12)&15),128|((a>>>6)&63),128|(a&63))}else{if(a<=2097151){b+=String.fromCharCode(240|((a>>>18)&7),128|((a>>>12)&63),128|((a>>>6)&63),128|(a&63))}}}}}return b}function rstr2binl(b){var a=Array(b.length>>2);for(var c=0;c<a.length;c++){a[c]=0}for(var c=0;c<b.length*8;c+=8){a[c>>5]|=(b.charCodeAt(c/8)&255)<<(c%32)}return a}function binl2rstr(b){var a="";for(var c=0;c<b.length*32;c+=8){a+=String.fromCharCode((b[c>>5]>>>(c%32))&255)}return a}function binl_md5(p,k){p[k>>5]|=128<<((k)%32);p[(((k+64)>>>9)<<4)+14]=k;var o=1732584193;var n=-271733879;var m=-1732584194;var l=271733878;for(var g=0;g<p.length;g+=16){var j=o;var h=n;var f=m;var e=l;o=md5_ff(o,n,m,l,p[g+0],7,-680876936);l=md5_ff(l,o,n,m,p[g+1],12,-389564586);m=md5_ff(m,l,o,n,p[g+2],17,606105819);n=md5_ff(n,m,l,o,p[g+3],22,-1044525330);o=md5_ff(o,n,m,l,p[g+4],7,-176418897);l=md5_ff(l,o,n,m,p[g+5],12,1200080426);m=md5_ff(m,l,o,n,p[g+6],17,-1473231341);n=md5_ff(n,m,l,o,p[g+7],22,-45705983);o=md5_ff(o,n,m,l,p[g+8],7,1770035416);l=md5_ff(l,o,n,m,p[g+9],12,-1958414417);m=md5_ff(m,l,o,n,p[g+10],17,-42063);n=md5_ff(n,m,l,o,p[g+11],22,-1990404162);o=md5_ff(o,n,m,l,p[g+12],7,1804603682);l=md5_ff(l,o,n,m,p[g+13],12,-40341101);m=md5_ff(m,l,o,n,p[g+14],17,-1502002290);n=md5_ff(n,m,l,o,p[g+15],22,1236535329);o=md5_gg(o,n,m,l,p[g+1],5,-165796510);l=md5_gg(l,o,n,m,p[g+6],9,-1069501632);m=md5_gg(m,l,o,n,p[g+11],14,643717713);n=md5_gg(n,m,l,o,p[g+0],20,-373897302);o=md5_gg(o,n,m,l,p[g+5],5,-701558691);l=md5_gg(l,o,n,m,p[g+10],9,38016083);m=md5_gg(m,l,o,n,p[g+15],14,-660478335);n=md5_gg(n,m,l,o,p[g+4],20,-405537848);o=md5_gg(o,n,m,l,p[g+9],5,568446438);l=md5_gg(l,o,n,m,p[g+14],9,-1019803690);m=md5_gg(m,l,o,n,p[g+3],14,-187363961);n=md5_gg(n,m,l,o,p[g+8],20,1163531501);o=md5_gg(o,n,m,l,p[g+13],5,-1444681467);l=md5_gg(l,o,n,m,p[g+2],9,-51403784);m=md5_gg(m,l,o,n,p[g+7],14,1735328473);n=md5_gg(n,m,l,o,p[g+12],20,-1926607734);o=md5_hh(o,n,m,l,p[g+5],4,-378558);l=md5_hh(l,o,n,m,p[g+8],11,-2022574463);m=md5_hh(m,l,o,n,p[g+11],16,1839030562);n=md5_hh(n,m,l,o,p[g+14],23,-35309556);o=md5_hh(o,n,m,l,p[g+1],4,-1530992060);l=md5_hh(l,o,n,m,p[g+4],11,1272893353);m=md5_hh(m,l,o,n,p[g+7],16,-155497632);n=md5_hh(n,m,l,o,p[g+10],23,-1094730640);o=md5_hh(o,n,m,l,p[g+13],4,681279174);l=md5_hh(l,o,n,m,p[g+0],11,-358537222);m=md5_hh(m,l,o,n,p[g+3],16,-722521979);n=md5_hh(n,m,l,o,p[g+6],23,76029189);o=md5_hh(o,n,m,l,p[g+9],4,-640364487);l=md5_hh(l,o,n,m,p[g+12],11,-421815835);m=md5_hh(m,l,o,n,p[g+15],16,530742520);n=md5_hh(n,m,l,o,p[g+2],23,-995338651);o=md5_ii(o,n,m,l,p[g+0],6,-198630844);l=md5_ii(l,o,n,m,p[g+7],10,1126891415);m=md5_ii(m,l,o,n,p[g+14],15,-1416354905);n=md5_ii(n,m,l,o,p[g+5],21,-57434055);o=md5_ii(o,n,m,l,p[g+12],6,1700485571);l=md5_ii(l,o,n,m,p[g+3],10,-1894986606);m=md5_ii(m,l,o,n,p[g+10],15,-1051523);n=md5_ii(n,m,l,o,p[g+1],21,-2054922799);o=md5_ii(o,n,m,l,p[g+8],6,1873313359);l=md5_ii(l,o,n,m,p[g+15],10,-30611744);m=md5_ii(m,l,o,n,p[g+6],15,-1560198380);n=md5_ii(n,m,l,o,p[g+13],21,1309151649);o=md5_ii(o,n,m,l,p[g+4],6,-145523070);l=md5_ii(l,o,n,m,p[g+11],10,-1120210379);m=md5_ii(m,l,o,n,p[g+2],15,718787259);n=md5_ii(n,m,l,o,p[g+9],21,-343485551);o=safe_add(o,j);n=safe_add(n,h);m=safe_add(m,f);l=safe_add(l,e)}return Array(o,n,m,l)}function md5_cmn(h,e,d,c,g,f){return safe_add(bit_rol(safe_add(safe_add(e,h),safe_add(c,f)),g),d)}function md5_ff(g,f,k,j,e,i,h){return md5_cmn((f&k)|((~f)&j),g,f,e,i,h)}function md5_gg(g,f,k,j,e,i,h){return md5_cmn((f&j)|(k&(~j)),g,f,e,i,h)}function md5_hh(g,f,k,j,e,i,h){return md5_cmn(f^k^j,g,f,e,i,h)}function md5_ii(g,f,k,j,e,i,h){return md5_cmn(k^(f|(~j)),g,f,e,i,h)}function safe_add(a,d){var c=(a&65535)+(d&65535);var b=(a>>16)+(d>>16)+(c>>16);return(b<<16)|(c&65535)}function bit_rol(a,b){return(a<<b)|(a>>>(32-b))};

/**
 * Base64 CoDec
 */
if(typeof btoa=='undefined'){function btoa(a){var b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';var d=[];var c=0;while(c<a.length){var e=a.charCodeAt(c++);var f=a.charCodeAt(c++);var g=a.charCodeAt(c++);var h=(e<<16)+((f||0)<<8)+(g||0);var i=(h&(63<<18))>>18;var j=(h&(63<<12))>>12;var k=isNaN(f)?64:(h&(63<<6))>>6;var l=isNaN(g)?64:(h&63);d[d.length]=b.charAt(i);d[d.length]=b.charAt(j);d[d.length]=b.charAt(k);d[d.length]=b.charAt(l)}return d.join('')}}if(typeof atob=='undefined'){function atob(a){var b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';var d={strlen:(a.length%4!=0),chars:new RegExp('[^'+b+']').test(a),equals:(/=/.test(a)&&(/=[^=]/.test(a)||/={3}/.test(a)))};if(d.strlen||d.chars||d.equals)throw new Error('Invalid base64 data');var e=[];var c=0;while(c<a.length){var f=b.indexOf(a.charAt(c++));var g=b.indexOf(a.charAt(c++));var h=b.indexOf(a.charAt(c++));var i=b.indexOf(a.charAt(c++));var j=(f<<18)+(g<<12)+((h&63)<<6)+(i&63);var k=(j&(255<<16))>>16;var l=(h==64)?-1:(j&(255<<8))>>8;var m=(i==64)?-1:(j&255);e[e.length]=String.fromCharCode(k);if(l>=0)e[e.length]=String.fromCharCode(l);if(m>=0)e[e.length]=String.fromCharCode(m)}return e.join('')}}

/** Add Extra Stuff to Default Classes */
/* String Find Function */
String.prototype.find=function(what){return(this.indexOf(what)>=0 ? true : false);}
/* String Capitalize Function */
String.prototype.capitalize = function capitalize(){var b=this,a=this.split(/[ ,.]/);for(I=0,L=a.length;I<L;I++){var c = a[I].substring(0,1).toUpperCase()+a[I].substring(1).toLowerCase();b=b.replace(a[I],c);}return b;}
/* Add filter method to the Array implementation for IE */
if(!Array.prototype.filter){Array.prototype.filter=function(fun){if(typeof(fun)!="function") throw new TypeError("1st argument not a function");var res=[],thisp=arguments[1],len=this.length,i=0;for(;i<len; i++){if(i in this){var val=this[i];if(fun.call(thisp,val,i,this)) res.push(val);}}return res;};}
/* Add Array.indexOf to IE */
if(!Array.prototype.indexOf){Array.prototype.indexOf=function(obj){for(var i=0,l=this.length;i<l;i++){if(this[i]==obj){return i;}}return -1;}}
/* Other Array Stuff */
if(!Array.prototype.pull){Array.prototype.pull = function(index){index=index||Math.floor(Math.random()*this.length);var val=this[index];var arr=this.slice(0,index).concat(this.slice(index+1));this.length=Math.max(this.length-1,0);for(var i=0;i<this.length;i++)this[i]=arr[i];return val;}}
if(!Array.prototype.clone){Array.prototype.clone = function(){var arr=[];for(var i=0,l=this.length;i<l;i++) arr.push(this[i]);return arr;}}
if(!Array.prototype.random){Array.prototype.random = function(count){var tmpArr=this.clone();var _arr=[];for(var i=0;i<count;i++)_arr.push(tmpArr.pull());return _arr;}}

gjs.alert = function(m){return window.alert(m);}
gjs.prompt = function(m){return window.prompt(m);}
gjs.confirm = function(m){return window.confirm(m);}

/** DOM Stuff */

/* Event Binding */
window.addEvent = function addEvent(n,e,h){ 
 if(n.addEventListener){n.addEventListener(e,h,false);}
 else if(n.attachEvent){n.attachEvent("on"+e,h);}
 else return false;
}
window.fixE = function fixE(e){
  if(!e && window.event) e = window.event;
  if(typeof e.layerX == 'undefined') e.layerX = e.offsetX;
  if(typeof e.layerY == 'undefined') e.layerY = e.offsetY;
  var btMap = [0,1,3,3,2];
  if(typeof e.which == 'undefined')  e.which = btMap[e.button];
  return e;
}
window.getNode = function getNode(e){
  var node = (!!e.target)?e.target:((!!document.all)?e.srcElement:this);
  if(node.nodeType == 3) node=node.parentNode;
  return node;
}
window.cancelE = function cancelE(e){
  if(typeof(e.preventDefault)=='function') e.preventDefault();
  else e.returnValue = false;

  if(typeof(e.stopPropagation)=='function') e.stopPropagation();
  if(typeof(e.preventBubble)=='function') e.preventBubble();
}


/* Browser Detection Object */
var Browser={IE:!!(window.attachEvent&&!window.opera),Opera:!!window.opera,WebKit:navigator.userAgent.indexOf('AppleWebKit/')>-1,Gecko:navigator.userAgent.indexOf('Gecko')>-1&&navigator.userAgent.indexOf('KHTML')==-1,MobileSafari:!!navigator.userAgent.match(/Apple.*Mobile.*Safari/)};

/* ID/Name/TagName Selector */
window._$=function(a){if(typeof(a)=='string'){var b=document.getElementById(a);if(!b){b=document.getElementsByName(a);if(b.length==0)b=null;else b=b[0]}return b}else if(typeof(a)=='object')return a;else return null};if(typeof(jQuery)=='undefined')window.$=window._$;

/* CSS Selectors */
window.$$=window.getElementsBySelector=function getElementsBySelector(b,d){d=_$(d)||document;var i,j,selid="",selclass="",tag=b,tag2="",v2,k,f,a,s=[],objlist=[],c;if(b.find("#")){if(b.find(" ")){s=b.split(" ");var e=s[0].split("#");if(e.length==1){return objlist}f=d.getElementById(e[1]);if(f){v=f.getElementsByTagName(s[1]);for(i=0,L=v.length;i<L;i++)objlist.push(v[i])}return objlist}else{s=b.split("#");tag=s[0];selid=s[1];if(selid!=""){f=d.getElementById(selid);if(f)objlist.push(f);return objlist}}}if(b.find(".")){s=b.split(".");tag=s[0];selclass=s[1];if(selclass.find(" ")){s=selclass.split(" ");selclass=s[0];tag2=s[1]}}var v=d.getElementsByTagName(tag);if(selclass==""){for(i=0,L=v.length;i<L;i++)objlist.push(v[i]);return objlist}for(i=0,L=v.length;i<L;i++){c=v[i].className.split(" ");for(j=0,K=c.length;j<K;j++){if(c[j]==selclass){if(tag2=="")objlist.push(v[i]);else{v2=v[i].getElementsByTagName(tag2);for(k=0,M=v2.length;k<M;k++)objlist.push(v2[k])}}}}return objlist}

/* Create new Nodes */
function ce(el){return document.createElement(el);}
function tn(text){return document.createTextNode(text);}
function loadJS(j){var n=ce("script");n.src=j;_$("ScriptContainer").appendChild(n);}

/* CSS Class Manipulation */
function hasClass(ele,cls){return _$(ele).className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));}
function addClass(ele,cls){ele=_$(ele);if(!this.hasClass(ele,cls)){ele.className += " "+cls;}}
function removeClass(ele,cls){ele=_$(ele);if(hasClass(ele,cls)){var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');ele.className=ele.className.replace(reg,' ');}}

/* Find Node Coordinates */
function findPos(e){l=0;b=Math.floor((e.offsetHeight+e.clientHeight)/2);if(e.offsetParent) do{l+=e.offsetLeft;b+=e.offsetTop;}while(e=e.offsetParent);return {"x":l,"y":b};}
function findPosition(o){var l=t=0;if(o.offsetParent){do{l+=o.offsetLeft;t+=o.offsetTop;}while(o=o.offsetParent);}return {"x":l,"y":t};}

/** AJAX Thread */
window.getThread=function(){var t=null;if(window.XMLHttpRequest){t=new XMLHttpRequest();if(t.overrideMimeType)t.overrideMimeType('text/html')}else if(window.ActiveXObject){try{t=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{t=new ActiveXObject("Microsoft.XMLHTTP")}catch(E){}}}return t};

/** Tab Stuff */
var tabSet=function(a){this._tC=_$(a);this.initialize()};tabSet.prototype={_lI:99,_tC:null,_tabs:null,_sT:"",_tCH:null,initialize:function(){this._tabs={};t=document.createElement("div");t.setAttribute("style","clear: both; width: auto; height: 1px; line-height: 22px;");this._tC.appendChild(t)},addTab:function(a,b,c){if(!_$(b))return;var t=document.createElement("div");t.setAttribute("style","float:left;");t.innerHTML="<div class='left'></div><div class='middle'>"+a+"</div><div class='right'></div><div class='space'></div>";addClass(t,"tab");var d=this;addEvent(t,"click",function(){d.selectTab(a)});addClass(b,"panel");this._tC.insertBefore(t,this._tC.lastChild);this._tabs[a]={"node":t,"content":_$(b),"handler":c}},selectTab:function(a){var b=this._tabs[a];if(typeof(b)=='undefined')return;this._sT=a;for(var c in this._tabs){c=this._tabs[c];removeClass(c.node,"selected");removeClass(c.content,"selectedPanel");c.content.style.zIndex=this._lI}addClass(b.node,"selected");addClass(b.content,"selectedPanel");b.content.style.zIndex=this._lI+2;if(typeof(b.handler)=='function')b.handler.apply(b,[{"tabLabel":a}]);if(typeof(this._tCH)=='function')this._tCH.apply(this,[])},setTabHandler:function(a){this._tCH=a}};


/**
 * Auto Completion/Suggestion
 */
// AC Constructor
gjs.AutoCompleter=function(args){
  var target = args["target"]||"quote";
  var source = args["source"]||"ac.php?q=";
  this._selectionHandler_ = args["selectionHandler"]||function(){return;}
  this._clearHandler_ = args["clearHandler"]||function(){return;}
  this._timerDelay_ = args["timerDelay"]||1;
  this._count_ = args["count"]||10;
  this._id_ = "ac_"+Math.floor(Math.random()*10000000);
  gjs.AutoCompleter.AC_Map[this._id_] = this;
  this.init(target,source);
};

// Static Members
gjs.AutoCompleter.searchCache = {};
gjs.AutoCompleter.AC_Map = {};
gjs.AutoCompleter.Node_Map = {};
gjs.AutoCompleter.complete = function(options,target,q){
  var ac = gjs.AutoCompleter.AC_Map[target];
  if(!!ac && typeof(ac.complete)=='function') ac.complete(options,q);
};

// Actual Class
gjs.AutoCompleter.prototype={_index:-1,init:function(a,b){this._target_=document.getElementById(a);this._source_=b;this._target_._ac=this;this._active=false;gjs.AutoCompleter.Node_Map[a]=this;var c=findPos(this._target_);this._optTable_=document.createElement("ol");this._optTable_.style.position="absolute";this._optTable_.style.top=c.y;this._optTable_.style.left=c.x;this._optTable_.style.display='none';this._optTable_.style.width=this._target_.clientWidth+"px";addClass(this._optTable_,"gjsAC");this._target_.setAttribute('autocomplete','off');this._target_.parentNode.insertBefore(this._optTable_,this._target_);this._target_.parentNode.insertBefore(this._target_,this._optTable_);addEvent(this._target_,"keyup",this._key_up);addEvent(this._target_,"keydown",this._key_down);addEvent(this._target_,"keypress",this._key_press);addEvent(this._target_,"blur",this._blur)},_renderer:function(a,b){},_clear:function(){var a=this._optTable_;setTimeout(function(){a.style.display='none'},100);this._active=false},_request:function(){var q=this._target_.value;var a=gjs.AutoCompleter.searchCache[q];if(typeof(a)!='undefined')this._process(a,q);else{this._optTable_.innerHTML='';this._index=-1;if(typeof(this._source_)=='object'&&this._source_ instanceof Array)this._filter(q);else if(typeof(this._source_)=='string'&&q.length>1)loadJS(this._source_+q+"&t="+this._id_+"&c="+this._count_)}},_select:function(a){this._target_.value=this._lastResults[a][1];if(typeof(this._selectionHandler_)=='function')this._selectionHandler_.apply(this,[this._lastResults[a]])},_highlight:function(a){var b=this._optTable_.getElementsByTagName("li");if(this._index>b.length-1)this._index=b.length-1;if(this._index<0)this._index=0;for(var i=b.length-1;i>-1;i--)removeClass(b[i],"selected");if(this._index>-1&&this._index<b.length)addClass(b[this._index],"selected");if(typeof(a)=='undefined')this._select(this._index)},complete:function(a,q){gjs.AutoCompleter.searchCache[q]=a;this._process(a,q)},_filter:function(q){var a={};var r=new RegExp("^"+q);for(var i=0,c=0,l=this._source_.length;i<l&&c<10;i++){if(!!this._source_[i].toLowerCase().match(r)){a[i]=[this._source_[i]];c++}}this._process(a,q)},_process:function(a,q){this._lastResults=[];this._optTable_.innerHTML='';i=0;for(opt in a){var l=document.createElement("li");if(typeof(a[opt][0])=="undefined")return;var b=a[opt][0];s=b.toLowerCase().indexOf(q.toLowerCase());m=b.substr(s,q.length);l.innerHTML=b.replace(m,m.bold());this._optTable_.appendChild(l);l.setAttribute("class",(i%2==0)?"even":"odd");var c=this._target_.getAttribute("id")+"_li"+i;l.setAttribute("id",c);gjs.AutoCompleter.Node_Map[c]=this;this._lastResults[i]=[opt].concat(a[opt]);i++;addEvent(l,"click",this._m_click);addEvent(l,"mouseover",this._m_over);addEvent(l,"mouseout",this._m_out)}this._active=true;this._optTable_.style.display='block'},_key_up:function(e){if(!e&&window.event)e=window.event;var a=(!!document.all)?e.srcElement:this;var b=gjs.AutoCompleter.Node_Map[a.getAttribute("id")];if(typeof(b._timer)!='undefined'&&b._timer!=null){clearTimeout(b._timer);delete(b._timer)}switch(b._key_){case 9:case 13:case 27:b._clear();case 37:case 39:return;case 38:b._index--;break;case 40:b._index++;break;default:if(b._key_>32||b._key_==8){b._timer=setTimeout(function(){b._request.apply(b,[])},b._timerDelay_);if(typeof(b._clearHandler_)=='function')b._clearHandler_.apply(b,[])}return}if(b._active)b._highlight()},_key_press:function(e){},_key_down:function(e){if(!e&&window.event)e=window.event;var a=(!!document.all)?e.srcElement:this;var b=gjs.AutoCompleter.Node_Map[a.getAttribute("id")];if(e)b._key_=e.keyCode;else b._key_=e.which;switch(b._key_){case 9:case 13:setTimeout(function(){b._target_.focus()},10)}},_blur:function(e){var a=(!!document.all)?e.srcElement:this;var b=gjs.AutoCompleter.Node_Map[a.getAttribute("id")];setTimeout(function(){b._clear()},10)},_m_click:function(e){var a=(!!document.all)?e.srcElement:this;if(!a.tagName.toLowerCase().match("li"))return;var b=gjs.AutoCompleter.Node_Map[a.getAttribute("id")];var c=a.getAttribute("id").indexOf("_li")+3;c=parseInt(a.getAttribute("id").substr(c));b._select(c)},_m_over:function(e){var a=(!!document.all)?e.srcElement:this;if(!a.tagName.toLowerCase().match("li"))return;var b=gjs.AutoCompleter.Node_Map[a.getAttribute("id")];addClass(a,"selected");var c=a.getAttribute("id").indexOf("_li")+3;c=parseInt(a.getAttribute("id").substr(c));b._index=c;b._highlight({})},_m_out:function(e){var a=(!!document.all)?e.srcElement:this;if(!a.tagName.toLowerCase().match("li"))return;var b=gjs.AutoCompleter.Node_Map[a.getAttribute("id")];removeClass(a,"selected");b._index=-1}};

function serializeForm(form){
  var el = form.elements;
  var ac = form.getAttribute("action");
  var params = [];
  for(var i=0,l=el.length;i<l;i++){
    if(el[i].name!=null && el[i].value!=null) params.push(el[i].getAttribute("name")+"="+el[i].value);
  }
  return ac+"?"+params.join('&');
}


/** Adding global eval function **/
gjs.globaleval = function(data, type) {
	
	if(!data || /\S/.test(data) == false) return; // data is null or only consists of spaces
	
	var script = document.createElement("script");
	script.type = "text/javascript";
	if(type == "url") {script.src = data;}
	else {
		if(document.all) script.text = data; // appendChild fails on script element in ie
		else script.appendChild(document.createTextNode(data));
	}
	
	var head = document.getElementsByTagName("head")[0] || document.documentElement;
	head.insertBefore( script, head.firstChild );
	//head.appendChild(script);
	//head.removeChild( script );
}

/** SSO Stuff*/
gsso.checkUser = function(userid){}

/** Portfolio Stuff */
window.gpf = {
  watchCompany:function(id){loadJS("?r=portfolio/addwatchlist&univ_id="+id);},
  removeCompany:function(id){loadJS("?r=portfolio/removewatchlist&univ_id="+id);},
  watchMF:function(id){loadJS("?r=portfolio/addwatchlist&mf=1&univ_id="+id);},
  removeMF:function(id){loadJS("?r=portfolio/removewatchlist&mf=1&univ_id="+id);},
  createNewPF:function(){var name = gjs.prompt("Name of the new Portfolio","");
    if(!!name){loadJS("?r=portfolio/create&name="+name);return true}
    else return false;
  },
  removePortfolio:function(pid){if(confirm("Sure you want to delete the portfolio?")) loadJS("?r=portfolio/remove&pid="+pid);},
  removeFromPortfolio:function(id,uid){if(confirm("Sure you want to remove this from portfolio?")) loadJS("?r=portfolio/removeFromPortfolio&id="+id+"&pid="+window.params.pid+"&uid="+uid);},
  removedFromPortfolio:function(uid){
    //var node = $("portfolioBreak_"+uid);
    var node = $("portfolio");
    if(node){
      node = node.parentNode;
      var func = node.refresh;
      if(typeof(func)=='function') func.call(node.obj);
    }
    node = $("portDetail");
    if(node){
      node = node.getElementsByTagName("div")[1];
      var func = node.refresh;
      if(typeof(func)=='function') func.call(node.obj);
    }
  },
  fetchPFList:function(){loadJS("?r=portfolio/list&menu=1");},
  addToPf:function(){
    var frm = $('modalInner').getElementsByTagName("form")[0];
    if(frm.quan.value != parseInt(frm.quan.value) || parseInt(frm.quan.value) < 0){
      alert("Invalid Quantity");return false;
    }
    if(frm.price.value != parseFloat(frm.price.value) || parseFloat(frm.price.value) < 0){
      alert("Invalid Price");return false;
    }
    if(frm.date.value.length == 0){
      alert("Select the date");return false;
    }

    Modal.loader.show();
    loadJS(serializeForm(frm)); 
    return false;
  }
}

gpf.watchlistHandler = function(id,wli){
  var node = _$("pf"+wli+"_"+id);
  //var company = node.nextSibling||node.previousSibling;
  var company = node.parentNode.getElementsByTagName("b")[0];
  if(typeof(company)=='undefined' || !company) return;
  company = (typeof(company.textContent)!='undefined')?company.textContent:company.innerText;

  var url = window.location.href.toLowerCase();
  var ent = (wli==-1)?"MF":"Company";

  if(hasClass(node,"add")){
    node.className = "remove";
    node.setAttribute("title","Remove from watchlist");
    if(!url.match("r=site/company") && !url.match("r=site/mutualfunddetails"))
      node.innerHTML = "<span onclick='gpf.remove"+ent+"("+id+");'></span>";
    else node.innerHTML = "<span onclick='gpf.remove"+ent+"("+id+");'>[ Remove from Watchlist ]</span>";
    
    if(typeof(company)=='undefined') company = (wli==-1)?"Mutual Fund":"Company";
    gjs.alert(company+" added to your watchlist");
  }else{
    if(!!url.match("r=portfolio/watchlist")){
      var refNodeSuffix = (wli==-1)?"MF":"";
      var refNode = _$("watchlist"+refNodeSuffix);
      if(refNode){
        refNode = refNode.parentNode;
        var refFunc = refNode.refresh;
        if(typeof(refFunc)=='function') refFunc.call(refNode.obj);
      }
      refNode = _$("watchlist"+refNodeSuffix+"news");
      if(refNode){
        refNode = refNode.parentNode;
        refFunc = refNode.refresh;
        if(typeof(refFunc)=='function') refFunc.call(refNode.obj);
      }
    }else{
      node.className = "add";
      node.setAttribute("title","Add to watchlist");
      if(!url.match("r=site/company") && !url.match("r=site/mutualfunddetails"))
        node.innerHTML = "<span onclick='gpf.watch"+ent+"("+id+");'></span>";
      else node.innerHTML = "<span onclick='gpf.watch"+ent+"("+id+");'>[ Add to watchlist ]</span>";
    }
    if(typeof(company)=='undefined') company = (wli==-1)?"Mutual Fund":"Company";
    gjs.alert(company+" removed from your watchlist");  
  }
}

gpf.portfolioListHandler = function(code,pid){
  if(!!window.params.r.match("portfolio")){
    if($('pfl').getElementsByTagName("a").length<2) window.history.go(0);
    switch(code){
      case 2:
        if(parseInt(window.params.pid) == parseInt(pid)) window.history.go(0);
      case 1:
        var refNode = _$("portfoliolist");
        if(refNode && refNode.parentNode){
          refNode = refNode.parentNode;
          var refFunc = refNode.refresh;
          if(typeof(refFunc)=='function') refFunc.call(refNode.obj);
        }
        break;
    }
  }else gpf.fetchPFList();
}

gpf.breakDetails = function(univ_id){
  var refNode = _$("pfbu_"+univ_id);
  refNode = refNode.parentNode.parentNode;
  var colCount = refNode.childNodes.length;
  var next = refNode.nextSibling;
  if(!next || typeof(next)==undefined || hasClass(next,"e") || hasClass(next,"o")){
    var table = refNode.parentNode;
    if(!!table.nodeName.toLowerCase().match("tbody"))
      table = table.parentNode;
    var index = refNode.rowIndex+1;
    var newRow = table.insertRow(index);
    //newRow.setAttribute("style","display:none;"); setAttribute doesn't work properly in ie
	newRow.style.display = "none";
    var newCell = newRow.insertCell(0);
    newCell.setAttribute("colspan",colCount);
    newCell.colSpan = colCount;
    newCell.setAttribute("class","tdContainer");

    // Now Get Content
    var t = window.getThread();
    t.onreadystatechange = function(){
      if(t.readyState==4 && t.status==200){
        newCell.innerHTML = t.responseText;
      }
    };

    t.open('GET',"index.php?r=portfolio/break&pid="+window.params.pid+"&univ_id="+univ_id,true);
    t.send('');
    next = newRow;
  }
  if(hasClass(refNode,"open")) removeClass(refNode,"open");
  else addClass(refNode,"open");
/*var refNode = _$("pfbu_"+univ_id);
  next = refNode.parentNode.parentNode.nextSibling;*/
  
  next.style.display = (next.style.display=="none")?'':'none';
}

gpf.handlePL = function(pfl){
  var i = 0;
  var html = ["<select name='pid'>"];
  for(var pid in pfl) {
    html.push("<option value='");
    html.push(pid);
    html.push("'>");
    html.push(pfl[pid]);
    html.push("</option>")
    i++;
  }
  html.push("</select>");
  if(i>0){
    var text = $('pfAddForm').innerHTML;
    text = text.replace("{1}",$('compname').innerHTML);
    text = text.replace("{2}",$('compname').getAttribute("rel"));
    text = text.replace("{3}",html.join(''));
    text = text.replace("{4}",parseFloat($('bse_current').innerHTML.replace(/,/g,"")));
    text = text.replace(/\{5\}/g,"dpBox");
    Modal.show(text);
  }else if(gjs.confirm("You have no portfolios. Would you like to create one now ?")){
    gpf.createNewPF();
  }
}

gpf.added2PL = function(pid){
  Modal.hide();
  window.location.href="?r=portfolio/details&pid="+pid;
}

window.Widget = function(){return this.init.apply(this, arguments);};
window.Widget.init = function(){
  var divWidgets = document.getElementsByTagName("div");
  for(i=0;i<divWidgets.length;i++){
    var tw = divWidgets[i];
    if(!tw.getAttribute("rel") || !tw.getAttribute("rel").match("widget")) continue;
    new Widget(tw);
  }
}
window.Widget.prototype = {
  _node:null,
  _timer:null,
  refresh:function(url){
    var url = url||this._node.getAttribute("gjs:url");
    var t = window.getThread();
    if(!url || url.length < 2 || !t) return;
    var inst = this._node;
    this.startLoader();
    t.onreadystatechange = function(){
      if(t.readyState==4 && t.status==200){
        inst.innerHTML = t.responseText;
        if(inst.obj && typeof(inst.obj.endLoader)=='function') inst.obj.endLoader();
      }
    };
    t.open('GET', url+"&ajax=1", true);
    t.send('');
  },
  startLoader:function(){
    this._node._loader.style.width = this._node.clientWidth+"px";
    this._node._loader.style.height = this._node.clientHeight+"px";
    this._node._loader.style.visibility='visible';
  },
  endLoader:function(){
    var inst = this._node;
    window.setTimeout(function(){inst._loader.style.visibility='hidden';inst.style.backgroundColor = "#FFFEE0";},500);
    window.setTimeout(function(){inst.style.backgroundColor="";},2000);
  },
  init:function(node){
    this._node = _$(node);
    this._node.refresh = this.refresh;
    this._node.obj = this;
    
    var refTime = this._node.getAttribute("gjs:refTime");
    if(!!refTime && parseInt(refTime) > 0){
      var inst = this;
      this._timer = window.setInterval(function(){inst.refresh.call(inst);},parseInt(refTime)*1000);
    }

    // Add Loader Layer
    var lDiv = document.createElement("div");
    if(typeof(this._node._loader)!='undefined') return;
    lDiv.className = "overlay";
    lDiv.setAttribute("style","width:"+this._node.clientWidth+"px;height:"+this._node.clientHeight+"px;");
    this._node._loader = lDiv;
    this._node.parentNode.insertBefore(lDiv,this._node);

    // Handle pagination Links using Event Delegation
    addEvent(this._node,"click",this.clickHandler);

    // Add add button and copy url button
    var addable = this._node.getAttribute("gjs:addable");
    var url = this._node.getAttribute("gjs:url");
    if(!addable || !url || !!_$('ssologin-test')) return;
    
    var bDiv = document.createElement("div");
    bDiv.className = "wButtons";
    //bDiv.setAttribute("style","display:none;");
	bDiv.style.display = "none";
    addEvent(this._node.parentNode,"mouseover",function(){bDiv.style.display = "";});
    addEvent(this._node.parentNode,"mouseout", function(){bDiv.style.display = "none";});
    
    var html = [];
    html.push("<div>");
    html.push("<a href='javascript:void(0);' title='Add to my finance' class='addBt'></a>");
    html.push(" <a href='javascript:void(0);' title='Copy URL to this widget' class='copyBt'></a>");
    html.push("</div>");
    bDiv.innerHTML = html.join('');
    this._node.parentNode.insertBefore(bDiv,this._node);
    
    // Handle buttons using Event Delegation
    addEvent(bDiv,"click",this.btHandler);
  },
  clickHandler:function(e){
    e = fixE(e);
    node = getNode(e);
    if(node.tagName.toLowerCase() != "a" || !node.getAttribute("gjs:url")) return;
    cancelE(e);

    // TODO : Put boundry conditions to prevent too much recursion
    bNode = node;
    while(!hasClass(bNode,"widget")) bNode = bNode.parentNode;
    bNode.refresh.call(bNode.obj,node.getAttribute("gjs:url"));
    return false;
  },
  btHandler:function(e){
    e = fixE(e);
    node = getNode(e);
    if(node.tagName.toLowerCase() != "a") return;
    cancelE(e);
    
    var w = node.parentNode.parentNode.nextSibling;
    var url =  w.getAttribute("gjs:url");
	// SPL: check for chart, modify distro scripts
	var chartflag = false;
	if(url.search("Chart") > 0) { chartflag = true; }
    var time = w.getAttribute("gjs:refTime")||0;

    switch(node.className.toLowerCase()){
      case "addbt":
        loadJS("?r=profile/addwidget&url="+escape(url)+"");
        break;
      case "copybt":
        var text = _$('distroBox').innerHTML;
        text = text.replace("{1}","http://finance.guruji.com/finance/index.php"+url);
        //text = text.replace("{2}",time);
        var iwidth;
        if(w.offsetWidth<352) { iwidth = 372; } else { iwidth = w.offsetWidth+20;} // accounting for minimum widget width
        if(document.all) iwidth+=20;
        text = text.replace("{2}", iwidth);
        text = text.replace("{3}", w.offsetHeight+156);
        Modal.show(text);
        break;
    }
  }
};
window.Widget.added = function added(){
  gjs.alert("widget added");
}

window.Modal = {
  init:function(){
    addEvent($("veil"),"click",Modal.hide);
    Modal.toHide = [];
  },
  show:function(html){
    if(!Modal.toHide.length){
      var nodes = [
        document.getElementsByTagName("iframe"),
        document.getElementsByTagName("select"),
        document.getElementsByTagName("embed"),
        document.getElementsByTagName("object")
      ];
      for(var i=0,l=nodes.length;i<l;i++) for(var j=0,L=nodes[i].length;j<L;j++) Modal.toHide.push(nodes[i][j]);
    }
    
    html = html||"";
    var st = (document.compatMode && document.compatMode=="CSS1Compat")?document.body.parentNode.scrollTop:((!!window.scrollY)?window.scrollY:document.body.scrollTop);
    var mt = (typeof(window.innerHeight)!='undefined')?window.innerHeight:(
      (typeof(document.documentElement)!='undefined' &&
       typeof(document.documentElement.clientHeight)!='undefined' &&
       document.documentElement.clientHeight!=0
      )?document.documentElement.clientHeight:document.getElementsByTagName('body')[0].clientHeight
    );
    var mt = parseInt((mt - $("modalInner").clientHeight)*0.3);
    //$("veil").style.top = st+"px";
    $("veil").style.height = (28+findPosition($("footer")).y)+"px";
    if(!(window.attachEvent && !window.opera)){
      $("modalOuter").style.position = "fixed";
      $("modalOuter").style.top = mt+"px";
    }
    else $("modalOuter").style.top = st+mt+"px";
    

    if(typeof(html)=='string') $("modalInner").innerHTML = html;
    else $("modalInner").innerHTML = html.innerHTML;

    //if(!Browser.IE)
    for(var i=0,l=Modal.toHide.length;i<l;i++) Modal.toHide[i].style.visibility = "hidden";
    addClass(document.body,"modal");
  },
  hide:function(){
    Modal.loader.hide();
    removeClass(document.body,"modal");
    $("modalInner").innerHTML = "";
    //if(!Browser.IE) 
    for(var i=0,l=Modal.toHide.length;i<l;i++) Modal.toHide[i].style.visibility = "";
  },
  loader:{
    show:function(){addClass(document.body,"loading");},
    hide:function(){removeClass(document.body,"loading");}
  }
};

addEvent(window,"load",function(){
  window.Modal.init();
  window.Widget.init();

  if(typeof window.location.href.split("?")[1] != 'undefined'){
    var arr = window.location.href.split("?")[1].split("&");
    for(var i=arr.length-1;i>=0;i--){
      var map = arr[i].split("=");
      if(map.length==2) window.params[map[0]]=unescape(map[1]).replace(/\+/," ");
    }
  }
  //_$('loginUser').focus(); // for login page
  if(_$("ad_frame") != null) _$("ad_frame").src = "/finance/ads.html";
  if(_$("research_frame") != null) _$("research_frame").src = "http://www.valuenotes.com/valuenotes/widgets/widgets_2.asp";
});
