/*++++++++++++++++++++++++++++++++++
 *
 * Implementation of Mootools JSON Request Object:
 *
 * Customised for DSPM application:
 *
 **/

/* method to restart app... */
AppRestart = function(){document.location.reload();}

/* Mootools  - JSON Request Object Implementation */
JSONRequest = function(xurl, xact, xdata, xwin, xtype){
    xtype = $pick(xtype,'send');
    xtype = xtype.toLowerCase();
    
    var e = xl_event();
    if(e) new Event(e).stop();
    if(xact){ //process/append action arg to URL:
        if(xurl.indexOf('php?')!==-1){ // has other args
            xurl+="&arg="+xact; //other url args
        }else{ // no args
            xurl+="?arg="+xact; // only url arg
        }
    }    
   switch(xtype){
        case 'postform': // HTML form element posting
            var R = new Request.JSON({
                url: MUI_XHR+xurl, data:{json: JSON.encode(xdata)},
                onSuccess: function(XHR,RX){MUIRequestSuccess(XHR,RX,xwin);},
                onFailure: function(XHR,RX){MUIRequestFailure(xact,XHR,RX);}
            });
            R.post(xdata); // xdata is HTML form element;
        break;
        case 'postdata': // send name-value pairs string as post data            
           var R = new Request.JSON({
                method:'post', url: MUI_XHR+xurl,
                onSuccess: function(XHR,RX){MUIRequestSuccess(XHR,RX,xwin);},
                onFailure: function(XHR,RX){MUIRequestFailure(xact,XHR,RX);}               
           }).send(xdata);
        break;
        case 'send': // JSON data sending...
            var R = new Request.JSON({
                url: MUI_XHR+xurl, data:{json: JSON.encode(xdata)},
                onSuccess: function(XHR,RX){MUIRequestSuccess(XHR,RX,xwin);},
                onFailure: function(XHR,RX){MUIRequestFailure(xact,XHR,RX);}
            });
            R.send();
        break;
        case 'get':
            var R = new Request.JSON({
                url: MUI_XHR+xurl, data:{json: JSON.encode(xdata)},
                onSuccess: function(XHR,RX){MUIRequestSuccess(XHR,RX,xwin);},
                onFailure: function(XHR,RX){MUIRequestFailure(xact,XHR,RX);}
            });
            R.get();
        break;   
        default:
            xhrNotifyError('The request ['+xact+'] failed. JSONRequest::XTYPE not could not be parsed<BR/><BR/>'+XHR.responseText,200,500);
   }
}

MUIRequestSuccess = function(XHR,RX,xwin){
    xhrDebugOutput(XHR,RX);
    if(xwin) $(xwin).retrieve('instance').close(); // close the window before processing
    if(XHR.EvalScripts) xhrJSONProcessEvalScripts(XHR.EvalScripts);
    if(XHR.Windows)  MUI.newWindowsFromJSON(XHR.Windows); // process any json windows requests
    xhrJSONProcessEvents(XHR.AddEvents); // process any event add requests
    if(XHR.NotifyClient) xhrNotifyClient(XHR.NotifyClient,XHR.NotifyClientWinHeight,XHR.NotifyClientWinWidth); // process any client notification requests
    if(XHR.NotifyError) xhrNotifyError(XHR.NotifyError,XHR.NotifyErrorWinHeight,XHR.NotifyErrorWinWidth); // process any client notification requests    
}
MUIRequestFailure = function(xact,XHR,RX){
    xhrNotifyError('The request ['+xact+'] failed. Please check your internet connection is connected and try again.<BR/><BR/>'+XHR.responseText,200,500);
}
/* MochaUI  - Debug Output Window */
var DebugLog= false;
xhrDebugOutput = function(XHR,RX){
    if(!XHR) alert('Server-side Error Detected:\n\n'+RX);
    if(XHR.DebugOutput){
        if(!DebugLog){
            DebugLog = new MUI.Window({
                id:'DebugLog', title:'Debug Logs', content: '<textarea class="DebugEntry">'+unescape(RX)+'</textarea>',
                storeOnClose:true, height: 200, width:300, x:0, y:0
            });
            $('DebugLog').retrieve('instance').minimize();
        }else{
            MUI.updateContent({
                element: $('DebugLog'),
                content: '<textarea class="DebugEntry">'+unescape(RX)+'</textarea>'
            });
            $('DebugLog').retrieve('instance').minimize();
        }
    }
}
xhrJSONSetHTML = function(elID,encHTML,stepToParent){
    var el = $(elID);
    try{
        if(stepToParent) el = el.parentNode;
        //el.set('html',unescape(encHTML)); // ie doesn't like this
        el.innerHTML = unescape(encHTML);
    }catch(e){
        alert("JSON HTML Set:\n\nID:"+elID+"\n\n"+e.message);
    }
}

