// JavaScript Document

var statusWin;
var statusField;
var staffNotes;
var notesWin;
var sidebarWin;
var customfilterwin;
var helpContent;
var wikistore;
var hasAudio = !!(document.createElement('audio').canPlayType);

Ext.BLANK_IMAGE_URL = '../javascript/ext/images/gray/s.gif';
//fix for issue with Extjs
Ext.lib.Event.resolveTextNode = Ext.isGecko ? function(node)
{
    if(!node)
    {
        return;
    }
    var s = HTMLElement.prototype.toString.call(node);
    if(s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]')
    {
        return;
    }
    return node.nodeType == 3 ? node.parentNode : node;
} : function(node){
    return node && node.nodeType == 3 ? node.parentNode : node;
};

//fixes grids so that they can be selectable
if (!Ext.grid.GridView.prototype.templates) {
    Ext.grid.GridView.prototype.templates = {};
}
Ext.grid.GridView.prototype.templates.cell = new Ext.Template(
    '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>',
    '<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>',
    '</td>'
);
//end fix

//add override for store exceptions
Ext.data.DataProxy.on('exception', function(proxy, type, action, o, response, mixed) {
    if (action == 'read') {
        var res = Ext.util.JSON.decode(response.responseText);
        if(res.success === false){
            ce.parseAjaxResponse(response);
        }
    }
});

/* start defining CE class */
function CE ()
{
   
}

/**
* Displays the greeting message
* 
* @param {Int} level Error level.
* @param {String} ex String message to log.
*/
CE.prototype.log = function(level,ex) {
    if(console!=undefined) console.log(level,ex);
}

/**
 * Used by ajax request success functions to determine if it should display error
 *
 * @param {String} response Raw Ajax Request response.
 * @param {Bool} display Show alert box with error.
 * @param {String} msg If message is not passed with error then use the passed string.
 * @return {Bool} Returns if there was an error or not
 */
CE.prototype.parseAjaxResponse = function(response, display, msg) {
    var jsonData;
    if (display == undefined) {display = true;}

    try {
        jsonData = Ext.decode(response.responseText);
        if (typeof(jsonData.error) != "undefined" && jsonData.error) {
            if ((jsonData.message != "") && display) {
                Ext.MessageBox.alert(lang("Errors"), jsonData.message);
            } else if (display) {
                var error = "There was an error performing this action";
                if (msg != undefined) {
                    error = msg;
                }
                Ext.MessageBox.alert(lang("Errors"), error);
            }
        } else if (typeof(jsonData.error) == "undefined") {
            //possible error where we areg getting back valid json
            //but not send via action Send return the jsonData but raise error
            Ext.MessageBox.alert(lang("Errors"), "Data returned is old json data");
        }else {
            //no errors maybe msgbox
            if ((jsonData.message != "") && display) {
                this.msg(jsonData.message, '');
            }
        }
    } catch(e) {
        jsonData=new Object();
        jsonData.error = true;
        jsonData.message = "Data returned is not valid json<br/>"+e.toString()+'<br />'+response.responseText;
        if (display) {
            Ext.MessageBox.alert(lang("Errors"), jsonData.message);
        }
    }

    return jsonData;
    
}


CE.prototype.msg = function(title, format){
        if(!msgCt){
            msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
        }
        //msgCt.alignTo(document, 'tr-tr?');
        var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
        var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
        m.slideIn('t').pause(4).ghost("t", {remove:true});
}

//create our site util js class
var ce = new CE();

function showNotes(){
    staffNotes.reset();
    notesWin.show();

    Ext.Ajax.request({
       url: 'index.php?fuse=admin&action=GetStaffNote',
       success: function(xhr) {
                    notesWin.setTitle(lang("My Notes"));
                    var data = Ext.decode(xhr.responseText);
                    $('ce-staffnotes').value = data.staffnote;
                },
       failure: function() {
            Ext.Msg.alert("Fail");
       },
       params: {foo: 'bar'}
    });

    notesWin.buttons[0].setDisabled(false);
    staffNotes.focus();
}

function getWikiAvailability(){

   // Set a timer to delay the call
   setTimeout("callWikiAvailble()", 2000);
}

