function _(s){return document.getElementById(s);}
function $$(s){return document.frames?document.frames[s]:_(s).contentWindow;}
function $c(s){return document.createElement(s);}

function exist(s){return _(s)!=null;}
function dw(s){document.write(s);}
function hide(s){_(s).style.display=_(s).style.display=="none"?"":"none";}
function isNull(_sVal){return (_sVal == "" || _sVal == null || _sVal == "undefined");}

String.prototype.strip = function(){return (this.replace(/^\s+/,'')).replace(/\s+$/,'');}
String.prototype.startsWith = function(str){return (this.substring(0, str.length)==str);}
String.prototype.endsWith = function(str){return (this.substring(this.length-str.length, this.length)==str);}
function stripSpaces(x) { return (x.replace(/^\s+/,'')).replace(/\s+$/,''); }

var euc = encodeURIComponent;
var _cookieEnabled = navigator.cookieEnabled;

function to_json(obj){
    function function_to_json(v){return "function";}
    function array_to_json (v) {
        var a = [];
        for (var i = 0; i < v.length; i++) a.push(to_json(v[i]));
        return '[' + a.join(',') + ']';
    };
    function boolean_to_string(v) {return String(v);};
    function date_to_json(v){
        function f(n) { return n < 10 ? '0' + n : n; }
        return '"' + v.getFullYear() + '-' + f(v.getMonth() + 1) + '-' + f(v.getDate()) + 'T' + f(v.getHours()) + ':' + f(v.getMinutes()) + ':' + f(v.getSeconds()) + '"';
    };
    function number_to_json(v) {return isFinite(v) ? String(v) : 'null';};
    function object_to_json(v){
	if(v.constructor==Date) return date_to_json(v);
        var a = [];
        for (var k in v)
            if (v.hasOwnProperty(k))
		a.push(to_json(k) + ':' + to_json(v[k]));
        return '{' + a.join(',') + '}';
    };
    function string_to_json(v) {
	var m = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'};
	function rep(s) {
	    for(var c in m)
		s=s.replace(c, m[c]);
	    return s;
	}
        return '"' + rep(v) + '"';
    };
    try{
        return eval((typeof obj)+"_to_json(obj)");
    }catch(e){ return "{}"; }
}

// AJAX for gad conversations
function getXmlHttpRequest(){
    var xml_http_request;
    
    try{
	return new XMLHttpRequest();
    }catch(e){
	try{
	    return new ActiveXObject('Msxml2.XMLHTTP');
	}catch (e){
	    try{
		return new ActiveXObject('Microsoft.XMLHTTP');
	    }catch (e){
		return null;
	    }
	}
    }
}

function _ajaxPost(url, load, resp_func, prepost_func, sync){
    var _xml_http_request = getXmlHttpRequest();
    if (_xml_http_request == null){
	alert('Can not send request via xml http.');
	return false;
    }else{
	if(!sync){ async=true; }
	else { async=false; }

	_xml_http_request.open('POST', url, async);
	if(async){
	    _xml_http_request.onreadystatechange = function(){ resp_func(_xml_http_request);};
	}
	_xml_http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	if(prepost_func){
	    prepost_func();
	}
	_xml_http_request.send(load);
	if(!async){
	    resp_func(_xml_http_request);
	}
	return true;
    }
}

function ajaxPost(load, resp_func, prepost_func){return _ajaxPost(base_url, load, resp_func, prepost_func);}

function getJsonResponser(resp_func){
    return function(_xml_http_request){
	if ((_xml_http_request.readyState == 'complete') || (_xml_http_request.readyState == 4)){
	    try{
		var ret = eval("("+_xml_http_request.responseText+")");
		resp_func(ret);
	    }catch(e){}
	    _xml_http_request = null;
	}
    };
}

function getSimpleResponser(resp_func){
    return getJsonResponser(function(ret){resp_func(ret.result, ret.message);});
}

function getListResponser(resp_func, tag){
    return function(_xml_http_request){
	var item_list = [];
	if ((_xml_http_request.readyState == 'complete') || (_xml_http_request.readyState == 4)){
	    var xmldoc = _xml_http_request.responseXML;
	    var items = xmldoc.getElementsByTagName(tag);
	    for(var i=0;i<items.length;i++){
		try{
		    var itemnode = items[i];
		    var value = itemnode.firstChild.nodeValue;
		    item_list.push(value);
		}catch(e){}
	    }
	    resp_func(item_list);
	}
    };
}

// utility functions
function getInnerUrl(baseUrl, withoutPage){
    var url = baseUrl;
    try{ if(auth) url+='&Auth=' + euc(auth);
    }catch(e){}
    
    try{ if(session) url+='&Session=' + euc(session);
    }catch(e){}
    
    try{ if(gad_routing_key) url+='&GadRoutingKey=' + euc(gad_routing_key);
    }catch(e){}

    try{ if(gad) url+='&Gad=' + euc(gad);
    }catch(e){}

    try{ if(!withoutPage)url+='&WikiPage=' + euc(wiki_page);
    }catch(e){}

    try{ if(debug)url+="&Debug=True";
    }catch(e){}

    try{ url+='&ShowChat=' + chat_status();
    }catch(e){}

    return url;
}

