$( function () {
  
  // Site Switcher
  currentSite = $('#location a#current-site').click(function() {
    $('#location #site-switcher').show();
    return false;
  });
  
  $('body').click(function() { $('#location #site-switcher').hide(); });

  $.cookie('site_key', null, { path: window.location.pathname });
  
  $('#site-switcher a').click(function (event) {
    event.preventDefault();
    var url = window.location.toString();
    var siteKey = $.trim($(this).text()).toLowerCase();

    if (url.toLowerCase().match('couponengine')) {
      $.cookie('site_key', null);
      $.cookie('site_key', null, { path: '/' });
      
      $.cookie('site_key', siteKey, { path: '/' });
      window.location = url;
    } else {
      window.location = url.replace(currentSite.attr('href'), $(this).attr('href'));
    }
  });
  
  // Fancybox
  function hideFancyLoading() {
    $(".fancy_loading").hide();
  }
  
  function showFancyLoading() {
    $.fn.fancybox.showLoading();
  }
  
  $('.newsletter-preview').fancybox({ 
    frameWidth: 760, 
    frameHeight: 500, 
    hideOnContentClick: false,
    callbackOnStart: showFancyLoading,
    callbackOnShow: hideFancyLoading
  });

  $('.newsletter-edit-message').fancybox({ 
    frameWidth: 745, 
    frameHeight: 480, 
    hideOnContentClick: false,
    callbackOnStart: showFancyLoading,
    callbackOnShow: function () {
      hideFancyLoading();
    } 
  });

  $('.newsletter-select-coupons').fancybox({ 
      frameWidth: 860, 
      frameHeight: 540, 
      hideOnContentClick: false,
      callbackOnStart: showFancyLoading,
      callbackOnShow: function () {
        hideFancyLoading();
        
        $('#store-list a').click( function (event) {
          event.preventDefault();
          $('#coupon-listing-title').html($(this).text() + ' Coupons');
          showFancyLoading();
          $('#coupon-listing').load( $(this).attr('href'), hideFancyLoading );
        });
        
        $('#remove-all-selected-coupons').live('click', function (event) {
          $('#selected-coupon-listing').load($(this).attr('href'), hideFancyLoading );
          event.preventDefault();
          showFancyLoading();
          $('input[type=checkbox]:checked').attr('checked', false);
        });
      
        $('#coupon-selecting input[type=checkbox]').live('click', function (event) {
          var checked = !!$(this).attr('checked');

          if (checked && parseInt($('#selected-coupon-count').text(), 10) >= 9) {
            event.preventDefault();
            $(this).attr('checked', false);
            alert("Cannot select more than 9 featured coupons.")
          } else {
            var url = $(this).attr('url');
            if (checked) { 
              url = url + '&checked=1'; 
            }
            $('#selected-coupon-listing').load(url, hideFancyLoading );
            showFancyLoading();
            $('input[coupon_id=' + $(this).attr('coupon_id') + ']').attr('checked', checked);
          }
        });
    
        $('#store-filter').liveUpdate('store-list');
        $(document).keydown(function () {
          if (!$('#store-filter:focus')[0]) {
            $('#store-filter').focus().val('');
          }
        });
    
        setTimeout(function () { $('#store-filter').focus(); }, 200);
    } // callbackOnShow
  });  
  
  // Hide flash after few seconds
  // setTimeout( function() { $('.flash').slideUp(); }, 6000 );
  
  // Date selection
  $(".form-date").datepicker({dateFormat: "mm/dd/yy"});

  $(".date-picker").each( function () {
    this.onclick = null;
  }).click( function (event) {
    $(this).prev("input").datepicker("show");
    event.preventDefault();
  });

  // Image or Text Preview
  // Based on: http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
	var xOffset = -20;
	var yOffset =   0;

	$(".preview").live('mouseover', function (event) {
	  var self = $(this);
	  var previewImageUrl = self.attr("preview-image-url");
	  var previewText = self.attr("preview-text");
	  
		$("body").append(
		  "<div id='preview'>" +
		  (previewImageUrl ? "<img src='" + previewImageUrl + "'/>" : "") +
      (previewText || "") +
		  "</div>"
		);
		
		var xOffset_ = xOffset;
		var yOffset_ = yOffset;

		if ($(this).attr("preview-text")) {
		  xOffset_ = -10;
		  yOffset_ =  10;
		}
		
		if (previewText) {
  		$("#preview").css('width', 500);
		}
		
		$("#preview")
			.css("top",  (event.pageY - xOffset_) + "px")
			.css("left", (event.pageX + yOffset_) + "px")
			.fadeIn(200);
  }).

  live('mouseout', function () {
		$("#preview").remove();
  });

	$(".preview").live('mousemove', function (event) {
	  $("#preview")
			.css("top", (event.pageY - xOffset) + "px")
			.css("left",(event.pageX + yOffset) + "px");
	});
});