	// ==========================================================================
	// ||||||||||||||||||||||||| GLOBAL VARIABLES |||||||||||||||||||||||||||||||
	// ==========================================================================
	// prepare all of the page's rollover graphics
	if(document.images){
		var icon_field_error_off = new Image(); icon_field_error_off.src = '/images/icons/icon_field_error_off.gif';
		var icon_field_error_on = new Image(); icon_field_error_on.src = '/images/icons/icon_field_error_on.gif';
		var icon_field_error_none = new Image(); icon_field_error_none.src = '/images/other/other_clear_spacer.gif';
	}
	
    //jQuery visibility plugin
    (function($){
        $.fn.visibility = function(status) {
            this.css('visibility',status);
            return this;
        }
    })(jQuery)

    //Add TRIM function to JS globally
    String.prototype.trim = function() {
    	return this.replace(/^\s+|\s+$/g,"");
    }
    String.prototype.ltrim = function() {
    	return this.replace(/^\s+/,"");
    }
    String.prototype.rtrim = function() {
    	return this.replace(/\s+$/,"");
    }

    // Replaces all instances of the given substring.
    String.prototype.replaceAll = function(strTarget, strSubString){
        var strText = this;
        var intIndexOfMatch = strText.indexOf( strTarget );
        
        // Keep looping while an instance of the target string
        // still exists in the string.
        while (intIndexOfMatch != -1){
            // Relace out the current instance.
            strText = strText.replace( strTarget, strSubString )
            
            // Get the index of any next matching substring.
            intIndexOfMatch = strText.indexOf( strTarget );
        }
        
        // Return the updated string with ALL the target strings
        // replaced out with the new substring.
        return( strText );
    }

