$(document).ready(function() {
    
  jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
		return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);  
	};
	
	jQuery.fn.slideToggle = function(speed, easing, callback) {
		return this.animate({height: 'toggle'}, speed, easing, callback);  
	};
    
  $("a.stbutton, .stbuttontext").css('padding', 0);
  $("li.more a.stbutton").css('padding', "8px");
  
  //center Sunbusrt on load
  function centerSunburst(){
    var offset = $("#logo").offset();
    var sunburstMargin = (offset.left - 240);
    if ( $("#partner-bar").length ) {
      $('body').css({'backgroundPosition' : sunburstMargin+"px"+" 100px"});
      $('html').css({'backgroundPosition' : "0"+" 120px"});
    } else {
      $('body').css({'backgroundPosition' : sunburstMargin+"px"+" 40px"});
      $('html').css({'backgroundPosition' : "0"+" 40px"});
    }

  }
  
  $('#flash #notice, #flash #loading, #flash #alert').live('click', function(){
    $(this).fadeOut("fast");
    return false;
  });
  
  $("header#top-bar #login_options, header#branding #login_wrapper #closeLogin").click(function(){
	  $("#login_wrapper").slideToggle();
	  if ( $("#signup_wrapper").is(":visible") ) {
	    $("#signup_wrapper").hide();
	  }
	});
	
	$("header#top-bar #signup_options, header#branding #signup_wrapper #closeSignup").click(function(){
	  $("#signup_wrapper").slideToggle();
	  if ( $("#login_wrapper").is(":visible") ) {
	    $("#login_wrapper").hide();
	  }
	});
    
  //accordion functions
  
  function addErrorClassToAccordion() {
    var ui_parent = $("span.error_message").parent().parent().parent();
    var ui_parent_header = ui_parent.prev("h3.ui-accordion-header");
    ui_parent_header.addClass("containsErrors");
    $("<em title='This section contains errors'>Edit this Section to fix errors</em>").appendTo(ui_parent_header);
  }
    
  centerSunburst();
  
  //center sunburst logo on resize
  $(window).resize(function(){
    centerSunburst();
  });
  
  if ( $("#toggle_locs").length ) {
    $("#toggle_locs").click(function(){
      var el = $(this);
      if ( $(".additional").is(":hidden") ) {
        $(".additional").slideToggle();
        el.text("Hide Additional Locations");      
        el.attr("title", "Hide Additional Locations");
      } else {
        $(".additional").slideToggle();
        el.text("View Additional Locations");
        el.attr("title", "View Additional Locations");
      }
      return false;
    });
  }
  
  //setup Tool Tips
  $("div#primaryFeaturedCoupon ul li span, ul#index-views li a,article .myOffer, form.redeemForm input[type='submit'], ul.org-actions li span, .follow-up-coupon-available, a.button, a.browse, a.favorite, a.print, a.more, a.give-kudos, ul.couponInfo li, .stbutton, .listing .entry-content ul li, .ui-accordion-header.containsErrors em, .ui-accordion-header.ui-state-active.containsErrors em, span.reserved-coupon, a.replaceSupportedOrg").tipTip({
    defaultPosition: "top"
  });
  
  //set ul dimension.multi height
  $("ul.dimension.multi").each( function() {
    if ( $(this).height() > 200 ) {
      $(this).height(200);
    } 
  });
	
	$('.fade').live("click", function() {
		var link_id = $(this).attr('rel');
		$('#'+link_id).slideFadeToggle('fast');
		return false;
	});
	
	$('.fader').live("click", function() {
		var link_id = $(this).data('sibling');
		$('#'+link_id).slideFadeToggle('fast');
		return false;
	});
	
	$('.fadeSibling').live("click", function() {
	  var el           = $(this);
		var link_class   = el.data('sibling');
		var parent       = el.parents(".prize, .featured_prize");
		var instructions = parent.find('.'+link_class);
    instructions.slideFadeToggle();
		return false;
	});
	
	if ( $(".required").length ) {
	  $(".required").append("<span class=\"star\"> *</span>");
	}
	
	//dashboard progress bar
	if ($("#profile-progressbar").length) {
	  var profile_percentage = parseInt( $("#profile-progressbar").attr("data-profile") );
  	$("#profile-progressbar").progressbar({value: profile_percentage});
	}

	//accordion forms
	if ( $(".ui-accordion-content span.error_message").length ) {
  
	  $("#accordionForm").accordion({
  	  collapsible: true,
  	  autoHeight: false,
  	  change: function(event, ui) { 
  	    addErrorClassToAccordion();
  	  },
  	  active: false    
  	});
    addErrorClassToAccordion();
	  
	} else if ( $("#accordionForm").length ) {
	  $("#accordionForm").accordion({
  	  collapsible: true,
  	  autoHeight: false    
  	});
	}
		
	//accordion next / previous buttons
	
	$('#accordionForm a.next').each(function (index, elm) {
    if ( ($("#accordionForm div.ui-accordion-content").length - 1) === index ) {
      $(elm).hide();
    } else {
      $(elm).click(function() {
          $('#accordionForm').accordion('activate', index + 1);
          return false;
      }); 
    }
  });
  
  $('#accordionForm a.previous').each(function (index, elm) {
    if ( index === 0 ) {
      $(elm).hide();
    } else {
      $(elm).click(function() {
          $('#accordionForm').accordion('activate', index - 1);
          return false;
      });
    }
  });
  	
	if ( $("form li span.hint, form p span.hint").length ) {
    $("form li, form p").bind("mouseenter mouseleave", function(event){
   	  if (event.type == 'mouseenter') {
   	    $(this).find("span.hint").css('display', 'block');
   	  } else {
   	    $(this).find("span.hint").hide();
   	  }
     });
  }
  
  //center and fade flash messages
  function centerFlashMessageAndFade() {
    var flashMargin = ($(window).width() - $("#flash").width()) / 2; 
    $("#flash").css({'left' : flashMargin+"px", 'top' : "10px"});
    $("#flash").delay(8000).fadeOut('slow', function() {$(this).remove();});
  }
  
  function centerFlashMessage() {
    var flashMargin = ($(window).width() - $("#flash").width()) / 2; 
    $("#flash").css({'left' : flashMargin+"px", 'top' : "10px"});
  }
  
  centerFlashMessageAndFade();
  
  // ===================== Ajax Setup =========================
  
  // http://brandonaaron.net/blog/2009/02/24/jquery-rails-and-ajax
	// Always send the authenticity_token with ajax
	$(document).ajaxSend(function(event, request, settings) {
	    if ( settings.type == 'post' || settings.type == 'put' || settings.type == 'delete'  ) {
	        settings.data = (settings.data ? settings.data + "&" : "")
	                + "authenticity_token=" + encodeURIComponent( $('meta[name=csrf-token]').attr('content') );
	        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	    }
	});
	
	// When I say html I really mean script for rails
	$.ajaxSettings.accepts.html = $.ajaxSettings.accepts.script;
		
	$.ajaxSetup({ 
	  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
	});
	
	jQuery.fn.sendPostWithAjax = function() {	  
	  this.click(function() {
      $.post($(this).attr("href"), $(this).serialize(), null, "script");
      // return false;
	  });
	  return this;
	};
	
	jQuery.fn.submitPostWithAjax = function() {
	  this.unbind('submit', false);
	  this.submit(function() {
		  $.post(this.action, $(this).serialize(), null, "script");
	    return false;
	  });
	  return this;
	};
		
	jQuery.fn.getWithAjax = function() {
	  this.unbind('click', false);
	  this.click(function() {
	    $.get($(this).attr("href"), $(this).serialize(), null, "script");
	    return false;
	  });
	  return this;
	};
	
	// ============== Feedback =================================
  $(".feedback_tab").live('click', function(){
    $(".modal").remove();
    $('#flash').remove();
		$(".content").prepend("<div class='modal' title='Share Your Idea'></div>");
    $("#branding").after('<div id="flash"><div id="notice">Loading...</div></div>');
      centerFlashMessage();
      $.get($(this).attr("href"), { page: window.location.href }, null, "script");
      return false;
  });
  
  $('.give_feedback p span').live('click', function(){
    var el = $(this);
    var daddy = $(this);
    
    $('.give_feedback p span').removeClass("active_feedback");
    el.addClass("active_feedback");
    $('.ui-dialog-title').text("Share Your "+el.text());
    $('label[for="feedback_body"]').text(el.attr('title'));
    $("#feedback_type").val(el.text());
    
  });
  
  //=============== Select Link ===============================
  
  $("input:text.referer_link, td.code textarea").focus(function(){
    $(this).select();
  });
    	
  // ============== Preview Coupon for Approval ===============
  
  $("a.preview_coupon").live('ajax:beforeSend', function(event){
    $(".modal").remove();
    $('#flash').remove();
    $("#branding").after('<div id="flash"><div id="notice">Loading...</div></div>');
		$(".content").prepend("<div class='modal' title='Coupon Preview'></div>");
    centerFlashMessage();
  });

  // ============== Remove Coupon ===============
  
  $("a.remove_coupon").live('ajax:beforeSend', function(event){
    $(".modal").remove();
    $('#flash').remove();
    $("#branding").after('<div id="flash"><div id="notice">Loading...</div></div>');
    centerFlashMessage();
  });


  // ============== Share Offer ===============
  
  $("a.share-email").live('ajax:beforeSend', function(event){
    $(".modal").remove();
    $('#flash').remove();
    $("#branding").after('<div id="flash"><div id="notice">Loading...</div></div>');
		$(".content").prepend("<div class='modal' title='Share Offer'></div>");
    centerFlashMessage();
  });
  
  $("form.email_share").live('ajax:beforeSend', function(event){
    $('#flash').remove();
    $("#branding").after('<div id="flash"><div id="notice">Sending...</div></div>');
    centerFlashMessage();
  });
  
  // ============== Preview Coupon for Approval ===============
  
  $("form.redeemForm, a.remove_coupon, form.entryForm").live('ajax:beforeSend', function(event){
    $(".modal").remove();
    $('#flash').remove();
    $("#branding").after('<div id="flash"><div id="notice">Loading...</div></div>');
    centerFlashMessage();
  });
  
  // ============== View Coupon =================================
  $("a.view_coupon").live('ajax:beforeSend', function(){
    var el = $(this);
    $(".modal").remove();
    $(".previewView").remove();    
    $('#flash').remove();
    $(".content").prepend("<div class='previewView' title='Preview "+el.data("title")+"'></div>");
    $("#branding").after('<div id="flash"><div id="notice">Loading...</div></div>');
      centerFlashMessage();
  });
    
  // ============== Faux error ===============
  
  $(".faux-login-error").live('click', function(){
    $(".modal").remove();
    $('#flash').remove();
    $("#branding").after('<div id="flash"><div id="alert">You must be logged in to continue</div></div>');
    centerFlashMessageAndFade();
    return false;
  });
  
  $(".faux-kudos-error").live('click', function(){
    $(".modal").remove();
    $('#flash').remove();
    $("#branding").after('<div id="flash"><div id="alert">You must be logged in to give Kudos</div></div>');
    centerFlashMessageAndFade();
    return false;
  });
  
  
  // ============== Give Kudos ===============
  	
	$("a.give-kudos").live('ajax:beforeSend', function(event) {
	  $('#flash').remove();
	  $("#branding").after('<div id="flash"><div id="notice">Loading...</div></div>');
    centerFlashMessage();
	});
	
	// ============== Maps ===============
  
  if($('#map_canvas').length > 0) {
    var mapOptions = {
      zoom: 7,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    
    $('div.content .vcard').each(function() {
        var hcard = $(this);

        var streetaddress = hcard.find('.street-address').text();
        var locality = hcard.find('.locality').text();
        var region = hcard.find('.region').text();
        var postcode = hcard.find('.postal-code').text();

        if(postcode != '' && postcode != null) {
          geocoder.geocode({'address': [streetaddress, locality, region, postcode].join(', ')},
            function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                bounds.extend(results[0].geometry.location);
                map.fitBounds(bounds);
                map.setCenter(bounds.getCenter());
                var marker = new google.maps.Marker({
                    map: map, 
                    position: results[0].geometry.location
                });
              } else {
                // alert("Geocode was not successful for the following reason: " + status);
              }
          });
        }
    });     
  
    google.maps.event.addListener(map, 'zoom_changed', function() {
            zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
                if (this.getZoom() > 16) // Change max/min zoom here
                    this.setZoom(16);

                google.maps.event.removeListener(zoomChangeBoundsListener);
            });
    });
  }
  $("body#show .coupon.hentry .entry-image, body#dashboard .coupon.hentry .entry-image").hide();
  
  if ( $("form.payments .offer_quantity").length ) {
    
    $("li.offer_total .total_price em").text( parseInt($("form.payments li.offer_quantity select").val() * parseFloat($("li.offer_price .original_price em").text())) );
    $("input[id$='total']:hidden").val( parseInt($("form.payments li.offer_quantity select").val() * parseFloat($("li.offer_price .original_price em").text())) );
    
    
    $('form.payments li.offer_quantity select').change(function(){
      var el = $(this);
      var order_quantity = parseInt(el.val());
      var base_price = parseFloat($("li.offer_price .original_price em").text());
      var new_total = parseFloat(order_quantity * base_price);
      $("li.offer_total .total_price em").text(new_total);
      $("input[id$='total']:hidden").val(new_total);
    });
  }
  
  $("a.target_blank").attr("target", "_blank");
  
  if ( $(".chzn").length ) {
    $(".chzn").chosen();
    $(".chzn deselect").chosen({allow_single_deselect:true});
  }
    
});

$(window).load(function(){
  //center coupon image
  if ( $("body#show .coupon.hentry .entry-image").width() < 620 ) {
    var width_offset = (620 - $("body#show .coupon.hentry .entry-image").width()) / 2;
    $("body#show .coupon.hentry .entry-image").css({'left' : width_offset+"px", "position" : "absolute"});
  }
  //center coupon image
  if ( $("body#dashboard .coupon.hentry .entry-image").width() < 620 ) {
    var width_offset = (620 - $("body#dashboard .coupon.hentry .entry-image").width()) / 2;
    $("body#dashboard .coupon.hentry .entry-image").css({'left' : width_offset+"px", "position" : "absolute"});
  }
  $("body#dashboard .coupon.hentry .entry-image, body#show .coupon.hentry .entry-image").fadeIn();
});

