// ******************************************************
// ab allocation form code:
// ******************************************************

// add a new allocation product row (or continue on if previous row quantity and cspc are blank)
function AddAllocationRow(rowNum) {
    // check to see it the quantity and cspc are blank, if so, move on and don't add another row
    if ($('#number_of_cases_'+rowNum).val() == '' && $('#cspc_'+rowNum).val() == '') {
        // move on, don't add another row
        $('#cc_email').focus();
    } else {
        // create the new row with the next row number
        var newRowNum = rowNum + 1;
        var newRow = GenerateProductRow(rowNum, newRowNum);
        // add the new row after the last row
        $('#allocationList'+rowNum).after(newRow);
        // remove this binded event for creating a new row (it will be added to the new row)
        $('#number_of_cases_'+rowNum).unbind('blur');
        // add the new row action
        $('#number_of_cases_'+newRowNum).bind('blur', function() {
            // add a new item row, default to same from, for codes
            AddAllocationRow(newRowNum);
        });
        // add the suggest action for the product field
        $('#cspc_'+newRowNum).autocomplete({
            source: "/private/ajax_system_select.php?province=ab&type=product_search_full",
            minLength: 2,
            delay: 1000,
            select: function(event, ui) {
                if (ui.item) {
                    $('#cspc_'+newRowNum).val(ui.item.value);
                    $('#wine_description_'+newRowNum).val(ui.item.wine_name);
                    $('#wine_description_span'+newRowNum).html(ui.item.wine_name);
                    $('#for_licensee_number_'+newRowNum).focus();
                } // if
            }
        });
        // add the suggest action for the 'from licensee' field
        $('#from_licensee_number_'+newRowNum).autocomplete({
            source: "/private/ajax_system_select.php?province=ab&type=ab_licensee",
            minLength: 2,
            delay: 1000,
            select: function(event, ui) {
                if (ui.item) {
                    $('#from_licensee_number_'+newRowNum).val(ui.item.value);
                    $('#from_licensee_name_'+newRowNum).val(ui.item.alpha_name);
                    $('#from_licensee_name_span'+newRowNum).html(' <strong>currently allocated to</strong> ' + ui.item.alpha_name);
                    //AddAllocationRow(newRowNum);
                    // update the next blank row if it is still blank
                    var nextRow = newRowNum + 1;
                    if ($('#from_licensee_number_'+nextRow).val() == '') {
                        //$('#from_licensee_number_'+nextRow).val(ui.item.value);
                        //$('#from_licensee_name_span'+nextRow).html(' <strong>from</strong> ' + ui.item.alpha_name);
                    }
                } // if
            }
        });
        // add the suggest action for the 'for licensee' field
        $('#for_licensee_number_'+newRowNum).autocomplete({
            source: "/private/ajax_system_select.php?province=ab&type=ab_licensee",
            minLength: 2,
            delay: 1000,
            select: function(event, ui) {
                if (ui.item) {
                    $('#for_licensee_number_'+newRowNum).val(ui.item.value);
                    $('#for_licensee_name_'+newRowNum).val(ui.item.alpha_name);
                    $('#for_licensee_name_span'+newRowNum).html(' <strong>for</strong> ' + ui.item.alpha_name);
                    //AddAllocationRow(newRowNum);
                    // update the next blank row if it is still blank
                    var nextRow = newRowNum + 1;
                    if ($('#for_licensee_number_'+nextRow).val() == '') {
                        //$('#for_licensee_number_'+nextRow).val(ui.item.value);
                        //$('#for_licensee_name_span'+nextRow).html(' <strong>for</strong> ' + ui.item.alpha_name);
                    }

                } // if
            }
        });
    } // if
} // function addAllocationRow

