$(document).ready(function(){

    jQuery.extend(jQuery.validator.messages, {
      required: "Required",
      email: "Invalid format",
      url: "Invalid format",
      equalTo: "Don't match",
      remote: "Unavailable"
    });

    jQuery.validator.addMethod("subdomain", function(value, element) {
     return this.optional(element) || /^[A-Za-z0-9-]+$/i.test(value)
    }, "Invalid format")


    jQuery.validator.addMethod("twitter", function(value, element) {
     return this.optional(element) || /^[A-Za-z0-9_]+$/i.test(value)
    }, "Not valid")

  
  // signin and signup
  $("div.dialog:not(div.dialog.signup)").dialog({autoOpen: false, modal: true, height: 350, width: 375})
  $("a.dialog[rel=forgotten]").click(function(){
    $("div.dialog.signin").dialog("close")
  })
  
  $("button.dialog, a.dialog").click(function(){
    $(".dialog." + $(this).attr("rel")).dialog("open")
  }) 

   
   $(".dialog.forgotten form").validate({
     errorElement: "em",
     errorPlacement: function(error, element) {
       element.parent("td").find("span.message").html(error)
     },
     submitHandler: function(form) {
       
       $.ajax({
          type: form.method,
          url: form.action,
          dataType: "json",
          data: $(form).serialize(),
          success: function(data){
             $(".dialog.forgotten").dialog("close").find("input").val("")
             alert(data.message)
            },
          error: function(xhr){
            var data = $.httpData(xhr, "json")
             var error_template = "<em class='error' generated='true'>{error}</em>"
             $.each(data.errors, function(i, error) {
               var element = $(form).find("." + error[0])
               element.parent("td").find("span.message").html($.nano(error_template, {error: error[1], value: error[0]}))
             })
          }
        })
       return false
     }
   })
    $('#homepage_signup_form').submit(function() {
        $('div.dialog.signup').dialog('open');
        return false;
    });
    $("div.signup.dialog").dialog({autoOpen: false, modal: true, height: 350, width: 375});
    $('div.signup.dialog').bind('dialogopen', function() {        
        $('#profile_search_url').val(($('input[name=profile_url]').val()));
        $('#profile-search-form').submit();
    });
    $('#profile-search-form').validate({
      errorElement: "em",
      errorPlacement: function(error, element) {
        element.parent("td").find("span.message").html(error);
      },
      invalidHandler: function(event) {
        $('#profile-search-form').show();
        $('#new-site-form').hide();
        $('div.signup.dialog > h1 ~ p').show();
        $('#website-display').html('Your Website');
          
        $('div.signup.dialog').dialog('option', 'height', 350);
        $('div.signup.dialog').dialog('option', 'width', 375);
        $('div.signup.dialog').dialog('option', 'position', 'center');
      },
      submitHandler: function(form) {
        var websiteUrl = $('#profile_search_url').val();
        $('div.signup.dialog').dialog('option', 'height', 496);
        $('div.signup.dialog').dialog('option', 'width', 656);
        $('div.signup.dialog').dialog('option', 'position', 'center');

        $('div.signup.dialog > h1 ~ p').hide();
        // Always reset input values.
        $('#site_twitter_username').val('');
        $('#twitter').removeAttr('checked');
        $('#site_feed_url').val('');
        ident.search(websiteUrl);
        google.feeds.lookupFeed(websiteUrl, function(result) {
            if(result.url)
                $('#site_feed_url').val(result.url);
        });

        $('#site_url').val(websiteUrl);
        $('div.signup.dialog #website-display').html(websiteUrl);
        $('#profile-search-form').hide();
        $('#new-site-form').show();

        return false;
      }
    });

    $('#new-site-form').validate({
        rules: {
            'site[password_confirmation]': {
                equalTo: '#site_password'
            },
            'site[subdomain]': {
                remote: '/account/availability.json'
            }
        },
        errorElement: "em",
        errorPlacement: function(error, element) {
          element.parent("td").find("span.message").html(error);
        },
        submitHandler: function(form) {

            $.ajax({
              type: form.method,
              url: form.action,
              dataType: "json",
              data: $(form).serialize(),
              success: function(data){
                 $(".dialog.signup").dialog("close").find("input").val("");
                 alert(data.message);
                },
              error: function(xhr){
                var data = $.httpData(xhr, "json");
                 var error_template = "<em class='error' generated='true'>{error}</em>";
                 $.each(data.errors, function(i, error) {
                   var element = $('div.signup.dialog').find("." + error[0]);
                   element.parent().find("span.message").html($.nano(error_template, {error: error[1], value: error[0]}));
                 });
              }
            });
            return false;
        }
    });
    $('input[name=twitter]').change(function () {
        if ($(this).attr('checked'))
            $('#site_twitter_username').removeAttr('disabled');
        else
            $('#site_twitter_username').attr('disabled', true);
        
    });    
    // Identi Engine stuff when included
    if (window.ident) {
        ident.useInwardEdges = true;
        ident.iconPath = "/images/identi-engine/icons/";
        ident.addPrimaryURL = true;
        $(document).bind('ident:update', renderProfileResults);
    }
    // This code just clears the watermark and unbinds the event.
  $('input.watermark').one('click', function() {
    $(this).val('');
    $(this).removeClass('watermark');
  });
  $('#profile_url, #profile_search_url').one('click', function() {
    $(this).val('http://');      
  });
});

function renderProfileResults() {    

    if(ident.identities.length > 0){
        for (var x = 0; x < ident.identities.length; x++) {
           if(ident.identities[x].domain != 'twitter.com')
                continue;
            if ($('#site_twitter_username').val() == '') {
                $('#site_twitter_username').val(ident.identities[x].username);
                $('#twitter').attr('checked', 'checked');
            }
        }
    }

};