// #############################################3
// ETE web GUI. AJAX version  
// Jaime Huerta-Cepas jhuerta@cipf.es
//
// #############################################3

// variables that will be used within this script 
var x1=y1=-1; // x,y position of the first click in relation to the image
var x2=y2=-1; // x,y position of the second click in relation to the image
var posx=posy=-1; // the x,y position in relation to the image's parent for selection area
var imgx=imgy=-1; // x,y position of the image in relation to its absolutely-positioned parent
var divx=divy=-1; // x,y position of the image's absolutely-positioned parent.
var poffx1=poffy1=-1; // the page offset (how far down or right have we scrolled) for first click
var poffx2=poffy2=-1; // the page offset (how far down or right have we scrolled) for first click
var abselemdet=false; // absolute-position element detected in the path?

//window.onscroll = movetoolbar;
function movetoolbar(){
    var toolbar    = document.getElementById("toolbar");
    toolbar.style.position="absolute";
    if(typeof(window.pageXOffset)=='undefined'){
      // MSIE browsers
      if(x1==-1 && y1==-1){
	poffx=document.body.scrollLeft;
	poffy=document.body.scrollTop;
        }
    }else{
      // others
     
      poffx=window.pageXOffset;
      poffy=window.pageYOffset;
    }
    if (poffy<100){
       toolbar.style.top="100px";
    }else{
      toolbar.style.top=poffy+"px";
    }
}

// Get pressed pixel
function getImagePressedPoint(obj,evnt){
    var opera=(navigator.userAgent.toLowerCase().indexOf("opera") != -1);

    // get image location relative to its absolutely-positioned parent (or document)
    // at first click (should this happen both times??)
    if(imgx == -1 && imgy == -1){
        // only if these are set to -1 (not calculated yet)
        while(obj.offsetParent){
            // check if this element has absolute positioning first
            var absposcheck=false;
            if(typeof(obj.currentStyle)!='undefined' && obj.currentStyle.position){
                // this is MSIE, we need to work differently
                if( obj.currentStyle && obj.currentStyle.position == 'absolute'){
                    absposcheck=true;
                    if(abselemdet)
                        abselemdet=false;
                    else
                        abselemdet=true;
                }
            }else{
                // others browsers
                if(window.getComputedStyle(obj, '').getPropertyValue('position') == 'absolute'){
                    absposcheck=true;
                    if(abselemdet)
                        abselemdet=false;
                    else
                        abselemdet=true;
                }
            }

            if(absposcheck){
                // this is absolutely positioned
                // need to know the position in relation to the document as well
                while(obj.offsetParent){
                    // this gives the element relative to the document
                    divy += obj.offsetTop;
                    divx += obj.offsetLeft;
                    obj = obj.offsetParent;
                }
                break;
            }

            imgy = obj.offsetTop;
            imgx = obj.offsetLeft;
            obj = obj.offsetParent;
        }
        if(abselemdet){
            divy+=15;
        }
    }

    // calculate the current page offset (to compensate for scrolling!)
    if(typeof(window.pageXOffset)=='undefined'){
        // MSIE browsers
        if(x1==-1 && y1==-1){
            // this is the first click
            poffx1=document.body.scrollLeft;
            poffy1=document.body.scrollTop;
        }else{
            // second click
            poffx2=document.body.scrollLeft;
            poffy2=document.body.scrollTop;
        }
    }else{
        // others
        if(x1==-1 && y1==-1){
            // this is the first click
            poffx1=window.pageXOffset;
            poffy1=window.pageYOffset;
        }else{
            // second click
            poffx2=window.pageXOffset;
            poffy2=window.pageYOffset;
        }
    }

    var last_x=-1;
    var last_y=-1;
    
    posx=evnt.clientX + poffx1 - divx;
    posy=evnt.clientY + poffy1 - divy;
    last_x = posx - imgx;
    last_y =  posy - imgy;
    if(opera && abselemdet){
            last_y+=11;
        }
    return [last_x,last_y];
}

function print_position(elem,evnt){
    var image    = document.getElementById("mainImage");
    var pos = getImagePressedPoint(image,evnt);
    alert (pos);
}

function set_default_action(act){
    var d_action = document.getElementById("default_action");
    d_action.value=act;
}

function get_fixed_url(){
  var IP        = document.getElementById("host").value;
  var PORT      = document.getElementById("port").value;
  var UNIQUEID  = document.getElementById("uniqueid").value;
  var OUTIMG    = document.getElementById("image_outpath").value;

  var url = ETE_cgi_URL;
  url += '?host='+IP;
  url += '&port='+PORT;
  url += '&uniqueid='+UNIQUEID;
  url += '&outimg='+OUTIMG;
  url += '&refresh='+Math.random();
  return url;
}


function execute_cmd(action){
  url = get_fixed_url();
  url += '&action='+action;
  ete_request(url,true);
}

