var timeoutId;
var num_calls=0;
var num_calls_reset=0;
$(document).ready(function() {
	
	set_states();
	
	function get_states(){
		hash = '';
		$('.states_list li').addClass('print_hide');
		$('.state_input:checked').each(function(){
			$('.'+this.id+'_state_li').removeClass('print_hide');
			if (hash.length && hash.length != 0){
				hash += ":"+this.id;
			} else {
				hash = this.id;
			};
		});
		$('#id_state_selection').attr('value',hash);
		if ($('#id_state_selection').val() == ''){
			$('#all_states').attr('checked','checked');
			$('.all_state_li').removeClass('print_hide');
		}else{
			$('#all_states').removeAttr("checked");
			$('.all_state_li').addClass('print_hide');
		};
		set_timmer();
	};
	
	$('#all_states').change(function() {
		if ($('#all_states').attr('checked') != 'checked'){
			$('.state_input:checked').removeAttr("checked");
			$('#id_state_selection').attr('value','');
			$('#all_states').attr('checked','checked');
			get_states();
		}else{
			get_states();
		};
	});


        function change_state_selection() {
            jQuery.ajax({url: '/provider/filters/get_state_from_zip?zip_code=' + $('#id_zip_code').val() + '&listing_type=' + get_listing_type(),
                         success: function(data) {
                            $('#id_state_selection').val(data);
                            return data;
                         },
                         async: false
                        });
            return "";
        }

        $('#id_zip_code').keydown(function(e) {
            key = e.keyCode || e.which || null;
            if (key == 13 || key == 10) {
                change_state_selection();
                set_states();
                set_timmer();
            }
            return true;
        });

	function set_states() {
		hash = $('#id_state_selection').val();
		$('.states_list li').addClass('print_hide');
		$('.state_input').removeAttr("checked");
		if(hash.length && hash.length != 0){
                    state_ids = hash.split(':');
                } else {
                    state_ids = change_state_selection().split(':');
                }
                $('.state_input').removeAttr("checked");
                for(i=0; i < state_ids.length; i++){
                        $('#'+state_ids[i]).attr("checked","checked");
                        $('.'+state_ids[i]+'_state_li').removeClass('print_hide');
		}
		if ($('#id_state_selection').val() == ''){
			$('#all_states').attr('checked','checked');
			$('.all_state_li').removeClass('print_hide');
		}else{
			$('#all_states').removeAttr("checked");
			$('.all_state_li').addClass('print_hide');
		}
	}
	
	$('.state_input').click(function() {
		get_states();
	});
	
	$(".state_image").click(function () {
		if($(".state_box").hasClass('hidden')){
			$(".state_box").removeClass('hidden');
		}else{
			$(".state_box").addClass('hidden');
		}
        });
	
        $("#activity_providers_tab").click(function () {
            if ($('#community_events_tab').hasClass('active')) {
                $("#id_providers").parent().removeClass('hidden').removeClass('print_hide');
                $("#id_activity_type").parent().removeClass('hidden').removeClass('print_hide');
                $("#id_order").parent().removeClass('hidden').removeClass('print_hide');
                $("#top_pagination_text").removeClass('print_hide').removeClass('hidden');
            }
            $(this).addClass("active");
            $(this).siblings("a").removeClass("active");
            $('#id_search_camps').attr('checked', false);
            $("#id_search_community").attr('checked', false);
            $(this).addClass("active");
            $('#id_search_activity').attr('checked', true);
            $(".state_filter").addClass('hidden');
            $(".state_box").addClass('hidden');
            $(".state_filter").addClass('print_hide');
            $(".state_box").addClass('print_hide');
            set_timmer();
            return false;
        });
	$("#camp_providers_tab").click(function () {
            if ($('#community_events_tab').hasClass('active')) {
                $("#id_providers").parent().removeClass('hidden').removeClass('print_hide');
                $("#id_activity_type").parent().removeClass('hidden').removeClass('print_hide');
                $("#id_order").parent().removeClass('hidden').removeClass('print_hide');
                $("#top_pagination_text").removeClass('print_hide').removeClass('hidden');
            }
            $(this).addClass("active");
            $(this).siblings("a").removeClass("active");
            $('#id_search_activity').attr('checked', false);
            $("#id_search_community").attr('checked', false);
            $(this).addClass("active");
            $('#id_search_camps').attr('checked', true);
            $(".state_filter").removeClass('hidden');
            $(".state_filter").removeClass('print_hide');
            $(".state_box").removeClass('print_hide');
            get_states();
            return false;
        });
        $("#community_events_tab").click(function() {
            $(this).addClass("active");
            $(this).siblings("a").removeClass("active");
            $("#id_search_activity").attr('checked', false);
            $("#id_search_camps").attr('checked', false);
            $("#id_search_community").attr('checked', true);
            $(".state_filter").addClass('hidden').addClass('print_hide');
            $(".state_box").addClass('hidden').addClass('print_hide');
            $("#id_order").parent().addClass('hidden').addClass('print_hide');
            $("#id_providers").parent().addClass('hidden').addClass('print_hide');
            $("#id_activity_type").parent().addClass('hidden').addClass('print_hide');
            $("#top_pagination_text").addClass('hidden').addClass('print_hide');
            set_timmer();
            return false;
        });
	//share thickbox
	$('#share_button').click(function() {
		thickbox.show('Share Provider Listing', '/provider/share/');
		return false;
	});

        $('#id_zip_code').change(function(e) {
            if ($(this).val().match(/^(\d{5}[-]?\d{4}|\d{5})$/)) {
                change_state_selection();
                set_states();
                set_timmer();
            }
        });

	/* load states on load */
	if ($('#id_zip_code').length > 0) {
	    var zip_code = $('#id_zip_code').val()
	    if (zip_code != 'undefined' && zip_code != '') {
	        change_state_selection();
		set_states();
	    }
	}

	$('#id_providers, #id_activity_type').change(function () {
            set_timmer();
	});
	
	
	function set_id_search() {
		var $this = $(this);
		if($this.val() == '') {
			$this.val('Provider Name');
			$this.addClass('prompt_text');
		}
	}
	$('#id_search').blur(set_id_search).each(set_id_search).focus(function() {
		if($(this).val() == 'Provider Name') {
			$(this).removeClass('prompt_text');
			$(this).val('');
			
		}
	});
	
	apply_events_listing_jq();
});

