﻿/// <reference path="jQuery/jquery-1.6.1.js" />
/// <reference path="global.js" />

var textBoxDefaultText = '';
var ac_multipleSearchPerformed = false;

// Client-side version of the mode enum.
var Mode =
    {
        Tag: 0,
        Instrument: 1,
        Users: 2,
        Multiple: 3,
        ExtendedInstrument: 4,
        ExtendedInstrumentWatchList: 5,
        Forex: 6
    };
   
var ExtendedInstrumentColumns =
    {
        ExchangeLongName: 0,
        ExchangeId: 1,
        ExchangeShortCode: 2,
        InstrumentId: 3,
        InstrumentSymbol: 4,
        InstrumentName: 5,
        Last: 6,
        Change: 7,
        PercentageChange: 8,
        TotalVolume: 9,
        Currency: 10
    };
var activeControl;
var ac_isAsyncPostback = false;

jQuery(document).bind("ready", function () {
    BindAutoCompleterEvents();    
    $("input[id*=_textbox]").each(function () {
        textBoxDefaultText = $(this).attr("defaulttext");
        $(this).trigger("blur");
    });
});

function autocomplete_formatNumber(number, doColorFormat) {
    var floatNumber = parseFloat(number);
    var fixedNumber = floatNumber.toFixed(2);
    var positiveNumberString = "<span style=\"color:green\">{0}</span>";
    var negativeNumberString = "<span style=\"color:red\">{0}</span>";
    var neutralNumberString = "<span style=\"color:gray\">{0}</span>";
    if (!doColorFormat) return fixedNumber;
    if (number == 0) return String.format(neutralNumberString, fixedNumber);
    if (number < 0) return String.format(negativeNumberString, fixedNumber);
    if (number > 0) return String.format(positiveNumberString, fixedNumber);
}

function formatHeader(mode) {
    var returnValue = "";
    switch (mode) {
        case Mode.Instrument:
            returnValue = "<div style=\"width:341px\" class=\"ac_header\">" +
                            '   <div style=\"float:right; width: 180px\"><b>¤translate("txtExchange")</b></div>' +
                            '   <div style=\"float:left; width: 160px\"><b>¤translate("txtInstrument")</b></div>' +
                            "</div>";
            break;
        case Mode.Multiple:
            returnValue = "<div style=\"width:220px\" class=\"ac_header\">" +
                            "   <div style=\"float:left\"><b>Name</b></div>" + 
                            "   <div style=\"float:right\"><b>Type</b></div>" +
                            "</div>";
            break;
        case Mode.ExtendedInstrumentWatchList:
        case Mode.ExtendedInstrument:
            returnValue = "<div class=\"ac_header\">" +
                            "   <div style=\"float: left; width:240px \"><b>¤translate(txtInstrument)</b></div>" +
                            "   <div style=\"float: right; width:100px; text-align:right; margin-right:10px \"><b>¤translate(txtLast)</b></div>" +  
                            "   <div style=\"float: right; width:50px\"><b>¤translate(txtExchange)</b></div>" +
                            "</div>";
            break;
        case Mode.Users:
            returnValue = "<div class=\"ac_header\">" +
                            "   <div style=\"float:left\"><b>¤translate(txtUsername)</b></div>" +
                            "</div>";
            break;
    }
    return returnValue;
}

function formatMatch(mode, data) {
    var value;    
    switch (mode) {
        case Mode.Forex:
            value = data[0].split('|')[0];
            break;
    }
    return value;
}

