/* 2003-06-17  CommonTown JS util functions */
/* Add your utility functions here. */
/* Please put a short comment with your big name for posterity */

function ctpopup(name,url,w,h,param) {
 // popup window at the centre of screen
 if (typeof w =="undefined") w=400;
 if (typeof h =="undefined") h=250;

 if (typeof param =="undefined") {
	 param=",status=no,menubar=no,resizable=yes,scrollbars=yes";
 }

 if (param.indexOf('left')==-1) {
   var left = ( screen.width - w ) / 2 ;
	 param+=",left="+left;
 }
 if (param.indexOf('top')==-1) {
   var top = ( screen.height - h ) / 2;
	 param+=",top="+top;
 }

 param += ",width="+w+",height="+h;
 win= window.open(url,name,param);
 if (win) win.focus();
 win.opener=self;
 return win;
}

function ctformselectval(elm) {
  // get form select value
  cnt=elm.options.length;
  for(var i=0; i< cnt; i++) {
    if (elm.options[i].selected) return elm.options[i].value;
  }
  return false;
}

function ctfilldiv(which,url,msg) {
  targetDiv=document.getElementById(which);

  if (targetDiv){
    if (msg) targetDiv.innerHTML=msg;
    else targetDiv.innerHTML='<div class=help align=center><br><br>Downloading, please wait..<br></div>';
  }

  fobj=document.getElementById('_dlframe');
  fobj.targetObj=targetDiv;
  aobj=document.getElementById('_dlgrabber');
  aobj.href=url;
  aobj.target='_dlframe';
  aobj.click();
}


function ctload_dlframe(c) {
  var rwin=c.contentWindow; // result
  if (rwin && rwin.document.body) {
    var html=rwin.document.body.innerHTML;
    if (html) c.targetObj.innerHTML=html;
  }
}


// 2004-08-23 joel: menu 
function ct_show_menu(mname,nudge) {
  var omenu=document.getElementById(mname);
  if (omenu) {
    if (nudge) {
	  if (!omenu.style.origleft) 
		omenu.style.origleft=omenu.style.pixelLeft;
	  omenu.style.pixelLeft=omenu.style.origleft+nudge;
	}
    omenu.style.display='block';
  }
//  else alert('ct_show_menu error: menu '+mname+' not found');
}
function ct_hide_menu(mname) {
  var omenu=document.getElementById(mname);
  if (omenu) omenu.style.display='none';
//  else alert('ct_hide_menu error: menu '+mname+' not found');
}

// 2004-08-23 joel: dialog box 
function ct_dialog(title,url,w,h) {
  if (!w) w=400;
  if (!h) h=300;
  param=new Array();
  param[0]=window;
  param[1]=title;
  param[2]=url;

  retval=window.showModalDialog(url,param,'dialogwidth:'+w+'px;dialogheight:'+h+'px;status:no;scroll:yes;help:no;resizable:yes');

  // 2003-07-13 joel: refresh entire browser
  if (retval) {
    if (retval=='view_refresh' && window.parent) {
      window.parent.leftFrame.document.location.reload();
      window.parent.mainFrame.document.location.reload();
    }
    else if (retval=='full_refresh' && window.parent) {
      window.parent.document.location.reload();
    }
    else if (retval=='confirm') {
      window.document.location=url+'&confirm=1';
    }
    else document.location.reload();
  }
}

// 2004-09-19 joel: dialog using window.open
function ct_open(name,url,w,h,param) {
  // popup window at the centre of screen
  if (typeof w =="undefined") w=400;
  if (typeof h =="undefined") h=250;
 
  var left = ( screen.width - w ) / 2 ;
  var top = ( screen.height - h ) / 2;
 
  if (typeof param =="undefined") {
    param=",status=no,menubar=no,resizable=yes,scrollbars=yes";
  }
  param += ",width="+w+",height="+h+",top="+top+",left="+left;
  win= window.open(url,name,param);
  if (win) {
    win.focus();
    if (!win.opener) win.opener=window;
    // 2006-02-25 joel: keep dialog on top 
    window.dialog_window=win;
    setTimeout('_waitdialog()',1000);
  }
// 2007-01-08 joel: cannot use this, it will reload caller with [object] 
//  return win;
}