// confirm, clear, and cancel the ab allocation form
function CancelAllocationForm() {
    // make sure
    if (confirm('Are you sure you want to clear and cancel this form?  All data will be erased.')) {
        // remove all product rows
        $('#abAllocationProducts').empty();
        // add one product row
        var newRow = GenerateProductRow(0,0);
        $('#abAllocationProducts').html(newRow);
        // clear fields
        $('#liis_licensee_id').val('');
        $('#cc_email').val('');
        $('#external_comments').val('');
        $('#internal_comments').val('');
        // hide all but first row of form
        $('#abAllocationHidden').fadeOut(300);
        // re-bind the default events
        $('#licensee_number').focus().bind('keypress', function() {
            $('#abAllocationHidden').fadeIn(300);
            $('#licensee_number').unbind('keypress');
        });
        // bind temporary action to "for" licensee number field for first round, it changes after this
        $('#number_of_cases_0').bind('blur', function() {
            // remove this binded event
            $('#number_of_cases_0').unbind('blur');
            // add a new item row, default to same from, for codes
            AddAllocationRow(0);
        });
    } // if
}

// confirm, validate, and submit the ab allocation form
function SubmitAllocationForm() {
    // make sure
    if (confirm('Are you sure you want to save and submit this allocation form?  The email will be sent to confirm the allocation and this cannot be undone.')) {
        // validate fields
        if ($('#licensee_number').val() == '') {
            // need a licensee value
            alert("Please enter a valid licensee number and try again.");
            return 0;
        } // if
        // submit form
        return true;
    } else {
        return false;
    } // if
}

// generate a new HTML <li></li> row for the ab allocation form products list
function GenerateProductRow(rowNum, newRowNum) {
    var newRow = "\n" + '<li id="allocationList' + newRowNum + '">' + "\n";
    newRow += '<input type="text" size="5" id="number_of_cases_' + newRowNum + '" name="number_of_cases[' + newRowNum + ']" class="quantityInput numeric"  /> cases of ' + "\n";
    newRow += '<input type="text" size="5" id="cspc_' + newRowNum + '" name="cspc[' + newRowNum + ']" class="codeInput" />' + "\n";
    newRow += ' currently allocated to <input type="text" size="5" id="from_licensee_number_' + newRowNum + '" name="from_licensee_number[' + newRowNum + ']" class="codeInput numeric"  />' + "\n";
    newRow += ' for <input type="text" size="5" id="for_licensee_number_' + newRowNum + '" name="for_licensee_number[' + newRowNum + ']" class="codeInput numeric"  />' + "\n";
    newRow += ' <a href="javascript:ClearAllocationRow(' + newRowNum + ')" class="delete"></a>' + "\n";
    newRow += '<br /><div id="allocationListStatus' + newRowNum + '" class="abStatusLine\"><span id="wine_description_span' + newRowNum + '"></span><span id="from_licensee_name_span' + newRowNum + '"></span><span id="for_licensee_name_span' + newRowNum + '"></span></div>' + "\n";
    newRow += '<input type="hidden" id="wine_description_' + newRowNum + '" name="wine_description[' + newRowNum + ']" />' + "\n";
    newRow += '<input type="hidden" id="for_licensee_name_' + newRowNum + '" name="for_licensee_name[' + newRowNum + ']" />' + "\n";
    newRow += '<input type="hidden" id="from_licensee_name_' + newRowNum + '" name="from_licensee_name[' + newRowNum + ']" />' + "\n";
    newRow += '</li>' + "\n";

    return newRow;

} // function GenerateProductRow

// lookup the numbers in the ab allocation product row and populate the status div with the results
function LookupProductLine(rowNum) {

    // only do it if we have a licensee number
    if ($('#cspc_' + rowNum).val() != '' && $('#from_licensee_number_' + rowNum).val() != '' && $('#for_licensee_number_' + rowNum).val() != '') {
        $('#allocationListStatus' + rowNum).fadeOut(500).html('<span class="pleaseWait">look up in progress</span>').fadeIn(1000);
        $.ajax({
          url: 'index.php?c_user_action=item_row_lookup&cspc=' + $('#cspc_' + rowNum).val() + '&from=' + $('#from_licensee_number_' + rowNum).val() + '&for=' + $('#for_licensee_number_' + rowNum).val(),
          success: function(data) {
            if (data == '') {
                // query error
                $('#allocationListStatus' + rowNum).html('no matches found').fadeIn(1000);
            } else {
                $('#allocationListStatus' + rowNum).html(data);
            } // if
          },
          error: function () {
            // ajax error
            $('#allocationListStatus' + rowNum).html('no matches found (error)').fadeIn(1000);
          }
        });
    } // if

} // function

