var zoom_drag = false;

$(document).ready(function() {
	if(map.searchResults != null && map.searchResults.length > 0)
	{
		map.putSearchResults();
	}
  $(".claim-store").click(function(e) {
		var claim_html = 'To claim your business, follow the following steps:<br><ol><li>Find your business on the map and click it</li>'
		+'<li>On the popup, click the “more info” link</li>'
		+'<li>From the Business Profile page, click the “Claim Your Store” button</li>'
		+'<li>Follow the on-screen instructions</li>'
		+'<li>To remove your logos from the map, send an email to <a href="mailto:logos@citymaps.com">logos@citymaps.com</a></li>';
		
		alert(claim_html, 'Instructions for Claiming Your Business',435);
	});
  $(".update-filter").click(OpenLayers.Function.bind(map.getUpdates,map));
  if(map.iframe)
  {
    $("#filter-bar").remove();
  } else {
    $("a#search-icon").click(OpenLayers.Function.bind(function(e) {
    	map.doSearch();
    },map));
    
  }
 
  //$("#all_stores").attr("checked",true);
  /*$(".cat-wrapper").click(function() {
  	$(this).children("input").attr("checked",true);
  	if(window.map)
  	{
  		map.filterLogos();
  		map.hideBusinessPopup();
  		return false;
  	} else 	{
  		return true;
  	}
  });*/
  /*$(".child-cat-wrapper").live('click',function() {
  	var wrapper = $(this).parents(".child-cats-list-wrapper");
  	var 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();
  		$.ajax({
  			url: '/map/getCategoryResults?cat_id='+cat_id+'&city='+map.city+"&main_cat="+main_cat+"&cx="+center.lon+"&cy="+center.lat,
  			dataType: 'json',
  			async: true,
  			success: OpenLayers.Function.bind(map.searchCallback,map)
  		});
  		map.filterLogos(main_cat);
  		map.hideBusinessPopup();
  		
  		return false;
  	} else 	{
  		return true;
  	}
  });*/
  
  $("#map_link_button").click(function() {
    $("#map_link").val(map.getMapLink());
    $("#embed_link").val(map.getMapEmbed());
    $("#link_popup").dialog({modal: true, resizable: false, movable: false});
  });
  $("#map_link").click(function() { $(this).select() });
  $("#embed_link").click(function() { $(this).select() });
  $("#map_email_button").click(function() {
    var map_link = map.getMapLink();
    $("#suggest-link").html(map_link).attr("href",map_link);
    $("#link_url").val(map_link);
    $("#link_text").val(map_link);
    $("#email_popup").dialog({
    	modal: true, 
    	width: 700, 
    	resizable: false, 
    	movable: false, 
    	close: function() {
    		$("#suggest-form").clearForm();
    	}
    });
  });
  $(".link_textbox").click(function(){
    $(this).select();
  });
  
  $("#map_print_button").click(function() {
    var link = map.getMapLink(null,null,null,null,true);
    
    window.open(link);
  });
  
  /*$(".cats-header").click(function() {
    if($(".hoods").css("display") == "block")
    {
      $(".hoods").hide('blind');
      $(".cats").show('blind');
      $(".hoods-header").removeClass("visible");
      $(this).addClass("visible"); 
    }
  });
  $(".hoods-header").click(function() {
    if($(".cats").css("display") == "block")
    {
      $(".cats").hide('blind');
      $(".hoods").show('blind');
      $(".cats-header").removeClass("visible");
      $(this).addClass("visible"); 
    }
  });*/
  $(".zoom-link").click(function() {
    if(map.edit_mode)
    {
      return;
    }
    var id = $(this).attr("id");
    var zoom = map.getZoom();
    if(id == 'zoom-in')
    {
      if(zoom < map.numZoomLevels - 1)
      {
        zoom = zoom+1;
      }
    } else if(id == 'zoom-out') {
      if(zoom > 0)
      {
        zoom = zoom-1;
      }
    } else {
      zoom = $(this).attr("data-zoom");
    }
    map.zoomTo(zoom);
    map.setZoomDash();
  });
  $("#zoomdash").mousedown(function(e) {
    e.preventDefault();
    zoom_drag = true;
  });
  $(".zoombar, #map-container").mouseup(function(e) {
    e.preventDefault();
    if(zoom_drag)
    {
      zoom_drag = false;
      map.setNearestZoom();
    }
  });
  $(".zoombar").mousemove(function(e) {
    e.preventDefault();
    if(zoom_drag)
    {
      var offset = $(this).offset();
      var layerY = e.pageY - offset.top;
      var top = (layerY - $(this).height()) + 15;
      if(top >= -123 && top <= -15)
        $("#zoomdash").css("margin-top",top+"px");
    }
  });
  
  $(".toggle-filters").live('click',function() {
  	var show = $("#filter-bar-outer").css("display") == "none";
  	toggleFilters(show);
  });
  $(".show_search_result").live('click',function() {
    map.showBusinessPopup($(this).attr("data-bid"));
  });
  $("#business_popup_delete").live('click',function() {
    confirm("Are you sure you want to delete this business?<br/>THIS IS PERMANENT AND CANNOT BE REVERSED.", function() {
      var form = $("#business_popup_delete").parents("form");
      form.ajaxSubmit({
        data: {op: 'delete'},
        success: function() {
          $("#edge_popup").dialog("close");
          map.logosVector.removeFeatures([map.selectedFeature]);
          map.markersLayer.clearMarkers();
        }
      });
      $(this).dialog("close");
    });
  });
  $("#user-location-input").keyup(function(e) {
  	if(e.keyCode == 13)
    {
      $("#save-user-location").click();
    }
  });
  $("#save-user-location").live('click',function() {
    var location = $("#user-location-input").val();
    if(location == "")
    {
      $("#user-location-error").html("Please enter a location.").show();
      return;
    }
    $(this).siblings(".loader").show();
    $.ajax({
      url: '/map/setUserLocation',
      data: "location="+location+"&city="+map.city,
      dataType: 'json',
      type: 'post',
      success: function(data) {
        if(data.found)
        {
          $("#user-location-error").hide();
          $("#user-location-text").html(data.location);
          $("#user-location").show();
          $("#enter-location").hide();
          var date = new Date();
          date.setTime(date.getTime() + (180 * 24 * 60 * 60 * 1000));
          $.cookie('default_location_'+map.city,data.location,{expires: date});
          $.cookie('default_x_'+map.city,data.point.x,{expires: date});
          $.cookie('default_y_'+map.city,data.point.y,{expires: date});
          $("#go-to-location").attr("data-x",data.point.x).attr("data-y",data.point.y);
          map.autoPanTo(new OpenLayers.LonLat(data.point.x,data.point.y));
        } else {
          $("#user-location-error").html("This location could not be found in your city").show();
        }
      }
    });
  });
  $("#go-to-location").click(function() {
    var x = $(this).attr("data-x");
    var y = $(this).attr("data-y");
    map.autoPanTo(new OpenLayers.LonLat(x,y));
  });
  $("#change-user-location").live('click',function() {
    $("#user-location").hide();
    $("#set-location").hide();
    $("#enter-location").show();
    $("#cancel-enter-location").show();
  });
  $("#cancel-enter-location").click(function() {
    $("#enter-location").hide();
    if($("#user-location-text").html() != '')
    {
      $("#user-location").show();
    } else {
      $("#set-location").show();
    }
    
  });
  $("#xy_search").click(function() {
    var x = $("#x").val();
    var y = $("#y").val();
    map.autoPanTo(new OpenLayers.LonLat(x,y));
  });
  $(".clear-results").live('click',function() {
  	$(".clear-results").hide();
    map.clearSearchResults();
  });
  $(".subway-toggle").click(function() {
    var layer = map.getLayersByName("subways");
    layer[0].extent = map.getExtent();
    var markers = map.getLayersByName("subway_stops");
    if($(this).hasClass("mapnavright")) {
      $(this).removeClass("mapnavright");
      $(this).addClass("mapnavrighta");
      map.reloadLayer(layer[0]);
      //layer[0].redraw();
      markers[0].setVisibility(true);
      markers[0].div.style.zIndex = 2002;
    } else {
      $(this).removeClass("mapnavrighta");
      $(this).addClass("mapnavright");
      layer[0].setVisibility(false);
			markers[0].setVisibility(false);
    }
  });
  $(".parking-toggle").click(function() {
    var layer = map.getLayersByName("parking");
    layer[0].extent = map.getExtent();
    if($(this).hasClass("mapnavleft")) {
      $(this).removeClass("mapnavleft");
      $(this).addClass("mapnavlefta");
      map.reloadLayer(layer[0]);
    } else {
      $(this).removeClass("mapnavlefta");
      $(this).addClass("mapnavleft");
      layer[0].setVisibility(false);
    }
  });
  $(".deals-toggle").click(function() {
    if($(this).hasClass("mapnavright2")) {
      $(this).removeClass("mapnavright2");
      $(this).addClass("mapnavright2a");
    } else {
      $(this).removeClass("mapnavright2a");
      $(this).addClass("mapnavright2");
    }
    map.filterMarkers();
  });
  $(".announcments-toggle").click(function() {
    if($(this).hasClass("mapnavleft2")) {
      $(this).removeClass("mapnavleft2");
      $(this).addClass("mapnavleft2a");
    } else {
      $(this).removeClass("mapnavleft2a");
      $(this).addClass("mapnavleft2");
    }
    map.filterMarkers();
  });
  /*if(map.getZoom() > 2)
  {
    $(".parking-toggle").click();
  }*/
  var sidebar_height = $(window).height() - 102;
  $("#filter-bar").css("height",sidebar_height);
  //$("#"+map.markersLayer.div.id).css("z-index","1000");
  /*$("path").click(function() {
    alert($(this).attr("bid"));
  });
  $("path").each(function() {
    alert($(this).attr("bid"));
  });*/
  
  $(".test").live('click',function() {alert("test");})
  $("#business_popup_cancel").live('click',function() {
	  $("#edge_popup").dialog("close");
	});
	$(".business-field-name textarea").live('blur',function() {
		var id = $(this).attr("id");
		id = id.replace("name","label");
		var elem = $("#"+id);
		if(elem.val() == '')
		{
			$("#"+id).val($(this).val());
		}
	});
	$(".move_up").live('click',moveUp);
	$(".move_down").live('click',moveDown);
	$(".delete_row").live('click',function() {
		var row_id = $(this).attr("row-id");
		var bid = $("#businesses_"+row_id+"_bid").val();
		$("#row"+row_id).remove();
		if(bid)
		{
			var cur_value = $("#deleted").val();
			$("#deleted").val(cur_value+bid+",");
		}
		
	});	
	$("#embed_zoom, #embed_parking, #embed_subway").click(function() {
		$("#embed_link").val(map.getMapEmbed());
	});
	$(".embed-text").keyup(function() {
		$("#embed_link").val(map.getMapEmbed());
	});
	$(".change-city-link").each(function() {
		var city = $.cookie('city');
		if($(this).hasClass("current") && city != $(this).attr("data-slug")) {
			$(this).removeClass("current");
		} else if(!$(this).hasClass("current") && city == $(this).attr("data-slug")) {
			$(this).addClass("current");
		}
	});
});
function toggleStoreFavoriteMap() {
  var favorite = $(".toggle-store-favorite").attr("favorite");
  var query = "favorite="+favorite;
  if(favorite == 'true')
  {
    query += "&usid="+$(".toggle-store-favorite").attr("usid");
  } else {
    query += "&bid="+$(".toggle-store-favorite").attr("bid");
  }
  $.ajax({
    url: '/profile/toggle_favorite',
    data: query,
    dataType: 'json',
    type: 'POST',
    success: function(data) {
      if(data.favorite)
      {
        $(".toggle-store-favorite").val("Remove Spot")
			 .attr("usid",data.usid)
			 .attr("favorite","true")
			 .html('<img src="/images/button_removespot.png" width="63" height="15" alt="Remove Spot" />');
        													 
      	
      } else {
        $(".toggle-store-favorite").val("Add Spot")
			  .attr("bid",data.bid)
				.attr("favorite","false")
			  .html('<img src="/images/button_addspot.png" width="59" height="15" alt="Add Spot" />');
      }
    }
  });
}