function _waitdialog() {
  if (!window.dialog_window.closed) {
    // 2006-09-18 joel: does not work now, need to bring to top, not focus 
    // IMPORTANT: cannot use window.focus() which messes up the focus of the active input fields
    //window.dialog_window.focus();
    //window.dialog_window.setActive();
    setTimeout('_waitdialog()',1000);
  }
  else {
   // window.document.location.reload();
  }
}

// 2005-11-28 joel: close myself and refresh opener 
function ct_close(reload_opener) {
  if (typeof reload_opener =="undefined") reload_opener=true;
  if (reload_opener && window.opener) window.opener.location.reload();
  window.close();
}

// 2004-09-19 joel: refresh routine callable by the window opened with ct_open
// win: should be window.opener usually
function ct_refresh(win,reftype) {
  if (reftype=='view_refresh' && win.parent) {
    win.parent.leftFrame.document.location.reload();
    win.parent.mainFrame.document.location.reload();
  }
  else if (reftype=='full_refresh' && window.parent) {
	win.parent.document.location.reload();
  }
  else if (reftype=='refresh') {
    win.document.location.reload();
  }
}

// 2004-10-21: ec convert query str to array 
function ct_querystr2arr (str) {
  str = str ? str : location.search;
  var query = str.charAt(0) == '?' ? str.substring(1) : str;
  var args = new Object();
  if (query) {
    var fields = query.split('&');
    for (var f = 0; f < fields.length; f++) {
      var field = fields[f].split('=');
    if(field[0]&&field[1]&&field[0].match(/^[a-zA-Z]/)&&!field[0].match(/[^0-9a-zA-Z_]/)){
      args[unescape(field[0].replace(/\+/g,' '))] = unescape(field[1].replace(/\+/g, ' '));
    }
    }
  }
  return args;
}

// 2006-04-28 joel: debug object 
function ct_dump(what,html) {
  if (html) {
    buf='<table>';
    for(i in what) buf+='<tr><td><b>'+i+'</b></td><td>'+what[i]+"</td></tr>";
    buf+='</table>';
  }
  else {
    buf='';
    for(i in what) buf+=''+i+': '+what[i]+'\n';
  }
  return buf;
}

// 2006-12-29 joel: pop window and run url for inserting into vedit box
function ct_inserter_open(oname,popup_url,w,h,param) {
  window.returnValue='';
  obj=document.getElementById((document.all?'viz_':'')+oname);
  if (obj.int_id) clearInterval(obj.int_id);
  obj.int_id=setInterval("_check_inserted('"+oname+"')",500);
  //setTimeout("_check_inserted('"+oname+"')",500);

  if (typeof w =="undefined") w=400;
  if (typeof h =="undefined") h=480;
  ct_open('insert',popup_url,w,h,param);
}

function _check_inserted(oname) {
  txt=window.returnValue;
  if (txt!='') {
    if (txt=='___empty___') return;

    if (document.all) {
      obj=document.getElementById('viz_'+oname);
      obj.focus();
      sRange  = obj.document.selection.createRange();

      if (sRange.length) { return alert("Unable to insert HTML.  Try highlighting content instead of selecting it."); }

      var oldHandler = window.onerror;
      window.onerror = function() { alert("Unable to insert HTML for current selection."); return true; } ;
      sRange.pasteHTML(txt);                
      window.onerror = oldHandler;

      sRange.collapse(false);
      sRange.select();      
    }
    else {
      // FF
      obj=document.getElementById(oname);
      rte=document.getElementById(oname).contentWindow;
      rte.document.execCommand('InsertHTML', false, txt);
      rte.focus();
    }
    if (obj.int_id) clearInterval(obj.int_id);

    return;
  }
//  else
//    setTimeout("_check_inserted('"+oname+"')",500);
}


function ct_inserter_close(instext) {
  window.returnValue=instext;
  window.opener.returnValue=instext;

  if (!instext) instext='___empty___';
  // for FF
  if (!document.all) window.opener.returnValue=instext;
  ct_close(false);
//  window.close();
}

