/*
 * ajax-actions.js
 *
 * Copyright Rubicon Systems Pty. Ltd.
 *
 * High-level wrapper class for Ajax functions.
 *
 * $Log: ajax-actions.js,v $
 * Revision 1.7  2009/12/29 02:20:55  markk
 * NEW - bug 586: Water statement is not thread safe
 * http://murray/bugzilla/show_bug.cgi?id=586
 *
 * Make report thread safe for use on the web
 *
 * Revision 1.6  2009/11/11 07:48:26  markk
 * Fixes for error handling in ajax calls
 *
 * Revision 1.5  2009/11/11 06:07:41  markk
 * Fix for error handling in ajax calls
 *
 * Revision 1.4  2009/06/03 00:40:28  markk
 * Add support for logon message provider
 *
 * Revision 1.3  2009/05/01 00:38:05  markk
 * Update focus after date picker closes
 *
 * Revision 1.2  2008/10/29 03:36:25  timm
 * Modified Service combobox code to initially display a blank entry (WP-19).
 *
 * Revision 1.1  2008/02/04 02:48:19  timm
 * Initial revision.
 *
 */

AjaxActions = Class.create();

Object.extend(AjaxActions,
{
    ACTION_GET_DETAILS_FOR_SP: "getDetailsForSP",
    ACTION_GET_DETAILS_FOR_SERVICE: "getDetailsForService",
    ACTION_GET_SERVICES_BY_SP_AND_PARTY: "getServicesBySPandParty",
    ACTION_GET_CROP_TYPES_FOR_SP: "getCropTypesForSPandService",
    ACTION_GET_METER_READING_HISTORY: "getMeterReadingHistory",
    ACTION_GET_STANDARD_ORDER_DETAILS: "getStandardOrderDetails",
    ACTION_GET_CROPS_FOR_PROPERTY: "getCropsForProperty",
    ACTION_GET_LOGON_MESSAGE: "getLogonMessage",
    ACTION_GET_REPORT_STATUS: "getReportStatus",
    
    updateServicesByServicePoint: function(loadingElement, targetDiv, servicePoint, repeatCountRow,
            repeatOffsetRow, repeatCountField, repeatOffsetField, complete)
    {
        Ajax.loadAndExecute(loadingElement, 
            {action: this.ACTION_GET_DETAILS_FOR_SP, servicePoint: servicePoint},
            function(response)
            {
                // If necessary, unregister previous event listeners
                if ($('service'))
                {
                    $('service').stopObserving('change', complete);
                    $('service').stopObserving('keyup', complete);
                }
                
                // If we had more than one result, create a combobox
                if (response.services.length > 1)
                {
                    var content = "<select name=\"service\" id=\"service\">\n";
                    
                    for (i=0; i<response.services.length; i++)
                        content += "<option value=\"" + response.services[i].objectNo +
                            "\">" + response.services[i].objectName + "</option>\n";
                                    
                    content += "</select>";
                    
                    $(targetDiv).update(content);
                    
                    // Now set an event listener, to track any selection changes
                    $('service').observe('change', complete);
                    $('service').observe('keyup', complete);
                }
                // Otherwise, for a single result, just display the label
                else if (response.services.length == 1)
                {
                    $(targetDiv).update(response.services[0].objectName +
                        " <input type=\"hidden\" name=\"service\" value=\"" +
                        response.services[0].objectNo + "\" id=\"service\" />");
                }
                else
                {
                    $(targetDiv).update("Error!");
                }
                
                // If repeating orders are enabled, show the input fields
                if ((repeatCountRow != null) && (repeatOffsetRow != null) &&
                        (repeatCountField != null) &&
                        (repeatOffsetField != null))
                {
                    if (response.repeat)
                    {
                        if (Prototype.Browser.IE)
                        {
                            $(repeatCountRow).setStyle({
                                display: "block"
                            });
                            $(repeatOffsetRow).setStyle({
                                display: "block"
                            });
                        }
                        else
                        {
                            $(repeatCountRow).setStyle({
                                display: "table-row"
                            });
                            $(repeatOffsetRow).setStyle({
                                display: "table-row"
                            });
                        }
                    }
                    else
                    {
                        $(repeatCountRow).setStyle({
                                display: "none"
                        });
                        $(repeatOffsetRow).setStyle({
                                display: "none"
                        });
                        $(repeatCountField).setValue("");
                        $(repeatOffsetField).setValue("");
                    }
                }
                
                // When we're done, fire off the callback
                if (complete)
                    complete(null, response.minFlow, response.maxFlow);
            });
    },
    
    /** Get the associated details for a Service Point. */
    getServicePointDetails: function(loadingElement, servicePoint, callback)
    {
        Ajax.loadAndExecute(loadingElement, 
            {
                action: this.ACTION_GET_DETAILS_FOR_SP,
                servicePoint: servicePoint
            },
            callback);
    },
    
    /** Get the associated details for a Service. */
    getServiceDetails: function(loadingElement, servicePoint, service, callback, errorCallback)
    {
        Ajax.loadAndExecute(loadingElement,
				            {action: this.ACTION_GET_DETAILS_FOR_SERVICE, servicePoint: servicePoint, service: service},
				            callback, 
				            errorCallback);
    },
    
    /** Get the associated details for a Standard Order. */
    getStandardOrderDetails: function(loadingElement, standardFlowNo, callback)
    {
        Ajax.loadAndExecute(loadingElement,
            {action: this.ACTION_GET_STANDARD_ORDER_DETAILS, standardFlowNo: standardFlowNo},
            callback);
    },
    
    getLogonMessage: function(loadingElement, callbackSuccess, callbackFailure)
    {
    	Ajax.loadAndExecute(loadingElement,
        		{action: this.ACTION_GET_LOGON_MESSAGE},
        		callbackSuccess,
        		callbackFailure);
    },
    
    getReportStatus: function(theUuid, callbackSuccess, callbackFailure)
    {
    	Ajax.loadAndExecute(null,
        		{action: this.ACTION_GET_REPORT_STATUS, uuid: theUuid},
        		callbackSuccess,
        		callbackFailure);
    },
    
    getCropsForProperty: function(loadingElement, service, startDate, callbackSuccess, callbackFailure)
    {
    	Ajax.loadAndExecute(loadingElement,
    		{action: this.ACTION_GET_CROPS_FOR_PROPERTY, service: service, startDate: startDate},
    		callbackSuccess,
    		callbackFailure);
    },
    
    /** Get the meter readings for a Service Point.
     * 
     * @param {Object} loadingElement	Body element which should be used to display the AJAX loading state.
     * @param {Object} servicePoint		object_no of the Service Point to load readings for.
     * @param {Object} callback			Function to call once AJAX call successfully returns.
     */
    getMeterReadingHistory: function(loadingElement, servicePoint, callback)
    {
        Ajax.loadAndExecute(loadingElement,
            {action: this.ACTION_GET_METER_READING_HISTORY, servicePoint: servicePoint},
            callback);
    },
    
    generateServiceSelection: function(data, serviceContainer, serviceCallback, preSelect)
    {
        // If necessary, unregister previous event listeners
        if ($('service') && serviceCallback)
        {
                $('service').stopObserving('change', serviceCallback);
                $('service').stopObserving('keyup', serviceCallback);
        }
        
        // If we had more than one result, create a combobox
        if (data.services.length > 1)
        {
            var content = "<select name=\"service\" id=\"service\">\n";
            
            content += "<option value=\"-1\"";
            if (!preSelect)
                content += " selected=\"true\"";
            content += ">- Please Select -</option>";
            
            for (i = 0; i < data.services.length; i++) 
            {
                content += "<option value=\"" + data.services[i].objectNo + "\"";
                
                if (preSelect && (data.services[i].objectNo == preSelect))
                    content += " selected=\"true\"";
                
                content += ">" + data.services[i].objectName + "</option>\n";
            }
                            
            content += "</select>";
            
            $(serviceContainer).update(content);
            
            // Now set an event listener, to track any selection changes
            if (serviceCallback) 
            {
                $('service').observe('change', serviceCallback);
                $('service').observe('keyup', serviceCallback);
            }
        }
        // Otherwise, for a single result, just display the label
        else if (data.services.length == 1)
        {
            $(serviceContainer).update(data.services[0].objectName +
                " <input type=\"hidden\" name=\"service\" value=\"" +
                data.services[0].objectNo + "\" id=\"service\" />");
        }
        else
        {
            $(serviceContainer).update("Error!");
        }
    },
    
    generateCropTypeSelection: function(data, parentDiv, labelDiv, contentDiv, preSelect)
    {
        if (data.noCrop || !data.cropTypes)
        {
            $(parentDiv).hide();
            $(contentDiv).update("");
        }
        else if (data.cropTypes.length == 1)
        {
        	var singleContent = "<b>" + data.cropTypes[0].label + "</b>" +
            " <input type=\"hidden\" name=\"crop-type\" value=\"" + data.cropTypes[0].value + "\" id=\"crop-type\" />";
        	
        	$(labelDiv).update(data.cropTitle);
        	$(contentDiv).update(singleContent);
            
            $(parentDiv).show();
        }
        else if (data.cropTypes.length > 1)
        {
            var content = "<select name=\"crop-type\" id=\"crop-type\">\n";
            
            for (i = 0; i < data.cropTypes.length; i++) 
            {
                content += "<option value=\"" + data.cropTypes[i].value + "\"";
                
                if (preSelect && (data.cropTypes[i].value == preSelect))
                    content += " selected=\"true\"";
                
                content += ">" + data.cropTypes[i].label + "</option>\n";
            }
                            
            content += "</select>";
            
            $(labelDiv).update(data.cropTitle);
            $(contentDiv).update(content);
            
            $(parentDiv).show();
        }
        else
        {
            $(contentDiv).update("Error!");
            
            return;
        }
    },
    
    updateServiceDetails: function(loadingElement, parentDiv, labelDiv,
            contentDiv, areaIrrRow, areaIrrCell, hourField, minuteField,
            servicePoint, service, complete)
    {
        Ajax.loadAndExecute(loadingElement, 
            {
                action: this.ACTION_GET_DETAILS_FOR_SERVICE,
                servicePoint: servicePoint, service: service
            },
            function(response)
            {
                if (response.nocrop)
                {
                    $(parentDiv).setStyle({display: "none"});
                    $(contentDiv).update("");
                }
                else if (response.data.length == 1)
                {
                    $(labelDiv).update(response.title);
                    $(contentDiv).update(response.data[0].label +
                        " <input type=\"hidden\" name=\"crop-type\" value=\"" +
                        response.data[0].value + "\" id=\"crop-type\" />");
                    
                    if (Prototype.Browser.IE)
                        $(parentDiv).setStyle({display: "block"});
                    else
                        $(parentDiv).setStyle({display: "table-row"});
                }
                else if (response.data.length > 1)
                {
                    var content = "<select name=\"crop-type\" id=\"crop-type\">\n";
                    
                    for (i=0; i<response.data.length; i++)
                        content += "<option value=\"" + response.data[i].value +
                            "\">" + response.data[i].label + "</option>\n";
                                    
                    content += "</select>";
                    
                    $(labelDiv).update(response.title);
                    $(contentDiv).update(content);
                    
                    if (Prototype.Browser.IE)
                        $(parentDiv).setStyle({display: "block"});
                    else
                        $(parentDiv).setStyle({display: "table-row"});
                }
                else
                {
                    $(contentDiv).update("Error!");
                    
                    return;
                }
                
                if (response.areaIrrigated)
                {
                    $(areaIrrCell).update("<input type=\"text\" name=\"area-irrigated\" " +
                        "id=\"area-irrigated\" size=\"5\" />");
                    if (Prototype.Browser.IE)
                        $(areaIrrRow).setStyle({display: "block"});
                    else
                        $(areaIrrRow).setStyle({display: "table-row"});
                }
                else
                {
                    $(areaIrrRow).setStyle({display: "none"});
                    $(areaIrrCell).update("");
                }
                
                // Enable/disable the start time where appropriate
                if ((hourField != null) && (minuteField != null))
                {
                    if (response.changeStartTime)
                    {
                        $(hourField).enable();
                        $(minuteField).enable();
                    }
                    else
                    {
                        $(hourField).disable();
                        $(minuteField).disable();
                    }
                    
                    // Set the default start time if necessary
                    if (response.defaultStartHour != "undefined")
                        $(hourField).setValue(response.defaultStartHour);
                    if (response.defaultStartMinute != "undefined")
                        $(minuteField).setValue(response.defaultStartMinute);
                }
                
                if (complete)
                    complete();
            });
    },
    
    updateCropTypeBySPandService: function(loadingElement, parentDiv, labelDiv, contentDiv, areaIrrRow,
                                                                               areaIrrCell, servicePoint, service, complete)
    {
        Ajax.loadAndExecute(loadingElement, 
            {
                action: this.ACTION_GET_CROP_TYPES_FOR_SP,
                servicePoint: servicePoint,
                service: service
            },
            function(response)
            {
                if (response.nocrop)
                {
                    $(parentDiv).setStyle({display: "none"});
                    $(contentDiv).update("");
                }
                else if (response.data.length == 1)
                {
                    $(labelDiv).update(response.title);
                    $(contentDiv).update(response.data[0].label +
                        " <input type=\"hidden\" name=\"crop-type\" value=\"" +
                        response.data[0].value + "\" id=\"crop-type\" />");
                    
                    if (Prototype.Browser.IE)
                        $(parentDiv).setStyle({display: "block"});
                    else
                        $(parentDiv).setStyle({display: "table-row"});
                }
                else if (response.data.length > 1)
                {
                    var content = "<select name=\"crop-type\" id=\"crop-type\">\n";
                    
                    for (i=0; i<response.data.length; i++)
                        content += "<option value=\"" + response.data[i].value +
                            "\">" + response.data[i].label + "</option>\n";
                                    
                    content += "</select>";
                    
                    $(labelDiv).update(response.title);
                    $(contentDiv).update(content);
                    
                    if (Prototype.Browser.IE)
                        $(parentDiv).setStyle({display: "block"});
                    else
                        $(parentDiv).setStyle({display: "table-row"});
                }
                else
                {
                    $(contentDiv).update("Error!");
                    
                    return;
                }
                
                if (response.areaIrrigated)
                {
                    $(areaIrrCell).update("<input type=\"text\" name=\"area-irrigated\" " +
                        "id=\"area-irrigated\" size=\"5\" />");
                    if (Prototype.Browser.IE)
                        $(areaIrrRow).setStyle({display: "block"});
                    else
                        $(areaIrrRow).setStyle({display: "table-row"});
                }
                else
                {
                    $(areaIrrRow).setStyle({display: "none"});
                    $(areaIrrCell).update("");
                }
                
                if (complete)
                    complete();
            });
    }
});
