/// <reference path="~/Scripts/Intellisense/jquery-1.3.2.js" />
Ext.namespace('Zapproved');
/**
 * Error Dialog
 * description goes here
 * Copyright 2008 Zapproved  
 */

Zapproved.ErrorDialog = Ext.extend(Ext.Window, {

    // error code constants
    AUTHORIZATION_REMOVED_MSG : 'Access to this proposal is no longer permitted.  This may be because the list of Approvers on this proposal has changed.',
    MISSING_PARAMETER_MSG : 'Missing parameter expected by server: {0}',  
    INVALID_PARAMETER_MSG : 'Invalid parameter expected by server: {0}',  
    PAYMENT_FAILED_MSG : 'Payment processing failed.  Please check your payment information and ensure that the name matches the name on your credit card then try again.', 
    UNKNOWN_CODE_MSG : 'Unknown error code: ',
    ALREADY_TAKEN_MSG : 'This email address already has a Zapproved account.  Click Welcome in the menu above to go to the home page, you can login using the fields in the top-right corner of the screen.',
    TOKEN_USED_MSG: 'This account has already been confirmed.  If you have forgotten your password, use the Reset Password feature.',
    ARCHIVE_EXPIRED_MSG: 'Access to this proposal has expired. Please upgrade to a paid account for access to all archived proposals.',
    PROPOSAL_LIMIT_EXCEEDED_MSG: 'You have exceeded the number of proposals you are allowed to send (currently 5/month). Your proposal has been saved as a draft. Please upgrade to a paid account to send more proposals immediately.',
    NOT_AUTHORIZED_MSG: 'You are not currently authorized to perform this action. Please contact support@legalholdpro.com for assistance.',

    // ext configs
    layout:'fit',
    width:400,
    autoHeight:true,
    closable: true,
    resizable: false,
    draggable: false,
    border:false,
    bodyBorder:false,
    plain:true,
    buttonAlign:'center',
    title:'<span class="error-text">Error</span>',
    modal:true
    
    // overrideable text strings
    ,timeoutMessage: 'The server took too long to respond or you are disconnected from the internet.  Please try again in a few minutes.'
    ,serverErrorMessage: 'An error occurred while processing your request.'
    ,serverStatusCodeMessage: '<b>Server Response:</b></br>The server returned response code {0} with message: {1} <br/><br/><b>Response Headers:</b><br/>{2}'
    ,serverInvalidResponseMessage: '<b>Server Response:</b></br>The server returned an unexpected response: {0} <br/><br/><b>Response Headers:</b><br/>{1}'

    
    ,initComponent: function() {
   
    	Ext.apply(this, {
	    	buttons:[{
		        text:'Close',
		        scope:this,
		        handler : function() { 
		            this.hide(); 
		            if (this.redirectUrl) window.location.pathname = this.redirectUrl;
		        }  
		    }]
    	});
    	
    	Zapproved.ErrorDialog.superclass.initComponent.apply(this, arguments);
    	
    } // end initComponent
    
    // public - message can be a single string or an array of strings, subject is not required but message is
    ,showError : function(subject, message) {
    	this.addSimpleErrorPanel(subject, message);
    	this.show();
    }
    
    // public - error code will be translated
    ,showErrorCode : function(subject, errorCode, messageValues) {
        var msg = this.translateCode(errorCode);
        if (messageValues && messageValues.length > 0) {
            //TODO: handle multiple values
            msg = String.format(msg, messageValues[0]);
        }
    	this.addSimpleErrorPanel(subject, msg);
    	this.show();
    }
    
    // public - message can be a single string or an array of strings, subject is not required but message is
    ,showErrorWithDetails : function(subject, message, details) {
    	this.addUnexpectedErrorPanel(subject, message, details);
    	this.show();
    }
    
    // public - automatically generates message from passed httpResponse, subject and response are required but result is optional
    ,showServerError : function(subject, response, result) {
    
        if (!response.responseText && !response.status) { 
 	        //this.showError(subject, this.timeoutMessage); 
 	        // this is assumed to be a timeout but it is not currently distinguishable from a user nav-away during TX
 	    } else if (response.status == 200) {
 	        if (result && result.errorCode) {
                this.showErrorCode(subject, result.errorCode, [ result.data ]);
            } else if (result && result.data) {
                //TODO: remove the line below, it is only needed because the server validation doesn't return an errorCode in every case, but it will in the future
                this.showError(subject, result.data);
            } else if (result && result.errors) { 
                // this is old style service result, shouldn't be needed once server refactor done
                this.showErrorCode(subject, result.errors[0].error, [ result.data || result.errors[0].id ]);
            } else {
                // this should never happen, server returned 200/OK but success=false and no message
                this.showErrorWithDetails(subject, this.serverErrorMessage, String.format(this.serverInvalidResponseMessage, response.responseText, response.getAllResponseHeaders)); 
            }
       
        } else {
            this.showErrorWithDetails(subject, this.serverErrorMessage, String.format(this.serverStatusCodeMessage, response.status, response.statusText, response.getAllResponseHeaders));
        }
    }
    
    // shows all errors for the passed form, you should only call this if it is a 'client' error
    // IMPORTANT:  requires that all fields in the form have msgTarget = 'qtip' (the default)
    ,showFormError : function(subject, form) {
	    // loop through all fields and collect messages from any fields that failed validation
        var msgCount = 0;
        var messages = new Array();
        for (i=0; i<form.items.items.length; i++) {
            var field = form.items.items[i];
            if (field.isValid && !field.isValid()) {
                // found an invalid item
                var fieldName = Ext.util.Format.stripTags(field.fieldLabel);
                messages[msgCount] = '<b>' + fieldName + ":</b> " + field.el.dom.qtip;
                msgCount++;
            }
        }
        this.showError(subject, messages);
    }
    
    ,showUnexpectedExceptionError : function(exception) {
    	var friendlyMessage = 'An error occurred while processing your request.';
    	var detailsMessage = 'Exception message: ' + exception;
    	//TODO: this is not called currently.
    }
    
    ,translateCode : function(errorCode) {
        if (errorCode == 'AuthorizationRemoved') {
            return this.AUTHORIZATION_REMOVED_MSG;
        } else if (errorCode == 'MissingParameter') {
            return this.MISSING_PARAMETER_MSG;
        } else if (errorCode == 'InvalidParameter') {
            return this.INVALID_PARAMETER_MSG;
        } else if (errorCode == 'PaymentFailed') {
            return this.PAYMENT_FAILED_MSG;
        } else if (errorCode == 'AlreadyTaken') {
            return this.ALREADY_TAKEN_MSG;
        } else if (errorCode == 'TokenUsed') {
            return this.TOKEN_USED_MSG;
        } else if (errorCode == 'ArchiveExpired') {
            return this.ARCHIVE_EXPIRED_MSG;
        } else if (errorCode == 'NotAuthorized') {
            return this.NOT_AUTHORIZED_MSG;
        } else if (errorCode == 'ProposalLimitExceeded') {
            return this.PROPOSAL_LIMIT_EXCEEDED_MSG;
        } else {
            return this.UNKNOWN_CODE_MSG + errorCode;
        }
    }
    
    ,buildMessageSubject : function(subject) {
        if (!subject || subject.length == 0) return '';
        return '<b>' + subject + ':</b></br>';
    }
    
    ,buildMessageList : function(messages) {
    	var html = '<ul style="margin-left:15px;list-style-type: disc">';
    	
    	if (messages instanceof Array) {
	    	for (i=0;i<messages.length;i++) {
	    		html += '<li>' + messages[i] + '</li>';
	    	}
    	} else {
    		html += '<li>' + messages + '</li>';
    	}
    	html += '</ul>';
    	return html;
    }

    
    // error message(s) with bullets
    ,addSimpleErrorPanel : function(subject, message) {

    	this.add(
    		new Ext.Panel({
	            frame : true,
	            border : false,
	            autoHeight : true,
	            html: '<div style="padding-bottom: 5px">' + this.buildMessageSubject(subject) + '</div><div class="ext-mb-icon" style="float: left"><img src="/Images/default/window/icon-error.gif" border="0"/></div><div class="ext-mb-content" style="margin-left: 50px; margin-top: 5px"><span class="ext-mb-text">' + this.buildMessageList(message) + '</span></div>'
	    	})
	    );
    }
    
    // unexpected errors get an initially-colapsesd error details section in addition to
    // the basic error message panel
    ,addUnexpectedErrorPanel : function(subject, friendlyMessage, detailsMessage) {
    	
    	this.add(
    		new Ext.Panel({
	            frame : true,
	            border : false,
	            autoHeight : true,
	            html: this.buildMessageSubject(subject) + this.buildMessageList(friendlyMessage)
	    	})
	    );
	    
	    this.add(
    		new Ext.Panel({
	            frame:true,
	            border:false, 
	            collapsed : true,
	            collapsible : true,
	            title : 'Error Details',
	            html:detailsMessage
	    	})
	    );
    }
    
});
 
Ext.reg('errordialog', Zapproved.ErrorDialog);

Zapproved.ErrorDialog.msg = function(subject, message) {
    var errorDialog = new Zapproved.ErrorDialog();
    errorDialog.showError(subject, message);
}

Zapproved.ErrorDialog.fromErrorCode = function (subject, errorCode, messageValues) {
    var errorDialog = new Zapproved.ErrorDialog();
	errorDialog.showErrorCode(subject, errorCode, messageValues);
}

Zapproved.ErrorDialog.fromServerError = function (subject, response, result) {
    var errorDialog = new Zapproved.ErrorDialog();
	errorDialog.showServerError(subject, response, result);
}

Zapproved.ErrorDialog.fromForm = function (subject, form) {
    var errorDialog = new Zapproved.ErrorDialog();
	errorDialog.showFormError(subject, form);
}
