/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * Copyright (C) 2004-2008 Aimluck,Inc.
 * http://aipostyle.com/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
dojo.require("aipo.widget.MemberNormalSelectList");
dojo.require("aipo.widget.DropdownDatepicker");

/* dojo.require("aipo.document.DropdownDatepicker"); */

dojo.provide("aipo.document");

aipo.document.onLoadDocumentFileDialog = function(pid){

    var obj = dojo.byId("file_title");
    if(obj){
        obj.focus();
    }

}

aipo.document.onLoadDocumentFolderDialog = function(pid){

    var obj = dojo.byId("folder_name");
    if(obj){
        obj.focus();
    }

    var mpicker = dijit.byId("membernormalselect");
    if(mpicker){
      var select = dojo.byId('init_memberlist');
      var i;
      var s_o = select.options;
      if (s_o.length == 1 && s_o[0].value == "") return;
      for(i = 0 ; i < s_o.length; i ++ ) {
        mpicker.addOptionSync(s_o[i].value,s_o[i].text,true);
      }
    }

}

aipo.document.onLoadDocumentFileDialog = function(pid){

    var obj = dojo.byId("folder_name");
    if(obj){
        obj.focus();
    }

    var mpicker = dijit.byId("membernormalselect");
    if(mpicker){
      var select = dojo.byId('init_memberlist');
      var i;
      var s_o = select.options;
      if (s_o.length == 1 && s_o[0].value == "") return;
      for(i = 0 ; i < s_o.length; i ++ ) {
        mpicker.addOptionSync(s_o[i].value,s_o[i].text,true);
      }
    }
    
    var mpicker2 = dijit.byId("membernormalselect2");
    if(mpicker2){
      var select2 = dojo.byId('init_memberlist2');
      //var i;
      var s_o2 = select2.options;
      if (s_o2.length == 1 && s_o2[0].value == "") return;
      for(i = 0 ; i < s_o2.length; i ++ ) {
        mpicker2.addOptionSync(s_o2[i].value,s_o2[i].text,true);
      }
    }
    
    var picker = dijit.byId("membernormalselect_workflow");
    if(picker){
        var memberlist_workflow = picker;
        var select = dojo.byId('init_memberlist_workflow');
        var i;
        var s_o = select.options;
        if (s_o.length == 1 && s_o[0].value == "") return;
        for(i = 0 ; i < s_o.length; i ++ ) {
            memberlist_workflow.addOptionSync(s_o[i].value,s_o[i].text,true);
        }
    }

    var obj = dojo.byId("route_name");
    if(obj){
       obj.focus();
    }

}

aipo.document.onLoadDocumentFileDetailDialog = function(pid){
	var picker = dijit.byId("membernormalselect_workflow");
    if(picker){
        var memberlist_workflow = picker;
        var select = dojo.byId('init_memberlist_workflow');
        var i;
        var s_o = select.options;
        if (s_o.length == 1 && s_o[0].value == "") return;
        for(i = 0 ; i < s_o.length; i ++ ) {
            memberlist_workflow.addOptionSync(s_o[i].value,s_o[i].text,true);
        }
    }

    var obj = dojo.byId("route_name");
    if(obj){
       obj.focus();
    }
}


aipo.document.onReceiveMessage = function(msg){
    if(!msg) {
        var arrDialog = dijit.byId("modalDialog");
        if(arrDialog){
            arrDialog.hide();
        }
        aipo.portletReload('document');
        aipo.portletReload('schedule');
    }
    if (dojo.byId('messageDiv')) {
        dojo.byId('messageDiv').innerHTML = msg;
    }
}

aipo.document.onListReceiveMessage = function(msg){
    if(!msg) {
        var arrDialog = dijit.byId("modalDialog");
        if(arrDialog){
            arrDialog.hide();
        }
        aipo.portletReload('document');
    }
    if (dojo.byId('listmessageDiv')) {
        dojo.byId('listmessageDiv').innerHTML = msg;
    }
}

