// anasys.com - main.js

$(document).ready(function(){
  // searchfield outfit
  $('.searchform input.textbox').css({'background-image' : 'none', 'margin-top' : '2px' });
  
  $('.searchform input.textbox').blur(function(){
    $('.searchform input.textbox').css({'background-image' : 'none', 'margin-top' : '2px' });
  });
  
  // Hide spam protector
  if ($('#id_meta_protect').length > 0 ) {
    $('#id_meta_protect').parent().parent().hide();  
  }
 
  
  
  // Form handling
  
  $('#main form').submit( function() {
    // exception for main contact form
    if ($(this).attr('id') != 'contactForm') {
      // validate forms for required fields on submit  
      if (valRequiredFields()==true) {
        // Processing message for user
        $('#main form input[@type=submit]').attr('value', 'Please wait...');
        $('#main form input[@type=submit]').attr('disabled', 'disabled');

        // collect form input
        var inputs = '';
        $('#main form input[@type!=submit]').each(function() {
          inputs += '&' + this.name + '=' + this.value;
        });
        
        // collect input from textareas
        $('#main form textarea').each(function() {
          inputs += '&' + this.name + '=' + this.value + '\n';
        });
        
        // collect input from select lists
        $('#main form select').each(function() {
          inputs += '&' + this.name + '=' + this.value;
        });
        
        // send form input as ajax request to server
        inputs = inputs.substring(1);
        ajaxPost(inputs);
          
      }
      return false;
    }
  }); 
        
});

function ajaxPost(myInput) {
  $.post('.', myInput, function(retVal){
    // replace form with response from server
    $('#main form').replaceWith('<form><p style="font-weight:bold;">' + retVal + '</p></form>');
  });
}

function valRequiredFields() {
  try {
    var errMsg = '';
    var result = true;
    // required fields
    $('form .required').each(function() {
      if ($(this).attr('value')==null) {
        errMsg += 'Field ' + $(this).attr('name') + ' is required.\n';
        result = false;
      }
    });
    
    // email fields
    $('form .email').each(function() {
      if ($(this).attr('value')!=null) {
        var myVal = $(this).attr('value');
        apos=myVal.indexOf("@");
        dotpos=myVal.lastIndexOf(".");
        if (apos<1||dotpos-apos<2) {
          errMsg += 'Field ' + $(this).attr('name') + ' must be a valid email address.\n';
          result = false;
        }
      }
    });
  
    if (errMsg!='') {
      alert(errMsg);
      return false;
    }
    else {
      return result;
    }
  } 
  catch(e) {
    alert(e);
  }
}

