/*
#===============================================================================
#
#         FILE:  pmp.js
#
#        USAGE:  ---
#
#      PURPOSE:  JavaScript - Routines for Browser
#
#      OPTIONS:  ---
#      RETURNS:  ---
# REQUIREMENTS:  ---
#     COMMENTS:
#
#       AUTHOR:  Konstantin
#      COMPANY:  SIB & Biozentrum University of Basel
#      VERSION:  $version$
#      CREATED:  7:16:08 PM Oct 20, 2007
#     REVISION:  $rev$
#===============================================================================
*/
// collection of java script code loaded by ajax
var scripts = new Array();

function ClearField(field_id) {
  if(document.getElementById(field_id)) {
    if(document.getElementById(field_id).type == "textarea"){
      document.getElementById(field_id).innerHTML = "";
      document.getElementById(field_id).value = "";
    } else {
      document.getElementById(field_id).value = "";
    }
  }
}
function FillField(field_id, value) {
if(document.getElementById(field_id)) {
    if(document.getElementById(field_id).type == "textarea"){
      document.getElementById(field_id).innerHTML = value;
      document.getElementById(field_id).value = value;
    } else {
      document.getElementById(field_id).value = value;
    }
  }
}


function checkSeq() {
  seq = trim(document.queryBySeq.seq.value);
  if (seq.match(/[^[0-9a-zA-z\n\r\ \t]/)){alert('Please enter alpha-numeric characters only!');return false;}
  if (seq.length > 25) { return true; }
  if (seq.match(/^\d...$/)) { return true; }
  if (seq.match(/^[A-Za-z][0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][0-9]$/)) { return true; }
  alert("Please provide a amino acid sequence query > 30 amino acids!"); return false;
}

function asyncPart(async_url, field, text) {
  if(!text){  var text = "loading data ...";  }
  text = "<img src=\"images/ajax_working_indicator.gif\" alt=\"Working...\" style=\"vertical-align: middle\" />&nbsp;&nbsp;" + text;
  document.getElementById(field).innerHTML = "<div id=\"asyncpart\">" + text + "</div>";

  var xmlHttp;
  try{
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
  }catch (e){
    // Internet Explorer
    try{
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }catch (e){
      try{
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
        alert("Your browser does not support AJAX!");
        return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function(){
    if(xmlHttp.readyState==4){
      parseScript(xmlHttp.responseText);
      document.getElementById(field).innerHTML = xmlHttp.responseText;
      // Loop through every script collected and eval it
      for(var i=0; i<scripts.length; i++) {
        try {
          eval(scripts[i]);
        }
        catch(ex) {
          //alert(ex.message);
        // do what you want here when a script fails
        }
      }
    }
  }
  xmlHttp.open("GET",async_url,true);
  xmlHttp.send(null);
}


function changeLinkToAsync(){
  for (var i = 0; i < document.links.length; ++i){
    if(document.links[i].href.search("modelDetai") != -1 ||
       document.links[i].href.search("queryByAC") != -1){
      document.links[i].href = document.links[i].href+"&zid=async";
    }
  }
  if(document.queryByAC){          document.queryByAC.action             = document.queryByAC.action+"&zid=async"; }
  if(document.queryBySeq){         document.queryBySeq.action            = document.queryBySeq.action+"&zid=async"; }
  if(document.statusQueryBySeq){   document.statusQueryBySeq.action      = document.statusQueryBySeq.action+"&zid=async"; }
  if(document.queryByTemplateID){  document.queryByTemplateID.action     = document.queryByTemplateID.action+"&zid=async"; }
  if(document.queryByText){        document.queryByText.action           = document.queryByText.action+"&zid=async"; }
}

function showTipPreview (location, template, seqid, seqstart, seqend, sid){
  new Tip (location, {
          target: $(location),
          ajax:  {
            url: '?aid=template_tooltip&template='+template+'&seqid='+seqid+
                       '&seqstart='+seqstart+'&seqend='+seqend+'&sid='+sid,
            options: {
            method: 'get'
            }
          },
          className: 'ajax',
          width: '250px',
          hideOn: { element: "tip, target", event: "mouseleave" },
          hideAfter: '1'
//          hook: { tip: 'topLeft', mouse: true },
//          hook: { target: 'topLeft', tip: 'topLeft' },
//          viewport: false,
//          offset: { x: -10, y: -10 }, //no neg offsets in FF!!IE7/8 ok
//        hideOn: { element: 'closeButton', event: 'click' },
 //         hideOn: { element: 'target', event: 'mouseout' },
//        hook: { target: 'bottomMiddle', tip: 'topRight' },
//        stem: 'topRight',
//        offset: { x: 1, y: 1 },
        });
}


function removeLink(){
  var anchor_list=document.getElementsByTagName("a");
  for (var i = 0; i < anchor_list.length; ++i){
    if(anchor_list[i].id.search("href_") != -1) {
      anchor_list[i].removeAttribute("href");
/*        anchor_list[i].parentNode.removeChild(anchor_list[i]);//too harsh, removes all*/
    }
  }
}

function activateSelectionLegend(ele_id){
  var ele=document.getElementById(ele_id);
  if (document.forms[0]){
    if (document.forms[0].elements.length>1){
      if (ele) {
        ele.style.display='inline';
      }
    }
  }
}
function trim (string) {
  return string.replace (/^\s+/, '').replace (/\s+$/, '');
}

function toggleAsyncDiv(async_url, div_id) {
  if(document.getElementById(div_id).innerHTML == "") {
    asyncPart(async_url, div_id);
  } else {
    document.getElementById(div_id).innerHTML = "";
  }
}

function toggleHitCluster(hitcluster_name){
  for(var i = 0; i < document.getElementsByName(hitcluster_name).length; i++){
    var e = document.getElementsByName(hitcluster_name)[i];
    if (e.style.display == '') e.style.display = 'none';
    else e.style.display = '';
  }
  if(document.getElementById('button_'+hitcluster_name)) {
    var re = new RegExp('arrow_right');
    if(re.exec(document.getElementById('button_'+hitcluster_name).innerHTML)){
      document.getElementById('button_'+hitcluster_name).innerHTML = '<img alt=" " src="img/arrow_down.gif" />';
    }else{
      document.getElementById('button_'+hitcluster_name).innerHTML = '<img alt=" " src="img/arrow_right.gif" />';
    }
  }
}

/* collapse/expand-effects - fancy editions*/
function collapseElement(element) {
  new Effect.BlindUp(element, { duration: 0.5 });
}
function expandElement(element) {
  new Effect.BlindDown(element, { duration: 0.5 });
}

function parseScript(_source) {
  var source = _source;


  /* Strip out tags*/
  while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
    var s = source.indexOf("<script");
    var s_e = source.indexOf(">", s);
    var e = source.indexOf("</script", s);
    var e_e = source.indexOf(">", e);

    /* Add to scripts array*/
    scripts.push(source.substring(s_e+1, e));
    /* Strip from source*/
    source = source.substring(0, s) + source.substring(e_e+1);
  }

  /* Return the cleaned source*/
  return source;
}

/* this function opens a link in a new window if rel="external" is specified.
 * replaces target="extern"
 * window.onload line is used to activate it*/
function externalLinks() {
  if (!document.getElementsByTagName) return;
  var anchors = document.getElementsByTagName("a");
  for (var i=0; i<anchors.length; i++) {
    var anchor = anchors[i];
    if (anchor.getAttribute("href") &&
      anchor.getAttribute("rel") == "external")
      anchor.target = "_blank";
  }
}
window.onload = externalLinks;

function getElementsByClassName(classname, node) {
  if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
      if(re.test(els[i].className))a.push(els[i]);
        return a;
}

/*more general function to color any element with any class defined in the style sheet*/
function colorElement(el_id, classname) {
  var myele=$(el_id);
  if (myele) {
    var ex_class=myele.classNames();
    if (ex_class){
      myele.removeClassName(ex_class);
    }
    Element.addClassName(myele, classname);
    //element.className = classname;
  }
}

/*resets the color to its original value(by seqid) or sets it selected*/
function resetColor(el_id, bChecked){
  var myelement = $(el_id);
  if (myelement){
    var ex_class=myelement.classNames();
    var re = new RegExp("tableRow.*_(.*)");
    var tableDetected=re.exec(el_id);
    if (bChecked) {
      if (tableDetected) {
        Element.removeClassName(myelement,ex_class);
        Element.addClassName(myelement,'selected');
      } else {
        Element.removeClassName(myelement,ex_class);
        Element.addClassName(myelement,'selected');
      }
    }else{
      if (tableDetected) {
        if (tableDetected[1] % 2 ==0) {
          Element.removeClassName(myelement,ex_class);
          Element.addClassName(myelement,'table_bg1');
        } else if (tableDetected[1] % 2 ==1) {
          Element.removeClassName(myelement,ex_class);
          Element.addClassName(myelement,'table_bg2');
        }
      } else {
        myelement.removeClassName('highlighted');
        Element.addClassName(myelement, 'model_bar');
        Element.setStyle(myelement, {borderColor: Bordercolors[myelement.id]});
      }
    }
  }
}

function deselectAll() {
  for (var j = 0; j <document.select_models.length; j++) {
    var mybox;
    if (document.forms[0].elements[j].type=="checkbox") {
      mybox=document.forms[0].elements[j];
//          mybox=document.select_models.elements[j];
      mybox.checked = false;
/*(\d{1,})_\d{1,}");*/
      var re = new RegExp("(.*)_.*");
      var id=re.exec(mybox.defaultValue);
      resetColor("summaryCluster_"+id[1], mybox.checked);
//          resetColor("tableRow_"+id[0], mybox.checked);
      resetColor(mybox.parentNode.parentNode.id, mybox.checked);
    }
  }
}

function openWin(link){
  newwin=window.open(link, '_blank');
  if (window.focus) {
    newwin.focus()
  }
  return false;
}
/*on submission of the summary page model selection a few checks are done*/
function validate() {
  var namelist = new Array();
  var counter=0;
  with(document.forms[0]) {
    for(var i = 0; i < elements.length; i++){
      if(elements[i].checked) {
        namelist[counter] = elements[i].value;
        counter++;
      }
    }
  }
if(namelist.length < 2) {
  alert("Please select at least two models!");
  return false;
}
return true;
}

function status_msg(stat_message){
/*    window.status=stat_message;*/
  self.status=stat_message;
  return true;
}

/*dynamically add element, e.g. button to deselect checkboxes*/
 function add_element(id,type,name,value) {
/*Create an input type dynamically.  */
  if (document.select_models) {
    if (document.select_models.elements.length>2) {
      var element = document.createElement('input');

/*Assign different attributes to the element.*/
      element.setAttribute("type", type);
      element.setAttribute("value", value);
      element.setAttribute("name", name);
      if (id=='deselectArea') {
        element.setAttribute("onClick", 'deselectAll()');
        element.onclick=function(){deselectAll();};
      }

      var ele = document.getElementById(id);

/*Append the element in page (in span).*/
      ele.appendChild(element);
    }
  }
}

/*updates the color in the modellist and the modelbar, when a checkbox is selected*/
/*counter is needed as second arg to account for checkboxes being numbered with relative numbers cluding cluster members from modbase*/
function clickSelectCheckbox(box) {
  box.checked=!box.checked;
  var re = new RegExp("(.*)_.*");
  var idbox=re.exec(box.defaultValue);
  var idmodel="summaryCluster_"+idbox[1];
  var tablrow=box.parentNode.parentNode.id;
  resetColor(idmodel, box.checked);
  resetColor(tablrow, box.checked);
}

function dblClick(link) {
  /*wt=window.setTimeout('if (bIsDblClick) {openWin(\"'+link+'\")}',timeout);*/
  if (bIsDblClick) {
    openWin(link)
  }
  bIsDblClick = false;
}

function sglClick(arg,timeout){
  bIsDblClick = false;
  wt=window.setTimeout('if (!bIsDblClick) {'+arg+'}', timeout);
}



function restoreAnchorLinks(){
    var anchors = document.getElementsByTagName("a");
    var basehref = document.getElementsByTagName("base")[0].href;
    var url = window.location.href;
    if(url.indexOf("#") > 0) url = url.substr(0, url.indexOf("#")); //strip hash
    if(basehref) {
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            poundPos = anchor.href.indexOf("/#");
            if (poundPos > 0) {
                anchor.href = url + anchor.href.substr(poundPos + 1);
            }
        }
    }

}


