// 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.Ajax.timeout = 120000; //2 minutes
Ext.BLANK_IMAGE_URL = '../javascript/ext/images/gray/s.gif';

function highlightCount(id, highlight) {
    id = '#'+id+'_count';
    if (highlight) {
        $(id).css('background-color','#555555');
        $(id).children().css('color','white');
    } else {
        $(id).css('background-color','#DFDFDF');
        $(id).children().css('color','#333333');
    }
}

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);
            document.getElementById('ce-staffnotes').value = data.staffnote;
        },
        failure: function() {
            Ext.Msg.alert("Fail");
        },
        params: {
            foo: 'bar'
        }
    });

    notesWin.buttons[0].setDisabled(false);
    staffNotes.focus('',300);
//todo we need to find a way to move cursor to the top
//or scroll down to last line where the cursor is at
}

function getEventCounts() {
    // Set a timer to delay the call
    if($('#session_count').html()==".."){
        setTimeout("callEventPolling()", 1500);
    }
    setInterval("callEventPolling()", 20000);
}

function callEventPolling()
{
    Ext.Ajax.request({
        url: 'index.php?fuse=admin&action=getEventNotifications',
        success: function(xhr) {
            var updateCache = false;
            var e = Ext.decode(xhr.responseText);
            //check to see if new counts are diff if diff then lets force save
            if ($('#session_count').html() != e.eventCounts.session) {
                updateCache = true;
            }
            $('#session_count').html(e.eventCounts.session);
            $('#day_count').html(e.eventCounts.day);
            if (updateCache) ce.updateEventCache();

            var newEventCount = e.eventCounts.newEvents.length;
            if (newEventCount > 0) {
                for(var x=0; x < newEventCount; x++) {
                    //only show events we didn't cause
                    if (e.eventCounts.newEvents[x].userid != ceChat.me.id) {
                        ce.showNewEvent(e.eventCounts.newEvents[x].subject,e.eventCounts.newEvents[x].fullName,e.eventCounts.newEvents[x].email);
                    }
                }
               
            }
        }
    });
}

function getTicketSummaries()
{
    // Set a timer to delay the call
    if($('#supportticketsummary').html()==""){
        setTimeout("callTicketSummaries()", 1000);
    }
    setInterval("callTicketSummaries()", 15000);
}

function callTicketSummaries()
{
    Ext.Ajax.request({
        url: 'index.php?fuse=support&view=SideBarTicketSummary',
        success: function(xhr) {
            $('#supportticketsummary').html(xhr.responseText);
            ce.updateTicketsCache();
        }
    });
}