function callWikiAvailble() {

   var currentPage = gFuse.toLowerCase()+"_"+gView.toLowerCase();
   Ext.Ajax.request({
       url: 'index.php?fuse=admin&action=IsWikiPageAvailable',
       success: function(xhr) {
            var data = Ext.decode(xhr.responseText);
            if(data.pageid != null){
                document.getElementById("headinglabelhelp").style.display="";
            }else{
                document.getElementById("headinglabelhelp").style.display="none";
            }
       },
       failure: function() {
            document.getElementById("headinglabelhelp").style.display="none";
       },
       params: {currentPage : currentPage}
    });
}

function html_entity_decode(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}

function createNewFilter(){
    //show custom filter window
    if(!customfilterwin){
        customfilterwin = new Ext.Window({
            el:'customfilter-win',
            layout:'fit',
            width:600,
            shadow:false,
            autoHeight:true,
            contentEl:"filtercontent",
            closeAction:'hide',
            plain: true
        });
    }
    customfilterwin.show(this);
}

function moveGuestToCustomer(id,fuse,action){
     oldurl = window.location.href;

     //need to see if we are in tickets
     var aPosition = oldurl.indexOf("frmClientID=");
     if(aPosition > -1){
        newurl = oldurl.substring(0,aPosition);
     }else{
         newurl = oldurl+"&";
     }
     $(id).innerHTML = lang("Migrate to user ID:") + "<form style='display:inline;padding-left:27px;' method='post' action='index.php?fuse="+ fuse +"&action=" + action + "'><input type='hidden' name='oldurl' value='"+newurl+"' /><input type='text' size='10' name='userId' value='' /> <input style='position:relative;top:-2px;' type='submit' value='" + lang("go") + "' class='button_small' onclick='return confirmChangeOwnership();' /></form>";
     //$('userid').focus();
}

function showSideBarSettings(){
    sidebarWin.show();
    Ext.Ajax.request({
       url: 'index.php?fuse=admin&action=GetSearializedCustomField',
       success: function(xhr) {
                    //notesWin.setTitle(lang("My Notes"));
                    var data = Ext.decode(xhr.responseText);
                    if(data.showdropdownlist!=null){
                        Ext.getCmp('showdropdownlist').setValue(data.showdropdownlist);
                    }
                    if(data.showsupportticketlinks!=null){
                        Ext.getCmp('showsupportticketlinks').setValue(data.showsupportticketlinks);
                    }
                    if(data.showonlinecustomers!=null){
                        Ext.getCmp('showonlinecustomers').setValue(data.showonlinecustomers);
                    }
                },
       failure: function() {
            Ext.Msg.alert("Fail");
       },
       params: {type: 'SidebarState'}
    });


    sidebarWin.buttons[0].setDisabled(false);
}

function updateSideBarSettings(){
    Ext.Ajax.request({
       url: 'index.php?fuse=admin&action=updateSideBarSettings',
       success: function(xhr) {
                msg('Settings Update Successfully','');
                },
       failure: function() {
            Ext.Msg.alert("Fail");
       },
       params: {showdropdownlist: Ext.getCmp('showdropdownlist').getValue(),
                 showsupportticketlinks: Ext.getCmp('showsupportticketlinks').getValue(),
                 showonlinecustomers: Ext.getCmp('showonlinecustomers').getValue()
                 },
       method:'post'
    });

    sidebarWin.buttons[0].setDisabled(true);
    sidebarWin.hide();
}

function updateNotes(){
    Ext.Ajax.request({
       url: 'index.php?fuse=clients&action=updateNote',
       success: function(xhr) {
                },
       failure: function() {
            Ext.Msg.alert("Fail");
       },
       params: {notes: staffNotes.getValue()},
       method:'post'
    });

    notesWin.setTitle(lang("My Notes - loading..."));
    notesWin.buttons[0].setDisabled(true);
    notesWin.hide();
}

function addTeamStatus(){
    statusField.reset();
    statusWin.show();
    statusField.focus(); // for some reason the focus get lost
}