// 一覧画面の検索ボタンを押したときの処理　　フォームのデータを登録する。
aipo.document.onSubmitSerchButton = function(form,url,p_id){
     var exec_url = url;
     //var search_params = [["sword",form.sword.value]];
     var search_params = [["sword",form.sword.value],["checkout_flag",form.checkout_flag.checked],["request_flag",form.request_flag.checked],["target_user_id",form.target_user_id.value]];
     aipo.viewPage(exec_url, p_id, search_params);
}

aipo.document.viewpageByFolderId = function(url,p_id,f_id){
    url = url + '&folder_id=' + f_id;
    aipo.viewPage(url, p_id);
}

aipo.document.ajaxDeleteSubmit = function(button, url, indicator_id, portlet_id, receive) {
  if(confirm('この'+button.form._name.value+'を削除してよろしいですか？なお、フォルダに含まれるファイルやフォルダはすべて削除されます。')) {
    aimluck.io.disableForm(button.form, true);
    aimluck.io.setHiddenValue(button);
    button.form.action = url;
    aimluck.io.submit(button.form, indicator_id, portlet_id, receive);
  }
}

aipo.document.ajaxCheckOutSubmit = function(button, url, url2, indicator_id, portlet_id, message, receive) {
  if(confirm(message + 'よろしいですか？')) {
    aimluck.io.disableForm(button.form, true);
    aimluck.io.setHiddenValue(button);
    button.form.action = url;
    aimluck.io.submit(button.form, indicator_id, portlet_id, receive);
    window.open(url2,"_top");
  }
}

aipo.document.ajaxFileDeleteSubmit = function(button, url, indicator_id, portlet_id, message, receive) {
  if(confirm(message + 'よろしいですか？')) {
    aimluck.io.disableForm(button.form, true);
    aimluck.io.setHiddenValue(button);
    button.form.action = url;
    aimluck.io.submit(button.form, indicator_id, portlet_id, receive);
  }
}

aipo.document.ajaxSubmit = function(button, url, indicator_id, portlet_id, message, receive) {
  if(confirm(message + 'よろしいですか？')) {
    aimluck.io.disableForm(button.form, true);
    aimluck.io.setHiddenValue(button);
    button.form.action = url;
    aimluck.io.submit(button.form, indicator_id, portlet_id, receive);
  }
}

aipo.document.showMember = function(button) {
  dojo.byId('Block-GroupMember-Show').style.display="";
  dojo.byId('is_member').value = "TRUE";
}

aipo.document.hideMember = function(button) {
  dojo.byId('Block-GroupMember-Show').style.display="none";
  dojo.byId('member_to').options.length = 0;
  dojo.byId('is_member').value = "FALSE";
}

//チェックボックスの状態によってメンバーリストの表示・非表示を切り替え
aipo.document.switchMember = function(checkbox, member) {
	if (dojo.byId(checkbox).checked) {
		//チェックボックスがチェックされている場合
		//メンバーを非表示にする。
		dojo.byId(member).style.display="none";
	} else {
	//チェックボックスがチェックされていない場合
		//メンバーを表示する。
		dojo.byId(member).style.display="";
	}
}

// カレンダーをクリアする
// （aipo.widget.DateCalendar.disabledCalendar メソッドと同じ処理を行う）
aipo.document.clearDatepicker = function(dateId) {
           var viewvalue = dojo.byId(dateId+'_view');
           viewvalue.innerHTML = "---- 年 -- 月 -- 日&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";

           var hiddendate_year = dojo.byId(dateId+'_year');
           hiddendate_year.value = "";
           var hiddendate_month = dojo.byId(dateId+'_month');
           hiddendate_month.value = "";
           var hiddendate_day = dojo.byId(dateId+'_day');
           hiddendate_day.value = "";
           
           dojo.byId(dateId).value = "";
           
           if(! dojo.byId(dateId+'_flag').checked) dojo.byId(dateId+'_flag').checked = true;
           //dojo.byId(dateId+'_flag').checked = false;
           //alert("flagchecked = " + dojo.byId(dateId+'_flag').checked);
          
}