function ClearAllocationRow(rowNum) {
    $('#allocationList'+rowNum + ' :input').val(''); // clear all input fields (including hidden) in this row
    // 20100505 CSN can't get this working: $('#allocationListStatus'+rowNum + '[id~=span]').html(''); // clear the span details in this status row
    $('#wine_description_span'+rowNum).html('');
    $('#for_licensee_name_span'+rowNum).html('');
    $('#from_licensee_name_span'+rowNum).html('');
} // if

// 20091210 CSN added the contents of the following: (these no longer need to be included seperately on any pages in the portal site)
//
// /lib/claerolib_3/display.js
// /lib/third-party/jquery/plugins/jquery.cascade.1.1.1/jquery.cascade.ext.js
// /lib/third-party/jquery/plugins/jquery.cascade.1.1.1/jquery.cascade.js
// jquery cascade commonTemplate stuff

function commonTemplate(item) {
    return "<option value='" + item.Value + "'>" + item.Text + "</option>";
};
function commonTemplate2(item) {
    return "<option value='" + item.Value + "'>***" + item.Text + "***</option>";
};
function commonMatch(selectedValue) {
    return this.When == selectedValue;
};


/*jquery.cascade.js */
/*
 * jQuery UI cascade
 * version: 1.1.1 (6/16/2008)
 * @requires: jQuery v1.2 or later
 * adapted from Yehuda Katz, Rein Henrichs autocomplete plugin
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Copyright 2008 Mike Nichols

 */

;(function($) {

  $.ui = $.ui || {}; $.ui.cascade = $.ui.cascade || {};

  $.fn.cascade = function(parent,opt) {
	if( opt.event ){
		//namespace our event
		opt.event = opt.event.replace('.cascade','') + '.cascade';
	}

    opt = $.extend({}, {
		list: [], //static list to use as datasource
		timeout: 10,//delay before firing getList operation
		getList: function(select) { $(this).trigger("updateList", [opt.list]); }, //function to fetch datasource
		template: function(str) { return "<option value='" + str + "'>" + str + "</option>"; },//applied to each item in datasource
		match: function(selectedValue) { return true;}, //'this' is the js object, or the current list item from 'getList',
		event: "change.cascade",	//event to listen on parent which fires the cascade
		getParentValue: function(parent) { return $(parent).val(); } //delegate for retrieving the parent element's value
    }, opt);

    if($.ui.cascade.ext) {
		for(var ext in $.ui.cascade.ext) {
	        if(opt[ext]) {
	          opt = $.extend(opt, $.ui.cascade.ext[ext](opt));
	          delete opt[ext];
	        }
		}
	}

    return this.each(function() {
		var source = $(parent);
		var self = $(this);

		//bind any events in extensions to each instance
		if($.ui.cascade.event) {
			for(var e in $.ui.cascade.event) {
				self.bind(e + ".cascade",[source],$.ui.cascade.event[e]);
			}
		}

		$(source).bind(opt.event,function() {
			self.trigger("loading.cascade",[source[0]]);

			var selectTimeout = $.data(self, "selectTimeout");
			if(selectTimeout) { window.clearInterval(selectTimeout); }
			$.data(self, "selectTimeout", window.setTimeout(function() {
					self.trigger("cascade");
			}, opt.timeout));

		});

        self.bind("cascade", function() {
          self.one("updateList", function(e, list) {
            list = $(list)
              .filter(function() { return opt.match.call(this, opt.getParentValue(parent)); })
              .map(function() {
                var node = $(opt.template(this))[0];
                return node;
              });

			self.empty();//clear the source/select

            if(list.length){
				self.html(list);
			}

			self.trigger("loaded.cascade",[source[0]]);//be sure to fire even if there is no data

			if( self.is(":input") ) {
				self.trigger("change.cascade");
			}
          });

          opt.getList.call(self[0],source);	//call with child element as this

        });
    });
  };

})(jQuery);