function sendTeamStatus(){
    if(statusField.getValue() !== ""){
        Ext.Ajax.request({
           url: 'index.php?fuse=home&action=SaveTeamStatus',
           success: function(xhr) {
                        if(pollStatus != undefined){
                            pollStatus.disconnect();
                            pollStatus.connect();
                        }
                    },
           failure: function() {
                Ext.Msg.alert("Fail");
           },
           params: {message: statusField.getValue()},
           method:'post'
        });
    }
    statusWin.hide();
}


//need to convert to msg
var msgCt;
function setStatus(s, time) { }
function resetStatus(s) {}
function unsetStatus(s, time) {}
function createBox(t){
    return ['<div class="msg" style="height: auto; position:fixed; top:0px; right:30px;">',
            '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
            '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">', t, '</div></div></div>',
            '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
            '</div>'].join('');
}
function msg(title, format){
        if(!msgCt){
            msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
        }
        //msgCt.alignTo(document, 'tr-tr?');
        var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
        var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
        m.slideIn('t').pause(4).ghost("t", {remove:true});
}
// End msg windows

Ext.onReady(function(){
    var advancedsearchwin;
	advancedsearchlink = Ext.get($('searchsubmit').id);
	
	advancedsearchlink.on('click', function(){
		winx = $('searchsubmit').offsetParent.offsetLeft -110;
		if(!advancedsearchwin){
			advancedsearchwin = new Ext.Window({
				el:'advancedsearch-win',
				layout:'fit',
				width:280,
				height:220,
				y:116,
				x:winx,
				contentEl:"advancedsearchcontent",
				closeAction:'hide',
				plain: true
			});
		}
		advancedsearchwin.show(this);
	});
	
	var searchquerytooltip = new Ext.ToolTip({
            target: 'searchquerytextfield',
            anchor: 'top',
                    autoHide: true,
                    dismissDelay:3500,
            anchorOffset: 1, // center the anchor on the tooltip
            html: lang('Search by name, organization, last 4 cc, e-mail, domain, user id, ticket id or invoice id')
        });
	Ext.QuickTips.init();

    var ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
			url: 'index.php?fuse=admin&action=GetSearchResults'
		}),
		
        reader: new Ext.data.JsonReader({
            root: 'results',
            totalProperty: 'totalcount',
            id: 'id'
        }, [
            {name: 'name'},
            {name: 'type'},
            {name: 'tooltip'},
            {name: 'match'},
            {name: 'url'}
        ])
    });

    // Custom rendering Template
    var resultTpl = new Ext.XTemplate(
        '<tpl for="."><div class="search-item" qtip="{tooltip}">',
            '<h3><span>{type}</span>{name}</h3>',
            '{match}',
        '</div></tpl>'

    );
    
    var search = new Ext.form.ComboBox({
        store: ds,
        typeAhead: false,
        loadingText: lang('Searching')+'...',
        width: 150,
		height:5,
		minChars:3,
		handleHeight:5,
        pageSize:10,
		listWidth:300,
		listClass: 'searchresultlist',
		autoHeight:false,
		y:-1,
        hideTrigger:true,
        tpl: resultTpl,
        applyTo: 'searchquerytextfield',
        itemSelector: 'div.search-item',
        onSelect: function(record){ // override default onSelect to do redirect
            window.location =
                String.format('{0}', record.data.url);
        }
    });

    // users dropdown list
    var allclientsstore = new Ext.data.JsonStore({
            id: "allclientsstore",
            root: 'clients',
            totalProperty: 'totalcount',
            idProperty: 'id',
            remoteSort: true,
            fields: [
                    'id','firstname','lastname', 'email','dateactivated','status','statusname','clienttype','clienttypename','clienttypebgcolor'
            ],

            // load using script tags for cross domain, if the data in on the same domain as
            // this page, an HttpProxy would be better
            proxy: new Ext.data.HttpProxy({
                    url: 'index.php?fuse=clients&action=GetClientList&comma=yes&onlyactiveinactive=yes'
            })
    });
    allclientsstore.setDefaultSort('lastname', 'asc');

    if(showCustomerDropdown){
        $('remote-users').style.display='';
        var customerDropDownWithTooltip = new Ext.form.ComboBox({
            tpl: '<tpl for="."><div ext:qtip="id: {id}<br/>e-mail: {email}<br/>status: {statusname}<br/>type: {clienttypename}" class="x-combo-list-item">{firstname} {lastname}</div></tpl>',
            store: allclientsstore,
            mode: 'remote',
            lazyRender: false,
            editable:false,
            triggerAction: 'all',
            selectOnFocus:true,
            applyTo: 'remote-users',
            onSelect: function(record){
                window.location = String.format('index.php?fuse=clients&view=Admin_Profile_Contact&frmClientID={0}', record.data.id);
            }
        });
        customerDropDownWithTooltip.setValue(lang('Select a customer')+' ...');
        //allclientsstore.load();
    }

    //staff notes
    staffNotes = new Ext.form.TextArea({
            id:         "ce-staffnotes",
            border:     false,
            hideLabel:  true,
            anchor:     '100%',
            height:227,
            width:480,
            name:       'ce-staffnotes'
    });

    notesWin = new Ext.Window({
        id: "notesWindow",
        width: 500,
        height:300,
        closeAction: 'hide',
        plain: true,
        title: lang("My Notes - loading..."),

        items : staffNotes,

        buttons: [{
            text : 'Update',
            disabled:true,
            handler:function(){
                updateNotes();
            }
        },{
            text: 'Close',
            handler:function(){
                notesWin.setTitle(lang("My Notes - loading..."));
                notesWin.buttons[0].setDisabled(true);
                notesWin.hide();
            }
        }]
    });

    sidebarWin = new Ext.Window({
       id: "sidebarWindow",
       width: 340,
       height: 160,
       closeAction: 'hide',
       plain: true,
       defaultType: 'checkbox',
       bodyStyle: 'padding-left:8px;padding-top:5px;',
       items:[{
          id: 'showdropdownlist',
          boxLabel:'Show customer dropdown list',
          checked: true
       },{
          id: 'showsupportticketlinks',
          boxLabel:'Show support ticket links',
          checked: true
       },{
          id: 'showonlinecustomers',
          boxLabel:'Show last seen',
          checked: true
       }
       ],
       title : "Sidebar Settings",
       buttons:[{
            text : 'Update',
            disabled:true,
            handler:function(){
                updateSideBarSettings();
            }
        },{
            text: 'Close',
            handler:function(){
                sidebarWin.buttons[0].setDisabled(true);
                sidebarWin.hide();
            }
       }]

    });

    //status window
    statusField = new Ext.form.TextArea({
        id:         "statusfield",
        border:     false,
        hideLabel:  true,
        anchor:     '100%',
        grow:       true,
        name:       'statusfield'
    });

    statusWin = new Ext.Window({
        id:           "statusWindow",
        x:            400,
        y:            200,
        labelAlign:   'right',
        layout:       'form',
        width:        400,
        autoHeight: true,
        defaultType:  'textfield',
        closeAction:  'hide',
        title:        lang("Your status:"),
        plain:        true,
        closable:     true,
        buttonAlign:  'right',
        items:        [
                          statusField
                      ],
        buttons:      [
                          {
                              id:       'btnAddStatus',
                              text:     lang("Add Status"),
                              disabled: false,
                              hidden:   false,
                              handler:  function(){
                                            sendTeamStatus();
                              }
                          }
                      ]
    });

});