function apply_events_listing_jq(){
	$('#id_order').change(function () {
		set_timmer()
	});
	$('#program_detail_content ul li.listing_row').click(function() {
		window.location = $($(this).find('a')[0]).attr('href');
	});
}

function set_timmer(page){
	$('#program_detail_content').empty()
	$('#program_detail_content').append('<div id="loading_holder" style="text-align:center;"><img style="margin-top:100px;margin-bottom:100px;" title="Loading" src="/public/images/ajax-loader.gif" /></div>')
    $('#bottom_search_ads').css('bottom', 0);
	if(timeoutId != 0) {
		clearTimeout(timeoutId);
		timeoutId = 0;
	}
	timeoutId = setTimeout('provider_update_search(' + (typeof(page) !== 'undefined' && parseInt(page) ? page : 0) + ')',10);
};

function get_listing_type() {
    if ($('#camp_providers_tab').hasClass('active')) {
	return 'camp';
    } else {
	return 'activity';
    }
}

function _update_providers_dropdown(type) {
    var listing_type = get_listing_type();
    var params = {
	zip_code: $('#id_zip_code').val(),
	state_selection: $('#id_state_selection').val(),
	type: type,
	listing_type: listing_type
    }
    var url = "/provider/filters/";
    $.ajax({
        type: 'get',
        dataType: 'json',
        url: url,
        data: params,
        success: function(resp_json) {
            var providers = resp_json.providers;
            var activity_types = resp_json.activity_types;
            
            var provider_val = $('#id_providers').val();
            var activity_type_val = $('#id_activity_type').val();
            
            $('#id_providers').html($(providers).html());
            $('#id_activity_type').html($(activity_types).html());
            
            $('#id_providers').val(provider_val);
            $('#id_activity_type').val(activity_type_val);       
        }
    });
    //update_analytics(build_url(url, params));
}

