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

// Global variables
var alarmAddURL = "/services/mymarketpulse/alarmlist_add_";
var alarmRemoveURL = "/services/mymarketpulse/alarmlist_remove_";
var alarmGetDataURL = "/services/mymarketpulse/alarmlist_get_data.json";
var segments = ["EQ", "BO", "FU", "IN"]; // FIXME: Must match the Java constants!
var nSetAlarm = 0;

// Add alarm from the autocomplete selector or from the portfolio
function initAutocompleteAlarm(selectionData) {
    var targetURL = alarmGetDataURL + "?selectionData=" + selectionData;
    
    // Request the data needed to make an "Add Alarm" 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("alarmAdd", response.Message);
        	}
        	else {
        		// Success: Popup "Add Alarm" dialog with data
        		dojo.byId('alarmAddDialog').alarmData = response;
        		dojo.byId('alarmAddDialog').alarmData.isRefresh = 'true';
        		initAlarmAdd();
        	}
        	return response;
        },
        // HTTP not OK - report error message and wait for user
        error: function(response, ioArgs) {
       		reportProblem("alarmAdd", response.Message);
        	return response;
        }
    });
}

// Set up the add alarm layer for user input
function initAlarmAdd() {

    // Copy the data object from the form
    var alarm = dojo.byId("alarmAddDialog").alarmData;
    
    if (nSetAlarm == 0) {
        nSetAlarm = alarm.nSetFromServer;
    }
    var nRemain = alarm.nMax - nSetAlarm;
    
    // Form on, info off and set numbers
    dojo.style("alarmAddDefinition", "display", "");
    dojo.style("alarmAddInfo", "display", "none");
    dojo.byId("alarmNumberSet").innerHTML = nSetAlarm;
    dojo.byId("alarmNumberTotal").innerHTML = alarm.nMax;
    dijit.byId("alarmAlarmPrice").setValue("");
    
    // Show the daily high/low message only if these are present
    if (alarm.dailyLowPrice == "" || alarm.dailyHighPrice == "")
		dojo.style("alarmModifyIfHighLow", "display", "none");
	else
		dojo.style("alarmModifyIfHighLow", "display", "");
		
    if (nSetAlarm == 1) {
            dojo.style("alarmStatusSingular", "display", "");
            dojo.style("alarmStatusPlural", "display", "none");
    } else {
            dojo.style("alarmStatusSingular", "display", "none");
            dojo.style("alarmStatusPlural", "display", "");            
    }
    
    if (nRemain > 0) {
    
    	// fill in data on the form display
    	dojo.style("alarmAddMessage", "display", "");
    	dojo.style("alarmNoAddMessage", "display", "none");
    	dojo.style("alarmOKButtonRow", "display", "none");
    	dojo.byId("alarmValorSymbol").innerHTML = alarm.valorSymbol;
    	dojo.byId("alarmShortName").innerHTML = alarm.shortName;
    	dojo.byId("alarmOrigPrice").innerHTML = alarm.origPrice;
    	dojo.byId("alarmDailyLowPrice").innerHTML = alarm.dailyLowPrice;
    	dojo.byId("alarmDailyHighPrice").innerHTML = alarm.dailyHighPrice;
    	if (alarm.portalSegment == "IN") {
    		dojo.byId("alarmCurrency_A").innerHTML = "";
    		dojo.byId("alarmCurrency_B").innerHTML = "";
    	}
    	else {
    		dojo.byId("alarmCurrency_A").innerHTML = alarm.currency + " ";
    		dojo.byId("alarmCurrency_B").innerHTML = alarm.currency + " ";
    	}
    }
    else {
    	// replace form with error message
    	dojo.style("alarmAddMessage", "display", "none");
    	dojo.style("alarmNoAddMessage", "display", "");
    	dojo.style("alarmAddTitleRow", "display", "none");
    	dojo.style("alarmAddDataRow", "display", "none");
    	dojo.style("alarmAddCancelButtonRow", "display", "none");
    	showOKButton("alarmOKButton");
    }
    dijit.byId("alarmAddDialog").show();
}

