var x_axis = null;
var y_axis = null;
var anim_dim = null;
function selectXAxis() {
  var select_x_axis = $('x_axis');
  var select_y_axis = $('y_axis');
  var select_anim_dim = $('anim_dim');
  if ( select_x_axis ) {
    var old = x_axis;
    x_axis = select_x_axis.selectedIndex;
    if ( x_axis==y_axis && draw_method.ndims>1 ) {
      var ary = [0,1,2];
      ary = ary.without(x_axis);
      if ( select_anim_dim && !select_anim_dim.disabled )
        ary = ary.without( select_anim_dim.selectedIndex );
      select_y_axis.selectedIndex = ary.min();
      selectYAxis();
    } else if ( x_axis==anim_dim && select_anim_dim && !select_anim_dim.disabled ) {
      var ary = [0,1,2];
      ary = ary.without(x_axis);
      if ( draw_method.ndims>2 )
        ary = ary.without( select_y_axis.selectedIndex );
      select_anim_dim.selectedIndex = ary.min();
      selectAnimDim();
    }
    changeDimensionStatus(old);
  }
}
function selectYAxis() {
  var select_x_axis = $('x_axis');
  var select_y_axis = $('y_axis');
  var select_anim_dim = $('anim_dim');
  if( select_y_axis && draw_method.ndims>1 ) {
    var old = y_axis;
    y_axis = select_y_axis.selectedIndex;
    if ( x_axis==y_axis ) {
      var ary = [0,1,2];
      ary = ary.without(y_axis);
      if ( select_anim_dim && !select_anim_dim.disabled )
        ary = ary.without( select_anim_dim.selectedIndex );
      select_x_axis.selectedIndex = ary.min();
      selectXAxis();
    } else if ( y_axis==anim_dim && select_anim_dim && !select_anim_dim.disabled ) {
      var ary = [0,1,2];
      ary = ary.without(y_axis);
      ary = ary.without(x_axis);
      select_anim_dim.selectedIndex = ary.min();
      selectAnimDim();
    }
    changeDimensionStatus(old);
  }
}
function selectAnimDim() {
  var select_x_axis = $('x_axis');
  var select_y_axis = $('y_axis');
  var select_anim_dim = $('anim_dim');
  if ( select_anim_dim && !select_anim_dim.disabled ) {
    var old = anim_dim;
    anim_dim = select_anim_dim.selectedIndex;
    if ( anim_dim==x_axis ) {
      var ary = [0,1,2];
      ary = ary.without(anim_dim);
      if ( draw_method.ndims>1 )
        ary = ary.without( select_y_axis.selectedIndex );
      select_x_axis.selectedIndex = ary.min();
      selectXAxis();
    } else if ( anim_dim==y_axis && draw_method.ndims>1 ) {
      var ary = [0,1,2];
      ary = ary.without(anim_dim);
      ary = ary.without(x_axis);
      select_y_axis.selectedIndex = ary.min();
      selectYAxis();
    }
    changeDimensionStatus(old);
  }
}

var dimensions = new Array();
function changeDimensionStatus(old) {
  var id;
  var select_anim_dim = $('anim_dim');
  if ( !(old==null) )
    if( (old!=x_axis) && !(old==y_axis&&draw_method.ndims>1) && !(old==anim_dim&&!select_anim_dim.disabled))
      dimensions[old].disableRight();
  if ( !(x_axis==null) )
    dimensions[x_axis].enableRight();
  if ( draw_method.ndims>1 )
    if ( !(y_axis==null) )
      dimensions[y_axis].enableRight();
  if ( !(anim_dim==null) )
    if ( select_anim_dim && !select_anim_dim.disabled )
      dimensions[anim_dim].enableRight();
}


function setAnim() {
  var anim_check_box = $('analysis_anim');
  var select_anim_dim = $('anim_dim');
  var draw_button = $('draw_button');
  draw_button.value = "draw";
  draw_button.onclick = drawExecute;
  selectXAxis();
  selectYAxis();
  if ( anim_check_box ) {
    if ( !anim_check_box.disabled && anim_check_box.checked ) {
      selectAnimDim();
      anim_check_box.disabled = false;
      select_anim_dim.disabled = false;
      draw_button.value = "start";
      draw_button.onclick = anim.start.bind(anim);
    } else {
      select_anim_dim.disabled = true;
      select_anim_dim.disabled = true;
      changeDimensionStatus(anim_dim);
    }
  }
}

