﻿/// <reference path="jquery-1.3.2.js" />

$.ns('AEC');

/*
*  AEC.SignInPanel - Panel containing elements related to signing in
*/
AEC.SignInPanel = {

  init: function() {

    /* 
    * Login functionality
    */

    // Keep a local reference to the form to reduce lookups
    var loginForm = $("#loginForm"),

        performLogin = function() {
          AEC.Dialog.show({
            message: 'Var god vänta...'
          });

          $.ajax({
            url: "/Account/Logon",
            type: "POST",
            data: loginForm.serialize(),
            success: function() {
              window.location.reload();
            }
          });


          return false;
        },

        onKeyDown = function(e) {
          if (AEC.Utilities.isEnterKeyEvent(e)) {
            performLogin();
            return false;
          }
        };

    loginForm.keydown(onKeyDown);

    $('#login').click(performLogin);


    /* 
    * New customer functionality
    */

    var newCustomer = {
      validationConfig: {
        rules: {
          identificationNumber: {
            required: true,
            minlength: 11,
            maxlength: 11
          },
          accountEmail: {
            required: true,
            email: true
          },
          accountEmailConfirm: {
            required: true,
            email: true,
            equalTo: "#accountEmail"
          },
          accountPassword: {
            required: true,
            minlength: 4
          },
          accountPasswordConfirm: {
            required: true,
            equalTo: "#accountPassword"
          }
        },
        messages: {
          identificationNumber: "<p>Ange ett giltigt organisationsnummer</p>",
          organizationNumber: "<p>Ange ett giltigt personummer</p>",
          accountEmail: "<p>Ange en giltig epostaddress</p>",
          accountEmailConfirm: {
            required: "<p>Obligatoriskt fält</p>",
            email: "<p>Ange en giltig epostaddress</p>",
            equalTo: "<p>Du måste ange samma epostadress som ovan</p>"
          },
          accountPassword: "<p>Lösenordet måste ha minst 4 tecken</p>",
          accountPasswordConfirm: {
            required: "<p>Obligatoriskt fält</p>",
            equalTo: "<p>Du måste ange samma lösenord som ovan</p>"
          }
        },
        showErrors: function() {
          if (this.numberOfInvalids() > 0) {
            $('#identificationNumberError').hide();
            this.defaultShowErrors();
          }
        }
      },

      dialogObject: null,

      showDialog: function() {
        if (!newCustomer.dialogObject) {
          $('body').append(
            '<div id="createAccountDialog" class="hide">' +
              rm.get("Common_PleaseWait") +
           '</div>'
          );
          newCustomer.dialogObject = $('#createAccountDialog').dialog({
            autoOpen: false,
            modal: true,
            width: 400,
            resizable: false,
            title: 'Jag vill gärna bli kund på Gullbergs',
            open: function(event, ui) {
              window.setTimeout(function() {
                jQuery(document).unbind('mousedown.dialog-overlay').unbind('mouseup.dialog-overlay');
              },
								100);
            },
            buttons: {
              "Avbryt": newCustomer.onCancelClick,
              "Bli kund": newCustomer.onCreateClick
            }
          });

          newCustomer.dialogObject.load('/Account/GetRegistrationForm', null, newCustomer.onFormLoad);
        }

        newCustomer.dialogObject.dialog("open");
        return false;
      },

      onCreateClick: function() {
        if ($('#accountForm').valid()) {
          AEC.Dialog.showProgress();

          $('#companyName').removeAttr('disabled');
          $('#addressLine').removeAttr('disabled');
          $('#postalCode').removeAttr('disabled');
          $('#city').removeAttr('disabled');

          $('#accountForm').submit();

          $('#companyName').attr('disabled', 'disabled');
          $('#addressLine').attr('disabled', 'disabled');
          $('#postalCode').attr('disabled', 'disabled');
          $('#city').attr('disabled', 'disabled');
        }
      },

      onCancelClick: function() {
        $(this).dialog("close");
      },

      mask: null,

      onGetAddressClick: function() {
        var idField = $('#identificationNumber');

        if (idField.val() && idField.valid()) {
          if (newCustomer.mask) {
            newCustomer.mask.destroy();
          }
          newCustomer.mask = AEC.Mask({
            el: $('#billingAddressPane'),
            message: 'Hämtar uppgifter...',
            msgAlign: 'center',
            border: true
          });

          $("#billingAddressPane").load("/Account/GetBillingAddress/?idno=" + encodeURI(idField.val()), null,
            function(data, status) {
              newCustomer.mask.destroy(true);
              newCustomer.mask = null;
              $('#identificationNumberError').hide();
              $('#billingAddressPane input:not(.enabled)').attr("disabled", true);
              if (status != "success") {
                $('#identificationNumberError').show();
              }
            }, true);
        }
        else {
          idField.focus();
        }
        return false;
      },

      onFormLoad: function() {
        $('#accountForm').ajaxForm({
          success: function() {
            window.location.reload();
          }
        });
        $('#accountForm').validate(newCustomer.validationConfig);
        $('#getAddress').click(newCustomer.onGetAddressClick);

        $('#billingAddressPane input:not(.enabled)').attr("disabled", true);

        $('#identificationNumber').focus();
      }
    };

    $('#newCustomer').click(newCustomer.showDialog);

    /* New password functionality
    * --------------------------
    */
    $("#passwordForm").validate({
      rules: {
        username: {
          required: true
        }
      },
      messages: {
        username: "<p>Ange ett användarnamn</p>"
      }
    });

    $('#showpasswordform').click(function() {
      $('#newpassword').dialog('open');
      return false;
    });

    var btnConfigNewPwd = {};
    btnConfigNewPwd[rm.get("Shared_Button_Cancel")] = function() {
      $(this).dialog("close");
    };
    btnConfigNewPwd[rm.get("Shared_Button_OK")] = function() {
      if ($("#passwordForm").valid()) {
        $("#newPwdStatusMessage").html("<br/><img src='/images/ajax-loader.gif' class='progressbar' align='center' />");
        postUpdate2($("#passwordForm").serialize(),
              "/Account/NewPassword",
              function() {
                //$("#newpassword").dialog("close");
                //AEC.Dialog.show(rm.get("Shared_CheckoutSignIn_NewPwdSent"));
                $("#newPwdStatusMessage").html(rm.get("Shared_CheckoutSignIn_NewPwdSent"));
                setTimeout(function() {
                  $("#newPwdStatusMessage").html("");
                  $("#newpassword").dialog("close");
                }, 3000);
              },
              function(msg) { $("#newPwdStatusMessage").html('<span class="error">' + msg + '</span>'); }
              );
      }
    };

    $('#newpassword').dialog({
      autoOpen: false,
      modal: true,
      height: 265,
      width: 310,
      resizable: false,
      title: 'Glömt lösenord?',
      open: function(event, ui) {
        $("#forgotusername").focus();
      },
      buttons: btnConfigNewPwd
    });

    $("#passwordForm").keydown(function(e) {
      if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        btnConfigNewPwd[rm.get("Shared_Button_OK")]();
        return false;
      } else {
        return true;
      }
    });

    $('#username').watermark({
      watermarkedText: "Användarnamn",
      watermarkedClass: 'loginWatermark'
    });

    assoc_password("#password");
  }
};