function loadHelp()
{
    var helpurl = 'index.php?fuse=admin&view=Admin_ContextHelp&contextkey='+gFuse.toLowerCase()+"_"+gView.toLowerCase();
    var contextpanel = new Ext.Panel({
        region: 'center',
        autoLoad: {url: helpurl, scripts: true},
        autoScroll: true
    });

    var win = new Ext.Window({
        id          : 'contextHelp',
        title       : lang('Context Help'),
        layout      : 'border',
        width       : 450,
        height      : 400,
        closeable   : true,
        minimizable : false,
        plain       : true,
        items       : contextpanel
    });

    win.show();

}

function HideShowAndUpdateCustomField(which,imgid,customfieldname){

    style = "";
    if (!document.getElementById)  return false;
    if (which.style.display=="none"){
        which.style.display="";
        if(document.images[imgid] != null){
                document.images[imgid].src= relativePath + "images/collapse.gif";
        }
    }else{
        style = "none";
        which.style.display="none";
        if(document.images[imgid] != null){
                document.images[imgid].src= relativePath + "images/expand.gif";
        }
    }

    Ext.Ajax.request({
       url: "index.php?fuse=clients&action=Admin_SaveCustomField",
       success: function(xhr) {
            var data = Ext.util.JSON.decode(xhr.responseText);
            if(data.error){
                //we do not need to repopulate the filters if there was a validation error
               msg(lang("There was an error when updating your custom field"),"");
            }
        },
       failure: function() {
            Ext.Msg.alert("Fail");
       },
       params: {newvalue: style, customfieldname: customfieldname}
    });


    return style;
}

