var sLoadingHtml = '<span class="loading"><img src="' + sCssHost + '/cdn/images/loading.gif" alt="Loading" /></span>';
jQuery.noConflict();
jQuery(document).ready(function(){
	jQuery('#maxDownloadErr').hide();
    var list = "";
    jQuery('#checkboxToggle').click(function(){
        var checkedValue = jQuery('#checkboxToggle').attr('checked') ? 'checked' : '';
        jQuery(':checkbox').attr('checked', checkedValue);
    });

    jQuery('#radiusUnits').change(function(){
        var val = jQuery('#radiusUnits').val();
        LocationAjaxController.saveZipRadiusUnitPrefs(val);
    });
});

function getExchangeData(){

    ListBuilderSpecialtyCriteriaController.getExchange(function(data){
          var holderString="";
          exArray = exchange.split(",");
          for (var i = 0; i < data.length; i++){
              holderString +='<span class="omit browseOmit">';
              holderString += '<label for="">';
              holderString +='<input value="" id="" name="exchangeOmit" type="checkbox">Omit</label></span>';
              holderString +='<label for=""><input name="exg" value="' + data[i].id + '|' ;
              holderString += data[i].name + '" id=""  type="checkbox"' ;
              holderString += "onClick=" + '"' + "submitList('" + "exg','specialtyCriteria')" + '"';
              if(jQuery.inArray(data[i].id , exArray)!= -1){

              holderString += 'checked="checked" ';
              }
              holderString +=   '>';
              holderString +=  data[i].name + ' </label>';

          }

          jQuery('#exchangeDataSelect').html(holderString)
     });



}
function fillLists(){
getRankingsData();
getExchangeData();
getTagsData();
}
function getRankingsData(){

    ListBuilderSpecialtyCriteriaController.getRankings(function(data){
          var holderString="";
          exArray = ranking.split(",");
          for (var i = 0; i < data.length; i++){
              holderString +='<span class="omit browseOmit">';
              holderString += '<label for="">';
              holderString +='<input value="" id="" name="rankingOmit" type="checkbox">Omit</label></span>';
              holderString +='<label for=""><input name="ranking" value="' + data[i].id + '|' ;
              holderString += data[i].name + '" id=""  type="checkbox"' ;
              holderString += "onClick=" + '"' + "submitList('" + "ranking','specialtyCriteria')" + '"';
              if(jQuery.inArray(data[i].id , exArray)!= -1){

              holderString += 'checked="checked" ';
              }
              holderString +=   '>';
              holderString +=  data[i].name + ' </label>';

          }
		  if (data != null && data.length > 1) {
			  jQuery('#rankingSelectLinks').show()
		  } else {
			  jQuery('#rankingSelectLinks').hide()
		  }
          jQuery('#rankingDataSelect').html(holderString)
     });



}

function getTagsData(){

    ListBuilderSpecialtyCriteriaController.getTags(function(data){
          var holderString="";
          exArray = tagItem.split(",");
          for (var i = 0; i < data.length; i++){
              holderString +='<span class="omit browseOmit">';
              holderString += '<label for="">';
              holderString +='<input value="" id="" name="tagOmit" type="checkbox">Omit</label></span>';
              holderString +='<label for=""><input name="tagItem" value="' + data[i].id + '|' ;
              holderString += data[i].tagName + '" id=""  type="checkbox"' ;
              holderString += "onClick=" + '"' + "submitList('" + "tagItem','specialtyCriteria')" + '"';
              if(jQuery.inArray(data[i].id , exArray)!= -1){

              holderString += 'checked="checked" ';
              }
              holderString +=   '>';
              holderString +=  data[i].tagName + ' </label>';

          }
		  if (holderString != "")	{
			  jQuery('#tagSelectLinks').show()
		  } else {
			  jQuery('#tagSelectLinks').hide()
		  }
          jQuery('#tagDataSelect').html(holderString)
     });



}


function continueButtonStatus(count) {
	if (jQuery("#isTbalUser").val()) {
		if (count == null || count == 0) {
			jQuery("#balGetResults").attr("disabled", "disabled").addClass('continueDisabled').show();
	        jQuery("#balSaveSearch").attr("disabled", "disabled").addClass('continueDisabled');
	        jQuery("#maxDownloadErr").hide();
		} else if (count > parseInt(jQuery("#maxResultsAllowed").val())) {
			jQuery("#balGetResults").attr("disabled", "disabled").addClass('continueDisabled').hide();
	        jQuery("#balSaveSearch").attr("disabled", "disabled").addClass('continueDisabled');
	        jQuery("#maxDownloadErr").show();
		} else {
			jQuery("#balGetResults").removeAttr("disabled").removeClass('continueDisabled').show();
	        jQuery("#balSaveSearch").removeAttr("disabled").removeClass('continueDisabled');
	        jQuery("#maxDownloadErr").hide();
		}
	} else {
		
		if (count != null && count != 0) {
	        jQuery("#balGetResults").removeAttr("disabled").removeClass('continueDisabled');
	        jQuery("#balSaveSearch").removeAttr("disabled").removeClass('continueDisabled');
	    } else {
	        jQuery("#balGetResults").attr("disabled", "disabled").addClass('continueDisabled');
	        jQuery("#balSaveSearch").attr("disabled", "disabled").addClass('continueDisabled');
	    }
	}
}


function removeFamilyTreeDUNSFile(fileName) {
    if (validateFileNameForRemove(fileName))
    {
        var companyParent = dwr.util.getValue('companyParent');
        var globalParent = dwr.util.getValue('globalParent');
        var fileName = document.getElementById(fileName).value;
        ListBuilderFamilyTree.removeDunsFile(fileName, companyParent, globalParent, function(data) {
            dwr.util.setValue("dunsFamilyTreeUploadReply", data);
         });
    }
}


function uploadCodeFileWithParent(uploadFieldId,
                                  messageFieldId,
                                  dwrType,
                                  immediateParentId,
                                  ultimateParentId,
                                  uploadButtonSpanId,
                                  uploadLinkSpanId,
                                  uploadedFilesSpanId)
{
    if (validateFileNameForUpload(uploadFieldId))
    {
        var fileContents = dwr.util.getValue(uploadFieldId);
        var fileName = document.getElementById(uploadFieldId).value;
        var immediateParent = document.getElementById(immediateParentId).checked;
        var ultimateParent = document.getElementById(ultimateParentId).checked;

        switch (dwrType)
        {
            case "familyTree":
                FamilyTreeAjaxController.uploadFileWithParentInfo(fileName, fileContents, uploadFieldId, immediateParent, ultimateParent, function(results) {
                    processUploadResult(results, messageFieldId);
                       fileName = results.fileName;
                    completeFileUpload(results,uploadButtonSpanId,uploadLinkSpanId,uploadedFilesSpanId,fileName,"FAMILY_TREE_DUNS_ULTIMATE_PARENT");

                 });
                break;
            default:
                alert("Invalid dwrType in function uploadCodeFile: " + dwrType);
                break;
        }

    }
}


function removeSpecialDataDUNSFile(fileName) {
    if (validateFileNameForRemove(fileName))
    {
        var fileName = document.getElementById(fileName).value;
        var ffe = "Duns";

        resultsLoading();
        ListBuilderSpecialtyCriteriaController.removeDunsFile(fileName,"DUNS",function(data) {
            var id = name.split(".",1);
            removeFileAnchor(id);
            printTypeResult(data.companySearch,"dunsSpecialDataUploadReply", data.messages, data.prettyResultCount);
         });
    }
}


function uploadCodeFile(uploadFieldId,
                        messageFieldId,
                        dwrType,
                        uploadButtonSpanId,
                        uploadLinkSpanId,
                        uploadedFilesSpanId,
                        ffe)
{

    var fileContents = dwr.util.getValue(uploadFieldId);
    var fileName = document.getElementById(uploadFieldId).value;

    resultsLoading();
    SpecialtyCriteriaAjaxController.uploadFileWithFieldName(fileName, fileContents, uploadFieldId,  function(results) {
    	printTypeResult(results.companySearch,"dunsSpecialDataUploadReply", results.messages[0], results.prettyResultCount);
            fileName = results.fileName;
            completeFileUpload(results,"DUNSUploader","DUNSfileDetect","DUNSuploadContainer",fileName,"DUNS");
        });
}

function processUploadResult(result, messageFieldId)
{	
	resultsLoading();
	printTypeResult(result.companySearch, messageFieldId, result.message, result.prettyResultCount, null);
}

function printTypeResult(companySearch, messageSpanId, message, resultCount, options) {
    if (options == null) options = {};

    dwr.util.setValue(messageSpanId, message, options);
    var messageSpan = document.getElementById(messageSpanId);

    if( messageSpan) {
    	if (message &&
    			message.length > 0) {
    		messageSpan.style.display="block";
    	} else {
    		messageSpan.style.display="none";
    	}
    }

    var resultCountNumber = resultCount.replace(/,/g, '');
    var isTbalUser = jQuery("#isTbalUser");
	
    if (companySearch){
        //to check for more than 1
        if(resultCountNumber < 1){
        	dwr.util.setValue('balCount', resultCount);
        } else if (resultCountNumber == 1){
        	dwr.util.setValue('balCount', resultCount + ' Company');
        } else {
        	dwr.util.setValue('balCount', resultCount + ' Companies');
        }
    } else {
    	 //to check for more than 1
        if(resultCountNumber < 1){
        	dwr.util.setValue('balCount', resultCount);
        } else if (resultCountNumber == 1){
        	dwr.util.setValue('balCount', resultCount + ' Person');
        } else {
        	dwr.util.setValue('balCount', resultCount + ' People');
        }
    }

    continueButtonStatus(resultCountNumber);
    updateCriteriaTracker();

}

