var infoControlID, errorControlID, successResponseMsg;
ResetMessageControlData();

function HighlightError(element, errorClass)
{
  AddHighlighting(element, 0);
}

function UnhighlightError(element, errorClass)
{
  AddHighlighting(element, 1);
}

function AddHighlighting(element, imageIndex)
{
  var imageSources = new Array('/templates/!shared/images/member/no.gif',
                 '/templates/!shared/images/member/tick.gif');
  var mark = $(element).next('img.generated').eq(0);
  var label = $(element.form).find('label[for=' + element.id + ']');

  if (mark.length == 0) $(element).after(mark = $(document.createElement('img')).addClass('generated'));
  mark.attr('src', imageSources[imageIndex]);

  if (imageIndex == 0) label.addClass('invalidFieldLabel'); else label.removeClass('invalidFieldLabel');
}

function ResetForm(formValidator, form)
{
  if (formValidator != null)
  {
    formValidator.resetForm();
    ClearFormErrorNotations(form);
    ClearMessages();
  }
  else
  {
    $(form)[0].reset();
    $(form).each(function()
    {  
      $("input[type='hidden']", this).each(function() { this.value = ''; });
    });
  }
}

function ClearFormErrorNotations(form, clearDisabledOnly)
{
  var disabledElements = '';
  if (clearDisabledOnly) { disabledElements = ':disabled'; }

  $(form + ' :input' + disabledElements).each(function () {
    $(this).next('img.generated').eq(0).remove();
    $(this.form).find('label[for=' + this.id + ']').removeClass('invalidFieldLabel');
  });
}

function ChangeAction(actionField, action)
{
  var defaultAction = $(actionField).val();
  var newAction = defaultAction ? defaultAction.replace(/\b\w+$/g, action) : '';
  if (newAction) $(actionField).val(newAction);
}

/**
* Submits the form (GET/POST)
*/
function SubmitAjaxForm(form, serviceName, successFunc, beforeSubmitFunc, afterSubmitFunc, requestMethod)
{
  var isMultiPartForm = $(form).attr('enctype') == 'multipart/form-data';
  
  // Initializing Ajax form submit options
  var options = {
    url: serviceName,
    type: requestMethod,
    dataType: 'json',
    success: successFunc
  };
  
  var multiPartOptions = {
    iframe: true,
    dataType: 'html'
  }

  // Setting multipart form options
  if (isMultiPartForm) { $.extend(options, multiPartOptions); }

  // Clearing error notations for disabled fields, because the form validation does not do that
  ClearFormErrorNotations(form, true);

  // Trimming the values of all input fields
  $(form + ' :text,' + form + ' :password,' + form + ' textarea').each(function () {
    $(this).val($.trim($(this).val()));
    
  });

  // Validating the form
  if ($(form).valid())
  {
    // Executing the passed function before form submit 
    if (beforeSubmitFunc && !beforeSubmitFunc()) return;

    // Submitting the form
    $(form).ajaxSubmit(options);
    
    // Executing the passed function after form submit
    if (afterSubmitFunc) afterSubmitFunc();
  }
}

/**
* Submits the form (GET), deprecated function
*/
function SubmitForm(form, serviceName, successFunc, beforeSubmitFunc, afterSubmitFunc)
{
  return SubmitAjaxForm(form, serviceName, successFunc, beforeSubmitFunc, afterSubmitFunc, 'get');
}

/**
* Shows form validation errors
*/
function ShowValidationErrors(errorMap, errorList)
{
  ClearMessages();
  this.defaultShowErrors();
}

/**
* Clears information and error messages
*/
function ClearMessages()
{
  $(infoControlID).text('');
  // Leaving the first element, which is used by validator,
  // and removing the remaining ones, which were added by ajax response
  $(errorControlID).children().not(':first').remove();
}

/**
* Shows an information dialog
*/
function ShowDataSavingDialog()
{
  ShowDataProcessingDialog('Saving data...');
}

/**
* Shows the data loading dialog
*/
function ShowDataLoadingDialog()
{
  ShowDataProcessingDialog('Loading data...');
}

/**
* Closes the data loading dialog
*/
function CloseDataLoadingDialog()
{
  CloseDataProcessingDialog();
}

/**
* Shows the data processing dialog
*/
function ShowDataProcessingDialog(message)
{
  if (!document.getElementById('divActionDialog')) return;
  
  $('#divActionDialog #pADInfo').text(message);
  $('#divActionDialog').dialog('open');
}

/**
* Closes the data processing dialog
*/
function CloseDataProcessingDialog()
{
  if (!document.getElementById('divActionDialog')) return;

  $('#divActionDialog').dialog('close');
}

/**
* Resets the message control data
*/
function ResetMessageControlData()
{
  LoadMessageControlData('#divInfo', '#divErrors', 'The data has been successfully saved');
}

/**
* Loads the message control data
*/
function LoadMessageControlData(infoCtrlID, errorCtrlID, responseMsg)
{
  infoControlID = infoCtrlID;
  errorControlID = errorCtrlID;
  successResponseMsg = responseMsg;
}

/**
* Processes the response of the Ajax form submit
*/
function ProcessResponse(data, statusText)
{
  if (data)
  {
    ClearMessages();
    
    if (data['success'] == 1)
    {
      $(infoControlID).text(successResponseMsg);
    }
    else
    {
      $(errorControlID).append(data['errors']);
    }
  }
  
  CloseDataProcessingDialog();
}