function assoc_password(selector) {
  var item = $(selector);
  if (!item.length) return;
  var replaced = $(set_pwd_type(item[0], "text"));
  $(replaced).watermark({
    watermarkedText: "Lösenord",
    watermarkedClass: 'loginWatermark'
  });
  $(replaced).focus(function() {
    set_pwd_type(this, "password").focus();
  });
}

function set_pwd_type(em, to) {
  var oldbtn = $(em);
  var newbtn = $("<input type='" + to + "'>");
  newbtn.attr("class", oldbtn.attr("class"));
  newbtn.attr("style", oldbtn.attr("style"));
  newbtn.attr("name", oldbtn.attr("name"));
  newbtn.attr("id", oldbtn.attr("id"));

  newbtn.insertBefore(oldbtn);
  oldbtn.remove();
  newbtn.attr("id", oldbtn.id);
  return newbtn;
}

// Generic method to post an update with AJAX and handle the response
// Used when calling from a dialog which handles progress indicator.
function postUpdate2(frm, posturl, onSuccess, onFailure) {
  $.ajax({
    url: posturl,
    type: "POST",
    data: frm,
    success: function(msg) {
      if (msg && msg != "ok") {
        if (typeof onFailure != undefined) {
          if (onFailure.constructor == String) {
            showErrorDialog(onFailure, 3000);
          }
          else if (onFailure.constructor == Function) {
            onFailure(msg);
          }
        }
      }
      else {
        if (typeof onSuccess != undefined) {
          if (onSuccess.constructor == String) {
            showMessageDialog(onSuccess, 3000);
          }
          else if (onSuccess.constructor == Function) {
            onSuccess();
          }
        }
      }
    },
    error: function(request, textStatus, errorThrown) {
      onFailure(request.responseText);
      //console.log(request.responseText);
      //showErrorDialog(request.responseText, rm.get("Shared_Error_ContactSupport"));
    }
  });
}