function processRange(fieldName1,fieldName2,operator,dwrType)
{

    var fieldValue1 = document.getElementById(fieldName1).value;

    if(fieldName2 != 'noInput'){
        var fieldValue2 = document.getElementById(fieldName2).value;
        if(operator != ''){
            var operatorValue = document.getElementById(operator).value;
        }else
        operatorValue = 2; // handle the range
    }

    if(fieldName2 == 'noInput'){
    operatorValue = 0;
    fieldName2 = null;

    }

    if (dwrType == 'financial')
    {
    	resultsLoading();
    	FinancialInfoAjaxController.processRange(fieldName1, fieldName2, fieldValue1, fieldValue2, operatorValue, function(result) {
        	printTypeResult(result.companySearch, fieldName1 + '_msg', result.message, result.prettyResultCount);
        });
    }
    else if (dwrType == 'companySize')
    {
    	resultsLoading();
    	CompanySizeAjaxController.processRange(fieldName1, fieldName2, fieldValue1, fieldValue2,operatorValue,function(result) {
        	printTypeResult(result.companySearch, fieldName1 + '_msg', result.message, result.prettyResultCount);
        });
    }
    else if (dwrType == 'companyType')
    {
    	resultsLoading();    
    	CompanyTypeAjaxController.processRange(fieldName1, fieldName2, fieldValue1, fieldValue2,operatorValue,function(result) {
            	printTypeResult(result.companySearch, fieldName1 + '_msg', result.message, result.prettyResultCount);
        });

    }
    else if (dwrType == 'specialtyCriteria')
    {
    	resultsLoading();
    	SpecialtyCriteriaAjaxController.processRange(fieldName1, fieldName2, fieldValue1, fieldValue2,operatorValue,function(result) {
        	printTypeResult(result.companySearch, fieldName1 + '_msg', result.message, result.prettyResultCount);
        });
    }

    else if (dwrType == 'people')
    {
    	resultsLoading();
    	PeopleAjaxController.processRange(fieldName1, fieldName2, fieldValue1, fieldValue2,operatorValue,function(result) {
        	printTypeResult(result.companySearch, fieldName1 + '_msg', result.message, result.prettyResultCount);
        });
    }

    else if (dwrType == 'familyTree')
    {
    	resultsLoading();
    	PeopleAjaxController.processRange(fieldName1, fieldName2, fieldValue1, fieldValue2,operatorValue,function(result) {
        	printTypeResult(result.companySearch, fieldName1 + '_msg', result.message, result.prettyResultCount);
        });
    }
    else if (dwrType == 'newChangedRecords')
    {
    	resultsLoading();
    	NewAndChangedRecordsAjaxController.processSystemGeneratedRange(fieldName1, fieldName2, fieldValue1, fieldValue2,operatorValue,function(result) {
        	printTypeResult(result.companySearch, fieldName1 + '_msg', result.message, result.prettyResultCount);
        });
    }
    else
    {
        alert("Invalid dwrType in function processRange: " + dwrType);
    }

}

function processRangeOperator(spanName, fieldName, operator, dwrType)
{
   /*
    * span1 is used to show/hide field1
    * span2 is used to show/hide field2
    * span3 is used to show/hide the "and" that connects field1 and field2 when they are both displayed
    */
    var fieldName1 = fieldName + "1";
    var fieldName2 = fieldName + "2";
    var field1 = document.getElementById(fieldName1);
    var field2 = document.getElementById(fieldName2);
    var span1 = document.getElementById(spanName + "1");
    var span2 = document.getElementById(spanName + "2");
    var span3 = document.getElementById(spanName + "3");
    var operatorValue = document.getElementById(operator).value;

    /*
	 * If a field is hidden (for example, span2 will show/hide field2), then
	 * clear the field's value.
	 */
    switch(operatorValue)
    {
        case '0':
            span1.style.display="";
            span2.style.display="none";
            span3.style.display="none";
            field2.value="";
            showHideChildElementsByTagName(span1, 'label', false);
            break;
        case '1':
            span1.style.display="none";
            span2.style.display="";
            span3.style.display="none";
            field1.value="";
            showHideChildElementsByTagName(span2, 'label', false);
            break;
        case '2':
            span1.style.display="";
            span2.style.display="";
            span3.style.display="";
            showHideChildElementsByTagName(span1, 'label', true);
            showHideChildElementsByTagName(span2, 'label', true);
            break;
        case '3':
            span1.style.display="";
            span2.style.display="none";
            span3.style.display="none";
            field2.value="";
            showHideChildElementsByTagName(span1, 'label', false);
            break;
    }

    var fieldValue1 = document.getElementById(fieldName1).value;
    var fieldValue2 = document.getElementById(fieldName2).value;

    if (fieldValue1.length > 0 || fieldValue2.length > 0)
    {
        processRange(fieldName1, fieldName2, operator, dwrType);
    }
    else
    {
        dwr.util.setValue(fieldName1 + "_msg", "");
        processRange(fieldName1, fieldName2, operator, dwrType);
    }
}


function upLoadPostalCode(fileName){
    var what = jQuery("input[name=locationFileType]:checked").val();

    if (what == null){
        what = 'usZIP';
        jQuery("#uploadUS-ZIP").attr("checked", "checked"); ;
    }

    switch (what){
        case "usZIP" :
            uploadUsPostalCodes(fileName);
            break;
        case "non-usPostal" :
            uploadNonUsPostalCodes(fileName)
            break;
    }
}


function formatAndPrintUploadResults(fieldName, results) {
    var formattedErrorList = "<ul>";
    var messageArray = results.messages

    for (var index = 0; index < messageArray.length; ++index) {
        var nextErrorMessage = messageArray[index];
        formattedErrorList = formattedErrorList + "<li>" + nextErrorMessage + "</li>";
    }

    formattedErrorList = formattedErrorList + "</ul>";
    resultsLoading();
    printTypeResult(results.companySearch, fieldName, formattedErrorList , results.prettyResultCount, {escapeHtml:false});
    jQuery('#' +  fieldName).show();
}


function uploadUsPostalCodes(fileName) {

    if (validateFileNameForUpload(fileName)) {

        var fileContents = dwr.util.getValue(fileName);

        var fileName = document.getElementById(fileName).value;

        LocationAjaxController.uploadUsPostalCodes(fileName, fileContents, "locationUpload", function(results) {
            formatAndPrintUploadResults( "locationUploadReply", results);
            fileName = results.fileName;
            completeFileUpload(results,"ZIPUploader","ulZipDetect","multiSelectUpload",fileName,"us_zip_code_upload");
            });
    }
}


function uploadNonUsPostalCodes(fileName)
{
    if (validateFileNameForUpload(fileName))
    {
        var fileContents = dwr.util.getValue(fileName);

        var fileName = document.getElementById(fileName).value;

        resultsLoading();
        LocationAjaxController.uploadNonUsPostalCodes(fileName, fileContents, "locationUpload", function(results) {
        	printTypeResult(results.companySearch, "locationUploadReply", results.messages, results.prettyResultCount);
            completeFileUpload(results,"ZIPUploader","ulZipDetect","multiSelectUpload",fileName,"postal_code_upload");
            });
    }
}

function uploadCodes(fileName) {

    var what = jQuery("input[name=indusFileType]:checked").val();
    var codeType = 'Primary'; // since only primary is su pported right now, 
    						// = jQuery("input[name=PrimarySecondary]:checked").val();

    switch ( what ) {
        case "usSIC" :
            if (validateFileNameForUpload(fileName)) {
                var fileContents = dwr.util.getValue(fileName);
                var fileName = document.getElementById(fileName).value;

                IndustryAjaxController.uploadUsSicCodes(fileName, fileContents ,"industryUpload",codeType,function(results) {
                    formatAndPrintUploadResults( "industryUploadReply",  results);
                    fileName = results.fileName;
                    completeFileUpload(results,
                            "IndusUploader",
                            "IndusULDetect",
                            "industryMultiSelectUploading",
                            fileName,
                            "UPLOAD_PRIMARY_SIC_CODE");
                }
                );
            }
            break;

        case "ukSIC" :
            if (validateFileNameForUpload(fileName)) {
                var fileContents = dwr.util.getValue(fileName);
                var ffe = "";
                var fileName = document.getElementById(fileName).value;

                IndustryAjaxController.uploadUkSicCodes(fileName, fileContents ,"industryUpload",codeType ,function(results) {
                    fileName = results.fileName;
                    formatAndPrintUploadResults( "industryUploadReply", results);
                    completeFileUpload(results,
                                "IndusUploader",
                                "IndusULDetect",
                                "industryMultiSelectUploading",
                                fileName,
                                "UPLOAD_PRIMARY_UK_SIC_CODE");
                    });
            }
            break;

        case "NAICS":
            if (validateFileNameForUpload(fileName)) {
                var fileContents = dwr.util.getValue(fileName);

                var fileName = document.getElementById(fileName).value;
                var countarray = null;
                IndustryAjaxController.uploadNaicsCodes(fileName, fileContents ,"industryUpload",codeType ,function(results) {
                         fileName = results.fileName;
                         formatAndPrintUploadResults( "industryUploadReply", results);
                         completeFileUpload(results,
                                 "IndusUploader",
                                 "IndusULDetect",
                                 "industryMultiSelectUploading",
                                 fileName,
                                 "UPLOAD_PRIMARY_NAICS_CODE");
                });
            }
        }
}