/*
function getWikiAvailability()
{
   // Set a timer to delay the call
   setTimeout("callWikiAvailble()", 5000);
}

function callWikiAvailble() 
{

   var currentPage = gFuse.toLowerCase()+"_"+gView.toLowerCase();
   Ext.Ajax.request({
       url: 'index.php?fuse=admin&action=IsWikiPageAvailable',
       timeout:3000,
       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 createNewFilter()
{
    customfilterwin = new Ext.Window({
        id          : 'customfilter-win',
        autoLoad: {
            url: 'index.php?fuse=admin&view=viewAddTicketFilter',
            scripts: true
        },
        title       : lang('Add Ticket Filter'),
        width       : 500,
        autoHeigh   : true,
        closeable   : true,
        modal       : true,
        minimizable : false,
        plain       : true
    });
    customfilterwin.show();
}

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+"&";
    }
    document.getElementById(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='sessionHash' value='"+gHash+"' /><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>";
//document.getElementById('userid').focus();
}

function updateSplashScreenValue(showNextLogin,userId) {
    Ext.Ajax.request({
       url: 'index.php?fuse=admin&action=updateSplashScreenValue',
       success: function(xhr) {
            var data = Ext.decode(xhr.responseText);
       },
       params: {show : showNextLogin,
				userid: userId}
    });
}

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('',300);
}

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

Ext.onReady(function(){
    /*
	var searchquerytooltip = new Ext.ToolTip({
            target: 'searchquerytextfield',
            anchor: 'bottom',
            autoHide: true,
            showDelay: 1500,
            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')
        });*/

    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: 194,
        height:5,
        minChars:3,
        handleHeight:5,
        value: lang("Live search"),
        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);
        },
        listeners: {
            'collapse' : function (combo){
                if (combo.store.data.length==0) {
                    ce.msg('No Match Found');
                } else {
                    $('#searchquerytextfield').val(lang('Live search'));
                    $('#searchquerytextfield').css("color","#444");
                }
            },
            'blur' : function (combo) {
                if (combo.store.data.length==0) {
                    $('#searchquerytextfield').val(lang('Live search'));
                    $('#searchquerytextfield').css("color","#444");
                }
            }
        }
    });

    // users dropdown list //used in billing module and other places that requires client list.. don't delete'
    allclientsstore = new Ext.data.JsonStore({
        id: "allclientsstore",
        root: 'clients',
        totalProperty: 'totalcount',
        idProperty: 'id',
        remoteSort: true,
        fields: [
        'id','firstname','lastname', 'fullname','isOrganization','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){
        document.getElementById('remote-users').style.display='';
        var customerDropDownWithTooltip = new Ext.form.ComboBox({
            tpl: '<tpl for="."><div ext:qtip="id: {id}<br/>contact: {firstname} {lastname}<br/>e-mail: {email}<br/>status: {statusname}<br/>type: {clienttypename}" class="x-combo-list-item"><span style="text-transform:capitalize;">{fullname}</span></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..."),
        modal: true,
        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: 260,
        height: 140,
        closeAction: 'hide',
        plain: true,
        y: 150,
        x : document.getElementById('sidebaropengear').offsetParent.offsetLeft+ 100,
        modal: 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,
        modal: true,
        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,
        modal:      true,
        height      : 400,
        closeable   : true,
        minimizable : false,
        plain       : true,
        items       : contextpanel
    });

    win.show();

}

function HideShowAndUpdateCustomField(which,imgid,customfieldname,whichopposite){

    style = "";
    if (!document.getElementById)  return false;
    if (which.style.display=="none"){
        which.style.display="";
        
        if (typeof(whichopposite)!="undefined") {
            whichopposite.style.display="none";
        }

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

        if (typeof(whichopposite)!="undefined") {
            whichopposite.style.display="";
        }

        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(document.getElementById(id+'_options').style.display == "none"){
        document.getElementById(id+'_options').style.display = "";
        document.getElementById(id).className = "toggleopen";
    }else{
        style = "none";
        document.getElementById(id+'_options').style.display = "none";
        document.getElementById(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
        }
    });

}

/*
 * The following override for automatically sizing a combo boxes contents
 * Replaces the previous one based on code at:
 * http://www.extjs.com/forum/showthread.php?63851-DISCUSS-ComboBox-should-allow-quot-auto-quot-as-its-listWidth-setting.-*Saves*-code.&p=367041#post367041
 * 
 * This code is based on a plugin at:
 * http://www.extjs.com/forum/showthread.php?94641-Plugin-to-allow-auto-sizing-of-the-combo-s-list&p=459687#post459687
 * 
 * Since we originally had an override in place, in order to apply new code in one location
 * instead of having to add a plugins option to 140+ ComboBox configugations, the plugin
 * was converted to an override
 * 
 * expand seems the appropriate method to override (as opposed to initList as previously)
 * as the lines of code that setWidth on list and innerList do not have any effect before
 * the original expand is called but do work as expected after the original expand is called 
 */
(function() {
    var originalComboBoxExpand = Ext.form.ComboBox.prototype.expand;
  
    Ext.override(Ext.form.ComboBox, {
        expand: function() {
            //prevent expand event from being fired when invoking original function
            this.suspendEvents();
            originalComboBoxExpand.apply(this, arguments);
            this.resumeEvents();
            
            if (this.innerList && this.list && !this.list.autosized) {
                //this.list.autosized is a new property for the purposes of managing state
                  
                var itemEl = this.view && this.view.getEl() 
                && this.view.getEl().child(this.itemSelector || ".x-combo-list-item");
                
                if (itemEl) {
                    var store = this.getStore();
                    var listenerFunc = function() {
                        this.list.autosized=false;
                    };
                    
                    /*
                     * store.events.load/update.autosizeListenerAdded are new state mgmt properties
                     * so that the necessary events for performing resizing when the underlying store
                     * is changed, only get added once
                     */
                    if (store.events && store.events.load && !store.events.load.autosizeListenerAdded) {
                        store.on('load', listenerFunc, this);
                        store.events.load.autosizeListenerAdded = true;
                    }
                    
                    if (store.events && store.events.update && !store.events.update.autosizeListenerAdded) {
                        store.on('update', listenerFunc, this);
                        store.events.update.autosizeListenerAdded = true;
                    }
                    
                    var autoWidth = Math.max(this.minListWidth, this.getWidth());
                    var defaultWidth = autoWidth;
                    
                    var textMetrics = Ext.util.TextMetrics.createInstance(itemEl);
                    
                    store.each(function(record) {
                        autoWidth = Math.max(autoWidth, textMetrics.getWidth(record.get(this.displayField)));
                    }, this);
                    
                    if (autoWidth > defaultWidth) {
                        autoWidth = Math.ceil(autoWidth * 1.15); //consider different approach
                        this.list.setWidth(autoWidth);
                        this.innerList.setWidth(autoWidth - this.list.getFrameWidth("lr"));
                        this.list.alignTo(this.wrap, this.listAlign);                    
                    }
                    
                    this.list.autosized = true;
                }
            }

            //invoke original expand event at very end just as in original method
            this.fireEvent('expand', this);
        }
    });
}());

/**
* Lazy load to add notes
*/
CE.prototype.addNote = function() {
    if(typeof CE.prototype.showClientNotes == 'function') {
        CE.prototype.showClientNotes();
    } else {
        LazyLoad.js(['../templates/admin/views/clients/profile/Notes_Add.js'], function () {
            CE.prototype.showClientNotes();
        });
    }
}

function togglePackageListType(type) {
    if (type == 'domain') {
        window.location = 'index.php?fuse=domains&view=ViewDomainsList';
    } else if (type == 'hosting') {
        window.location = 'index.php?fuse=clients&view=ViewPackagesList';
    } else if (type =='general') {
        window.location = 'index.php?fuse=clients&view=ViewGeneralPackagesList';
    }
}