function getEnv(withoutPage){
  var env = {};
  try{ if(auth) env.Auth = auth;
  }catch(e){}
  
  try{ if(session) env.Session = session;
  }catch(e){}
  
  try{ if(gad_routing_key) env.GadRoutingKey = gad_routing_key;
  }catch(e){}

  try{ if(gad) env.Gad = gad;
  }catch(e){}

  try{ if(!withoutPage && wiki_page) env.WikiPage = wiki_page;
  }catch(e){}

  try{ env.ShowChat = chat_status();
  }catch(e){}

  try{ evn.Debug = debug;
  }catch(e){}

  return env;
}

function updateEnv(){
    try{
	if(use_simple_url){
	    var show_chat = new Cookie(document, "ShowChat");
	    show_chat.store_value(chat_status());
	}
    }catch(e){}
}

function getActionParam(act, noPage, params){
    var p = getEnv(noPage);
    p.Action = act;
    if(params) p = $.extend(p, params);
    return p;
}

function getInnerParam(paramString, withoutPage){return getInnerUrl(paramString, withoutPage, true);}

function gotoInnerUrl(url, withoutPage, withAllParam){window.location.href=getInnerUrl(url, withoutPage, withAllParam);}

function popPanel(url, width, height) { updateEnv(); window.open(url,'_blank','status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,height='+height+',width='+width);}

function openWin(url){ updateEnv(); window.open(url);}

function gotoUrl(url){ updateEnv(); window.location.href=url;}

function useGad(gadname, keepPage){
    gad = gadname;
    try{
	if(use_simple_url){
	    gotoUrl(base_url+"gad/"+euc(gadname));
	}else{
	    gotoInnerUrl(base_url+"?Action=UseGad", !keepPage);
	}
    }catch(e){
	gotoInnerUrl(base_url+"?Action=UseGad", !keepPage);
    }
}

function gotoPage(page){
  if(use_simple_url){
    gotoUrl(base_url+"gad/"+euc(gad)+"/"+euc(page));
  }else{
    gotoInnerUrl(base_url+"?WikiPage=" + euc(page), true);
  }
}

function showPage(page){gotoInnerUrl(base_url+"?Action=ShowWikiPage&NewWikiPageName="+euc(page), true);}

function openNewWin(url){open(url, "_blank");}

function openHomeNewWin(url) {openNewWin(base_url+url);}

function openGadNewWin(gadname){
    if(use_simple_url){
	openHomeNewWin("gad/"+euc(gadname));
    }else{
	openHomeNewWin("?Action=UseGad&Gad="+euc(gadname));
    }
}

function gotoHomePage(){gotoInnerUrl(base_url+"?Action=GotoDefaultPage", true);}

function logout(){gotoInnerUrl(base_url+'?Action=SignOut');}

function runApp(appname){
    try{
	if(use_simple_url){
	    gotoUrl(base_url+"gad/"+euc(gad)+"/app/"+euc(appname));
	}else{
	    gotoInnerUrl(base_url+'?Action=RunApp&App='+euc(appname), true);
	}
    }catch(e){
	gotoInnerUrl(base_url+'?Action=RunApp&App='+euc(appname)+"&Session="+encodeURIComponent(session), true);
    }
}

function runPreApp(appname){
    try{
	if(use_simple_url){
	    gotoUrl(base_url+"gad/"+euc(gad)+"/app/preinstall/"+euc(appname));
	}else{
	    gotoInnerUrl(base_url+'?Action=RunApp&App=preinstall/'+euc(appname), true);
	}
    }catch(e){
	gotoInnerUrl(base_url+'?Action=RunApp&App=preinstall/'+euc(appname)+"&Session="+encodeURIComponent(session), true);
    }
}

function openAppFile(appname, file){
    try{
	if(use_simple_url){
	    gotoUrl(base_url+"gad/"+euc(gad)+"/app/"+euc(appname)+"/"+euc(file));
	}else{
	    gotoInnerUrl(base_url+"?Action=ShowGadAppFile&App="+euc(appname)+"&AppFile="+euc(file), true);
	}
    }catch(e){
	gotoInnerUrl(base_url+"?Action=ShowGadAppFile&App="+euc(appname)+"&AppFile="+euc(file), true);

    }    
}

function getAppFileUrl(appname, file){
    return getInnerUrl(base_url+"?Action=GetGadAppFile&App="+euc(appname)+"&AppFile="+euc(file));
}

function editProject(prj){gotoInnerUrl(base_url+"?Action=EditProject&Project="+euc(prj), true, true);}

function editCurrentPage(){gotoInnerUrl(base_url+'?Action=EditWikiPage', false, true);}

function showVersions(){gotoInnerUrl(base_url+'?Action=BrowseVersions', false, true);}

function clean_list(id){
    var list = _(id);
    for(var i=list.options.length-1;i>=0;i--)list.remove(i);
}

function _updateListControl(id, items, values, header_prompt, none_prompt){
    clean_list(id);

    var list = _(id);
    if(items.length>0){
	if(header_prompt){
	    var option = document.createElement("OPTION");
	    list.options.add(option);
	    option.innerHTML = header_prompt;
	    option.style.color = "gray";
	    option.selected = true;
	}
	
	for(var i=0;i<items.length;i++){
	    try{
		var option = document.createElement("OPTION");
		list.options.add(option);
		option.innerHTML = items[i];
		option.value = values[i];
	    }
	    catch(e){}
	}
    }else{
	if(none_prompt){
	    var option = document.createElement("OPTION");
	    list.options.add(option);
	    option.innerHTML = none_prompt;
	    option.style.color = "gray";
	    option.selected = true;
	}
    }
}

