Search:
Template:Directories > Template:XsysPrEdit

Template:XsysPrEdit

    Table of contents
    No headers

     

    /* 
    //    Copyright (C) 2010 - www.intertesto.com - www.fitzcarraldo.it
    //    Author: gianluca.sabena@intertesto.com - adrian.policarp@fitzcarraldo.it
    //
    //    This program is free software: you can redistribute it and/or modify
    //    it under the terms of the GNU General Public License  http://www.gnu.org/licenses/gpl-2.0.html
    //    
    // ------ Docs ----------------------
    //
    // Fields:[{type:'',label:'',field:'',value:'',help:'', ,...},{...},...] - Define a series of input types element
    // type: name of input type - see below
    // label: label of input elements
    // field: name of the field used when store data in properties
    // elements: list or map of values (apply to radio and select) 
    // value: default value when create new form
    // help: optional text to help the insertion
    // viewshow:bool (optional, default: true) show field in view mode
    // isreadonly: bool (optional, default:false) make fieled readonly
    // isrequired:bool (optional, default:false) field is required, disabled save button if no text is inserted
    // iscreateonly:bool (optional, default:false) display fields ONLY when create page and DO NOT save in properties
    // istag:bool(optional, default:false) append value to page tags
    // tagprefix:string - text to prepend to value (usefull for date: tag ecc..)
    // 
    // TYPE:
    // -- html_text = html input type text - size:'num' (default 16) html max input - 
    //                maxlength:'num' (optional,default:255) maximum chars length allowed
    //                jqmaxchars:num - bind a jq function that check a max length
    // -- html_mail = html input type mail - size:'num' (default 16) html max input - 
    //                maxlength:'num' (optional,default:255) maximum chars length allowed
    //                jqmaxchars:num - bind a jq function that check a max length
    // -- html_link = html input type web link - size:'num' (default 16) html max input - 
    //                maxlength:'num' (optional,default:255) maximum chars length allowed
    //                jqmaxchars:num - bind a jq function that check a max length
    // -- html_hidden = html input type hidden
    // -- html_textarea = html input type textarea - row: number of rows - cols: num of colons - 
    //                    newline: bool (default false) replace '\n' with <br />
    // -- html_select = html input type select - elements: list or map used to create drop down select, 
    //                  if map map.key is stored and map.value is displayed as label
    // -- html_checkbox = html input type checkbox - elements: single value, set elements = value 
    //                    to start a new form checked
    // -- html_radio = html input type radio - elements:list of radio value-label 
    // -- mtsid_user = input type select single from a list of wiki users, store user-page-id - 
    //                 link:(page|changes|none, default: none) Insert a link to user page, recent changes of 
    //                 the user, or no link
    // -- mtmid_users = identical mtsid_user, but accept multiple select	 
    // -- mtsid_page = input type select single from a list of page titles, store page-id - 
    //                 link:(default: true) in view mode insert a link to page - getsearch: list of 4 value,
    //                 passed in order to  wiki.getsearch() - pathsearch: path to page where get all 1 level 
    //                 subpages (if end with /* extract 2 level subpages) 
    // -- mtmid_pages = same as mtsid_page, but allow multiple selections
    // -- mtmtx_tags = html input tag, store list of tags as string and update page tags via @api, 
    //                 tags are separated using colon or semicolon - jqautocomplete: bool (default: false) 
    //                 enable jQuery autocomplete tags list - hidetags:list if match from left tag is hidden in
    //                 view and in autocomplete
    // -- mt_body = textarea - used only in create new page mode - text to append in the new created page afther newpagecontent
    // -- jq_date = jQuery datepicker - display date in format dd-mm-yyyy, but save in format yyyy-mm-dd
    //              so it is test sortable
    // NOTE:
    // -- tags: we push tags in MT tags space in 2 way: a field mtmtx_tags and any field with attribute
    //    istag:true, the forms OVERRIDE any tags added from skin
    // TODO:
    // - enanche tags management, the forms override ANY tags adeed from skin, we need to match them togheter
    */
    /* ------------------- Config ------------------------------------ */
    var prname = $prname ?? "formdata"; /* name of properties used to store data */
    var titlefields = $titlefields ?? []; /* list of fields name used to generate page title name */
    var titlejointstring = $titlejointstring ?? " - "; /* string used to joint different titlefields */ 
    var issynctitle = $issynctitle ?? true; /* update page title via @api  to sync with titlefields */
    var inputs = $fields ?? [ ]; /* array of maps that define forms fields */
    var newpagecontent = $newpagecontent ?? ""; /* page content to inject when create new page */
    var pathsearch = $pathsearch ?? ""; /* page path to look fot properties when we update */
    var loc = "ita"; /* localize message - see labels below */
    var firstSelectLabel = "--- Select ---"; /* text added as first option in a html drop down menu */
    var firstSelectValue = "----Not selected---"; /* value saved as first option in a html drop down menu */
    
    /* ------------------ Init ---------------------------------------- */
    var debug=false; /* mus be exactly true or false - if true display debug info and don't redirect */
    var jqautocompletepath = "http://scripts.intertesto.com/jquery/jquery.autocomplete.pack.js"; /* link to a jquery autocomplete.pack.js */
    var labels = {ita:{
                  clearButton:"Clear",
                  editButtonUpdate:"Update "..prname,
                  editButtonAdd:"Create "..prname,
                  saveButton:"Save",
                  cancelButton:"Cancel",
                  msgNoData:"No Data",
                  msgOnSave:"On Save...",
                  msgGoto:"Go to page >>",
                  msgReload:"Reload page >>",
                  msgIsAppendDataDetect:"There is data saved in the previous version of the form: ",
                  msgAjaxOkPageRead:'Page read',
                  msgAjaxOkPageUpdate:'Page update',
                  msgAjaxErrorPageRead:'Error reading the page',
                  msgAjaxErrorPageUpdate:'Error updating the page',
                  msgAjaxOkTagUpdate:'Update Tag',
                  msgAjaxErrorTagUpdate:'Error updating page',
                  msgAjaxOkPageCreate:'Create new page',
                  msgAjaxErrorPageCreate:'Error creating page!',
                  msgAjaxOkPropertyCreate:'Create content',
                  msgAjaxErrorPropertyCreate:'Error creating content',
                  msgAjaxOkPropertyUpdate:'Content updated',
                  msgAjaxErrorPropertyUpdate:'Error updating content',
                  msgAjaxErrorPropertyRead:'Error reading content', 
                  msgFieldRequired:' - Required field',
                  msgFieldCharsCount:'Character count: ',
                  msgFieldCharsFull:'Warning! Maximum chracters reached: ',
                  msgFieldSaveRequired:'Required fields must be completed to save form: ',
                  msgOkSave:'Save sucessful ',
                  msgErrorSave:'Warning: there has been a error in saving the page. Please reload',
                  msgPageExsists:'The page already exits. Update content!'
                  },
                  eng:{MsgNoData:"Store contains no data"}};
    
    /* ------ check parameters --------- */
    var pp; /* page object where properties are stored */
    
    if (#pathsearch > 0 ) {
      let pp = wiki.getpage(pathsearch);
    } else {
      let pp = page;
    }
    var data = json.parse(pp.properties[prname].text ?? 'null');
    
    /* -- define and compute  script state -- */
    
    var ispredit = false; /* true when we are in edit mode - update OR create */
    if (__request.args['ispredit']=='true' && __request.args['prname']==prname) let ispredit = true;
    var editmode = false; /* true when we edit page properties */
    if(#data > 0) let editmode = true;
    var iscreatepage = false; /* true when we edit properties for a new page */
    if (#$newpagepath > 0 ) let iscreatepage = true;
    
    /* ----- */
    var appendfields =[]; 
    var requiredfields = []; /* list of fields required  */
    let newpagecontent = string.escape(newpagecontent);
    var jsBtFormEdit = ""; /* javascript code to execute on Button Edit click */
    
    var errors = "";
    var fieldvalues = list.collect(inputs,'field');
    var fieldtypes = list.collect(inputs,'type');
    
    var tagInputId = ''; /* unique id selectorr of tags input box */
    var tagfields = []; /* list of tagid to append to page tags */
    var mtbodyid = ""; /* css id of mt_body field */
    var newpagepath = '';
    if (#$newpagepath > 0 && wiki.pageExists($newpagepath)) let newpagepath = $newpagepath;
    else if (#$newpagepath > 0) let errors ..="<li>Error! NEWPAGEPATH is set to a NON EXISTING PAGE:"..$newpagepath.."</li>";
    foreach (var t in titlefields ) {
      if (#t > 0 && !(list.contains(fieldvalues,t))) {
        let errors ..= "<li>Error! TITLEFIELD is set to a NON EXISTING FIELD value:"..t.."</li>";
      }
    }
    if (string.startswith(newpagepath,'/')) let newpagepath = string.remove(newpagepath,0,1);
    if (string.endswith(newpagepath,'/')) let newpagepath = string.remove(newpagepath,#newpagepath-1,1);
    if (list.contains(fieldvalues,"fpid")) {
      let errors ..= "<li>Error!   FPID is a reserver word, can't be a input.field value!</li>";
    }
    if (list.contains(fieldvalues,"fsid")) {
      let errors ..= "<li>Error!   FSID is a reserver word, can't be a input.field value!</li>";
    }
    
    
    
    /* ------------------- render view ------------------------------------------ */
    
    if (!ispredit && !user.anonymous && wiki.pagepermissions(pp.path).update) {
      if (iscreatepage)  web.link(pp.uri.."?ispredit=true&prname="..prname,labels[loc].editButtonAdd);
      else {
        if (!editmode && !user.anonymous && wiki.pagepermissions(pp.path).update) <p>;labels[loc].msgNoData;</p>;
        web.link(pp.uri.."?ispredit=true&prname="..prname,labels[loc].editButtonUpdate);
      }
    }
    
    /* ------------------ edit / add --------------------------------------------- */
    if (#errors == 0 && ispredit==true) {
      /* ------------------ check dependance extensions and reserved fields ----- */
      dekiapi();
      if (list.contains(fieldtypes,"mtmtx_tags")) {
        <script type="text/javascript" src=(jqautocompletepath)></script>
      }
      if (list.contains(fieldtypes,"jq_date")) {
        jquery.ui('smoothness');
      }
      if (list.contains(fieldtypes,"int_locator")) {
        locator.init();
      }
      /* --------- conservative data check ------------ */
      if(#data > 0) {
        var keys = map.keys(data[0]);
        foreach (var key in keys) {
          if (!(list.contains(fieldvalues,key))) let appendfields ..=[key];
        }
      }
      <div id="FormStatus"></div>
      <div id="FormMessages"></div>
      <div id="DivFormEdit">
      <form>
        <div id=(@form)>
          <input type="hidden" id="fpid" name="fpid" value=(pp.id)  />; //add a unique id set to wiki pageid 
          <input type="hidden" id="fsid" name="fsid" value="1"  />; //add a unique sequential id 
            foreach (var input in inputs where !(editmode && input.iscreateonly)) {
                var jmessage = "";
                var jsform = ""; /* javascript jem function to attach to any form elements */
                if (input.isrequired == true) let requiredfields..=[input.field];
                if (input.istag == true) let tagfields..=[input.field.."||"..input.tagprefix];
                var type = input.type ? (string.tolower(input.type)) : "html_text"; // default to 'text'
                if (input.type == "html_hr") {
                    <div class="fHr" >;web.html("<hr />");</div>;
                }
                else if (input.type == "html_label") {
                    <div class="fTitle" >;web.html(input.value);</div>;
                } else {
                    var inputclass = "";
                    let jmessage = (input.jqmaxchars+0 > 0 ? labels[loc].msgFieldCharsCount..input.jqmaxchars:"")..(input.isrequired ? labels[loc].msgFieldRequired : "");
                    let jsform = (input.isrequired > 0 ? "when($this.keyup) CheckField(); ":"");
    
                    if (iscreatepage && input.iscreateonly) let inputclass="createonly"; 
                    if (iscreatepage && input.isrequired) let inputclass="frequired"; 
                    <div class=(input.field..' fRow')>;
                    <span class="fLabel" > (input.label && input.type!='html_hidden' ?  string.tocamelcase(input.label):'') </span>;
                    <span class="fField" >;
                        if (type == "html_text" || type == "html_link" || type == "html_mail") {
                            var v = (editmode ? data[0][input.field] : input.value);
                            var r = (input.isreadonly ? "readonly":"nul");
                            let jsform ..= (input.jqmaxchars+0 > 0 ? "when($this.keyup) limitChars($this,"..input.jqmaxchars..",'fInfo"..input.field.."','"..jmessage.."');":"");
                            <input type="text" id=(input.field) name=(input.field) class=(inputclass) value=(v) size=(input.size ?? 16) maxlength=(input.maxlength ?? 255) (r)=(r) ctor=(jsform) />;                        
                        }
                        else if (type == "html_textarea" || (type == "mt_body" && iscreatepage)) {
                            let mtbodyid = (type == "mt_body" ? input.field :"");
                            var v = (editmode ? data[0][input.field] : input.value);
                            let jsform ..= (input.jqmaxchars+0 > 0 ? "when($this.keyup) limitChars($this,"..input.jqmaxchars..",'fInfo"..input.field.."','"..jmessage.."');":"");
                            <textarea id=(input.field) name=(input.field) class=(inputclass) cols=(input.cols ?? 30) rows=(input.rows ?? 4) ctor=(jsform)>v</textarea>;
                        }
                        else if (type == "html_hidden") {
                            var v = (editmode ? data[0][input.field] : input.value);
                            <input type="hidden" id=(input.field) name=(input.field)  class=(inputclass) value=(v)  />;
                        }
                        else if (type == "html_select")
                            <select id=(input.field) name=(input.field) class=(inputclass) >;
                                <option value=(firstSelectValue)   > firstSelectLabel </option>;
                                var val = "";
                                var key = "";
                                if (typeof input.elements == 'list') { 
                                  let val = input.elements;
                                  let key = input.elements;
                                }
                                else if (typeof input.elements == 'map') {
                                  let val = map.values(input.elements);
                                  let key = map.keys(input.elements);
                                } key;
                                foreach (var opt in val) {
                                  var v ="nul";
                                  if (editmode && data[0][input.field] == key[__index]) let v = "selected";
                                  else if (!editmode && opt == input.value) let v = "selected";
                                  <option value=(key[__index]) (v)=(v)  > opt; </option>;
                                }
                            </select>;
                        else if (type == "html_radio") {
                            foreach (var opt in input.elements) {
                                var v ="nul";
                                if (editmode && data[0][input.field] == opt) let v = "checked";
                                else if (!editmode && opt == input.value) let v = "checked";
                                <input style="width:auto;" id=(input.field) type="radio" name=(input.field) class=(inputclass) value=(opt) (v)=(v)> " "..opt.." " </input>;
                            }
                        }
                        else if (type == "html_checkbox") {
                                var v ="nul";
                                if (editmode && data[0][input.field] == input.elements) let v = "checked";
                                else if (!editmode && input.elements == input.value) let v = "checked";
                                <input id=(input.field) type="checkbox" name=(input.field) class=(inputclass) value=(input.elements) (v)=(v) />;
                            }
                        else if (type == "mtsid_user") {                  
                                <select id=(input.field)  name=(input.field) class=(inputclass) >
                                <option value=(firstSelectValue)   > firstSelectLabel </option>;
                                foreach(var u in site.users where !u.anonymous) {
                                  var v ="nul";
                                  if (editmode && data[0][input.field]+0 == u.id) { let v = "selected"};
                                    <option value=(u.id) (v)=(v)>u.name</option>
                                }
                                </select>
                            }
                        else if (type == "mtmid_users") {                  
                                <select id=(input.field)  name=(input.field) class=(inputclass) multiple="multiple">
                                <option value=(firstSelectValue)   > firstSelectLabel </option>;
                                foreach(var u in site.users where !u.anonymous) {
                                  var v ="nul";
                                  if (editmode && list.contains(data[0][input.field]..[""],u.id.."")) { let v = "selected"};
                                    <option value=(u.id) (v)=(v)>u.name</option>
                                }
                                </select>
                            }
                        else if (type =="mtsid_page" || type == "mtmid_pages") {
                          var pl = {};
                          if (#input.pathsearch > 0 ) {
                            foreach (var searchpagepath in input.pathsearch) {
                              var path = "";
                              if (string.startswith(searchpagepath,'/')) let searchpagepath = string.remove(searchpagepath,0,1);
                              if (string.endswith(searchpagepath,'/')) let path = string.remove(searchpagepath,#searchpagepath-1,1);
                              else if (string.endswith(searchpagepath,'/*')) let path = string.remove(searchpagepath,#searchpagepath-2,2);
                              else let path =  searchpagepath;
                              var t = wiki.getpage(path);
                              if (string.endswith(searchpagepath,'/*')) let pl ..= t.subpages;
                              else let pl ..= {(t.name):t};
                            }
                          } else if (#input.getsearch > 0) {
                            let pl = wiki.getsearch(input.getsearch[0],input.getsearch[1],input.getsearch[2],input.getsearch[3]);
                          } else "Error! PATSEARCH or GETSEARCH parameter is required!";
                          if (type == "mtsid_page") {                  
                                <select id=(input.field)  name=(input.field) class=(inputclass) >
                                <option value=(firstSelectValue)   > firstSelectLabel </option>;
                                foreach(var p in pl ) {
                                  var v ="nul";
                                  if (editmode && data[0][input.field]+0 == p.id) { let v = "selected"};
                                  <option value=(p.id) (v)=(v)>p.title</option>
                                }
                                </select>
                            }
                          else if (type == "mtmid_pages") {    
                                <select id=(input.field)  name=(input.field) class=(inputclass) multiple="">
                                <option value=(firstSelectValue)   > firstSelectLabel </option>;    
                                foreach(var p in pl) {
                                  var v = "nul";
                                  if (editmode && list.contains(data[0][input.field]..[""],p.id.."")) { let v = "selected"};
                                    <option value=(p.id) (v)=(v)>p.title</option>
                                }
                                </select>
                          }
                        }
                        else if (type == "mtmtx_tags") {
                            var v = (editmode ? data[0][input.field] : input.value);
                            var suggesttags = [];
                            if (#input.hidetags>0) {
                              foreach (var k in map.keys(site.tags) where #k>0) {
                                  if (#list.select(input.hidetags..[],"string.startswith(string.tolower(string.trim('"..k.."')),string.trim(string.tolower($)))") == 0) { 
                                    let suggesttags ..= [string.trim(k)];
                                  }                          
                              }
                            } else let suggesttags = map.keys(site.tags);
                            var autocomplete = string.join(suggesttags," ");
                              <script type="text/jem">"
                                $(document).ready(function(){
                                  var data = '"..autocomplete.."'.split(' ');
                                  $('#"..input.field.."').autocomplete(data,{multiple: true, mustMatch: false, max: 4, autoFill: true });
                                });
                             " </script>
                            <input type="text" id=(input.field) name=(input.field) class=(inputclass) value=(v) size=(input.size ?? string.length(v)+12) maxlength=(input.maxlength ?? 255)  ctor=(jsform) />;
                            let tagInputId = input.field;
                        }
                        else if (type == "jq_date") {
                            var v = (editmode ? data[0][input.field] : input.value);
                            <input id=("jqdateview"..__count) type="text" readonly="readonly" value=(date.isvalid(v) ? date.format(v,'dd-MM-yyyy'):"") ctor=("$this.datepicker({ altField:'#"..input.field.."',dateFormat:'dd-mm-yy',altFormat: 'yy-mm-dd' })")/>
                            <input id=(input.field) type="hidden"  name=(input.field) class=(inputclass) value=(v)  />;
                        }
                        else if (type == "int_locator") {
                            var v = (editmode ? data[0][input.field] : input.value);
                            <div id="int_locator" >locator.coordinates(input.optCoor);</div>
                            let jsBtFormEdit="gmapCoordinatesInit();";
                        }
                        else
                            <span style="color:red"> "ERROR: unknown input type '"..type.."'" </span>;
                    </span> /*class="fField"*/
                    
                    <div class="fHelp" ><span id=("fInfo"..input.field)>jmessage;</span>" ";<span>input.help</span></div>;
                </div>
              }
            }
            // -- isappenddata
            if (#appendfields > 0) {
              <div class="appenddata">
                labels[loc].msgIsAppendDataDetect;
                foreach (var f in appendfields) {
                  <div id=("div_"..f)>f.." "; 
                    <input id=(f) name=(f) value=(data[0][f]) readonly="readonly" />
                    <a href="#" ctor="when($this.click) { Deki.$('#div_'+{{f}}).remove();}" >"remove"</a>
                  </div>
                }
              </div>
             }
                <div class="BtFormSave fRow">
                    <input id="BtFormSave" type="button" value=(labels[loc].saveButton;)  disabled="disabled" />
                    <div class="fHelp" ><span id=("fInfoBtFormSave")></span></div>;
                </div>
             <div class="BtFormCancel fRow"><input id="BtFormCancel" type="button" href="#"  value=(labels[loc].cancelButton;) /></div>
        </div>
      </form>
    </div>
    } else if (#errors > 0) {
      web.html("<ul>"..errors.."</ul>");
    }
    // ------------------------------ javascript -------------------------
    if (#errors == 0 && ispredit==true) {
    <script type="text/jem">"
    /* ---- variable definition --------- */
    var papiid='"..pp.api.."';
    var sapi='"..site.api.."';
    var siteuri = '"..site.uri.."';
    var pageuri =  '" .. string.escape(pp.uri) .. "';
    var titlefields = eval("..json.emit(titlefields)..");
    var titlejointstring = '"..titlejointstring.."';
    var requiredfields = eval("..json.emit(requiredfields)..");
    var issynctitle = "..issynctitle..";
    var iscreatepage = "..iscreatepage.." ;
    var newpagecontent = '"..newpagecontent.."';
    var newpagepath = '"..newpagepath.."';
    var datapage ='';
    var debug ="..debug..";
    var tagfields =eval("..json.emit(tagfields)..");
    var ptitle = '';
    var errors = 0;
    var tagInputId = '"..tagInputId.."';
    var pagetags = eval("..json.emit(map.keys(pp.tags))..");
    var prname = '"..prname.."';
    var mtbodyid = '"..mtbodyid.."';
    
    Deki.$(document).ready(function(){
      "..jsBtFormEdit.."
      CheckField(); /* on modified we may have requiref field already filled */
    
      Deki.$('#BtFormCancel').bind('click', function() {
              setTimeout('window.location.href = \"'+pageuri+'\"', 1);
      });
    
      Deki.$('#BtFormSave').bind('click', function()  {
              /* TODO: check if a page with the same proposed name exsists and advise user !! */
              writeView('');
              writeMessage('<p>"..labels[loc].msgOnSave.."</p>');
              #DivFormEdit.hide();
              var s = '';
              for ( var ii=0; ii < titlefields.length; ii++ ) {
                var t = $('#'+titlefields[ii]).val()+'';
                if (t.length > 0 && t!='undefined') {
                  ptitle +=s + t;
                  s = titlejointstring;
                }
              }
              var m = { };
              Deki.$('#' + {{@form}}).find('input,select,textarea').each(function() {
                var type = $(this).attr('type');
                var createonly = $(this).is('.createonly'); /*alert(this.name+' - '+createonly);*/
                if (!((type == 'radio' || type == 'checkbox') && !$(this).attr('checked')) &&
                    Deki.hasValue(this.name) && this.name != 'gmapInputAddress' && this.name != 'fpid' 
                    && this.name != 'fsid' && this.name != 'jqdateview' && !createonly ) m[this.name] = Deki.$(this).val();
                });
              if(iscreatepage) { /* we must encapsulate create page, create prop and update tag beacause ajax call are async */
                if (ptitle.length == 0) ptitle='Nuovo titolo pagina';
                puri = ptitle.replace(/[àáâãäå]/gi,'a');
                puri = puri.replace(/[èéêë]/gi,'e');
                puri = puri.replace(/[ìíîï]/gi,'i');
                puri = puri.replace(/[òóôõö]/gi,'o');
                puri = puri.replace(/[ùúûü]/gi,'u');
                puri = puri.replace(/[^a-zA-Z0-9-]/g,'_');
                puri = puri.replace(/_+$/g,'');
                puri = puri.replace(/^_+/g,'');
                var fpenc = encodeURIComponent(encodeURIComponent(newpagepath+'/'+puri));
                ptitle = encodeURIComponent(ptitle);
                puri = sapi + '/pages/='+ fpenc;
                var redirect = siteuri + fpenc+'?action=edit&isprsave=true&prname='+prname;
                if (mtbodyid.length > 0) newpagecontent +=$('#'+mtbodyid).val().replace(/\\n/g,'<br />');
                createNewPageAndUpdate(puri,ptitle, newpagecontent,m,tagInputId,redirect,tagfields, pagetags);
                pageRedirect(redirect);
              } else { 
                if (issynctitle && ptitle.length > 0) synctitle(papiid,encodeURIComponent(encodeURIComponent(ptitle)));
                if (tagInputId.length > 0) UpdatePageTags( papiid,tagInputId,tagfields, pagetags);
                FormUpdateProperty(papiid, m);
                pageRedirect(pageuri+'?isprsave=true&prname='+prname);
              }
      });
    
    
    }); // close document ready function
    
    /* ------------------------------------------
    // Read tags from input field, process and store in deki tags
    //
    */
    function UpdatePageTags( pageapi,idname,itagfields, ipagetags) {
      if (idname.length>0) {
      var tags = $('#'+idname).val();
      var postData = '<tags>';
      var tl ='';
      var ltags = tags.replace(/^\\s*|\s*$/g,'');
      /*ltags = ltags.replace(/\\s+/g,',');*/
      ltags = ltags.replace(/,+/g,',');
      ltags = ltags.replace(/;+/g,',');
      ltags = ltags.split(',');
      for (var j=0; j<itagfields.length; j++) {
        var t = itagfields[j].split('||');
        var v = $('#'+t[0]).val();
        var p = t[1]+v;
        if (ltags.indexOf(p)==-1) ltags.push(p);
      }
      /*TODO: if add site tags is impossible to delete them ltags = ltags.concat(ipagetags); */
      for (var j=0; j<ltags.length; j++) {
        /*if (ltags[j].substr(0,5) == 'date:' && ltags[j].substr(7,1) == '-'  && ltags[j].substr(10,1) == '-') {
          ltags[j]='date:'+ltags[j].substr(11,4)+'-'+ltags[j].substr(8,2)+'-'+ltags[j].substr(5,2);
        }*/
        if (ltags[j].length > 0)
        {
          postData += '<tag value=\\''+ltags[j]+'\\'   />';
          tl += ltags[j] + ', ';
        }
      }
      /*$(idname).val(tl);*/
      postData += '</tags>'; 
      MindTouch.Web.Put(pageapi+'/tags/?', postData, 'text/xml ; charset=utf-8', null, function(xhr) {
        if(MindTouch.Web.IsSuccessful(xhr)) {
          xhrOut(xhr,'"..labels[loc].msgAjaxOkTagUpdate.."');
        } else {
          xhrOut(xhr,'"..labels[loc].msgAjaxErrorTagUpdate.."');
        }
      });
    }
    }
    
    /* ------------------------------------------
    // Update page property
    //
    */
    function FormUpdateProperty(ipapi, m) {
      var prop = 'urn:custom.mindtouch.com#'  + prname;
      Deki.Api.ReadPageProperty(ipapi, prop, function(result) {
        var data = eval('(' + (result.value || '[]') + ')');
        /*data.push(m); //append data at end */
        var data = [m];
        if(result.etag) {
          MindTouch.Web.Put(ipapi+'/properties/'+encodeURIComponent(encodeURIComponent(prop)), YAHOO.lang.JSON.stringify(data), 'text/plain; charset=utf-8', { ETag: result.etag}, function(xhr) {
            if(MindTouch.Web.IsSuccessful(xhr)) {
              xhrOut(xhr,'"..labels[loc].msgAjaxOkPropertyUpdate.."');
            } else {
              xhrOut(xhr,'"..labels[loc].msgAjaxErrorPropertyUpdate.."');
            }    
          });
          } else {
            MindTouch.Web.Post(ipapi+'/properties', YAHOO.lang.JSON.stringify(data), 'text/plain; charset=utf-8', { Slug: prop }, function(xhr) {
            if(MindTouch.Web.IsSuccessful(xhr)) {
              xhrOut(xhr,'"..labels[loc].msgAjaxOkPropertyCreate.."');
            } else {
              xhrOut(xhr,'"..labels[loc].msgAjaxErrorPropertyCreate.."');
            }
          });
        }
      }, function(result) {
        xhrOut(result.xhr,'"..labels[loc].msgAjaxErrorPropertyRead.."');
      });
    }
    
    
    /* ------------------------------------------
    // update page title
    //
    */
    
    function synctitle(ipapi,ititle) {
      MindTouch.Deki.ReadPageContents(ipapi,{format:'xhtml', mode:'raw'}, function(result) {
          xhrOut(result.xhr,'"..labels[loc].msgAjaxOkPageRead.."');
          datapage=result.xhr.responseText;
          var patt = /<body[^>]*>([\\s\\S]*?)<\\/body>/i;
          var contents = datapage.match(patt);
          var cc = contents[1];
          ipapi += '/contents?edittime=' + "..Date.format( Date.Now, "yyyyMMddhhmmss" )..";
          if (ititle.length>0)
            ipapi += '&preservetitle=false&title='+ ititle;
          MindTouch.Web.Post(ipapi, cc, 'text/plain; charset=utf-8', null, function(xhr) {
          if(MindTouch.Web.IsSuccessful(xhr)) {
            xhrOut(xhr,'"..labels[loc].msgAjaxOkPageUpdate.."');
          } else {
            xhrOut(xhr,'"..labels[loc].msgAjaxErrorPageUpdate.."');
          }
      });
        }, function(result) {
          xhrOut(result.xhr,'"..labels[loc].msgAjaxErrorPageRead.."');
      });
    }
    
    /* ------------------------------------------
    // Create new page
    //
    */
    
    function createNewPageAndUpdate(ipapi, iptitle,  icontents, m, iTagInputId, ired, itagfields, ipagetags ) {	
      var tapi = ipapi+ '/contents?edittime=' + "..Date.format( Date.Now, "yyyyMMddhhmmss" ).."+'&abort=exists&title='+iptitle;
      if (icontents.length == 0) icontents ='<p></p>';
      MindTouch.Web.Post(tapi, icontents, 'text/plain; charset=utf-8', null, function(xhr) {
        if(MindTouch.Web.IsSuccessful(xhr)) {
          xhrOut(xhr,'"..labels[loc].msgAjaxOkPageCreate.."');
          FormUpdateProperty(ipapi, m,ired);
          if (iTagInputId.length > 0) UpdatePageTags( ipapi,iTagInputId, itagfields, ipagetags);
        } else {
          if(xhr.status == '409') { /*page exsists */
            xhrOut(xhr,'"..labels[loc].msgAjaxErrorPageCreate.."');
            writeView('"..labels[loc].msgPageExsists.."  <a href=\\''+ired+'\\'>"..labels[loc].msgGoto.."</a>');    
          } else {
            xhrOut(xhr,'"..labels[loc].msgAjaxErrorPageCreate.."');
          }
        }
      });
    }
    
    /* --------------------------------
    // Redirect to a page after some time
    //
    */
    
    function pageRedirect(url) {
      if (!debug) {
        setTimeout('window.location.href = \"'+url+'\"', 3000);
      }
      if (errors == 0) {
        writeView('"..labels[loc].msgOkSave.." <a href=\\''+url+'\\'>"..labels[loc].msgGoto.."</a>');      
      } else {
        writeView('"..labels[loc].msgErrorSave.." <a href=\\''+url+'\\'>"..labels[loc].msgGoto.."</a>'); 
      }
    }
    
    function xhrOut(xhr, msg) {
    var tag = 'p';
      if (debug) {
        msg += ' \\n\ReadyState:'+ xhr.readyState + '\\nStatus: ' + xhr.status + '\\nResponse text: '+ xhr.responseText + '\\nResponseXml: '+ xhr.responseXml + '\\nStatusText: ' + xhr.statusText ;
        tag = 'pre';
       }
       if(MindTouch.Web.IsSuccessful(xhr))
         writeMessage('<'+tag+'>'+msg+'</'+tag+'>');
       else {
         errors++;
         writeMessage('<'+tag+'>'+msg+'</'+tag+'>');
       }
    } function writeView(msg) {
       var div = '#FormStatus';
       $(div).html(msg);
    } function writeMessage(msg) {
       var div = '#FormMessages';
       var t = $(div).html();
       $(div).html(t+msg);
    } 
    function CheckField() {
      var fill = 0;
      for ( var ii=0; ii < requiredfields.length; ii++ ) {
        if (($('#'+requiredfields[ii]).val()).length > 0) fill ++;
      }
      if (fill == requiredfields.length) {
        Deki.$('#BtFormSave').removeAttr('disabled');
        $('#fInfoBtFormSave').html('');
      } else {
        Deki.$('#BtFormSave').attr('disabled','disabled');
        $('#fInfoBtFormSave').html('"..labels[loc].msgFieldSaveRequired.." '+requiredfields.join(', '));
      } 
    }
    function limitChars($this, limit, infodiv,im) {
      var text = $this.val(); var textlength = text.length+1;
      if(textlength == 0) {
        $('#' + infodiv).html(im);   return true;
      } else if(textlength > limit) {
        $('#' + infodiv).html('"..labels[loc].msgFieldCharsFull.."'+limit);
        $this.val(text.substr(0,limit));
        return false;
      } else {
        $('#' + infodiv).html('"..labels[loc].msgFieldCharsCount.."'+ (limit - textlength));   return true;
      }
    }"</script>}
    

    Files (0)

     

    Comments (0)

    You must login to post a comment.