// 2007-01-18 joel: fit object into window 
function ct_fit_object(oname,dy,dx) {
  if (!dy) dy=90;
  if (!dx) dx=20;
  if (document.all) {
    //width=window.frameElement.width;
    //height=window.frameElement.height;
    width=document.body.clientWidth;
    height=document.body.clientHeight;
    ve=document.getElementById(oname);
    ve.style.overflowX='auto';
  }
  else {
    width=window.innerWidth;
    height=window.innerHeight;
    ve=document.getElementById(oname);
  }
  if (dx!='keep') ve.style.width=width-dx;
  if (dy!='keep') ve.style.height=height-dy;
}

function ct_urlencode(msg) {
	if (typeof(msg) == 'undefined' || !msg || msg == '') return; 

	if (window.encodeURIComponent) 
		msg= encodeURIComponent(msg); 
	else if (window.escape) 
		msg = escape(msg); 
	return msg;

}

function ct_urldecode(msg) {
	if (typeof(msg) == 'undefined' || !msg || msg == '') return;

	if (window.decodeURIComponent)
		msg= decodeURIComponent(msg);
	else if (window.escape)
		msg = unescape(msg);
	return msg;

}

// 2008-08-24: expand/collapse 
function ct_toggle_expand(oname) {
  obj=document.getElementById(oname); 
  icon=document.getElementById(oname+'_icon'); 
  obj.style.display=(obj.style.display=='none'?'block':'none');
  icon.src='/pix/b/'+(obj.style.display=='none'?'collapse.gif':'expand.gif');
}

function ct_cp2clipboard (txt) {
	// ec 2008-08-03 ff-support 
	if(window.clipboardData) { 
		window.clipboardData.clearData(); 
		window.clipboardData.setData("Text", txt); 
	} else if(navigator.userAgent.indexOf("Opera") != -1) { 
		window.location = txt; 
	} else if (window.netscape) { 
	try { 
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
	} catch (e) { 
	alert("You need to set 'signed.applets.codebase_principal_support=true'.\nYou can change it from within the browser by calling the 'about:config' page."); 
		return false; 
	} 
	var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance (Components.interfaces.nsIClipboard); 
	if (!clip) return; 
	var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance (Components.interfaces.nsITransferable); 
	if (!trans) return; 
	trans.addDataFlavor('text/unicode'); 
	var str = new Object(); 
	var len = new Object(); 
	var str = Components.classes["@mozilla.org/supports-string;1"].createInstance (Components.interfaces.nsISupportsString); 
	var copytext = txt; 
	str.data = copytext; 
	trans.setTransferData("text/unicode",str,copytext.length*2); 
	var clipid = Components.interfaces.nsIClipboard; 
	if (!clip) return false; 
	clip.setData(trans,null,clipid.kGlobalClipboard); 
	} 
	return true;
}

function gup( name )
{
  name = name.replace(/[[]/,"\\[").replace(/[]]/,"\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return ""; 
  else
    return results[1];
}
function autoResize(id){
    var newheight;
    var newwidth;
    //alert(id);
    if(document.getElementById){
	newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
    }
    
    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}


function getDocHeight(doc)
{
  var docHt = 0, sh, oh;
  if (doc.height)
  {
    docHt = doc.height;
  }
  else if (doc.body)
  {
    if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
    if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
    if (sh && oh) docHt = Math.max(sh, oh);
  }
  return docHt;
}
function getReSize(id)
{
  
  var iframeWin = window.frames[id];
  var iframeEl = window.document.getElementById? window.document.getElementById(id): document.all? document.all[id]: null;
  
  //alert(iframeWin);
  //alert(iframeEl);
  if ( iframeEl && iframeWin )
  {
    var docHt = getDocHeight(iframeWin.document);
    if (docHt != iframeEl.style.height) iframeEl.style.height = docHt + 'px';
  }
  else
  { // FireFox
    //alert(document.getElementById(id));
    var docHt = window.document.getElementById(id).contentDocument.height;
    window.document.getElementById(id).style.height = docHt + 'px';
  }
}


