/* jQuery checkAvailability plugin
 * Examples and documentation at: http://www.jqeasy.com/
 * Version: 1.0 (22/03/2010)
 * No license. Use it however you want. Just keep this notice included.
 * Requires: jQuery v1.3+
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
(function($){
    $.fn.checkAvailability = function(opts) {
        opts = $.extend({
            target: '#geoid-info',
			trigger: '#btnCheck',
			ajaxSource: constants.site_url + 'check/',
			fireOnKeypress: false
        }, opts || {});
		var $this = $(this);
		
		if (opts.fireOnKeypress) {
			$this.keyup(function() {
				setTimeout(function(){ 
					checkGeoid();
				  }, 500 );
			});
			
			$this.keypress(function(event) {
				if (event.keyCode == 13) {
					event.preventDefault();
					return false;
				}
			});
		};
		// Modified to work with jquery typing plugin
		checkGeoid();
/*		
		$(opts.trigger).click(function() {
			checkGeoid();
        });
*/	
		function checkGeoid() {
			if (validateGeoid()) {
				$(opts.target).html('<img src="http://media.geoid.me/img/loading.gif"> checking availability...');
				geoidLookup(); 
			}
			else
			{
				$(opts.target).html('Letters, numbers and .-_ are accepted. Min 4 characters');
			}	
		};
		
		function geoidLookup() { 
			var val = $this.val();
			$.post(opts.ajaxSource, {
				geoid : val
			}, function(data) {
				switch(data) {
				case '1':
					$(opts.target).html('<span class="geoid-available">GeoID is available</span>');
					available=true;
					break;
				case '0':
					$(opts.target).html('<span class="geoid-unavailable">GeoID is not available</span>');
					available=false;
					break;
				default:
					$(opts.target).html("Error occurred");
				
				break;
			}

			});
			
//			$.ajax({ 
//					url: opts.ajaxSource, 
//					data: {geoid:val,s:Math.random()},
//					success: function(html){
//						$(opts.target).html(html);
//					},
//					error:function (){
//						$(opts.target).html('Sorry, but there was an error loading the document.');
//					}
//			}); 
		};
		
		function validateGeoid(str) {
			return (/^[A-Za-z0-9]{4,25}$/.test($this.val()));
		};
	};
})(jQuery);
