var cur_cat = null;
var cur_filter_item = null;
var remove_slideout_timeout = null;
var show_slideout_timeout = null;
var pending_slideout = null;
var cur_cat_id = 0;
var cur_hood = 0;
var subcat_request = null;

$(document).ready(function() {
	initFilterBar();
  /*$("#filter-bar").accordion({
    clearStyle
    autoHeight: false
  });*/
});
function initFilterBar()
{
	$("#filter-bar h2").each(function() {
		var id = $(this).attr("id");
		if($(this).hasClass("visible"))
		{
			$(this).children(".toggle-arrow").addClass(".toggle-arrow-open");
			//$("#"+id+"-content").show();
		} else {
			$(this).children(".toggle-arrow").addClass(".toggle-arrow-closed");
			//$("#"+id+"-content").hide();
		}
	});
	$(".module-map #filter-bar h2").click(function() {
    /*if(cur_filter_item != $(this).attr("id"))
    {
      if(cur_filter_item != null)
      {
        var item = $("#"+cur_filter_item);
        item.removeClass("visible");
        item.children(".toggle-arrow").removeClass("toggle-arrow-open").addClass("toggle-arrow-closed");
        var cur_container = $("#"+cur_filter_item+"-content");
        cur_container.hide('blind');
      }
      $(this).addClass("visible");
      $(this).children(".toggle-arrow").removeClass("toggle-arrow-closed").addClass("toggle-arrow-open");
      var container = $("#"+$(this).attr("id")+"-content");
      container.show('blind');
      cur_filter_item = $(this).attr("id");
    }*/
    var container = $("#"+$(this).attr("id")+"-content");
    if($(this).hasClass("visible"))
    {
      $(this).removeClass("visible");
      container.hide('blind');
    } else {
      $(this).addClass("visible");
      container.show('blind');
    }
    adjustSlideoutForScrollbars()
  });
  $("h2.visible").each(function() {
    cur_filter_item = $(this).attr("id");
  });
	//$(".main-cats").click(putMainCats);
	
	$(".custom-filter").click(function() {
		var layer = $(this).children("input").val();
		var label = $(this).children("label").text().trim();
		var trackdata = {};
				trackdata.type = "custom";
				trackdata.name = label;
		mpmetrics.track("filterBarClick", trackdata);
		$(".cat-wrapper").removeClass("selected");
		//$(this).parents(".cat-wrapper").addClass("selected");
		$(this).addClass("selected");
		if(window.map && layer)
		{
			//map.filterLogosLayer(layer)
			if(subcat_request)
			{
				subcat_request.abort();
			}
			if(cur_cat_id != layer)
			{
				cur_cat_id = layer;
			} else {
				return;
			}
			var base = map.getLayersByName("basemap_logos")[0];
      var base_only = map.getLayersByName("basemap")[0];
      var logos = map.getLayersByName("logos");
      base.setVisibility(true);
    	base_only.setVisibility(false);
    	if(logos.length > 0)
    	{
    		logos[0].setVisibility(false);
    	}
    	var filter = Filters.get(layer);
    	map.cur_cat_id = filter.category;
    	map.cur_sub_cat_id = 0;
    	map.customFilter = filter;
			map.setLogosLayerCached(layer);
			map.markersLayer.clearMarkers();
			map.loadUpdates();
		}
		return false;
	});
	$(".main-cats").click(function() {
		if(window.map)
		{
			map.cur_sub_cat_id = 0;
			map.clearSearchResults();
			if(subcat_request)
			{
				subcat_request.abort();
			}
		}
		
		putMainCats($(this).children("input"));
		var label = $(this).children("label").html();
		var trackdata = {};
				trackdata.type = "main";
				trackdata.name = label;
		mpmetrics.track("filterBarClick", trackdata);		return false;
	});
	$(".child-cat-wrapper").click(function() {
		var cat_id = $(this).children("input").val();
		var label = $(this).children("label").html();
		var parent_label = $(this).parent().parent().siblings("label").html();
		var trackdata = {};
				trackdata.type = "main-sub";
				trackdata.name = parent_label+"-"+label;
		mpmetrics.track("filterBarClick", trackdata);		
		if(cat_id != cur_cat_id)
		{
			cur_cat_id = cat_id;
		} else {
			return;
		}
    var main = $(this).parents(".child-cats-list-wrapper").siblings(".main-cats");
    clearCurCat(main);
    main.attr("checked","true");
    cur_cat = main;
    $(".child-cat-wrapper").removeClass("selected");
  	$(".child-cats").attr("checked",false);
    $(".cats-list .cat-wrapper").removeClass("selected");
    main.parents(".cat-wrapper").addClass("selected");
    $(this).addClass("selected");
    
    var wrapper = $(this).parents(".child-cats-list-wrapper");
  	main = wrapper.siblings("input");
  	main.attr("checked",true);
  	$(".cats-list .cat-wrapper").removeClass("selected");
    main.parent().addClass("selected");
    var main_cat = main.val();
  	//putMainCats(main);
  	var input = $(this).children("input");
  	input.attr("checked",true);
  	var cat_id = input.val();
  	$(".child-cat-wrapper").removeClass("selected");
  	$(this).addClass("selected");
  	wrapper.hide();
    
    if(window.map)
    {
    	var center = map.getCenter();
  		subcat_request = $.ajax({
  			url: '/map/getCategoryResults?cat_id='+cat_id+'&city='+map.city_id+"&main_cat="+main_cat+"&cx="+center.lon+"&cy="+center.lat,
  			dataType: 'json',
  			async: true,
  			success: OpenLayers.Function.bind(map.searchCallback,map)
  		});
  		if(main_cat != map.cur_cat_id) {
  			map.filterLogos(main_cat);
  		}
  		
  		map.hideBusinessPopup();
    	//map.filterLogos();
    	//return true;
    } else {
    	updatePostings();
    }
    return false;
  });
  $(".child-cats-list .cat-label").click(function() {
    //var id = $(this).attr("for");
    //$("#"+id).attr("checked",true);
    $(".child-cat-wrapper").removeClass("selected");
    $(this).parents(".child-cat-wrapper").addClass("selected");
    $(this).parents(".child-cats-list-wrapper").hide();
  });
  $(".show-slideout, .slideout-list-wrapper").mouseover(function() {
    if(remove_slideout_timeout != null)
    {
      window.clearTimeout(remove_slideout_timeout);
    }
    if(show_slideout_timeout != null)
    {
    	window.clearTimeout(show_slideout_timeout);
    }
    $(".slideout-list-wrapper").hide();
    if($(this).hasClass("slideout-list-wrapper"))
    {
      $(this).show();
      $(this).siblings(".cat-label").addClass("selected");
    } else {
      
      if($(this).hasClass("cat-label"))
      {
        $(this).addClass("selected");
      } else {
        $(this).siblings(".cat-label").addClass("selected");
      }
      pending_slideout = $(this).siblings(".slideout-list-wrapper");
      show_slideout_timeout = window.setTimeout(function() {
      	pending_slideout.show();
      },250);
      
      
      //$(this).siblings(".slideout-list-wrapper").find(".child-list").show('slide');
    }
    
    //$(this).find(".child-list").show('slide');
  });
  $(".show-slideout, .slideout-list-wrapper").mouseout(function() {
    if(remove_slideout_timeout != null)
    {
      window.clearTimeout(remove_slideout_timeout);
    }
    if(show_slideout_timeout != null)
    {
    	window.clearTimeout(show_slideout_timeout);
    }
    remove_slideout_elem = $(this);
    remove_slideout_timeout = window.setTimeout(function() {
      if(remove_slideout_elem.hasClass("slideout-list-wrapper"))
      {
        remove_slideout_elem.hide();
        remove_slideout_elem.siblings(".cat-label").removeClass("selected");
      } else {
        remove_slideout_elem.siblings(".slideout-list-wrapper").hide();
        if(remove_slideout_elem.hasClass("cat-label"))
        {
          remove_slideout_elem.removeClass("selected");
        } else {
          remove_slideout_elem.siblings(".cat-label").removeClass("selected");
        }
      }
    },500);
  });
 
  $(".slideout-list-wrapper").each(function() {
    var count = $(this).find(".child").length;
    var child_width = 145;
    
    if(count > 13)
    {
      var width = child_width * (Math.ceil(count/13));
      $(this).css("width",width+"px");
    } else {
      $(this).css("width",child_width+"px");
    }
    $(this).children(".child-list").css("height",$(this).height()+"px");
    var winheight = $(window).height();
    var offsetTop = 0;
    if($(this).siblings(".show-slideout").length > 0)
    {
    	offsetTop = $(this).siblings(".show-slideout").offset().top;
    } else {
    	offsetTop = $(this).find(".show-slideout").offset().top;
    }
    
    if((winheight - offsetTop) < 200)
    {
      var height = $(this).height()-2;
      $(this).css("margin-top",-height+"px");
    }
    /*if(count > 15)
    {
      var child_height = 18;
      height = child_height*15;
      $(this).css("height",height+"px");
      $(this).children(".child-list").css("height","220px");
    }*/
  });
  $(".neighborhood-link").click(function() {
    var slideout_list = $(this).parents(".slideout-list-wrapper");
    $(".borough").removeClass("selected");
    slideout_list.parents(".borough").addClass("selected");
    slideout_list.hide();
    //$(".hoods h2").html($(this).html());
    if(window.map)
    {
    	map.autoPanTo(new OpenLayers.LonLat($(this).attr("data-x"),$(this).attr("data-y")));
    	map.hideBusinessPopup();
    } else {
    	$(".neighborhood").removeClass("selected");
    	$(this).parents(".neighborhood").addClass("selected");
    	cur_hood = $(this).attr("hood-id");
    	updatePostings();
    	return true;
    }
    
  });
  $("#all-hoods").click(function() {
  	cur_hood = 0;
  	$(".neighborhood, .borough").removeClass("selected");
  	$(this).parents(".borough").addClass("selected");
  	updatePostings();
  });
  /*$(".category:checked").each(function() {
  	if($(this))
  });*/ 
  $(".category").attr("checked",false);
  $("#all_stores").attr("checked",true);
 	setCategories();
}
function setCategories() {
	var url_vars = getUrlVars();
	
	if(url_vars.f) {
		/*var filters = f.split(",");
		for(int i = 0; i < filters.length; i++) {
			$("#cat-"+i).click();
		}*/
		$("#cat-"+url_vars.f).parent().click();
	}
}
function putMainCats(elem)
{
	var cat_id = elem.val();
	if(cat_id != cur_cat_id)
	{
		cur_cat_id = cat_id;
	} else {
		return;
	}
  clearCurCat(elem);
  elem.attr("checked",true);
  //$(this).siblings(".child-cats-list-wrapper").find(".child-cats").attr("checked",true);
  $(".child-cat-wrapper").removeClass("selected");
  $(".child-cats").attr("checked",false);
  $(".cats-list .cat-wrapper").removeClass("selected");
  elem.parents(".cat-wrapper").addClass("selected");
  //$(this).siblings(".cat-label").addClass("selected");
  cur_cat = elem;
  
  if(window.map)
  {
  	map.filterLogos(cur_cat_id);
  } else {
  	updatePostings();
  }
 
}

