function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }

function distantAffiliate(id,dist){
	this.id = id;
	this.distance = dist;
}

jQuery.Afilliates = {
	options : {
		robot : 'no',
		wwwroot : '',
		delayImage : 'layout/loading.gif'
	},
	
	init : function(options)
	{
		if (options)
			jQuery.extend(jQuery.Afilliates.options, options);

		if (jQuery.browser.msie) {

		}
	},
	
	checkZip : function(zip){
		if(zip.length == 5 && IsNumeric(zip))return zip;
	},
	

	//get the list of clinics from the server based on the zip that was entered
	getLatLon : function(input){
		var zip = jQuery(input).val();
		if(jQuery.Afilliates.checkZip(zip)){
			$('#searchResultsInternational').hide();
			jQuery('#findClinicError').html("<img height=\"27\" src=\""+jQuery.Afilliates.options.wwwroot+jQuery.Afilliates.options.delayImage+"\"></img>");
			var request = {'zip':zip};
			jQuery.Afilliates.sendSubmit(jQuery.Afilliates.options.wwwroot+'lib/zipToLatLon.php',request,jQuery.Afilliates.calculateAndLoad);
		}else{
			jQuery('#findClinicError').html('<h3 style="color:red;">Please enter a valid zipcode to calculate distance.</h3>');
		}
	},
	
	sortDist : function(a, b){
		return a.distance - b.distance;
	},
	
	resetResults : function(){
		jQuery("#affiliatesResults").empty();
		jQuery("#pasResults").empty();
		jQuery("#searchResults").hide();
	},
	
	calculateAndLoad : function(result){
		jQuery('#findClinicError').html("<h3>Recommended and Certified Affiliates near "+result.location.CITY+" "+result.location.STATE+" "+result.location.ZIP+"</h3>");
		jQuery.Afilliates.resetResults();
		jQuery.Afilliates.loadType('affiliates',result);
		jQuery.Afilliates.loadType('pas',result);
		jQuery("#searchResults").show();
	},
	
	loadType : function(type,result){
		var size = jQuery("#findClinicInputSize").val();
		//n array to sort the results
		var pairs = new Array();
		//get the lat lon from the result
		var lat2 = result.location.LATITUDE;
		var lon2 = result.location.LONGITUDE;
		//go through the list and calculate distances to the affiliates
		jQuery("#"+type+" .affiliate").each(function(i){
			var id = jQuery(this).attr("id");
			var lat1 = jQuery("#" + id+" #lat").text();
			var lon1 = jQuery("#" + id+" #lon").text();
			var dist = Number(jQuery.Afilliates.distance(lat1,lon1,lat2,lon2)).toFixed(0);
			var affiliate = new distantAffiliate(id,dist);
			pairs.push(affiliate);
			pairs = pairs.sort(jQuery.Afilliates.sortDist);
			//jQuery(id+" #distance").text(Number(dist).toFixed(1));
		});
		for(var i = 0;i < pairs.length; i++){
			if(Number(pairs[i].distance) > Number(size))break;
			jQuery("#" + pairs[i].id + " #distance").html("<br>Distance: "+pairs[i].distance+" miles").show();
			var clone = jQuery("#" + pairs[i].id).clone();
			jQuery('#'+type+"Results").append(clone);

			//jQuery('#findClinicError').html(clone.toSource()+' '+pairs[i].id);
			
			//jQuery('#findClinicError').html(jQuery('#findClinicError').html()+pairs[i].distance+"<br>");
		}
		jQuery('#'+type+"ResultsCount").html(i+" Results");
	},
	
	distance : function(lat1, lon1,	lat2, lon2){
		var theta = lon1 - lon2; 
		var dist	= Math.sin(jQuery.Afilliates.deg2rad(lat1)) *	Math.sin(jQuery.Afilliates.deg2rad(lat2))	+  Math.cos(jQuery.Afilliates.deg2rad(lat1)) * Math.cos(jQuery.Afilliates.deg2rad(lat2)) * Math.cos(jQuery.Afilliates.deg2rad(theta)); 
		dist = Math.acos(dist); 
		dist = jQuery.Afilliates.rad2deg(dist); 
		var miles = dist * 60 *	1.1515;

		return miles;
	},
	
	deg2rad : function(deg){
		return deg * (Math.PI / 180);
	},
	
	rad2deg : function(rad){
		return rad * (180 / Math.PI);
	},
	

	
	sendSubmit : function(url,request,callback){
		var ul_vars = {
		  interval : 1000, //The time in milleseconds between each status request.
		  speeds : []      //Keeps track of the speeds of each upload.
		};
		setTimeout(function(){
			submitter = new RepeatGetAction(url, request, ul_vars.interval);
			submitter.go();
			submitter.successFunc = function (getBack) {
				setTimeout(function (){callback(getBack);},100);
			}
			submitter.failFunc = function (getBack) {
		    	jQuery('#findClinicError').html('<h3 style="color:red;">Please enter a valid zipcode</h3>');
		  	}
			//this is what we do at the end
		;},100)
	}
};

//run this script when the document is ready
$(document).ready(function(){

	$.Afilliates.init(
		{
			robot: 'test',
			wwwroot : $('#www0').text()
		}
	);
	//attach the find clinic action to the button and maybe some color changes.
	$('#findClinicButton').bind('click',function(e){
		$.Afilliates.getLatLon($('#findClinicInput'));
	});
	$('#findClinicInput').keypress(function(e){
		if(e.which == 13 || e.which == 3)$.Afilliates.getLatLon($('#findClinicInput'));
	});
	$('#findClinicInput').bind('click',function(e){
		if($('#findClinicInput').val() == 'zip')$('#findClinicInput').val('');
	});
	
	//set up the buttons for the affiliate and certified student info
	$('.recommendedLabel').mouseover(function(e){
		$(this).css('color','#FF0000');
	}).mouseout(function(e){
		$(this).css('color','#000000');
	}).click(function(e){
		e.stopPropagation();
		var theBox = $(this).next();;
		$(theBox).css({'top':e.pageY-50,'left':e.pageX-10}).animate({
				'height':'170px'
		},250);
	});
	
	$('.closeMyParent').click(function(e){
		$(this).parent().hide();
	});
	
	//open up the internation lists
	$('#findInterNationalClinicButton').click(function(e){
		$('#searchResults').hide();
		$('#findClinicError').html('');
		$('#searchResultsInternational').css('height','0px').animate({
				'height':'350px'
		},250);
		//$('#usSearchControl').hide();
	});
});