// Set up the modify alarm layer for user input
function initAlarmModify() {
	var alarm = dojo.byId('alarmModifyDialog').alarmData;

	var greaterThan = "greater than";
	var lessThan = "less than";
	var textRising = "rising";
	var textFalling = "falling";
	if (alarm.lang == "de") {
		greaterThan = "grösser als";
		lessThan = "kleiner als";
		textRising = "steigende";
		textFalling = "fallende";	
	}
	if (alarm.lang == "fr") {
		greaterThan = "supérieur à";
		lessThan = "inférieur à";
		textRising = "la hausse";
		textFalling = "la baisse";	
	}

    // Form on, info off and set numbers
    dojo.style("alarmModifyDefinition", "display", "");
    dojo.style("alarmModifyInfo", "display", "none");
    dijit.byId("alarmModifyPrice").setValue("");
    
    // If dailyHigh|Low are empty, set to origPrice
    if (alarm.dailyHighPrice == "")
    	alarm.dailyHighPrice = alarm.origPrice;
    if (alarm.dailyLowPrice == "")
    	alarm.dailyLowPrice = alarm.origPrice;
    
    if (alarm.alarmDirection == "RISING") {
    	dojo.byId("alarmGTorLT").innerHTML = greaterThan;
    	dojo.byId("alarmLimitPrice").innerHTML = alarm.dailyHighPrice;
	    dojo.byId("alarmDirectionSpan").innerHTML = textRising;
	    if (alarm.dailyHighPrice == "")
		    dojo.style("alarmModifyIfHighLow", "display", "none");
    }
    else if (alarm.alarmDirection == "FALLING") {
    	dojo.byId("alarmGTorLT").innerHTML = lessThan;
    	dojo.byId("alarmLimitPrice").innerHTML = alarm.dailyLowPrice;
	    dojo.byId("alarmDirectionSpan").innerHTML = textFalling;
	    if (alarm.dailyLowPrice == "")
		    dojo.style("alarmModifyIfHighLow", "display", "none");
    }
    
    // fill in data on the form display
    dojo.style("alarmModifyMessage", "display", "");
    dojo.style("alarmModifyOKButtonRow", "display", "none");
    dojo.byId("alarmModifyValorSymbol").innerHTML = alarm.valorSymbol;
    dojo.byId("alarmModifyShortName").innerHTML = alarm.shortName;
    dojo.byId("alarmModifyOrigPrice").innerHTML = alarm.origPrice;
   	if (alarm.portalSegment == "IN") {
   		dojo.byId("alarmModifyCurrency_A").innerHTML = "";
   		dojo.byId("alarmModifyCurrency_B").innerHTML = "";
   	}
   	else {
   		dojo.byId("alarmModifyCurrency_A").innerHTML = alarm.currency + " ";
   		dojo.byId("alarmModifyCurrency_B").innerHTML = alarm.currency + " ";
   	}
    dijit.byId("alarmModifyDialog").show();
}

// Called when user clicks the submit button from add alarm form
function alarmAdd() {
    var alarm = dojo.byId("alarmAddDialog").alarmData;
    var alarmPrice = dojo.byId('alarmAlarmPrice').value;
    var targetURL = alarmAddURL + alarm.lang + ".json?SecurityId=" + alarm.securityId +
    	"&OrigPrice=" + alarm.origPrice + "&AlarmPrice=" + alarmPrice;
    
    // Form off, Info panel on
    dojo.style("alarmAddDefinition", "display", "none");
    dojo.style("alarmAddInfoOKButtonRow", "display", "none");
    switchBeforeOnAfterOff("alarmAddInfo");
        
    // Bring area back (in case it was faded previously)
    dojo.style("alarmAddInfo", "opacity", 1);
    dojo.style("alarmAddInfo", "display", "");
    
    // Check that alarm price is outside daily high/low
    var priceInDailyHL = "Cannot add alarm: price is inside the daily high/low range";
    if (alarm.lang == "de")
    	priceInDailyHL = "Alarm kann nicht erstellt werden: Preis ist innerhalb der Spanne zwischen Tageshoch/Tagestief";
    if (alarm.lang == "fr")
    	priceInDailyHL = "Le prix étant situé dans la fourchette comprise entre le cours du jour le plus élevé et le plus bas, l'alarme ne peut être installée.";
    if ((parseFloat(alarmPrice) <= parseFloat(alarm.dailyHighPrice)) &&
    	(parseFloat(alarmPrice) >= parseFloat(alarm.dailyLowPrice))) {
    	reportProblem("alarmAdd", priceInDailyHL);
    	return false;
    }
    
    // Make a request to the XSP that adds the alarm entry
    dojo.xhrGet( {
        url: targetURL,
        handleAs: "json-comment-filtered",
        timeout: 20000,
        
        // If HTTP 200 (successful or "Problem")
        load: function(response, ioArgs) {
                dojo.byId("alarmAddInfoAfterRequest").innerHTML = response.Message;
                switchBeforeOffAfterOn("alarmAddInfo");
                if (response.Message.substring(0,5) == "Probl") {
                
                    // Show button and wait for user
                    showOKButton("alarmAddInfoOKButton");
                }
                else {
	                // Fade out dialog box and finish
                    fadeAway("alarmAddDialog");
                    nSetAlarm = response.nSet;
                }
                // Sometimes (eg after autocomplete) we refresh the page
                if (alarm.isRefresh == "true")
	               	location.reload();
                return response;
            },
            
        // HTTP not OK - report error message and wait for user
        error: function(response, ioArgs) {
       		reportProblem("alarmAdd", response.Message);
        	return response;
        }
    });
}