function updateZipRadius(fieldName,fieldName2,fieldName3){

  var unit = document.getElementById(fieldName2).value;
  var zips = document.getElementById(fieldName3).value;
  var radius = document.getElementById(fieldName).value;

  resultsLoading();
  LocationAjaxController.updateZipRadius(zips, radius, unit ,function(results) {
	  printTypeResult(results.companySearch, "zipRadiusReply", results.messages, results.prettyResultCount);

        });

}

function updateFileList(fileName,fieldName,element){

    var fileList = document.getElementById(element).innerHTML;
    updatedfileList =  "<label for=''><input value='' name='locationUL' id='filelist_" + filename + "' checked='checked' type='checkbox' /> " + fileName + "</label>";

   document.getElementById(fieldName).value = "" ;
    document.getElementById(element).innerHTML = updatedfileList ;

}

function processRangeWithModifier(fieldName, fieldName2, operator, modifierName, dwrType)
{

	
	var fieldValue = jQuery('#' + fieldName).val();
    var fieldValue2 = jQuery('#' + fieldName2).val();    
    var operatorValue = jQuery('#' + operator).val();

    
    var modifierId = getSelectedRadioButtonId(modifierName);  
    
    
    if (dwrType == 'financial')
    {
    	resultsLoading();
    	FinancialInfoAjaxController.processRangeWithModifier(fieldName, fieldName2, fieldValue, fieldValue2, operatorValue, modifierId, function(result) {
        	printTypeResult(result.companySearch, fieldName + '_msg', result.message, result.prettyResultCount);
        });
    }

    else if (dwrType == 'companySize')
    {
    	resultsLoading();
    	CompanySizeAjaxController.processRangeWithModifier(fieldName, fieldName2, fieldValue, fieldValue2, operatorValue, modifierId, function(result) {
        	printTypeResult(result.companySearch, fieldName + '_msg', result.message, result.prettyResultCount);
        });
    }
    else if (dwrType == 'companyType')
    {
    	resultsLoading();    
    	CompanyTypeAjaxController.processRangeWithModifier(fieldName, fieldName2, fieldValue, fieldValue2, operatorValue, modifierId, function(result) {
            	printTypeResult(result.companySearch, fieldName + '_msg', result.message, result.prettyResultCount);
        });

    }
    else if (dwrType == 'specialtyCriteria')
    {
    	resultsLoading();
    	SpecialtyCriteriaAjaxController.processRangeWithModifier(fieldName, fieldName2, fieldValue, fieldValue2, operatorValue, modifierId, function(result) {
        	printTypeResult(result.companySearch, fieldName + '_msg', result.message, result.prettyResultCount);
        });
    }

    else if (dwrType == 'people')
    {
    	resultsLoading();
    	PeopleAjaxController.processRangeWithModifier(fieldName, fieldName2, fieldValue, fieldValue2, operatorValue, modifierId, function(result) {
        	printTypeResult(result.companySearch, fieldName + '_msg', result.message, result.prettyResultCount);
        });
    }

    else if (dwrType == 'familyTree')
    {
    	resultsLoading();
    	FamilyTreeAjaxController.processRangeWithModifier(fieldName, fieldName2, fieldValue, fieldValue2, operatorValue, modifierId, function(result) {
        	printTypeResult(result.companySearch, fieldName + '_msg', result.message, result.prettyResultCount);
        });
    }
}

function processRangeOperatorWithModifier(spanName, fieldName, operator, modifierName, dwrType)
{
   /*
    * span1 is used to show/hide field1
    * span2 is used to show/hide field2
    * span3 is used to show/hide the "and" that connects field1 and field2 when they are both displayed
    */
    var fieldName1 = fieldName + "1";
    var fieldName2 = fieldName + "2";
    var field1 = document.getElementById(fieldName1);
    var field2 = document.getElementById(fieldName2);
    var span1 = document.getElementById(spanName + "1");
    var span2 = document.getElementById(spanName + "2");
    var span3 = document.getElementById(spanName + "3");
    var operatorValue = document.getElementById(operator).value;

    /*
	 * If a field is hidden (for example, span2 will show/hide field2), then
	 * clear the field's value.
	 */
    switch(operatorValue)
    {
        case '0':
            span1.style.display="";
            span2.style.display="none";
            span3.style.display="none";
            field2.value="";
            showHideChildElementsByTagName(span1, 'label', false);
            break;
        case '1':
            span1.style.display="none";
            span2.style.display="";
            span3.style.display="none";
            field1.value="";
            showHideChildElementsByTagName(span2, 'label', false);
            break;
        case '2':
            span1.style.display="";
            span2.style.display="";
            span3.style.display="";
            showHideChildElementsByTagName(span1, 'label', true);
            showHideChildElementsByTagName(span2, 'label', true);
            break;
        case '3':
            span1.style.display="";
            span2.style.display="none";
            span3.style.display="none";
            field2.value="";
            showHideChildElementsByTagName(span1, 'label', false);
            break;
    }

    if (dwrType != "none") {
        var fieldValue1 = document.getElementById(fieldName1).value;
        var fieldValue2 = document.getElementById(fieldName2).value;

        if (fieldValue1.length > 0 || fieldValue2.length > 0)
        {
            processRangeWithModifier(fieldName1, fieldName2, operator, modifierName, dwrType);
        }
        else
        {
            dwr.util.setValue(fieldName1 + "_msg", "");
            processRangeWithModifier(fieldName1, fieldName2, operator, modifierName, dwrType);
        }
    }
}

function processRangeOperatorWithModifierPaired(spanName, fieldName, operator, modifierName,
                                spanName2, fieldName2, operator2, modifierName2,field, fieldGlue) {

    processRangeOperatorWithModifier(spanName, fieldName, operator, modifierName, "none");
    processRangeOperatorWithModifier(spanName2, fieldName2, operator2, modifierName2, "none");

    var fieldName1A = fieldName + "1";
    var fieldName2A = fieldName + "2";
    var fieldValue1A = document.getElementById(fieldName1A).value;
    var fieldValue2A = document.getElementById(fieldName2A).value;
    var operatorValue1A = document.getElementById(operator).value;
    var modifierId1A = getSelectedRadioButtonId(modifierName);

    var fieldName1B = fieldName2 + "1";
    var fieldName2B = fieldName2 + "2";
    var fieldValue1B = document.getElementById(fieldName1B).value;
    var fieldValue2B = document.getElementById(fieldName2B).value;
    var operatorValue1B = document.getElementById(operator2).value;
    var modifierId1B = getSelectedRadioButtonId(modifierName2);

    var conjunctFld = document.getElementById(fieldGlue).value;
    
    resultsLoading();
    if(field.name == 'ttlEmpRng1' || field.name == 'ttlEmpRng2'){
    CompanySizeAjaxController.processRangeWithModifierPaired(fieldName1A, fieldName2A,
        fieldValue1A, fieldValue2A, operatorValue1A, modifierId1A, fieldName1B, fieldName2B,
        fieldValue1B, fieldValue2B, operatorValue1B, modifierId1B, conjunctFld,field.name, function(result) {
    	printTypeResult(result.companySearch, fieldName1A+ '_msg', result.message, result.prettyResultCount);
    });
    }else{
    CompanySizeAjaxController.processRangeWithModifierPaired(fieldName1A, fieldName2A,
        fieldValue1A, fieldValue2A, operatorValue1A, modifierId1A, fieldName1B, fieldName2B,
        fieldValue1B, fieldValue2B, operatorValue1B, modifierId1B, conjunctFld,field.name, 
        function(result) {
    		printTypeResult(result.companySearch, fieldName1B+ '_msg', result.message, result.prettyResultCount);
    });
    }
}

function getSelectedRadioButtonId(fieldName)
{
    var id = "";
    var myArray = document.getElementsByName(fieldName);
    for (var i = 0; i < myArray.length; i++)
    {
        if (myArray[i].checked)
        {
            //alert("found a checked radio button with name: " + myArray[i].id);
            id = myArray[i].id;
        }
    }
   
    return id;
	
}


//This method will allow a single check box to be selected out of two
function toggleCheckboxSelection(fieldName,flag)
{
    var val = document.getElementsByName(fieldName);

 if (val[0].checked && flag== val[0].id)
 {
     val[1].checked=false;

 }else if (val[1].checked && flag== val[1].id)
 {
     val[0].checked=false;
 }
}