var draw_method;
function selectDrawMethod() {
    var anim_check_box = $('analysis_anim');
    var select_anim_dim = $('anim_dim');

    var draw_method_select = $('draw_method');

    if (draw_method_select) {
	var draw_method_options = draw_method_select.options;
	draw_method = draw_method_options[draw_method_select.selectedIndex];
	for(n=0;n<draw_method_options.length;n++)
	    Element.hide('draw_'+draw_method_options[n].value+'_settings');
	Element.show('draw_'+draw_method.value+'_settings');

	if( draw_method.ndims == 1 ) {
	    if ( $('y_axis') ) {
		Element.hide('y_axis_row');
		changeDimensionStatus(y_axis);
	    }
	    if ( select_anim_dim && select_anim_dim.length>1 ) {
		anim_check_box.disabled = false;
		select_anim_dim.disabled = false;
	    } else {
		anim_check_box.disabled = true;
		select_anim_dim.disabled = true;
	    }
	    setAnim();
	} else {
	    Element.show('y_axis_row');
	    if ( select_anim_dim && select_anim_dim.length>2 ) {
		anim_check_box.disabled = false;
		select_anim_dim.disabled = false;
	    } else {
		anim_check_box.disabled = true;
		select_anim_dim.disabled = true;
	    }
	}
    }
    setAnim();
}


var variablesOrder = new Array();
function selectVarOrder(select,type,i) {
  var new_num = select.selectedIndex;
  var old_num = variablesOrder[type][i];
  variablesOrder[type][i] = new_num;
  for(n=0;n<variablesOrder[type].length;n++){
    if(n==i) continue;
    sel = $(type+'_variables_order_'+n);
    if(sel.selectedIndex == new_num){
      sel.options[old_num].selected = true;
      variablesOrder[type][n] = old_num;
      break;
    }
  }
}


function getKeyCode(e) {
  if (window.event) {
    return event.keyCode;
  } else if (e.keyCode) {
    return (e.keyCode!=0) ? e.keyCode : e.charCode;
  } else if (e.which) {
    return e.which;
  }
}
function eventStop(e) {
  if ( e ) {
    e.preventDefault(); 
    e.stopPropagation(); 
  } else {
    event.returnValue = false; 
    event.cancelBubble = true; 
  }
}

var executable;
function afterCallBack() {
  if( action_type == 0 ) {
    dimensions.each( function(v,i){ v.disableRight(); } );
    selectDrawMethod();
    Element.show("popular_diagrams");
    if( executable )
      Element.show("draw_button");
    else
      Element.hide("draw_button");
    document.onkeypress = function(e){
      if ( getKeyCode(e)==Event.KEY_RETURN ) {
        $('draw_button').click();
        Event.stop(e);
      }
    };
  }
  if( action_type == 1 ) {
    Element.hide("popular_diagrams");
    if( executable )
      if ($("analysis_button"))
        Element.show("analysis_button");
    else
      if ($("analysis_button"))
        Element.hide("analysis_button");
    document.onkeypress = function(e){
      if ( getKeyCode(e)==Event.KEY_RETURN ) {
        $('analysis_button').click();
        Event.stop(e);
      }
    };

  }
}


function openOptionMenu() {
  Element.hide('open_menu_link');
  Element.show('option_menu');
}

function closeOptionMenu() {
  Element.hide('option_menu');
  Element.show('open_menu_link');
}

shrinkHalf = function(element) {
  element = $(element);
  var options = Object.extend({
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();
  var moveX = dims.width / 2;
  var moveY = dims.height / 2;
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition:
options.opacityTransition }),
      new Effect.Scale(element, 0.5, { sync: true, transition:
options.scaleTransition})
    ], Object.extend({
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned();
           effect.effects[0].element.makeClipping(); },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.undoClipping();
           effect.effects[0].element.undoPositioned();
}
       }, options)
  );
}



function showOption(category, name) {
  var first = arguments[2];
  full_name = category+"_"+name+"_option";
  var element = $(full_name);
  Element.show(element);
  Element.hide("add_"+full_name+"_link");
  Element.show("hide_"+full_name+"_link");
  if( !first )
    new Effect.Highlight(element, {
      duration: 3.0
    });
  setCookie("option_" + category + "_" + name, "true", null);
}

function hideOption(category, name) {
  full_name = category+"_"+name+"_option";
  Element.hide("hide_"+full_name+"_link");
  Element.show("add_"+full_name+"_link");
  Effect.Fade(full_name);
  setCookie("option_" + category + "_" + name, "false", null);
}

function showOptions(category) {
  Element.show(category+"_options");
  Element.show(category+"_options_menu");
}

