﻿/* Interaction controller contains and controls the UI (except the map view) */

com.timmons.srl.InteractionManager = function() {

    //Declare private properties here
    var _stopNavAwayAlert = false;
    var _myAlexUserJson = null;
    
    var _mapManager;   // Object that manages communication to/from the map for the map request location step
    var _dataManager;  // Object that manages data transfer to and from the server
    var _stateManager; // Object that manages the state of the application (stores form data)
    var _qaList;       // Object that manages the question and answers aspect of the describe the request step
    var questionsPresented = false;

    var _requestTypeSelected; // bool to indicate if the request type has been identified (true/false)
    var _requestTypeMethod;   // string to indicate which method was used to find the request type ("Search","Department","All")
    var _problemTypesAz;      // JSON array of problem/request type objects for the All Request Types (A-Z) method in the identify request type step
    var _problemTypesSearch;  // JSON array of problem/request type objects for the Search method in the identify request type step
    var _problemTypesDept;    // JSON array of problem/request type objects for the By Department method in the identify request type step
    var _fileUploadPath;      // Used to store the path/directory to any files uploaded by the user

   // var _rlProblemLeaf;         //JSON array of RLPROBLEMLEAF / RLLINKSPROBLEMLEAF type objects for problemsId passed in
   // var _rlQuestionAnswer;      //JSON array of RLQUESTIONANSWER / RLLINKSQUESTIONANSWER type objects for answerId passed in

    var _isRequestStarted;               // bool to indicate if a request has been started and is in progress (true/false)
    var _isRequestTypeStepInitialized;   // bool to indicate if the identify the request type step has been initialized (true/false)
    var _isMapInitialized;               // bool to indicate if the map the request location type step has been initialized (true/false)
    var _isContactInfoStepInitialized;   // bool to indicate if the map the enter contact information step has been initialized (true/false)
    var _isContactInfoRequired;          // bool to indicate if the contact information is required to be filled out (initialized by web.cofig)
    var _isMapLocationRequired;          // bool to indicate if the map the request location step is required
    var _isCancelInfoRequest;            // bool to indicate if the user decided to close/cancel the information request dialog

    var _configurationSettings = null;   // JSON object that contains configurable settings/options for the application (i.e. map settings, file upload, etc.)

    /*
     *  Need to build out the ability to start a request using a remote link.
     *  I'll use a URL parameter to make this happen.
     *  http://localhost/Request.asmx?problemsId=605
     *
     *  _requestUrlHandler is called after _getDefaultSettingsComplete (below)
     *  I wanted to make sure _requestUrlHandler executes only after everything is done
     *  _requestUrlHandler calls _newRequest
     *
     */
     var _problemsIdFromLink;
     var _cleanUrl;
     
    // Private methods

    /**
    Initialize all variables, build widgets, and bind element events           
    */
    var _initialize = function(mapManager, dataManager, configurationSettings) {
        _cleanUrl = $(location).attr('protocol') + '//' + $(location).attr('host') + $(location).attr('pathname');
        
        _mapManager = mapManager;
        _dataManager = dataManager;
        _configurationSettings = configurationSettings; //nvs 20090915            
        _stateManager = new com.timmons.srl.stateManager();
        _stateManager.initialize();
        _isRequestStarted = false;
        _isRequestTypeStepInitialized = false;
        _isContactInfoStepInitialized = false;
        _isMapInitialized = false;
        _initializePage();
        
        //These are Info and/or Link panels in Describe Request Step
        $('srlProblemLeafInfo').hide();
        $('#srlAnswerInfoLinks').html('');
        $('srlAnswerInfoLinks').hide();
        $('#UseMapLocation').hide();  //Turn this on only if the user has located an address
        
    };

    $.extend({
          getUrlVars: function(){
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for(var i = 0; i < hashes.length; i++)
            {
              hash = hashes[i].split('=');
              vars.push(hash[0]);
              vars[hash[0]] = hash[1];
            }
            return vars;
          },
          getUrlVar: function(name){
            return $.getUrlVars()[name];
          }
        });

    var _navAwayProtection = function() {
        
        window.onbeforeunload = confirmBrowseAway;

        function confirmBrowseAway()
        {
            var workIsDone = false;
            if(_isRequestStarted){
                if (!workIsDone) {
                    return "If you leave this page now, your work will NOT be saved!";
                }
            }
        }
    };

    /**
    Initialze page elements
    */
    var _initializePage = function() {
        _comptibilityCheck();
        _initializePageLoading();
        _showPageLoading();

        _initializeCoreApp();
        _initializeSteps();
        
        _navAwayProtection();
        
        if(userJsonClientId){
            JSON.parse($('#' + userJsonClientId).val());
        }

                
    };

    /**
    Checks to make sure internet exploreris not verion 6.0
    */
    var _comptibilityCheck = function() {
        if ($.browser.msie == true) {
            if ($.browser.version < 7.0) {
                alert("We see that you are using Internet Explorer 6 or earlier. The site you are loading contains enhanced functionality that is not compatible with Internet Explorer 6. Click OK to upgrade to the latest Internet Explorer version. The site is compatible with Internet Explorer 7 and 8, Mozilla Firefox 3 and 3.5, and Safari 3 and 4.");
                window.location = "http://www.microsoft.com/windows/Internet-explorer/default.aspx";
            }
        }
    };

    /**
    Initialize core application including but not limited to buttons (start a new request, cancel, etc.), 
    default application settings, etc.
    */
    var _initializeCoreApp = function() {

        $('#srlMainWrapper a').live("click", function() {

            if ($(this).attr('href') == '#') return false;
        });
        
        
        $("#PrintTester").click(function(){
            $("#srlIdentify").printArea( {
                    mode:'popup',
                    popHt:600, 
                    popWd:800, 
                    popTitle:'Request Confirmation', 
                    popClose:false,
                    strict:false
                } );
        });
                
        $("#printConfirmationButton").click(function(){
            $("#srlSubmitConfirmation").printArea( {
                    mode:'popup',
                    popHt:600, 
                    popWd:800, 
                    popTitle:'Request Confirmation', 
                    popClose:true
                } );
        });
        
        $('#srlNewRequestButton').click(_newRequestButtonClick);
        $('#srlCancelRequestButton').click(_cancelRequest);
        $('#chkUseMapLocation').click(_checkUseMapInfo);
        _initializeSubmitConfirmation();
        _initializeRequestInfoDialog();
        _dataManager.getDefaultSettings(this._getDefaultSettingsComplete, _getDefaultSettingsComplete);
    };

    var _checkUseMapInfo = function() {
        if ($('#chkUseMapLocation').is(':checked')) {
            _contactInfoFromMap();
        }
        else {
            _clearAddressInformation();
        }
    };

    var _newRequestButtonClick = function() {
        _problemsIdFromLink=null;
        _newRequest()
    }

    var _clearAddressInformation = function() {
        $("#tbxAddress").val("");
        $("#tbxCity").val("");
        //$("#tbxState").val("");
        $("#lbxState").val("");
        $("#tbxZip").val("");
    };

    var _contactInfoFromMap = function() {
        var address = _mapManager.getAddress();
        if (address) {
            if (address.street) $('#tbxAddress').val(address.street);
            if (address.city) $('#tbxCity').val(address.city);
            //if (address.state) $('#tbxState').val(address.state);
            if (address.state) {
                _currentStateValue(address.state);
            }
            if (address.zip) $('#tbxZip').val(address.zip);
        }
    };

    var _currentStateValue = function(stateValue) {
        $("#lbxState option").each(function() {
            if ($(this).val() == stateValue) {
                $('#lbxState').selectmenu('value', $(this)[0].index);
            }
        });
    }


    /**
    Once getting the default application settings is complete we need to initialize the application
    with these settings.
    */
    var _getDefaultSettingsComplete = function(appSettings) {

        _configurationSettings.appSettings = appSettings;

        _initializeConfigurableUI();

        _currentStateValue(_configurationSettings.defaultSate);

        _hidePageLoading(null,_requestUrlHandler,null);
        
       
    };

    /** 
    Initialize any configurable UI elements using the configuration settings
    */
    var _initializeConfigurableUI = function() {

        if (_configurationSettings.appSettings.AllowRequestAttachmentUploads) _initializeFileUpload();
        _configureContactInfo();
    };

    /**
    Configure the Enter Contact Information step.
    */
    var _configureContactInfo = function() {

        // Initialize contact info step based on bool
        _requireContactInformation(_configurationSettings.appSettings.IsContactInfoRequired);
    };

    /**
    Set contact information step to either require contact info or allow anonymous (blank) contact info.
    Enable the next button if contact information is not required.
    */
    var _requireContactInformation = function(isRequired) {
        //Populate the State Selector Dropdown...
        _createStateSelectorDropdown();

        if (isRequired) {

            $('#srlContactInfoIsRequiredText').html('required');
            $('#srlContactInfo .srlInputWrapper label').removeClass('srlOptional');

        } else {

            $('#srlContactInfoIsRequiredText').html('optional');
            if (!$('#srlContactInfo .srlInputWrapper label').hasClass('srlOptional'))
                $('#srlContactInfo .srlInputWrapper label').addClass('srlOptional');
        }

        _checkEnableContactNextStep();
    };

    var _uploadFileAlreadyUploaded = function(fileName){
        var filesArray = _stateManager.getUploadFiles();
        for(var i=0;i!=filesArray.length;i++){
            if(fileName == filesArray[i].fileName){
            return true;
            }
        }
        return false;
    };

    /**
    Initialize File Upload functionality and UI elements. File types/format, total file size, and number of files
    are all configurable in the web.config file.
    */
    var _initializeFileUpload = function() {

        $('#srlUploadWrapper').show();

        var fileTypes = _configurationSettings.appSettings.FileTypes;
        var numFileUploadsAllowed = _configurationSettings.appSettings.RequestAttachmentUploadCount;
        var maxTotalFileSizeAllowed = _configurationSettings.appSettings.CombinedMaxFileUploadSizeKB;
        var currNumFiles = 0;

        // Build file extension string for comparison later
        var fileTypeStr = '';
        var fileTypeAllowedStr = '';

        for (var i = 0; i < fileTypes.length; i++) {

            fileTypeStr += fileTypes[i].extension;
            fileTypeAllowedStr += '.' + fileTypes[i].extension;

            if (i != fileTypes.length - 1) {

                fileTypeStr += '|';
                fileTypeAllowedStr += ', ';
            }
        }

        // Set some text in the html to show which file extensions/formats are allowed, number of files allowed,
        // and total file size allowed
        $('#srlMaxNumUploadFiles').html(' ' + numFileUploadsAllowed + ' files ');
        $('#srlUploadFileTypesAllowed').html('&nbsp;' + fileTypeAllowedStr + '.');

        if ((maxTotalFileSizeAllowed + '').toLowerCase() != "unlimited"){
            
              maxTotalFileSizeAllowed = 'no larger than ' + com.timmons.srl.Utility.readablizeBytes(maxTotalFileSizeAllowed * 1024) + ' combined. ';
            
            }else{
                maxTotalFileSizeAllowed = ' of any size.  ';
            }

        $('#srlMaxSizeUploadFiles').html(maxTotalFileSizeAllowed);


        // Create the ajax file upload object/handler
        new AjaxUpload('#srlUploadButton', {
            action: 'FileUpload/UploadFileHandler.ashx',
            responseType: "json",
            onSubmit: function(file, ext) {

                // Check to see if this upload will exceed the maximum number of files allowed
                // only if there is a limit

                currNumFiles = _stateManager.getUploadFiles().length;

                if (numFileUploadsAllowed != "unlimited") {

                    if (!(currNumFiles < parseInt(numFileUploadsAllowed))) {

                        alert('You may only upload up to ' + numFileUploadsAllowed + ' file(s).');
                        // cancel upload
                        return false;
                    }
                }

                // Check to see the file has an acceptable extension/format

                var patt = new RegExp('^(' + fileTypeStr + ')$');

                if (!(ext && patt.test(ext))) {
                    // extension is not allowed
                    alert('Error: invalid file extension');
                    // cancel upload
                    return false;
                }

                // Check to see if file is aready been uploaded
                if(_uploadFileAlreadyUploaded(file)){
                    
                    alert('Error: File has already been uploaded');
                    return false;
                }

                // Set the location/path so that all files for this request are stored in the same place.
                // The first time through it gets set by the server.  Subsequently, this tells the server
                // where to put additional files.
                this.setData({
                    'filePath': _fileUploadPath
                });

                _showPageLoading();
            },
            onComplete: function(file, response) {

                // The attempt to upload the file has been completed so hide the loading image and update the UI
                // to indicate success or failure of the upload.

                //$('#loading').css('visibility', 'hidden');
                var parameters = {};
                parameters.file = file;
                parameters.response = response;
                _hidePageLoading(this._uploadFileComplete, _uploadFileComplete, parameters);
            }
        });
    };

    /**
    Update the UI to reflect what happened with the last file upload and bind events. 
    */
    var _uploadFileComplete = function(parameters) {

        if (parameters.response) {

            if (parameters.response.responseStatus == "Failed") {

                alert(parameters.response.responseMessage);

            } else { // Succeeded

                // Set the file upload path for future uploads to be stored at the same location
                _fileUploadPath = parameters.response.filePath;

                // Build new UI elements to show file information and create a button to remove the file.

                var readableBytes = com.timmons.srl.Utility.readablizeBytes(parseInt(parameters.response.currentFileSize));

                var filenum = $('#srlUploadResults .srlUploadResult').length + 1;
                var inputName = "srlFileDescription" + filenum;
                var deleteButtonId = "srlDeleteFileButton" + filenum;

                var htmlStr = '<tr class="srlUploadResult">';
                htmlStr += '<td>' + parameters.file + '</td>';
                htmlStr += '<td>' + readableBytes + '</td>';
                htmlStr += '<td><input type="text" maxlength="256" name="' + inputName + '" id="' + inputName + '" class="ui-corner-all" /></td>';
                htmlStr += '<td><div class="srlButtonWrapper"><a href="#" class="ui-state-default ui-corner-all srlButton button-icon-left" id="' + deleteButtonId + '"><span class="ui-icon ui-icon-circle-close"></span>Remove this file</a></div></td>';
                htmlStr += '</tr>';

                $('#srlUploadResults').append(htmlStr);
                $('#srlUploadGrid thead').show();

                // Update the state manager to reflect the last uploaded file

                var uploadFile = {};
                uploadFile.fileName = parameters.file;
                uploadFile.fileDescription = '';
                uploadFile.fileSize = readableBytes;
                uploadFile.filePath = _fileUploadPath;

                var uploadFiles = _stateManager.getUploadFiles();

                var numfiles = uploadFiles.length;

                if (!uploadFiles || !numfiles) {

                    uploadFiles = [];
                }

                uploadFiles.push(uploadFile);

                _stateManager.setUploadFiles(uploadFiles);

                // Bind Events to the newly added form elements (file description text input and remove this file button)

                $('#' + inputName).blur(function() {

                    // Trim off whitespace at beginning and end of text entered into file description input 

                    var newAnswer = jQuery.trim($(this).val());
                    $(this).val(newAnswer)
                });

                $('#' + inputName).bind("blur keyup", function() {

                    // Add file description to the state manager and attach it to the correct file

                    var currUploadFiles = _stateManager.getUploadFiles();
                    var currIndex;

                    for (var i = 0; i < currUploadFiles.length; i++) {

                        if (currUploadFiles[i].fileName == uploadFile.fileName) {

                            currIndex = i;
                            break;
                        }
                    }

                    currUploadFiles[currIndex].fileDescription = $(this).val();

                    _stateManager.setUploadFiles(currUploadFiles);
                });

                $('#' + deleteButtonId).click(function() {

                    // Show the page loading and remove the corresponding file from this request

                    _showPageLoading();
                    _dataManager.deleteUploadFile(uploadFile, this._deleteUploadFileComplete, _deleteUploadFileComplete);
                });
            }
        } else {

            alert('Error: File upload was unsuccessful.  Please try again later or notify the system administrator.');
        }
    };

    /**
    Once the server has attempted to remove the file from the file system udate the UI to reflect it           
    */
    var _deleteUploadFileComplete = function(deleteSuccess, uploadFile) {

        var parameters = {};

        parameters.deleteSuccess = deleteSuccess;
        parameters.uploadFile = uploadFile;

        _hidePageLoading(this._removeUploadFileFromGrid, _removeUploadFileFromGrid, parameters);
    };

    /** 
    Remove the file from the HTML/UI if the file was successfully removed or alert that it was not
    */
    var _removeUploadFileFromGrid = function(fileResult) {

        deleteSuccess = fileResult.deleteSuccess;
        uploadFile = fileResult.uploadFile;

        if (deleteSuccess) {

            // Delete was successfull so remove the HTML and update the state manager

            var uploadFiles = _stateManager.getUploadFiles();

            for (var i = 0; i < uploadFiles.length; i++) {

                if (uploadFiles[i].fileName == uploadFile.fileName) {

                    $('#srlUploadResults tr:eq(' + i + ')').remove();
                    uploadFiles.splice(i, 1);
                    break;
                }
            }

            if (!uploadFiles.length) $('#srlUploadGrid thead').hide();

            _stateManager.setUploadFiles(uploadFiles);

        } else {

            alert('We were unable to remove the file.  Please try again later or contact the system administrator.');
        }
    };

    /**
    This is no longer used
    */
    var _initializePageLoading = function() {

        /*$("#srlPageLoadingModal").dialog({
        modal: true,
        autoOpen: false,
        height: 200,
        width: 200,
        zIndex: 4999,
        resizable: false,
        dialogClass: 'srlPageLoading'
        });*/
    };

    /**
    Show the page loading image  
    */
    var _showPageLoading = function() {

        //$('#srlPageLoadingModal').dialog('open');
        $('#srlPageLoadingModal').show();
    };

    /**
    Hide the page loading image after a delay of time to allow the user to see it.
    If provided, call the callback function passed in along with the parameters for the callback.
    */
    var _hidePageLoading = function(obj, callback, parameters) {

        $('#srlPageLoadingImage').fadeTo(1000, 1, function() {

            //$('#srlPageLoadingModal').dialog('close');
            $('#srlPageLoadingModal').hide();
        
            if (callback) callback.call(obj, parameters);
        });
    };

    /**
    Start a new request. Clear out any existing request data and initialize/start the first step.
    */
    var _newRequest = function() {
        clearRemoteLink();
        
        if (_checkCancelCurrentRequest()) {
            _showPageLoading();
            $('#srlMap').show();
            $('#srlContactInfo').show();
            $('#srlVerifySubmit').show();
            _clearRequest();
            _isRequestStarted = true;
            com.timmons.srl.Utility.enableButton("#srlCancelRequestButton");
            $('#srlCancelRequestButton').click(_cancelRequest);
            _initializeRequestTypeStep();
        }
    };

    /**
    Cancel the exisiting request.  Clear out any existing request data and reset the state of the application.
    */
    var _cancelRequest = function() {

        if (_checkCancelCurrentRequest()) {
            _clearRequest();
            com.timmons.srl.Utility.disableGenericButtons("#srlCancelRequestButton");
            $('#srlCancelRequestButton').unbind('click');


            // Deactivate the accordion and close it

            $('#srlRequestAccordion').accordion('activate', false);
            $('#srlRequestAccordion').accordion('option', 'active', 0);
        }
    };

    /**
    Empties the Accordian as well as existing information in the request. Alternative to _cancelRequest() ecxept without the confirmation alert.
    */
    var _emptyRequest = function() {
        _clearRequest();

        com.timmons.srl.Utility.disableGenericButtons("#srlCancelRequestButton");
        $('#srlCancelRequestButton').unbind('click');
        // Deactivate the accordion and close it

        $('#srlRequestAccordion').accordion('activate', false);
        $('#srlRequestAccordion').accordion('option', 'active', 0);
    }

    /**
    If there is an existing request in progress ask the user first if they are sure they want to cancel it.  If they are then return true.
    Otherwise, return false.
    */
    var _checkCancelCurrentRequest = function() {

        if (_isRequestStarted) {

            if (!confirm('Are you sure you want to cancel the existing request and start a new one?  If you are sure you want to start a new request then select the "OK" button.  Otherwise, select the "Cancel" button.')) {
                return false;
            }
        }

        return true;
    };

    /**
    Clear out any existing request data and reset the state of the application.
    */
    var _clearRequest = function() {
        
        clearRemoteLink();
        //console.log("Enter _clearRequest() in interactionManager.js");

        // Loop through all form elements and reset/clear them.
        // Leave contact info alone

        $(':input', $("form")).each(function() {
            var type = this.type;
            var tag = this.tagName.toLowerCase(); // normalize case
            // it's ok to reset the value attr of text inputs,
            // password inputs, and textareas
            if (type == 'text' || type == 'password' || tag == 'textarea') {

                if ($(this).attr('id') != 'tbxFirstName' &&
                    $(this).attr('id') != 'tbxLastName' &&
                    $(this).attr('id') != 'tbxEmail' &&
                    $(this).attr('id') != 'tbxEmailReType' &&
                    $(this).attr('id') != 'tbxHomePhone' &&
                    $(this).attr('id') != 'tbxOtherPhone' &&
                    $(this).attr('id') != 'tbxAddress' &&
                    $(this).attr('id') != 'tbxCity' &&
                //$(this).attr('id') != 'tbxState' &&
                    $(this).attr('id') != 'lbxState' &&
                    $(this).attr('id') != 'tbxZip'
                   )
                    this.value = "";
            }
            // checkboxes and radios need to have their checked state cleared
            // but should *not* have their 'value' changed
            else if (type == 'checkbox' || type == 'radio') {

                if ($(this).attr('id') != 'srlMyAlexContact')
                    this.checked = false;
            }
            // select elements need to have their 'selectedIndex' property set to -1
            // (this works for both single and multiple select elements)
            else if (tag == 'select')
                this.selectedIndex = -1;
        });

        // Reset configuration variables

        _isContactInfoRequired = _configurationSettings.appSettings.IsContactInfoRequired;
        _isMapLocationRequired = true;
        _dataManager.setMapRequired(true);
        _isRequestStarted = false;

        // Clear out each step

        _clearRequestTypeStep();
        _mapManager.clear();
        _clearDescribeStep();
        _clearContactInfoStep();

        // Reset the state manager

        _stateManager.clear();

        // Disable appropriate page elements such as the next step buttons

        com.timmons.srl.Utility.disableNextButton('#srlMainWrapper .srlNextStepButton');
        com.timmons.srl.Utility.disableSteps();
        
        
    };

    /**
    Clear the Identify the Request Type step.  Reset variables, HTML and UI widgets (i.e. tabs)
    */
    var _clearRequestTypeStep = function() {

        _requestTypeSelected = false;
        _requestTypeMethod = '';

        $('#srlMainWrapper .srlSelectedRequestTypeText').html('None Selected');

        // Hide any open request type inline dialog (i.e. search results)
        $('#srlIdentify .srlInlineDialog').hide();

        // Select the first tab for the request type method (i.e. Search, By Department, etc.)
        $('#srlRequestTypeTabs').tabs('select', 0);
    };

    /**
    Clear the Describe the Request step.  Reset variables and HTML.
    */
    var _clearDescribeStep = function() {

        // Clear the question and answer list

        $('#srlQaList').html('');

        // If file uploads / request attachments are allowed then clear out and reset the file  
        // upload widget.

        if (_configurationSettings.appSettings.AllowRequestAttachmentUploads) {

            _fileUploadPath = '';
            $('#srlUploadResults').html('');
            $('#srlUploadGrid thead').hide();
        }
    };

    /**
    Currently function is empty and not used but could be used to clear out the Enter Contact 
    Information step
    */
    var _clearContactInfoStep = function() {


    };

    /**
    Submit the request to the server/CityWorks.  Regular service requests are handled differently than requests for information.        
    */
    var _submitRequest = function(requestTypeType) {

        _showPageLoading();

        if (requestTypeType == 'service') {

            // This is a regular service request.  Disable the submit button so the user can't click and submit again.
            // The current loading image will also prevent interaction with the page.

            com.timmons.srl.Utility.disableNextButton('#srlSubmitRequestButton', 5);

            // Build the request JSON and then get it to send to the server

            _stateManager.createSubmitJson();
            var submitJson = _stateManager.getSubmitJson();

            // Submit the request to the server

            _dataManager.submitRequest(submitJson, this._submitComplete, _submitComplete);

        } else { // for now only other option is 'information'

            // This is just a request for information.  This is only called if the user doesn't require follow up.
            // The only data we need to send in this case is the request type ID.  Clear out any other data if there
            // is any.

            var requestType = _stateManager.getRequestType();
            _stateManager.clear();
            _stateManager.setRequestType(requestType);

            // Build the request JSON and then get it to send to the server

            _stateManager.createSubmitJson();
            var submitJson = _stateManager.getSubmitJson();

            // Submit the request to the server (may want this to be configurable at some point)

            _dataManager.submitRequest(submitJson, this._infoSubmitComplete, _infoSubmitComplete);
        }
    };

    /**
    An attempt to submit the request to CityWorks database has been completed.  For now we are assuming that the 
    attempt was successful and that we have a request ID.  We show the user a confirmation that their request
    was submitted.
    */
    var _submitComplete = function(submitJson) {

        if (submitJson.REQUESTID) $('#srlRequestId').html(submitJson.REQUESTID);
        _hidePageLoading(this._showSubmitConfirmation, _showSubmitConfirmation);
    };

    /**
    An attempt to submit the request (only for info request where no follow is requested by the user) to CityWorks 
    database has been completed.  For now we are assuming that the attempt was successful.
    */
    var _infoSubmitComplete = function(submitJson) {

        _hidePageLoading(this._showInfoSubmitConfirmation, _showInfoSubmitConfirmation);
    };

    /**
    Initialize generic elements that are contained within all the steps.  For example, each step has generic buttons
    that need mouse hover events bound to them.
    */
    var _initializeSteps = function() {

        // Create the main accordion widget
        $("#srlRequestAccordion").accordion({
            autoHeight: false,
            collapsible: true,
            active: false,
            change: function(event, ui) { _stepChangeEndController(); },
            changestart: function(event, ui) { _stepChangeStartController(); }
        });

        // Disable all the steps.  This makes it so you can't open any accordion section and adds a disabled 
        // state to each accordion header.
        com.timmons.srl.Utility.disableSteps();

        // Initialize generic buttons.  Bind mouse over and mouse out events.

        com.timmons.srl.Utility.initializeGenericButtons('.srl button:not(.srlNextStepButton)');
        com.timmons.srl.Utility.initializeGenericButtons('.srl .srlButton:not(.srlNextStepButton)');

        // Initialize inline dialog close button

        com.timmons.srl.Utility.initializeGenericButtons('.srlInlineDialog .ui-dialog-titlebar-close');

        $('.srlInlineDialog .ui-dialog-titlebar-close').click(function() {

            $(this).parent().parent().hide('slow');
        });

        // Make previous buttons point to the correct steps and disable all the next buttons

        //Process incoming ProblemsId after everything else is done.
        _initializeNextPreviousButtons();

        // Custom code start
       
        // Custom code end

        //console.log("Enter _initializeSteps() in interactionManager.js");
    };

    var _requestUrlHandler = function() {
        _problemsIdFromLink = null;
        _problemsIdFromLink = ($.getUrlVars('problemsId'));
        
        if(_problemsIdFromLink.problemsId){
            _problemsIdFromLink = _problemsIdFromLink.problemsId;
            _newRequest(_setRequestType());
            
            setRemoteLink(_problemsIdFromLink);
        }else{
            clearRemoteLink();
        }
    }
    
    function setRemoteLink(problemsId){
        $('#remoteLink').html('Currently Selected Request Id: ' + problemsId +  ' | Remote Hyperlink: ' + _cleanUrl + '?problemsId=' + problemsId);
    }
    
    function clearRemoteLink(){
        $('#remoteLink').html('');
    }

    var _setRequestType = function(callback) {
        $(location).attr('hash','srlRequestTypeTab3');
        
        if (callback) callback.call();
    }
    
    var _findMatchingRequestFromAz = function(){
        for(var i = 0; i != _problemTypesAz.length; i++){
            if($(_problemTypesAz[i]).attr('PROBLEMSID') == _problemsIdFromLink)
            {
                _stateManager.setRequestType(_problemsIdFromLink);

                var requestTypeText = $(_problemTypesAz[i]).attr('DESCRIPTION')
                $(".srlSelectedRequestTypeText").html(requestTypeText);

                _stateManager.setRequestTypeText(requestTypeText);

                // have to reset in case they did info request with follow up and then changed to different request type
                _isContactInfoRequired = _configurationSettings.appSettings.IsContactInfoRequired;

                $('#srlAnswerInfoLinks').html('');
                $('srlAnswerInfoLinks').hide();
                $('srlAnswerInfoLinks').removeAttr('style');

                $('#srlContactInfo .srlStepNumber').text('4');

                $('#srlVerifySubmit .srlStepNumber').text('5');
                
                
                _dataManager.getProblemQuestionList(_problemsIdFromLink, this._initializeQaList, _initializeQaList);
        
                _dataManager.getRLPROBLEMLEAF(_problemsIdFromLink, this._checkRLProblemLeafData, _checkRLProblemLeafData);
                return true;
            }
        }
           alert('The Request Type configured with the link provided does no existing in our system. Please feel free to search out application for a matching Request Type.');
           $(location).attr('href',_cleanUrl);     
    }

    /**
    Make previous buttons point to the correct steps and disable all the next buttons
    */
    var _initializeNextPreviousButtons = function() {

        // Make previous buttons point to the correct steps

        $('.srlPreviousStepButton').each(function(i) {

            $(this).click(function() {
                com.timmons.srl.Utility.showStep(i);
            });
        });

        // Disable all the next buttons
        com.timmons.srl.Utility.disableGenericButtons('.srlNextStepButton');
        
        return true;
    };

    /**
    This method is called each time a step is open before the animation is complete
    */
    var _stepChangeStartController = function() {

        // Loop through each active accordion step (should only be one)

        $('#srlRequestAccordion .srlStep > .ui-state-active').each(function(i) {

            // Save all state data 
            _saveStateData();

            var activeAccordionElementId = $(this).parent().attr('id');

            // Check which step we are in and perform step specific stuff that needs to occur
            // before the animation is complete

            if (activeAccordionElementId == "srlVerifySubmit") {

                _initializeVerifyStep();
                return false;
            }
        });
    };

    /** 
    Save all application state data.  This is only stored client side at the moment, but at some point this data 
    could be stored somewhwere on the server side in a session or DB to allow it to be pulled back into the client.
    */
    var _saveStateData = function() {

        //_saveRequestType(); already handled elsewhere
        //_saveMapLocation(); already handled elsewhere
        _saveDescribeRequest();
        _saveContactInfo();
    };

    /**
    Not currently used, but could be used to save the request/problem type in the state manager
    */
    var _saveRequestType = function() {


    };

    /**
    Save the location of the request in the state manager
    */
    var _saveMapLocation = function() {

        if (_stateManager) _stateManager.setRequestLocation(_mapManager.getAddress());
    };

    /**
    Save the question and answer combinations and the details of the request.  File upload is not included here.
    I believe it is handled elsewhere.
    */
    var _saveDescribeRequest = function() {

        // Save additional details

        if (_stateManager) _stateManager.setRequestDetails($('#tbxDetails').val());

        // Save question and answer combinations

        if (_qaList) {
            _qaList.updateQaValueList();
            _qaList.saveData();
        }
    };

    /**
    Save the contact information in the state manager
    */
    var _saveContactInfo = function() {

        $.Watermark.HideAll();

        var contactData = {};

        contactData.person = {};
        contactData.person.firstName = $('#tbxFirstName').val();
        contactData.person.lastName = $('#tbxLastName').val();
        contactData.person.email = $('#tbxEmail').val();
        contactData.person.homephone = $('#tbxHomePhone').val();
        contactData.person.otherphone = $('#tbxOtherPhone').val();


        contactData.address = {};
        contactData.address.street = $('#tbxAddress').val();
        contactData.address.city = $('#tbxCity').val();
        if($('#lbxState').val() != -1){
            contactData.address.state = $('#lbxState').val();
        }else{
            contactData.address.state = $('#tbxOtherState').val();
        }
        //contactData.address.state = $('#tbxState').val();
        contactData.address.zip = $('#tbxZip').val();

        _stateManager.setContactInformation(contactData);

        $.Watermark.ShowAll();
    }

    /**
    This method is called each time a step is open after the animation is complete
    */
    var _stepChangeEndController = function() {

        $('#srlRequestAccordion .srlStep > .ui-state-active').each(function(i) {

            // Set the value of the active accordion section

            var activeAccordionElementId = $(this).parent().attr('id');

            if (activeAccordionElementId == "srlIdentify") {

                $('#srlRequestAccordion').accordion('option', 'active', 1);
                return false;

            } else if (activeAccordionElementId == "srlMap") {
                
                // Need to show map only after the accordion is open so it has the size of the container
                if(_isMapLocationRequired)
                {
                    _initializeMapLocationStep();
                    $('#srlRequestAccordion').accordion('option', 'active', 3);
                    $('#AddressIn').focus();
                }
                else{
                    _initializeMapLocationStep();
                    //com.timmons.srl.Utility.showStep(3);
                    $('#srlRequestAccordion').accordion('option', 'active', 3);
                }
                return false;

            } else if (activeAccordionElementId == "srlDescribe") {

                $('#srlRequestAccordion').accordion('option', 'active', 2);
                return false;

            } else if (activeAccordionElementId == "srlContactInfo") {

                $('#srlRequestAccordion').accordion('option', 'active', 4);
                return false;

            } else {

                $('#srlRequestAccordion').accordion('option', 'active', 5);
                return false;
            }
        });
    };

    /**
    Initialize the Identify the Request Type step.  Reset all variables and get the latest data from the server
    for the departments dropdown and the A-Z listing of request types.
    */
    var _initializeRequestTypeStep = function() {

        _showPageLoading();

        _requestTypeSelected = false;
        _requestTypeMethod = '';
        _problemTypesAz = [];
        _problemTypesSearch = [];
        _problemTypesDept = [];

        // Get all departments and create input element to select department
        _dataManager.getAllDepartments(this._getAllDepartmentsComplete, _getAllDepartmentsComplete);
    };

    /**
    This function is called once an attempt to get department data is completed.  Create the department
    dropdown and initialize its selected value.  Next get all the problem types for the A-Z listing.
    */
    var _getAllDepartmentsComplete = function(deptData) {

        _createDepartmentDropdown(deptData);

        // Set Dept dropdown to "Please Select"
        $('#lbxSelectDepartment').val('');
        $('#lbxSelectDepartment').selectmenu('value', 0);

        // Get all problem types and create input elements for "All Request Types"
        _dataManager.getAllProblemTypes(this._getAllProblemTypesComplete, _getAllProblemTypesComplete);
    };

    /**
    This function is called once an attempt to get all problem/request types is completed.  Create and populate
    the problem/request type input for the A-Z listing.  Then initialize the request type step if it hasn't already
    been done.
    */
    var _getAllProblemTypesComplete = function(problems) {

        // Create and populate the problem/request type input for the A-Z listing

        _createProblemTypeInputAz(problems);

        // initialize the request type step if it hasn't already been done

        if (!_isRequestTypeStepInitialized) {

            // Create Request Type Tabs
            $("#srlRequestTypeTabs").tabs();

            // Search for Request Type

            $("#tbxKeyword").keypress(function(e) {
                // Check to see if the user hit the 'enter' button on the keyboard while in the keyword input.
                // If they have then execute a click on the search button
                if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                    $('#requestTypeSearchButton').click();
                    return false;
                } else {
                    return true;
                }
            });

            // Execute a keyword search when the search button is "clicked" and list any matching request types

            $('#requestTypeSearchButton').click(function() {

                _requestTypeSearchKeyword();  //Added by James on 7/20/2009
            });

            // When the department dropdown is changed get all request types for the selected department

            $('#lbxSelectDepartment').change(function() {

                _requestTypeSearchDepartment();  //Added by James on 7/20/2009
            });

            // Execute a function when a request type is selected by the user

            $('input.srlRequestTypeInput').live("click", function() {

                _requestTypeClick(this);
            });

            /*$('#srlIdentify .srlNextStepButton').live("click", function() {

                _dataManager.getProblemQuestionList(_stateManager.getRequestType(), this._initializeQaList, _initializeQaList);
            });*/

            // When the results of a department select are closed we need to reset the dropdown value to the first value

            $('#srlRequestTypeDept .srlInlineDialog .ui-dialog-titlebar-close').click(function() {

                $('#lbxSelectDepartment').val('');
                $('#lbxSelectDepartment').selectmenu('value', 0);
            });

            _isRequestTypeStepInitialized = true;
        }

        _hidePageLoading(this._showRequestTypeStep, _showRequestTypeStep);
    };

    /**
    This function executes when the user selects a request type.  Clear out other selected request types.
    Indicate what method the user used to select the request type.  Set the request type value and enable
    the next step.
    */
    var _requestTypeClick = function(elem) {

        // Clear out selection of other request type radios so only one can be checked at a time.
        // Indicate what method was used to select the request type.
        

        var elemName = $(elem).attr('name');

        if (elemName == "RBLKeyword") {

            $('input[name="RBLDepartment"]').attr("checked", false);
            $('input[name="RBLAz"]').attr("checked", false);
            _requestTypeMethod = "Search";

        } else if (elemName == "RBLDepartment") {

            $('input[name="RBLKeyword"]').attr("checked", false);
            $('input[name="RBLAz"]').attr("checked", false);
            _requestTypeMethod = "Department";

        } else {

            $('input[name="RBLDepartment"]').attr("checked", false);
            $('input[name="RBLKeyword"]').attr("checked", false);
            _requestTypeMethod = "All";
        }

        // If the request type selected by the user has changed then set the request type value,
        // disable all the steps then enable the next step.  Once the request type has changed
        // we want to force the user to revisit all the steps.

        var requestTypeValue = parseInt($(elem).val());
        
        setRemoteLink(requestTypeValue);

        if (_stateManager.getRequestType() != requestTypeValue) {

            com.timmons.srl.Utility.disableNextButton('#srlStepButtons1 .srlNextStepButton');
            //com.timmons.srl.Utility.disableSteps();
            com.timmons.srl.Utility.enableSteps(1);
            _setRequestTypeValue(elemName);
        }
    };

    /**
    Initialize the dialog that handles information type requests.
    */
    var _initializeRequestInfoDialog = function() {
        
        // Need to clear request type selection when the user closes (cancels) dialog window
        $("#srlRLProblemLeafOrQA").dialog({
            modal: true,
            autoOpen: false,
            zIndex: 999,
            width: 600,
            resizable: false,
            buttons: { "Continue...": function() { $(this).dialog("close"); } },
            close: function(event, ui) { _cancelInfoRequest(); }
        });
        
        // Need to clear request type selection when the user closes (cancels) dialog window
        $("#srlRequestInfoDialog").dialog({
            modal: true,
            autoOpen: false,
            zIndex: 999,
            width: 450,
            resizable: false,
            buttons: { "Change Request Type.": function() { $(this).dialog("close"); } },
            close: function(event, ui) { _cancelInfoRequest(); }
        });

        // Handle Citizen NOT needing follow up to information type requests
        $('#srlRequestFollowUpNo').live("click", function() {

            // Reset some private variables
            _isMapLocationRequired = false;
            _dataManager.setMapRequired(false);
            _isCancelInfoRequest = false;
            _requestTypeSelected = true;

            // Disable the rest of the steps
            com.timmons.srl.Utility.disableSteps();
            com.timmons.srl.Utility.enableSteps(1);

            // Close Info Request Modal
            $('#srlRequestInfoDialog').dialog("close");

            _submitRequest('information');
        });


        // Handle Citizen needing follow up to information type requests
        $('#srlRequestFollowUpYes').live("click", function() {

            // Reset some private variables
            _isMapLocationRequired = false;
            _dataManager.setMapRequired(false);
            _isCancelInfoRequest = false;
            _requestTypeSelected = true;
            _isContactInfoRequired = _configurationSettings.appSettings.IsContactInfoRequired;

            // Disable the rest of the steps
            com.timmons.srl.Utility.disableSteps();
            com.timmons.srl.Utility.enableSteps(1);

            // Close Info Request Modal
            $('#srlRequestInfoDialog').dialog("close");

            // Wire next button to Describe the Request step
            $('#srlStepButtons1 .srlNextStepButton').unbind('click');
            com.timmons.srl.Utility.enableNextButton('#srlStepButtons1 .srlNextStepButton', 1);

            // Wire previous button on describe step to step 1
            $('#srlStepButtons3 .srlPreviousStepButton').unbind('click');
            $('#srlStepButtons3 .srlPreviousStepButton').click(function() {
                com.timmons.srl.Utility.showStep(0);
            });

            // Clear Out any Q/A (already handled by initialize?)
            _qaList.clear();

            // Clear the map
            _mapManager.clear();

            // Clear out any map location from the state manager
            _stateManager.setRequestLocation(null);

            // Clear out he map location address input
            $('#AddressIn').val('');

            _initializeContactInfo(); // move later

            com.timmons.srl.Utility.disableNextButton('#srlStepButtons2 .srlNextStepButton', 2);

            // Show Describe Request Step
            com.timmons.srl.Utility.enableSteps(3);
            com.timmons.srl.Utility.showStep(2);
        });
    };

    /**
    Initialize the verify and submit request step.  Get all of the request data from the state manager and populate
    the HTML with the data.  Ensure that all required fields are filled out and if so enable the submit button.
    If there are required fields that aren't filled out then indicate that through error messages and disable
    the submit button.  
    */
    var _initializeVerifyStep = function() {

        // Get all the request data from the state manager

        var requestType = _stateManager.getRequestType();
        var requestLocation = _stateManager.getRequestLocation();
        var requestDetails = _stateManager.getRequestDetails();
        var contactInfo = _stateManager.getContactInformation();

        // Populate the request location HTML if applicable

        if (requestLocation) {

            // Hide any error messages

            $('#srlRequestLocationError').hide();

            // Populate the HTML with the request location data

            $('#srlVerifyLocStreetData').html(requestLocation.street);
            $('#srlVerifyLocCityData').html(requestLocation.city);
            $('#srlVerifyLocStateData').html(requestLocation.state);
            $('#srlVerifyLocZipData').html(requestLocation.zip);

            $('#srlSubmitLocStreetData').html(requestLocation.street);
            $('#srlSubmitLocCityData').html(requestLocation.city);
            $('#srlSubmitLocStateData').html(requestLocation.state);
            $('#srlSubmitLocZipData').html(requestLocation.zip);

        } else { // There is no request location provided

            // If a request location is required then show an error message

            if (_isMapLocationRequired) {

                $('#srlRequestLocationError').show();
                $('#srlVerifyLocation').show();

            } else {

                $('#srlRequestLocationError').hide();
                $('#srlVerifyLocation').hide();
            }

            // Clear out the request location HTML

            $('#srlVerifyLocStreetData').html('');
            $('#srlVerifyLocCityData').html('');
            $('#srlVerifyLocStateData').html('');
            $('#srlVerifyLocZipData').html('');

            $('#srlSubmitLocStreetData').html('');
            $('#srlSubmitLocCityData').html('');
            $('#srlSubmitLocStateData').html('');
            $('#srlSubmitLocZipData').html('');
        }

        // Populate the request description (Q/A & Details)

        try {
            _qaList.renderVerifyQa('#srlVerifyDescriptionQa');
        } catch (ex) {
            //console.error(ex);
        }

        try {
            _qaList.renderVerifyQa('#srlSubmitDescriptionQa');
        } catch (ex) {
            //console.error(ex);
        }

        $('#srlVerifyDetails').html(requestDetails); //shows up before the submission
        $('#srlSubmitDetails').html(requestDetails); //shows up after the submission
        var currentDate = new Date();
        var currentMonth = currentDate.getMonth() + 1;
        if(currentMonth < 10){
            currentMonth = '0' + currentMonth;
        }
        
        var currentDay = currentDate.getDate();
        if(currentDay < 10){
            currentDay = '0' + currentDay;
        }
        var currentYear = currentDate.getFullYear();
        var currentHour = currentDate.getHours();
        var currentAMPM = '';
        if(currentHour > 11){
            currentAMPM = 'PM';
        }else{
            currentAMPM = 'AM';
        }
        if(currentHour < 10){
            currentHour = '0' + currentHour;
        }
        var currentMinute = currentDate.getMinutes();
        if (currentMinute < 10){
            currentMinute = "0" + currentMinute;
        }
        
        $('#srlSubmitDateTime').html(currentMonth + '/' + currentDay + '/' + currentYear + ' ' + currentHour + ':' + currentMinute + ' ' + currentAMPM);
        // Populate attachment/file upload HTML if the application is configured to allow
        // attachments/files

        if (_configurationSettings.appSettings.AllowRequestAttachmentUploads) {

            // Get the list of uploaded files from the state manager    

            var uploadFiles = _stateManager.getUploadFiles();

            // Build the HTML

            var uploadFilesHtml = '';

            if (!uploadFiles.length) {

                uploadFilesHtml = '<tr><td colspan="2">No files uploaded</td></tr>';
                $('#srlVerifyUploadedFilesGrid thead, #srlSubmitUploadedFilesGrid thead').hide();

            } else {

                $('#srlVerifyUploadedFilesGrid thead, #srlSubmitUploadedFilesGrid thead').show();
            }

            for (var i = 0; i < uploadFiles.length; i++) {

                uploadFilesHtml += '<tr>';
                uploadFilesHtml += '<td>' + uploadFiles[i].fileName + '</td>';
                uploadFilesHtml += '<td>' + uploadFiles[i].fileSize + '</td>';
                uploadFilesHtml += '<td>' + uploadFiles[i].fileDescription + '</td>';
                uploadFilesHtml += '</tr>';
            }

            // Add the HTML to the document and show it

            $('#srlVerifyUploadedFilesGrid tbody, #srlSubmitUploadedFilesGrid tbody').html(uploadFilesHtml);
            $('#srlVerifyUploadedFiles, #srlSubmitUploadedFiles').show();
        }

        // Populate the Contact Info HTML

        $('#srlVerifyContactFirstName').html(contactInfo.person.firstName);
        $('#srlVerifyContactLastName').html(contactInfo.person.lastName);
        $('#srlVerifyContactEmail').html(contactInfo.person.email);
        $('#srlVerifyContactHomePhone').html(contactInfo.person.homephone);
        $('#srlVerifyContactOtherPhone').html(contactInfo.person.otherphone);

        $('#srlSubmitContactFirstName').html(contactInfo.person.firstName);
        $('#srlSubmitContactLastName').html(contactInfo.person.lastName);
        $('#srlSubmitContactEmail').html(contactInfo.person.email);
        $('#srlSubmitContactHomePhone').html(contactInfo.person.homephone);
        $('#srlSubmitContactOtherPhone').html(contactInfo.person.otherphone);

        $('#srlVerifyContactStreetData').html(contactInfo.address.street);
        $('#srlVerifyContactCityData').html(contactInfo.address.city);
        $('#srlVerifyContactStateData').html(contactInfo.address.state);
        $('#srlVerifyContactZipData').html(contactInfo.address.zip);

        $('#srlSubmitContactStreetData').html(contactInfo.address.street);
        $('#srlSubmitContactCityData').html(contactInfo.address.city);
        $('#srlSubmitContactStateData').html(contactInfo.address.state);
        $('#srlSubmitContactZipData').html(contactInfo.address.zip);

        // Check to see if all required fields have been filled out

        var isSubmitReady = true;

        if (!requestType) isSubmitReady = false; // Identify step
        if (_isMapLocationRequired && (!requestLocation || !requestLocation.street)) isSubmitReady = false; // Map location step

        try {
            if (!_qaList.isStepComplete()) isSubmitReady = false; // Describe request step
        } catch (ex) {
            //console.error(ex);
        }
        
        if(_isContactInfoRequired){
            if (!_isContactInfoComplete()) isSubmitReady = false; // Contact Information step
        }

        // Enable / Disable Submit button

        if (isSubmitReady) {

            com.timmons.srl.Utility.enableButton('#srlSubmitRequestButton');

            $('#srlSubmitRequestButton').click(function() {

                _submitRequest('service');
            });

        } else {

            com.timmons.srl.Utility.disableNextButton('#srlSubmitRequestButton', 5);
        }
    };

    /**
    Initialize the submit confirmation dialogs. When the dialogs are closed we need to clear the request data
    out of the UI and set the application back to the initial state.
    */
    var _initializeSubmitConfirmation = function() {

        $("#srlSubmitConfirmation").dialog({
            modal: true,
            autoOpen: false,
            height: $(window).height() - 50,
            width: $(window).width() - 50,
            zIndex: 5,
            resizable: true,
            show: 'blind',
            hide: 'blind',
            buttons: { "I have recorded my Request ID. Close this panel.": function() { $(this).dialog("close"); } },
            close: function(event, ui) { _emptyRequest(); }
        });

        $("#srlInfoSubmitConfirmation").dialog({
            modal: true,
            autoOpen: false,
            zIndex: 5,
            show: 'blind',
            hide: 'blind',
            buttons: { "Ok, Close this Window.": function() { $(this).dialog("close"); } },
            close: function(event, ui) { _emptyRequest(); }
        });
    };

    var _showSubmitConfirmation = function() {

        $('#srlSubmitConfirmation').dialog('option', 'height', $(window).height() - 50);
        $('#srlSubmitConfirmation').dialog('option', 'width', $(window).width() - 50);
        $('#srlSubmitConfirmation').dialog('open');
    };

    var _showInfoSubmitConfirmation = function() {

        $('#srlInfoSubmitConfirmation').dialog('open');
    };

    var _initializeContactInfo = function(address) {

        var contactData = {};
        contactData.person = {};
        contactData.address = {};

        _checkUseMapInfo();
        //        if (address) {
        //            if (address.street && !jQuery.trim($('#tbxAddress').val())) $('#tbxAddress').val(address.street);
        //            if (address.city && !jQuery.trim($('#tbxCity').val())) $('#tbxCity').val(address.city);
        //            if (address.state && !jQuery.trim($('#tbxState').val())) $('#tbxState').val(address.state);
        //            if (address.zip && !jQuery.trim($('#tbxZip').val())) $('#tbxZip').val(address.zip);
        //        }

        _saveContactInfo();

        if (!_isContactInfoStepInitialized) {

            $('#srlContactInfo input').blur(function() {

                var newAnswer = jQuery.trim($(this).val());
                $(this).val(newAnswer)
            });

            $('#tbxFirstName').bind("blur keyup", function() {

                contactData.person.firstName = $(this).val();
                _stateManager.setContactInformation(contactData);
            });

            $('#tbxLastName').bind("blur keyup", function() {

                contactData.person.lastName = $(this).val();
                _stateManager.setContactInformation(contactData);
            });

            $('#tbxEmail').bind("blur", function() {

                contactData.person.email = $(this).val();

                if (!com.timmons.srl.Utility.isValidEmailAddress(contactData.person.email)) {
                    if(contactData.person.email != ''){
                        $('#tbxEmailInvalid').show();
                    }

                } else {

                    $('#tbxEmailInvalid').hide();
                    _stateManager.setContactInformation(contactData);
                }

                if ($(this).val() != $('#tbxEmailReType').val()) {

                    $('#tbxEmailNotMatch').show();

                } else {

                    $('#tbxEmailNotMatch').hide();
                }
            });

            $('#tbxEmailReType').bind("blur focusout", function() {

                if ($(this).val() != $('#tbxEmail').val()) {

                    $('#tbxEmailNotMatch').show();

                } else {

                    $('#tbxEmailNotMatch').hide();
                }
            });

            $('#tbxHomePhone').bind("blur", function() {

                $.Watermark.HideAll();

                if (validatePhone($('#tbxHomePhone').val())) {
                    contactData.person.homephone = $(this).val();
                    _stateManager.setContactInformation(contactData);
                    $('#tbxHomePhoneError').hide();
                }
                else {
                    $('#tbxHomePhoneError').show();
                }

                $.Watermark.ShowAll();

            });

            $('#tbxHomePhone').Watermark("(###) ###-#### or ###-###-####");

            $('#tbxOtherPhone').bind("blur", function() {

                $.Watermark.HideAll();

                if (validatePhone($('#tbxOtherPhone').val())) {
                    contactData.person.otherphone = $(this).val();
                    _stateManager.setContactInformation(contactData);
                    $('#tbxOtherPhoneError').hide();
                }
                else {
                    $('#tbxOtherPhoneError').show();
                }

                $.Watermark.ShowAll();

            });

            $('#tbxOtherPhone').Watermark("(###) ###-#### or ###-###-####");

            $('#tbxAddress').bind("blur keyup", function() {

                contactData.address.street = $(this).val();
                _stateManager.setContactInformation(contactData);
                $('#chkUseMapLocation').attr('checked', false);

            });

            $('#tbxCity').bind("blur keyup", function() {

                contactData.address.city = $(this).val();
                _stateManager.setContactInformation(contactData);
                $('#chkUseMapLocation').attr('checked', false);
            });

            $('#tbxZip').Watermark("Postal Code");
            
            $('#tbxOtherState').Watermark('Enter Country Here');
            
            $('#lbxState').bind("blur change", function() {
                //contactData.address.state == -1 for "OTHER" State value
                if($(this).val() == -1){
                    $('#tbxIncorrectZip').hide();
                    
                    $('#otherStateDiv').show('slow');
                    
                    $('#tbxOtherState').bind('blur keyup', function(){
                        contactData.address.state = $('#tbxOtherState').val();
                        _stateManager.setContactInformation(contactData);
                    });
                    
                    
                    
                   // $('#tbxZip').val("");
                  //  $('#tbxZip').Watermark('POSTAL CODE');
                    
                    $('#srlStepButtons4 .srlPreviousStepButton').unbind('click');
                    $('#srlStepButtons4 .srlPreviousStepButton').click(function() {
                        com.timmons.srl.Utility.showStep(2);
                    });                    
                }else{
                   // $('#tbxZip').val('');
                   // $('#tbxZip').Watermark("#####-#### or #####");
                    contactData.address.state = $(this).val();
                    _stateManager.setContactInformation(contactData);
                    $('#tbxOtherState').unbind('blur keyup')
                    $('#chkUseMapLocation').attr('checked', false);
                    $('#otherStateDiv').hide();
                    
                    if($('#tbxZip').val().length > 0 && $('#tbxZip').val() != "#####-#### or #####"){
                        if (validateZip()) {
                            $('#tbxIncorrectZip').hide();
                            $('#srlStepButtons4 .srlPreviousStepButton').unbind('click');
                            $('#srlStepButtons4 .srlPreviousStepButton').click(function() {
                                com.timmons.srl.Utility.showStep(2);
                            });
                        }
                        else {
                            $('#tbxIncorrectZip').show();
                            $('#srlStepButtons4 .srlPreviousStepButton').unbind('click');
                        }
                    }                    
                }
                

            });

            $('#tbxZip').bind("blur focusout", function() {
                if (validateZip()) {
                    $('#tbxIncorrectZip').hide();
                    $('#srlStepButtons4 .srlPreviousStepButton').unbind('click');
                    $('#srlStepButtons4 .srlPreviousStepButton').click(function() {
                        com.timmons.srl.Utility.showStep(2);
                    });
                }
                else {
                    $('#tbxIncorrectZip').show();
                    $('#srlStepButtons4 .srlPreviousStepButton').unbind('click');
                }
                contactData.address.zip = $(this).val();
                _stateManager.setContactInformation(contactData);
                $('#chkUseMapLocation').attr('checked', false);
//                if($('#tbxZip').val()){
//                    $('#tbxZip').attr('color','#000000');
//                }
                
            });

            $('#tbxZip').bind("blur keyup", function() {
                $('#tbxIncorrectZip').hide();
//                if($('#tbxZip').val()){
//                    $('#tbxZip').attr('color','#000000');
//                }
            });

            $('#srlContactInfo input').bind("blur keyup", _checkEnableContactNextStep);

            _isContactInfoStepInitialized = true;
        }

        //console.log("Exit _initializeContactInfo() in interactionManager.js");

        _requireContactInformation(_isContactInfoRequired);
    };

    var addWaterMarkToState = function(){
    
    }

    var validatePhone = function(phnNum) {
    
        if(phnNum.substring(1,4) == '900'){ return false;}
        if(phnNum.substring(0,3) == '900'){ return false;}
    
    
        var regPhn = new RegExp("(^[01]?[- .]?(\\([2-9]\\d{2}\\)|[2-9]\\d{2})[- .]?\\d{3}[- .]?\\d{4}$)|(^$)");
        return regPhn.test(phnNum);
    };

    var validateZip = function() {
    
        if($('#tbxZip').val() == null){
            return true;
        }
    
        if($('#tbxZip').val() == '#####-#### or #####' || $('#tbxZip').val() == 'Postal Code' ){
            return true;
        }
    
        if($('#tbxZip').val() == ''){
            return true;
        }
        
        if($('#lbxState').val() == -1){
            return true;
        }else{
            var regZip = new RegExp("^\\d{5}([\\-]\\d{4})?$");
            var boolval = regZip.test($('#tbxZip').val());

            return boolval;
        }
        
        return true;
    };

    /**
    Returns true if there is a valid address entered, otherwise false.
    */
    var _hasValidAddress = function() {
        //Change tbxState to lbxState
        if ((!$("#tbxAddress").val() == "") && (!$("#tbxCity").val() == "") && (!$("#lbxState").val() == "") && (!$("#tbxZip").val() == "")) {
            return true;
        }
        else {
            return false;
        }

        //        if ((!$("#tbxAddress").val() == "") && (!$("#tbxCity").val() == "") && (!$("#tbxState").val() == "") && (!$("#tbxZip").val() == "")) {
        //            return true;
        //        }
        //        else {
        //            return false;
        //        }
    }

    var _checkEnableContactNextStep = function() {

        if (_isContactInfoComplete()) _enableContactNextStep();
        else _disableContactNextStep();
    };

    var _isContactInfoComplete = function() {

        var isComplete = true;

        if (_isContactInfoRequired) {

            $('#srlContactInfo input').each(function() {

                if (!$(this).val()) {

                    isComplete = false;
                    return isComplete;
                }
            });

            if (!com.timmons.srl.Utility.isValidEmailAddress($('#tbxEmail').val())) return false;
            if ($('#tbxEmail').val() != $('#tbxEmailReType').val()) return false;
        }

        return isComplete;
    };

    var _enableContactNextStep = function() {

        var next_button = $('#srlStepButtons4').children('.srlButtonWrapper').children('.srlNextStepButton');
        com.timmons.srl.Utility.enableNextButton($(next_button), 4);
    };

    var _disableContactNextStep = function() {

        var next_button = $('#srlStepButtons4').children('.srlButtonWrapper').children('.srlNextStepButton');
        com.timmons.srl.Utility.disableNextButton($(next_button), 4);
    };

    var _setRequestTypeValue = function(rbl) {

        var rb = $('input[name=' + rbl + ']:checked');

        var requestTypeValue = parseInt(rb.val());

        _stateManager.setRequestType(requestTypeValue);

        var requestTypeText = $(rb).next().text();
        $(".srlSelectedRequestTypeText").html(requestTypeText);

        _stateManager.setRequestTypeText(requestTypeText);

        // have to reset in case they did info request with follow up and then changed to different request type
        _isContactInfoRequired = _configurationSettings.appSettings.IsContactInfoRequired;

        $('#srlAnswerInfoLinks').html('');
        $('srlAnswerInfoLinks').hide();
        $('srlAnswerInfoLinks').removeAttr('style');

        $('#srlContactInfo .srlStepNumber').text('4');

        $('#srlVerifySubmit .srlStepNumber').text('5');
        
                
        _dataManager.getProblemQuestionList(requestTypeValue, this._initializeQaList, _initializeQaList);
        
        _dataManager.getRLPROBLEMLEAF(requestTypeValue, this._checkRLProblemLeafData, _checkRLProblemLeafData);
    };

    var _addProblemLeafListOfLinks = function(rlProblemLeaf){
        if(rlProblemLeaf.ListOfLinks.length > 0){
             var docHtml = '<ul>';
             $('#srlProblemLeafInfo').append(docHtml);
             for (var i = 0; i < rlProblemLeaf.ListOfLinks.length; i++) {
                docHtml = '<li class="srlRequestInfoData"><a class="RLProfileLinks" href="' + rlProblemLeaf.ListOfLinks[i].URL + '" target="_blank">' + rlProblemLeaf.ListOfLinks[i].DESCRIPTION + '</a></li>';
                $('#srlProblemLeafInfo').append(docHtml);
            }
            var docHtml = '</ul>';
             $('#srlProblemLeafInfo').append(docHtml);
        }
    };
    
    var _addProblemLeafInfo = function(rlProblemLeaf){
        var docHtml = '';
        if(rlProblemLeaf.ADDITIONALINFORMATION.length > 0){
        
             docHtml = '</br>' + rlProblemLeaf.ADDITIONALINFORMATION + '</br>';
            $('#srlProblemLeafInfo').append(docHtml);

            if(rlProblemLeaf.STOPTYPEID == 1){
                $('#srlProblemLeafInfo').css("color","red");
            }
        }
    };    

    var _checkStepNumbers = function(rlProblemLeaf){
        if(rlProblemLeaf.STOPTYPEID > 0)
        { 
            if(rlProblemLeaf.MAPREQUIRED == 0)
            {                
                //Reset the numbers on the Step Panels...
                $('#srlContactInfo .srlStepNumber').text('3');

                $('#srlVerifySubmit .srlStepNumber').text('4');
            }else{
                //Reset the numbers on the Step Panels...
                $('#srlContactInfo .srlStepNumber').text('4');

                $('#srlVerifySubmit .srlStepNumber').text('5');
            }
        }
        else{
            //Reset the numbers on the Step Panels...
            $('#srlContactInfo .srlStepNumber').text('4');

            $('#srlVerifySubmit .srlStepNumber').text('5');
        }
    };



    var _checkRLProblemLeafData = function(rlProblemLeaf) {
        
        //Clear out any links or info from RLProblemLeaf
        $('#srlProblemLeafInfo').html('');
        
        if(rlProblemLeaf.STOPTYPEID > 0)
        {
            $('#srlProblemLeafInfo').show();
            
            _addProblemLeafInfo(rlProblemLeaf);
            
            _addProblemLeafListOfLinks(rlProblemLeaf);
            
            if(rlProblemLeaf.STOPTYPEID == 1)
            {
                $('#srlMap').hide();
                $('#UseMapLocation').hide();
                $('#srlContactInfo').hide();
                $('#srlVerifySubmit').hide();
                com.timmons.srl.Utility.showStep(1);
                
                // Re-Wire Describe Next button
//                $('#srlStepButtons4 .srlNextStepButton').unbind('click');
//                $('#srlStepButtons4 .srlNextStepButton').click(function() {
//                    _newRequest();
//                });
                _checkStepNumbers(rlProblemLeaf);
                return false;
            }
            else
            {
                $('#srlMap').show();
                
                $('#srlContactInfo').show();
                $('#srlVerifySubmit').show();
                
                _checkStepNumbers(rlProblemLeaf);
                                
            }
           
            _checkStepNumbers(rlProblemLeaf);
                        
            if(rlProblemLeaf.ADDITIONALINFORMATION != "")
            {
            
            }
            
            /* 
                MAPREQUIRED == 0 - Skip Map
                MAPREQUIRED == 1 - Required
                MAPREQUIRED == 2 - Optional
            
            */
            if(rlProblemLeaf.MAPREQUIRED == 0)
            {
            
                
                // Wire Describe Next button to skip map
                //$('#srlStepButtons2 .srlNextStepButton').unbind('click');
                if(questionsPresented){
                    com.timmons.srl.Utility.disableNextButton('#srlStepButtons2 .srlNextStepButton', 3);
                }else{
                    com.timmons.srl.Utility.enableNextButton('#srlStepButtons2 .srlNextStepButton', 2);
                    $('#srlStepButtons2 .srlNextStepButton').unbind('click');
                    $('#srlStepButtons2 .srlNextStepButton').click(function() {
                            com.timmons.srl.Utility.enableSteps(3);
                            com.timmons.srl.Utility.showStep(3);
                            com.timmons.srl.Utility.enableNextButton('#srlStepButtons4 .srlNextStepButton', 4);
                            
                        $('#srlStepButtons4 .srlNextStepButton').unbind('click');
                        $('#srlStepButtons4 .srlNextStepButton').click(function() {
                            com.timmons.srl.Utility.enableSteps(4);
                            com.timmons.srl.Utility.showStep(4);
                        });                              
                    });
                }
                
                //com.timmons.srl.Utility.enableSteps(3);
                
                
                // Re-Wire Contact Information buttons
                $('#srlStepButtons4 .srlPreviousStepButton').unbind('click');
                $('#srlStepButtons4 .srlPreviousStepButton').click(function() {
                    com.timmons.srl.Utility.showStep(1);
                });

                // Re-Wire Verify buttons
                $('#srlStepButtons5 .srlPreviousStepButton').unbind('click');
                $('#srlStepButtons5 .srlPreviousStepButton').click(function() {
                    com.timmons.srl.Utility.showStep(3);
                });
                
                 // Reset some private variables
                _isMapLocationRequired = false;
                _dataManager.setMapRequired(false);
                _isCancelInfoRequest = false;
                _requestTypeSelected = true;
                _isContactInfoRequired = _configurationSettings.appSettings.IsContactInfoRequired;;  

                // Clear the map
                _mapManager.clear();

                // Clear out any map location from the state manager
                _stateManager.setRequestLocation(null);

                // Clear out he map location address input
                $('#AddressIn').val('');

                _initializeContactInfo(); // move later   
                
                $('#srlMap').hide();
                $('#UseMapLocation').hide();
                //com.timmons.srl.Utility.disableSteps(1);
                             
            }
            else{
                $('#srlMap').show();
                if(rlProblemLeaf.MAPREQUIRED != 0 || rlProblemLeaf.MAPREQUIRED != 2){
                    com.timmons.srl.Utility.disableNextButton('#srlStepButtons3 .srlNextStepButton', 3);
                }
                
                if(rlProblemLeaf.MAPREQUIRED == 2){
                    com.timmons.srl.Utility.enableNextButton('#srlStepButtons3 .srlNextStepButton', 3);
                }
            }
        }
        else{
            $('#srlMap').show();
            
            $('#srlDescribe').show();
            $('#srlContactInfo').show();
            $('#srlVerifySubmit').show();
                                
                // Re-Wire Describe Request buttons
                $('#srlStepButtons2 .srlNextStepButton').unbind('click');
                com.timmons.srl.Utility.enableNextButton('#srlStepButtons2 .srlNextStepButton', 2);

                $('#srlStepButtons4 .srlNextStepButton').unbind('click');
                $('#srlStepButtons4 .srlNextStepButton').click(function() {
                    com.timmons.srl.Utility.enableSteps(4);
                    com.timmons.srl.Utility.showStep(4);
                });  
                
                // Re-Wire Contact Information buttons
                $('#srlStepButtons4 .srlPreviousStepButton').unbind('click');
                $('#srlStepButtons4 .srlPreviousStepButton').click(function() {
                    com.timmons.srl.Utility.showStep(2);
                });

                // Re-Wire Verify buttons
                $('#srlStepButtons5 .srlPreviousStepButton').unbind('click');
                $('#srlStepButtons5 .srlPreviousStepButton').click(function() {
                    com.timmons.srl.Utility.showStep(3);
                });
                                
            _isMapLocationRequired = true;
            _dataManager.setMapRequired(true);
            _enableRequestTypeStepNext();
            com.timmons.srl.Utility.enableSteps(2);

            // wire previous button on describe step to go to map step
            $('#srlStepButtons3 .srlPreviousStepButton').unbind('click');
            $('#srlStepButtons3 .srlPreviousStepButton').click(function() {

                com.timmons.srl.Utility.showStep(1);
            
            });        
        
        }
        _checkStepNumbers(rlProblemLeaf);
        

    };
    
    var _checkRLQuestionAnswerData = function(rlQuestionAnswer) {
        _initializeQaList(rlQuestionAnswer);

//        _qaList.setCurrentQaList(problemQuestionList);
//        _qaList.setQaValueList([]);

//        $('#srlQaList').html('');

//        $.each(
//            answers,
//                    function(i, answer) {
//                        try {
//                            //console.log("answer: ", answer);
//                            _qaList.addToQaValueList(answer.question, answer.answer);
//                        } catch (ex) {
//                                //console.warn(ex);
//                        }
//                        }
//                    );
    };



    var _setRequestTypeInformationValue = function(trueFalse) {
        _stateManager.setRequestTypeInformation(trueFalse);
    };

    var _getRequestTypeValue = function() {

        var requestTypeValue = $("#HFProblemsId").val();

        return parseInt(requestTypeValue);
    };

    var _enableRequestTypeStepNext = function() {

        _requestTypeSelected = true;

        $('#srlStepButtons1 .srlNextStepButton').unbind('click');
        com.timmons.srl.Utility.enableNextButton('#srlStepButtons1 .srlNextStepButton', 1);
        
        if(questionsPresented){
            com.timmons.srl.Utility.disableNextButton('#srlStepButtons2 .srlNextStepButton', 2);
        }else{
            com.timmons.srl.Utility.enableNextButton('#srlStepButtons2 .srlNextStepButton', 2);
        }
    };

    var _initializeQaList = function(qaData) {

        if (!_qaList) _qaList = new com.timmons.srl.qaList(_dataManager);

        _qaList.initialize(qaData, _stateManager, _dataManager);

        if (qaData.length > 0){
            questionsPresented = true;
        }else{
            questionsPresented = false;
        }


        if (qaData.length > 0 && qaData[0].QuestionType == "LINK") {
            
            com.timmons.srl.Utility.disableNextButton('#srlStepButtons2 .srlNextStepButton');
            
            // Populate the Information Dialog with the links
            var docHtml = '';

            $('#srlRequestInfoDataWrapper').html('');

            _enableRequestTypeStepNext();
            if(_isMapLocationRequired){com.timmons.srl.Utility.enableSteps(2);}
            
        } else {
            if(qaData.MAPREQUIREDID == 0)
            {
                _isMapLocationRequired = false;
                _dataManager.setMapRequired(false);
            }
            else{
                _isMapLocationRequired = true;
                _dataManager.setMapRequired(true);
            }

            _enableRequestTypeStepNext();
            com.timmons.srl.Utility.enableSteps(1);

            if (qaData.length > 0){
                com.timmons.srl.Utility.disableNextButton('#srlStepButtons2 .srlNextStepButton', 2);
            }else{
                com.timmons.srl.Utility.enableNextButton('#srlStepButtons2 .srlNextStepButton', 2);
            }

            if (!_mapManager.isMapClear()) {

                _mapManager.clear();
                _stateManager.setRequestLocation(null);
                com.timmons.srl.Utility.disableNextButton('#srlStepButtons2 .srlNextStepButton', 2);
            }
        }
    };

    var _cancelInfoRequest = function() {

        if (_isCancelInfoRequest) { // kludge

            $('input[name="RBLKeyword"]').attr('checked', false);
            $('input[name="RBLDepartment"]').attr('checked', false);
            $('input[name="RBLAz"]').attr('checked', false);

            _stateManager.setRequestType();
            _requestTypeSelected = false;
            $(".srlSelectedRequestTypeText").html('None Selected');

            com.timmons.srl.Utility.disableNextButton($('#srlStepButtons1').children('.srlButtonWrapper').children('.srlNextStepButton'), 1);
            com.timmons.srl.Utility.disableSteps();
            com.timmons.srl.Utility.enableSteps(1);
        }
    };

    //Added by James on 7/20/2009 to try to programmatically set the tab.
    var _requestTypeSearchKeyword = function() {

        _showPageLoading();

        //Modified by James Lloyd 11/19/2009
        //Need to filter out extra double-quote characters
        //Break the app if you don't
        //May want to add functionality to handle exact 
        //match of multi-word inputs
        var keyword = $('#tbxKeyword').val().replace(/"/g, '');

        if ($('#tbxKeyword').val().charAt(0) == '\"' &&
                    $('#tbxKeyword').val().charAt($('#tbxKeyword').val().Length - 1) == '\"') {
            _dataManager.getProblemTypesByKeyword2(keyword, this._createProblemTypeInputByKeyword, _createProblemTypeInputByKeyword);
        }
        else {
            _dataManager.getProblemTypesByKeyword(keyword, this._createProblemTypeInputByKeyword, _createProblemTypeInputByKeyword);
        }

        $('#HFProblemTypeTab').val('keyword');  //Added by James on 7/20/2009
    };

    //Added by James on 7/20/2009 to try to programmatically set the tab.
    var _requestTypeSearchDepartment = function() {

        var deptID = $('#lbxSelectDepartment').val();

        if (deptID) {

            _showPageLoading();
            _dataManager.getProblemTypesByDepartment(deptID, this._createProblemTypeInputByDept, _createProblemTypeInputByDept);

        } else {

            $('#requestTypeDeptResultsWrapper').hide('slow');
        }

        $('#HFProblemTypeTab').val('department');  //Added by James on 7/20/2009
    };

    var _createProblemTypeInputAz = function(problems) {

        _problemTypesAz = problems;

        if (_problemTypesAz.length > 20) {
            $("#srlRequestTypesAzPage").show();
            $("#srlRequestTypesAzPage").pagination(_problemTypesAz.length, {
                items_per_page: 20,
                callback: _requestTypeAzPaginationClick
            });
        } else {
            $("#srlRequestTypesAzPage").html();
            $("#srlRequestTypesAzPage").hide();
            _renderProblemTypeInput("RBLAz", "srlAzProblemTypeInput", "#srlRequestTypesAzContent", _problemTypesAz);
        }
        
        if(_problemsIdFromLink){
            if(_findMatchingRequestFromAz()){

            }
        }
    };

    var _requestTypeAzPaginationClick = function(page_index, pagination_container) {

        _renderProblemTypeInputHtml(page_index, _problemTypesAz, "RBLAz", "srlAzProblemTypeInput", "#srlRequestTypesAzContent");

        var requestType = _stateManager.getRequestType();
        if (_requestTypeMethod == "All") {

            $('input[name = "RBLAz"]').each(function() {

                if (requestType == $(this).val()) {

                    $(this).attr('checked', true);
                    return false;
                }
            });
        }
        return false;
    };

    var _createProblemTypeInputByKeyword = function(problems) {

        _problemTypesSearch = problems;
        if (problems.length < 1) {
            $("#srlSearchInstructions").html("<p>No results were found. Please try again with a new keyword.</p>");
        }
        else {
            $("#srlSearchInstructions").html("<p>Select the Request Type that most closely matches your request or search again:</p>");
        }

        if (_problemTypesSearch.length > 20) {
            $("#srlRequestTypesSearchPage").show();
            $("#srlRequestTypesSearchPage").pagination(_problemTypesSearch.length, {
                items_per_page: 20,
                callback: _requestTypeSearchPaginationClick
            });
        } else {
            $("#srlRequestTypesSearchPage").html();
            $("#srlRequestTypesSearchPage").hide();
            _renderProblemTypeInput("RBLKeyword", "srlSearchProblemTypeInput", "#srlRequestTypesSearchContent", _problemTypesSearch);
        }

        //Changed by James Lloyd on 11/19/2009 to remove redundant double quotes...
        //$('#requestTypeSearchResultsWrapper .srlSearchTerms').html($('#tbxKeyword').val());
        if ($('#tbxKeyword').val().charAt(0) == '\"' &&
                    $('#tbxKeyword').val().charAt($('#tbxKeyword').val().Length - 1) == '\"') {
            $('#requestTypeSearchResultsWrapper .srlSearchTerms').html($('#tbxKeyword').val().replace(/"/g, ''));
        }
        else {
            var searchTerms = $('#tbxKeyword').val().split(' ');

            var searchTermsDisplay = new String;

            for (x in searchTerms) {
                if (searchTermsDisplay.length == 0) {
                    searchTermsDisplay = searchTerms[x];
                }
                else {
                    searchTermsDisplay += " OR " + searchTerms[x];
                }

            }

            $('#requestTypeSearchResultsWrapper .srlSearchTerms').html(searchTermsDisplay, '');
        }



        _hidePageLoading(this._showSearchRequestTypes, _showSearchRequestTypes);
    };

    var _showSearchRequestTypes = function() {

        $('#requestTypeSearchResultsWrapper').show('slow');
    };

    var _requestTypeSearchPaginationClick = function(page_index, pagination_container) {

        _renderProblemTypeInputHtml(page_index, _problemTypesSearch, "RBLKeyword", "srlSearchProblemTypeInput", "#srlRequestTypesSearchContent");

        var requestType = _stateManager.getRequestType();

        if (_requestTypeMethod == "Search") {

            $('input[name = "RBLKeyword"]').each(function() {

                if (requestType == $(this).val()) {

                    $(this).attr('checked', true);
                    return false;
                }
            });
        }
        return false;
    };

    var _createProblemTypeInputByDept = function(problems) {

        //var html = _renderProblemTypeInput("RBLDepartment", "srlDeptProblemTypeInput", problems);

        _problemTypesDept = problems;

        if (_problemTypesDept.length > 20) {
            $("#srlRequestTypesDeptPage").show();
            $("#srlRequestTypesDeptPage").pagination(_problemTypesDept.length, {
                items_per_page: 20,
                callback: _requestTypeDeptPaginationClick
            });
        } else {
            $("#srlRequestTypesDeptPage").html();
            $("#srlRequestTypesDeptPage").hide();
            _renderProblemTypeInput("RBLDepartment", "srlDeptProblemTypeInput", "#srlRequestTypesDeptContent", _problemTypesDept);
        }

        $('#requestTypeDeptResultsWrapper .srlSearchTerms').html($('#lbxSelectDepartment :selected').text());

        _hidePageLoading(this._showDepartmentRequestTypes, _showDepartmentRequestTypes);
    };

    var _showDepartmentRequestTypes = function() {

        $('#requestTypeDeptResultsWrapper').show('slow');
    };

    var _requestTypeDeptPaginationClick = function(page_index, pagination_container) {

        _renderProblemTypeInputHtml(page_index, _problemTypesDept, "RBLDepartment", "srlDeptProblemTypeInput", "#srlRequestTypesDeptContent");

        var requestType = _stateManager.getRequestType();

        if (_requestTypeMethod == "Department") {

            $('input[name = "RBLDepartment"]').each(function() {

                if (requestType == $(this).val()) {

                    $(this).attr('checked', true);
                    return false;
                }
            });
        }
        return false;
    };

    var _renderProblemTypeInputHtml = function(page_index, problems, input_name, input_id, targetSelector) {

        var html = '';

        var items_per_page = 20;
        var items_per_col = 10;
        var num_cols = items_per_page / items_per_col; // only works for no remainders

        var max_elem = Math.min((page_index + 1) * items_per_page, problems.length);
        if (problems.length < 1) {
        }
        else {

            for (var j = 0; j < num_cols; j++) {

                html += '<div class="problemTypeCol">';

                var k = page_index * items_per_page + (j * items_per_col);

                var m = Math.min(k + items_per_col, max_elem);

                for (var i = k; i < m; i++) {

                    html += '<div>';
                    html += '<input class="srlRequestTypeInput" type="radio" id="' + input_id + i + '" value="' + problems[i].PROBLEMSID + '" name="' + input_name + '" />';
                    html += '<label for="' + input_id + i + '">' + problems[i].DESCRIPTION + '</label>';
                    html += '</div>';
                }

                html += '</div>';
            }
        }

        html += '<div class="clear"></div>';

        $(targetSelector).html(html);
        //$('input[name=' + input_name + ']').customInput();
    };


    var _renderProblemTypeInput = function(input_name, input_id, targetSelector, problems) {

        var html = '';

        var items_per_page = 20;
        var items_per_col = 10;
        var num_cols = items_per_page / items_per_col; // only works for no remainders
        for (var j = 0; j < num_cols; j++) {

            html += '<div class="problemTypeCol">';

            var k = j * items_per_col;

            var m = Math.min(k + items_per_col, problems.length);

            for (var i = k; i < m; i++) {
                html += '<div>';
                html += '<input class="srlRequestTypeInput" type="radio" id="' + input_id + i + '" value="' + problems[i].PROBLEMSID + '" name="' + input_name + '" />';
                html += '<label for="' + input_id + i + '">' + problems[i].DESCRIPTION + '</label>';
                html += '</div>';
            }

            html += '</div>';
        }

        html += '<div class="clear"></div>';

        $(targetSelector).html(html);
        //$('input[name=' + input_name + ']').customInput();
    };

    var _showRequestTypeStep = function() {

        com.timmons.srl.Utility.enableSteps(0);
        
        //This was added to handle Structured Url input
        if(_problemsIdFromLink){
            com.timmons.srl.Utility.showStep(1);
            com.timmons.srl.Utility.disableSteps(0);
            com.timmons.srl.Utility.enableSteps(2);
        }else{
            com.timmons.srl.Utility.showStep(0);
        }
        
    };

    var _initializeMapLocationStep = function() {

        // Anything that needs to occur after the Map Step is shown
        if (!_isMapInitialized) _showPageLoading();

        _mapManager.displayMap(this._mapLocationStepMapComplete, _mapLocationStepMapComplete);
    };

    var _mapLocationStepMapComplete = function() {

        _mapManager.setMainMarkerRequestType(_stateManager.getRequestTypeText());

        if (!_isMapInitialized) {

            $("#AddressIn").keypress(function(e) {
                if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                    $('#btnMapAddress').click();
                    return false;
                } else {
                    return true;
                }
            });

            // Allow the user to click on the map to designate the location of the request
            _mapManager.enableMapClickLocation(_configurationSettings.serviceAreas, this._enableMapLocationStepNext, _enableMapLocationStepNext);

            $('#btnMapAddress').click(function() {

                var address = jQuery.trim($('#AddressIn').val());

                if (!address) {

                    _stateManager.setRequestLocation(null);
                    _mapManager.clear();
                    com.timmons.srl.Utility.disableNextButton($('#srlStepButtons2').children('.srlButtonWrapper').children('.srlNextStepButton'), 1);
                    alert('Please enter an address.');

                } else {

                    //_dataManager.getCityStateList(this._createCandidatesList, _createCandidatesList);
                    _showPageLoading();
                    _createCandidatesList(_configurationSettings.serviceAreas); //nvs 20090915
                }
            });

            _isMapInitialized = true;

            _hidePageLoading();
        }
    };

    var _createCandidatesList = function(cityStateList) {

        var address = $('#AddressIn').val();

        _mapManager.findAddress(address, cityStateList, this._enableMapLocationStepNext, _enableMapLocationStepNext);
    };

    var _enableMapLocationStepNext = function(success) {

        var next_button = $('#srlStepButtons3').children('.srlButtonWrapper').children('.srlNextStepButton');

        if (success) {
            var address = _mapManager.getAddress();
            _stateManager.setRequestLocation(address);

            var addressText = '';
            if (address.street) addressText += address.street;
            if (address.city) addressText += ', ' + address.city;
            if (address.state) addressText += ', ' + address.state;
            if (address.zip) addressText += ' ' + address.zip;
            $('#AddressIn').val(addressText);

            _initializeContactInfo(address); // move later
            
            if(_configurationSettings.showExistingRequests){
                _dataManager.getOpenRequestsByType(_stateManager.getRequestType(), this._addMarkersToMap, _addMarkersToMap); // is this the right place?
            }
            
            com.timmons.srl.Utility.enableNextButton($(next_button), 3);

        } else {

            alert(_configurationSettings.GeocodingOutOfBounds);
            _stateManager.setRequestLocation(null);
            com.timmons.srl.Utility.disableNextButton($(next_button), 3);
            _hidePageLoading();
        }
        _hidePageLoading();
    };

    var _addMarkersToMap = function(markersData) {

        _mapManager.addMarkers(markersData);
        _hidePageLoading();
    };

    var _createDepartmentDropdown = function(deptData) {

        var options = '<option value="">Please Select</option>';

        for (var i = 0; i < deptData.length; i++) {

            options += '<option value="' + deptData[i].ProbCatCode + '">' + deptData[i].ProbCatDescription + '</option>';
        }

        //$('#srlRequestTypeTabs').tabs('select', 1);
        $('#lbxSelectDepartment').html(options);

        $('#lbxSelectDepartment').selectmenu({ style: 'dropdown', width: 230, maxHeight: 300 }); // modified selectmenu core code to account for handle
        //$('#srlRequestTypeTabs').tabs('select', 0);
    };

    var _createStateSelectorDropdown = function() {
        var options = '<option value="">Select State</option>';

        options += '<option value="-1">Outside U.S.</option>';
        options += '<option value="AL">ALABAMA</option>';
        options += '<option value="AK">ALASKA</option>';
        options += '<option value="AS">AMERICAN SAMOA</option>';
        options += '<option value="AZ">ARIZONA</option>';
        options += '<option value="AR">ARKANSAS</option>';
        options += '<option value="CA">CALIFORNIA</option>';
        options += '<option value="CO">COLORADO</option>';
        options += '<option value="CT">CONNECTICUT</option>';
        options += '<option value="DE">DELAWARE</option>';
        options += '<option value="DC">DISTRICT OF COLUMBIA</option>';
        options += '<option value="FM">FEDERATED STATES OF MICRONESIA</option>';
        options += '<option value="FL">FLORIDA</option>';
        options += '<option value="GA">GEORGIA</option>';
        options += '<option value="GU">GUAM</option>';
        options += '<option value="HI">HAWAII</option>';
        options += '<option value="ID">IDAHO</option>';
        options += '<option value="IL">ILLINOIS</option>';
        options += '<option value="IN">INDIANA</option>';
        options += '<option value="IA">IOWA</option>';
        options += '<option value="KS">KANSAS</option>';
        options += '<option value="KY">KENTUCKY</option>';
        options += '<option value="LA">LOUISIANA</option>';
        options += '<option value="ME">MAINE</option>';
        options += '<option value="MH">MARSHALL ISLANDS</option>';
        options += '<option value="MD">MARYLAND</option>';
        options += '<option value="MA">MASSACHUSETTS</option>';
        options += '<option value="MI">MICHIGAN</option>';
        options += '<option value="MN">MINNESOTA</option>';
        options += '<option value="MS">MISSISSIPPI</option>';
        options += '<option value="MO">MISSOURI</option>';
        options += '<option value="MT">MONTANA</option>';
        options += '<option value="NE">NEBRASKA</option>';
        options += '<option value="NV">NEVADA</option>';
        options += '<option value="NH">NEW HAMPSHIRE</option>';
        options += '<option value="NJ">NEW JERSEY</option>';
        options += '<option value="NM">NEW MEXICO</option>';
        options += '<option value="NY">NEW YORK</option>';
        options += '<option value="NC">NORTH CAROLINA</option>';
        options += '<option value="ND">NORTH DAKOTA</option>';
        options += '<option value="MP">NORTHERN MARIANA ISLANDS</option>';
        options += '<option value="OH">OHIO</option>';
        options += '<option value="OK">OKLAHOMA</option>';
        options += '<option value="OR">OREGON</option>';
        options += '<option value="PW">PALAU</option>';
        options += '<option value="PA">PENNSYLVANIA</option>';
        options += '<option value="PR">PUERTO RICO</option>';
        options += '<option value="RI">RHODE ISLAND</option>';
        options += '<option value="SC">SOUTH CAROLINA</option>';
        options += '<option value="SD">SOUTH DAKOTA</option>';
        options += '<option value="TN">TENNESSEE</option>';
        options += '<option value="TX">TEXAS</option>';
        options += '<option value="UT">UTAH</option>';
        options += '<option value="VT">VERMONT</option>';
        options += '<option value="VI">VIRGIN ISLANDS</option>';
        options += '<option value="VA">VIRGINIA</option>';
        options += '<option value="WA">WASHINGTON</option>';
        options += '<option value="WV">WEST VIRGINIA</option>';
        options += '<option value="WI">WISCONSIN</option>';
        options += '<option value="WY">WYOMING</option>';


        $('#lbxState').html(options);
        $('#lbxState').selectmenu({ style: 'dropdown', width: 230, maxHeight: 125 });

        _currentStateValue(_configurationSettings.defaultSate);
    };

    return {
        //Declare public properties here
        //Declare public methods here        
        initialize: function(mapManager, dataManager, configurationSettings) { //nvs 20090915 added 'configurationSettings' method parameter

            _initialize(mapManager, dataManager, configurationSettings);
        },
        myAlexUserJson:function(jsonIn){
            _myAlexUserJson = jsonIn;
        },
        stopNavAwayAlert: function(valIn){
            //valIn = true or false
            _stopNavAwayAlert = valIn;
        },
        showMapStepContent: function() {

            $('#srlMap .ui-accordion-content').show();
        },
        hideMapStepContent: function() {

            $('#srlMap .ui-accordion-content').hide();
        },
        getMapManager: function() {

            return _mapManager;
        },
        getQaList: function() {

            return _qaList;
        },
        getStateManager: function() {

            return _stateManager;
        },
        initializeContactInfo: function(address) {
            //console.log("Enter initializeContactInfo() in interactionManager.js");

            _initializeContactInfo(address);

            //console.log("Exit initializeContactInfo() in interactionManager.js");            
        },
        initializeRequestTypeStep: function() {
            _initializeRequestTypeStep();
        },
        enableContactNextStep: function() {
            _enableContactNextStep();
        },
        renderProblemTypeInputHtml: function(page_index, problems, input_name, input_id, targetSelector) {
            //console.log("Enter renderProblemTypeInputHtml() in interactionManager.js");

            _renderProblemTypeInputHtml(
                page_index,
                problems,
                input_name,
                input_id,
                targetSelector
            );

            //console.log("Exit renderProblemTypeInputHtml() in interactionManager.js");            
        },
        setRequestType: function(element, answers, obj, callback) {
            //console.log("Enter setRequestType() in interactionManager.js");

            //Ok, ok, this might not be the best place for this code 
            //or the best way to do it...I just needed it to work.
            //feel free to move around as needed.

            var elementName = $(element).attr('name');
            var elementValue = $(element).val();

            _stateManager.setRequestType(elementValue);

            $(".srlSelectedRequestTypeText").html($(element).next().text());

            //_dataManager.getProblemQuestionList(elementValue, this._initializeQaList, _initializeQaList);
            $.ajax({
                url: 'WebMethods/SRL_WS.asmx/GetProblemQuestionList',
                data: '{ "ProblemsIDIn": "' + elementValue + '" }',
                success: function(msg) {

                    var problemQuestionList = eval('(' + msg + ')');
                    //console.log(problemQuestionList);

                    _initializeQaList(problemQuestionList);

                    _qaList.setCurrentQaList(problemQuestionList);
                    _qaList.setQaValueList([]);

                    $('#srlQaList').html('');

                    $.each(
                        answers,
                        function(i, answer) {
                            try {
                                //console.log("answer: ", answer);
                                _qaList.addToQaValueList(answer.question, answer.answer);
                            } catch (ex) {
                                //console.warn(ex);
                            }
                        }
                    );
                    callback.call(obj);
                }
            });

            //console.log("Exit setRequestType() in interactionManager.js");
        }
    };
};