var eSBX;
xhrJSONProcessEvents = function(xhrEvents){
    // some auto-event assignments:
    // dialog cancel button, if exists...
    var z = document.body.getElements('.DLG_CancelBtn');
    if(z.length > 0){
        var pz = z[0];
        while(pz.tagName!=="DIV" || pz.className.indexOf("mocha ")==-1) pz = pz.parentNode;
        z.addEvent('click', function(){
            //MUI.closeWindow(pz);
            try{
                if(eSBX){eSBX.selectedIndex = eSBX.initSlctIdx;}
            }catch(e){
                //do nothing
            }
        });
    }
    
    // any custom event assignments:
    if(xhrEvents){
        for(i=0;i< xhrEvents.length;i++){
            var eD = xhrEvents[i];
            p = (eD.ParentID) ? $(eD.ParentID) : document ;
            if(!p){
                alert("JSON Request Processing Failure:\nAdd Event [parent ID not found in document]\nElement ID: "+eD.ParentID);
                return;
            }
            elems = (eD.Selector) ? p.getElements(eD.Selector): p;
            elems.addEvent(eD.EventType,function(){xhrEvalCmd(eD.Method,'SERVER-JSON-EVENT');});
        }
    }
}
xhrJSONProcessEvalScripts = function(xhrEvalScripts){
    for(i=0;i< xhrEvalScripts.length;i++){
        xhrEvalCmd(xhrEvalScripts[i],'SERVER-EVAL-REQUEST');
    }
}
xhrEvalCmd = function(cmd,src){
    try{eval(cmd);}catch(e){
        alert("xhrEvalCmd failed:\n\n"+cmd+"\n\nSource:"+src+"\n\nError:"+e.message);
    }
}
var CNoteWin;
xhrNotifyClient = function(msg,wh,ww){
    ww = $pick(ww, 400);
    wh = $pick(wh, 50);    
    msg = '<div style="text-align:center">'+msg+'</div>';
    if(CNoteWin) CNoteWin.close();
    CNoteWin = new MUI.Window({
        title: 'Application Says...', id:'ClientNotify', content:msg, addClass:'ClientNotify', 
        width:ww, height:wh, maximizable:false, minimizable:false, resizable:false
    });
}
var CErrorWin;
xhrNotifyError = function(msg,wh,ww){ 
    ww = $pick(ww, 400);
    wh = $pick(wh, 80);
    msg = '<div style="text-align:center">'+msg+'</div>';
    if(CErrorWin) CErrorWin.close();
    CErrorWin = new MUI.Window({ // build window
        title: 'Error Notification',id:'ErrorNotify',content: msg, addClass:'ErrorNotify',
        width: ww, height:wh, maximizable:false, minimizable:false, resizable:false
    });
}
xhrConfirmClient = function(msg,execfunc){
    ConfWin = new MUI.Window({ // build window
        title: 'Please Confirm Operation...',
        id:'ConfirmClient',
        type: 'modal',
        modalOverlayClose: false,
        contentURL:_vars._get('DIR_INTFCS')+'control.dialog.confirm.phtml?msg='+escape(msg), 
        addClass:'ConfirmClient',
        width: 400, height:90, maximizable:false, minimizable:false, resizable:false,
        require:{
            onload: function(){
                $('_ConfCancel').addEvent('click',function(e){$('ConfirmClient').retrieve("instance").close();});
                $('_ConfGo').addEvent('click',function(e){
                    $('ConfirmClient').retrieve("instance").showSpinner();
                    xhrEvalCmd(eval(unescape(execfunc)),'CONFIRM DIALOG');                    
                });
            }
        }
    });
}
xhrProjectEditLockUpdate = function(argPjLdID){
    // first check edit form exists, else terminate periodical:
    if(document.forms.ProjectLead){ // run update...
        var PjLdFrm = document.forms.ProjectLead;
        var PjLdID = parseInt(PjLdFrm.pj_ld.value);
        if(argPjLdID == PjLdID) JSONRequest('xhr.project.lead.edit.lock.php','project.lead.edit.lock','pj_ld='+PjLdID,null,'postdata');
    }else{ //terminate periodical
        clearInterval(ProjectEditLockUpdate);
    }
}
ControlButtonEnable = function(id,exec,title){
    $(id).removeEvents();
    $(id).addEvent('click',function(e){xhrEvalCmd(exec,'CONTROL-BUTTON')});
    if(title) $(id).value=TITLE;
    $(id).disabled = false;
}
ControlButtonDisable = function(id){
    
    $(id).disabled = true;
    $(id).removeEvents();
}
ControlButtonsReset = function(){
    $('CntlBtnSave').disabled = true;
    $('CntlBtnSave').value = 'SAVE';
    $('CntlBtnSave').removeEvents();
    $('CntlBtnEmail').disabled = true;
    $('CntlBtnEmail').value = 'EMAIL';
    $('CntlBtnEmail').removeEvents();
    $('CntlBtnDelete').disabled = true;
    $('CntlBtnDelete').value = 'DELETE';
    $('CntlBtnDelete').removeEvents();
    $('CntlBtnEdit').disabled = true;
    $('CntlBtnEdit').value = 'EDIT';
    $('CntlBtnEdit').removeEvents();
}
/*++++++++++++++++++++++++++++++++++
 *
 * Utility to get all properties/values of an object:
 *
 **/