// Called when user clicks the submit button from modify alarm form
function alarmModify() {
    var alarm = dojo.byId("alarmModifyDialog").alarmData;
    var alarmPrice = dojo.byId('alarmModifyPrice').value;
    var targetURL = alarmAddURL + alarm.lang + ".json?SecurityId=" + alarm.securityId + "&OrigPrice=" + alarm.origPrice +
    	"&AlarmPrice=" + alarmPrice + "&modify=true";
    	
    var wrongTypeRising = "This is a rising alarm - new price must be greater than ";
    var wrongTypeFalling = "This is a falling alarm - new price must be less than ";
    if (alarm.lang == "de") {
    	wrongTypeRising = "Dies ist eine Alarm für steigende Kurse - der neue Preis muss grösser sein als ";
    	wrongTypeFalling = "Dies ist eine Alarm für fallende Kurse - der neue Preis muss kleiner sein als ";
    }
    if (alarm.lang == "fr") {
    	wrongTypeRising = "Ceci est une alerte pour des cours haussiers -  le nouveau prix doit être supérieur à ";
    	wrongTypeFalling = "Ceci est une alerte pour des cours baissiers - le nouveau prix doit être inférieur à ";
    }
    
    // Form off, Info panel on
    dojo.style("alarmModifyDefinition", "display", "none");
    dojo.style("alarmModifyInfoOKButtonRow", "display", "none");
    switchBeforeOnAfterOff("alarmModifyInfo");
        
    // Bring area back (in case it was faded previously)
    dojo.style("alarmModifyInfo", "opacity", 1);
    dojo.style("alarmModifyInfo", "display", "");
    
    // New alarmPrice must correspond to original alarmDirection (ie, you cannot change
    // the alarmDirection).
    if (alarm.alarmDirection == "RISING" &&
    		parseFloat(alarmPrice) < parseFloat(alarm.dailyHighPrice)) {
    	reportProblem("alarmModify", wrongTypeRising + alarm.currency + " " + alarm.dailyHighPrice);
    	return false;
    }
    else if (alarm.alarmDirection == "FALLING" &&
    		parseFloat(alarmPrice) > parseFloat(alarm.dailyLowPrice)) {
    	reportProblem("alarmModify", wrongTypeFalling + alarm.currency + " " + alarm.dailyLowPrice);
    	return false;
    }
    
    // Make a request to the XSP that adds the alarm entry
    dojo.xhrGet( {
        url: targetURL,
        handleAs: "json-comment-filtered",
        timeout: 20000,
        
        // If HTTP 200 (successful or "Problem")
        load: function(response, ioArgs) {
                dojo.byId("alarmModifyInfoAfterRequest").innerHTML = response.Message;
                switchBeforeOffAfterOn("alarmModifyInfo");
                if (response.Message.substring(0,5) == "Probl") {
                
                    // Show button and wait for user
                    showOKButton("alarmModifyInfoOKButton");
                }
                else {
                	// modify alarm price in table and switch icons
                	dojo.byId(alarm.securityId + alarm.alarmDirection + "Price").innerHTML =
                		parseFloat(alarmPrice).toFixed(2);
				    dojo.style(alarm.securityId + alarm.alarmDirection + "Set", "display", "none");
				    dojo.style(alarm.securityId + alarm.alarmDirection + "Unset", "display", "");
                
                	// Fade out dialog box and finish
					fadeAway("alarmModifyDialog");                
                    nSetAlarm = response.nSet;
                }
                return response;
            },
        // HTTP not OK - report error message and wait for user
        error: function(response, ioArgs) {
       		reportProblem("alarmModify", response.Message);
        	return response;
        }
    });
}