/*jquery.cascade.ui.ext.js */
/*
 * jQuery UI cascade
 * version: 1.1 (5/20/2008)
 * @requires: jQuery v1.2 or later
 * adapted from Yehuda Katz, Rein Henrichs autocomplete plugin
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *  depends on templating  plugin if using with templateText
 * Copyright 2008 Mike Nichols
 */

;(function($) {
	$.ui = $.ui || {};
	$.ui.cascade = $.ui.cascade || {};
	$.ui.cascade.ext = $.ui.cascade.ext || {};
	$.ui.cascade.event = $.ui.cascade.event || {};

	$.ui.cascade.ext.ajax = function(opt) {
		var ajax = opt.ajax;//ajax options hash...not just the url
		return { getList: function(parent) {
			var _ajax = {};
			var $this = $(this);//child element
			var defaultAjaxOptions = {
				type: "GET",
				dataType: "json",
				success: function(json) { $this.trigger("updateList", [json]); },
				data: $.extend(_ajax.data,ajax.data,{ val: opt.getParentValue(parent) })
			};
			//overwrite opt.ajax with required props (json,successcallback,data)
			//this lets us still pass in handling the other ajax callbacks and options
			$.extend(_ajax,ajax,defaultAjaxOptions);

			$.ajax(_ajax);
		} };
	};

	$.ui.cascade.ext.templateText = function(opt) {
	var template = $.makeTemplate(opt.templateText, "<%", "%>");
	return { template: function(obj) { return template(obj); } };
	};

	/*these events are bound on every instance...so the indicator appears  on each target */
	/*
	*	CSS: .cascade-loading: { background: transparent url("${staticDir}/Content/images/indicator.gif") no-repeat center; }
	*/
	$.ui.cascade.event.loading = function(e,source) {
		$(this).empty();
		var position = {
			'z-index':'6000',
			'position':'absolute',
			'width':'16px'
		};
		$.extend(position,$(this).offset());
		position.top = position.top + 3;
		position.left = position.left + 3;
		$("<div class='cascade-loading'>&nbsp;</div>").appendTo("body").css(position);
		$(this)[0].disabled = true;
	};
	$.ui.cascade.event.loaded = function(e,source) {
		$(this)[0].disabled = false;
		$(".cascade-loading").remove();
	};

})(jQuery);

var MULTIPLE_EDIT = 0;

function showCalendar(calendar, link, format, inputId) {
    var inputIdElement = document.getElementById(inputId);
    calendar.select(inputIdElement, link, format, inputIdElement.value);
    return false;
}

// invoked when a user clicks the checkbox to either expire or delete a record
function SetExpireFlag(b) {
  var confirmDeleteForm = document.forms['confirm_delete'];
  if (b) {
      confirmDeleteForm.expiryFlag.value = 1;
  } else {
      confirmDeleteForm.expiryFlag.value = 0;
  }
//    f.submit();
}

function clickContentBox(box, trueValue, falseValue) {
    var pattern = box.id.replace(/checkbox_/, "");
    var checkbox = get(pattern);
    if (! checkbox) {
        alert('System error - this field may not be updated in the database');
    }
    if (box.checked) {
        checkbox.value = trueValue;
    } else {
        checkbox.value = falseValue;
    }
}

function ClickMultipleEdit(checked) {
    if (checked) {
        MULTIPLE_EDIT++;
    } else {
        MULTIPLE_EDIT--;
    }
    var button = document.getElementById('submit_multiple_edit');
    if (button) {
        if (MULTIPLE_EDIT) {
            button.removeAttribute('disabled');
        } else {
            button.setAttribute('disabled', 'disabled');
        }
    }

    if (!checked) {
        // if a checkbox has been unchecked, then uncheck the check all checkbox
        c = document.getElementById('c_check_all');
        if (c) {
            c.checked = false;
        }
    }
}

function SubmitSearch() {
    var i = document.forms['claero_form'];
    eval('i.' + CLAERO_REQUEST_USER_ACTION + '.value = "search";');
    i.target = '_self';
    i.submit();
}

function CancelSearch() {
    var h = document.forms['claero_form'];
    eval('h.' + CLAERO_REQUEST_USER_ACTION + '.value = "cancel_search";');
    h.target = '_self';
    h.submit();
}