function clearCurCat(new_cat)
{
  if(cur_cat != null && cur_cat.val() != new_cat.val())
  {
    cur_cat.siblings(".child-cats-list-wrapper").find(".child-cats").attr("checked",false);
  }
}

function updatePostings()
{
	if(window.loadMorePosts)
	{
		$("#postings-inner").html("");
		post_offset = 0;
		no_more_postings = false;
		loadMorePosts();
	}
	
	/*$.ajax({
    url: "/posting/getPosts?type="+type+"&cat_id="+cur_cat_id+"&hood="+cur_hood,
    type: 'POST',
    success: function(data){
      $('#loading').hide();
      $('#postings').html(data);
    }
  });*/
}

var Filters = {
	filterJoin: '',
	filterWhere: '',
	category: 0,
	name: '',
	
	get: function(name) {
		if(name)
		{
			eval('this.'+name+'Filter()');
		} else {
			this.filterWhere = '1=1';
		}
		return {'join':this.filterJoin, 'where':this.filterWhere, 'category':this.category, 'name': this.name};	
	},
	
	opentableFilter: function() {
  	this.filterJoin = 'INNER JOIN external.open_table_restaurants o ON m.bid=o.bid';
  	this.filterWhere = 'm.category=1';
  	this.category = 1;
  	map.cur_cat_id = 1;
  	this.name = 'opentable';
  },
  
  starbucksFilter: function() {
  	this.filterJoin = "";
  	this.filterWhere = "m.category=1 AND b.name LIKE 'Starbucks%'";
  	this.category = 1;
  	map.cur_cat_id = 1;
  	this.name = 'starbucks';
  },
  
  noCategoryFilter: function() {
  	this.filterJoin = "LEFT JOIN business_category bc ON bc.bid=m.bid";
  	this.filterWhere = "m.category="+map.cur_cat_id+ " AND bc.cat_id IS NULL";
  },
  
  noContactFilter: function() {
  	this.filterJoin = "";
  	this.filterWhere = "m.category="+map.cur_cat_id+ " AND (b.address IS NULL OR b.address='' OR b.primary_phone IS NULL OR b.primary_phone='')";
  },
};