function AllProps(obj,lnbrk,stripIDs,preTags){
    if(lnbrk==undefined) lnbrk = '\n';
    if(preTags==undefined) preTags = true;
    var s = '';
    var v;
    for(i in obj){
        if(i=='channel') continue;
        if(s!=='') s += lnbrk;
        v = obj[i];
        if(obj[i] && obj[i].length > 0){
            // to stop the console code messing with DOM ID refs:
            if(stripIDs && v.indexOf) while(v.indexOf('id=') !== -1) v = v.replace('id=','xd=');
        }
        if(preTags){
            s += i+': <pre>'+v+'</pre>';
        }else{
            s += i+': '+v;
        }
    }
    return(s);
}
function Trim(val){
    if(val.length < 1)	return "";
    val = RTrim(val);
    val = LTrim(val);
    if(val==""){return "";}else{return val;}
}//End Function
function RTrim(val){
    var w_space = String.fromCharCode(32);
    var v_length = val.length;
    var strTemp = "";
    if(v_length < 0)	return"";
    var iTemp = v_length -1;
    while(iTemp > -1){
        if(val.charAt(iTemp) !== w_space){
            strTemp = val.substring(0,iTemp +1);
            break;
        }
        iTemp = iTemp-1;
    } //End While
    return strTemp;
} //End Function
function LTrim(val){
    var w_space = String.fromCharCode(32);
    if(v_length < 1)	return "";
    var v_length = val.length;
    var strTemp = "";	
    var iTemp = 0;
    while(iTemp < v_length){
        if(val.charAt(iTemp) !== w_space){
            strTemp = val.substring(iTemp,v_length);
            break;
        }
        iTemp = iTemp + 1;
    } //End While
    return strTemp;
} //End Function


/*++++++++++++++++++++++++++++++++++
 *
 * Shortcuts to get client PC date and time:
 *
 **/
GetTheTime = function(){
    var d = new Date();
    var h = new String(d.getHours());
    var m = new String(d.getMinutes());
    var s = new String(d.getSeconds());
    if(h.length==1) h = '0'+h;
    if(m.length==1) m = '0'+m;
    if(s.length==1) s = '0'+s;
    return(h+":"+m+":"+s);
}
GetTheDate = function(){
    var d = new Date();
    var m = new String(d.getMonth()+1);
    if(m.length==1) m = '0'+m;
    return(d.getFullYear()+"-"+m+"-"+d.getDate());
}
/*++++++++++++++++++++++++++++++++++
 *
 * Currency formatter for Mootools native Number
 *
 **/
Number.implement({
format: function(kSep, floatsep, decimals){
decimals = $pick(decimals, 2);
floatsep = $pick(floatsep, '.');
kSep = $pick(kSep, ' ');

var parts = this.round(decimals).toString().split('.');
var integer = parts[0];
while (integer != (integer = integer.replace(/([0-9])(...($|[^0-9]))/, '$1' + kSep + '$2')));
if (decimals == 0) return integer;
return integer + floatsep + ((parts[1] || '') + '0000000000').substr(0, decimals);
}
});