// Remove an alarm entry from the DB
function alarmRemove(securityId, alarmDirection, lang) {
    var targetURL = alarmRemoveURL + lang + ".json?SecurityId=" + securityId + "&direction=" + alarmDirection;
    dojo.style("alarmRemoveInfoOKButtonRow", "display", "none");
    switchBeforeOnAfterOff("alarmRemoveInfo");
    dijit.byId("alarmRemoveDialog").show();
    dojo.style("alarmRemoveInfo", "opacity", 1);
    dojo.style("alarmRemoveInfo", "display", "");
    
    // Make a request to the XSP that handles the alarm entry removal
    dojo.xhrGet( {
        url: targetURL,
        handleAs: "json-comment-filtered",
        timeout: 20000,

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

                    // Show button and wait for user
                    showOKButton("alarmRemoveInfoOKButton");
                }
                else {
               	    // Remove row and possibly segment table
                    dojo.style(securityId + alarmDirection, "display", "none"); // remove row
                    for (i = 0; i < segments.length; i++) {
                    	if (response.nSet[i] == 0) {
                      	  if (dojo.byId("title" + segments[i]))
                      	    dojo.style("title" + segments[i], "display", "none"); // If no alarms left
                      	  if (dojo.byId("table" + segments[i]))                   // for this segment,
                      	    dojo.style("table" + segments[i], "display", "none"); // remove title and table.
                    	}
                    }
                    // Fade out dialog box and finish
					nSetAlarm = response.nSet[0] + response.nSet[1] + response.nSet[2];
                    fadeAway("alarmRemoveDialog");
                }
                return response;
            },
        // HTTP not OK - report error message and wait for user
        error: function(response, ioArgs) {
       		reportProblem("alarmRemove", response.Message);
        	return response;
        }
    });
}

// Make a dialog fade away - usually after completion
// dialogName: id of dialog box, eg "alarmAddDialog"
function fadeAway(dialogName) {
	var fadeDialog = dojo.fadeOut({node: dijit.byId(dialogName).domNode, duration: 2000});
	dojo.connect(fadeDialog, "onEnd", function(){dijit.byId(dialogName).hide();});
	fadeDialog.play();
}

// Report problem, show button and wait for user
// formFunction: functional title of form, eg "alarmAdd"
function reportProblem(formFunction, message) {
	var definitionForm = formFunction + "Definition";
	if (dojo.byId(definitionForm))
		dojo.style(definitionForm, "display", "none");
	dojo.style(formFunction + "Info", "display", "");
    dojo.byId(formFunction + "InfoAfterRequest").innerHTML = message;
    switchBeforeOffAfterOn(formFunction + "Info");
    showOKButton(formFunction + "InfoOKButton");
    dijit.byId(formFunction + "Dialog").show();
}

// Show OK button (if error or Problem)
function showOKButton(buttonRoot) {
    dojo.style(buttonRoot+"Row", "display", "");
    dijit.byId(buttonRoot).setDisabled(false);
}

// Switch visibility from BeforeRequest to AfterRequest
function switchBeforeOffAfterOn(elementRoot) {
    dojo.style(elementRoot+"BeforeRequest", "display", "none");
    dojo.style(elementRoot+"AfterRequest", "display", "");
}

// Switch visibility from AfterRequest to BeforeRequest
function switchBeforeOnAfterOff(elementRoot) {
    dojo.style(elementRoot+"BeforeRequest", "display", "");
    dojo.style(elementRoot+"AfterRequest", "display", "none");
}