function submitList(fieldName, dwrType)
{
    var fields = document.getElementsByName(fieldName);
    var values = new Array();
    var j = 0;
    for (var i = 0; i < fields.length; i++)
    {
        if (fields[i].checked == true)
        {
            values[j] = fields[i].value;
            j++;
        }
    }

    if (dwrType == 'financial')
    {
    	resultsLoading();
    	FinancialInfoAjaxController.processList(fieldName, values, function(result) {
        	printTypeResult(result.companySearch, null, result.message, result.prettyResultCount, null);
        });
    }
    else if (dwrType == 'people')
    {
    	resultsLoading();
    	PeopleAjaxController.processList(fieldName, values, function(result) {
        		printTypeResult(result.companySearch, null, result.message, result.prettyResultCount, null);
        });
    }
    else if (dwrType == 'specialtyCriteria')
    {
    	resultsLoading();
    	SpecialtyCriteriaAjaxController.processList(fieldName, values, function(result) {
        		printTypeResult(result.companySearch, null, result.message, result.prettyResultCount, null);
        });
    }else if (dwrType == 'companyType')
    {
    	resultsLoading();
    	CompanyTypeAjaxController.processList(fieldName, values, function(result) {
        		printTypeResult(result.companySearch, null, result.message, result.prettyResultCount, null);
        });
    }else if (dwrType == 'newChangedRecords')
    {
    	resultsLoading();    
    	NewAndChangedRecordsAjaxController.processList(fieldName, values, function(result) {
            	printTypeResult(result.companySearch, null, result.message, result.prettyResultCount, null);
        });
    }

}

function submitListWithAll(fieldName, dwrType, inclusionName)
{
    var fields = document.getElementsByName(fieldName);

    var values = new Array();
    var j = 0;
    for (var i = 0; i < fields.length; i++)
    {
        if (fields[i].checked == true)
        {
            values[j] = fields[i].value;
            j++;
        }
    }

    /* Get the value or the inclusion radio button that is selected */
    var inclusionValue = "";
    var inclusionFields = document.getElementsByName(inclusionName);
    for (var i = 0; i < inclusionFields.length; i++)
    {
        if (inclusionFields[i].checked)
        {
            inclusionValue = inclusionFields[i].value;
            break;
        }
    }

    switch (dwrType)
    {
        case "financial":
        	resultsLoading();
            FinancialInfoAjaxController.processListWithAll(fieldName, values, inclusionValue, function(result) {
            		printTypeResult(result.companySearch, null, result.message, result.prettyResultCount, null);
            });
            break;
        case "specialtyCriteria":
        	resultsLoading();
            SpecialtyCriteriaAjaxController.processListWithAll(fieldName, values, inclusionValue, function(result) {
            		printTypeResult(result.companySearch, null, result.message, result.prettyResultCount, null);
            });
            break;
        default:
            alert("Invalid dwrType in function submitListWithAll: " + dwrType);
            break;
    }
}

/**
 * @param  fieldName  the name of the check box field or fields
 * @param  check  true to check all the boxes; false to uncheck all the boxes
 */
 
 function toggleCheckBoxes(fieldName, check, buttonName)
 {
	    var fields = document.getElementsByName(fieldName);

	    for (var i = 0; i < fields.length; i++)
	    {
	        if (check)
	        {
	            fields[i].checked = true;
	        }
	        else
	        {
	            fields[i].checked = false;
	        }
	        

	    }
	 
 }
 
function toggleCheckBoxes(fieldName, check)
{

    var fields = document.getElementsByName(fieldName);

    for (var i = 0; i < fields.length; i++)
    {
        if (check)
        {
            fields[i].checked = true;
        }
        else
        {
            fields[i].checked = false;
        }
    }
}

function processDelimitedStringWithParent(fieldId, messageFieldId, dwrType, immediateParentId, ultimateParentId)
{
    var fieldValue = document.getElementById(fieldId).value;
    var immediateParent = document.getElementById(immediateParentId).checked;
    var ultimateParent = document.getElementById(ultimateParentId).checked;

    switch (dwrType)
    {
        case "familyTree":
            FamilyTreeAjaxController.processDelimitedListWithParent(fieldId, fieldValue, immediateParent, ultimateParent, function(result) {
                processUploadResult(result, messageFieldId);
             });
            break;
        default:
            alert("Invalid dwrType in function uploadCodeFile: " + dwrType);
            break;
    }
}

function processDelimitedString(fieldId, messageFieldId, dwrType)
{
    var fieldValue = document.getElementById(fieldId).value;

    switch (dwrType)
    {
        case "specialtyCriteria":
            SpecialtyCriteriaAjaxController.processDelimitedList(fieldId, fieldValue, function(result) {
                processUploadResult(result, messageFieldId);
             });
            break;
        case "companyType":
        	if ( fieldId == 'phoneNo')
        	{
        		fieldValue = fieldValue.replace(/-/g,"");
        	}
            CompanyTypeAjaxController.processDelimitedList(fieldId, fieldValue, function(result) {
                processUploadResult(result, messageFieldId);
             });
            break;
        default:
            alert("Invalid dwrType in function uploadCodeFile: " + dwrType);
            break;
    }
}

/**
* Clears all of the criteria from the Search
*/
function clearSearch() {

	if (jQuery("#criteriaTrackerBox tr").length > 1) {
		if (confirm('Are you sure you want to clear the form?')) {
	        document.balForm.reset();
	        RemoveCriteriaTracker.clearCriteria();
	        BALGlobalAjaxController.clearSearch(function(result) {
	               document.resetBal.submit();
	        });
	    }
	} else return false;
}

/**
* Update criteria tracker
*/
function updateCriteriaTracker() {
    jQuery.post("listbuilder/criteriaTracker/getCriteriaTracker", { layout: "none" },
        function(data) {
            jQuery("#criteriaTrackerBox").html(data);
        }
    );
}

function processDelimitedStringWithInclusion(fieldId, messageFieldId, dwrType, modifierName, inclusionName)
{
    var fieldValue = document.getElementById(fieldId).value;
    var modifierValue = "";
    var inclusionValue = "";

    /* Get the value or the inclusion radio button that is selected */
    var inclusionFields;
    if (inclusionName == "all") {
        inclusionValue = "all";
    } else if (inclusionName == "any") {
        inclusionValue = "any";
    } else {
        inclusionFields = document.getElementsByName(inclusionName);
        for (var i = 0; i < inclusionFields.length; i++)
        {
            if (inclusionFields[i].checked)
            {
                inclusionValue = inclusionFields[i].value;
            }
        }
    }

    /* Get the value of the modifier select box */
    if(modifierName != 'noInput')
    {
        modifierValue = document.getElementsByName(modifierName)[0].value;
    }

    var array = new Array();

    switch (dwrType)
    {
        case "people":
        	resultsLoading();
            PeopleAjaxController.processDelimitedListWithAll(fieldId, fieldValue, modifierValue, inclusionValue, function(result) {
            	printTypeResult(result.companySearch, fieldId + '_msg', result.message, result.prettyResultCount);
             });
             break;
        case "companyType":
        	resultsLoading();
            CompanyTypeAjaxController.processDelimitedListWithAll(fieldId, fieldValue, modifierValue, inclusionValue, function(result) {
            	printTypeResult(result.companySearch, fieldId + '_msg', result.message, result.prettyResultCount);
             });
             break;
        case "familyTree":
        	resultsLoading();
            FamilyTreeAjaxController.processDelimitedListWithAll(fieldId, fieldValue, modifierValue, inclusionValue, function(result) {
            	printTypeResult(result.companySearch, fieldId + '_msg', result.message, result.prettyResultCount);
            });
            break;
        case "specialtyCriteria":
        	resultsLoading();
            SpecialtyCriteriaAjaxController.processDelimitedListWithAll(fieldId, fieldValue, modifierValue, inclusionValue, function(result) {
            	printTypeResult(result.companySearch, fieldId + '_msg', result.message, result.prettyResultCount);
             });
            break;
        default:
            alert("Invalid dwrType in function processDelimitedStringWithInclusion: " + dwrType);
            break;
    }
}

/**
* @param result the BALFieldResult object containing the results of the upload
* @param uploadButtonSpanId the Id of the span surrounding the file field (input type="file") and the upload button
* @param uploadLinkSpanId the Id of the span surrounding the word "another" in the upload file link
* @param uploadedFilesSpanId the Id of the div into which the names of the currently uploaded files will be placed
* @param fileName the name of the file that was uploaded
*/
function completeFileUpload(result, uploadButtonSpanId, uploadLinkSpanId, uploadedFilesSpanId, fileName,ffe) {
    if (result.valid &&
        result.validProcess) {

        document.getElementById(uploadButtonSpanId).style.display = "none";
        document.getElementById(uploadedFilesSpanId).style.display = "";

        /* Create an anchor and assign it an id */
        var theAnchor = document.createElement("a");
        var id = "f" + result.fileIndex;
        theAnchor.id = id;
        theAnchor.href = "#";

        /* Create text and assign it to the anchor */
        var theText = document.createTextNode("Remove file: " + fileName);
        theAnchor.appendChild(theText);

        /* Add an onclick to the anchor */
        theAnchor.onclick = (function() {testRemoveFile(fileName,uploadLinkSpanId,ffe,id);return false;});

        /* Add the new anchor to the div */
        document.getElementById(uploadedFilesSpanId).appendChild(theAnchor);

        /* Create a break, assign an id, and attach the break to the div */
        var theBreak = document.createElement("br");
        theBreak.id = fileName + "_br";
        document.getElementById(uploadedFilesSpanId).appendChild(theBreak);
    }
}