function hideOptions(category) {
  Element.hide(category+"_options");
  Element.hide(category+"_options_menu");
}

var action_type;
function changeActionType(type) {
  action_type = type;
  new Ajax.Request(gfdnaviUrlRoot + "/analysis/action_type_selected",
                   {asynchronous: true,
                    evalScripts: true,
                    parameters: 'action_type=' + type,
                    method: 'post',
                    onLoading: function(){ progressText.start($('progress')); },
                    onComplete: function(res){ progressText.stop(); },
                    onFailure: function(res){
                        $('messages').update('error occured in server<br><div class="information"><p>'+res.responseText+"</p></div>");
                      }
                   });
  return false;
}

function changeVariable() {
  form = $('variables_body');
  new Ajax.Request(gfdnaviUrlRoot + "/analysis/variables_selected",
                   {asynchronous: true,
                    evalScripts: true,
                    parameters: Form.serialize(form),
                    method: 'post',
                    onLoading: function(){ progressText.start($('progress')); },
                    onComplete: function(res){ progressText.stop(); },
                    onFailure: function(res){
                        $('messages').update('error occured in server<br><div class="information"><p>'+res.responseText+"</p></div>");
                      }
                   });
  return false;
}

var actionButton = null;
var onAction = false;
var onDraw = false;
var onAnim = false;
actionExecuteHook = {
                     onLoading: function(){
                       if ( actionButton ) actionButton.disabled = true;
                       if ( !onAnim ) progressText.start($('progress'));
                       onDraw = true;
                       onAction = true;
                     },
                     onComplete: function(res){
                       if ( onAnim ) {
                         if (anim) anim.moveDial();
                       } else {
                         progressText.stop();
                       }
                       if ( actionButton ) {
                         actionButton.disabled = false;
                         actionButton = null;
                       }
                       onAction = false;
                     },
                     onFailure: function(res){
                        $('messages').update('error occured in server<br><div class="information"><p>'+res.responseText+"</p></div>");
                       }
}

var funcs = null;
var funcVNums = null;
function selectFunction(select) {
  var index = select.selectedIndex;
  var obj = funcs[index];
  var html = "";
  var elm;
  for(i=0;i<funcs.length;i++) {
      elm = $('function_arguments_'+funcs[i].name);
      Element.hide(elm);
//      Form.disable(elm);
      Form.getElements(elm).invoke('disable');
  }
  elm = $('function_arguments_'+obj.name);
  Element.show(elm);
//  Form.enable(elm);
  Form.getElements(elm).invoke('enable');

  for(i=0;i<funcVNums.length;i++){
      elm = $('function_variables_order_'+funcVNums[i]);
      Element.hide(elm);
//      Form.disable(elm);
      Form.getElements(elm).invoke('disable');
  }
  Element.show(obj.order);
//  Form.enable(obj.order);
  Form.getElements(obj.order).invoke('enable');

  return false;
}

var num_of_figure;
var check = 0;
function drawKnowledgeFromAnalysisButton() {
  num_of_figure++;
  if (check == 0) {
    var node = document.getElementById('create_knowledge_from_analysis');
    var form = document.createElement('form');
    form.setAttribute("action", "/knowledge/new_from_analysis");
    form.setAttribute("method", "post");
    var br1 = document.createElement('br');
    var br2 = document.createElement('br');
    var inputButton = document.createElement('input');
    inputButton.setAttribute("type", "image");
    inputButton.setAttribute("src", "/images/create_from_analysis_button.png");
    inputButton.setAttribute("name", "create_a_knowledge_document");
    inputButton.setAttribute("alt", "Create a Knowledge Document");
    inputButton.setAttribute("title", "Create a Knowledge Document");
    inputButton.setAttribute("align", "absmiddle");
    var inputHidden = document.createElement('input');
    inputHidden.setAttribute("type", "hidden");
    inputHidden.setAttribute("name", "from_analysis");
    inputHidden.setAttribute("value", "from_analysis");

    form.appendChild(inputButton);
    form.appendChild(inputHidden);
    node.appendChild(br1);
    node.appendChild(br2);
    node.appendChild(form);

    check = 1;
  }
}

function deleteKnowledgeFromAnalysisButton() {
  num_of_figure--;
  if (!num_of_figure){
    var node = document.getElementById('create_knowledge_from_analysis');
    node.removeChild(node.lastChild);
    check = 0;
  }
}