function execute_point(pos){
  var d_action = document.getElementById("default_action").value;
  url = get_fixed_url();
  url += '&action='+d_action+' '+pos[0]+' '+pos[1]+'!';
  if (d_action == "WRITE_NODE_INFO"){
    ete_request(url,false);
  }else
    {
    ete_request(url,true);
    }


}

function change_tree_style(style){
    url = get_fixed_url();
    url += '&action=CHANGE_STYLE '+style;
    ete_request(url,true);
}

function transpose_profile(){
    url = get_fixed_url();
    url += '&action=INVERT_PROFILE ';
    ete_request(url,true);
}

function set_scale(max,min,center){
    url = get_fixed_url();
    url += '&action=SET_SCALE '+max+' '+min+" "+center+" ";
    ete_request(url,true);
}

function set_default_scale(){
    url = get_fixed_url();
    url += '&action=SET_DEFAULT_SCALE ';
    ete_request(url,true);
}


function search(){
  var search = document.getElementById("search_text");
  url = get_fixed_url();
  url += '&action=SEARCH '+search.value;
  ete_request(url,true);
}

function clean_search(){
  url = get_fixed_url();
  url += '&action=CLEAN_SEARCH ';
  ete_request(url,true);
}

function collapse_by_deviation(name){
  var field = document.getElementById(name);
  thr = field.value;
  url = get_fixed_url();
  url += '&action=COLLAPSE_BY_DEVIATION '+thr;

  ete_request(url,true);
}
function collapse_by_silhoutte(name){
  var field = document.getElementById(name);
  thr = field.value;
  url = get_fixed_url();
  url += '&action=COLLAPSE_BY_SILHOUTTE '+thr;

  ete_request(url,true);
}
function collapse_by_intracluster(name){
  var field = document.getElementById(name);
  thr = field.value;
  url = get_fixed_url();
  url += '&action=COLLAPSE_BY_INTRACLUSTER '+thr;

  ete_request(url,true);
}
function collapse_by_intercluster(name){
  var field = document.getElementById(name);
  thr = field.value;
  url = get_fixed_url();
  url += '&action=COLLAPSE_BY_INTERCLUSTER '+thr;
  ete_request(url,true);
}

function ask_for_silhoutte(){
  var string = 'Silhoutte Threshold:<input type=text value="" id="asked_value"> <input type=submit value="Ok" onclick=\'javascript:collapse_by_silhoutte("asked_value");hide_window("info_window");\'>';
  show_window("info_window", string,250,100);
}
function ask_for_deviation(){
  var string = 'Std.deviation Threshold:<input type=text value="" id="asked_value"> <input type=submit value="Ok" onclick=\'javascript:collapse_by_deviation("asked_value");hide_window("info_window");\'>';
  show_window("info_window", string,250,100);
}
function ask_for_intra(){
  var string = 'IntraCluster Threshold:<input type=text value="" id="asked_value"> <input type=submit value="Ok" onclick=\'javascript:collapse_by_intracluster("asked_value");hide_window("info_window");\'>';
  show_window("info_window", string,250,100);
}
function ask_for_inter(){
  var string = 'InterCluster Threshold:<input type=text value="" id="asked_value"> <input type=submit value="Ok" onclick=\'javascript:collapse_by_intercluster("asked_value");hide_window("info_window");\'>';
  show_window("info_window", string,250,100);
}
function ask_for_scale(){
  var string = '<br>Max value:<input type=text value="" id="max_scale"><br> Min value:<input type=text value="" id="min_scale"> <br> Center value:<input type=text value="" id="center_scale"> <br> <input type=submit value="Ok" onclick=\'javascript:change_scale();hide_window("info_window");\'>';
  show_window("info_window", string, 250, 150);
}

function change_scale(){
  var max_scale    = document.getElementById("max_scale").value;
  var min_scale    = document.getElementById("min_scale").value;
  var center_scale = document.getElementById("center_scale").value;
  set_scale(max_scale,min_scale,center_scale);

}



function close_server(){
  url = get_fixed_url();
  url += '&action=EXIT'
  ete_request(url,true);
}

function update_main_image(){
  var mainImage   = document.getElementById("mainImage") ;
  var UNIQUEID  = document.getElementById("uniqueid").value ;
  var IMAGEURL    = document.getElementById("imageurl").value ;
  mainImage.src   = IMAGEURL+"?"+ Math.random();	    
}

// MAIN ETE AJAX REQUEST
function new_connector()
{

  if (typeof XMLHttpRequest != 'undefined') {
        return new XMLHttpRequest();
  }
  try {
    return new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      return new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {}
  }
  return false;

  /// My way

  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;
	    }
	}
    }
    return xmlHttp;
}