function _updateListControl2(id, items, header_prompt, none_prompt){
    clean_list(id);

    var list = _(id);
    if(items.length>0){
	if(header_prompt){
	    var option = document.createElement("OPTION");
	    list.options.add(option);
	    option.innerHTML = header_prompt;
	    option.style.color = "gray";
	    option.selected = true;
	}
	
	for(var i=0;i<items.length;i++){
	    try{
		var option = document.createElement("OPTION");
		list.options.add(option);
		option.innerHTML = items[i][0];
		option.value = items[i][1];
	    }
	    catch(e){}
	}
    }else{
	if(none_prompt){
	    var option = document.createElement("OPTION");
	    list.options.add(option);
	    option.innerHTML = none_prompt;
	    option.style.color = "gray";
	    option.selected = true;
	}
    }
}

function updateListControl(id, items, values, header_prompt, none_prompt){
    if(!header_prompt) header_prompt = "Please Choose...";
    if(!none_prompt) none_prompt = "No Item";

    if(items.length!=values.length) values = items; // it may be better to give a warning

    _updateListControl(id, items, values, header_prompt, none_prompt);
}

function _updateList(id, load, tag, header_prompt, none_prompt, post_func){
    function res_func(items){
	updateListControl(id, items, items, header_prompt, none_prompt);
	if(post_func) post_func(items);
    }
    ajaxPost(load,getListResponser(res_func,tag));
}

function updateList(id, action, tag, header_prompt, none_prompt, post_func){
    var load = getInnerParam('Action='+action);
    _updateList(id, load, tag, header_prompt, none_prompt, post_func);
}

function updateList2(id, act, tag, header_prompt, none_prompt, post_func){
    $.getJSON(base_url, getActionParam(act), function(items){
	updateListControl(id, items, items, header_prompt, none_prompt);
	if(post_func) post_func(items);
    });
}

///////////////////////////////////////////
// base64 Adapted from http://www.aardwulf.com/tutor/base64/base64.html
///////////////////////////////////////////
function Base64(){
}

Base64.prototype.keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    
Base64.prototype.encode = function(input){
    var output = '';
    var chr1, chr2, chr3 = '';
    var enc1, enc2, enc3, enc4 = '';
    var i = 0;
    input = String(input);
    
    // make this compatible with the Python implementation of base64 encoding algorithm.
    if(input==""||input==null||input==undefined) return "";
    
    do{
	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);
	chr1 = chr2 = chr3 = '';
	enc1 = enc2 = enc3 = enc4 = '';
    }while (i < input.length);
    
    return output;
}

Base64.prototype.decode = function(input){
    var output = '';
    var chr1, chr2, chr3 = '';
    var enc1, enc2, enc3, enc4 = '';
    var i = 0;
    
    // make this compatible with the Python implementation of base64 decoding algorithm.
    if(input==""||input==null||input==undefined) return "";
    
    // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
    var base64test = /[^A-Za-z0-9\+\/\=]/g;
    
    if (base64test.exec(input))
	alert('There were invalid base64 characters in the input text.  Expect errors in decoding.');
    
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
    
    do {
	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);
	
	chr1 = chr2 = chr3 = '';
	enc1 = enc2 = enc3 = enc4 = '';
	
    }while (i < input.length);

    return output;
}

///////////////////////////////////////////
// tt
///////////////////////////////////////////
function TT(){
    this.log_func = null;    
}

