﻿/*	================================================================================
	$.Example.survey
	Author: 	 Philip Poole
				
	Date:		 2010-01-30
	Description: Attemps to set the selected country in a drop down list of countries to
	 			 the user's current location. 
	================================================================================ */

(function($) {

    /**
    * <p>Attemps to set the selected country in a drop down list of countries to
    *    the user's current location.</p>
    * 
    * <p>For the script to work it is expect that each country is an option in a selected element
    * and the value for each option is the offical country code for that country.</p>
    *
    * <p>For more information view http://welovenicethings.com/XXXXX
    * 
    * <p>The script uses an API call from http://www.wipmania.com to carry out the 
    * Geolocation.</p>
    *
    * @param {string} cookieName The name of the cookie to set.
    * 
    * @example $.CountryLocator('ShippingAddress');
    * @class
    */
    $.fn.CountryLocator = function(cookieName, callback) {




       try{
        //if no cookie has been set (from a previous request) then call the API to find the users current country
        if ($.cookie(cookieName) == null) {
             //alert($.cookie(cookieName)+' j');
            $.getJSON('http://api.wipmania.com/jsonp?callback=?', '', function(j) {
            //if the user has already selected a country then do not overwrite that choice.
            //alert(j.address.country_code);
            $.cookie(cookieName, j.address.country_code);
            
                if (callback)
                    callback(j.address.country_code);

            });
        }
        else {
            //alert($.cookie(cookieName));
            if (callback)
                callback($.cookie(cookieName));
        }
        }
        catch(err){
        alert(err);
           $.getJSON('http://api.wipmania.com/jsonp?callback=?', '', function(json) {
            //if the user has already selected a country then do not overwrite that choice.
            //alert(json);
          
            
                if (callback)
                    callback(json.address.country_code);

            });
        }
    }
})(jQuery);