function SubmitAdd() {
    var g = document.forms['claero_form'];
    eval('g.' + CLAERO_REQUEST_USER_ACTION + '.value = "add";');
    g.target = '_self';
    g.submit();
}

function RecordCustom(id,action,target) {
    alert (action);
    if (action == 'reverse'){
        if (confirm("Are you sure you want to reverse this order?")){
            var claeroForm = document.forms['claero_form'];
            eval('claeroForm.' + CLAERO_REQUEST_USER_ACTION + '.value = "' + action + '";');
            claeroForm.id.value = id;
            //if (target != 'null'){
                claeroForm.target = target;
            //}
            claeroForm.submit();    
        }
    }else{
        if (confirmDelete(id)) {
          var claeroForm = document.forms['claero_form'];
            eval('claeroForm.' + CLAERO_REQUEST_USER_ACTION + '.value = "' + action + '";');
            claeroForm.id.value = id;
            //if (target != 'null'){
                claeroForm.target = target;
            //}
            claeroForm.submit();
        }     
    }
}

function confirmDelete(name) {
//    input_box=confirm("Are you sure you want to remove '" + name + "' ?");
//    if (input_box==true) {
        return true;
//    }
}

function EditRecords() {
    var claeroForm2 = document.forms['claero_form'];
    if (CountCheckboxes(claeroForm2, 'ids[]') > 0) {
        eval('claeroForm2.' + CLAERO_REQUEST_USER_ACTION + '.value = "edit_multiple";');
        claeroForm2.submit();
    } else {
        alert('Please select atleast one record to edit.');
    }
}

function CountCheckboxes(theForm, name) {
    count = 0;
    for (i=0,n=theForm.elements.length-1;i<n;i++) {
        if (theForm.elements[i].name.indexOf(name) !=-1 && theForm.elements[i].checked == true) count ++;
    }
    return count;
}

function ExportRecords() {
    var claeroForm3 = document.forms['claero_form'];
    if (claeroForm3) {
        eval('claeroForm3.' + CLAERO_REQUEST_USER_ACTION + '.value = "create_csv";');
        claeroForm3.submit();
    }
}
/* not used ??
function RecordAdd(theRecord) {
    var f = document.forms['claero_form'];
    eval('f.' + CLAERO_REQUEST_USER_ACTION + '.value = "add";');
    f.id.value = theRecord;
    f.submit();
}
*/
function CancelForm(theForm, url) {
    // no url was passed, so submit the form
    if (arguments.length == 1) {
        theForm.user_action.value = "cancel";
        theForm.submit();
    // a url was passed, so use that to redirect the browser
    } else {
        document.location = url;
    }
}

function CheckAllCheckBoxes(f, name, checked) {
    if (arguments.length == 2) { checked = true; }
    count = 0;
    var form = GetById(f);
    var children = GetByTagName(f, "input");
    for (i = 0; i < children.length; i++) {
        if (children[i].type == "checkbox") {
            if (!name || children[i].name == name) {
                children[i].checked = checked;
                if (children[i].checked) count++;
            }
        }
    }

    if (checked) {
        return count-1;
    } else {
        return 0;
    }
}

/******************    helper functions    ******************/

// returns the number of checkboxes that are child elements of f and that are checked
/* long and complicated
function CountCheckedBoxes(f, name) {
    var count = 0;
    var children = GetByTagName(f, "input");
    for (var i = 0; i < children.length; i++) {
    alert(children[i].type);continue;
        if (children[i].type == "checkbox" && children[i].checked) {
            if (name) {
                if (children[i].name == name) {
                    count++;
                }
            } else {
                count++;
            }
        }
    }
    return count;
}
*/

// get a reference to an element by id
function GetById(id) {
    if (typeof id == "string") {
        return document.getElementById(id);
    } else {
        return id;
    }
}

// retrieves a list of all child tags with the appropriate name
function GetByTagName(tag, name) {
    if (arguments.length == 1) {
        return document.getElementsByTagName(tag);
    } else {
        var t = GetById(tag);
        if (! t) { return false; }
        return t.getElementsByTagName(name);
    }
}