function ete_request(url,refresh_img)
{
    var st       = document.getElementById("status");

    ajax = new_connector();

    ajax.open("GET",url,true);
    ajax.onreadystatechange=function(){
	//loading
	if(ajax.readyState==1){
	    show_loading_window("Processing...", 1);
        }
	// loaded
	if(ajax.readyState==2){

        }
	// interactive
	if(ajax.readyState==3){

        }
	// complete
	if(ajax.readyState==4){
	  hide_loading_window();
	  execute_post_action(ajax.responseText,refresh_img)
        }
    }
    ajax.send(null);
 }

function execute_post_action(response,refresh_img){
  var d_action = document.getElementById("default_action").value;
  if( refresh_img){
    update_main_image();
  }
  else if (d_action == "WRITE_NODE_INFO" && response!= ""){
    show_window("info_window", response,500,500);
  }

}

function init_ete(divname,treefile,arrayfile,distance,uptreefile,outimg,style){
    var image_outpath  = document.getElementById("image_outpath");
    image_outpath.value =  outimg;

    // Prepare load command 
    var load_action  = 'action=LOAD_TREE '+treefile+'!';
    // if array given 
    if (arrayfile != '' && distance != ''){
	load_action += ' LOAD_PROFILE '+arrayfile+' '+distance+'!';
	// if uptreefile
	if (uptreefile != ''){
		load_action += ' LOAD_UPTREE '+uptreefile+'!';
	    }
    }

    if (style == 'summary' || style == 'circular' || style == 'unrooted' || style == 'rooted'){
	load_action += 'CHANGE_STYLE '+style+'!';
	}

    var url = ETE_cgi_URL;
    url += '?'+load_action ;
    url += '&outimg='+image_outpath.value;
	
    var st  = document.getElementById("status");

    ajax = new_connector();

    ajax.onreadystatechange=function(){
	//loading
	if(ajax.readyState==1){ 
	    show_loading_window("Processing...", 1);
	}
	// loaded
	else if(ajax.readyState==2){   }
	// interactive
	else if(ajax.readyState==3){   }
	// complete
	else if(ajax.readyState==4){
	    hide_loading_window();
	    gui_window = document.getElementById(divname);
	    gui_window.innerHTML = ajax.responseText;
            if (m2) { 
	      m2.make_visible();
	      save_ete_image();
            }
        }
    }
    ajax.open("GET",url,true);
    ajax.send(null);
 }


function show_loading_window(msg,clock){
    var st =  document.getElementById("status");
    if (clock) {
      st.innerHTML= msg + '<br> <img src="img/clock.png" width="75">';
    } else {
      st.innerHTML= '<br>' + msg + '<br>';
    }
    center(st,'200','50');
    st.style.visibility="visible";
    
}

function hide_loading_window(){
    var st  = document.getElementById("status");
    st.innerHTML='Ok.\n'+Math.random();
    st.style.visibility="hidden";
}

function border_tool(name){
  toolnames = ["execute_icon","info_icon","root_icon","cut_icon","goup_icon"];
  for (i = 0; i<toolnames.length; i++){
    var img  = document.getElementById(toolnames[i]);
    if (img){
      if (toolnames[i] == name){
	img.style.border="1px";
      }else{
	img.style.border="1px";
      }
    }
  }
}


function show_window(winname,text,w,h){
  var st =  document.getElementById(winname);
  if (text!=""){
    head = '<img align="left" src="../img/close.png" onclick=\'javascript:hide_window("'+winname+'");\' >';
    st.innerHTML= head +'<BR>'+text;
  } 
  st.style.width = w+"px";
  st.style.height= h+"px";
  center(st,w,h);
  st.style.visibility="visible";
  
}

function hide_window(winname){
    var st  = document.getElementById(winname);
    st.style.visibility="hidden";
}


/****************************************\
* Actually center box
\****************************************/
function center(window, _width, _height) {

    var pagesize = getPageSize();    
    var arrayPageScroll = getPageScrollTop();
    window.style.left = (arrayPageScroll[0] + (pagesize[0] - _width )/2)+"px";
    window.style.top = (arrayPageScroll[1] + (pagesize[1] - _height )/3)+"px";
}
/****************************************\
*
\****************************************/
function getPageSize(){
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
    arrayPageSize = new Array(w,h) 
    return arrayPageSize;
}
/****************************************\
*
\****************************************/
function getPageScrollTop(){
    var yScrolltop;
    var xScrollleft;
    if (self.pageYOffset || self.pageXOffset) {
        yScrolltop = self.pageYOffset;
        xScrollleft = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){     // Explorer 6 Strict
        yScrolltop = document.documentElement.scrollTop;
        xScrollleft = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
        yScrolltop = document.body.scrollTop;
        xScrollleft = document.body.scrollLeft;
    }
    arrayPageScroll = new Array(xScrollleft,yScrolltop) 
    return arrayPageScroll;
}

