//params = {
//  inputId : '',
//  resultsId : '',
//  forceSelection : false,
//  preserveInput : true,
//  parents : false,
//  children : false,
//  akaNames : false,
//  imageRefs : false,
//  ratingCriteria : false
//};
RoleAutoComplete = function(params) {
    this.input = document.getElementById(params.inputId);
    this.results = document.getElementById(params.resultsId);
    this.preserveInput = !params.preserveInput ? false : true;
    this.roleInfoPanel = null;
    this.parents = !params.parents ? false : true;
    this.children = !params.children ? false : true;
    this.akaNames = !params.akaNames ? false : true;
    this.imageRefs = !params.imageRefs ? false : true;
    this.ratingCriteria = !params.ratingCriteria ? false : true;

    this.onRoleChosen = new YAHOO.util.CustomEvent('RAC_RoleChosen', this);
    this.onSearchFailed = new YAHOO.util.CustomEvent('RAC_SearchFailed', this);
    this.onSearchInitiated = new YAHOO.util.CustomEvent('RAC_SearchInitiated', this);

    this.dataSource = new YAHOO.widget.DS_XHR(GLOBALS.contextPath + '/ajax/findRole', ['results', 'name', 'id', 'description', 'akaNames', 'imageRefs', 'parents', 'children', 'ratingCriteria']);
    this.dataSource.responseType = YAHOO.widget.DS_XHR.TYPE_JSON;
    this.dataSource.scriptQueryAppend = "parents=" + this.parents +
                                        "&children=" + this.children +
                                        "&akaNames=" + this.akaNames +
                                        "&imageRefs=" + this.imageRefs +
                                        "&ratingCriteria=" + this.ratingCriteria;

    this.autoComplete = new YAHOO.widget.AutoComplete(this.input, this.results, this.dataSource);

    this.autoComplete.minQueryLength = 3;
    this.autoComplete.maxResultsDisplayed = 10;
    this.autoComplete.queryDelay = 0.25;
    this.autoComplete.forceSelection = !params.forceSelection ? false : true;

    // this.autoComplete.typeAhead = true;
    this.autoComplete.allowBrowserAutocomplete = false;
    this.autoComplete.useShadow = true;

    this.formatResult = function(resultItems, query) {
        var result = resultItems[0];
        var resultLC = result.toLowerCase();
        var queryLC = query.toLowerCase();
        var n = resultLC.indexOf(queryLC);
        var html;
        if (n == 0) {
            html =
                [ '<div id="ac_result">',
                '<span class="ac_substring">',
                result.substring(0, query.length),
                '</span>',
                result.substring(query.length),
                '</div>'
            ];
            return html.join('');
        }
        else if (n > 0) {
            html =
                [ '<div id="ac_result">',
                result.substring(0, n),
                '<span class="ac_substring">',
                result.substring(n, n + query.length),
                '</span>',
                result.substring(n + query.length),
                '</div>'
            ];
            return html.join('');
        }
        else {
            return result;
        }
    }

    this.showRoleInfoPanel = function(query, role) {
        if (!this.roleInfoPanel) {
            var options = {
                width: '320px',
                visible: false,
                draggable: false,
                close: false,
                constraintoviewport: true,
                underlay: 'shadow',
                context: [this.input, 'tl', 'br'],
                zindex: 100
            };
            this.roleInfoPanel = new YAHOO.widget.Panel('roleInfoPanel', options);
            this.roleInfoPanel.render(document.body);
            this.roleInfoPanel.cfg.setProperty('x', this.roleInfoPanel.cfg.getProperty('x') + 10, true);
            this.roleInfoPanel.cfg.setProperty('y', this.roleInfoPanel.cfg.getProperty('y') + 10, true);
            this.roleInfoPanel.cfg.setProperty('context', null, true);
            this.roleInfoPanel.cfg.refresh();
        }

        var nameLC = role.name.toLowerCase();
//        var descriptionLC = role.description.toLowerCase();
        var queryLC = query.toLowerCase();
        var n = nameLC.indexOf(queryLC);
        var html;
        if (n == 0) {
            html =
                [ '<span class="ac_substring">',
                role.name.substring(0, query.length),
                '</span>',
                role.name.substring(query.length)
            ];
            this.roleInfoPanel.setHeader(html.join(''));
        }
        else if (n > 0) {
            html =
                [  role.name.substring(0, n),
                '<span class="ac_substring">',
                role.name.substring(n, n + query.length),
                '</span>',
                role.name.substring(n + query.length)
            ];
            this.roleInfoPanel.setHeader(html.join(''));
        }
        else {
            this.roleInfoPanel.setHeader(role.name);
        }

/*
        n = descriptionLC.indexOf(query.toLowerCase());
        if (n == 0) {
            html =
                [ '<span class="ac_substring">',
                role.description.substring(0, query.length),
                '</span>',
                role.description.substring(query.length)
            ];
            this.roleInfoPanel.setBody(html.join(''));
        }
        else if (n > 0) {
            html =
                [ role.description.substring(0, n),
                '<span class="ac_substring">',
                role.description.substring(n, n + query.length),
                '</span>',
                role.description.substring(n + query.length)
            ];
            this.roleInfoPanel.setBody(html.join(''));
        }
        else {
            this.roleInfoPanel.setBody(role.description);
        }
*/

        this.roleInfoPanel.setBody(role.description);

        html = [];
        if (role.akaNames && role.akaNames.length > 0) {
            html.push('<br />');
            html.push('<span class="akaHeading">Also known as :</span>');
            html.push('<br />');
            html.push('<span class="akaBody">');
            for (var i = 0; i < role.akaNames.length; i++) {
                html.push(role.akaNames[i]);
                html.push('<br />');
            }
            html.push('</span>');
        }

        if (role.ratingCriteria && role.ratingCriteria.length > 0) {
            html.push('<br />');
            html.push('<span class="criteriaHeading">Has rating criteria :</span>');
            html.push('<br />');
            html.push('<span class="criteriaBody">');
            for (i = 0; i < role.ratingCriteria.length; i++) {
                html.push(role.ratingCriteria[i].name);
                html.push(' # ');
            }
            // remove the last #
            html.pop();
            html.push('</span>');
        }

        if (html.length > 0) {
            this.roleInfoPanel.setFooter(html.join(''));
        }
        else {
            this.roleInfoPanel.setFooter('');
        }

        this.roleInfoPanel.render(document.body);
        this.roleInfoPanel.show();
    }

    this.hideRoleInfoPanel = function() {
        if (this.roleInfoPanel) {
            this.roleInfoPanel.hide();
        }
    }

    var roleChosenHandler = function(type, args, me) {
        var role = {
            name : args[2][0],
            id : args[2][1],
            description : args[2][2],
            akaNames : args[2][3],
            imageRefs : args[2][4]
        };

        var parents = args[2][5];
        if (parents && parents.length) {
            role.parents = parents;
        }

        var children = args[2][6];
        if (children && children.length) {
            role.children = children;
        }

        var ratingCriteria = args[2][7];
        if (ratingCriteria && ratingCriteria.length) {
            role.ratingCriteria = ratingCriteria;
        }
        if (!me.preserveInput) {
            me.input.value = '';
        }
        me.onRoleChosen.fire(role);
    };
    this.autoComplete.itemSelectEvent.subscribe(roleChosenHandler, this);

    var containerCollapseHandler = function(type, args, me) {
        me.hideRoleInfoPanel();
    };
    this.autoComplete.containerCollapseEvent.subscribe(containerCollapseHandler, this);

    var itemMouseOverHandler = function(type, args, me) {
        var role = {
            name : args[1]._oResultData[0],
            description : args[1]._oResultData[2],
            akaNames : args[1]._oResultData[3],
            ratingCriteria : args[1]._oResultData[7]
        };
        me.showRoleInfoPanel(me.input.value, role);
    };
    this.autoComplete.itemMouseOverEvent.subscribe(itemMouseOverHandler, this);

    var itemArrowToHandler = function(type, args, me) {
        var role = {
            name : args[1]._oResultData[0],
            description : args[1]._oResultData[2],
            akaNames : args[1]._oResultData[3],
            ratingCriteria : args[1]._oResultData[7]
        };
        me.showRoleInfoPanel(me.input.value, role);
    };
    this.autoComplete.itemArrowToEvent.subscribe(itemArrowToHandler, this);

    var dataRequestHandler = function (type, args, me) {
        me.onSearchInitiated.fire();
    };
    this.autoComplete.dataRequestEvent.subscribe(dataRequestHandler, this);

    var dataReturnHandler = function(type, args, me) {
        if (args[2].length == 0) {
            me.input.focus();
            me.onSearchFailed.fire();
        }
    };
    this.autoComplete.dataReturnEvent.subscribe(dataReturnHandler, this);
};