/** the next 2 functions are for dealing with 1 to multiple edits **/
function AddMultipleRow(formId, table) {
    f = document.getElementById(formId);
    a = document.getElementById('c_add_row');
    if (f && a) {
        a.value = table;
        f.submit();
    } else {
        alert('There was an error while adding a new row.');
    }
}

function RemoveMultipleRow(rowId, deleteFlag) {
    r = document.getElementById(rowId);
    f = document.getElementById(deleteFlag);
    if (r && f) {
        r.style.display = 'none';
        f.value = 1;
    }
}

// jQuery Extension: any fields it is added to will not allow most non numeric values
if (jQuery) {
    jQuery.fn.numeric = function() {
        this.keypress(function(e) {
            var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; // 20100301 CSN e.charCode generates an error on Mac FF 3.6
            if (e.ctrlKey || e.altKey // ctrl or alt key has been pressed
                || (key >= 48 && key <= 57) // numbers
                || key == 9 // tab
                || key == 39 // right, also single quote
                || key == 37 // left, also percent "%"
                || key == 35 // end, also hash "#"
                || key == 36 // home, also dollar symbol "$"
                || key == 8 // backspace
                || key == 46 // delete, also period "."
                || key == 13 // enter
                || key == 45 // dash "-"
                || key == 43) { // plus "+"
                    return true;
            }

            return false;
        });

        return this;
    }
}

/**
 * toggle the advanced search filters (used in saq comp. report for now, could be used anywhere)
 *
 * @param   [string]     action      if 'show', then show, otherwise, hide
 * @return
 */
function ShowHideAdvanced(action) {
    if (action == 'show') {
        $('#advanced_filters').show();
        $('#advanced_search').html('<input type="button" name="advanced" value="Hide Advanced Search Criteria" onclick="ShowHideAdvanced(\'hide\')" />');
    } else {
        $('#advanced_filters').hide();
        $('#advanced_search').html('<input type="button" name="advanced" value="Show Advanced Search Criteria" onclick="ShowHideAdvanced(\'show\')" />');
    } // if
}

/**
 * toggle the help div(s) to display or hide the help text on each screen
 *
 * @param [int]     toggleFlag      if 0, just use the helpFlag global js var, if 1, then toggle it
 * @return [array]                  the running total for the award, or false if error
 */
function ShowHideHelp(toggleFlag) {
    var menuLabel = '';
    $("#helpToggleLinkLabel").html('Setting...');
    if (toggleFlag) {
        // toggle the help
        if (helpFlag == '0') {
            helpFlag = '1';
        } else {
            helpFlag = '0';
        } // if
    } // if
    // fade in or out depending on helpFlag
    if (helpFlag == '0') {
        $(".helpSection").slideUp(300);
        //$(".helpSection").hide();
        helpButton = '<input type="button" class="helpButton" value="Help On" name="togglehelp" onclick="ShowHideHelp(1)" />';
    } else {
        //$(".helpSection").show();
        $(".helpSection").slideDown(300);
        helpButton = '<input type="button" class="helpButton" value="Help Off" name="togglehelp" onclick="ShowHideHelp(1)" />';
    }
    // if we are toggling, then save the new value in the session and database
    if (toggleFlag) {
        $.get("/private/ajax_help.php", {action:'toggle_help'});
    } // if
    $("#helpToggleLinkLabel").html(helpButton);
} // function ShowHideHelp()


/**
 * functions to support the auto-suggest as found on the Quebec private order form, manual sales entry, etc.
 *  USAGE:
 *  on the text field you want to autocomplete add the following onFocus event.
 *  onFocus="AttachSuggest(this, '/private/ajax_system_select.php?company_id='+$('#company_id').val()+'company='+$('#prov').val()+'&type=product_search&search_text=');";
 */

var suggestFormId = '#qcPrivateOrder';
var suggestDelay = null;
var suggestDelayTime = 0;
var currentSelectedIndex = null;
var currentCount = 0;
var resultRowHeight = 17;
var blockSubmit;
var resultData = null;

/**
 * attach the auto suggest to the supplied text field object
 *
 * @param [object]     textField    text field to attach the suggest to
 * @param [string]     requestUrl   what is the URL of the AJAX script returning the values for the selection list
 */