// Generic functions for form list boxes, ties up to a XHR server-side processor:
SBXEventsSet = function(parentID,reload){
    // REFERENCE FORM:
   // var PjLdFrm = document.forms.ProjectLead;
    // LIST BOXES CONTROLS:
    var parentBox = $(parentID); //'ProjectLeadBox'
    var lstBxs = parentBox.getElements('SELECT[ref="NewOpt"]');

    //CLEAR EVENTS:
    lstBxs.removeEvents();
    // APPLY EVENTS:
    lstBxs.addEvent('change',function(e){
        SBXOnChangeEvent(e,parentID);
    });
    // custom for document type:
    if($('sbx_pj_ld_dctp'))
       $('sbx_pj_ld_dctp').addEvent('change',function(e){
        SBXOnChangeEvent(e,parentID);
    });
    if(!reload)lstBxs.each(function(e){e.initSlctIdx = parseInt(e.selectedIndex);});
}
function SBXOnChangeEvent(e,parentID){    
    eSBX = e.target;
    $("_SBXOptID").value = eSBX.id;
    $("_SBXOptVAL").value = eSBX.value;
    
    var frmname = eSBX.form.name;
    
    // capture the form's dom id prefix if defined:
    var domidprefix = 0;
    if(eSBX.form.DomIDPrefix) domidprefix = eSBX.form.DomIDPrefix.value;
    
    var urlargs = '?SBXType='+eSBX.id;
    urlargs += '&SBXFormName='+frmname;
    urlargs += '&SBXDomParentID='+parentID;
    urlargs += '&DomIDPrefix='+domidprefix;
    urlargs += '&SBXOptVAL='+eSBX.value;
    
    if(eSBX.value.indexOf('lb_add')!==-1){
        JSONRequest( // NEW LISTBOX OPTION:
          'xhr.listbox.controller.php'+urlargs,'sbx.new.option.dialogue',eSBX.form,null,'postform');
    }else{
        JSONRequest( // LISTBOX TO LISTBOX FILTERS:
          'xhr.listbox.controller.php'+urlargs,'sbx.filter.options',eSBX.form,null,'postform');
    }
}

/* Generic Window Calls: */
ProfessionalContactWindow = function(prfid,nme,snme,pjld){
    prfid =parseInt($pick(prfid, 0));
    var utitle = 'New Professional Contact'
    if(prfid>0) var utitle = "Edit Professional Contact: "+nme+" "+snme;
    new MUI.Window({
        id: 'WinProfCntctFrm',
        title: utitle ,
        loadMethod:'xhr',
        contentURL: MUI_VIEWS+'view.project.lead.professional.php?prof_cntct='+prfid+'&pj_ld='+pjld,
        width: 710,
        height: 410,
        padding: {top: 8, right: 0, bottom: 0, left: 0},
        require: {
            css: [MUI_CSS+'ui.professional.contact.css'],
            js: [MUI_MEIO+'Meio.Mask.js'],                
            onload: function(e){
                SBXEventsSet('_PjLd_Professional',true);
                var ProfFrm = $('_PjLd_Professional');
                // form submit
                ProfFrm.addEvent('submit',function(e){
                    new Event(e).stop(); // cancel default submit action...
                    JSONRequest("xhr.form.project.lead.professional.php","project.lead.professional.store",ProfFrm,null,"postform");
                });
                // input masking, as needed:
                //$('_ProfTelephone').meiomask('fixed.phone-us');
                //$('_ProfFax').meiomask('fixed.phone-us');
                //$('_ProfMobile').meiomask('fixed.mobile');
            }
            //PROJECT LEAD DOC CONTROLS:
            //PjLd_DocCntrlSetEvents(PjLdID);
            //}
        }
    });
}
ProjectLeadNoteWindow = function(PjLdID,PjLdNtID){
    var utitle = 'New Project Lead Note';
    if(PjLdNtID && parseInt(PjLdNtID)>0) utitle = "Edit Project Lead Note";
    new MUI.Window({
        id: 'WinPjLdNote',
        title: utitle,
        loadMethod:'xhr',
        contentURL: MUI_VIEWS+'view.project.lead.note.php?pj_ld='+PjLdID+'&pjld_nt='+PjLdNtID,
        width: 500,
        height: 350,
        resizable: false,
        maximizable: false,                  
        padding: {top:8,right:0,bottom:0,left:0},
        require: {
            onload: function(){
                PjLd_NotesCntrlSetEvents();
            }
        }
    });
}

ProjectLeadWindow = function(PjLdID,PjLdCode){
    MUI.updateContent({
        element: $('mainPanel'),
        url: '/view/view.project.lead.php?pj_ld='+PjLdID+'&view=edit',
        title: 'Edit Project Lead: '+PjLdCode,
        padding: {top: 8, right: 8, bottom: 8, left: 8},
        require: {
            css: [MUI_CSS+'ui.project.lead.css'],
            js: [MUI_JS + 'form.project.lead.js'],
            onload:function(e){PjLd_FormEvents();}
        }            
    });     
}