function formatItem(mode, data, i, total) {    
    var value;    
    switch (mode) {
        case Mode.Tag:
            value = '<div style="font-size:10px;padding-left:5px;padding-right:5px">' + data[0] + '</div>' +                    
                    '<div class="data_sep"></div>';           
            break;
        case Mode.Instrument:
            var dataItem = data[0].replace('Euronext', '');
            value = '<div style="width:341px;font-size:10px;padding-left:5px;padding-right:5px">' +
                    '   <div class=\"TrimText\" style=\"float:right;width:180px\">' + dataItem + '</div>' + 
                    '   <div class=\"TrimText\" style=\"float:left;width:160px\">' + data[5] + '</div>' +
                    '</div>' +
                    '<div class="data_sep"></div>';
            break;
        case Mode.ExtendedInstrumentWatchList:
        case Mode.ExtendedInstrument:
            value = '<div style="font-size:10px;padding-left:5px;padding-right:5px">' +
                    '   <div style=\"width:100px;float:right;text-align:right;margin-right:10px\">' + autocomplete_formatNumber(data[ExtendedInstrumentColumns.Last], false) + ' ' + data[ExtendedInstrumentColumns.Currency] + '</div>' +                    
                    '   <div class=\"TrimText\" style=\"width:50px;float:right\">' + data[ExtendedInstrumentColumns.ExchangeShortCode] + '</div>' +
                    '   <div class=\"TrimText\" style=\"float:left;width:240px\">' + data[ExtendedInstrumentColumns.InstrumentName] + ' (' + data[ExtendedInstrumentColumns.InstrumentSymbol] + ')</div>' +
                    '</div>' +
                    '<div class="data_sep"></div>';          
            break;
        case Mode.Users:
            value = '<div style="font-size:10px;padding-left:5px;padding-right:5px">' +
                    '   <div class=\"TrimText\">' + data[1] + '</div>' +                    
                    '</div>' +
                    '<div class="data_sep"></div>';
            break;
        case Mode.Multiple:            
            value = '<div style="font-size:10px;padding-left:5px;padding-right:5px">' +
                    '   <div style=\"float:right\" class=\"TrimText\">' + data[1] + '</div>' +
                    '   <div style=\"width:150px;float:left\" class=\"TrimText completionrow\">' + data[3] + '</div>' +
                    '</div>' +
                    '<div class="data_sep"></div>';
            break;
        case Mode.Forex:
            value = '<div style="font-size:10px;padding-left:5px;padding-right:5px">' + data[0].split('|')[0] + '</div>' +
                    '<div class="data_sep"></div>';
            break;
    }
    return value;
}

function formatResult(mode, row) {
    switch (mode) {
        case Mode.Tag:
            return row[0].replace(/(<.+?>)/gi, '');
            break;
        case Mode.Instrument:
            return row[2] + ':' + row[4];
            break;
        case Mode.ExtendedInstrument:
            return row[2] + ':' + row[4];
            break;
        case Mode.Users:
            return row[1].replace(/(<.+?>)/gi, '');
            break;
        case Mode.Multiple:
            return row[3];
            break;
    }
}

