


// -- Location selection --
// Required DIVs:
// * confirmationLocation
// * confirmAutoSelect
// * suggestNotFound
// * suggestErrorBlock
// * suggestProgress 
// * autoSelectFindButton
// -- -- -- -- -- -- -- -- 
// Form: needs the following form fields
//    * zip_select (hidden)
//    * city_select (hidden)
//    * state_select (hidden)
//    * nextButton (button)
//    * location (text) with id 'locationBar'
// -- -- -- -- -- -- -- -- 
function doSelected( value, dataString ) {
    var parts = dataString.split(';');
    _selected(parts[0],parts[1],parts[2], value, true);
}
function _selected( city, state, zip, value, submitFlag ) {
    var theLocationInput = jQuery("#locationBar");
    var oForm = document.forms[theLocationInput.closest('form').attr('name')];

    var locStr = city + ', '+state;
    if( hasZip(value) ) {
        locStr += ' '+zip;
    }
    theLocationInput.val(locStr);
    oForm.zip_select.value=zip;
    oForm.state_select.value=state;
    oForm.city_select.value=city;
    updateConfirmationLocation(locStr);
    jQuery('#nextButton').show();
    
    if( gInitializingLocation ) {
        gInitializingLocation = false;
        theLocationInput.focus();
    } else {
    	if( $.isFunction(window.lmOnValueChange) ) {
		lmOnValueChange(locStr);
    	}
    }
    
    if( submitFlag ) {
        submitAutoSuggestForm();// submit the form when the user clicks on a selection
    }    
}

function submitAutoSuggestForm() {
    if( $('#location').find('#nextButton').length == 0 ) {
    	// only try to auto submit if there is a location panel with a next button.  Otherwise we're
    	// on a landing page and shouldn't click the button.
    	return true; 
    }
    
    var locval = $("#locationBar").val();
    if( locval == null || $.trim(locval).length == 0 ) {
    	// nothing to submit
    	return false;
    }
    
    if( $('#confirmationLocation').length > 0 && $('#confirmationLocation').text() == 0 ) {
    	return hasZip(locval); // resolved on the server side
    } 
    
    $('#confirmAutoSelect').show();
    $('#confirmAutoSelect').effect("pulsate", { times:10 }, 1000, function(){ $(this).hide(); });
        
    // finally submit the form
    $('#location').find('#nextButton').click();
    return true;
}

function getAutoSelectDisplayLocation() {
    var theLocationInput = $("#locationBar");
    var oForm = document.forms[theLocationInput.closest('form').attr('name')];

    var state = oForm.state_select.value;
    var city = oForm.city_select.value;
    var zip = oForm.zip_select.value;
    
    if( null == city || city.length == 0 ) {
        return "";
    }
    
    var basicLoc = city + ", " + state;
    var fullLoc = basicLoc + " " + zip;
    var inLoc = theLocationInput.val();
    return inLoc == fullLoc ? fullLoc : basicLoc;
}

function hasZip(str) {
    return /^.*\d{5}.*/.test(str);
}

var gAutoSuggest = null;
var gInitializingLocation = true; 
function initAutoSelect() {
   var suggestOptions = { 
      serviceUrl: '/home/caseIntake/dyna/suggest.do',
      minChars:3, 
      maxHeight: 200,
      zIndex: 9999,
      deferRequestBy: 500, //miliseconds
      onSelect: function(value, data){ 
          doSelected(value, data);
      }
   };
   var suggestBar = jQuery('#locationBar');
   gAutoSuggest = suggestBar.autocomplete(suggestOptions);
   jQuery('#autoSelectFindButton').show();
   if( suggestBar.val().length == 0 ) {
   	gInitializingLocation = false;
        suggestBar.focus();
   } else {
   	gAutoSuggest.onValueChange();
   }
   $('#nextButton').show();
}

// lmOnChange is called from within jquery.autocomplete.js
function lmOnChange() {
    jQuery('#suggestNotFound').hide();
}

function lmOnNoSuggestions( srcElementId ){
    if( null != srcElementId ) {
        jQuery('#suggestNotFound').show();
    }
}

// lmShowCallback is called from within jquery.autocomplete.js
function lmShowCallback() {
    gAutoSuggest.adjustScroll(0); // selects the first in the list
    var input = jQuery('#locationBar');
    input.focus();
    jQuery('#suggestNotFound').hide();

    if( gAutoSuggest.suggestions.length < 1 ) {
        return;
    }
    
    // clear error messages if there are any
    jQuery('#suggestErrorBlock').hide();

    var data = gAutoSuggest.data[0];
    var suggestion = gAutoSuggest.suggestions[0];
    var dsplit = data.split(';');
    var inputValue = jQuery.trim(input.val()).toUpperCase();
    if( inputValue.indexOf(suggestion) != -1 && suggestion.indexOf(inputValue) != -1 ) {
        if( typeof disableonbeforeunload != 'undefined' ) {
	        disableonbeforeunload();
        }
        var loading = gInitializingLocation;
        _selected(dsplit[0], dsplit[1], dsplit[2], suggestion);
        if( loading ) {
        	gAutoSuggest.hide();
        } else {
	        gAutoSuggest.adjustScroll(0); // selects the first in the list
	}
        jQuery('#nextButton').show();
    } 
}
// callback added to autosuggest
function lmShowStatusIndicator( flag ) {
    if( flag ) {
        jQuery('#suggestProgress').show();
        jQuery('#autoSelectFindButton').hide();
    } else {
        jQuery('#suggestProgress').hide();
        jQuery('#autoSelectFindButton').show();
    }
}
// callback added to autosuggest
function lmHandleError( httpStatusCode, httpResponseText, errorDescription ) {
    var block = jQuery('#suggestErrorBlock');
    switch( httpStatusCode ) {
        case 503:
            block.html("Error: The service is temporarily unavailable. Please try again later.");
            break;
        case 502:
            //overload condition
            break;
        default :
            block.html("Error: An error occurred.  Please try again later.");
    }

    jQuery('#autoSelectFindButton').show();
    block.show();
}

function findAutoSelect( srcElementId ) {
    jQuery('#suggestNotFound').hide();
    gAutoSuggest.onValueChange(srcElementId);
    return false;
}

function initLocation() {
    jQuery.ajax({
        url: "/home/dynalocation",
        type: 'post',
        dataType : "json",
        timeout: 9000000,
        error: function( xhr, desc ){
            lmHandleError(xhr.status, xhr.responseText, "An error occurred.  Check the server's logs for details.");
       },
        success: function(jObj){
           var location = jObj.location;
           if( location.length > 0 ) {
           	if( jQuery('#locationBar').val() != location ) {
           		jQuery('#locationBar').val(location);
           		updateConfirmationLocation(location);
           	} 
           }
           if( jQuery('#locationBar').is(":visible") ) {
	   	initAutoSelect();
	   }
        } 
    });
}

function updateConfirmationLocation( loc ) {
	jQuery('#confirmationLocation').html(loc);
	jQuery('#noneSelected').hide();
	jQuery('#confirmAutoSelect').show();
}

function displayBlocks() {
	var show = jQuery('#combo_loc').val() == '1';
	if( show ) {
		jQuery('#locBoxHeader').fadeIn();
		jQuery('#locBox').fadeIn();
	} else {
		jQuery('#locBoxHeader').hide();
		jQuery('#locBox').hide();
	}
}

jQuery(document).ready(
    function() {
      // initializes based on which form is visible
      initLocation();
      // ab testing of location box
      displayBlocks();
    }
);


// end of file


