var map;
var markersArray = [];
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();

function pad2(number) {
  return (number < 10 ? '0' : '') + number  
}

function prettyInterval(interval) {
  days = Math.floor(interval / 86400);
  hours = Math.floor((interval - (days * 86400)) / 3600);
  minutes = Math.floor((interval - (days * 86400) - (hours * 3600)) / 60);
  seconds = Math.floor((interval - (days * 86400) - (hours * 3600) - (minutes*60)));
 
  if(days > 0) {
    if(days == 1)
      return(days + ' day');
    else
      return(days + ' days');
  }
  else
    return(pad2(hours) + ':' + pad2(minutes) + ':' + pad2(seconds));
}

jQuery.extend(jQuery.expr[':'], {
    focus: function(element) { 
        return element == document.activeElement; 
    }
});

function centerFlashMessage() {
  var flashMargin = ($(window).width() - $("#flash").width()) / 2; 
  $("#flash").css({'left' : flashMargin+"px", 'top' : "10px"});
}

$(document).ready(function() {

	//Location drop down
	$("header#top-bar #location #change_location, #location_wrapper #closeLocation").click(function(){
	  $("#location_wrapper").slideToggle();
	});
		
	$("#market_wrap #market_selection").click(function(){
	  $("#market_wrap ul").slideToggle();
	});
	
//	$("#market_wrap ul li").click(function(){
//	  var el = $(this);
//	  if ( el.hasClass("active") ) {
//	    $("#market_wrap input#market_name").val(el.text());
//  	  $('#flash').remove();
//      $("#branding").after('<div id="flash"><div id="notice">Loading...</div></div>');
//      var flashMargin = ($(window).width() - $("#flash").width()) / 2; 
//      $("#flash").css({'left' : flashMargin+"px", 'top' : "10px"});
//  	  $("#market_wrap #market_selector").submit();
//	  }
//	});
	$("#market_wrap ul li").click(function() {
        $("#location_wrapper").slideToggle();
    });

  //activate moving boxes on home
  if ( $(".scrollable").length ) {
    $(".scrollable").scrollable({circular: true, speed: 1200}).autoscroll(12500);
  }		    
  
  //popups
  $(".popupLink").click(function(){
    $(".popup").clone().dialog({width: 500, position: ['center',120] });
    return false;
  });
  
  //reserved tabs
  $( "#tabs" ).tabs();
  $( "#offerTabs" ).tabs();
  
  $("#offerTabs ul li a").click(function(){
    var el = $(this);
    var offer_type = el.data("offer");
    
    if (offer_type === "All") {
      $(".mainOfferWrap article").show();
      $(".PledgeType").show(); //Show Pledge Banners
    } else  {
      $(".mainOfferWrap article").hide();
      $(".PledgeType").hide(); //Hide Pledge Banners
      $(".mainOfferWrap "+"."+offer_type).show();
    }
  });
    
  //extends textchange functionality to add to multiple objects  
  $.fn.text_count_down = function(options){    
    //extend defaults with new options
    var opts = $.extend({}, $.fn.text_count_down.defaults, options);
    
    return this.bind('textchange', function (event, previousText){
      var el = $(this);  
      //get vars or defaults
      var d = opts;
      var count_display = 'form span.charactersLeft.'+d.countdown_class;
      var text_length = d.max_length - parseInt($(this).val().length);
      
      if ( text_length < 0 ) {
        $(count_display).addClass('lengthError');
      } else if ( text_length > 0 ) {
        $(count_display).removeClass('lengthError');
      }
      $(count_display).html( text_length );
      
    });
  };
  
  $.fn.text_count_down.defaults = {
    max_length: 160,
    countdown_class: 'summary'
  };
    
  if ( $(".faq_helper").length ) {
    $.fn.scroll_with_page = function(options){
      //extend defaults with new options
      var opts = $.extend({}, $.fn.scroll_with_page.defaults, options);
      var el = $(this);
      var current_offset = el.offset();  //Inspired by http://thinkminimal.net/
      var d = opts;

      $(window).scroll(function() {
        if ($(window).scrollTop() > current_offset.top) {
          el.stop().animate({
            marginTop: $(window).scrollTop() - current_offset.top + d.top_padding    
          }, 1000);
        } else {
          el.stop().animate({  
            marginTop: d.top_margin_after_scroll
          });
        };
      });

    };

    $.fn.scroll_with_page.defaults = {
      top_padding: 80,
      top_margin_after_scroll: 20
    };
    
   $(".faq_helper").scroll_with_page();
  }
  
  //Countdown
  // $('#seattle_countdown').countdown({
  //   until: $.countdown.UTCDate(-8, 2011, 3 - 1, 29, 8, 0, 0, 0),
  //   significant: 4,
  //     labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Mins', 'Secs'],
  //     compactLabels: ['y', 'monts', 'weeks', ' days', 'hrs', 'mins', 'secs'], // The compact texts for the counters
  //     compact: true,
  //     layout: '<b>{hn}</b> {hl} to launch'
  // });
  
  // New Share ===========================================
  
  $("a.share_options").click(function(){
    var el = $(this);
    $(".share_methods").hide();
    if ( el.data("loc") === "" ) {
      el.parents(".info-wrap").find(".share_methods").show();
    } else {
      el.parents(".vcard").find(".share_methods").show();
    }
    return false;
  });
  
  $(".share_methods a.close_share").click(function(){
    var el = $(this);
    el.parent().hide();
    return false;    
  });
          
  // ============== Replace Supported Orgs =================================
  $("li a.replaceSupportedOrg").live('click', function(){
    $(".modal").remove();
    $('#flash').remove();
		$(".content").prepend("<div class='modal' title='Replace a Supported Organization'></div>");
    $("#branding").after('<div id="flash"><div id="notice">Loading...</div></div>');
      centerFlashMessage();
      return false;
  });
    
  // ============== Reserve Coupon =================================
  $(".previewView .redeem_coupon a").live('ajax:beforeSend', function(){
    var el = $(this);
    $('#flash').remove();
    $("#branding").after('<div id="flash"><div id="notice">Loading...</div></div>');
      centerFlashMessage();
  });
  
  // close dialog
  $(".previewView a.dialog_close").live('click', function(){
    $(".previewView").dialog( "close" );
  });

  $(".previewView a.close").live('click', function(){
    $(".previewView").dialog( "close" );
    return false;
  });
      
  //autosearch cities for targeting
  var city_cache = {};
    
  $('form input[type=text].autocomplete_cities').live('focus', function(){
    var el = $(this);
    var parent = el.parent();
    el.autocomplete({
      minLength: 3,
      delay: 500,
      source: function(request, response) {
        if ( request.term in city_cache ) {
  				response( city_cache[ request.term ] );
  				return;
  			}
        $.ajax({
          url: "/autocomplete_cities",
          dataType: "json",
          data: {term: request.term},
          success: function( data ) {
    				city_cache[ request.term ] = data;
  					response( data );
          }
        });
      },
      select: function(event, ui){
  		  parent.find("input[type=hidden]#city_id").val(ui.item.id);
        el.val(ui.item.value);
  		}    	     
    });
  });
  
  function clear_zips() {
    $(".filter input#location").val("");
  }
  function clear_city() {
    $(".filter input[type=hidden]#city_id").val("");
    $(".filter input.autocomplete_cities").val("");    
  }
  
  //hide show search types
  if ( $(".filter ul").length ) {    
    if ( $("#search_location_type_zipcode").is(":checked") ) {
      $(".filter .zipSearch").show();
      $(".filter .citySearch").hide();
      $(".filter .stateSearch").hide();
      $(".filter .marketSearch").hide();
      clear_city();
    } else if ( $("#search_location_type_city").is(":checked") ) {
      $(".filter .zipSearch").hide();
      $(".filter .stateSearch").hide();      
      $(".filter .citySearch").show();
      $(".filter .marketSearch").hide();
      clear_zips();            
    } else if ( $("#search_location_type_state").is(":checked") ) { 
      $(".filter .zipSearch").hide();
      $(".filter .citySearch").hide();
      $(".filter .stateSearch").show();
      $(".filter .marketSearch").hide();                    
      clear_zips();
      clear_city();
    } else if ( $("#search_location_type_market").is(":checked") ) { 
      $(".filter .zipSearch").hide();
      $(".filter .citySearch").hide();
      $(".filter .stateSearch").hide();
      $(".filter .marketSearch").show();                    
      clear_zips();
      clear_city();  
    } else {
      $(".filter .zipSearch").hide();      
      $(".filter .citySearch").hide();
      $(".filter .stateSearch").hide();
      $(".filter .marketSearch").hide();      
      clear_zips();
      clear_city();
    }
    
    $(".filter input[name='search_location_type']").live('click',function(){
      if ( $("#search_location_type_zipcode").is(":checked") ) {
        $(".filter .zipSearch").show();
        $(".filter .citySearch").hide();
        $(".filter .stateSearch").hide();
        $(".filter .marketSearch").hide();        
        clear_city();
      } else if ( $("#search_location_type_city").is(":checked") ) {
        $(".filter .zipSearch").hide();
        $(".filter .stateSearch").hide();      
        $(".filter .citySearch").show();
        $(".filter .marketSearch").hide();
        clear_zips();        
      } else if ( $("#search_location_type_state").is(":checked") ) { 
        $(".filter .zipSearch").hide();
        $(".filter .citySearch").hide();
        $(".filter .stateSearch").show();                    
        $(".filter .marketSearch").hide();        
        clear_zips();
        clear_city();
      } else if ( $("#search_location_type_market").is(":checked") ) { 
        $(".filter .zipSearch").hide();
        $(".filter .citySearch").hide();
        $(".filter .stateSearch").hide();
        $(".filter .marketSearch").show();                    
        clear_zips();
        clear_city();  
      } else {
        $(".filter .zipSearch").hide();
        $(".filter .marketSearch").hide();              
        $(".filter .citySearch").hide();
        $(".filter .stateSearch").hide();           
        clear_zips();
        clear_city();
      }
    });
  }  
  
  if ($("#yelper").length) {
    $("#yelper").click(function(){
      var el = $(this);
      var holder = $("#YelpFeedTab");
      var path = holder.data("path");
      if (!holder.find(".yelp_reviews .yelp_review").length) {
        $.get(path);
      }
    });
  }
  
  //
  // Organization Autocompletion
  //

  var cache = {}, lastXhr, context, originalValue, originalContent,
      valueElement, searchElement;

  $('.organization-input-edit').live('click', function() {
    context = $(this).closest('.organization-input');
    originalValue = context.find('input.organization-input-id').val();
    originalContent = context.html();
    context.html(
      '<div class="organization-name-input-search-text">Search for an Organization</div>' +
      '<input type="hidden" class="organization-input-id">' +
      '<input type="text" class="organization-input-search">' +
      '<div class="organization-input-links">' +
      '<span class="organization-input-cancel">Cancel</span>' +
      '</div>'
    );

    valueElement = context.find('input.organization-input-id');
    valueElement.val(originalValue);

    searchElement = context.find('input.organization-input-search');
    searchElement.blur(function() {
        context.html(originalContent);
    });
    
    searchElement.keydown(function(event) {
      if (event.keyCode == 13) {
        context.blur();
        context.find('.organization-input-name').html('None Selected');
        context.find('input.organization-input-id').val('');
        context.find('.organization-input-location').html('');
      }
    });

    searchElement.focus().autocomplete({
    		minLength: 0,
    		source: function( request, response ) {
    						var term = request.term;
    						if ( term in cache ) {
    							response( cache[ term ] );
    							return;
    						}

    						lastXhr = $.getJSON( "/organizations/autocomplete_search", request, function( data, status, xhr ) {
    							cache[ term ] = data;
    							if ( xhr === lastXhr ) {
    								response( data );
    							}
    						});
    					},
    		focus: function(event, ui) {
    			context.find('.organization-input-search').val(ui.item.label);
    			return false;
    		},
    		select: function(event, ui) {  
          context.blur();
          context.find('.organization-input-name').html(ui.item.label);
          context.find('input.organization-input-id').val(ui.item.value);
          context.find('.organization-input-location').html(ui.item.description);
    			return false;
    		}
    	}).data('autocomplete')._renderItem = function(ul, item) {
    		return $('<li></li>')
    			.data('item.autocomplete', item)
    			.append('<a><span>' + item.label + '</span>' + item.description + '</a>')
    			.appendTo(ul);
    	};
  });
  $('.organization-input-delete').live('click', function() {
    context = $(this).closest('.organization-input');
    context.find('.organization-input-name').html('None Selected');
    context.find('input.organization-input-id').val('');
    context.find('.organization-input-location').html('');
    return false;
  });
	
});