var benchmark = null;
function drawExecute() { 
  if (actionButton) actionButton.disable = false;
  actionButton = $('draw_button');
  actionExecute('action_type=draw');
  if (benchmark) benchMark.start();
  return false;
}
function analysisExecute() {
  if (actionButton) actionButton.disable = false;
  actionButton = $('analysis_button');
  actionExecute('action_type=analysis');
  if (benchmark) benchMark.start();
  return false;
}
function actionExecute(param) {
  var action_form = $('action_form');
  var variable_form = $('variables_body');
  new Ajax.Request(gfdnaviUrlRoot + "/analysis/execute",
                   Object.extend({
                     asynchronous:true,
                     evalScripts:true,
                     parameters: Form.serialize(variable_form)+'&'+Form.serialize(action_form)+'&'+param,
                     method: 'post'
                   }, actionExecuteHook)
                  );
  return false;
}

var Anim = Class.create();
Anim.prototype = {
  initialize: function() {
    this.interval = 1000;
    this.intervalId = null;
  },
  start: function() {
    this.clear();
    var anim_dim = $('anim_dim').selectedIndex;
    var dim = dimensions[anim_dim];
    onAnim = true;
    var action_form = $('action_form');
    var variable_form = $('variables_body');
    var params = Form.serialize(variable_form)+'&'+Form.serialize(action_form);
    var min = dim.left_obj.dial.index;
    var max = dim.right_obj.dial.index;
    if ( this.params!=params || this.dim!=dim || this.min!=min || this.max!=max ) {
      new Ajax.Request(gfdnaviUrlRoot + "/analysis/clear_diagrams",
                       {evalScripts:false,
                       onLoading: function(){ onAction = true; },
                       onComplete: function(){ onAction = false; }
                       }
                      );
      this.ary = dim.ary;
      this.min = min;
      this.max = max;
      this.index = this.min;
      this.diagrams = new Array();
      this.diagramIndex = null;
      this.params = params;
      this.dim = dim;
      this.firstLoop = true;
    }
    var free_obj = dim.free_obj;
    free_obj.dial.index = this.index;
    this.moveDial();
    free_obj.dial_dom.show();
    this.intervalId = setInterval(this.draw.bind(this), this.interval);
    var button = $('draw_button');
    button.value = 'stop';
    button.onclick = this.stop.bind(this);
  },
  stop: function() {
    this.clear();
    var button = $('draw_button');
    this.dim.free_obj.dial_dom.hide();
    button.value = 'start';
    button.onclick = this.start.bind(this);
  },
  clear: function() {
    if ( this.intervalId ) {
      clearInterval( this.intervalId );
      this.intevalId = null;
    }
    onAnim = false;
  },
  clearAll: function() {
    this.clear();
    this.params = null;
  },
  draw: function() {
    if ( onAction || onDraw ) return;
    if ( this.index > this.max ) {
      if ( this.firstLoop )
        this.firstLoop = false;
      this.index = this.min;
    }
    this.dim.free_obj.dial.index = this.index;
    if ( this.firstLoop ) {
      actionExecute( 'anim[val]=' + this.ary[this.index] + '&action_type=draw&disable_benchmark=true' );
    } else {
      this.next();
    }
    this.index += 1;
  },
  next: function() {
    if ( this.diagramIndex == null ) {
      this.diagramIndex = 0;
    } else {
      Element.hide( this.diagrams[this.diagramIndex] );
      this.diagramIndex += 1;
      if ( this.diagramIndex >= this.diagrams.length ) {
        this.diagramIndex = 0;
      }
    }
    Element.show( this.diagrams[this.diagramIndex] );
    this.moveDial();
  },
  moveDial: function() {
    this.dim.moveFreeDial();
  }
}
var anim = new Anim();

function actionDropDiagram(upper, lower) {
  document.write("dropDiagram!\n");
  
  if (actionButton) actionButton.disable = false;
  actionButton = null;
  new Ajax.Request(gfdnaviUrlRoot + '/analysis/pile_up?upper=' + upper + '&lower=' + lower,
                   Object.extend({
                     asynchronous:true,
                     evalScripts:true
                   }, actionExecuteHook)
                  );
}


var num_keywords = 0;
function addRowKeyword() {
  var row;
  num_keywords = num_keywords + 1;
  row = "<tr>\n"
  row += "<td><input type='text' name='keywords[" + num_keywords + "][name]' id='save_keywords_" + num_keywords + "_name'/></td>\n"
  row += "<td><input type='text' name='keywords[" + num_keywords + "][value]' id='save_keywords_" + num_keywords + "_value'/></td>\n"
  row += "</tr>\n"
  new Insertion.Bottom($('save_keywords'),row);
}
