// $Id: watchEntry.js,v 1.3 2009/12/14 14:13:29 hbr Exp $

// Global variables
var watchAddURL = "/services/mymarketpulse/watchlist_add.json";
var watchRemoveURL = "/services/mymarketpulse/watchlist_remove_";
var watchGetDataURL = "/services/mymarketpulse/watchlist_get_data.json";
var segments = ["EQ", "BO", "FU", "IN"]; // FIXME: Must match the Java constants!
var nSetWatch = 0;

// Set the counts to zero on load - they will then be set to the correct value by the 
// init functions (eg initAddWatch)
function initEntryCounts() {
	nSetWatch = 0;
	nSetAlarm = 0;
}

// Add watch from the autocomplete selector or from the portfolio
function initAutocompleteWatch(selectionData) {
    var targetURL = watchGetDataURL + "?selectionData=" + selectionData;
    
    // Request the data needed to make an "Add Watch" pop-up
    dojo.xhrGet( {
        url: targetURL,
        handleAs: "json-comment-filtered",
        timeout: 20000,
        
        // If HTTP 200 (successful or "Problem")
        load: function(response, ioArgs) {
        
        	// HTTP OK - but problem with data
        	if (response.Message.substring(0,5) == "Probl") {
        		reportProblem("watchAdd", response.Message);
        	}
        	else {
        		// Success: Popup "Add Watch" dialog with data and isRefresh = true
        		dojo.byId('watchAddDialog').watchData = response;
        		dojo.byId('watchAddDialog').watchData.isRefresh = 'true';
        		initWatchAdd();
        	}
        	return response;
        },
        // HTTP not OK - report error message and wait for user
        error: function(response, ioArgs) {
       		reportProblem("watchAdd", response.message);
        	return response;
        }
    });
}

// Add a watch entry from Product Explorer
function initWatchAdd() {
    var watch = dojo.byId("watchAddDialog").watchData;
    
    if (nSetWatch == 0) {
    	nSetWatch = watch.nSetFromServer;
    }
    var nRemain = watch.nMax - nSetWatch;
    
// Display the main text box loaded with nSet and nRemain
    dojo.style("watchAddDefinition", "display", "");
    dojo.style("watchAddInfo", "display", "none");
    dojo.byId("watchShortNameDisplay").innerHTML = watch.shortName;
    dojo.byId("watchNumberSet").innerHTML = nSetWatch;
    dojo.byId("watchNumberTotal").innerHTML = watch.nMax;
    dijit.byId("watchNoteData").setValue("");
    
    if (nSetWatch == 1) {
            dojo.style("watchStatusSingular", "display", "");
            dojo.style("watchStatusPlural", "display", "none");
    } else {
            dojo.style("watchStatusSingular", "display", "none");
            dojo.style("watchStatusPlural", "display", "");            
    }
    
    if (nRemain > 0) {

// Add-Cancel buttons on, OK button off, and display add message
        dojo.style("watchNoteData", "display", "");
        dojo.style("watchAddCancelButtonRow", "display", "");
        dojo.style("watchOKButtonRow", "display", "none");
        dojo.style("watchAddMessage", "display", "");
        dojo.style("watchNoAddMessage", "display", "none");        
    }
    else {
		// text field and Add/Cancel buttons off, OK button on, display no-add message
        dojo.style("watchNoteData", "display", "none");
        dojo.style("watchAddCancelButtonRow", "display", "none");
        dojo.style("watchAddMessage", "display", "none");
        dojo.style("watchNoAddMessage", "display", "");
        showOKButton("watchOKButton");
    }
    dijit.byId("watchAddDialog").show();
}

// Set up the modify watch layer for user input
function initWatchModify() {
    var watch = dojo.byId("watchModifyDialog").watchData;

    // Form on, info off and set numbers
    dojo.style("watchModifyDefinition", "display", "");
    dojo.style("watchModifyInfo", "display", "none");
    
    // fill in data on the form display
    dojo.style("watchModifyMessage", "display", "");
    dojo.style("watchModifyOKButtonRow", "display", "none");
    dojo.byId("watchModifyValorSymbol").innerHTML = watch.valorSymbol;
    dojo.byId("watchModifyShortName").innerHTML = watch.shortName;
    dijit.byId("watchModifyNoteData").setValue(watch.noteData); // textbox needs special technique in IE
    dojo.byId("watchModifyNoteData").value = watch.noteData;
    dijit.byId("watchModifyDialog").show();
}