aipo.document.openRevList = function(url){
    var wx = 800;
    var wy = 500;
    var x = (screen.width  - wx) / 2;
    var y = (screen.height - wy) / 2;

    var revlist_subwin = window.open(url,"rev_list_window","left="+x+",top="+y+",width="+wx+",height="+wy+",resizable=yes,status=yes,scrollbars=yes");
    revlist_subwin.focus();
}

aipo.document.ajaxCheckinSubmit = function(button, message, url, indicator_id, portlet_id, receive) {
  if(message =="" || confirm(message + 'よろしいですか？')) 
  {
    aimluck.io.disableForm(button.form, true);
    aimluck.io.setHiddenValue(button);
    button.form.action = url;
    aimluck.io.submit(button.form, indicator_id, portlet_id, receive);
  }
}

//aipo.document.ajaxCheckin = function(button, message, url, indicator_id, portlet_id, receive) {
aipo.document.ajaxCheckin = function(button, message, indicator_id, portlet_id, receive) {
  if(confirm(message + 'よろしいですか？')) 
  {
    aimluck.io.disableForm(button.form, true);
    aimluck.io.selectAllOptions(button.form.attachments);
    aimluck.io.selectAllOptions(button.form.relations);
    //aimluck.io.selectAllOptions(dojo.byId("attachments"));
    //aimluck.io.selectAllOptions(dojo.byId("relations"));
    aimluck.io.setHiddenValue(button);
    //button.form.action = url;
    aimluck.io.submit(button.form, indicator_id, portlet_id, receive);
  }
}


/****** aipo/relationupload/form.js ******/

dojo.provide("aipo.relationupload");

aipo.relationupload.getFolderName = function() {

    var obj = dojo.byId("folderName");
//    if(obj){
//        obj.focus();
//    }

}

aipo.relationupload.onAddFileInfo = function(foldername, fileid, filename) {
    var select = dojo.byId('relations');
    var value = fileid;
    var text = filename;
    aimluck.io.addOption(select, value, text, false); 
    
    dojo.byId('folderName').value =  foldername;
}
                  
aipo.relationupload.openAttachment = function(url){
    var wx = 430;
    //var wy = 175;
    //var wy = 200;
    var wy = 210;
    var x = (screen.width  - wx) / 2;
    var y = (screen.height - wy) / 2;
    
    var select = dojo.byId('relations');
    var select_len = select.options.length;
    if(select_len == 1 && select.options[0].value == ''){
        select_len = 0;
    }

    var attachment_subwin = window.open(url+'&nsize='+select_len,"attachment_window","left="+x+",top="+y+",width="+wx+",height="+wy+",resizable=yes,status=yes");
    attachment_subwin.focus();
}

/****** aipo/relationupload/widget/relationuploadDialog.js ******/

dojo.provide("aipo.relationupload.widget.RelationuploadDialog");
dojo.provide("aipo.relationupload.widget.RelationuploadDialogUnderlay");

dojo.require("aimluck.widget.Dialog");

dojo.declare(
    "aipo.relationupload.widget.RelationuploadDialogUnderlay",
    [aimluck.widget.DialogUnderlay],
    {
       templateString: "<div class=relationuploadDialogUnderlayWrapper id='${id}_underlay'><div class=relationuploadDialogUnderlay dojoAttachPoint='node'></div></div>"
    }

);

