$(document).ready(function(){
	$('#change_country').click(function(){
		$('#as_login').dsLightbox('popup',{
			 PopTitle 	: gettext('Change Country'),
			 PopOk	 	: gettext('Change'),
			 PopDivId	: 'country_change_div',
			 successfn	: 'change_location_settings()',
			 lbWidth	: '385',
		});
	});
	$('#as_gbl_country').live('change',function(){
		get_states_cities();
	});
	$('#id_state').live('change',function(){
		if ($('#id_state').val() == '') {
			$('#id_city').val('');
		}
		get_cities();
	});
	$('#id_city').live('change',function(){
		if ( $.trim($('#id_city').val()) != '' ) {
			$('#id_state').val($(this).val().split('__')[0]);
		}
	});
	
	$('#as_register').click(function(event){
		event.preventDefault();
		$('.as_register_pop').toggle();
		event.stopPropagation();
	});
	
	$('.as_register_pop a').click(function(event){
		event.stopPropagation();		
	});
	
    $(document).click(function() {
        $(".as_register_pop").hide();
    });
});

function get_states_cities(){
	$('#id_state,#id_city').attr('disabled','disabled');
	$("#as_gbl_country_spinner").show();
	$.get('/get-gbl-country-specific-states-cities/',{ code : $('#as_gbl_country').val() },function(data){
		$('#as_gbl_state_dt,#as_gbl_state_dd,#as_gbl_city_dt,#as_gbl_city_dd').remove();
		$('#location_dl').append(data);
		$("#as_gbl_country_spinner").hide();
	});
}

function get_cities(){
	$('#id_city').attr('disabled','disabled');
	$("#as_gbl_state_spinner").show();
	$.get('/get-state-specific-cities/',{ id : $('#id_state').val() , code : $('#as_gbl_country').val() , call_from : 'public' },function(data){
		if (data == '0') {
			$('#as_gbl_city_dd, #as_gbl_city_dt').hide();
		}
		else {
			$('#as_gbl_city_dd, #as_gbl_city_dt').show();
		}
		$("#as_gbl_state_spinner").hide();
		$('#as_gbl_city_dd').html(data);
	});
}

function change_location_settings(){
	$('#save_spinner').show();
	var country_code = $('#as_gbl_country').val();
	var country_name = $('#as_gbl_country option:selected').html();

	if ($('#as_gbl_state_dd').css('display') == 'none') {
		var state_name = 'All';
	}
	else {
		var state_name = $('#id_state option:selected').html();
	}
	
	var city_name = $('#id_city option:selected').html();
	
	if (state_name == 'All') {
		state_name = ''
	}
	if (city_name == 'All') {
		city_name = ''
	}
	$.get('/set-location/',{ country_code : country_code, country_name : country_name, state_name : state_name , city_name : city_name }, function(data){
		window.location.reload( false );
	});
}

