/**
 * Javascript file for Sugar
 *
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004 - 2008 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 */



/**
 * browse document for quickSearch fields
 * Compatible ExtJS 1.1.1 and ExtJS 2.0
 * parameter : noReload - if set to true, enableQS will enable only
 *             the new sqsEnabled field on the page. If set to false
 *             it will reload all the sqsEnabled fields.
 */
function enableQS(noReload){
    Ext.onReady(function(){
        var qsFields = Ext.query('.sqsEnabled');
        for(var qsField in qsFields){
            var loaded = false;
            //verify that the sqs object has this field and that this field need a quickSearch
            if (isInteger(qsField) && (qsFields[qsField].id && !document.getElementById(qsFields[qsField].id).readOnly) && typeof sqs_objects != 'undefined' && sqs_objects[qsFields[qsField].id] && sqs_objects[qsFields[qsField].id]['disable'] != true) {
                // verify that this field has not been already loaded
                if(typeof Ext.getCmp('combobox_'+qsFields[qsField].id) != 'undefined'){
                    if (noReload == true) {
                        loaded = true;
                    }else if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined') {
                        Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
                        var parent = QSFieldsArray[qsFields[qsField].id][0];
                        if (typeof QSFieldsArray[qsFields[qsField].id][1] != 'undefined') {
                            var nextSib = QSFieldsArray[qsFields[qsField].id][1];
                            parent.insertBefore(QSFieldsArray[qsFields[qsField].id][2], nextSib);
                        }
                        else {
                            parent.appendchild(QSFieldsArray[qsFields[qsField].id][2]);
                        }
                    }
                }
                if (!loaded) {
                    // populate QSFieldsArray for being able to reload all the field (with noreload = false)
                    if (typeof QSFieldsArray[qsFields[qsField].id] == 'undefined') {
                        var Arr = new Array(qsFields[qsField].parentNode, qsFields[qsField].nextSibling, qsFields[qsField]);
                        QSFieldsArray[qsFields[qsField].id] = Arr;
                    }
                    var sqs = sqs_objects[qsFields[qsField].id];
                    
                    function setAll(el, e){
                        var selected = false;
                        for (var i = 0; i < el.store.data.length; i++) {//browse the record available in the store
                            if (el.store.data.items[i].json[e.displayField] == el.getValue()) {//if the record match what is in the field
                                for (var field in el.store.data.items[i].json) {
                                    for (var key in sqs_objects[el.el.id].field_list) {
                                        if (field == sqs_objects[el.el.id].field_list[key] && document.getElementById(sqs_objects[el.el.id].populate_list[key])) {
                                            document.getElementById(sqs_objects[el.el.id].populate_list[key]).value = el.store.data.items[i].json[field];
                                        }
                                    }
                                }
                                selected = true;
                                break;
                            }
                        }
                        return selected;
                    }
                    var display_field = sqs.field_list[0];
                    
                    var ds = new Ext.data.Store({
                        storeId: "store_" + qsFields[qsField].id,
                        proxy: new Ext.data.HttpProxy({
                            url: 'index.php'
                        }),
                        remoteSort: true,
                        reader: new Ext.data.JsonReader({
                            root: 'fields',
                            totalProperty: 'totalCount',
                            id: 'id'
                        }, [{
                            name: display_field
                        }, ]),
                        baseParams: {
                            to_pdf: 'true',
                            module: 'Home',
                            action: 'quicksearchQuery',
                            data: Ext.util.JSON.encode(sqs)
                        }
                    });
                    
                    var search = new Ext.form.ComboBox({
                        id: "combobox_" + qsFields[qsField].id,
                        store: ds,
                        //lazyRender: true,
                        queryDelay: 700,// delay before starting the search
                        maxHeight: 100,// max height of the drop and down
                        minListWidth: 120,//The minimum width of the dropdown list in pixels
                        displayField: display_field,
                        fieldClass: '',
                        listClsClass: typeof(Ext.version) != 'undefined' ? 'x-sqs-list' : 'x-combo-list',
                        focusClass: '',
                        disabledClass: '',
                        emptyClass: '',
                        invalidClass: '',
                        selectedClass: typeof(Ext.version) != 'undefined' ? 'x-sqs-selected' : 'x-combo-list',
                        typeAhead: true,// Autofill if only one match
                        loadingText: SUGAR.language.get('app_strings', 'LBL_SEARCHING'),
                        valueNotFoundText: sqs.no_match_text,
                        hideTrigger: true,
                        applyTo: typeof(Ext.version) != 'undefined' ? qsFields[qsField].id : Ext.form.ComboBox.prototype.applyTo,
                        minChars: 1,//1 character needed to start the search
                        listeners: {
                            select: function(el, type){
                                Ext.EventObject.preventDefault();
                                Ext.EventObject.stopPropagation();
                                for (var field in type.json) {
                                    for (var key in sqs_objects[el.el.id].field_list) {
                                        if (field == sqs_objects[el.el.id].field_list[key] && document.getElementById(sqs_objects[el.el.id].populate_list[key])) {
                                            document.getElementById(sqs_objects[el.el.id].populate_list[key]).value = type.json[field];
                                        }
                                    }
                                }
                                
                                //Handle special case where post_onblur_function is set    
                                if (typeof(sqs_objects[el.el.id]['post_onblur_function']) != 'undefined') {
                                    collection_extended = new Array();
                                    for (var field in type.json) {
                                        for (var key in sqs_objects[el.el.id].field_list) {
                                            if (field == sqs_objects[el.el.id].field_list[key]) {
                                                collection_extended[sqs_objects[el.el.id].field_list[key]] = type.json[field];
                                            }
                                        }
                                    }
                                    eval(sqs_objects[el.el.id]['post_onblur_function'] + '(collection_extended, el.el.id)');
                                }
                            },
                            autofill: function(el, ev){
                                el.lastQuery = "";
                                el.doQuery(el.getRawValue());
                                el.store.on("load", function(){
                                    if (el.store.data.items != 'undefined' && el.store.data.items[0]) {
                                        el.setRawValue(el.store.data.items[0].json[this.displayField]);
                                        setAll(el, this);
                                    }
                                    else {//clear all
                                        for (var key in sqs_objects[el.el.id].field_list) {
                                            if (isInteger(key)) 
                                                document.getElementById(sqs_objects[el.el.id].populate_list[key]).value = '';
                                        }
                                    }
                                }, this, {
                                    single: true
                                });
                            },
                            blur: function(el){
                                var selected = setAll(el, this);
                                if (el.getRawValue() == "") {//clear all
                                    for (var key in sqs_objects[el.el.id].field_list) {
                                        if (isInteger(key)) 
                                            document.getElementById(sqs_objects[el.el.id].populate_list[key]).value = '';
                                    }
                                    selected = true;
                                }
                                if (!selected) {
                                    el.fireEvent("autofill", el);
                                }
                            }
                        }
                    });
                    // For Ext 1.1.1 (Emails Module)
                    if(typeof search.applyTo != 'undefined'){
                        search.applyTo(qsFields[qsField].id);
                    }
                    search.wrap.applyStyles('display:inline');
                    qsFields[qsField].className = qsFields[qsField].className.replace('x-form-text', '');
                    
                    //For Mac + Firefox
                    if (Ext.isMac && Ext.isGecko) {
                        document.getElementById(qsFields[qsField].id).addEventListener('keypress', preventDef, false);
                    }
                    // Allow not matching data in the QS SearchForm fields.
                    if((qsFields[qsField].form && typeof(qsFields[qsField].form) == 'object' && qsFields[qsField].form.name == 'search_form')
                        || (qsFields[qsField].className.match('sqsNoAutofill') !=  null)){
                        search.events.autofill.listeners[0].fireFn = function() {};
                    }
                }
            }
        }
    });
}

function preventDef(event){
    // Key ENTER
    if(event.keyCode == '13'){
        event.preventDefault();
    }
}

function registerSingleSmartInputListener(input) {
	if ((c = input.className) && (c.indexOf("sqsEnabled") != -1)) {
		if (typeof Ext == 'object') {
		 	enableQS(true);
		} // if
	}
}
QSFieldsArray = new Array();
if (typeof Ext == 'object') {
    enableQS(true);
}