function testRemoveFile(name,spanId,ffe,id) {
    switch (spanId){
        case "ulZipDetect":
        	resultsLoading();
         LocationAjaxController.removeZipFile(name,ffe,id, function(results) {
             removeFileAnchor(id);
             printTypeResult(results.companySearch, "locationUploadReply", results.messages, results.prettyResultCount);
         });
         break;
     case "IndusULDetect":
         var codeType = jQuery("input[name=indusFileType]:checked").val();
         var what = jQuery("input[name=PrimarySecondary]:checked").val();
         var test ="";

         switch (codeType){
            case "usSIC":
                if (what == "Secondary"){
                    test = "UPLOAD_SECONDARY_SIC_CODE";
                }else{
                    test =  "UPLOAD_PRIMARY_SIC_CODE";
                }
            break;
            case "ukSIC":
                if (what == "Secondary"){
                    test = "UPLOAD_UK_SECONDARY_SIC_CODE";
                }else{
                    test = "UPLOAD_PRIMARY_UK_SIC_CODE";
                }
            break;
            case "NAICS":
                if (what == "Secondary"){
                    test = "UPLOAD_SECONDARY_NAICS_CODE";
                }else{
                    test = "UPLOAD_PRIMARY_NAICS_CODE";
                }
            break;
         }
         resultsLoading();
         IndustryAjaxController.removeIndustryFile(name,test,id, function(results) {
                     removeFileAnchor(id);
                     printTypeResult(results.companySearch, "industryUploadReply", results.messages, results.prettyResultCount);
         });
         break;
         case "DUNSfileDetect":
        	 resultsLoading();
            ListBuilderSpecialtyCriteriaController.removeDunsFile(name,"DUNS", id, function(results) {
                removeFileAnchor(id);
                printTypeResult(results.companySearch, "industryUploadReply", results.messages, results.prettyResultCount);

            });
         break;
         case "pDUNSfileDetect":
        	 resultsLoading();
            ListBuilderFamilyTreeController.removeDunsFile(name,ffe , id, function(results) {
                removeFileAnchor(id);
                // TODO: csanders
                // This isn't working, the br is getting removed even though jquery fines it
                // low priority , 6-30-09  
                var br = jQuery('#' + name + '_br');                
                if ( br )
                {
                	
                	br.remove();
                }
                printTypeResult(results.companySearch, "dunsFamilyTreeUploadReply", results.messages, results.prettyResultCount);
         });
         break;
         default :
         break;
    }
}

function removeFileAnchor(name){
    var id = "#" + name;
    jQuery(id).remove();
}

function showSaveSearch() {
	jQuery('#saveSearchLimitMessage').jqmHide();
    jQuery("#saveSearch").jqmShow();
    jQuery('#btnOverwriteSavedSearch').hide();

    jQuery('#saveSearchDiv').show();
    jQuery('#endSearchDiv').hide();

}

function saveSearch(name, description) {
    jQuery('#btnOverwriteSavedSearch').hide();
    BALGlobalAjaxController.saveSearch(name, description, function(result) {
        saveSearchPost(result);
    });
}

function updateSavedSearch(name, description) {
    jQuery('#btnOverwriteSavedSearch').hide();
    BALGlobalAjaxController.updateSavedSearch(name, description, function(result) {
        saveSearchPost(result);
    });
}

function handleSuccesfulSaveOfSearch() {
	jQuery('#saveSearchName').val("");
	jQuery('#saveSearchDescription').val("");
	jQuery('#saveSearchError').html("");
	jQuery('#saveSearchError').hide();
	jQuery('#closeSearchTitle').html("Search Saved");
	jQuery('#closeSearchContent').html("Your search has been saved.");

    jQuery('#saveSearchDiv').hide();
    jQuery('#endSearchDiv').show();

}


function handleUnsuccesfulSaveOfSearch(result) {
	var errorMessage = "";
	for (i = 0; i < result.messages.length; i++) {
		errorMessage += result.messages[i];
	}

	if (errorMessage.indexOf("Overwrite") > -1) {
		jQuery('#saveSearchError').html("<font color=red>" + errorMessage
				+ "</font>");
		jQuery('#saveSearchError').show();
		jQuery('#btnOverwriteSavedSearch').show();
	}
	else {

		jQuery('#saveSearchLimitError').html("<font color=red>" + errorMessage
				+ "</font>");
		jQuery('#saveSearchLimitError').show();

		jQuery("#saveSearch").jqmHide();
		jQuery('#saveSearchLimitMessage').jqmShow();
	}



}



function saveSearchPost(result) {
	if (result.validProcess) {
		handleSuccesfulSaveOfSearch();
	} else {
		handleUnsuccesfulSaveOfSearch(result);
	}
}


var MAX_DUMP_DEPTH = 10;

function dumpObj(obj, name, indent, depth) {
    if (depth > MAX_DUMP_DEPTH) {
        return indent + name + ": <Maximum Depth Reached>\n";
    }

    if (typeof obj == "object") {
        var child = null;
        var output = indent + name + "\n";
        indent += "\t";
        for (var item in obj)
        {
            try {
                child = obj[item];
            } catch (e) {
                child = "<Unable to Evaluate>";
            }

            if (typeof child == "object") {
                   output += dumpObj(child, item, indent, depth + 1);
            } else {
                   output += indent + item + ": " + child + "\n";
            }
        }
        return output;
    } else {
        return obj;
    }
}

function searchFastByDelimitedList(fieldId, dwrType, popOverDivId, popOverDataDivId) {
    var fieldValue = document.getElementById(fieldId).value;

    switch (dwrType)
    {
        case "financial":
             FinancialInfoAjaxController.searchFastByDelimitedList(fieldId, fieldValue, function(result) {
                completeFastSearch(result, popOverDivId, popOverDataDivId, dwrType);
             });
             break;
         case "specialtyCriteria":
             SpecialtyCriteriaAjaxController.searchFastByDelimitedList(fieldId, fieldValue, function(result) {
            	 completeSpecialtySearch(result, popOverDivId, popOverDataDivId, dwrType);
             });
             break;

         case "location":
     	    //clear our any data
     	    jQuery("#"+popOverDataDivId).empty().html(sLoadingHtml);
     	    var areaType = jQuery("#locationSearchAreaType").val();
    		LocationAjaxController.searchFastByLocation(fieldId, fieldValue, areaType, function(result) {
    	 		completeLocationSearch(result, popOverDivId, popOverDataDivId, dwrType);
    	 	});
        	 	break;

         case "industry":
            //clear our any data
	        jQuery("#"+popOverDataDivId).empty().html(sLoadingHtml);
        	var industryCodeType = jQuery("#industryCodeSearchType").val();
    	 	IndustryAjaxController.searchFastByIndustry(fieldId, fieldValue, industryCodeType, function(result) {
    	 		completeIndustrySearch(result, popOverDivId, popOverDataDivId, dwrType);
    	 	});
    	 	break;

        default:
            alert("Invalid dwrType in function searchFastByDelimitedList: " + dwrType);
            break;
    }
}

function completeSpecialtySearch(result, popOverDivId, popOverDataDivId, dwrType)
{
    var theHtml = "";
    if (result.successful)
    {
        var submitButton = jQuery("#"+popOverDivId+"_submit")[0];


        // disable the submit button if it exists
        if (submitButton != null) {
        	submitButton.disabled=true;
        }

        //clear our any data
        jQuery("#"+popOverDataDivId).empty();

        // Add the search results to the search results div
        var searchResults = result.searchResults;
        var selectionLinks = jQuery("#"+popOverDivId+"SelectLinks")[0];
        if (searchResults.length > 0) {
        	if (submitButton != null) {
        		submitButton.style.display = "";
        		selectionLinks.style.display = "";
        	}
            for (var i = 0; i < searchResults.length; i++)
            {
                theHtml += '<label for="'+popOverDataDivId+'_input_'+i+'">' +
                           '<input value="'+searchResults[i].id +'" ' +
                    'id="'+searchResults[i].id + '"' + 
                           'onclick="recordCheckBoxClicks(\''+searchResults[i].id+'\',\'addCriteriaAndCloseSpecialtySearch\');" ' +
                           'type="checkbox" name="'+popOverDataDivId+'_input"/>' +
                           searchResults[i].name +
                           '</label>';
            }
            jQuery("#"+popOverDataDivId).html(theHtml);
        } else {
        	if (submitButton != null) {
	            submitButton.style.display = "none";
	            selectionLinks.style.display = "none";
        	}
            jQuery("#" + popOverDataDivId).html("No matching entries are available.");
        }

        /* Display the pop over box that will be populated with the search results */
        jQuery('#' + popOverDivId).jqmShow();
    } else {
    	// the search was unsuccessfull, diplay any messages if present
    	if (result.messages.length > 0) {
    		for (var i = 0; i < result.messages.length; i++)
            {
                theHtml += '<p>' + result.messages[i] + '</p>';
            }
            jQuery("#"+popOverDataDivId).html(theHtml);
    	}
    }
}