// Handles the "result" event from the completer
function autocomplete_onResult(event, data, formatted, extraParam) {
    if (this.id != activeControl[0].id) { return; }
    var textBox = $(this);    
    var isGamePortfolio = eval(textBox.attr("isgameportfolio"));
    var controlPrefix = this.id.substring(0, this.id.length - 8);
    var singleMode = textBox.attr("singlemode");
    var convertTextBoxToList = textBox.attr("converttextboxtolist");
    var searchMode = textBox.attr("searchmode");    
    var mode = textBox.attr("mode");
    var outputList = $("#" + controlPrefix + "_divOutput");
    var hiddenValue = $("#" + controlPrefix + "_hiddenValue");
    var getValue;
    if (data.length == 2) {
        getValue = data;
    }
    else {
        getValue = data[3];
    }    
    if (singleMode) {
        textBox.val(''); // clear textbox as only single input is allowed
        if (convertTextBoxToList) {
            textBox.hide();            
            outputList.show();
        }
        switch (parseInt(mode)) {
            case Mode.Forex:
                var instrumentId = data[0].split('|')[1];
                window.location.href = '/forex/details.aspx?id=' + instrumentId;
                break;
            case Mode.Tag:
                if (convertTextBoxToList) {
                    // Add chosen item to list                     
                    outputList.html(outputList.html() + "<span id=\"" + formatted + "\">" + formatted + "&nbsp;<a id=\"tag_" + formatted + "\" style=\"cursor:default\">X</a><br/></span>");
                }
                break;
            case Mode.Instrument:
                hiddenValue.val(getValue);
                if (convertTextBoxToList) {
                    // Add chosen item to list                       
                    outputList.html("<span style=\"float:left; padding:0px 2px 0px 2px; margin-bottom:5px; background-color:#f8f8f8; border:1px solid #d4d4d4\" id=\"" + data[3] + "\">" + data[2] + ":" + data[4] + "&nbsp;<a id=\"instrument_" + data[3] + "\" style=\"cursor:pointer\">X</a><br/></span>");
                    $("a[id=instrument_" + data[3] + "]").bind("click", RemoveElement);
                }
                break;
            case Mode.Users:
                hiddenValue.val(getValue);
                if (convertTextBoxToList) {
                    // Add chosen item to list                
                    outputList.html("<span style=\"float:left; padding:0px 2px 0px 2px; margin-bottom:5px; background-color:#f8f8f8; border:1px solid #d4d4d4\" id=\"" + data[1] + "\">" + data[1] + "&nbsp;<a id=\"user_" + data[1] + "\" style=\"cursor:pointer\">X</a><br/></span>");
                    $("a[id=user_" + data[1] + "]").bind("click", RemoveElement);
                }
                break;
            case Mode.ExtendedInstrument:
                if (isGamePortfolio) {
                    EI.Global.loadTradeOverlay(4, 0, getValue); // show trading overlay
                }
                else {                    
                    if (EI.Portfolio) {
                        EI.Portfolio.loadPortfolioOverlay(getValue, extraParam);
                    } else {
                        EI.DelayLoad.loadScriptFile("/JS/EI/EI.Portfolio.js", function () {
                            EI.Portfolio.loadPortfolioOverlay(getValue, extraParam);
                        });
                    }
                    //window.location = "/portfolio/edittrades.aspx?ptfno=" + querySt("ptfno") + "&iid=" + getValue;   // redirect to normal portfolio "insert trade" page.
                }
                break;
            case Mode.ExtendedInstrumentWatchList:
                // do nothing because atm. a callback is defined when adding to the watchlist so the section underneath will be run.
                break;                   
        }
        if (textBox.attr("ac_callback") != null && textBox.attr("ac_callback") != "undefined" && textBox.attr("ac_callback") != "")
            if(typeof(extraParam) != "undefined")
                textBox.trigger(textBox.attr("event"), [data, extraParam]); // fire event to notify parent that an element has been chosen           
            else
                textBox.trigger(textBox.attr("event"), [data]); // fire event to notify parent that an element has been chosen           
    } else {
        if (mode == Mode.Tag) {

        } else if (mode == Mode.Instrument) {
            if (hiddenValue.val() != "")
                hiddenValue.val(hiddenValue.val() + "," + getValue);
            else
                hiddenValue.val(getValue);
        } else if (mode == Mode.Users) {
            if (hiddenValue.val() != "") {
                var existingText = hiddenValue.val();
                if (existingText.indexOf(getValue[0]) == -1)
                    hiddenValue.val(hiddenValue.val() + "," + getValue[0]);
                else
                    jQuery(this).val(jQuery.trim(removeSubstring(jQuery(this).val(), data[1])));
            }
            else
                hiddenValue.val(getValue[0]);
        } else if (mode == Mode.Multiple || mode == Mode.ExtendedInstrument) {
            if (searchMode) {
                if (mode == Mode.ExtendedInstrument) {
                    event.preventDefault();                    
                    window.location.href = data[12];
                    return false;
                }
                // alert(mode);
                ac_multipleSearchPerformed = true;                
                window.location.href = '/search/default.aspx?q=' + data[3] + '&type=' + data[0] + '&id=' + data[4];
                event.preventDefault();
            } else {
                var url = window.top.location.toString().replace('investors\.aspx', 'investorsearchresult.aspx');
                if (url.indexOf('?') != -1) url = url + '&facet=' + escape(data[0]) + '%23' + escape(data[2]);
                else url = url + '?facet=' + escape(data[0]) + '%23' + escape(data[2]);
                window.location = url;
            }
        }
    }
}

// If user hits enter button on global search and no items is selected submit the search with the typed data.
function autocomplete_onKeyup(e) {
    setTimeout(function(e) { // Neccessary with small delay to fix timing issue between events firing.
        var searchMode = jQuery(this).attr("searchmode");
        if (searchMode) {
            if (e.keyCode == 13 && !ac_multipleSearchPerformed) {
                e.preventDefault();
                jQuery(this).attr("searchmode", "false");           
                jQuery("#search_button").trigger("mousedown");
            }
        }
    }, 100);
}

// Clear the textbox of the default text on focus
function autocomplete_onFocus() {    
    activeControl = $(this);    
    if (this.value == activeControl.attr("defaulttext")) {        
        activeControl.animate({ color: '#bfbfbf' }, 300, function () {
            activeControl.val('').css('color', '#555555');            
        });
    }
}

// Set default text on blur event.
function autocomplete_onBlur() {    
    var mode = jQuery(this).attr("mode");    
    if (mode == Mode.Instrument || mode == Mode.ExtendedInstrument || mode == Mode.ExtendedInstrumentWatchList || mode == Mode.Users) {
        if (this.value == '') {
            var defaultText = $(this).attr("defaulttext") || textBoxDefaultText;
            $(this).val(defaultText).css("color", "#bfbfbf");
            $(this).animate({ color: '#555555' }, 300, function () {});            
        }
    }
}

