jQueryFactory(document).ready(function ($) {
  // Form submit
  $("#lovefactory-form").submit(function () {
    var valid = formValidation();

    return valid;
  });

  // Ajax availabilty checkers
  $(".ajax-check").each(function () {
    var timer = null;
    var input = $(this);

    $(this).bind("keyup blur", function () {
      if ('' == input.val())
      {
        input.parent().find(".response").hide();
        return false;
      }

      input.parent().find(".loader").show().end().find(".response").hide();

      clearInterval(timer);

      timer = setInterval(function () {
        var type = input.hasClass('email') ? 'email' : 'username';
        $.ajax({
          type:     "POST",
          url:      root + "index.php?option=com_lovefactory&controller=signup&task=checkavailability",
          data:     { format: "raw", value: input.val(), type: type },
          dataType: "json",
          success: function (response) {
            input.parent().find(".loader, .error").hide();

            if ("1" == response.status)
            {
              input.parent().find(".response").show().html('<img src="' + root + '/components/com_lovefactory/assets/images/buttons/accept.png" />');
            }
            else
            {
              input.parent().find(".response").show().html('<img src="' + root + '/components/com_lovefactory/assets/images/buttons/cancel.png" />');
            }
          },
          error: function () {
            if (0 == input.parent().find(".error").length)
            {
              input.parent().append("<div class='error'>Error completing request! Try again and if the problem persists contact the administrator.</div>");
            }
            input.parent().find(".loader").hide();
          }
        });

        clearInterval(timer);
      }, 500)
    })
  });

  // Progress bar
  $("#progressbar").progressbar({ value: 0 });

  // Main photo upload
  $('#swfupload-control').swfupload({
    upload_url:             root + "index.php?option=com_lovefactory&controller=gallery&task=registrationupload&format=raw",
    file_size_limit:        "10240000",
    file_types:             "*.jpg;*.gif;*.png;",
    file_types_description: "Images",
    file_upload_limit:      "0",
    file_queue_limit:       "1",
    file_post_name:         "photo",
    flash_url:              root + "components/com_lovefactory/assets/swfs/swfupload.swf",
    button_image_url :      root + 'components/com_lovefactory/assets/images/buttons/picture_add_swf.png',
    button_width:           100,
    button_height:          25,
    button_text:            '<span class="theFont">' + txt_upload + '</span>',
    button_text_style:      ".theFont { text-align: left; margin-left: 20px; font-size: 12px; font-family: Helvetica,Arial,sans-serif; font-weight: bold; }",
    button_placeholder:     $('#button')[0],
    debug:                  false,
    button_cursor:          SWFUpload.CURSOR.HAND,
    button_window_mode:     'transparent',
    post_params:            { "PHPSESSID": session_id, session_name : session_id },
    custom_settings: {something : "here"}
  })
  .bind('fileQueued', function(event, file){
    $(this).swfupload('startUpload');
    var parent = $(this).parent();
    parent.find(".error").hide();
  })
  .bind('uploadStart', function(event, file){
    $('#progressbar').progressbar("option", "value", 0).fadeIn(100);
  })
  .bind('uploadProgress', function(event, file, bytesLoaded){
    $('#progressbar').progressbar("option", "value", Math.floor(bytesLoaded * 100 / file.size));
  })
  .bind('uploadSuccess', function(event, file, serverData){
    try
	  {
      var response = eval('(' + serverData + ')');
	  }
	  catch (e)
	  {
	    var parent = $(this).parent();
	    var error  = txt_error_uploading;
	    if (0 == parent.find(".error").length)
	    {
	      parent.append('<div class="error lovefactory-button lovefactory-bullet-error lovefactory-error-field">' + error + '</div>');
	    }
	    else if ("none" == parent.find(".error").css("display"))
	    {
	      parent.find(".error").html(error).show();
	    }

	    return false;
	  }

	  if (0 == response.status)
	  {
	    var parent = $(this).parent();
	    if (0 == parent.find(".error").length)
	    {
	      parent.append('<div class="error lovefactory-button lovefactory-bullet-error lovefactory-error-field">' + response.message + '</div>');
	    }
	    else if ("none" == parent.find(".error").css("display"))
	    {
	      parent.find(".error").html(response.message).show();
	    }
	  }
	  else
	  {
	    $("#lovefactory-main-photo-upload").fadeOut(100, function () {
	      $(this).css("background-image", "url(" + response.thumb + ")").fadeIn(100);
	    });

	    $("#main_photo_upload").val(response.filename);
	  }
  })
  .bind('uploadComplete', function(event, file){
    $("#progressbar").fadeOut(100);
  });
});