//When the window loads
$(window).load(function() {
    //Add a text box helper to the boxes that have the class
    //This allows text suggestions to be in Text Boxes, but get removed upon focus
    $('.form_input_text_helper').live('focus', function() {change_textbox_helper(this.id,0);});
    $('.form_input_text_helper').live('blur', function() {change_textbox_helper(this.id,1);});

    //Add directive to submit parent form of input boxes
    //This is mainly for IE
    $("input").live('keydown', function(e) {
        if (e.keyCode == 13 && !$(this).hasClass('block_auto_enter')) {
            $(this).parents('form').submit();
            return false;
        }
    });

    //Hide Support/Assistance for IE
    if ($.browser.msie && $.browser.version.substr(0,1)<8) {
      // search for selectors you want to add hover behavior to
      $('#header_assistance_div').attr('style','display:none;');
    }

    //Create a style for the tooltip
    $.fn.qtip.styles.aa_general_tooltip = {
        tip:'bottomLeft',
        width: 300,
        padding: 3,
        background: '#FFFFFF',
        color: 'black',
        textAlign: 'left',
        border: {
            width: 3,
            radius: 5,
            color: '#ff9600'
        }
    }
    
    //Assign the tooltip to all the general tooltips
    $(".general_tooltip").live('mouseover', function() {
        if (!$(this).data('qtip'))
        {
            $(this).qtip({
                position: {
                    corner: {
                        target: 'topMiddle',
                        tooltip: 'bottomLeft'
                    }
                },
                show: 'mouseover',
                hide: 'click mouseout unload',
                style: 'aa_general_tooltip'
            });
            $(this).trigger('mouseover');
        }
    });

    //Assign the tooltip to all form input items
    $(".form_tooltip").live('focus', function() {
        if (!$(this).data('qtip'))
        {
            $(this).qtip({
                content: $(this).attr('title'),
                position: {
                    corner: {
                        target: 'topLeft',
                        tooltip: 'bottomLeft'
                    }
                },
                show: 'focus',
                hide: 'blur',
                style: 'aa_general_tooltip'
            });
        }
    });
    
    //Remove error class from input items once it's not needed
    $("input,textarea,select").live('focus', function() {
        //Get the name of this input
        this_id_name = $(this).attr('id');
        
        //Remove error class from input and it's label
        if($(this).hasClass('form_input_error')){$(this).removeClass('form_input_error')}
        $('#' + this_id_name + '_label').removeClass('form_label_error');
        $('#' + this_id_name + '_error').visibility('hidden');
    });
});
	
	// ==========================================================================
	// ||||||||||||||||||||||||| FUNCTIONS |||||||||||||||||||||||||||||||
	// ==========================================================================

    //Check if something is an array
    function isArray(obj) {
        if(!obj){return false;}
       if (obj.constructor.toString().indexOf("Array") == -1 && obj.toString().indexOf("[object Object]") == -1)
          return false;
       else
          return true;
    }
    
    function strip_nonnumeric(val)
    {
        return val.replace(/[^0-9]/g, '');
    }
	
	//Check if this is Internet explorer
	function browser_is_ie()
	{
	   if(navigator.appName == "Microsoft Internet Explorer")
	   {
	       return true;
	   }else{
	       return false;
	   }
	}
	
	//Check the version of this browser
	function browser_version()
	{
        return parseFloat(navigator.appVersion);
	}
	
	//If there Browser is a certain version assign class variables
	if(browser_is_ie() && browser_version() < 8)
	{
	   var classText = "className";
	}else{
	   var classText = "class";
	}

    /******SPECIFIC FUNCTIONS FOR DATA TABLES******/
    function dt_fnSetKey( aoData, sKey, mValue )
    {
        for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
        {
            if ( aoData[i].name == sKey )
            {
                aoData[i].value = mValue;
            }
        }
    }
     
    function dt_fnGetKey( aoData, sKey )
    {
        for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
        {
            if ( aoData[i].name == sKey )
            {
                return aoData[i].value;
            }
        }
        return null;
    }
    /******SPECIFIC FUNCTIONS FOR DATA TABLES******/
	
	//Set a timeout for certain functions. The timeout will prevent a function from happening in case a user continues hitting keystrokes
    var timeout_functions_arr = new Object();
	function timeout_function_set(timeout_vars)
	{
        if(!isArray(timeout_vars)){ timeout_vars = new Object; }

        if(timeout_functions_arr[timeout_vars['field_name']]){ clearTimeout(timeout_functions_arr[timeout_vars['field_name']]); }
        timeout_functions_arr[timeout_vars['field_name']] = setTimeout(timeout_vars['field_function'], ((timeout_vars['timeout_duration']) ? timeout_vars['timeout_duration'] : '0' ));
	}
	
	//field_id* = the id of the text box/area field
	//display_type = 0 - Hide help
    //              1 - Show help
	function change_textbox_helper(field_id, display_type)
	{
        original_width = $("#" + field_id).width();
        original_height = $("#" + field_id).height();
        if(display_type == 0)
        {
            if($("#" + field_id).attr('value') == $("#" + field_id).attr('defaultValue'))
            {
                $("#" + field_id).attr('value', '');
                $("#" + field_id).attr('style', 'color:black;');
            }
        }else if(display_type == 1)
        {
            if(trim($("#" + field_id).attr('value')) == "" || $("#" + field_id).attr('value') == $("#" + field_id).attr('defaultValue'))
            {
                $("#" + field_id).attr('value', $("#" + field_id).attr('defaultValue'));
                $("#" + field_id).attr('style', 'color:gray;');
            }
        }
        $("#" + field_id).width(original_width);
        $("#" + field_id).height(original_height);
	}

	//This function allows any components display setting to be changed depending on what you want
	//id_name - the ID of the div/span/etc.
	//display_type - whether you want to show/hid
	//				0 = hide
	//				1 = show
	//				2 = toggle
	function change_display_value(id_name, display_type)
	{
		if(display_type == 2)
		{
			if(document.getElementById(id_name).style.display == "block")
			{
				display_type = 0;
			}else{
				display_type = 1;
			}
		}
	
		if(display_type == 1)
		{
			display_text = "block";
		}else if(display_type == 0){
			display_text = "none";
		}
		
		document.getElementById(id_name).style.display = display_text;
	}

	function display_help_text(field_name, toggle_type)
	{
		field_name = field_name.name;
		if(document.getElementById(field_name + "_info")){
    		if(toggle_type == 1)
    		{
    			document.getElementById(field_name + "_info").innerHTML = help_text[field_name];
    			$("#" + field_name + "_info").attr('class', 'feedback_help');
    			
    			if(document.getElementById(field_name + "_label"))
    			{
    				document.getElementById(field_name + "_label").style.color = "black";
    			}
    		}else{
    			$("#" + field_name + "_info").attr('class', 'feedback_hidden');
    		}
        }
	}

	function display_error_text(errors_arr, is_new_version)
	{
        for(var field_name in errors_arr) {
            if(field_name == "error_all")
            {
                message_box_display("error", '', errors_arr[field_name]);
            }else{
                //New version handling of errors
                if(is_new_version == true)
                {
                    //Update the classes for text box, label, etc. with errors
                    $("#" + field_name).addClass('form_input_error'); //Input box
                    $('#' + field_name + '_label').addClass('form_label_error'); //label
                    $('#' + field_name + '_error').html(errors_arr[field_name]); //error text
                    $('#' + field_name + '_error').visibility('visible');
                    //$('' + field_name).qtip('updateStyle');
                }else{
                //AA 2
        			document.getElementById(field_name + "_info").innerHTML = errors_arr[field_name];
                    $("#" + field_name + "_info").attr('class', 'feedback_error');
        			
        			if(document.getElementById(field_name + "_label"))
        			{
        				document.getElementById(field_name + "_label").style.color = "black";
        			}
                }
            }
        }
	}
	
	total_z_index = 100;
	function message_box_display(message_box_type, message_title, message_content)
	{
        posY = getScreenCenterY();
        posX = getScreenCenterX();

	   if(message_box_type == 'cs'){$('#' + message_box_type + '_box').draggable({handle: '#' + message_box_type + '_box_handle', containment: 'body'});}
	   var message_box = document.getElementById(message_box_type + "_box");
	   var message_box_title = document.getElementById(message_box_type + "_box_title");
	   var message_box_content = document.getElementById(message_box_type + "_box_content");
	   
	   if(message_title != "")
	   {
	       message_box_title.innerHTML = message_title;
	   }else if(message_box_type == "error"){
	       message_box_title.innerHTML = "Error";
	   }
	   
	   if(message_content != "")
	   {
	       message_box_content.innerHTML = message_content;
	   }
	   
	   if(message_box_type == "error")
	   {
	       message_box_content.innerHTML += '<br /><br /><table border="0" cellspacing="0" cellpadding="0"><tr><td><a href="#" class="error_button" onclick="message_box_hide(\'error\'); return false;">&nbsp;OK&nbsp;</a></td></tr></table>';
	   }
	   
	   message_box.style.visibility = "hidden";
	   message_box.style.display = "block";
	   
	   if(message_box_type != 'cs' || (message_box_type == 'cs' && message_box.style.left == "" && message_box.style.top == ""))
	   {
    	   message_box.style.left = (posX - (message_box.offsetWidth / 2)) + "px";
    	   message_box.style.top = (posY - (message_box.offsetHeight / 2)) + "px";
	   }
	   
	   message_box.style.visibility = "visible";
	   
	   message_box.style.zIndex = parseInt(total_z_index) + 1;
	   total_z_index++;
	}
	
	function message_box_hide(message_box_type)
	{
	   if(!message_box_type){message_box_type = "message";}
	   var message_box = document.getElementById(message_box_type + "_box");
	   
	   total_z_index--;
	   
	   message_box.style.display = "none";
	}
	
	var message_text = "";
	var print_message_box = "";
	function print_message(message_text_tmp)
	{
        message_text = message_text_tmp;
        print_message_box = window.open("/template_blanks/print_message_template.php", "print_message_box", "width=800,height=600,scrollbars=1");
        $(print_message_box.document).ready(function(){print_message_box.focus(); print_message_out();});
        
    }
    
    function print_message_out()
    {
        if(print_message_box.document.getElementById("print_message_text"))
        {
            print_message_box.document.getElementById("print_message_text").innerHTML = message_text;
            print_message_box.print();
        }else{
            setTimeout("print_message_out();", 100);
        }
    }

    function format_money(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;

    }

    function format_number(nStr)
    {
    	nStr += '';
    	x = nStr.split('.');
    	x1 = x[0];
    	x2 = x.length > 1 ? '.' + x[1] : '';
    	var rgx = /(\d+)(\d{3})/;
    	while (rgx.test(x1)) {
    		x1 = x1.replace(rgx, '$1' + ',' + '$2');
    	}
    	return x1 + x2;
    }

    function compile_checked_list(form_checkboxes)
    {
        var compile_check_arr = new Array();
        var list_count = 0;
        
        $("input[name=" + form_checkboxes + "]:checked").each(function(){
            compile_check_arr.push(this.value);
        });
        
        return compile_check_arr;
    }

    //action_page = the page where the ajax script is for the function you want to retrieve
    //action_type = the name of the request/funciton/ajax
    //parameters = list of all the parameters to send to ajax
    //function_parameters = list of all the parameters you want to pass to the function
    function produce_action(action_page, action_type, parameters, function_parameters)
    {
        //Create an array for the parameters if it doesn't exist
        if(!isArray(parameters)){ parameters = new Object; }
        
        //Loop through functions and create variables to use later
        //The functions allow this function to add extra capability to the request
        var function_parameter_arr = ['confirm_title', 'confirm_text','submit_form','disable_buttons','enable_buttons_force','load_function', 'load_progress_bar', 'load_grid_data', 'return_function', 'force_function', 'load_js', 'refresh_page', 'load_tinymce', 'return_dev_alert'];
        for (i = 0; i < function_parameter_arr.length; i++)
        {
            eval('var ' + function_parameter_arr[i] + ' = "";');
        }
        if(function_parameters)
        {
            var list_count = 0;
            var new_function_parameters = Array();
            for (var i in function_parameters)
            {
                if(i == "load_grid_data"){load_grid_data = 1; continue;}
                if(i == "disable_buttons")
                {
                    if(!$.isArray(function_parameters[i])){function_parameters[i] = [function_parameters[i]];}
                    function_parameters[i] = "['" + function_parameters[i].join("','") + "']";
                    new_function_parameters[list_count] = "'" + i + "':" + function_parameters[i];
                    eval('var ' + i + ' = ' + function_parameters[i] + ';');
                    list_count++;
                    continue;
                }

                eval('var ' + i + ' = "' + function_parameters[i].replace(/"/g, '\\"').replace(/\n/g, '') + '";');
                
                if(i == "confirm_title" || i == "confirm_text"){ function_parameters[i] = ""; }
                new_function_parameters[list_count] = "'" + i + "':'" + function_parameters[i].replace(/'/g, "\\'") + "'";
                
                list_count++;
            }
        }
        
        //If this is a form submission, grab all the form fields and pass it through
        if(submit_form != "")
        {
            //Remove focus from whatever has it to disable any tips
            $("body").blur();
            var request_parameters = AjaxRequest.serializeForm(document.getElementById(submit_form));
            if(request_parameters != "")
            {
                request_parameters = request_parameters.split("&");
                for(i=0; i<request_parameters.length;i++)
                {
                    if(!parameters[request_parameters[i].split("=")[0]]){parameters[request_parameters[i].split("=")[0]] = decodeURIComponent(request_parameters[i].split("=")[1]);}
                }
            }
        }
        
        //If there are submission parameters or just passwed parameters, create an array to pass
        if(parameters)
        {
            var list_count = 0;
            var new_parameters = Array();
            for (var i in parameters)
            {
                new_parameters[list_count] = "'" + i + "':'" + parameters[i]+ "'";
                list_count++;
            }
        }
        
        //If the show confirmation message is selectect, show a message and then on "Yes" send out the function
        if(confirm_text != "")
        {
            message_box_display('message', confirm_title, confirm_text + '<br /><br /><div class="float_l"><a href="#" class="g_button g_button_small g_button_yes" onclick="produce_action(\'' + action_page + '\', \'' + action_type + '\', {' + new_parameters + '}, {' + new_function_parameters + '}); message_box_hide(\'message\'); return false;">Yes</a></div><div class="float_l">&nbsp;&nbsp;</div><div class="float_l"><a href="#" class="g_button g_button_small g_button_yes" onclick="message_box_hide(\'message\'); return false;">No</a></div><br /><br />');
            return false;
        }

        //If there are any buttons to disable, do it now
        if(disable_buttons)
        {
            for (var i in disable_buttons)
            {
                $('#' + disable_buttons[i]).hide();
            }
        }
        
        //Create the Ajax request
       	AjaxRequest.post(
       	        {
    				'url':'/ajax/' + action_page
    				,'parameters':parameters
    				,'request_type':action_type
    				,'onLoading':function(){
    				                            //Check if a progress bar should be shown during load
    				                            if(load_progress_bar == "1")
    				                            {
    				                            }else if(load_progress_bar != ""){
    				                                document.getElementById(load_progress_bar).innerHTML = '<p><img src="/images/ajax_loader.gif" border="0" /></p>';
    				                            }
    				                            if(load_function != "")
    				                            {
    				                                eval(load_function);
    				                            }
    				                        }
    				,'onSuccess':function(req)
    										{
                                                if(return_dev_alert){alert(req.responseText);}
                                                //If a main error was passed, show it
    							                if(req.responseText.substring(0,6) == "error:")
    							                {
    							                }else if(req.responseText.substring(0,13) == "errors_array:")
    							                {
                                                    //If a list of errors are there, display it for the fields that have the errors
    							                    eval(req.responseText.substring(13));
    							                    display_error_text(error_text);
    
    							                    for(i=0; i<disabled_action_buttons.length; i++)
    							                    {
    							                        document.getElementById(disabled_action_buttons[i] + "_on").style.display = "block";
    							                        document.getElementById(disabled_action_buttons[i] + "_off").style.display = "none";
    							                    }
    							                }else if(req.responseText.substring(0,5) == "json:")
    							                {
                                                    //If this is a JSON feedback
                                                    //We are transitioning to JSON so all newer functions will use this and 
                                                    //older functions will use the retro way in the next if
                                                    //However, all the retro fuctions should be updated
                                                    req.responseText = req.responseText.substring(5);
                                                    //Create JSON object                                                    
                                                    eval('var ajax_json_obj = ' + req.responseText);
                                                    
                                                    //Display errors if they are passed
                                                    if(enable_buttons_force){var enable_buttons = true;}else{var enable_buttons = false;}
                                                    if(ajax_json_obj['error'])
                                                    {
        							                    message_box_display("error", '', ajax_json_obj['error']);
        							                    setTimeout("message_box_hide('error')", 3000);
        							                    enable_buttons = true;
                                                    }else if(ajax_json_obj['errors_array'])
                                                    {
                                                        //Display text box errors
                                                        display_error_text(ajax_json_obj['errors_array'], true);
                                                        enable_buttons = true;
                                                    }else if(req.responseText != "")
    							                    {
                                                        //If this is data for the grid, load it
                                                        if(load_grid_data != ""){ eval("var d = " + ajax_json_obj['grid_data']); function_parameters["load_grid_data"](d); }
                                                        
                                                        //If everything was successfull
                                                        //Run after retrieval function if there was on passed
    							                        if(return_function != "")
    							                        {
                                                            //Loop through all the variable sent through JSON and replace the items in the function
                                                            var replace_string = "";
                                                            for(var i in ajax_json_obj) {
                                                                return_function = return_function.replace('[aa:' + i + ']', 'ajax_json_obj[\'' + i + '\']')
                                                            }
                                                            
                                                            //Run the function
    							                            eval(return_function);
    							                        }

                                                        //If output is asking to do a redirection
    							                        if(ajax_json_obj['js_redirect'])
    							                        {
                                                            js_redirect(ajax_json_obj['js_redirect']);
    							                        }

    							                        //If there wasn't a function or if there is a message to display
    							                        //if(return_function == "" || ajax_json_obj['message_title'])
    							                        if(ajax_json_obj['message_title'])
    							                        {
                                                            //Add Ok button if need be
                                                            if(ajax_json_obj['message_ok_button'] == '1')
                                                            {
                                                                ajax_json_obj["message_text"] += '<br /><br /><div><a href="#" class="g_button g_button_small g_button_yes" onclick="message_box_hide(\'message\'); return false;">Ok</a></div><br /><br />';
                                                            }
                                                            //Display the message
    							                            message_box_display("message", ajax_json_obj['message_title'], ajax_json_obj["message_text"]);
    							                            
    							                            //Hide if there is a timeout
                                                            if(ajax_json_obj['message_set_timeout'])
                                                            {
                							                    setTimeout("message_box_hide('message')", parseInt(ajax_json_obj['message_set_timeout']));
                                                            }
                                                            
                                                            enable_buttons = true;
    							                        }
    							                    }else if(force_function == '1'){
                                                        //Run the return function even if nothing was paseed, but user wants a force
    							                        eval(return_function);
    							                    }
    							                    
    							                    //Refresh the page
                                                    if(refresh_page == "1")
                                                    {
    							                        location.reload();
                                                    }
                                                    
                                                    //Do a JS load if it was passed through JSON
                                                    if(load_js && ajax_json_obj['js_onload'])
                                                    {
                                                        eval(ajax_json_obj['js_onload']);
                                                    }

                                                    //If there are any buttons that are disabled, enable them
                                                    if(disable_buttons && enable_buttons)
                                                    {
                                                        for (var i in disable_buttons)
                                                        {
                                                            $('#' + disable_buttons[i]).show();
                                                        }
                                                    }
    							                }else{
                                                    //If everything was successfull, check if information needs to be parsed
    							                    if(req.responseText != "")
    							                    {
    							                        response_parse = req.responseText.split(";|;|;|;|");
    							                        if(return_function != "")
    							                        {
    							                            eval(return_function.replace("[aa:return_text]", "response_parse[0]"));
    							                        }else{
    							                            message_box_display("message", response_parse[0], response_parse[1]);
    							                        }
    							                    }else if(force_function == '1'){
    							                         eval(return_function);
    							                    }
                                                    if(refresh_page == "1")
                                                    {
                                                        location.reload();
                                                    }
                                                    if(load_tinymce != "")
                                                    {
                                                        tinyMCE.idCounter = 0;
                                                        tinyMCE.execCommand('mceAddControl', true, load_tinymce);
                                                    }
    											}
    										}
    			}
    		);
    }
    
    //Update the position of the Flashback Navigation so that it's positioned at the bottom
    function update_flashback_nav()
    {
        $('#flashback_navigation').css('top', ($(window).height() + document.documentElement.scrollTop - $('#flashback_navigation').height() - 2) + 'px');
        $('#flashback_navigation').css('display', 'block');
    }


    var uploads_in_progress = false;
    var uploads_in_queue = 0;
    var uploads_count = 0;
    var uploads_queue = new Array();
    function uploads_add_queue(upload_field)
    {
        var error_text = new Array();
        var errors = false;
        
        uploads_count++;
        
        file_name = upload_field.value;
        if(file_name.lastIndexOf("\\")){ file_name = file_name.substring(file_name.lastIndexOf("\\") + 1) }

        
        if(errors == true)
        {
            display_error_text(error_text);
        }else{
            var new_div = document.createElement('div');
            new_div.innerHTML = '<span id="uploads_text_' + uploads_count + '"><span style="color: red; font-weight: bold;">Uploading:</span> ' + file_name + ' (<a href="#" class="link" onclick="uploads_cancel(' + uploads_count + '); return false;">cancel upload</a>)</span>';
            document.getElementById("uploads_section_list").appendChild(new_div);
            
            uploads_queue.push(uploads_count);
            
            var uploads_submit_form = document.createElement("form");
            uploads_submit_form.name = "uploads_submit_form_" + uploads_count;
            uploads_submit_form.id = "uploads_submit_form_" + uploads_count;
            uploads_submit_form.method = "post";
            uploads_submit_form.action = "/ajax/function_requests.php";
            uploads_submit_form.target = "uploads_target";
            if(browser_is_ie()){ enc_type = uploads_submit_form.getAttributeNode("enctype"); enc_type.value = "multipart/form-data"; }else{ uploads_submit_form.enctype = "multipart/form-data"; }
            document.body.appendChild(uploads_submit_form);
            uploads_submit_form.style.display = "none";
            
            
            var request_type_input = document.createElement('input');
            request_type_input.type = "hidden";
            request_type_input.name = "request_type";
            request_type_input.value = "uploads_process_file";
            uploads_submit_form.appendChild(request_type_input);

            var uploads_clone = upload_field.cloneNode(true);
            if(!browser_is_ie()){ uploads_clone.value = ""; }
            document.getElementById("uploads_section").appendChild(uploads_clone);
            uploads_submit_form.appendChild(upload_field);

            if(uploads_in_progress == false){ uploads_process_queue(0); }
        }
    }
    
    function uploads_process_queue(next_file)
    {
        if(uploads_queue.length > 0 && (uploads_in_progress == false || next_file == 1))
        {
            uploads_in_progress = true;
            uploads_in_queue = uploads_queue.shift();

            document.getElementById("uploads_submit_form_" + uploads_in_queue).submit();
        }
    }
    
    function uploads_process_completed(file_name, file_location, attachment_id)
    {
        document.getElementById("uploads_text_" + uploads_in_queue).innerHTML = '<input type="checkbox" name="message_attachments_' + attachment_id + '" value="' + attachment_id + '" checked="checked">&nbsp;<a href="' + file_location + '" target="_blank" class="link">' + file_name + '</a>';
        if(uploads_queue.length > 0){ uploads_process_queue(1); return false; }
        uploads_in_progress = false;
    }
    
    function uploads_cancel(upload_id)
    {
        document.getElementById("uploads_text_" + upload_id).style.display = "none";
        if(upload_id == uploads_in_queue)
        {
            if(browser_is_ie()){ uploads_target.document.execCommand('Stop'); }else{ uploads_target.stop(); }
            setTimeout("uploads_process_queue(1);", 1000);
        }else{
            for(i=0; i<uploads_queue.length; i++)
            {
                if(uploads_queue[i] == upload_id)
                {
                    uploads_queue.splice(i, 1);
                    break;
                }
            }
        }
    }

    function file_upload_process_iframe()
    {
        var error_text = new Array();
        var errors = false;
        
        file_name = document.file_upload_form.file_upload.value;
        
        if(file_name.length == 0){ error_text["file_upload"] = "Please select a file to upload"; errors = true; }
        if(file_name.length > 0)
        {
            var ext_dot = file_name.lastIndexOf(".");
            var file_ext = "";
            if( ext_dot != -1 )
            {
                file_ext = file_name.substr(ext_dot + 1,file_name.length).toLowerCase();
            }
            
            if(file_ext != "csv" && file_ext != "txt" && file_ext != "zip")
            {
                error_text["file_upload"] = "TXT/CSV files that are Zipped/UnZipped only"; errors = true;
            }
        }
        if(errors == true)
        {
            display_error_text(error_text, true);
        }else{
            $('#file_upload_form').submit();
            $('#file_upload_box').html('<p>Please wait while your file is being uploaded <span style="color: red;">(do not close this)</span><br /><br /><img src="/images/ajax_loader.gif" border="0" /></p>');
        }
    }

    function taxfile_process_iframe()
    {
        var error_text = new Array();
        var errors = false;
        
        file_name = $('#tax_file').val();
        
        if(file_name.length == 0){ error_text["tax_file"] = "Please select a file to upload"; errors = true; }
        if(file_name.length > 0)
        {
            var ext_dot = file_name.lastIndexOf(".");
            var file_ext = "";
            if( ext_dot != -1 )
            {
                file_ext = file_name.substr(ext_dot + 1,file_name.length).toLowerCase();
            }
            
            if(file_ext != "csv" && file_ext != "txt" && file_ext != "zip")
            {
                error_text["tax_file"] = "CSV files that are Zipped/UnZipped only"; errors = true;
            }
        }
        if(errors == true)
        {
            display_error_text(error_text, true);
        }else{
            $('#upload_tax_file').submit();
            $('#upload_tax_file').html('<p>Please wait while your file is being uploaded <span style="color: red;">(do not close this page)</span><br /><br /><img src="/images/ajax_loader.gif" border="0" /></p>');
        }
    }

    function profile_retrieve_info(account_id)
    {
        produce_action('profile_requests.php','retrieve_info',{'account_id':account_id,'request_from':'pop_up'},'');
    }

    function registration_submit_info()
    {
       	AjaxRequest.submit(
       	        document.registration_form
       	        ,{
       	            'url':'/ajax/registration_requests.php'
					,'request_type':'registration_submit_info'
					,'onSuccess':function(req)
											{
								                if(req.responseText.substring(0,6) == "error:")
								                {
								                    message_box_display("error", '', req.responseText.substring(6));
								                    setTimeout("message_box_hide('error')", 3000);
								                }else if(req.responseText.substring(0,13) == "errors_array:")
								                {
								                    eval(req.responseText.substring(13));
								                    display_error_text(error_text);
								                }else if(req.responseText.substring(0,16) == "existing_domain:")
								                {
								                    message_box_display("message", 'Existing Organization', req.responseText.substring(16));
								                }else if(req.responseText.substring(0,21) == "confirmation_message:")
								                {
								                    message_box_display("message", 'Confirmation', req.responseText.substring(21));
								                }else{
								                    setup_split = req.responseText.split(":");
								                    window.location = ("/registration_completion.php?email_address=" + setup_split[1] + "&setup_id=" + setup_split[0]);
                                                }
											}
				}
			);
    }

    function registration_update_existing_account(account_decision)
    {
        if(account_decision == 1)
        {
            if(!document.existing_account_form.existing_account_id.length)
            {
                document.registration_form.existing_account_id.value = document.existing_account_form.existing_account_id.value;
            }else{
                for (i=0;i<document.existing_account_form.existing_account_id.length;i++)
                {
                      if (document.existing_account_form.existing_account_id[i].checked)
                      {
                             document.registration_form.existing_account_id.value = document.existing_account_form.existing_account_id[i].value;
                      }
                }
            }
        }else{
            document.registration_form.existing_account_id.value = "0";
        }
        
        message_box_hide('message')
        registration_submit_info();
    }

    function network_add_request_confirm(account_id, user_id, network_account_id, request_info)
    {
       	AjaxRequest.post(
       	        {
					'url':'/ajax/network_requests.php'
					,'request_type':'add_request_confirm'
					,'account_id':account_id
					,'user_id':user_id
					,'network_account_id':network_account_id
					,'request_info':request_info
					,'onSuccess':function(req)
											{
								                if(req.responseText.substring(0,6) == "error:")
								                {
								                    message_box_display("error", '', req.responseText.substring(6));
								                    setTimeout("message_box_hide('error')", 3000);
								                }else{
								                    response_parse = req.responseText.split(";|;|;|;|");
								                    message_box_display("message", response_parse[0], response_parse[1]);
												}
											}
				}
			); 
    }

    function network_add_request(account_id, user_id, network_account_id, lender_code, allow_taxservice, request_info,assessment_fee_1,assessment_fee_2)
    {
       	AjaxRequest.post(
       	        {
					'url':'/ajax/network_requests.php'
					,'request_type':'add_request'
					,'account_id':account_id
					,'user_id':user_id
					,'network_account_id':network_account_id
					,'lender_code':lender_code
					,'allow_taxservice':allow_taxservice
					,'request_info':request_info
					,'assessment_fee_1':assessment_fee_1
					,'assessment_fee_2':assessment_fee_2
					,'onSuccess':function(req)
											{
								                if(req.responseText.substring(0,6) == "error:")
								                {
								                    message_box_display("error", '', req.responseText.substring(6));
								                    setTimeout("message_box_hide('error')", 3000);
								                }else{
								                    response_parse = req.responseText.split(";|;|;|;|");
								                    if(response_parse[3])
								                    {
								                        produce_action('network_requests.php', 'create_network_list', {'account_id':account_id, 'user_id':user_id, 'request_from':'home_actions', 'replacement_item':response_parse[2], 'items_total':response_parse[3]}, {'load_progress_bar':'create_network_item_' + response_parse[2],'return_function':'$(\"#create_network_item_' + response_parse[2] + '\").html([aa:display_text]);'});
								                    }else{
    								                    message_box_display("message", response_parse[0], response_parse[1]);
    								                    if(document.getElementById("network_request_action_holder_" + network_account_id)){
    								                        document.getElementById("network_request_action_holder_" + network_account_id).innerHTML = '<span class="network_action_pending">Network Request Pending</span>';
    								                    }
    								                    setTimeout("message_box_hide('message')", 3000);
								                    }
												}
											}
				}
			); 
    }

    function network_delete_request_confirm(account_id, user_id, network_account_id, my_network_id)
    {
       	AjaxRequest.post(
       	        {
					'url':'/ajax/network_requests.php'
					,'request_type':'delete_request_confirm'
					,'account_id':account_id
					,'user_id':user_id
					,'network_account_id':network_account_id
					,'my_network_id':my_network_id
					,'onSuccess':function(req)
											{
								                if(req.responseText.substring(0,6) == "error:")
								                {
								                    message_box_display("error", '', req.responseText.substring(6));
								                    setTimeout("message_box_hide('error')", 3000);
								                }else{
								                    response_parse = req.responseText.split(";|;|;|;|");
								                    message_box_display("message", response_parse[0], response_parse[1]);
												}
											}
				}
			); 
    }

    function network_delete_request(account_id, user_id, network_account_id, my_network_id)
    {
       	AjaxRequest.post(
       	        {
					'url':'/ajax/network_requests.php'
					,'request_type':'delete_request'
					,'account_id':account_id
					,'user_id':user_id
					,'network_account_id':network_account_id
					,'my_network_id':my_network_id
					,'onSuccess':function(req)
											{
								                if(req.responseText.substring(0,6) == "error:")
								                {
								                    message_box_display("error", '', req.responseText.substring(6));
								                    setTimeout("message_box_hide('error')", 3000);
								                }else{
								                    response_parse = req.responseText.split(";|;|;|;|");
								                    message_box_display("message", response_parse[0], response_parse[1]);
								                    if(document.getElementById("network_request_action_holder_" + network_account_id))
								                    {
								                        document.getElementById("network_request_action_holder_" + network_account_id).innerHTML = '<a href="#" class="network_action_add" onclick="network_add_request_confirm(\'' + account_id + '\', \'' + user_id + '\', \'' + network_account_id + '\');">Add To Network</a>';
								                    }
								                    setTimeout("message_box_hide('message')", 3000);
												}
											}
				}
			);
    }

    function inbox_send_message(account_id, user_id, redirect)
    {
        if(uploads_in_progress){message_box_display('error','Attachment Upload In Progress','Please wait till your attachments are uploaded and then click Send again.'); return false;}
        
        var return_function;
        if(redirect == 1)
        {
            return_function = "js_redirect('/inbox.php?view_id=' + [aa:display_text])";
        }else if(redirect != ""){
            return_function = redirect;
        }else{
            return_function = 'message_box_display("message", "Message sent", \'Your message has been sent.<br /><br /><table border="0" cellspacing="0" cellpadding="0"><tr><td><a href="#" class="save" onclick="message_box_hide();return false;">&nbsp;OK&nbsp;</a></td></tr></table>\'); setTimeout("message_box_hide(\'message\')", 3000);';
        }
        produce_action('inbox_requests.php', 'send_message',{'account_id':account_id,'user_id':user_id},{'disable_buttons':['inbox_message_send','inbox_message_cancel'],'submit_form':'send_message','return_function':return_function});
    }

    function inbox_send_template(account_id, user_id, redirect, message_to, message_subject, message_text)
    {
       	AjaxRequest.post(
				{
					'url':'/ajax/inbox_requests.php'
					,'request_type':'send_template'
					,'account_id':account_id
					,'user_id':user_id
					,'redirect':redirect
					,'message_to':message_to
					,'message_subject':message_subject
					,'message_text':message_text
					,'onSuccess':function(req)
											{
								                if(req.responseText.substring(0,6) == "error:")
								                {
								                    message_box_display("error", '', req.responseText.substring(6));
								                    setTimeout("message_box_hide('error')", 3000);
								                }else{
								                    message_box_display("message", 'Send a message', req.responseText);
												}
											}
				}
			);
    }

    function picture_process_iframe()
    {
        var error_text = new Array();
        var errors = false;
        
        file_name = document.upload_picture_file.picture_file.value;
        
        if(file_name.length == 0){ error_text["picture_file"] = "Please select a file to upload"; errors = true; }
        if(file_name.length > 0)
        {
            var ext_dot = file_name.lastIndexOf(".");
            var file_ext = "";
            if( ext_dot != -1 )
            {
                file_ext = file_name.substr(ext_dot + 1,file_name.length);
                file_ext = file_ext.toLowerCase();
            }
            
            if(file_ext != "jpg" && file_ext != "png")
            {
                error_text["picture_file"] = "JPG or PNG files only"; errors = true;
            }
        }
        if(errors == true)
        {
            display_error_text(error_text);
        }else{
            document.upload_picture_file.submit();
            document.getElementById("picture_upload_box").innerHTML = 'Please wait while your file is being uploaded<br /><br /><img src="/images/ajax_loader.gif" border="0" />';
        }
    }

    var g_parcel_status = "";
    var g_parcel_search = "";

    //info_type =   0 - Just info
    function property_file_retrieve(agent_id, collector_id, parcel_status, parcel_search, is_collector, lender_code, parcel_last_modified)
    {
        g_parcel_status = parcel_status;
        g_parcel_search = parcel_search;
        
        document.getElementById("property_file_box").innerHTML = '<p>Please wait while your file is being loaded<br /><br /><img src="/images/ajax_loader.gif" border="0" /></p>';
        
       	AjaxRequest.post(
       	        {
					'url':'/ajax/property_file_requests.php'
					,'request_type':'retrieve_file'
					,'agent_id':agent_id
					,'collector_id':collector_id
					,'parcel_status':parcel_status
					,'parcel_search':parcel_search
					,'is_collector':is_collector
					,'lender_code':lender_code
					,'parcel_last_modified':parcel_last_modified
					,'onSuccess':function(req)
											{
								                if(req.responseText.substring(0,6) == "error:")
								                {
								                    message_box_display("error", '', req.responseText.substring(6));
								                    setTimeout("message_box_hide('error')", 3000);
								                }else{
								                    document.getElementById("property_file_box").innerHTML = req.responseText;
												}
											}
				}
			);
    }
    
    function property_group_toggle(agent_id, collector_id, parcel_grp, parcel_status, parcel_search, is_collector, lender_code, parcel_last_modified)
    {
        if(document.getElementById("parcel_grp_" + parcel_grp).innerHTML == "")
        {
           	AjaxRequest.post(
           	        {
    					'url':'/ajax/property_file_requests.php'
    					,'request_type':'retrieve_file_parcels'
    					,'agent_id':agent_id
    					,'collector_id':collector_id
    					,'parcel_grp':parcel_grp
    					,'parcel_status':parcel_status
    					,'parcel_search':parcel_search
    					,'is_collector':is_collector
                        ,'lender_code':lender_code
                        ,'parcel_last_modified':parcel_last_modified
    					,'onLoading':function() { document.getElementById("parcel_grp_" + parcel_grp).innerHTML = 'Please wait while the parcels are being loaded<br /><br /><img src="/images/ajax_loader.gif" border="0" />'; }
    					,'onSuccess':function(req)
    											{
    								                if(req.responseText.substring(0,6) == "error:")
    								                {
    								                    message_box_display("error", '', req.responseText.substring(6));
    								                    setTimeout("message_box_hide('error')", 3000);
    								                }else{
    								                    document.getElementById("parcel_grp_" + parcel_grp).innerHTML = req.responseText;
    												}
    											}
    				}
    			);
        }
        if(document.getElementById("parcel_grp_" + parcel_grp).style.display == "none")
        {
            document.getElementById("parcel_grp_" + parcel_grp).style.display = "block";
            document.getElementById("img_grp_" + parcel_grp).src = "/images/minus.jpg";
        }else{
            document.getElementById("parcel_grp_" + parcel_grp).style.display = "none";
            document.getElementById("img_grp_" + parcel_grp).src = "/images/plus.jpg";
        }
    }

//============================================================================================
//|||||||||||||||||||||||||||||||||| START CUSTOMER SERVICE ||||||||||||||||||||||||||||||||||
//============================================================================================

    //Load up the control panel area on the top right of the header with the newest information
    var cs_control_panel_timeout = '';
    function cs_control_panel_reload()
    {
        if(cs_control_panel_timeout){clearTimeout(cs_control_panel_timeout);}
        produce_action('customer_service_requests.php', 'cs_control_panel', '', {'return_function' : '$(\'#cs_control_panel\').html([aa:display_text])'});
        cs_control_panel_timeout = setTimeout('cs_control_panel_reload()', 60000);
    }
    
    //Open the CS box to show certain information based on what's passed
    function cs_main_open(js_vars)
    {
        //Create the js_vars object if it doesn't exist
        if(!isArray(js_vars)){ js_vars = {}; }
        
        //Hide the CS panel until new data is received
        message_box_hide('cs');
        
        //If this is just a refresh of the task view based on a user's change, pass proper variables
        if(js_vars['cs_task_reload'] == "1")
        {
            js_vars['task_status_id'] = $('#task_status_id').val();
            js_vars['task_type_id'] = $('#task_type_id').val();
            js_vars['account_id'] = $('#account_id').val();
            js_vars['admin_user_id'] = $('#admin_user_id').val();
        }
        
        //Grab new data for the control panel
        produce_action('customer_service_requests.php', 'cs_task_list', js_vars, {'return_function':'message_box_display(\'cs\', [aa:display_title], [aa:display_text]); eval([aa:js_onload]);'});
    }

    //Retrieve the list of all the users for a particular customer
    function cs_task_retrieve_customer_users(js_vars)
    {
        //Create the js_vars object if it doesn't exist
        if(!isArray(js_vars)){ js_vars = {}; }

        //Grab users list
        produce_action('customer_service_requests.php', 'cs_task_retrieve_customer_users', js_vars, {'load_progress_bar':'cs_task_customer_users', 'return_function':'$(\'#cs_task_customer_users\').html([aa:display_text]);'});
    }
    
    function cs_view_comments(js_vars)
    {
        //Create the js_vars object if it doesn't exist
        if(!isArray(js_vars)){ js_vars = {}; }
        
        var return_function_text = 'message_box_display(\'cs\', [aa:display_title], [aa:display_text]);';
        if(js_vars['request_from'] != undefined && js_vars['request_from'] != '')
        {
            return_function_text = '$(\'#' + js_vars['request_from'] + '\').html([aa:display_text]);';
        }

        //Grab comments info
        produce_action('customer_service_requests.php', 'cs_task_comment', js_vars, {'return_function':return_function_text});
    }

//============================================================================================
//|||||||||||||||||||||||||||||||||| END CUSTOMER SERVICE ||||||||||||||||||||||||||||||||||||
//============================================================================================

	
	function confirm_box(confirmText)
	{
		confirmation = confirm(confirmText);
		
		return confirmation;
	}
	
	function trim(str)
	{
		return str.replace(/^\s*|\s*$/g,"");
	}  
  
    function getScreenCenterY() {  
        var y = 0;  
      
        y = getScrollOffset()+(getInnerHeight()/2);  
      
        return(y);  
    }  
      
    function getScreenCenterX() {  
        return(document.body.clientWidth/2);  
    }  
      
    function getInnerHeight() {  
        var y;  
        if (self.innerHeight) // all except Explorer  
        {  
            y = self.innerHeight;  
        } else if (document.documentElement &&  
            document.documentElement.clientHeight)  
            // Explorer 6 Strict Mode  
        {  
            y = document.documentElement.clientHeight;  
        } else if (document.body) // other Explorers  
        {  
            y = document.body.clientHeight;  
        }  
        return(y);  
    }  
      
    function getScrollOffset() {  
        var y;  
        if (self.pageYOffset) // all except Explorer  
        {  
            y = self.pageYOffset;  
        } else if (document.documentElement &&  
                document.documentElement.scrollTop)  
            // Explorer 6 Strict  
        {  
            y = document.documentElement.scrollTop;  
        } else if (document.body) // all other Explorers  
        {  
            y = document.body.scrollTop;  
        }  
        return(y);  
    }
    
    function js_redirect(url)
    {
        window.location = url;
    }
    
    //Grid Functions
    //Grid HTML Sort
    function mygrid_html_sort(a,b,order){ 
        a = a.replace(/(<([^>]+)>)/ig,"");
        b = b.replace(/(<([^>]+)>)/ig,"");
        return (a.toLowerCase()>b.toLowerCase()?1:-1)*(order=="asc"?1:-1);
    }


// ===========================================================================
// take a DOM object and determine its absolute top/left/width/height
// geometry relative to the browser window (body).
function get_abs_geometry(_dObj){
    var jCoords = -1; // assume failure
    var nDeltaX, nDeltaY;
    var t;

    // make sure we're not dealing with null, undefined, or empty string
    if(_dObj != null && _dObj != void(0) && _dObj != ''){
        // if the object has a tagname, then we're most likely working with a DOM object
        if(_dObj.tagName){
            jCoords = new Object();
            jCoords.x = jCoords.y = jCoords.w = jCoords.h = 0;

            // get the DOM object's width and height
            jCoords.w += (_dObj.offsetWidth) ? _dObj.offsetWidth : 0;
            jCoords.h += (_dObj.offsetHeight) ? _dObj.offsetHeight : 0;

            // always count the x,y geometry of the object passed in
            nDeltaX = nDeltaY = 0;
            nDeltaX = (_dObj.offsetLeft) ? _dObj.offsetLeft : 0;
            nDeltaY = (_dObj.offsetTop) ? _dObj.offsetTop: 0;

            // update our coordinates
            jCoords.x += nDeltaX;
            jCoords.y += nDeltaY;

            // look at this DOM object's parent for the next calculation
            _dObj = (_dObj.offsetParent) ? _dObj.offsetParent : _dObj.parentNode;

            // calculate it's position relative to top left corner of browser body
            while(1){
                // if our current object is the body or has no parent, we are done calculating
                if(!_dObj.parentNode || _dObj.tagName.toUpperCase() == 'BODY'){ break; }

                nDeltaX = nDeltaY = 0;
                // ignore poisonous tag geometry.
                // TR's geometry is already taken into account by the TD geometry
                // B, I, U, FONT, CENTER tags geometry should be ignored

                t = _dObj.tagName.toUpperCase();
                if(t!='TR' && t!='TBODY' && t!='B' && t!='I' && t!='U' && t!='FONT' && t!='CENTER' && t!='A'){
                    // continue summing/calculating our rendered position
                    nDeltaX = (_dObj.offsetLeft) ? _dObj.offsetLeft : 0;
                    nDeltaY = (_dObj.offsetTop) ? _dObj.offsetTop: 0;
                }

                jCoords.x += nDeltaX;
                jCoords.y += nDeltaY;

                // look at this DOM object's parent for the next calculation
            	_dObj = (_dObj.offsetParent) ? _dObj.offsetParent : _dObj.parentNode;
            }
        }
    }
    // return our coordinate object (-1 on failure)
    return jCoords;
}
//============================================================================================
//|||||||||||||||||||||||||||||||||| STANDARDIZE ARRAYS ||||||||||||||||||||||||||||||||||||||
//============================================================================================
if(!Array.prototype.pop){
	Array.prototype.pop = function(){
		var last_val = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return last_val;
	}
}
//--------------------------------------------------------------------------------------------
if(Array.prototype.push && ([0].push(true)==true)){ Array.prototype.push = null; }
if(!Array.prototype.push){
	Array.prototype.push = function(){
		for(var i = 0; i < arguments.length; i++){
			this[this.length] = arguments[i];
		}
		return this.length;
	}
}
//============================================================================================




/*REPLACEMENTS FOR NEW DESIGN*/
/*
function display_help_text(field_name, toggle_type)
{
	field_name = field_name.name;
	if(document.getElementById(field_name + "_info")){
		if(toggle_type == 1)
		{
			document.getElementById(field_name + "_info").innerHTML = help_text[field_name];
			$("#" + field_name + "_info").attr('class', 'feedback_help');
			
			if(document.getElementById(field_name + "_label"))
			{
				document.getElementById(field_name + "_label").style.color = "black";
			}
		}else{
			$("#" + field_name + "_info").attr('class', 'feedback_hidden');
		}
    }
}

function display_error_text(errors_arr)
{
    for(var field_name in errors_arr) {
        if(field_name == "error_all")
        {
            message_box_display("error", '', errors_arr[field_name]);
        }else{
			document.getElementById(field_name + "_info").innerHTML = errors_arr[field_name];
            $("#" + field_name + "_info").attr('class', 'feedback_error');
			
			if(document.getElementById(field_name + "_label"))
			{
				document.getElementById(field_name + "_label").style.color = "black";
			}
        }
    }
}
*/