function completeIndustrySearch(result, popOverDivId, popOverDataDivId, dwrType)
{
    var theHtml = "";
    if (result.successful)
    {
        // Add the search results to the search results div
        var searchResults = result.searchResults;
        //var selectionLinks = jQuery("#"+popOverDivId+"SelectLinks")[0];
        if (searchResults.length > 0) {
            for (var i = 0; i < searchResults.length; i++)
            {
                theHtml += '<label for="'+popOverDataDivId+'_input_'+i+'">' +
                           '<input id="'+searchResults[i].id +'_indSearch" ' +
                           'browseitems="' + searchResults[i].browseItems + '" ' +
                           'display="' + searchResults[i].name + '" ' +
                           'onclick="recordCheckBoxClicks(\''+searchResults[i].id+'\',\'addCriteriaAndCloseIndustrySearch\');" ' +
                           'type="checkbox" name="'+popOverDataDivId+'_input"/>' +
                           searchResults[i].name +
                           '</label>';
            }
            jQuery("#"+popOverDataDivId).html(theHtml);
        } else {
            jQuery("#" + popOverDataDivId).html("No matching entries are available.");
        }

        /* Display the pop over box that will be populated with the search results */
        jQuery('#' + popOverDivId).jqmShow();
    } else {
    	// the search was unsuccessfull, diplay any messages if present
    	if (result.messages.length > 0) {
    		for (var i = 0; i < result.messages.length; i++)
            {
                theHtml += '<p>' + result.messages[i] + '</p>';
            }
            jQuery("#"+popOverDataDivId).html(theHtml);
    	}
    }
}

function completeLocationSearch(result, popOverDivId, popOverDataDivId, dwrType)
{
    var theHtml = "";
    if (result.successful)
    {


        // Add the search results to the search results div
        var searchResults = result.searchResults;
        //var selectionLinks = jQuery("#"+popOverDivId+"SelectLinks")[0];
        if (searchResults.length > 0) {
            for (var i = 0; i < searchResults.length; i++)
            {
                theHtml += '<label for="'+popOverDataDivId+'_input_'+i+'">' +
                           '<input id="'+searchResults[i].id +'_locSearch" ' +
                           'browseitems="' + searchResults[i].browseItems + '" ' +
                           'display="' + searchResults[i].name + '" ' +
                           'onclick="recordCheckBoxClicks(\''+searchResults[i].id+'\',\'addCriteriaAndCloseSearch\');" ' +
                           'type="checkbox" name="'+popOverDataDivId+'_input"/>' +
                           searchResults[i].name +
                           '</label>';
            }
            jQuery("#"+popOverDataDivId).html(theHtml);
        } else {
            jQuery("#" + popOverDataDivId).html("No matching entries are available.");
        }

        /* Display the pop over box that will be populated with the search results */
        jQuery('#' + popOverDivId).jqmShow();
    } else {
    	// the search was unsuccessfull, diplay any messages if present
    	if (result.messages.length > 0) {
    		for (var i = 0; i < result.messages.length; i++)
            {
                theHtml += '<p>' + result.messages[i] + '</p>';
            }
            jQuery("#"+popOverDataDivId).html(theHtml);
    	}
    }
}

/**
* @param result the SearchResult object containing the results of the fast search
* @param popOverDivId the Id of the hidden pop over box that will be displayed
* @param popOverDataDivId the Id of the div (inside the pop over box) into which the search results will be placed
* @param dwrType the section name of the dwr controller to call ('financial', for example)
*/
function completeFastSearch(result, popOverDivId, popOverDataDivId, dwrType)
{
    var theHtml = "";
    if (result.successful)
    {
        var submitButton = jQuery("#"+popOverDivId+"_submit")[0];


        // disable the submit button if it exists
        if (submitButton != null) {
        	submitButton.disabled=true;
        }

        //clear our any data
        jQuery("#"+popOverDataDivId).empty();

        // Add the search results to the search results div
        var searchResults = result.searchResults;
        var selectionLinks = jQuery("#"+popOverDivId+"SelectLinks")[0];
        if (searchResults.length > 0) {
        	if (submitButton != null) {
        		submitButton.style.display = "";
        		selectionLinks.style.display = "";
        	}
            for (var i = 0; i < searchResults.length; i++)
            {
                theHtml += '<label for="'+popOverDataDivId+'_input_'+i+'">' +
                           '<input value="'+searchResults[i].id +'" ' +
                           'onclick="enableModalSubmit(\''+popOverDivId+'\')" ' +
                           'type="checkbox" name="'+popOverDataDivId+'_input"/>' +
                           searchResults[i].name +
                           '</label>';
            }
            jQuery("#"+popOverDataDivId).html(theHtml);
        } else {
        	if (submitButton != null) {
	            submitButton.style.display = "none";
	            selectionLinks.style.display = "none";
        	}
            jQuery("#" + popOverDataDivId).html("No matching entries are available.");
        }

        /* Display the pop over box that will be populated with the search results */
        jQuery('#' + popOverDivId).jqmShow();
    } else {
    	// the search was unsuccessfull, diplay any messages if present
    	if (result.messages.length > 0) {
    		for (var i = 0; i < result.messages.length; i++)
            {
                theHtml += '<p>' + result.messages[i] + '</p>';
            }
            jQuery("#"+popOverDataDivId).html(theHtml);
    	}
    }
}

/*
* Enables the submit button for modal search results.
*/
function enableModalSubmit(popOverDivId) {
    var checkBoxes = jQuery("#"+popOverDivId+" :checkbox");
    var anyChecked = false;
    jQuery.each(checkBoxes, function(){if (this.checked) anyChecked = true;});
    if (anyChecked)
    {
       jQuery("#"+popOverDivId+"_submit")[0].disabled=false;
       jQuery("#"+popOverDivId+"_submit").addClass("disable");
    }
    else {
    
    	jQuery("#"+popOverDivId+"_submit")[0].disabled=true;
    	jQuery("#"+popOverDivId+"_submit").removeClass("disable");
    }
}

/**
* @param popOverDivId the Id of the hidden pop over box that will be displayed
* @param popOverDataDivId the Id of the div (inside the pop over box) into which the search results were placed
* @param selectedResultsDivId the Id of the div into which the selected search results will be placed
* @param dwrType the section name of the dwr controller to call ('financial', for example)
*/
function processFastSelections(popOverDivId,popOverDataDivId,selectedResultsDivId,dwrType)
{
    var selectedResultsDiv = document.getElementById(selectedResultsDivId);
    var popOverDataDiv = document.getElementById(popOverDataDivId);

    /* Display the results box */
    selectedResultsDiv.style.display="";

    /* Find any search results that were selected in the pop up div */
    var selectFields = popOverDataDiv.getElementsByTagName('label');

    /* Find out how many entries are already in the selected results div */
    var startingSelectedResultSize = selectedResultsDiv.getElementsByTagName('label').length;
    // alert("startingSelectedResultSize: " + startingSelectedResultSize);

    /* Copy selections from the pop up div to the selected results div */
    var nextSelectedResultNumber = startingSelectedResultSize;
    if (usingIE())
    {
        buildSelectedInnerHtmlCheckboxes(selectFields, selectedResultsDivId, nextSelectedResultNumber, dwrType);
    }
    else
    {
        for (var i = 0; i < selectFields.length; i++)
        {
            var inputFields = selectFields[i].getElementsByTagName('input');
            {
                if (inputFields.length > 0 &&
                    inputFields[0].type == "checkbox" &&
                    ( inputFields[0].checked == "checked" || inputFields[0].checked == true))
                {
                    /* Node 0 of selectFields is the label element; node 1 is the text node containing the item name */
                    var itemName = selectFields[i].childNodes[1].nodeValue;
                    var itemId = inputFields[0].value;
                    addSelectLinksToDiv(itemName, itemId, selectedResultsDivId, nextSelectedResultNumber, true, true, dwrType);
                    nextSelectedResultNumber++;
                }
            }
        }
    }

    /* Call the server to process the selections */
    submitList(selectedResultsDivId + "_input",dwrType);

    /* Close the pop over box that will be populated with the search results */
    jQuery('#' + popOverDivId).jqmHide();
}

/**
* @param itemName the display name of an item
* @param itemId the id of an item; this value will be sent to the server
* @param divId the Id of the div where the links will be inserted
* @param index the index for the link to be created
* @param checked true if the checkbox should be checked; otherwise false
* @param addEvent true an event should be added to the checkbox
* @param dwrType the section name of the dwr controller to call ('financial', for example)
*/
function addSelectLinksToDiv(itemName, itemId, divId, index, checked, addEvent, dwrType) {
    /* Create a input field */
    var theInput = document.createElement("input");
    theInput.setAttribute("type", "checkbox");
    var theInputId = divId + "_input_" + index;
    theInput.setAttribute("id", theInputId);
    var theInputName = divId + "_input";
    theInput.setAttribute("name", theInputName);
    theInput.setAttribute("value", itemId);
    /* Set the checkbox to checked if requested */
    if (checked == true){
        theInput.checked = true;
    }
    /* Add an onclick to the checkbox if requested */
    if (addEvent == true) {
        theInput.onclick = (function() {submitList(theInputName,dwrType);});
    }

    /* Create a label */
    var theLabel = document.createElement("label");
    theLabel.setAttribute("for", divId + "_input_" + index);

    /* Append the input field to the label */
    theLabel.appendChild(theInput);

    /* Append text to the label */
    var txtNode = document.createTextNode(itemName);
    theLabel.appendChild(txtNode);

    /* Append the label to the div */
    document.getElementById(divId).appendChild(theLabel);
}