function AttachSuggest(textField, requestUrl) {

    field = $(textField);
    textFieldId = field.attr('id');
    resultDivId = textFieldId + '_results';

    // create and position the result div below the target field
    var offSet = field.offset();
    $('<div id="' + resultDivId + '" class="suggestResults"></div>').css({
        // position the result div
        top: offSet.top + field.outerHeight() + 'px',
        left: offSet.left,
        //width: field.outerWidth()-2 + 'px',
        height: resultRowHeight + 'px'
    }).hide().insertAfter(field);

    //special handling to make sure the width of the autosuggest is wide enough
    if (textFieldId.substring(0, 43) == 'trialto_private_order_qc_items_product_code'  || textFieldId.substring(0, 4)=='cspc') {
        //$('#' + resultDivId).css('width', '500px');
    }

    // 20100301 CSN I don't understand why this is done this way:

    // assign the event actions to activate or hide the suggest feature / results if the field does not already have an 'onkeydown' event
    if (field.attr('onkeydown') == null) {
        eval('field.keydown(function(event) { return GetSuggestions(\'#' + textFieldId + '\', \'#' + resultDivId + '\', \'' + requestUrl + '\', event); } );');
        eval('field.blur(function() { HideSuggest(\'#' + resultDivId + '\'); } );');
    }

    /*
    field.keydown(function(event) {
        return GetSuggestions('#' + textFieldId, '#' + resultDivId, requestUrl, event);
    });
    field.blur(function() {
        HideSuggest('#' + resultDivId);
    });
    */
}
/**
 * function to handle the keydown event
 *
 * @param [string]     textFieldId  id of the text field being suggested
 * @param [string]     resultDivId  id of the results div
 * @param [string]     requestUrl  what is the URL of the AJAX script returning the values for the selection list
 * @param [event]     evt  fired event
 */
function GetSuggestions(textFieldId, resultDivId, requestUrl, evt) {

    // what is this doing?
    var keyCode =
        document.layers ? evt.which :
        document.all ? event.keyCode :
        document.getElementById ? evt.keyCode : 0;

    // prevent form submit in opera when selecting with return key
    $.browser.opera && $($(textFieldId).form).bind("submit.autocomplete", function() {
        if (blockSubmit) {
            blockSubmit = false;
            return false;
        }
    });

    switch (keyCode) {

        case 40 : // down arrow
            if (currentCount > 0) {
                PerformSuggestUpDownArrow(textFieldId, resultDivId, requestUrl);

                if (currentSelectedIndex == null || currentSelectedIndex == (currentCount - 1)) {
                    nowSelect = 0;
                } else {
                    nowSelect = currentSelectedIndex + 1;
                }
                SuggestOver(resultDivId, nowSelect);
            }
            return false;
            break;

        case 38 : // up arrow
            if (currentCount > 0) {
                // if the div is hidden, then we run the suggest function to populate the div and therefore show it
                PerformSuggestUpDownArrow(textFieldId, resultDivId, requestUrl);

                if (currentSelectedIndex == null || currentSelectedIndex == 0) {
                    nowSelect = currentCount - 1;
                } else {
                    nowSelect = currentSelectedIndex - 1;
                }
                SuggestOver(resultDivId, nowSelect);
            }
            return false;
            break;

        case 32 : // space
        case 13 : // return/enter
            if ($(resultDivId).css('display') != 'none') {
                UseSuggest(resultDivId, textFieldId, currentSelectedIndex);

                if (keyCode == 13) {
                    evt.preventDefault();
                    blockSubmit = true;
                }

                return false;
            }
            break;

        case 9 : // tab
        case 16 : // shift + tab
            break;
        default :
            if (suggestDelay == null) suggestDelay = setTimeout('MakeSuggestRequest(\'' + textFieldId + '\', \'' + resultDivId + '\', \'' + requestUrl + '\')', suggestDelayTime);
            break;
    } // switch
}

/**
 * function to handle the actual suggest request to the server
 *
 * @param [string]     textFieldId  id of the text field being suggested
 * @param [string]     resultDivId  id of the results div
 * @param [string]     requestUrl  what is the URL of the AJAX script returning the values for the selection list
 */
