﻿
//start----------------用于编辑日程的form*/
var EditScheduleForm = new function(){
  
  //---------------属性
  this.sid = '';
  this.year = '';
  this.month = '';
  this.dayOfMonth = '';
  this.dayOfWeek = '';
  this.hour = '';
  this.minute = '';
  this.note = '';
  this.allday = 0;
  
  this.changed = false;
  this.mode = null;
  this.cldOptions = null;
  
  this.calendarID = 0;
  this.isTemp = false;
  this.canChoose = false;
  this.displayDiv = null;
  this.link = '';
  
  //配合index页使用的初始化
  this.initAsHome = function(){
  	this.initCldOptions();
    this.canChoose = true;
    this.displayDiv = document.getElementById("detailOptPane");
    $('#addScheduleBtn').show();
  }
  
  this.initCldOptions = function() {
  	//初始化options
    var lastSelectedCldId = getCookie('lastSelectedCldId');
    var str = '<option value="0">个人日程</option>';
    if(g_userCreatedClds){
      for(var k = 0; k < g_userCreatedClds.length; k++){
      	if (lastSelectedCldId && lastSelectedCldId != '' && g_userCreatedClds[k].calendarID == lastSelectedCldId) {
      		str += '<option value="'+g_userCreatedClds[k].calendarID+'" selected>'+g_userCreatedClds[k].calendarName+'</option>';
      		EditScheduleForm.setValue('calendarID',lastSelectedCldId,true)
      	} else {
        	str += '<option value="'+g_userCreatedClds[k].calendarID+'">'+g_userCreatedClds[k].calendarName+'</option>';
      	}
      }
    }
    if(g_userPartedClds){
      for(var k = 0; k < g_userPartedClds.length; k++){
        if(g_userPartedClds[k].permission=='1') {
        	if (lastSelectedCldId && lastSelectedCldId != '' && g_userPartedClds[k].calendarID == lastSelectedCldId) {
				str += '<option value="'+g_userPartedClds[k].calendarID+'" selected>'+g_userPartedClds[k].calendarName+'</option>';
				EditScheduleForm.setValue('calendarID',lastSelectedCldId,true)
        	} else {
        		str += '<option value="'+g_userPartedClds[k].calendarID+'">'+g_userPartedClds[k].calendarName+'</option>';
        	}
        }
      }
    }
    this.cldOptions = str;
  }
  
  //配合calendar页使用的初始化
  this.initAsCalendar = function(cid){
    this.calendarID = cid;
    this.canChoose = false;
    this.displayDiv = document.getElementById("editScheduleDiv");
    $('#addScheduleBtn,.addScheduleBtn,.uploadScheduleFileBtn').show();
  }


  this.clear = function(){
    this.sid = '';
    this.year = '';
    this.month = '';
    this.dayOfMonth = '';
    this.dayOfWeek = '';
    this.hour = '';
    this.minute = '';
    this.note = '';  
	this.allday = 0;
    this.changed = false;
    this.link = '';
  }
    
  //－－－－－－－方法
  //按照传入的schedule设置form属性
  this.setSchedule = function(schedule){
    if(schedule == null){
      window.alert("EditScheduleForm.setSchedule error!");
      return;
    }
    this.clear();
    this.sid = schedule.sid;
    this.year = schedule.year;
    this.month = schedule.month;
    this.dayOfMonth = schedule.dayOfMonth;
    this.dayOfWeek = schedule.dayOfWeek;
    this.hour = schedule.hour;
    this.minute = schedule.minute;
    this.note = schedule.note;
	this.allday = schedule.allday;
    this.calendarID=schedule.calendarID;
    this.link = schedule.link?schedule.link:'';
  }

  //返回当前数据的schedule
  this.getSchedule = function(){
    
  }
  
  this.setValue = function(name,value,format){
    this.changed = true;
    if(format!=null&&value!="*"){
      var values = value.split(",");
      for(var i=0;i<values.length;i++){
        if(values[i].length==1)values[i]="0"+values[i];
      }
      value = values.join(",");
    }
    eval("this."+name+" = value");    
    var field = eval("document.getElementById('"+name+"Field')");
    if(field!=null){
      field.value = value;
    }
  }
    
  this.isSimple=function(){
    if(this.year!="*"&&this.month!="*"&&this.dayOfMonth!=null&&this.dayOfMonth!="*"&&this.hour!="*"&&this.minute!="*"&&this.year.length+this.month.length+this.dayOfMonth.length+this.hour.length+this.minute.length==12){
      return true;
    }else{
      return false;
    }
  }
  
  
  //添加新日程
  this.newSchedule = function(){
  	if (!g_selectedDay) {
  		g_selectedDay = g_tD;
  	}
    this.clear();
    this.mode = "new";
    //取点击的日期，设置到编辑层中    
    this.year = g_cldYear+'';
    this.month = g_cldMonth+'';
    this.dayOfMonth = (g_selectedDay<10?'0':'')+g_selectedDay;
    this.hour = "09";
    this.minute = "00";
    this.note = "";

    this.setJunior();
  }

  //编辑日程
  this.edit = function(cid,sid){
    this.clear();
    //获取日程数据
    var schedule = CalendarData.findSchedule(cid,sid);
    if(schedule==null){
      window.alert("edit schedule error!");
      return;
    }
    this.setSchedule(schedule);
    this.mode = "edit";
    this.calendarID = schedule.calendarID;
    if(this.isSimple()){
      this.setJunior();
    }
    else{
      this.setSenior();
    }
  }
  
	this.showUploadScheduleForm = function() {
		$('#uploadScheduleFile').show();
	}
	
	this.uploadSchedule = function() {
		var theForm = document.forms['uploadScheduleFileForm'];
		theForm.uploadCldId.value = CalendarView.calendar.calendarID;
		theForm.uploadForward.value = self.location.href;
		theForm.submit();
	}
	
	
  
  
  this.setJunior = function(){
    var phtml ='<table cellspacing="0" cellpadding="2">';
    phtml += '<tr><td><div id="seniorBtn" onClick="EditScheduleForm.switchView(\'高级\')"></div></td></tr>';
	
	phtml += '<tr><td><input type="checkbox" name="allday" value="1"' + (this.allday ? ' checked' : '') + ' onclick="switchTimeDisplay(this.checked)" />全天日程</td></tr>';
	
    phtml += '<tr><td>';
    phtml += '<select name="year" onchange="EditScheduleForm.setValue(this.name,this.value,null)">';
    for(var i=1990,yt='';i<2020;i++){
      yt += '<option value="'+i+'" ';
      if(this.year == i) yt += 'selected';
      yt += '>'+i+'</option>';
    }
    phtml += yt;
    phtml += '</select>&nbsp;年&nbsp;';

    phtml += '<select name="month" onchange="EditScheduleForm.setValue(this.name,this.value,true)">';
    for(var i=1;i<=12;i++){
      phtml += '<option value="'+i+'" ';
      if(this.month == i) phtml += 'selected';
      phtml += '>'+i+'</option>'
    };
    phtml += '</select>&nbsp;月&nbsp;';

    phtml += '<select name="dayOfMonth" onchange="EditScheduleForm.setValue(this.name,this.value,true)">';
    for(var i=1;i<=31;i++){
      phtml += '<option value="'+i+'" ';
      if(this.dayOfMonth == i) phtml += 'selected';
      phtml += '>'+i+'</option>'
    };
    phtml += '</select>&nbsp;日&nbsp;';

	phtml += '<span id="editScheduleTime"' + (this.allday ? ' style="display:none;"' : '') + '>';
    phtml += '<select name="hour" onchange="EditScheduleForm.setValue(this.name,this.value,true)">';
    for(var i=0;i<=24;i++){
      phtml += '<option value="'+i+'" ';
      if(this.hour == i) phtml += 'selected';
      phtml += '>'+i+'</option>'
    };
    phtml += '</select>&nbsp;点&nbsp;';

    phtml += '<select name="minute" onchange="EditScheduleForm.setValue(this.name,this.value,true)">';
    for(var i=0;i<=60;i++){
      phtml += '<option value="'+i+'" ';
      if(this.minute == i) phtml += 'selected';
      phtml += '>'+i+'</option>'
    };
    phtml += '</select>&nbsp;分';
	phtml += '</span>';

    phtml += '<input type="hidden" name="sid" id="sidField"value="'+this.sid+'"/>';
    phtml += '<input class="input" type="hidden" name="type" id="typeField" value="'+(this.isTemp == true?'temp':'')+'"/>';
    phtml += '<input class="input" type="hidden" name="calendarID" id="calendarIDField" value="'+this.calendarID+'"/>';
    phtml += '</td></tr>';
	
    phtml += '<tr><td style="color:#000000">日程内容：<br><textarea name="note" cols="44" rows="3" id="noteField" onchange="EditScheduleForm.setValue(this.name,this.value,null)" class="input">'+this.note+'</textarea></td></tr>';
   	//alert(withLink);
   	if(withLink) phtml += '<tr ><td>日程链接：<input name="link" id="linkField" onchange="EditScheduleForm.setValue(this.name,this.value,null)" style="width:400px;" value="'+this.link+'"></td></tr>';
    if(this.canChoose){
      phtml += '<tr><td>请选择要添加到的日历：';
      phtml += '<select name="calendarID" onchange="EditScheduleForm.setValue(this.name,this.value,true)">';
      phtml += this.cldOptions;
      phtml += '</select></td></tr>';
    }
    phtml += '<tr><td><div id="confirmDetailBtn" onClick="EditScheduleForm.Submit()"></div> <div id="cancelDetailBtn" onClick="EditScheduleForm.hideForm()"></div>';
    phtml += '</td></tr>';
    phtml += '</table>';
    
    this.showForm(phtml);
  }
  
  this.setSenior = function(){
    var phtml ='<table cellspacing="0" cellpadding="2">';
    phtml += '<tr><td width="50%"><div id="juniorBtn" onClick="EditScheduleForm.switchView(\'简易\')"></div></td>';
    phtml += '<td width="50%" rowspan="6" valign="top" class="l20"><br>说明：高级模式可以使用逗号以及星号。例如：月份中输入4,8,10表示4月、8月和10月均安排此日程。输入*则表示每个月都安排此日程。</td></tr>';
	phtml += '<tr><td><input type="checkbox" name="allday" value="1"' + (this.allday ? ' checked' : '') + ' onclick="switchTimeDisplay(this.checked)" />全天日程</td></tr>';
    phtml += '<tr><td><input class="input" type="text" name="year" id="yearField" value="'+this.year+'" onchange="EditScheduleForm.setValue(this.name,this.value,null)"/>年</td></tr>';
    phtml += '<tr><td><input class="input" type="text" name="month" id="monthField" value="'+this.month+'" onchange="EditScheduleForm.setValue(this.name,this.value,true)"/>月</td></tr>';
    phtml += '<tr><td><input class="input" type="text" name="dayOfMonth" id="dayOfMonthField" value="'+this.dayOfMonth+'" onchange="EditScheduleForm.setValue(this.name,this.value,true)"/>日</td></tr>';
    phtml += '<tr><td>周<input class="input" type="text" name="dayOfWeek" id="dayOfWeekField" value="'+(this.dayOfWeek==null?'':this.dayOfWeek)+'" onchange="EditScheduleForm.setValue(this.name,this.value,null)"/></td></tr>';
	
	phtml += '<tbody id="editScheduleTime"' + (this.allday ? ' style="display:none;"' : '') + '>';
    phtml += '<tr><td><input class="input" type="text" name="hour" id="hourField" value="'+this.hour+'" onchange="EditScheduleForm.setValue(this.name,this.value,true)"/>时</td></tr>';
    phtml += '<tr><td><input class="input" type="text" name="minute" id="minuteField" value="'+this.minute+'" onchange="EditScheduleForm.setValue(this.name,this.value,true)"/>分</td></tr>';
	phtml += '</tbody>';
	
    phtml += '<input class="input" type="hidden" name="type" id="typeField" value="'+(this.isTemp == true?'temp':'')+'"/>';
    phtml += '<input class="input" type="hidden" name="calendarID" id="calendarIDField" value="'+this.calendarID+'"/>';
    phtml += '<input class="input" type="hidden" name="sid" id="sidField"value="'+this.sid+'"/>';
    phtml += '<tr><td colspan="2">日程内容：<br><textarea class="input" name="note" id="noteField" rows="3" cols="44" onchange="EditScheduleForm.setValue(this.name,this.value,null)">'+this.note+'</textarea></td></tr>';
    if(this.canChoose){
      phtml += '<tr><td colspan="2">请选择要添加到的日历：';
      phtml += '<select name="calendarID" onchange="EditScheduleForm.setValue(this.name,this.value,true)">';
      phtml += this.cldOptions;
      phtml += '</select></td></tr>';
      this.calendarID = 0;
    }
    phtml += '<tr><td colspan="2"><div id="confirmDetailBtn" onClick="EditScheduleForm.Submit()"></div> <div id="cancelDetailBtn" onClick="EditScheduleForm.hideForm()"></div>';
    phtml += '</td></tr>';
    phtml += '</table>';      
    
    this.showForm(phtml);
  }
  
  this.switchView = function(type){
    if(type == "简易"){
      if(!this.isSimple()){
        window.alert("此日程不能转换为简易模式");
        return;
      }
      this.setJunior();
    }else{
      this.setSenior();
    }
  }
    
  this.validate = function(){
    var errorMsg = '';
    if(this.year==null||this.year=='') errorMsg+="年不能为空\n";
    if(this.month==null||this.month=='') errorMsg+="月不能为空\n";
    if((this.dayOfMonth==null||this.dayOfMonth=='')&&(this.dayOfWeek==null||this.dayOfWeek=='')) errorMsg+="每月几号和每周几至少要填一项\n";
    if(!(this.dayOfMonth==null||this.dayOfMonth=='')&&!(this.dayOfWeek==null||this.dayOfWeek=='')) errorMsg+="每月几号和每周几只能填写其中一项\n";
    if(this.hour==null||this.hour=='') errorMsg+="时不能为空\n";
    if(this.minute==null||this.minute=='') errorMsg+="分不能为空\n";
    if(this.note==null||this.note=='') errorMsg+="日程内容不能为空\n";
    
    if(errorMsg!=''){
      window.alert(errorMsg);
      return false;
    }
    
    if(this.year.indexOf("*")>-1){
      if(this.year.length>1) errorMsg+="年格式错误：*代表每年，不需要其它字符。\n";
    }
    else if(!this.isFieldValid("year",/^1|2\d{3}$/,null)) errorMsg+="年的格式不正确，正确格式为：'2006,2007'或者'*'\n";

    if(this.month.indexOf("*")>-1){
      if(this.month.length>1) errorMsg+="月份格式错误：*代表每月，不需要其它字符。\n";
    }
    else if(!this.isFieldValid("month",/(^0[1-9]$)|(^1[012]$)/,null)) errorMsg+="月份的格式不正确，正确格式为：'01,02,...12'或者'*'\n";

    if(this.dayOfMonth.indexOf("*")>-1){
      if(this.dayOfMonth.length>1) errorMsg+="每月几号格式错误：*代表月中每天，不需要其它字符。\n";
    }
    else if(this.dayOfMonth!=null&&this.dayOfMonth!='')
      if(!this.isFieldValid("dayOfMonth",/(^0[1-9]$)|(^[12]\d$)|(^3[0-1]$)/,null)) errorMsg+="每月几号的格式不正确，正确格式为：'01,02,...,31'或者'*'\n";


    if(this.dayOfWeek && this.dayOfWeek.indexOf("*")>-1){
      if(this.dayOfWeek.length>10) errorMsg+="周几格式错误：*代表每天，不需要其它字符。\n";
    }
    else if(this.dayOfWeek!=null&&this.dayOfWeek!='')
      if(!this.isFieldValid("dayOfWeek",/^[1-7]$/,null)) errorMsg+="周几的格式不正确，正确格式为：'1,2...,7'\n";
    

    if(this.hour.indexOf("*")>-1){
      if(this.hour.length>1) errorMsg+="时格式错误：*代表每小时，不需要其它字符。\n";
    }
    else if(!this.isFieldValid("hour",/(^[01]\d$)|(^2[0-3]$)/,null)) errorMsg+="时的格式不正确，正确格式为：'01,02,...,23'或者'*'\n";
    

    if(this.minute.indexOf("*")>-1){
      if(this.minute.length>1) errorMsg+="分格式错误：*代表每分钟，不需要其它字符。\n";
    }
    else if(!this.isFieldValid("minute",/^[0-5]\d$/,null)) errorMsg+="分的格式不正确，正确格式为：'01,03,04...60'或者'*'\n";
    

    if(errorMsg!=''){
      window.alert(errorMsg);
      return false;
    }
        
    return true;    
  }

  this.isFieldValid = function(name,regx,pos){
    var fvalue = eval("this."+name);
    var valueArray = fvalue.split(",");
    for(var i=0;i<valueArray.length;i++){
      if(!regx.test(valueArray[i])) return false;
    }
    return true;
  }
  
  this.getParams = function(){
  	if(withLink)
    	return "withLink=true&link="+escape(this.link)+"&sid="+this.sid+"&year="+this.year+"&month="+this.month+"&dayOfMonth="+this.dayOfMonth+"&dayOfWeek="+this.dayOfWeek+"&hour="+this.hour+"&minute="+this.minute+"&allday=" + this.allday + "&note="+this.note+"&calendarID="+this.calendarID+(this.isTemp == true?'&type=temp':'');  		
  	else
    	return "sid="+this.sid+"&year="+this.year+"&month="+this.month+"&dayOfMonth="+this.dayOfMonth+"&dayOfWeek="+this.dayOfWeek+"&hour="+this.hour+"&minute="+this.minute+"&allday=" + this.allday + "&note="+this.note+"&calendarID="+this.calendarID+(this.isTemp == true?'&type=temp':'');
  }
  
  //提交日程数据
  this.Submit = function(){
    if(!this.changed){
      this.hideForm();
      return;
    }
    this.handler = function(xmlhttp){
      var response = JSON.parse(xmlhttp.responseText);
      if(response.state == 'success'){
        var schedule = response.schedule;
        if(EditScheduleForm.mode=='new'){
          CalendarData.addSchedule(schedule);
          //记住本次添加的日历id
          setCookie('lastSelectedCldId', EditScheduleForm.calendarID, 30);
          //刷新选项
          EditScheduleForm.initCldOptions();
          afterEditSchedule(schedule);          
        }
        else if(EditScheduleForm.mode=='edit'){
          CalendarData.updateSchedule(schedule);
          afterEditSchedule(schedule);          
        }
        EditScheduleForm.hideForm();
      }
      else if(response.state == 'duplicate'){
        window.alert("这条日程已经安排过了");
      }
      else if(response.state == 'noPermission'){
        window.alert("您的权限不足");
      }
      else if(response.state == 'noSchedule'){
        window.alert("你要编辑的日程不存在");
      }
      else if(response.state == 'noCalendar'){
        window.alert("您要编辑的日历不存在");
      }
      else
        window.alert("操作失败 ");
    }
    //alert(this.getParams());
    if(this.validate()){
      postData("/editScheduleAction.do",this.getParams(),this.handler);
    }
  }
  
  this.remove = function(cid,sid){
    if(!confirm("您确定要删除此日程吗？"))return;
    this.handler = function(xmlhttp){
      var response = JSON.parse(xmlhttp.responseText);
      if(response.state == 'success'){
      	alert('日程删除成功。');
        CalendarData.removeSchedule(cid,sid);
        afterRemoveSchedule(cid,sid);
      }
      else if(response.state == 'noPermission'){
        window.alert("您的权限不足");
      }
      else if(response.state == 'noSchedule'){
        window.alert("你要删除的日程不存在");
      }
      else if(response.state == 'noCalendar'){
        window.alert("您要删除的日历不存在");
      }
      else
        window.alert("操作失败 ");
    }
    postData("/removeScheduleAction.do","sid="+sid,this.handler);
  }

  //显示编辑窗口
  this.showForm = function(html){
    this.displayDiv.innerHTML = html;
    try{afterShowEditForm(this.mode)}catch(err){};
  }
  
  //关闭编辑窗口
  this.hideForm = function(){
    this.displayDiv.innerHTML = '';
    try{afterHideEditForm()}catch(err){};
  }
}

function switchTimeDisplay(isAllday) {
	EditScheduleForm.changed = true;
	if (isAllday) {
		$('#editScheduleTime').hide();
		EditScheduleForm.allday = 1;
	} else {
		$('#editScheduleTime').show();
		EditScheduleForm.allday = 0;
	}
}