TT.prototype.executeFunc = function(){
    var output = '';
    if (arguments.length <= 0)
	return '';
    var base64 = new Base64();
    var tt_function_argv = '';
    for (var argc = 0; argc < arguments.length; argc++){
	if (argc > 0) tt_function_argv += ',';
	if (!arguments[argc]||arguments[argc]==""){
	    tt_function_argv += "'";
	}else{
	    try{	       
		tt_function_argv += base64.encode(arguments[argc]);
	    }catch(e){
		tt_function_argv += base64.encode(arguments[argc]);
	    }
	}
    }
    $.ajax({
        async: false,
	type: 'POST',
	url:base_url,
	data:{Action:'Query', 
	      Question:'execute tt func', 
	      ParamAUTH:auth, 
	      ParamSESSION:session, 
	      ParamGAD_ROUTING_KEY:gad_routing_key, 
	      ParamIS_INFRASTRUCTURAL_QUESTION:true, 
	      ParamTT_FUNCTION_ARGV:tt_function_argv, 
	      ToAnswer:50},
	dataType:'json',
	success:function(log_func, func_name){	    
	    return function(result){
		var answer = result.answers[0];
		var status = answer.status;
		var text = base64.decode(answer.text);
		text = text.replace(/__TG_RET__/g, "<br>").replace(/__TG_REP__/g, "<br>").replace(/__TG_TAB__/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
		if(status=="Success"){
		    output = text;
		}else if(status=="Failure"){ // exception reported from TT
		    if(this.log_func){
			this.log_func("TT Runtime Exception: "+text);
		    }else{
			alert("TT Runtime Exception: "+text);
		    }
		    output = "";
		}else{
		    // unknown status
		    output = text;
		}
		
		// get debug message from TT print
		try{
		    var msg = base64.decode(result.answers[1].text);
		    msg = msg.replace(/__TG_RET__/g, "<br>").replace(/__TG_REP__/g, "<br>").replace(/__TG_TAB__/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
		    if(log_func && msg!=""){
			log_func("TT func "+func_name+" outputs:<br>"+msg);
		    }
		}catch(e){}
	    };
	}(this.log_func, arguments[0])
    });
    return output;
}
    

////////////////////////////////////////
//  floatpanle
////////////////////////////////////////
var lastPopUp = '';
var modalMode = false;

function resize_shade(){
    this.style.width=document.body.clientWidth + "px";
    this.style.height=document.body.clientHeight + "px";
}

function resize_dlg(){
    this.style.top=(document.body.clientHeight-this.offsetHeight)/2 + "px";
    this.style.left=(document.body.clientWidth-this.offsetWidth)/2 + "px";
}

function showPop(id, focus_item, no_hide_previous) {
    if (!no_hide_previous && lastPopUp != '') hidePop(lastPopUp);

    function click_shade(){
	if(!modalMode){
	    hideLastPop();
	}
    }
    var shade = $("<div></div>").appendTo(document.body).addClass("Mask").attr({title:"click to close dialog box"}).click(click_shade).resize(resize_shade);
    var elem = $("#"+id).show().resize(resize_dlg);
    $(window).resize(function(dlg){
	return function(){
	    dlg.trigger("resize");
	};
    }(elem)).resize(function(sh){
	return function(){
	    sh.trigger("resize");
	};
    }(shade)).trigger("resize");
    
    if(focus_item)
	_(focus_item).focus();

    if(!no_hide_previous)
	lastPopUp = id;
}

function hidePop(id, no_hide_previous, new_focus) {
    var elem = $("#"+id).css({display:"none"});
    $(".Mask").remove();
    $(window).unbind("resize", resize_dlg).unbind("resize", resize_shade);
    if(!no_hide_previous)
	lastPopUp = '';

    if(!new_focus) new_focus = "Input";
    if(typeof new_focus == "string") new_focus = _(new_focus);
    if(typeof new_focus == "object"){
	try{new_focus.focus();}catch(e){}
    }
}

function hideLastPop(){
    if (!modalMode && lastPopUp != '') hidePop(lastPopUp);
}

function showProgressDlg(){
    if(progress_bar){
	progress_bar.showBar();
    }
    showPop("pop_progress", null, true, true);
    modalMode = true;
}

function hideProgressDlg(){
    modalMode = false;
    hidePop("pop_progress", true);
    if(progress_bar){
	progress_bar.hideBar();
    }
}

var mask = '';
function showWindowShade(id, displayMode, func){ // set object's display property according to id and displayMode
    var el = _(id);
    
    if (el.style.display == displayMode)
	return;	
    if(func && func instanceof Function){
	func(displayMode);
    }
    if (displayMode == 'block'){
	var biggestHeight = document.body.scrollHeight;
	if (getWinHeight() > biggestHeight)
	    biggestHeight = getWinHeight();
	el.style.width=document.body.scrollWidth+'px';
	el.style.height=biggestHeight+'px';
    }
    
    el.style.display = displayMode;
    mask = id;
}

function getWinHeight(){
    if (window.innerHeight) return window.innerHeight;
    else if (document.documentElement && document.documentElement.clientHeight) 
	return document.documentElement.clientHeight;
    else if (document.body && document.body.clientHeight) 
	return document.body.clientHeight;
    else if (document.body && document.body.parentNode && document.body.parentNode.clientHeight) 
	return document.body.parentNode.clientHeight;
}

///////////////////////////////////////////
// progress
///////////////////////////////////////////
// xp_progressbar
// Copyright 2004 Brian Gosselin of ScriptAsylum.com

var w3c=($)?true:false;
var ie=(document.all)?true:false;
var N=-1;

function createBar(w,h,bgc,brdW,brdC,blkC,speed,blocks,count,action){
if(ie||w3c){
var t='<div id="_xpbar'+(++N)+'" style="visibility:visible; position:relative; overflow:hidden; width:'+w+'px; height:'+h+'px; background-color:'+bgc+'; border-color:'+brdC+'; border-width:'+brdW+'px; border-style:solid; font-size:1px;">';
t+='<span id="blocks'+N+'" style="left:-'+(h*2+1)+'px; position:absolute; font-size:1px">';
for(i=0;i<blocks;i++){
t+='<span style="background-color:'+blkC+'; left:-'+((h*i)+i)+'px; font-size:1px; position:absolute; width:'+h+'px; height:'+h+'px; '
t+=(ie)?'filter:alpha(opacity='+(100-i*(100/blocks))+')':'-Moz-opacity:'+((100-i*(100/blocks))/100);
t+='"></span>';
}
t+='</span></div>';
document.write(t);
var bA=(ie)?document.all['blocks'+N]:_('blocks'+N);
bA.bar=(ie)?document.all['_xpbar'+N]:_('_xpbar'+N);
bA.blocks=blocks;
bA.N=N;
bA.w=w;
bA.h=h;
bA.speed=speed;
bA.ctr=0;
bA.count=count;
bA.action=action;
bA.togglePause=togglePause;
bA.showBar=function(){
this.bar.style.visibility="visible";
}
bA.hideBar=function(){
this.bar.style.visibility="hidden";
}
bA.tid=setInterval('startBar('+N+')',speed);
return bA;
}}

function startBar(bn){
var t=(ie)?document.all['blocks'+bn]:_('blocks'+bn);
if(parseInt(t.style.left)+t.h+1-(t.blocks*t.h+t.blocks)>t.w){
t.style.left=-(t.h*2+1)+'px';
t.ctr++;
if(t.ctr>=t.count){
eval(t.action);
t.ctr=0;
}}else t.style.left=(parseInt(t.style.left)+t.h+1)+'px';
}

function togglePause(){
if(this.tid==0){
this.tid=setInterval('startBar('+this.N+')',this.speed);
}else{
clearInterval(this.tid);
this.tid=0;
}}

function togglePause(){
if(this.tid==0){
this.tid=setInterval('startBar('+this.N+')',this.speed);
}else{
clearInterval(this.tid);
this.tid=0;
}}

/////////////////////////////////////////
// apputil
/////////////////////////////////////////
// utilities for common applications

//var allow_debug_app =false;

var mygads = new Object();

mygads.base64 = new Base64();

mygads._console = null;

mygads.debug = function(msg){
    if(allow_debug_app){
	mygads._console = _("info_area");
	if(mygads._console){
	    try{
		_log(msg);
	    }catch(e){}
	}
    }
}

function _log(str){
    var info_area = mygads._console;

    var time = document.createElement("span");
    info_area.appendChild(time);
    var t = new Date();
    var tstr = (t.getHours()>9?t.getHours():"0"+t.getHours())+":";
    tstr += (t.getMinutes()>9?t.getMinutes():"0"+t.getMinutes())+":";
    tstr += (t.getSeconds()>9?t.getSeconds():"0"+t.getSeconds())+" - ";
    var timestr = document.createTextNode(tstr);
    time.appendChild(timestr);

    var txt = document.createElement("span");
    info_area.appendChild(txt);
    txt.innerHTML = str;
    //var txtstr = document.createTextNode(str);
    //txt.appendChild(txtstr);

    var br = document.createElement("br");
    info_area.appendChild(br);

    txt.scrollIntoView(false);
}

mygads.tt = new TT();

mygads.tt.f = function(f_name){
    return function(){
	var func_name = f_name;
	if(mygads.tt.ns && mygads.tt.ns!=""){
	    // prepend the namespace for the tt function call
	    func_name=mygads.tt.ns.replace("preinstall/", "")+"."+func_name;
	}	
	
	var args = [func_name];
	if (arguments.length > 0){
	    for (var argc = 0; argc < arguments.length; argc++){
		args[args.length] = String(arguments[argc]);
	    }
	}
	return mygads.tt.executeFunc.apply(null, args);
    }
};

mygads.tt.log_func = function(info){
    if(allow_debug_app){
	mygads.debug(info);
    }else{
	alert(info);
    }
};

mygads.gadAppFile = new Object();

mygads.gadAppFile.getFileSrc = function(filename){
    if(allow_debug_app){
	return getInnerUrl(base_url+"?Action=GetGadAppFile&Debug=True&App=" + euc(project_name) + "&AppFile=" + euc(filename), true);
    }else{
	return getInnerUrl(base_url+"?Action=GetGadAppFile&App=" + euc(project_name) + "&AppFile=" + euc(filename), true);
    }
}

mygads.gadAppFile.getFileHref = function(filename){
    if(allow_debug_app){
	return getInnerUrl(base_url+"?Action=ShowGadAppFile&Debug=True&App=" + euc(project_name) + "&AppFile=" + euc(filename), true);
    }else{
	return getInnerUrl(base_url+"?Action=ShowGadAppFile&App=" + euc(project_name) + "&AppFile=" + euc(filename), true);
    }
}

function getButton(value, callback, id){
    var _btn = document.createElement("input");
    if(id)
	_btn.id = id;
    _btn.type = "button";
    _btn.className = "PopButton";
    _btn.value = value;
    if(callback)
	_btn.onclick = callback;
    return _btn;
}

mygads.Dialog = function(id, title, content, buttons, width){
    this.id = id;

    this._dlg = document.createElement("div");
    this._dlg.className = "PopDialog";
    this._dlg.id = this.id;
		
    this._title = document.createElement("div");
    this._dlg.appendChild(this._title);
    this._title.className = "PopTitle";
    if(title){
	this._title.innerHTML = title;
    }else{
	this._title.innerHTML = "&nbsp;";
    }
    function get_close_func(dlg){ return function(){dlg.close();};}
    $(this._title).prepend($('<img src="'+base_url+'images/close.gif"/>').addClass("CloseButton").css({styleFloat:"right",cssFloat:"right",border:"0"}).click(get_close_func(this)));
	
    this._content = document.createElement("div");
    this._dlg.appendChild(this._content);
    this._content.className = "PopContent";
    if(content.constructor==String){
	this._content.innerHTML = content;
    }else{

	this._content.appendChild(content);
    }
	
    this._buttons = document.createElement("div");
    this._dlg.appendChild(this._buttons);
    this._buttons.className = "PopButtons";

    if(buttons)	this.set_buttons(buttons);
       
    if(width){
      if(width.indexOf("px")==-1)
	this._dlg.style.width = width+"px";
    }

    document.body.appendChild(this._dlg);
}

mygads.Dialog.prototype.open = function(){
    showPop(this.id);
};
    
mygads.Dialog.prototype.hide = function(){
    hidePop(this.id);
};

mygads.Dialog.prototype.close = function(){
    hidePop(this.id);
    $("#"+this.id).remove();
    setInterval(function(dlg){return function(){delete dlg;};}(this), 10);
};

mygads.Dialog.prototype.set_buttons = function(btns){
    if(btns.constructor==String){
	this._buttons.innerHTML = btns;
    }else if(btns.constructor==Array){
	for(var i=0;i<btns.length;i++){
	    this._buttons.appendChild(btns[i]);
	}
    }else{
	this._buttons.appendChild(btns);
    }
}

mygads.Dialog.prototype.set2buttons = function(lb_value, lb_callback, rb_value, rb_callback){
    var lb = getButton(lb_value, lb_callback);
    lb.style.styleFloat = "left";
    lb.style.cssFloat = "left";
    
    var rb = getButton(rb_value, rb_callback);
    rb.style.styleFloat = "right";
    rb.style.cssFloat = "right";
    
    this.set_buttons([lb, rb]);
}

mygads.Dialog.prototype.set3buttons = function(lb_value, lb_callback, mb_value, mb_callback, rb_value, rb_callback){
    var tab = document.createElement("table");
    tab.border="0";
    
    var tb = document.createElement("tbody");
    tab.appendChild(tb);
    
    var tr = document.createElement("tr");
    tb.appendChild(tr);
    
    var td = document.createElement("td");
    tr.appendChild(td);
    
    var lb = getButton(lb_value, lb_callback);
    lb.style.styleFloat = "left";
    lb.style.cssFloat = "left";    
    td.appendChild(lb);
    
    td = document.createElement("td");
    td.align = "center";
    var mb = getButton(mb_value, mb_callback);
    td.appendChild(mb);
    
    td = document.createElement("td");
    var rb = getButton(rb_value, rb_callback);
    rb.style.styleFloat = "right";
    rb.style.cssFloat = "right";
    td.appendChild(rb);
    
    this.set_buttons(tab);
}

var __mygads_do_upload_string_callback  = null;

// callback is a function with a string parameter to process the content of opened text file from local machine
mygads.openTextFile = function(callback){
    var action = "UploadToString";
    var id = "mygads_upload_toString";
    var frm_id = id+"_iframe";
    var cont = '<iframe id="'+frm_id+'" style="width:100%; height:40px; border:0;" src=""></iframe>';
    var dlg = new mygads.Dialog(id, "Open", cont, null, "280px");

    var frm = _(frm_id);
    var fdoc = frm.contentWindow.document;
    var cont = '<html><body style="margin:0; background-color: #BBD8FF; border:none;"><form method="POST" action="'+base_url+'" enctype="multipart/form-data" id="upload_form"><input type="HIDDEN" name="Action" value="'+action+'" /><input type="HIDDEN" name="Auth" value="'+auth+'" /><input type="HIDDEN" name="Session" value="'+session+'" /><input type="HIDDEN" name="Gad" value="'+gad+'" /><input type="HIDDEN" name="GadRoutingKey" value="'+gad_routing_key+'" /><input type="HIDDEN" name="Callback" value="__mygads_do_upload_string_callback" /><input type="FILE" name="FileToUpload" onkeydown="return false;" id="file_to_upload"/></form></body></html>';

    fdoc.write(cont);
    fdoc.close();

    function _do_upload(){
	var f = fdoc.getElementById("file_to_upload").value;
	if(!f){
	    alert("Please choose a file to upload first.");
	    return;
	}
	fdoc.getElementById("upload_form").submit();
	dlg.hide();
	try{
	    showProgressDlg();
	}catch(e){}
    }

    __mygads_do_upload_string_callback = function(result, msg, str){
	try{
	    hideProgressDlg();
	}catch(e){}

	dlg.close()

	if(result){
	    if(callback){
		callback(str);
	    }else{
		alert(str);
	    }
	}else{
	    alert("Open text file failed: "+msg);
	}
    }
    
    dlg.set2buttons("Upload", _do_upload, "Cancel", function(){dlg.close();});
    dlg.open();
}

mygads.openTextFileIntoCtrl = function(id){
    function callback(str){ try{ _(id).value = str; }catch(e){ alert("Failed to open text file into control "+id); } }
    mygads.openTextFile(callback);
}

var upload_response = null;

mygads.uploadToGADFS = function(callback, ext_cont){
    var action = "UploadToGadfs";
    var id = "mygads_upload_togadfs";
    var frm_id = id+"_iframe";
    var cont = '<iframe id="'+frm_id+'" style="width:100%; height:40px; border:0;" src=""></iframe>';
    if(ext_cont) cont+=ext_cont;
    var dlg = new mygads.Dialog(id, "Upload", cont, null, "300");

    var frm = _(frm_id);
    var fdoc = frm.contentWindow.document;
    var cont = '<html><body style="margin:0; background-color: #BBD8FF; border:none;"><form method="POST" action="'+base_url+'" enctype="multipart/form-data" id="upload_form"><input type="HIDDEN" name="Action" value="'+action+'" /><input type="HIDDEN" name="Auth" value="'+auth+'" /><input type="HIDDEN" name="Session" value="'+session+'" /><input type="HIDDEN" name="Gad" value="'+gad+'" /><input type="HIDDEN" name="GadRoutingKey" value="'+gad_routing_key+'" /><input type="FILE" name="FileToUpload" onkeydown="return false;"  id="file_to_upload"/></form></body></html>';

    fdoc.write(cont);
    fdoc.close();

    function _do_upload(){
	var f = fdoc.getElementById("file_to_upload").value;
	if(!f){
	    alert("Please choose a file to upload first.");
	    return;
	}
	fdoc.getElementById("upload_form").submit();
	dlg.hide();
	try{
	    showProgressDlg();
	}catch(e){}
    }

    upload_response = function(result, msg){
	try{
	    hideProgressDlg();
	}catch(e){}
	if(callback) callback(msg); // the file name will be returned as msg.
	dlg.close();
    }
    
    dlg.set2buttons("Upload", _do_upload, "Cancel", function(){dlg.close();});

    dlg.open();
}

mygads.message = new Object();

mygads.message.get = function(message_processor){
    var p = getEnv();
    p.Action = "GetMessage";
    $.getJSON(base_url, p, message_processor);
}

mygads.message.send = function(recipient, message){
    var p = getEnv();
    p.Action = "SendMessage";
    p.Recipient = recipient;
    p.Message = message;

    $.getJSON(base_url, p, function(ret){
	if(!ret.result)
	    alert(ret.message);
    });
}



///////////////////////////////////////
// upload
///////////////////////////////////////
function show_upload_dlg(dlg_id, frm_id, action, obj){
    var frame = document.getElementById(frm_id);
    var fdoc = frame.contentWindow.document;
    var cont = '<html><body style="margin:0; background-color: #BBD8FF; border:none;"><form method="POST" action="'+base_url+'" enctype="multipart/form-data" id="upload_form"><input type="HIDDEN" name="Action" value="'+action+'" /><input type="HIDDEN" name="Auth" value="'+auth+'" /><input type="HIDDEN" name="Session" value="'+session+'" /><input type="HIDDEN" name="Gad" value="'+gad+'" /><input type="HIDDEN" name="GadRoutingKey" value="'+gad_routing_key+'" />';
    if(obj){
	try{
	    for(var i in obj)
		cont+='<input type="HIDDEN" name="'+i+'" value="'+obj[i]+'" />';
	}catch(e){}
    }
    cont+='<input type="FILE" name="FileToUpload" id="upload_file" onkeydown="return false;" /></form></body></html>';

    fdoc.write(cont);
    fdoc.close();
    
    showPop(dlg_id);
    frame.focus();
    fdoc.getElementById("upload_file").focus();
}

function do_upload_file(dlg_id, frm_id, responser){
    var frame = document.getElementById(frm_id);
    var fdoc = frame.contentWindow.document;

    fdoc.getElementById("upload_form").submit();

    hidePop(dlg_id);
    try{
	showProgressDlg();
    }catch(e){}
    
    if(responser)
	upload_response = responser;
    else{	
	upload_response = function(result, msg){
	    hidePop(dlg_id);
	    try{
		hideProgressDlg();
	    }catch(e){}
	    alert(msg);
	}
    }
}

////////////////////////////////////
// Cookie
////////////////////////////////////
function Cookie(document, name, hours, path, domain, secure){
    this.$document = document;
    this.$name = name;
    if (hours)
        this.$expiration = new Date((new Date()).getTime() + hours*3600000);
    else this.$expiration = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
    if (secure) this.$secure = true; else this.$secure = false;
}

// This function is the store() method of the Cookie object.
function _Cookie_store_value(cookieval){
    var cookie = this.$name + '=' + cookieval;
    if (this.$expiration)
        cookie += '; expires=' + this.$expiration.toGMTString();
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    if (this.$secure) cookie += '; secure';

    // Now store the cookie by setting the magic Document.cookie property.
    this.$document.cookie = cookie;
}

function _Cookie_store(){
    var cookieval = "";
    for(var prop in this) {
        // Ignore properties with names that begin with '$' and also methods.
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) 
            continue;
        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + escape(this[prop]);
    }
    _Cookie_store_value(cookieval);
}

// This function is the load() method of the Cookie object.
function _Cookie_load(){
    var allcookies = this.$document.cookie;
    if (allcookies == "") return false;

    var start = allcookies.indexOf(this.$name + '=');
    if (start == -1) return false;   // Cookie not defined for this page.
    start += this.$name.length + 1;  // Skip name and equals sign.
    var end = allcookies.indexOf(';', start);
    if (end == -1) end = allcookies.length;
    var cookieval = allcookies.substring(start, end);
    this["__val__"] = cookieval;

    var a = cookieval.split('&');    // Break it into array of name/value pairs.
    for(var i=0; i < a.length; i++)  // Break each pair into an array.
        a[i] = a[i].split(':');

    for(var i = 0; i < a.length; i++) {
      try{
        this[a[i][0]] = unescape(a[i][1]);
      }catch(e){}
    }

    return true;
}

// This function is the remove() method of the Cookie object.
function _Cookie_remove(){
    var cookie;
    cookie = this.$name + '=';
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

    this.$document.cookie = cookie;
}

// Create a dummy Cookie object, so we can use the prototype object to make
// the functions above into methods.
new Cookie();
Cookie.prototype.store = _Cookie_store;
Cookie.prototype.store_value = _Cookie_store_value;
Cookie.prototype.load = _Cookie_load;
Cookie.prototype.remove = _Cookie_remove;

function gen_header(){
    document.write(getHeader());
}

function getHeader(){
  var un = new Cookie(document, "UserName");
  var l = un.load();
  var r = ('<table width="100%" bgcolor="#4072E6" cellpadding="5" cellspacing="0" border="0"><tr>');
  if(l){
    r+=('<td class="navtext" style="width:70px;"><a href="#" onclick="return false;"><nobr>Hi, ' + un.__val__ + '</nobr></a></td>');
  }
  r+=('<td class="navtext" style="width:775px;"><a href="./">Home</a>');
  if(!l){
    r+=('<a href="./?Action=CreateAccount">Sign Up!</a><a href="./?Action=Login">Login</a>');
  }
  r+=('<a href="tour_intro.htm">Tour</a><a href="gad/help-gad">Help</a><a href="contactus.htm">Contact Us</a><a href="about.html">About Us</a><a href="license.html">License</a><a href="pressrelease.htm">News</a></td>');
  
  if(l){
    r+=('<td class="navlogin" style="text-align:right;"><a href="./?Action=SignOut"><nobr>Logout</nobr></a></td>');
  }else{
    r+=('<td class="navlogin" style="text-align:right;"><a href="./?Action=Login&Simple=True"><nobr>Not Logged In</nobr></a></td>');
  }
  r+=('</tr></table>');
  return r;
}

function getTimezone(){
}

function validateString(x){
    if(x.search("[\"%]")!=-1){
	alert("Invalid character (\" or %) is contained.");
	return false;
    }
    return true;
}

// jquery.corner
jQuery.fn.corner = function(o) {
    function hex2(s) {
        var s = parseInt(s).toString(16);
        return ( s.length < 2 ) ? '0'+s : s;
    };
    function gpc(node) {
        for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode  ) {
            var v = jQuery.css(node,'backgroundColor');
            if ( v.indexOf('rgb') >= 0 ) { 
                rgb = v.match(/\d+/g); 
                return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
            }
            if ( v && v != 'transparent' )
                return v;
        }
        return '#ffffff';
    };
    function getW(i) {
        switch(fx) {
        case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
        case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
        case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
        case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
        case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
        case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
        case 'curl':   return Math.round(width*(Math.atan(i)));
        case 'tear':   return Math.round(width*(Math.cos(i)));
        case 'wicked': return Math.round(width*(Math.tan(i)));
        case 'long':   return Math.round(width*(Math.sqrt(i)));
        case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
        case 'dog':    return (i&1) ? (i+1) : width;
        case 'dog2':   return (i&2) ? (i+1) : width;
        case 'dog3':   return (i&3) ? (i+1) : width;
        case 'fray':   return (i%2)*width;
        case 'notch':  return width; 
        case 'bevel':  return i+1;
        }
    };
    o = (o||"").toLowerCase();
    var keep = /keep/.test(o);                       // keep borders?
    var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]);  // corner color
    var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]);  // strip color
    var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
    var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
    var fx = ((o.match(re)||['round'])[0]);
    var edges = { T:0, B:1 };
    var opts = {
        TL:  /top|tl/.test(o),       TR:  /top|tr/.test(o),
        BL:  /bottom|bl/.test(o),    BR:  /bottom|br/.test(o)
    };
    if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
        opts = { TL:1, TR:1, BL:1, BR:1 };
    var strip = document.createElement('div');
    strip.style.overflow = 'hidden';
    strip.style.height = '1px';
    strip.style.backgroundColor = sc || 'transparent';
    strip.style.borderStyle = 'solid';
    return this.each(function(index){
        var pad = {
            T: parseInt(jQuery.css(this,'paddingTop'))||0,     R: parseInt(jQuery.css(this,'paddingRight'))||0,
            B: parseInt(jQuery.css(this,'paddingBottom'))||0,  L: parseInt(jQuery.css(this,'paddingLeft'))||0
        };

        if (jQuery.browser.msie) this.style.zoom = 1; // force 'hasLayout' in IE
        if (!keep) this.style.border = 'none';
        strip.style.borderColor = cc || gpc(this.parentNode);
        var cssHeight = jQuery.curCSS(this, 'height');

        for (var j in edges) {
            var bot = edges[j];
            strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
            var d = document.createElement('div');
            var ds = d.style;

            bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

            if (bot && cssHeight != 'auto') {
                if (jQuery.css(this,'position') == 'static')
                    this.style.position = 'relative';
                ds.position = 'absolute';
                ds.bottom = ds.left = ds.padding = ds.margin = '0';
                if (jQuery.browser.msie)
                    ds.setExpression('width', 'this.parentNode.offsetWidth');
                else
                    ds.width = '100%';
            }
            else {
                ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                                    (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
            }

            for (var i=0; i < width; i++) {
                var w = Math.max(0,getW(i));
                var e = strip.cloneNode(false);
                e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
                bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
            }
        }
    });
};