function initBusinessPopupFormSubmits()
{
  $("#create_business_form_add").click(function() {
    var form = $(this).parents("form");
    form.ajaxSubmit({
      iframe: false,
      data: {op: 'add_another_item'},
      target: '#create_business_form_table'
    });
    return false;
  });
  $("#create_business_add").click(function() {
    var form = $(this).parents("form");
    $(this).attr("disabled","disabled");
    $("#create_business_loader").show();
    form.ajaxSubmit({
      iframe: true,
      data: {op: 'save'},
      dataType: 'json',
      success: function(data) {
      	$("#create_business_loader").show();
        if(data.single)
        {
          if(data.data)
          {
            map.refreshSelectedFeature(data.data);
          } else {
            map.removeSelectedFeature();
          }
        } else {
          map.refreshScreen();
        }
        map.setSaveTimeout();
        $("#edge_popup").dialog('close');
      }
    });
    return false;
  });
}
  
function distance(p1, p2)
{
  return Math.sqrt(((p2.lon-p1.lon)*(p2.lon-p1.lon))+((p2.lat-p1.lat)*(p2.lon-p1.lat)));
}

function adjustSlideoutForScrollbars()
{
	if(!map.iframe) {
	  var elem = document.getElementById("filter-bar");
	  if(elem.clientHeight < elem.scrollHeight)
	  {
	    $(".slideout-list-wrapper").css("margin-left","194px");
	  } else {
	    $(".slideout-list-wrapper").css("margin-left","211px");
	  }
  }
}
function moveDown()
{
	var id = parseInt($(this).attr("row-id"));
	var max = $("#create_business_form_table tr").length;

	if(id + 1 < max)
	{
		var this_row = $(this).parents("tr");
		var next_id = id+1;
		var next = $("#row"+(next_id));
		var tmp = next.html();
		next.html(this_row.html());
		this_row.html(tmp);
		
		//this_row.attr("id","row"+next_id);
		this_row.find(".row-number").html(id+1);
		this_row.find(".move_up").attr("row-id",id);
		this_row.find(".move_down").attr("row-id",id);
		
		//next.attr("id","row"+id);
		next.find(".row-number").html(next_id+1);
		next.find(".move_up").attr("row-id",next_id);
		next.find(".move_down").attr("row-id",next_id);
		
		//window.location.href = "#row-link-"+next_id;
	}
}
function moveUp()
{
	var id = parseInt($(this).attr("row-id"));
	if(id - 1 >= 0)
	{
		var this_row = $(this).parents("tr");
		var next_id = id-1;
		var next = $("#row"+(next_id));
		var tmp = next.html();
		next.html(this_row.html());
		this_row.html(tmp);
		
		//this_row.attr("id","row"+next_id);
		this_row.find(".row-number").html(id+1);
		this_row.find(".move_up").attr("row-id",id);
		this_row.find(".move_down").attr("row-id",id);
		
		//next.attr("id","row"+id);
		next.find(".row-number").html(next_id+1);
		next.find(".move_up").attr("row-id",next_id);
		next.find(".move_down").attr("row-id",next_id);
		
		//window.location.href = "#row-link-"+next_id;
	}
}
function toggleFilters(show) {
    if(show)
    {
      $("#filter-bar-outer").show('slide', {direction: 'left'});
      $("#show_filters").hide('slide');
      $(".zoombar").animate({"left": "+=210px"});
      $(".olControlPanPanel").animate({"left": "+=210px"});
      //$(".sidebar-right").css("margin-left","200px");
      map.resizeToScreen();
      map.paddingForPopups.left = 300;
    } else {
      map.resizeToScreen(true);
      $("#show_filters").show('slide', {direction: 'right'});
      $(".zoombar").animate({"left": "-=210px"});
      $(".olControlPanPanel").animate({"left": "-=210px"});
      $("#filter-bar-outer").hide('slide');
      map.paddingForPopups.left = 100;
      
      
      //$(".sidebar-right").css("margin-left","0");
    }
    
  }
