jQuery(function ($) {
	var contact = {
		message: null,
		adds:null,
		errs:false,
		init: function () {
			$('#contact-form input.contact, #contact-form a.contact').click(function (e) {
				//e.preventDefault();
				
				// load the contact form using ajax
				$.get("/send/contact.php", function(data){
					// create a modal dialog with the data
					$(data).modal({
						closeHTML: "<a href='#' title='close' class='modal-close'>x</a>",
						position: ["15%",],
						overlayId: 'contact-overlay',
						containerId: 'contact-container',
						onOpen: contact.open,
						onShow: contact.show,
						onClose: contact.close
					});
				});
			});
		},
		open: function (dialog) {
			// add padding to the buttons in firefox/mozilla
			contact.adds=false;
			if ($.browser.mozilla) {
				$('#contact-container .contact-button').css({
					'padding-bottom': '2px'
				});
			}
			// input field font size
			if ($.browser.safari) {
				$('#contact-container .contact-input').css({
					'font-size': '.9em'
				});
			}

			// dynamically determine height
			h = 360;
			if ($('#contact-subject').length) {
				h += 26;
			}
			if ($('#contact-cc').length) {
				h += 22;
			}
			if ($('#contact-ra').length) {
				h += 22;
			}			
			if ($('#contact-container .contact-message:visible').length > 0) {
				h += 16;
			}

			title = $('#contact-container .contact-title').html();
			$('#contact-container .contact-title').html('');
			if ($.browser.msie && $.browser.version < 7) {
				dialog.overlay.show(0,function(){
					dialog.container.show(0, function () {
						dialog.data.show(0, function () {
							$('#contact-container .contact-content').animate({
								height: h
							}, function () {
								$('#contact-container .contact-title').html(title);
								$('#contact-container form').show();
								//$('#contact-container form').show(0, function () {
									$('#contact-container #contact-cnt').focus();
	
									$('#contact-container .contact-cc').click(function () {
										cc = $('#contact-container #contact-cc');
										cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
									});
									
									$('#contact-container .contact-ra').click(function () {
										ra = $('#contact-container #contact-ra');
										ra.is(':checked') ? ra.attr('checked', '') : ra.attr('checked', 'checked');
									});									
	
									// fix png's for IE 6
									if ($.browser.msie && $.browser.version < 7) {
										$('#contact-container .contact-button').each(function () {
											if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
												src = RegExp.$1;
												$(this).css({
													backgroundImage: 'none',
													filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
												});
											}
										});
									}
								//});
							});
						});
					});
				});
			}else{
				dialog.overlay.fadeIn(200, function () {
					dialog.container.fadeIn(200, function () {
						dialog.data.fadeIn(200, function () {
							$('#contact-container .contact-content').animate({
								height: h
							}, function () {
								$('#contact-container .contact-title').html(title);
								$('#contact-container form').fadeIn(200, function () {
									$('#contact-container #contact-cnt').focus();
	
									$('#contact-container .contact-cc').click(function () {
										cc = $('#contact-container #contact-cc');
										cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
									});
									
									$('#contact-container .contact-ra').click(function () {
										ra = $('#contact-container #contact-ra');
										ra.is(':checked') ? ra.attr('checked', '') : ra.attr('checked', 'checked');
									});											
	
									// fix png's for IE 6
									if ($.browser.msie && $.browser.version < 7) {
										$('#contact-container .contact-button').each(function () {
											if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
												src = RegExp.$1;
												$(this).css({
													backgroundImage: 'none',
													filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
												});
											}
										});
									}
								});
							});
						});
					});
				});
			}
		},
		show: function (dialog) {
			$('#contact-container .contact-send').click(function (e) {
				//e.preventDefault();
				// validate form
				if (contact.validate()) {
					msg = $('#contact-container .contact-message');
					msg.fadeOut(function () {
						msg.removeClass('contact-error').remove();
					});
					$('#contact-container .contact-title').html('');
					if ($.browser.msie && $.browser.version < 7) {
						$('#contact-container form').hide(0);
					}else{
						$('#contact-container form').fadeOut(200);
					}
					$('#contact-container .contact-content').animate({
						height: '180px'
					}, function () {
						if ($.browser.msie && $.browser.version < 7) {
							$('#contact-container .contact-loading').show(0, function () {
								usid = $('.user_id .uid').html();
								$.ajax({
									url: '/send/contact.php',
									data: $('#contact-container form').serialize() + '&action=send'+'&usid='+usid,
									type: 'post',
									cache: false,
									dataType: 'html',
									success: function (data) {
										$('#contact-container .contact-loading').hide(0, function () {
											$('#contact-container .contact-content').html('<div class="contact-finish-msg"><h1>Ваш запрос принят!</h1><h3>В ближайшее время с Вами<br/>свяжется наш менеджер.</h3></div>');
											msg.html(data).show(0);
											_gaq.push(['_trackPageview', '/virtual/mailto']); //yaCounter10191082.reachGoal('/virtual/mailto'); 
										});
									},
								 
								
	 
								
									error: contact.error
								});
							});
						}else{
							$('#contact-container .contact-loading').fadeIn(200, function () {
								usid = $('#user_id .uid').html();
								$.ajax({
									url: '/send/contact.php',
									data: $('#contact-container form').serialize() + '&action=send'+'&usid='+usid,
									type: 'post',
									cache: false,
									dataType: 'html',
									success: function (data) {
										$('#contact-container .contact-loading').fadeOut(200, function () {
											$('#contact-container .contact-content').html('<div class="contact-finish-msg"><h1>Ваш запрос принят!</h1><h3>В ближайшее время с Вами<br/>свяжется наш менеджер.</h3></div>');
											msg.html(data).fadeIn(200);
											_gaq.push(['_trackPageview', '/virtual/mailto']); //yaCounter10191082.reachGoal('/virtual/mailto'); 
										});
									},
									error: contact.error
								});
							});
						}
					});
				}
				else {
					if ($('#contact-container .contact-message:visible').length > 0) {
						msg = $('#contact-container .contact-message div');
						msg.fadeOut(200, function () {
							msg.empty();
							contact.showError();
							msg.fadeIn(200);
						});
					}
					else {
						$('#contact-container .contact-message').animate({
							height: '40px'
						}, contact.showError);
					}
					h = $('.contact-content').height();
					if(contact.adds !== true){
						h = h + 40;
					}
					contact.adds = true;
					$('.contact-content').animate({height:h+'px'},200);
					return false;
				}
				return false;
			});
		},
		close: function (dialog) {
			$('#contact-container .iner').hide(0);
			$('#contact-container .contact-title').html('');
			if ($.browser.msie && $.browser.version < 7) {
				$('#contact-container form').hide(0);
				$('#contact-container .contact-message').hide(0);
			}else{
				$('#contact-container .contact-message').fadeOut(0);
				$('#contact-container form').fadeOut(0);
			}
			$('#contact-container .contact-content').animate({
				height: 40
			},0, function () {
				if ($.browser.msie && $.browser.version < 7) {
					dialog.data.hide(0, function () {
						dialog.container.hide(0, function () {
							dialog.overlay.hide(0, function () {
								$.modal.close();
							});
						});
					});
				}else{
					dialog.data.fadeOut(0, function () {
						dialog.container.fadeOut(0, function () {
							dialog.overlay.fadeOut(0, function () {
								$.modal.close();
							});
						});
					});
				}
			});
			contact.errs = false;
		},
		error: function (xhr) {
			alert(xhr.statusText);
		},
		validate: function () {
			if(contact.errs !== true){
			    $('#contact-container').append('<div class="iner er0"></div>');
				$('#contact-container').append('<div class="iner er1"></div>');
				$('#contact-container').append('<div class="iner er2"></div>');
				$('#contact-container').append('<div class="iner er3"></div>');
				$('#contact-container').append('<div class="iner er4"></div>');
			}
			contact.errs = true;
			contact.message = '';
			
			
			if (!$('#contact-container #contact-cna').val()) {
				$('#contact-container .iner.er0').show(0);
				contact.message += 'Проверьте правильность заполнения поля!'; /* название компании */
				 
			}else{
				$("#contact-container .er0").hide(0);
			}
			
			
			
			if (!$('#contact-container #contact-name').val()) {
				$('#contact-container .iner.er1').show(0);
				contact.message += 'Проверьте правильность заполнения поля!'; /* контактное лицо */
				/*$('#contact-container.contact-znak')
				.html($('<div class=""></div>'))
					.fadeIn(200);
			*/		
			}else{
				$("#contact-container .er1").hide(0);
			}
           if (!$('#contact-container #contact-phone').val()) {
				$('#contact-container .iner.er2').show(0);
				contact.message += 'Необходимо ввести телефон!<br/>';
		}else{
			$("#contact-container .er2").hide(0);
		}
		
			email = $('#contact-container #contact-email').val();
			if (!email) {
				contact.message += 'Необходимо ввести Email!<br/>';
				$('#contact-container .iner.er3').show(0);
			}
			else {
				if (!contact.validateEmail(email)) {
					contact.message += 'Email задан неверно!<br/>';
					$('#contact-container .iner.er3').show(0);
				}else{
					$("#contact-container .er3").hide(0);
				}
				
			}			
			
		/*	var cnt= $('#contact-container #contact-cnt').val();
			if (!cnt) {
				contact.message += 'Необходимо ввести количество товара!<br/>';
			}
			else {
				if (!contact.validateCnt(cnt)) {
					contact.message += 'Количество задается целым числом!<br/>';
				}
			}
			
			*/
			
			if (!$('#contact-container #contact-message').val()) {
				$('#contact-container .iner.er4').show(0);
				contact.message += 'Необходимо ввести текст!<br/>';
			}else{
				$("#contact-container .er4").hide(0);
			}

			if (contact.message.length > 0) {
				return false;
			}
			else {
				return true;
			}
		},
		validateEmail: function (email) {
			at = email.lastIndexOf("@");

			// Make sure the at (@) sybmol exists and  
			// it is not the first or last character
			if (at < 1 || (at + 1) === email.length)
				return false;

			// Make sure there aren't multiple periods together
			if (/(\.{2,})/.test(email))
				return false;

			// Break up the local and domain portions
			local = email.substring(0, at);
			domain = email.substring(at + 1);

			// Check lengths
			if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
				return false;

			// Make sure local and domain don't start with or end with a period
			if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
				return false;

			// Check for quoted-string addresses
			// Since almost anything is allowed in a quoted-string address,
			// we're just going to let them go through
			if (!/^"(.+)"$/.test(local)) {
				// It's a dot-string address...check for valid characters
				if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
					return false;
			}

			// Make sure domain contains only valid characters and at least one period
			if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
				return false;	

			return true;
		},
				 
		//проверка количества
		
		 
		validateCnt:function(cnt) 
		{
           if (+cnt != cnt || cnt.indexOf(".") != -1) 
		   {
           return false;
           } 
		   else 
		   {
          return true;
          }
        },	
		
		
		showError: function () {
			if ($.browser.msie && $.browser.version < 7) {
				$('#contact-container .contact-message').html($('<div class="contact-error"></div>').append('Проверьте правильность заполнения поля')).show(0);
			}else{
				$('#contact-container .contact-message').html($('<div class="contact-error"></div>').append('Проверьте правильность заполнения поля')).fadeIn(200);
			}
			
		}
	};

	contact.init();

});