// jqDnR - Minimalistic Drag'n'Resize for jQuery.
(function($){
$.fn.jqDrag=function(r){$.jqDnR.init(this,r,'d'); return this;};
$.fn.jqResize=function(r){$.jqDnR.init(this,r,'r'); return this;};
$.jqDnR={
init:function(w,r,t){ r=(r)?$(r,w):w;
	r.bind('mousedown',{w:w,t:t},function(e){ var h=e.data; var w=h.w;
	hash=$.extend({oX:f(w,'left'),oY:f(w,'top'),oW:f(w,'width'),oH:f(w,'height'),pX:e.pageX,pY:e.pageY,o:w.css('opacity')},h);
	h.w.css('opacity',0.8); $().mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
	return false;});
},
drag:function(e) {var h=hash; var w=h.w[0];
	if(h.t == 'd') h.w.css({left:h.oX + e.pageX - h.pX,top:h.oY + e.pageY - h.pY});
	else h.w.css({width:Math.max(e.pageX - h.pX + h.oW,0),height:Math.max(e.pageY - h.pY + h.oH,0)});
	return false;},
stop:function(){var j=$.jqDnR; hash.w.css('opacity',hash.o); $().unbind('mousemove',j.drag).unbind('mouseup',j.stop);},
h:false};
var hash=$.jqDnR.h;
var f=function(w,t){return parseInt(w.css(t)) || 0};
})(jQuery);