// Wire up the completers on the page and bind the events.
function autocomplete_onBindEvents() {
    var textBox = jQuery(this);
    var selectFirst = textBox.attr("selectfirst");
    var mode = textBox.attr("mode");
    var width = 351; // default value...
    var rightAlignDropDown = false;
    var showLoadingIcon = true;
    var additionalDropdownOffset = 0;
    var matchContains = eval(textBox.attr("matchcontains"));
    var matchSubset = eval(textBox.attr("matchsubset"));    
    var additionalSubmit = textBox.attr("additionalsubmit");
    if (mode != null && mode != "undefined" && mode != "") {
        if (mode == Mode.ExtendedInstrument || mode == Mode.ExtendedInstrumentWatchList) {   
            width = 420;
            selectFirst = true; // this might override the previous set value. Maybe do this server-side...
        }
    }
    var limit = eval(textBox.attr("limit"));
    if (!(limit > 0)) limit = 10;

    if (textBox.attr("ac_callback") != null && typeof(textBox.attr("ac_callback")) != "undefined" && textBox.attr("ac_callback") != "") {  
        textBox.bind(textBox.attr("event"), eval(textBox.attr("ac_callback")));
    }

    if (textBox.attr("rightaligndropdown") != null && typeof (textBox.attr("rightaligndropdown")) != "undefined" && textBox.attr("rightaligndropdown") != "")
        rightAlignDropDown = textBox.attr("rightaligndropdown");

    if (!isNullOrUndefined(textBox.attr("showloadingicon")) && textBox.attr("showloadingicon") != "") {        
        showLoadingIcon = (textBox.attr("showloadingicon") == 'true'); 
    }

    if (textBox.attr("additionaldropdownoffset") != null && typeof (textBox.attr("additionaldropdownoffset")) != "undefined" && textBox.attr("additionaldropdownoffset") != "")
        additionalDropdownOffset = parseInt(textBox.attr("additionaldropdownoffset"));

    
    jQuery(this).autocomplete('', {
        width: width,
        multiple: true,
        matchContains: matchContains,
        matchSubset: matchSubset,
        scroll: false,
        formatItem: formatItem,
        delay: 1,
        formatResult: formatResult,
        formatHeader: formatHeader,
        formatMatch: formatMatch,
        isAsync: ac_isAsyncPostback,
        selectFirst: selectFirst,
        rightAlignDropDown: rightAlignDropDown,
        additionalDropdownOffset: additionalDropdownOffset,
        max: limit,
        showLoadingIcon: showLoadingIcon,
        additionalSubmit: additionalSubmit
    });
}

function BindAutoCompleterEvents(isAsync) {    
    ac_isAsyncPostback = isAsync;
    $("input[id*=_textbox]").each(function () {        
        $(this).blur(autocomplete_onBlur);        
        $(this).focus(autocomplete_onFocus);
        $(this).keyup(autocomplete_onKeyup);
        $(this).result(autocomplete_onResult);
        $(this).each(autocomplete_onBindEvents);        
    });
}

function RemoveElement(e) {    
    var element = e.target.id;
    var parentControlId;
    if (e.srcElement)
        parentControlId = e.srcElement.parentElement.parentElement.id; // IE
    else
        parentControlId = e.target.parentNode.parentNode.id; // Firefox
        
    var controlPrefix = parentControlId.substring(0, parentControlId.length - 10);
    var mode = jQuery(e).attr("mode");
    
    // Remove element from lst
    jQuery("#" + element).remove();

    // Set the default text for instruments
    if (mode == Mode.Instrument) {        
        jQuery("#" + controlPrefix + "_textbox").val(textBoxDefaultText);
        jQuery("#" + controlPrefix + "_textbox").addClass("TextBoxDefault");
    }
    
    // Clear hidden field and show textbox and hide list
    jQuery("#" + controlPrefix + "_hiddenValue").val('');
    jQuery("#" + controlPrefix + "_textbox").show();  
    jQuery("#" + controlPrefix + "_divOutput").hide();
}
   
function removeSubstring(myStr, mySubstr) {
    myStr = "," + myStr + ",";
    myStr = myStr.split("," + mySubstr + ",").join(",");
    myStr = myStr.substring(1, myStr.length-1);
    return myStr;
}