function enableDisableDropDown(field1){
    var firstField = document.getElementById(field1).checked;

    if(firstField == true){
        document.balForm.importExportSlct.disabled = false;
    } else {
        document.balForm.importExportSlct.disabled  = true;
    }
}

function submitSelectBoxList(fieldName, dwrType) {
    var index = document.balForm.importExportSlct.selectedIndex;
    var values = new Array();
    values[0] = document.balForm.importExportSlct.options[index].value;

    if (dwrType == 'companyType') {
    	resultsLoading();
        CompanyTypeAjaxController.processList(fieldName, values, function(result) {
        		printTypeResult(result.companySearch, null, result.message, result.prettyResultCount, null);
        });
    }
}

// Handles the range for the New and Changed Records
function processNewAndChangedRecordsRange(fieldName1,fieldName2) {
    var fieldValue1 = document.getElementById(fieldName1).value;
    var fieldValue2 = document.getElementById(fieldName2).value;
    operatorValue = 2; // handle the Between operator internally with out user
						// selection

    if(document.getElementById(fieldName1).checked == false)
    {
        fieldValue1 = "";
        fieldValue2 = "";
    }
        //System internally determines the range
    resultsLoading();
    NewAndChangedRecordsAjaxController.processSystemGeneratedRange(fieldName1, fieldName2, fieldValue1, fieldValue2,operatorValue,function(result) {
    	printTypeResult(result.companySearch, fieldName1 + '_msg', result.message, result.prettyResultCount);
        });
}