function MakeSuggestRequest(textFieldId, resultDivId, requestUrl) {
    var field = $(textFieldId);
    var resultDiv = $(resultDivId); // get the result div

    // Get the company id
    var companyId = $('#private_order_on_agent_id_0').val();

    if (field.val() != '') {
        results = $.get(requestUrl + field.val() + "&company_id=" + companyId, function(results) {
            if (results.substring(0, 5) == 'error') {
                resultData = null;
                currentSelectedIndex = null;
                alert('SQL Error: ' + results.substring(6, results.length));

            } else if (results == 'perm') {
                // don't have permission
                currentCount = 0;
                resultData = new Array;
                currentSelectedIndex = null;
                resultDiv.html('<em>Permission Error</em>').show();

            } else if (results == 'none') {
                // no results found
                currentCount = 0;
                resultData = new Array;
                currentSelectedIndex = null;
                HideSuggest(resultDivId);

            } else {
                // try evaling the results, as it should be a json_encoded array
                currentCount = 0;
                currentSelectedIndex = null;
                resultDiv.html('');
                resultData = eval("(" + results + ")");

                $(resultData).each(function (index, values) {
                    resultRow = '<div class="result_row" id="result_row_' + index + '" '
                        + 'onmousedown="UseSuggest(\'' + resultDivId + '\', \'' + textFieldId + '\', ' + index + ');" '
                        + 'onmouseover="SuggestOver(\'' + resultDivId + '\', ' + index + ');" '
                        + 'onmouseout="SuggestOver(\'' + resultDivId + '\', false);">'
                        + '<span class="result_name" id="result_name_' + index + '">' + values['name'] + '</span>'
                        + '</div>';
                    resultDiv.append(resultRow);

                    currentCount++;
                });
                resultDiv.css('height', (currentCount * resultRowHeight) + 'px').show();
                //alert(resultDiv.html());
            }
        });
    }

    suggestDelay = null;
}
/**
 * function to handle the up and down key strokes
 *
 * @param [string]     textFieldId  id of the text field being suggested
 * @param [string]     resultDivId  id of the results div
 * @param [string]     requestUrl  what is the URL of the AJAX script returning the values for the selection list
 */
function PerformSuggestUpDownArrow(textFieldId, resultDivId, requestUrl) {
    if ($(resultDivId).css('display') == 'none') {
        MakeSuggestRequest(textFieldId, resultDivId, requestUrl);
        currentSelectedIndex == null;
    }
}

/**
 * function to handle the highlighting of the current selected/mouse over
 *
 * @param [string]     textFieldId  id of the text field being suggested
 * @param [int]        selectedIndex  currently selected index in the list
 */
function SuggestOver(resultDivId, selectedIndex) {
    $(resultDivId + ' div.result_row_over').removeClass('result_row_over');

    if (selectedIndex !== false) {
        $(resultDivId + ' div#result_row_' + selectedIndex).addClass('result_row_over');
        currentSelectedIndex = selectedIndex;
    }
}

/**
 * function to apply the selected item to the selected fieldId
 *
 * @param [string]     resultDivId  id of the results div
 * @param [string]     textFieldId  id of the text field being suggested
 * @param [int]        selectedIndex  currently selected index in the list
 */
function UseSuggest(resultDivId, textFieldId, selectedIndex) {

    //check to see if the custom action function exists and then call it as applicable

    if(typeof window.CustomSuggest == 'function') {
        CustomSuggest(textFieldId,resultData,selectedIndex);
    }
    value = resultData[selectedIndex].full_name;

    currentSelectedIndex = null;
    HideSuggest(resultDivId);
    if ( !$(textFieldId).hasClass('noSuggest') ){
        $(textFieldId).val(value).focus();
    }
    resultData = new Array;
}

/**
 * function hide the suggest list
 *
 * @param [string]     resultDivId  id of the results div
 */
function HideSuggest(resultDivId) {
    suggestDelay = null; // end timer
    currentSelectedIndex = null;
    $(resultDivId).hide();
}