function provider_update_search(page){
	params = {partial:'True'};
	url = '/provider/'
	if (page != 0){
		params.page = page
	}
	if ($('#id_zip_code').length != 0){
		params.zip_code = $('#id_zip_code').val();
	}
	if($('#id_search_activity').attr('checked') == true){
		params.search_activity = 'on';
	}
	if($('#id_search_camps').attr('checked') == true){
		params.search_camps = 'on';
	}
	if($('#id_search_community').attr('checked') == true){
            params.search_community = 'on';
            params.activity_type = 'all';
            params.providers = 'all:all';
	} else {
            params.state_selection = $('#id_state_selection').val();
            params.activity_type = $('#id_activity_type').val();
            params.providers = $('#id_providers').val();
            params.order = $('#id_order').val();
            _update_providers_dropdown(params.activity_type);
        }

	params.search = $('#id_search').val()
	        
        update_analytics(build_url(url, params));
        num_calls += 1;
        
        //num_calls_reset = setInterval(function () {
        //    if ( num_calls != 1 ) num_calls=1;
        //    }, 2000);
	$.post(url, params,
		function(data){
                        if (num_calls > 1) {
                            num_calls -= 1;
                            return;
                        }
                        //if (num_calls_reset != 0) clearInterval(num_calls_reset);
                        num_calls -= 1;
			re = new RegExp("^window.location");
			if (data.match(re)) {
				data = data.replace('window.location = ', '');
				data = data.replace('\"', '');
				data = data.replace('\"', '');
				window.location = data;
				return;
			} else {
				$('#search_area').empty();
				$('#search_area').append(data);
                $('#bottom_search_ads').css('bottom', '51px');
				apply_events_listing_jq();
			}
            update_static_content(params);
//            update_right_column(params);
//            update_search_static_content();
	});
        external_refresh_marquee('forward');
        external_refresh_side_marketing();
	return false;
};

function update_right_column(params) { 
    update_static_content(params);

}

function update_search_static_content() {

    var search_static_url = '/static/search_content/update/';
    var current_lat = $('input[name="current_lat"]').val();
    var current_long = $('input[name="current_long"]').val();
    var activity_type = $('#id_activity_type').val();
    var params = {}
    if (current_lat && current_lat != '' && current_lat !== 'undefined' && parseFloat(current_lat) != 0.0) {
        params.latitude = encodeURIComponent(current_lat);
        params.longitude = encodeURIComponent(current_long);
    }
    if (activity_type && activity_type != '' && activity_type !== 'undefined') {
        params.activity_type = encodeURIComponent(activity_type);
    }

    $.get(search_static_url, 
            params,
            function(data) {
                $('#search_static_block').html(data);
            }
            
    );
}

function update_static_content(params) {
    $.ajax({
        type: 'GET',
        url: '/provider/static_content/update/',
        data: params,
        dataType: 'json',
        async: true,
        success: function(data) {
                var right_content_func = function() { 
                    $('#featured_block').html(data.featured_providers); 
                    $('#at_university').html(data.activity_academy); 
                };
                var search_static_content_func = function() { $('#search_static_block').html(data.search_static_content); };
                var change_title_func = function() { document.title = data.title; };
                var change_meta_func = function() { 
                    $('meta[name=keywords]').attr('content', data.meta.keywords);
                    $('meta[name=description]').attr('content', data.meta.description);
                 };
                var map_func = function() {
                $('#featured_content, #featured, #search_local_map').show(1, function () {
                    gmap_run(params, data.local_map_xml);
                });
                        
                        //setTimeout(show_hide_right_nav, 1);
                };
                setTimeout(search_static_content_func, 80);
                setTimeout(change_title_func, 1);
                setTimeout(change_meta_func, 5);

                setTimeout(right_content_func, 10);
                setTimeout(map_func, 30);
                setTimeout(show_hide_academy_refresh, 60);
        }

            
    });
}



$(document).ready(function() {
//    $(window).bind('resize', update_right_nav_width);
//  $('#right_column').hover(function() {
//      if ($(window).width() < 1198) {
//           window.scrollTo(0, 1198);
//      } 

//  });
    //$('#search_local_map, #map').show();
});