// Remove a watch entry from the DB
function watchRemove(securityId, portalSegment, lang) {
	var isRefresh = "true";
    var targetURL = watchRemoveURL + lang + ".json?SecurityId=" + securityId;
    dojo.style("watchRemoveInfoOKButtonRow", "display", "none");
    switchBeforeOnAfterOff("watchRemoveInfo");
    dijit.byId("watchRemoveDialog").show();
    dojo.style("watchRemoveInfo", "opacity", 1);
    dojo.style("watchRemoveInfo", "display", "");
    
    // Make a request to the XSP that handles the watch entry removal
    dojo.xhrGet( {
        url: targetURL,
        handleAs: "json-comment-filtered",
        timeout: 20000,

        // If HTTP 200 (successful or "Problem")
        load: function(response, ioArgs) {
                dojo.byId("watchRemoveInfoAfterRequest").innerHTML = response.Message;
                switchBeforeOffAfterOn("watchRemoveInfo");
                if (response.Message.substring(0,5) == "Probl") {

                    // Show button and wait for user
                    showOKButton("watchRemoveInfoOKButton");
                }
                else {
                	// If removing a watch from the Not Trading table, remove the row directly.
                	if (portalSegment == "NOT_TRADING") {
	                    dojo.style(securityId + "NOT_TRADING", "display", "none");
	                }
                    // Fade out dialog box and finish
					nSetWatch = response.nSet[0] + response.nSet[1] + response.nSet[2];
                    fadeAway("watchRemoveDialog");
                }
                
                // If we are in the watchlist display page, we must refresh the pane to remove
                // the security from the list. We don't do this if we are in an explorer page.
                // To test if we are in the watchlist, we check if the pane's queryString contains
                // the securityId.
				var pane = dijit.byId("resultsPane_" + portalSegment);
				if (pane && pane.href.indexOf(securityId) > -1) {                
				
					// Remove the current securityId from the query-string. Refresh the pane if
					// there is still at least one securityId, otherwise hide the pane.
					var newQS = removeFromQS(pane.href, securityId);
					pane.href = newQS;
					if (newQS.indexOf("SecurityId") > -1) {
						pane.refresh();
					} else {
						dojo.style("title" + portalSegment, "display", "none");
						dojo.style("config_button_and_results_" + portalSegment, "display", "none");
					}
				}
                return response;
            },
        // HTTP not OK - report error message and wait for user
        error: function(response, ioArgs) {
       		reportProblem("watchRemove", response.message);
        	return response;
        }
    });
}

// Convenience function to add a watch entry
function watchAdd() {
	watchAddOrModify(dojo.byId("watchAddDialog").watchData,
		dojo.byId('watchNoteData').value, "watchAdd");
}

// Convenience function to modify a watch entry
function watchModify() {
	watchAddOrModify(dojo.byId("watchModifyDialog").watchData,
		dojo.byId('watchModifyNoteData').value, "watchModify");
}

// Add or modify a watch entry in the DB.
// mode is either "watchAdd" or "watchModify"
function watchAddOrModify(watch, noteData, mode) {
    var targetURL = watchAddURL + "?SecurityId=" + watch.securityId +
    	"&ShortName=" + watch.shortName + "&Note=" + noteData;
    
    // Form off, OK button off, switch After to Before
    dojo.style(mode + "Definition", "display", "none");
    dojo.style(mode + "InfoOKButtonRow", "display", "none");
    switchBeforeOnAfterOff(mode + "Info");
    
    // Bring area back (in case it was faded previously)
    dojo.style(mode + "Info", "opacity", 1);
    dojo.style(mode + "Info", "display", "");
    
    // Make a request to the XSP that handles the watch entry adding
    dojo.xhrGet( {
        url: targetURL,
        handleAs: "json-comment-filtered",
        timeout: 20000,
        
        // If HTTP 200 (successful or "Problem")
        load: function(response, ioArgs) {
                dojo.byId(mode + "InfoAfterRequest").innerHTML = response.Message;
                switchBeforeOffAfterOn(mode + "Info");
                if (response.Message.substring(0,5) == "Probl") {
                
                    // Show button and wait for user
                    showOKButton(mode + "InfoOKButton");
                }
                else {
	                // Fade out dialog box and finish
	                fadeAway(mode + "Dialog");
                    nSetWatch = response.nSet;
                }
                // Sometimes (eg after autocomplete) we refresh the list (or make a new pane if
                // this is the first).
                if (watch.isRefresh == "true") {
	                var pane = dijit.byId("resultsPane_" + watch.portalSegment);
	                if (pane) {
                		dojo.style("title" + watch.portalSegment, "display", "");
                		dojo.style("config_button_and_results_" + watch.portalSegment, "display", "");
		                pane.href += "&SecurityId=" + watch.securityId;
		                pane.refresh();
		            }
		            else {
		            	location.reload();
		            }
	            }
                
                // If a tooltip exists, update it.
                var toolTip = dojo.byId(watch.securityId + "_noteTip");
                if (toolTip)
                	toolTip.innerHTML = noteData;

				// Successful end
                return response;
            },
        // HTTP not OK - report error message and wait for user
        error: function(response, ioArgs) {
       		reportProblem(mode, response.message);
        	return response;
        }
    });
}

// Edit an explorer query string and remove the securityId being deleted
function removeFromQS(queryString, securityId) {
	
	// Split the string by ampersands and then re-assemble, skipping the deleted secId
	var data = queryString.split("&");
	var result = "";
	for (i = 0; i < data.length; i++) {
		if (data[i].length > 0 && data[i].indexOf(securityId) == -1)
			result += data[i] + "&";
	}
	return result;
}