function toggleTicketParent(id,customfieldname){

    style = "";

    if($(id+'_options').style.display == "none"){
        $(id+'_options').style.display = "";
        $(id).className = "toggleopen";
    }else{
        style = "none";
        $(id+'_options').style.display = "none";
        $(id).className = "toggle";
    }

    Ext.Ajax.request({
       url: "index.php?fuse=clients&action=Admin_SaveCustomField",
       success: function(xhr) {
            var data = Ext.util.JSON.decode(xhr.responseText);
            if(data.error){
                //we do not need to repopulate the filters if there was a validation error
               msg(lang("There was an error when updating your custom field"),"");
            }
        },
       failure: function() {
            Ext.Msg.alert("Fail");
       },
       params: {newvalue: style, customfieldname: customfieldname}
    });

}

//http://wonko.com/post/lazyload-200-released
LazyLoad=function(){var f=document,g,b={},e={css:[],js:[]},a;function j(l,k){var m=f.createElement(l),d;for(d in k){if(k.hasOwnProperty(d)){m.setAttribute(d,k[d])}}return m}function h(d){var l=b[d];if(!l){return}var m=l.callback,k=l.urls;k.shift();if(!k.length){if(m){m.call(l.scope||window,l.obj)}b[d]=null;if(e[d].length){i(d)}}}function c(){if(a){return}var k=navigator.userAgent,l=parseFloat,d;a={gecko:0,ie:0,opera:0,webkit:0};d=k.match(/AppleWebKit\/(\S*)/);if(d&&d[1]){a.webkit=l(d[1])}else{d=k.match(/MSIE\s([^;]*)/);if(d&&d[1]){a.ie=l(d[1])}else{if((/Gecko\/(\S*)/).test(k)){a.gecko=1;d=k.match(/rv:([^\s\)]*)/);if(d&&d[1]){a.gecko=l(d[1])}}else{if(d=k.match(/Opera\/(\S*)/)){a.opera=l(d[1])}}}}}function i(r,q,s,m,t){var n,o,l,k,d;c();if(q){q=q.constructor===Array?q:[q];if(r==="css"||a.gecko||a.opera){e[r].push({urls:[].concat(q),callback:s,obj:m,scope:t})}else{for(n=0,o=q.length;n<o;++n){e[r].push({urls:[q[n]],callback:n===o-1?s:null,obj:m,scope:t})}}}if(b[r]||!(k=b[r]=e[r].shift())){return}g=g||f.getElementsByTagName("head")[0];q=k.urls;for(n=0,o=q.length;n<o;++n){d=q[n];if(r==="css"){l=j("link",{href:d,rel:"stylesheet",type:"text/css"})}else{l=j("script",{src:d})}if(a.ie){l.onreadystatechange=function(){var p=this.readyState;if(p==="loaded"||p==="complete"){this.onreadystatechange=null;h(r)}}}else{if(r==="css"&&(a.gecko||a.webkit)){setTimeout(function(){h(r)},50*o)}else{l.onload=l.onerror=function(){h(r)}}}g.appendChild(l)}}return{css:function(l,m,k,d){i("css",l,m,k,d)},js:function(l,m,k,d){i("js",l,m,k,d)}}}();