
var China = Class.create();
China.prototype =
{
  initialize: function(){},
  AjaxRequest: function(method,url,pars,func,func_params){
    var myAjax = new Ajax.Request(
      url,
      {
	method: method,
	parameters: pars+'&timestamp='+new Date().getTime(),
	onComplete: function(originalRequest){
	  var json = China.prototype.GetJson(originalRequest);
//alert("AjaxRequest="+json);
	  func(json,func_params);
	}
      }
    );
  },
  GetJson: function(request){
    var xml = request.responseXML;
    var json = xml.getElementsByTagName('html_content')[0].firstChild.data;
    if( json.length==4096 ){ // FF
      json = request.responseText.split(/html_content>/);
      json = json[1];
      json = json.substring(0,json.length-2);
    }
    return json;
  },

  FindDictionary: function(){
    var chinese = document.dic_form['dic/chinese'].value;
    var pinyin = document.dic_form['dic/pinyin'].value;
//alert(chinese+","+pinyin);
    if( !chinese || !pinyin){
      return;
    }
    var url = "/api/dic/find_chinese";
    var pars = "chinese="+encodeURIComponent(chinese)+"&pinyin="+encodeURIComponent(pinyin);
//alert(url+"?"+pars);
    China.prototype.AjaxRequest('get',url,pars,China.prototype.FindDictionaryDone,{});
  },
  FindDictionaryDone: function(json,params){
    try{
      eval(json);
    }catch(e){
      alert(e+"\n"+json);
// TODO:setClipboard(json);
    }
    if( word ){
      location.href = "/dic/edit/"+word.id;
    }
  },
  FindQuestion: function(value){
    if( value.length<=0 ){ $('error').update(""); }
    var url = "/api/question/find_chinese";
    var pars = "chinese="+encodeURIComponent(value);
    China.prototype.AjaxRequest('get',url,pars,China.prototype.FindQuestionDone,{});
  },
  FindQuestionDone: function(json,params){
    try{
      eval(json);
    }catch(e){
      alert(e+"\n"+json);
// TODO:setClipboard(json);
    }
    if( question ){
      $('error').innerHTML = "この中国語はすでに登録してあります。";
    }else{
      $('error').innerHTML = "";
    }
  },
  RequestFeedback: function(url){
    var url = location.href;
    var html = '<a href="javascript:MediaWagon.prototype.CreateDialog({url:\'/feedback/request?url='+url+'\'});">要望は、こちら</a>';
    html += '<link rel="stylesheet" type="text/css" href="/css/window/default.css" />';
    html += '<script type="text/javascript" src="/js/window.js"></script>';
//    document.writeln(html);
  }
}

/*
function tag(e, v, a) {
  var sv = a ? v + " " + a : v;
  var str = getSelectionRange(e);
//  setSelectionRange(e, '<' + sv + '>' + str + '</' + v + '>');
  setSelectionRange(e, sv );
}
*/

function getSelectionRange(e) {
  var str;
  if (document.selection) {
    str = document.selection.createRange().text;
  } else if(/Gecko/.test(navigator.userAgent) /*isGecko*/){
    var start = e.selectionStart;
    var end = e.selectionEnd;
    str = e.value.substring(start, end);
  } else {
    str = '';
  }
  return str;
}

function setSelectionRange(e, v) {
  if(document.selection) {
    if(getSelectionRange(e))
      document.selection.createRange().text = v;
    else
      e.value = e.value + v;
  } else if(/Gecko/.test(navigator.userAgent) /*isGecko*/){
    var start = e.selectionStart;
    var end = e.selectionEnd;
    var len = e.textLength;
    var str = e.value.substring(start, end);
    var head = e.value.substring(0, start);
    var foot = e.value.substring(end, len);
    e.value = head + v + foot;
  } else {
    e.value = e.value + v;
  }
}

var focus_element = null;
function tag(c)
{
  if(!focus_element){
    alert("入力先を選択してください。");
    return;
  }
  element = focus_element;
//  var pro=document.getElementById('pro');
  element.focus();

  if( document.selection ){
    element.currentPos = document.selection.createRange().duplicate();

/*
var text="";
for(o in element.currentPos){text+=o+"=>"+element.currentPos[o]+"\n";}
alert("[debug]"+text);
*/

    if( element.currentPos ){
      element.currentPos.text+=c;
    }
  }else if(/Gecko/.test(navigator.userAgent)){
    var str = getSelectionRange(element);
//  var sv = a ? v + " " + a : v;
    setSelectionRange(element, c );
  }else{
    element.value+=c;
  }
}


