jQuery.extend({
  // Encodes text with html safe entities.
  encode: function(text) {
    return $("<div/>").text(text).html();
  }
});

$(function() {
  initializeHover();
  
  $(".contact .contact-submit").click(function(event) {
    contactUs(this);
    
    event.preventDefault();
  });
});

$(function() {
  var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

  if ($.browser.msie && ie6) {
    $(".png").each( function() {
      var $$ = $(this);
      
      var src = $$.attr("src");
      var width = $$.width();
      var height = $$.height();
      
      $$.wrap('<span class="pngfix" style="width:' + width + 'px; height: ' + height + 'px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + src + '\', sizingMethod=\'scale\');"></span>');          
    });
  }
});

function initializeHover() {
  $(".with-hover").each(function() {
    var $$ = $(this);
    
    var image = new Image();
    image.src = $$.attr("rel");
    
    var normal = $$.attr("src");
    var hover = $$.attr("rel");
    
    $$.hover(function() {
      $(this).attr("src", hover);      
    }, function() {      
      $(this).attr("src", normal);
    })
  });
}

function animateColor(element, initial, result) {
  element.css({ backgroundColor: initial }).animate({ backgroundColor: result}, 1000);
}

function contactUs(action) {
  var $$ = $(action);
  var $$status = $$.parent().find(".status");
  
  $$status.html("Sending...");
  
  $.ajax({
    type: "post",
    url: "/support/contact/",
    data: $$.closest("form").serialize(),
    dataType: "json",
    success: function(data) {
      if (data.errors) {
        if (data.errors.length > 0) {
          animateColor($$status, '#fff', '#ffe400');
          $$status.html(data.errors[0]);
        }
        else {
          animateColor($$status, '#fff', '#ffe400');
          $$status.html("Unexpected error, please try again.");
        }
      } else {
        animateColor($$status, '#fff', '#c4f2ff');
        $$status.html("Thank you, message sent.");
      }      
    },
    error: function() {
      animateColor($$status, '#fff', '#ffe400');
      $$status.html("Unexpected error, please try again.");
    }    
  });  
}