//jQuery Form Validation

(function($){
 $.fn.validate = function(options) {
    
   var defaults = {
   req_prepend: "*",
   req_append: "(*) ",
   tag: ".inputreq",
   script: "/design_enquiry_send.php"
  };
  
  var options = $.extend(defaults, options);
    
  obj = $(this);
   
  var oid = $(obj).attr('id');
   
  $('#' + oid + ' ' + options.tag).each(function()
  {
	
  var required = $(this);
   
  $(required).prev('label').append(options.req_append);
	
  });
  
  var captcha = $("#" + oid + " input#valid");
  
  if(captcha.length > 0)
  {
							   
  $(captcha).prev('label').before('<div class="form_row captcha"><img id="'+ oid +'_catcha" src="" /></div><div class="form_row captcha"><p>Can\'t Read This? <a href="#" id="'+ oid +'_capt_refresh">Click Here</a> to Refresh.</p></div>');
  
  $('#' + oid + '_capt_refresh').click(function()
											{
												
												$.ajax({
													   
													   type: "POST",
													   url: "/captcha.php?id=" + oid + "&rand=" + Math.floor(Math.random()*5),
													   success: function(captcha)
													   {
														
														$('#' + oid + '_captcha').replaceWith('<div class="form_row captcha">' + captcha + '</div>');
														   
													   }
													   
													   });
												
												return false;
												
											});
							   
  }
   
  $(obj).submit(function()
  {
							
							$('#' + oid + ' ' + options.tag).each(function()
							{
								
							var val = $(this).val();
								
							var next = $(this).next('span.req');
								
							$(this).removeClass('empty_input');
								
							if($(next))
							{
							$(next).remove();
							}
									 
							if(val == "")
							{
								
							$(this).addClass('empty_input');
								
							$(this).after('<span class="req">' + options.req_prepend + '</span>');
								
							}
								
							});
							
							var req = $('span.req');

							if(req.length == 0)
							{
								
							var serial = $(obj).serialize();
								
						    if($("#" + oid + " input#valid").length > 0)
						    {
							   
							   alert('Valid');
							   
						    }
						   
						    $.ajax({
							type: "POST",
							url: options.script,
							data: serial,
							success: function(msg){
								  
								  if(msg != 'failed')
								  {
									
									$("#" + oid).before(msg);
									
									$('#'+oid).each(function(){
									this.reset();
									});
									  
								  }
								  else
								  {
									
									alert("Failed");
									  
								  }
								  
							}
							});
								
							}
							else
							{
							
							$('.empty_input:first').focus();
							
							}
							
							return false;
							
						  });
   
 };
})(jQuery);