$(document).ready(function(){
	
	$("form.validate_form").validate_form();

	if($("form.seminar").length>0)
	{
		$("#coincides_with_real_address").click(function(){
			if(this.checked)$("#real_address").removeClass("valid-required");
            else			$("#real_address").addClass("valid-required");
		});

		$("input.is_attested_accountant").livequery("click",function(){
			var num_certificate_id = "#num_certificate_"+this.id;
			var num_member_ticket_id = "#num_member_ticket_"+this.id;
			if(this.checked)
			{
				$(num_certificate_id).addClass("valid-required");
				$(num_member_ticket_id).addClass("valid-required");
			}
			else
			{
				$(num_certificate_id).removeClass("valid-required");
				$(num_member_ticket_id).removeClass("valid-required");
			}
		});
		$("#addParticipant").click(function(){
			var i = $("#participant_block tbody").length;
			$('<tbody id="participant_block_'+i+'"><tr><td class="dt"><label for="fio'+i+'">ФИО участника семинара&nbsp;<span class="red">*</span></label></td><td class="dd"><input type="hidden" name="labels[fio'+i+']" value="ФИО участника семинара" class="participant participant_title" /><div class="input"><input type="text" id="fio'+i+'" class="txtField validate_form valid-required participant participant_value" name="data[fio'+i+']" /></div></td></tr><tr><td colspan="2" class="cert"><span class="check f90"><input type="hidden" name="labels[is_attested_accountant'+i+']" value="Участник является аттестованным профессиональным бухгалтером" class="participant participant_title" /><input type="checkbox" class="label_highlight is_attested_accountant participant participant_value" id="attested'+i+'" name="data[is_attested_accountant'+i+']" value="Да" /><label for="attested'+i+'">Участник является аттестованным профессиональным бухгалтером</label></span></td></tr><tr class="attested'+i+'_sectShow" style="display:none;"><td class="dt"><label for="num_certificate_attested'+i+'">Номер аттестата&nbsp;<span class="red">*</span></label></td><td class="dd"><input type="hidden" name="labels[num_certificate'+i+']" value="Номер аттестата" class="participant participant_title" /><div class="input_short"><input type="text" id="num_certificate_attested'+i+'" class="nmbrField validate_form participant participant_value" name="data[num_certificate'+i+']" /></div></td></tr><tr class="attested'+i+'_sectShow" style="display:none;"><td class="dt"><label for="num_member_ticket_attested'+i+'">Номер членского билета&nbsp;<span class="red">*</span></label></td><td class="dd"><input type="hidden" name="labels[num_member_ticket'+i+']" value="Номер членского билета" class="participant participant_title" /><div class="input_short"><input type="text" id="num_member_ticket_attested'+i+'" class="nmbrField validate_form participant participant_value" name="data[num_member_ticket'+i+']" /></div></td></tr></tbody>').insertBefore("#participant_block tbody:last");
			
			return false;
		});
	}
});