dojo.declare(
    "aipo.relationupload.widget.RelationuploadDialog",
    [aimluck.widget.Dialog],
    {
        loadingMessage:"<div class='indicator'>読み込み中...</div>",
        templateCssString:"relationuploadDialog",
        templateString:"<div id='relationuploadDialog' class='${templateCssString}' dojoattachpoint='wrapper'><span dojoattachpoint='tabStartOuter' dojoonfocus='trapTabs' dojoonblur='clearTrap'tabindex='0'></span><span dojoattachpoint='tabStart' dojoonfocus='trapTabs' dojoonblur='clearTrap' tabindex='0'></span><div dojoattachpoint='containerNode' style='position: relative; z-index: 2;'></div><span dojoattachpoint='tabEnd' dojoonfocus='trapTabs' dojoonblur='clearTrap' tabindex='0'></span><span dojoattachpoint='tabEndOuter' dojoonfocus='trapTabs' dojoonblur='clearTrap' tabindex='0'></span></div>",
        _setup: function(){

            this._modalconnects = [];

            if(this.titleBar){
                this._moveable = new dojo.dnd.Moveable(this.domNode, { handle: this.titleBar });
            }

            this._underlay = new aipo.relationupload.widget.RelationuploadDialogUnderlay();

            var node = this.domNode;
            this._fadeIn = dojo.fx.combine(
                [dojo.fadeIn({
                    node: node,
                    duration: this.duration
                 }),
                 dojo.fadeIn({
                    node: this._underlay.domNode,
                    duration: this.duration,
                    onBegin: dojo.hitch(this._underlay, "show")
                 })
                ]
            );

            this._fadeOut = dojo.fx.combine(
                [dojo.fadeOut({
                    node: node,
                    duration: this.duration,
                    onEnd: function(){
                        node.style.display="none";
                    }
                 }),
                 dojo.fadeOut({
                    node: this._underlay.domNode,
                    duration: this.duration,
                    onEnd: dojo.hitch(this._underlay, "hide")
                 })
                ]
            );
        }
    }
);


/*** ワークフローから移植 ***/

aipo.document.formSwitchRouteSelect = function(button) {
    if(button.form.is_saved_route.value == 'TRUE' || button.form.is_saved_route.value == 'true') {
        button.value = '申請経路一覧から選択する';
        aipo.document.formRouteSelectOff(button.form);
    } else {
        button.value = 'ユーザー一覧から選択する';
        aipo.document.formRouteSelectOn(button.form);
    }
}

aipo.document.formRouteSelectOn = function(form) {
    dojo.byId('workflowRouteSelectField').style.display = "";
    dojo.byId('workflowRouteInputField').style.display = "none";

    form.is_saved_route.value = 'TRUE';
}

aipo.document.formRouteSelectOff = function(form) {
    dojo.byId('workflowRouteSelectField').style.display = "none";
    dojo.byId('workflowRouteInputField').style.display = "";

    form.is_saved_route.value = 'FALSE';
}

aipo.document.onChangeSelecter = function(portletId , url , values, named , flgName){

    dojo.byId(flgName).checked = false;
    var callbackArgs = new Array();
    callbackArgs["named"] = "workflow_" + named;

    aimluck.io.sendRawData(url + "&value=" + values,values,aipo.document.setTemplate,callbackArgs);

    return false;
}

aipo.document.setTemplate = function(array,rtnData){

        var jsonData = eval( '('+rtnData["type"].toString().slice(4,-4)+')' );
        var routeH = jsonData.route_h;
        var route = jsonData.route;

        var routeArray = route.split(",");
        var routeLength = (routeArray.length-1)/2;

        if ( route == null || route == "" ) {
            dojo.byId(array["named"]).style.display = "none";
        } else {
            dojo.byId(array["named"]).style.display = "";
        }

        if ( route == null || route == "") {
            dojo.byId(array["named"]).value = "";
        } else {
            dojo.byId(array["named"]).value = routeH;
        }

        memberFrom = dojo.byId('tmp_member_from_workflow');
        memberFromOpts = memberFrom.options;
        for ( i = 0; i < memberFromOpts.length ; i++ ){
            memberFromOpts[i].selected = false;
        }
        memberTo = dojo.byId('positions_workflow');
        while(memberTo.lastChild) {
             memberTo.removeChild(memberTo.lastChild);
       }
        var opt;
        for ( i = 0; i < routeLength ; i++ ){
            memberTo.options[i] = new Option(routeArray[2*i+1], routeArray[2*i]);
        }
}
