var errorCount=0;


$(document).ready(function(){
	$('#navUL li').hover(function() {
     	$('ul', this).addClass('navHov ').css({'left': '0px'});
     },function(){    
		$('ul', this).removeClass('navHov ').css({'left': '-999em'});
	});
	
	$(".jqImgHover").hover(function () {
		btnSrc = $(this).not(".leftSelected").find('img').attr('src'); 												
		var dot = btnSrc.lastIndexOf('.'); 
        var fName = btnSrc.substr(0,dot);
        var fType = btnSrc.substr(dot,btnSrc.length); 
        $(this).not(".leftSelected").find('img').attr('src', fName+ '_over' + fType);  		
	}, function () {		  
		$(this).not(".leftSelected").find('img').attr('src', btnSrc);
		}
    );	
	

	$('.jqImgHover').each(function() {								   
        preSrc = $('img', this).not(".leftSelected").attr('src');  
        var preDot = preSrc.lastIndexOf('.'); 
     	var preName = preSrc.substr(0,preDot);
		var preType = preSrc.substr(preDot,preSrc.length);         
		preload(preName+ '_over' + preType)  
    });	
	
	$('.datePick').datepicker();

	$('.showNext').click(function() {
		$(this).parent().hide()						  
		$(this).parent().next().show();						  
								  
	//	$(this).parent().slideUp('fast', function() {
		//	$(this).next().slideDown('fast');						 
		// });								  
	})
	
	$('.txtBlue').hover(function() {
		$(this).addClass('hovBlue')
		$(this).removeClass('txtBlue')
	},function() {
		$(this).addClass('txtBlue')
		$(this).removeClass('hovBlue')									 
	 })
								 
								 

	

	$.ajaxSetup({
		error:function(x,e){
			if(x.status==0){
			$('#sendMessage').text('Unable to connect to the internet. Please check your network connection.'); 
			}else if(x.status==404){
			$('#sendMessage').text('Requested URL not found, unable to submit your request.  Please try again');
			}else if(x.status==500){
			$('#sendMessage').text('Internel Server Error. Unable to submit your request.  Please try again');
			}else if(e=='parsererror'){
			$('#sendMessage').text('Error. Unable to submit your request.  Please try again.');
			}else if(e=='timeout'){
			$('#sendMessage').text('Request Time out. Unable to submit your request.  Please try again');
			}else {
			$('#sendMessage').text('Unknown Error.Unable to submit your request.  Please try again');
			}
			$('#sendMessage').hide();
			$('#spinner').hide();
		}
	});					   
						   
	$("#aForm :input:visible:enabled:first").focus(); 
	$('#aForm').submit(function(event){
		event.returnValue = false;
		event.preventDefault();
		errorCount=0;
		var message = '';
		$('.required:visible', this).each(function() {
			var mes = $(this).parent().parent().find('.formMessage');										   
			if($(this).hasClass('email')) {
            	if(!$(this).val()) {
					setError($(this), mes, 'Required')
                } else if(!checkEmail($(this).val())) {				
					setError($(this), mes,'Invalid email')
				} 
			} else if($(this).is("input:radio")) {
				var isChecked = 0
				$(this).parent().find('input[type=radio]').each(function() {
					if($(this).is(":checked")) {isChecked = 1}													
				});
				
				if(isChecked == 0) {
			//	if($(this).is(":not(:checked)") && $(this).siblings().is(":not(:checked)")) {
					setError($(this), mes, 'Required')
				}
			} else if($(this).is("input:checkbox")) {
				if(!$(this).is(":checked")) {setError($(this), mes, 'Required')}		
				
			}else if(!$(this).val()) {
				setError($(this), mes, 'Required')
			}
		})
		if(errorCount == 0) {
			var multiCheck = false;
			$('.ff:visible').each(function() {
				var thisVal = '';			
				//message += '\n';
				if(($(this).is("input:radio")) && $(this).is(":checked")) {
					thisVal = $(this).val();
					message += '\n' + $(this).parent().parent().find('.formQ label').text() + ' ' + thisVal;			
				} else if(($(this).is("input:checkbox")) && $(this).is(":checked")) {					
					if($(this).parent().parent().parent().find('.formQ').hasClass('multiCheck')) {					
						if( multiCheck == false) {
							multiCheck = true;
							message += '\n' + $(this).parent().parent().parent().find('.multiCheck label').text();		
						}
						message+= '\n' + ' -' + $(this).val() + ', ';			
					}  else {
							message += '\n' + $(this).parent().parent().find('.formQRt label').text() + thisVal	
						
					}							
					
				} else if(!($(this).is("input:radio") || $(this).is("input:checkbox"))) { 
				
					if($(this).parent().hasClass('dispNone') && $(this).parent().prev().find("input:radio")) {
						message += $(this).val()
					} else if($(this).hasClass('inputInline') && $(this).parent().hasClass('qInline')) {
							if($(this).parent().prev().find("input:radio").is(':checked')) {
								message += ' $' + $(this).val()
							} else {

							}
					} else {
						if($(this).val() != '') {
						thisVal = $(this).val();
						message += '\n' + $(this).parent().parent().find('.formQ label').text() + ' ' + thisVal + '\n';	
						}
					}
				}
			});
			$('#sendMessage').fadeOut('fast', function() {
					$('#spinner').show();
					$('#send').fadeTo("fast", 0);
					$("div#aFormHideAfterSubmit").slideUp('fast')
					//$('#aForm').fadeTo("fast", 0.33);
			});
			
			// The formTitle attribute on the aForm form over-rides the title of the page for the email and logging to analytics
			formTitle = $("#aForm").attr("formTitle") || $('#rightColumn>.txtTitle').text();
			//vet@manchacavet.com
			$.post("http://www.manchacavet.com/mwp/wp-content/themes/mvvc/sendemail.php", { 
				emailTo: 'vet@manchacavet.com', emailFrom: 'vet@manchacavet.com', subject: '[Web Form] ' + formTitle, message: message 
				
				
			}, function(data){
					$('#spinner').fadeOut('slow');
					// $("#aFormFields .formItem").fadeTo("slow", .3);
					$('#send').hide();
					sendMes($('#formFinalMessage').html(),'txtGreen');
			},'json');
			
			if (pageTracker != null) {
			    pageTracker._trackEvent('Forms', 'Submission', formTitle);
			    pageTracker._trackPageview('/Forms/Submission/' + formTitle); 
//			} else {
//			    console.log("Did NOT track events in Google Analytics!");
			}
			return false;
		}
		
		return false;
	});		// end validation
	
	$('.required').each(function() {
								 
	/*	if($(this).is("input:radio")) {
			$(this).click(function() {
			$(this).parent().parent().find('.formMessage').fadeOut();
			$(this).removeClass('inputReq')	
								   });
		} else {	*/							 
		$(this).focus(function() {
			$(this).parent().parent().find('.formMessage').fadeOut();
			$(this).removeClass('inputReq')								 
		})		
		//}
	})	
	
	$('.formShow').click(function() {								 
		if($(this).is(":checked") && $(this).val() == 'Yes') {			
			$(this).parent().parent().next().slideDown('fast') 	
		} else {
			$(this).parent().parent().next().slideUp('fast')
			$(this).parent().parent().next().find('input').val('')
		}
	});
	
	$('.formShow').each(function() {	 
		if($(this).is(":checked") && $(this).val() == 'Yes') {	
			$(this).parent().parent().next().show();	
		} 
	});	
	
	$('.formSelectShow').change(function() {
		var thisId = $(this)[0].selectedIndex;
		$(this).parent().parent().siblings('.selectShow').not('#selectShow_'+thisId).slideUp('fast');
		$(this).parent().parent().siblings('.selectShow').filter('#selectShow_'+thisId).slideDown('fast');
		// $(this).parent().parent().next('#selectShow_'+thisId).slideDown('fast'); 
								  
								  
								  });
	
	
	$('#formShowDog').click(function() {	 
		if($(this).is(":checked")) {	
			$('#formHiddenDog').show();	
			$('#formHiddenCat').hide();
			$('#formHiddenCatOther').hide();
		} 
	});
	
	$('#formShowDog').each(function() {	 
		if($(this).is(":checked")) {	
			$('#formHiddenDog').show();	
			$('#formHiddenCat').hide();
			$('#formHiddenCatOther').hide();
		} 
	});
	
	$('.formShowSms').click(function() {
		if($('#smsApptYes').is(":checked") || $('#smsHwYes').is(":checked")) {
			$('#formHiddenSmsNumber').slideDown('fast');
		} else {
			$('#formHiddenSmsNumber').slideUp('fast');
		}
		if($('#smsHwYes').is(":checked")) {
			$('#formHiddenSmsDay').slideDown('fast');
		} else {
			$('#formHiddenSmsDay').slideUp('fast');
		}
	});
	
	$('#formShowCat').click(function() {	 
		if($(this).is(":checked")) {	
			$('#formHiddenCat').show();	
			$('#formHiddenDog').hide();
		} 
	});
	
	$('#formShowCat').each(function() {	 
		if($(this).is(":checked")) {	
			$('#formHiddenCat').show();	
			$('#formHiddenDog').hide();
		} 
	});
	
	$('#cat_other').click(function() {	 
		if($(this).is(":checked")) {	
			$('#formHiddenCatOther').show();				
		} 
	});
	
	$('#cat_other').each(function() {	 
		if($(this).is(":checked")) {	
			$('#formHiddenCatOther').show();				
		} 
	});
	
	$('#Long-hair, #Medium-hair, #Short-hair').click(function() {	 
		if($(this).is(":checked")) {	
			$('#formHiddenCatOther').hide();				
		} 
	})
	
	
	
	
	
	
	$('.formCbShow').click(function() {								 
		if($(this).is(":checked")) {
			$(this).parent().next().next('.dispNone').slideDown('fast'); 	
		} else {
			$(this).parent().next().next('.dispNone').slideUp('fast');
			$(this).parent().next().next('.dispNone').find('input').val('');
		}
	});
	
		$('.formCbShow').each(function() {	 
		if($(this).is(":checked")) {	
			$(this).parent().next().next('.dispNone').show();	
		} 
	});	
	
	
	$('#send').hover(function() {
		$(this).addClass('txtCream');
	}, function() {
		$(this).removeClass('txtCream');
	});	

	$('.size-thumbnail').parent().fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	400, 
		'speedOut'		:	200, 
		'overlayShow'	:	true
	   });
	
}); // end onready


function preload() {
    for(var i = 0; i<arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}

function checkEmail(address) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(address);
}

function setError(id, mes,text,txt) {
	mes.text(text);
    $(id).not("input:radio").addClass('inputReq')	
	if(mes.is(':hidden')) {
		mes.show('slide', {direction: 'left'}, 300, function() {
			sendMes('Please verify that all required fields have been entered.','txtRed')
		});
	}
    errorCount ++;	
}


function sendMes(txt,thisClass) {
	$('#sendMessage span').removeClass().html(txt).addClass(thisClass)
	$('#sendMessage').slideDown('fast');	
}

// This method will look to see if utm_campaign is in the URL -- if it is not, then it redirects to itself with utm_campaign set to the proper value.
// We do not redirect on a preview -- because this breaks the ability to preview.
function campaign_redirect(campaign,source) {
  var location;

  if( document.location.href.indexOf("utm_campaign") == -1 && document.location.href.indexOf("preview=true") == -1 ) {
    if (document.location.href.indexOf("?") == -1 ) {
      location = document.location.href + "?";
    } else {
      location = document.location.href + "&";
    }
    document.location.href = location + "utm_campaign=" + campaign + "&utm_source=" + source;
  }
}