(function($)
{
  $.fn.validate_form = function(args)
  {
  	/* Load the default options. */
    var options = $.extend({}, $.fn.validate_form.defaults, args);
    var jQ = jQuery;
    return this.each(function()
    {
      /***** Plugin Goes Here *********/
      jQ(this).submit(function()
      {
        jQ(this).find(".mistake").remove();
        jQ(this).find(".error-field").removeClass("error-field");
        var valid=true;
        
        jQ(this).find(".validate_form").each(function()
        {
          el = jQ(this);
          if(el.hasClass("valid-group"))
          {
            if(!valid_group(el.find('input[type=checkbox]:checked,input[type=radio]:checked').length))
            {
              add_error(el, options.group_error_message);
              valid=false;
            }
          }
          if(el.hasClass("valid-url"))
          {
            if(!valid_url(el.val()))
            {
              add_error(el, options.url_error_message);
              valid=false;
            }
          }
          if(el.hasClass("valid-email"))
          {
            if(!valid_email(el.val()))
            {
              add_error(el, options.email_error_message);
              valid=false;
            }
          }
          if(el.hasClass("valid-date"))
          {
            if(!valid_date(el.val(), options.date_format))
            {
              add_error(el, options.date_error_message);
              valid=false;
            }
          }
          if(el.hasClass("valid-required"))
          {
            if(!valid_required(el.val()))
            {
              add_error(el, options.required_error_message);
              valid=false;
            }
          }
          if(el.hasClass("valid-number"))
          {
            if(!valid_number(el.val()))
            {
              add_error(el, options.number_error_message);
              valid=false;
            }
          }
          
          if(valid==false)
          {
		  		$("#form-message-err").text('Заполните, пожалуйста, все поля.');
          }
          
        });
		if(valid===true)
		{
			document.getElementById('form_submit').disabled="disabled";
			$("#form-message-err").text('Пожалуйста подождите, выполняется отправка формы.');
			
			//Заявка на оказание услуг
			if($("form.zayavka").length>0)
			{
				if($("#service_type").val()=='6' || $("#service_type").val()=='7' || $("#service_type").val()=='8' || $("#service_type").val()=='9' || $("#service_type").val()=='10')
				{
					$("form.validate_form input:first").val('27354');
				}
				else
				{
					$("form.validate_form input:first").val('27353');
				}
				
				$.ajax({
					type: "POST",
					url: "/webforms/send/",
					data: $("form.validate_form").formSerialize() + '&data[new][service_type]=' + $('select[@name=service_type] option:selected').text(),
					success: function(msg)
					{
						$("h1").text('Заявка на оказание услуг отправлена');
    					$('<p>Спасибо, что решили воспользоваться услугами нашей компании. Наш сотрудник свяжется с Вами в кратчайшие сроки.</p><br/><div class="f90" align="right"><a href="/uslugi/zayavka/">Отправить еще одну заявку</a></div>').insertBefore("div.form");
						$("div.content div.form").remove();
						$("div.content div.remark2").remove();
		  	 		}
				});
			}
			
			//Регистрация на семинар
			if($("form.seminar").length>0)
			{
				if($("#coincides_with_real_address").is(":checked"))
				{
					$("input[name$='data[new][real_address]']").val(($("input[name$='data[new][juridical_address]']").val()));
				}
				if($("#coincides_with_fax").is(":checked"))
				{
					$("input[name$='data[new][contact_fax]']").val(($("input[name$='data[new][contact_phone]']").val()));
				}
				if($("#contract_audit").is(":checked"))	$("form.validate_form input:first").val('27355');
				else									$("form.validate_form input:first").val('27356');
				
				var all_members = '';
				var temp_title = '';
				jQ(this).find(".participant").each(function()
	        	{
	        		el = jQ(this);
	          		if(el.hasClass("participant_title"))
	          		{
	        	    	temp_title = el.val();
	          		}
		          	else if(el.hasClass("participant_value"))
		          	{
	    	    	    if(el.is(':visible'))
	        		    {
	        	    		if(el.attr("type")=='checkbox')
	        		    	{
		        	    		if(el.attr("checked"))
			          			{
		        	    			all_members = all_members + "\n" + temp_title + ':' + el.val();
		        	    		}
        	    			}
		        	    	else if(el.attr("type")=='text')
		        	    	{
		        	    		if(el.val().length > 0)
		        	    		{
		        	    			all_members = all_members + "\n" + temp_title + ':' + el.val();
	        	    			}
		        	    	}
	        	    	}
		          	}
		        });

				$.ajax({
					type: "POST",
					url: "/webforms/send/",
					data: $("form.validate_form").formSerialize()+ '&data[new][members]=' + all_members,
					success: function(msg)
					{
				  		$("h1").text('Ваша анкета отправлена');
    					$('<p>Спасибо, что решили воспользоваться услугами нашей компании. Наш сотрудник свяжется с Вами в кратчайшие сроки.</p>').insertBefore("div.form");
						$("div.content div.form").remove();
						$("div.content div.remark2").remove();
		  	 		}
				});
			}
		}
        return false;
      });
       
    });
  
  };
  
  function add_error(el, message)
  {
  	el.parent().addClass("error-field");
	el.parent().after('<img src="/img/ic_mistake.gif" alt="" class="mistake" />');
  }
  
  function valid_email(email)
  {
    var email_pattern  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if(email.match(email_pattern)) return true;
    return false;
  };
  
  function valid_url(url)
  {
    var url_pattern  = /^((http|ftp|https):\/\/w{3}[\d]*.|(http|ftp|https):\/\/|w{3}[\d]*.)([\w\d\._\-#\(\)\[\]\\,;:]+@[\w\d\._\-#\(\)\[\]\\,;:])?([a-z0-9]+.)*[a-z\-0-9]+.([a-z]{2,3})?[a-z]{2,6}(:[0-9]+)?(\/[\/a-z0-9\._\-,]+)*[a-z0-9\-_\.\s\%]+(\?[a-z0-9=%&amp;\.\-,#]+)?$/;
    if(url.match(url_pattern)) return true;
    return false;
  };
  
  function valid_number(number)
  {
    var number_pattern = /^([0-9\s])+$/;
    if(number.match(number_pattern)) return true;
    return false;
  };
  
  function valid_required(val)
  {
    if(val.length>0) return true;
    return false;
  }
 
  function valid_group(val)
  {
    return val>0;
  }
  
  function valid_date(date_passed, date_format)
  {
    if(date_format == "mm/dd/yyyy") var date_pattern  = /(0[1-9]|1[012])+\/(0[1-9]|[12][0-9]|3[01])+\/(19|20)\d\d/;
    if(date_format == "dd/mm/yyyy") var date_pattern  = /(0[1-9]|[12][0-9]|3[01])+\/(0[1-9]|1[012])+\/(19|20)\d\d/;
    if(date_passed.match(date_pattern)) return true;
    return false;
  };
  
  $.fn.validate_form.defaults = {
  	email_error_message: 'not a valid email address',
  	text_error_message: 'must be text only',
  	number_error_message: 'not a valid number',
  	date_error_message: 'not a valid date',
  	required_error_message: 'is a required field',
  	group_error_message: 'is a required field',
  	url_error_message: 'not a valid url address',
  	date_format: "dd/mm/yyyy"
  };
  
})(jQuery);



/*   отправить ссылку другу - взято с нагасаки       */
function send_recipe()
{
	if($("#linkId1").val()!='' &&$("#linkId3").val()!='' && $("#linkId4").val()!='' && $("#linkId2").val().match(/^[a-z0-9._%+-]+@(?:[a-z0-9-]+\.)+[a-z]{2,4}$/))
	{
		$.ajax({
			type: "POST",
			url: "/send_recipe/send_recipe.php",
			data: 'name=' + $("#linkId1").val() + '&email=' + $("#linkId2").val() + '&name_from=' + $("#linkId3").val() + '&msg=' + $("#linkId4").val(),
			success: function(msg)
			{
  	 		}
		});
		$("#linkId1").val('');
		$("#linkId2").val('');
		$("#linkId3").val('');
		$("#linkId4").val('');
		$("#linkId5").show();
		$('#send_button_form_link').hide();

	}
}