CafeLesson = {
  findAddressByZip: function(zipcode){
    if( zipcode.length<7 ){
      $('zip_searching').hide();
      return;
    }

    new Ajax.Request("/api/proxy",{
      parameters: "u=http://api.aimy.jp/zip/view/"+zipcode,
      asynchronous: true,
      method: 'get',
      evalScripts: true,
      onComplete: function(request){
	$('zip_searching').hide();
	try{
	  eval(request.responseText);
	}catch(e){
	  alert(e+","+request.responseText);
	}

	var val;
	if( zip ){
	  val = zip.pref+" "+zip.city+" "+zip.town;
	}else{
	  val = "";
	}
	if($('teacher_address')){
	  $('teacher_address').value = val;
	}else if($('student_address')){
	  $('student_address').value = val;
	}
      }
    });
  },
  AdmitTeacher: function(id){
    var ret = confirm("本当に承認していいですか？");
    if( !ret ){ return; }
//alert("AdmitTeacher:"+id+","+ret);
    new Ajax.Request('/api/admin/admit_teacher/'+id,{method: 'get',asynchronous: true,evalScripts:true});
  },
  WaitResumeTeacher: function(id){
    new Ajax.Request('/api/admin/wait_resume_teacher/'+id,{method: 'get',asynchronous: true, evalScripts:true});
  },
  FailTeacher: function(id,mode){
    var ret = confirm("本当に不合格としていいですか？");
    if( !ret ){ return; }
    new Ajax.Request('/api/admin/fail_teacher/'+id,{method:'get',parameters:'mode='+mode,asynchronous: true,evalScripts:true});
  }
};

CafePlace = {
  id: "",
  Init: function(id,data){
    data = data||[];
    if( data.length<=0 ){
      data.push({});
    }
    this.id = id;
    this.data = data;
    this.SetData();
  },
  Add: function(data,i){
    data = data||{};
    if( typeof(i)=="undefined" ){
      i = this.data.length;
      this.data.push({});
    }
    var html = TrimPath.processDOMTemplate('template_cafe_place',{data:data,index:i});
/*
    var div_obj = document.createElement("div");
    div_obj.innerHTML = html;
    $(this.id).appendChild(div_obj);
*/
    new Insertion.Bottom($(this.id),html);
//    $(this.id).innerHTML += html; // Fail!!

  },
  Remove: function(index){
    $('cafe_place_select_'+index).remove();
  },
  SetData: function(){
    var html = "";
    for(var i=0;i<this.data.length;i++){
      CafePlace.Add(this.data[i],i);
    }
  }
};

TimeTable = {
  id: "",
  Init: function(id,data){
    data = data||[];
    if( data.length<=0 ){
      data.push({});
    }
    this.id = id;
    this.data = data;
    this.SetData();
  },
  Add: function(data,i){
    data = data||{};
    if( typeof(i)=="undefined" ){
      i = this.data.length;
//alert("index:"+this.data.length);
//      this.data.length++;
      this.data.push({});
    }
    var html = TrimPath.processDOMTemplate('template_time_table',{data:data,index:i});
//alert(html);
//    $(this.id).innerHTML+=html;
    new Insertion.Bottom($(this.id),html);
  },
  Remove: function(index){
    $('time_table_select_'+index).remove();
  },
  SetData: function(){
    var html = "";
    for(var i=0;i<this.data.length;i++){
      TimeTable.Add(this.data[i],i);
    }
//    $(this.id).update(html);
  },
  ToSec: function(hm){
    var temp = hm.split(":");
    var hour = temp[0];
    var min = temp[1];
//alert("ToSec:hour="+hour+",min="+min+"=>"+parseInt(hour,10)+","+parseInt(min,10));
    return parseInt(hour,10)*60+parseInt(min,10);
  },
  ToHM: function(hm){
    var hour = Math.floor(hm/60);
    var min = hm%60;
//alert("HM="+"hour="+hour+"("+hour.toString().length+"),min="+min+"("+min.toString().length);
    if( hour.toString().length==1 ){
      hour = "0"+hour;
    }
//    min = ("0"+min).substr(-2);
    if( min.toString().length==1 ){
      min = "0"+min;
    }
    return hour+":"+min;
  },
  ChangeEndTimeRange: function(index,value){
    // 終了時間が開始時間よりも遅いならば、
    var end_time = $F('teacher_end_time_'+index);
    // HH:MM -> HH*60+MM
    var start_time_sec = this.ToSec(value);
    var end_time_sec = this.ToSec(end_time);

    if( start_time_sec+60>end_time_sec){
      start_time_sec+=60;
      end_time = this.ToHM(start_time_sec);
//alert("ChangeEndTimeRange:"+index+","+value+",end_time="+end_time+"::"+$('teacher_end_time_'+index).length);
      for(var i=0;i<$('teacher_end_time_'+index).length;i++){
	if( end_time == $('teacher_end_time_'+index).options[i].value ){
	  $('teacher_end_time_'+index).options[i].selected = "selected";
	  break;
	}
      }
    }
  }
};


var previous_email = "--";
function FindByEmail(email){
  if( previous_email!=email ){
    previous_email = email;

    var url = "/api/user/find_by_email";
//alert(url+"?email="+encodeURIComponent(email));
    new Ajax.Request(url,{
      method: 'get',
      parameters:"email="+encodeURIComponent(email),
      evalScripts:true
    });
  }
}

function FindStudentByEmail(email){
  if( previous_email!=email ){
    previous_email = email;

    var url = "/api/user/find_student_by_email";
//alert(url+"?email="+encodeURIComponent(email));
    new Ajax.Request(url,{
      method: 'get',
      parameters:"email="+encodeURIComponent(email),
      evalScripts:true
    });
  }
}