function usingIE()
{
    var browser = navigator.appName;
    if (browser == 'Microsoft Internet Explorer')
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
* @param searchResults an array of search result objects
* @param divId the Id of the div where the links will be inserted
*/
function buildCandidateInnerHtmlCheckboxes(searchResults, divId)
{

}

/**
* @param selectFields an array of input select fields
* @param divId the Id of the div where the links will be inserted
* @nextSelectedResultNumber the index of the next selected item
* @param dwrType the section name of the dwr controller to call ('financial', for example)
*/
function buildSelectedInnerHtmlCheckboxes(selectFields, divId, nextSelectedResultNumber, dwrType)
{
    var theHtml = '';

    for (var i = 0; i < selectFields.length; i++)
    {
        var inputFields = selectFields[i].getElementsByTagName('input');
        {
            if (inputFields.length > 0 &&
                inputFields[0].type == "checkbox" &&
                ( inputFields[0].checked == "checked" || inputFields[0].checked == true))
            {
                /* Node 0 of selectFields is the label element; node 1 is the text node containing the item name */
                var itemName = selectFields[i].childNodes[1].nodeValue;
                var itemId = inputFields[0].value;
                var theInputId = divId + "_input_" + nextSelectedResultNumber;
                var theInputName = divId + "_input";

                /*
				 * The HTML we are constructing below follows the format of this
				 * sample label
				 */
                theHtml = theHtml + '<label for="' +
                                     theInputId +
                                      '"><input id="' +
                                      theInputId +
                                      '" value="' +
                                      itemId +
                                      '" type="checkbox" checked="checked" name="' +
                                      theInputName +
                                      '" onclick ="submitListWithAll(' +
                                      '\'' +
                                      theInputName +
                                      '\',\'' +
                                      dwrType +
                                      '\')"' +
                                      ' />' +
                                      itemName +
                                      '</label>';

                nextSelectedResultNumber++;
            }
        }
    }

    /* Append the label to the div */
    document.getElementById(divId).innerHTML = document.getElementById(divId).innerHTML + theHtml;
}

//handle the select box logical operator values(AND,OR)
// TO DO - This method is not generalised, Currently will serve only
// import/export
function processSelectBoxLogicalOperator(fieldId,modifier) {
    var index = document.balForm.importExportSlct.selectedIndex;
    var fieldValue = new Array();
    fieldValue[0] = document.balForm.importExportSlct.options[index].value;
    var checkBoxState = document.getElementById('importExport').checked;
    var myVal = "";
    if(checkBoxState == true) {
		// TODO: Short-term fix: Quote individual values to prevent wildcarding
		// Better long term fix will probably be to call
		// CompanyTypeAjaxController.processListWithAll()
        val = '24,25';
        myVal = '"' + fieldValue[0] + '"';
    }else{
        val ='';
    }

    if (fieldValue[0] == "2425")
    {
    	resultsLoading();
    	CompanyTypeAjaxController.processDelimitedListWithAll(fieldId, val, "noWildCard", "any", function(result) {
        	printTypeResult(result.companySearch, fieldId + '_msg', result.message, result.prettyResultCount);
                 });
    } else if (fieldValue[0] == "2524")
    {
    	resultsLoading();
    	CompanyTypeAjaxController.processDelimitedListWithAll(fieldId, val, "noWildCard", "all", function(result) {
        	printTypeResult(result.companySearch, fieldId + '_msg', result.message, result.prettyResultCount);
                 });
    } else {
    	resultsLoading();
    	CompanyTypeAjaxController.processDelimitedListWithAll(fieldId, myVal, "noWildCard", "any", function(result) {
        	printTypeResult(result.companySearch, fieldId + '_msg', result.message, result.prettyResultCount);
                 });
    }

}


function dumpObj(obj, name, indent, depth) {
    if (depth > 10) {
        return indent + name + ": <Maximum Depth Reached>\n";
    }

    if (typeof obj == "object") {
          var child = null;
          var output = indent + name + "\n";
          indent += "\t";

          for (var item in obj) {
                try {
                       child = obj[item];

                } catch (e) {
                       child = "<Unable to Evaluate>";
                }

                if (typeof child == "object") {
                       output += dumpObj(child, item, indent, depth + 1);
                } else {
                       output += indent + item + ": " + child + "\n";
                }
          }
          return output;
    } else {
        return obj;
    }
}

/**
* Shows or hides all instances of a child element (by tag name) that
* is inside a parent element.  For example, if childElementTagName is
* set to "label", this function will show or hide all label elements
* that are within the specified parentElement.
* @param parentElement the element whose child elements will be shown or hidden
* @param childElementTagName the tag name of the element (example, "label") to be shown or hidden
* @param show whether to show or hide the child elements
*/
function showHideChildElementsByTagName(parentElement, childElementTagName, show) {
    var children = parentElement.getElementsByTagName(childElementTagName);

    if (children)
    {
        for (var i = 0; i < children.length; i++) {
            if (show)
            {
                children[i].style.marginLeft ='';
            } else {
                /* setting style to display:none wasn't working for some reason,
                   so we hide the field my moving it far to the left of the display page.  */
                children[i].style.marginLeft ='-3000px';
            }
        }
    }
}


function clearAllErrorMessages() {
    var elements = document.getElementsByTagName('SPAN');
    if (elements)
    {
        for (var i = 0; i < elements.length; i++)
        {
            if (elements[i].className == 'errorText')
            {
                var id = elements[i].id;
                dwr.util.setValue(id, "");
            }
        }
    }
}

function processUserPref(fieldValue) {
    IndustryAjaxController.saveIndustryPrefs(fieldValue);
}

function expandSection(fieldId) {
    var field = document.getElementById(fieldId);

    var toToggle = '#' + jQuery(field).attr("rel") + ' .criteria';
    var theH3 = '#' + jQuery(field).attr("rel") + ' h3';
    jQuery(toToggle).show();
    if ( ! jQuery(theH3).hasClass("open")) {
       // alert("Going to expand" + jQuery(field).attr("rel") + "!");
        jQuery(theH3).addClass("open");
    }
    return false;
}

function expandSubsection(fieldId) {
    var field = document.getElementById(fieldId);
    var toToggle = '#' + jQuery(field).attr("rel") + ' .subcriteria';
    jQuery(toToggle).show();
    var theH4 = '#' + jQuery(field).attr("rel") + ' h4';
    jQuery(theH4).addClass("open");

    return false;
}

function expandCollapse() {
	
    var expandCompanyType = document.getElementById('expandCompanyType');
    var expandFinancialInfo = document.getElementById('expandFinancialInfo');
    var expandPeopleInfo = document.getElementById('expandPeopleInfo');
    var expandJobFunctionInfo = document.getElementById('expandJobFunctionInfo');
    var expandPeopleCriteria = document.getElementById('expandPeopleCriteria');
    var expandFamilyTree = document.getElementById('expandFamilyTree');
    var expandSpecialtyCriteria = document.getElementById('expandSpecialtyCriteria');
    var expandGeneralSpecialtyCriteria = document.getElementById('expandGeneralSpecialtyCriteria');
    var expandDBBizIndicators = document.getElementById('expandDBBizIndicators');
    var expandNewChangedRecords = document.getElementById('expandNewChangedRecords');

}

function isArray(obj) {
	return obj.constructor == Array;
}



recordedCheckBoxes = new Array();

function selectAll(parentDivName,buttonName)
{

    selectOrDeselect(parentDivName,buttonName,true);
}

function deselectAll(parentDivName,buttonName)
{
    selectOrDeselect(parentDivName,buttonName,false);
}

function selectOrDeselect(parentDivName, buttonName, setChecked)
{

    jQuery('#'+ parentDivName +' :checkbox').each(function(){

            if ( this.checked != setChecked ) recordCheckBoxClicksDeferDisableSubmit(this.id,buttonName,true);
            this.checked = setChecked;
        });

    disableOrEnableAddCriteriaButton(buttonName);
}

function recordCheckBoxClicksDeferDisableSubmit(fieldId, buttonName,deferDisable)
{
	fieldIndex = jQuery.inArray(fieldId, recordedCheckBoxes);

	if (fieldIndex != -1) {
		recordedCheckBoxes.splice(fieldIndex, 1);

	} else {
		recordedCheckBoxes.push(fieldId);

	}

	if ( !deferDisable) disableOrEnableAddCriteriaButton(buttonName);
	checkChildren(fieldId);

}

function recordCheckBoxClicks(fieldId, buttonName) {
    recordCheckBoxClicksDeferDisableSubmit(fieldId, buttonName,false);
}


function disableOrEnableAddCriteriaButton(buttonName) {
	if (recordedCheckBoxes.length > 0) {
		jQuery('#' + buttonName).attr('disabled', false);
		jQuery('#' + buttonName).removeClass('disable btnTallG');
		jQuery('#' + buttonName).addClass('btnTallY');
		jQuery('#' + buttonName).addClass('jqmClose');

	} else {
		jQuery('#' + buttonName).attr('disabled', true);
		jQuery('#' + buttonName).removeClass('btnTallY'); 
		jQuery('#' + buttonName).addClass('disable btnTallG');
		return false;
	}

}

function updateCriteria(browseTarget, checkboxIdentifier, buttonName,
		criteriaDiv) {

	var criteriaItems = new Array;
	var checkBoxes = jQuery('input:checkbox:[id*=' + checkboxIdentifier + ']:checked');
	var identifierLength = checkboxIdentifier.length + 1;
	var totalBrowseItems = '';

	for ( var index = 0; index < checkBoxes.length; index++) {
		if (!checkBoxes[index].disabled) {
			var fieldId = checkBoxes[index].id.substr(0,
					checkBoxes[index].id.length - identifierLength);
			var browseItems = jQuery('#' + fieldId).attr('browseitems');
			var display = jQuery('#' + fieldId).attr('display');
			var selectionType = (jQuery("#" + fieldId + " :checkbox.include")[0].checked) ? "INCLUDED" : "UNSELECTED";

			totalBrowseItems += browseItems + '^';


			checkChildren(fieldId);
			criteriaItem = new RemoveCriteriaItem(fieldId, display, browseItems, browseTarget, criteriaDiv);
			criteriaItems.push(criteriaItem);

		}

	}

	postToUrl(browseTarget, totalBrowseItems.substring(0,
			totalBrowseItems.length - 1), "INCLUDED", function(data) {

		if (data.search("DOCTYPE html PUBLIC") != -1) {
			alert("Session expired, please log in again");
			document.location = '/';
			return;
		}

		var result = eval("(" + data + ")");
		resultsLoading();
		printTypeResult(result.companySearch, null, result.message, result.prettyResultCount);
		

	});
	
	/* See if row is already in table */
	var rows = jQuery("#industryRemoveCriteriaDiv tr");

	for (index = 0; index < criteriaItems.length; index++) {
		var updateItem = criteriaItems[index];
		
		var fieldAlreadyInTable = false;
		var fieldId = updateItem.fieldId;
		for (var i = 0; i < rows.length; i++) {
			var substringIndex = rows[i].id.indexOf(fieldId);
			if (substringIndex != -1) {
				fieldAlreadyInTable = true;
				break;
			}
		}
		
		if ( !fieldAlreadyInTable) {
			updateRemoveCriteriaSection(updateItem.browseTarget,
					updateItem.browseItems, updateItem.display,
					updateItem.locationDiv, updateItem.fieldId,true);
		}
	}

	

	resetCriteriaTree(checkboxIdentifier);
	disableOrEnableAddCriteriaButton(buttonName);

}

function RemoveCriteriaItem(fieldId, display, browseItems, browseTarget,
		locationDiv) {
	this.fieldId = fieldId;
	this.display = display;
	this.browseItems = browseItems;
	this.browseTarget = browseTarget;
	this.locationDiv = locationDiv;
}

function postToUrl(browseTarget, browseItems, selectionType, callback) {
	jQuery.post(browseTarget, {
		layout : "none",
		browseitems : browseItems,
		selectionType : selectionType
	}, callback);
}

function updateSearchCriteria(browseTarget, checkboxIdentifier, buttonName,
		criteriaDiv, dataDiv ) {

	var criteriaItems = new Array;
	var checkBoxes = jQuery('input:checkbox:[id*=' + checkboxIdentifier + ']:checked');
	var identifierLength = checkboxIdentifier.length + 1;
	var totalBrowseItems = '';


	for ( var index = 0; index < checkBoxes.length; index++) {
		if (!checkBoxes[index].disabled) {
			var fieldId = checkBoxes[index].id;
			var display = jQuery('#' + fieldId).attr('display');
			var browseItems = jQuery('#' + fieldId).attr('browseitems');

			criteriaItem = new RemoveCriteriaItem(fieldId, display,
					browseItems, browseTarget, criteriaDiv);
			criteriaItems.push(criteriaItem);

			totalBrowseItems += browseItems + '^';
		}

	}
	postToUrl(browseTarget, totalBrowseItems.substring(0,
			totalBrowseItems.length - 1), "INCLUDED", function(data) {

		if (data.search("DOCTYPE html PUBLIC") != -1) {
			alert("Session expired, please log in again");
			document.location = '/';
			return;
		}

		var result = eval("(" + data + ")");
		resultsLoading();
		printTypeResult(result.companySearch, null, result.message, result.prettyResultCount);

	});
	
	/* See if row is already in table */
	var displayColumns = jQuery("#industryRemoveCriteriaDiv tr:td:nth-child")

	for (index = 0; index < criteriaItems.length; index++) {
		var updateItem = criteriaItems[index];
		
		var rowAlreadyInTable = false;
		var displayValue = updateItem.display;
		for (var i = 0; i < displayColumns.length; i++) {
			var substringIndex = displayColumns[i].textContent.indexOf(displayValue);
			if (substringIndex != -1) {
				rowAlreadyInTable = true;
				break;
			}
		}
		
		if ( ! rowAlreadyInTable) {
			updateRemoveCriteriaSection(updateItem.browseTarget,
					updateItem.browseItems, updateItem.display,
					updateItem.locationDiv, updateItem.fieldId,true);
		}
	}


	resetCriteriaTree(checkboxIdentifier);
	disableOrEnableAddCriteriaButton(buttonName);

}

function removeCriteria(browseTarget, browseItems, id) {
	postToUrl(browseTarget, browseItems, "UNSELECTED", function(data) {

		if (data.search("DOCTYPE html PUBLIC") != -1) {
			alert("Session expired, please log in again");
			document.location = '/';
			return;
		}

		var result = eval("(" + data + ")");
		resultsLoading();
		printTypeResult(result.companySearch, null, result.message, result.prettyResultCount);

	});

	jQuery('#' + id + '_remove').remove();
	RemoveCriteriaTracker.deleteRemoveCriteria(id);

}

function updateRemoveCriteriaSection(browseTarget, browseItems, display,
		divName, fieldId,addToSession) {
	var tableRow = '<tr id="' + fieldId + '_remove" ><td>' + display + '</td><td>';

	tableRow += '<a href="#" onClick=\'removeCriteria("'
			+ browseTarget.replace(/"/g, "\\\"") + '","'
			+ browseItems.replace(/"/g, "\\\"") + '","'
			+ fieldId.replace(/"/g, "\\\"") + '");return false;\'>Remove</a>';
	tableRow += '</td></tr>';
	jQuery('#' + divName).append(tableRow);
	if ( addToSession )
	{
		RemoveCriteriaTracker.addRemoveCriteria(browseTarget, browseItems, display, divName, fieldId );
	}
}

function resetCriteriaTree(checkboxIdentifier) {

	jQuery.each(
			jQuery('input[type=checkbox][id*=' + checkboxIdentifier + ']'),
			function(index, collection) {

				jQuery('#' + this.id).attr('checked', false);
//				var fieldId = this.id.substr(0, this.id.length
//						- (checkboxIdentifier.length + 1));
//				checkChildren(fieldId);
			});

	recordedCheckBoxes.length = 0;

}

function getRemoveCriteriaFromSession()
{


	RemoveCriteriaTracker.getCriteria(
			function(result) {
				if ( result.successful )
				{
					for ( var i = 0;i < result.searchResults.length; i++ )
					{
						updateRemoveCriteriaSection(result.searchResults[i].browseTarget,
								result.searchResults[i].browseItems,
								result.searchResults[i].display,
								result.searchResults[i].locationDiv,
								result.searchResults[i].fieldId,false);
					}
				}

    	 	});


}

function zeroState(searchBox,resultsDiv)
{
	jQuery('#' + resultsDiv).empty();
	document.getElementById(searchBox).value = '';
}
function resultsLoading() {
	jQuery('#balCount').empty().html(sLoadingHtml);
}