//JQuery Setup
$(function(){
//Important functions to fire first!
//-------------------------------------------------------------------------------
//Lazy Script Loading Setup
//see: http://nicolas.rudas.info/jQuery/getPlugin/
//get all plugins referenced above and runs functions
$(document).bind('ready',function(){
	$.plugin('superfish').get(); //to get all files associated with all plugins
	$.plugin('cycle').get(); //to get all files associated with all plugins
	$.plugin('forms').get(); //to get all files associated with all plugins
	$.plugin('flash').get(); //to get all files associated with all plugins
	$.plugin('prettyPhoto').get(); //to get all files associated with all plugins
});//end

	//Google Analytics 
	$.jGoogleAnalytics(
		'UA-8482951-1', // Your GA tracker code
		{
			anchorClick: true, // adds click tracking to *all* anchors
			domainName: 'marrisortho.com/', // e.g. 'nottingham.ac.uk'
			pageViewsEnabled: true // can be disabled e.g. if only tracking e.g. click events
		}
	);


  	//IE6 duct tape
  	//detects if browser is IE by checking leadingWhitespace property. 
  	//See: http://docs.jquery.com/Utilities/jQuery.support
	var fancyHover = $.support.leadingWhitespace;
	if(fancyHover == false) {//browser is IE, use script
		$('#nav ul li, #utility-nav ul li').bind('mouseenter mouseleave', function(){
			$(this).toggleClass('sfhover');
		});	
		//PNG fix for IE6
		$.ajax({
			type: 'GET',
			url: 'scripts/jquery.pngFix1.2.js',
			cache: true,
			success: function() { 
				$(document).pngFix();
			},
			dataType: 'script',
			data: null
		});
 
		//click to close behavior
		if($('.ie-alert-link').length > 0) {
			$.ajax({
				type: 'GET',
				url: 'scripts/jquery.cookie.js',
				cache: true,
				success: function() { 
					$('.ie-alert-link').click(function() {
						$('#ie_alert').slideToggle("slow");
						$.cookie('ie_alert', 'noshow', { expires: 14 });
					});
					//IE6 Upgrade Warning
					//-- requires:
					//-- <script type="text/javascript" src="http://1.scripts.sesamehost.com/scripts/jquery1.3.2.min.js"></script>
					//-- <script type="text/javascript" src="http://9.scripts.sesamehost.com/scripts/jquery.cookie.js"></script>
					
					//cookies
						
					//set cookie handler
					var alertBox = $.cookie('ie_alert');
					//if cookie val "noshow" then hide message - user has already seen this message!
					if(alertBox == 'noshow') {
						$('#alert').css('display', 'none');
					}else{
						$('#alert').css('display', 'block');
					}
				},
				dataType: 'script',
				data: null
			});
		
		}
		//-- /end ie6 warning
	}
        	
	// Some effects rely on an element to be initially hidden,
	// but we only hide them if the user has javascript
	$('.jshide').addClass('hide');
	
		
// Image Replacement	
//-------------------------------------------------------------------------------
	
	//Cufon + jQuery
	//--- requires:
	//--- <script type="text/javascript" src="scripts/jquery.fontavailable-1.1.min.js"></script>
	//--- <script type="text/javascript" src="http://2.scripts.sesamehost.com/scripts/cufon-yui.js"></script>
	if (!$.fontAvailable('Chelsea Studio Regular')) {
		// load the cufon library
		$.ajax({
			type: 'GET',
			url: 'scripts/ChelseaStudioRegular_400.font.js',
			cache: true,
			success: function() { 
	            Cufon.replace('h1, #sidebar dt, #utility-nav>ul>li>a',{
	            	fontFamily:'ChelseaStudioRegular'
	            });
			},
			dataType: 'script',
			data: null
		});
	}

	//jcIR 
	//--- requires: 
	//--- <script type="text/javascript" src="http://4.scripts.sesamehost.com/scripts/jquery.pngFix.js"></script>
	//--- <script type="text/javascript" src="http://2.scripts.sesamehost.com/scripts/jquery.jcIR.js"></script>

	//check if images are enabled then run replacement
	$('h1.jcir').jcIR({
		image_dir: 'titles',//no slashes
		image_ext: '.jpg',//file extention of replacement image
		elem_width: '834',//width of element being replaced
		elem_height: '316'//height of el;ement being replaces
	});

// Navigation
//-------------------------------------------------------------------------------
	//superfish menus
	$.plugin('superfish', {
			files: 		['scripts/superfish.js'],
			selectors:	['#nav>ul, #utility-nav>ul, #logins>ul'],
			//run superfish function dropdowns
			callback:	function() {
					$('#nav>ul, #utility-nav>ul, #logins>ul').superfish({ 
						hoverClass:		'sfhover',							//class used by IE for hover effects
				        delay:			500,                             	//one second delay on mouseout 
				        animation:		{opacity:'show',height:'show'},  	//fade-in and slide-down animation 
				        autoArrows:  	false,                           	//disable generation of arrow mark-up 
				        disableHI:   	true              					// set to true to disable hoverIntent detection
				    });
				}//end callback
	});//end $.plugin superfish


// Utilities
//-------------------------------------------------------------------------------

	
//Toggle functions
//---------------------------------------------------------------------------------
	
	// Show only when javascript is available
	$('.toggle-link').css('display','block');

	//hide lists first!
	//$('#toggle-content li div').css('display','none');	
	$('#toggle-content dl').css('display','none');	

	//toggle
	function toggleInfoContent(id){
		if($(id).css('display') != 'none'){
		  $(id).fadeOut('fast');
  		  $('.back-to-top').addClass('hide');
		}else{
		  //$("#toggle-content li div").hide();
		  $("#toggle-content dl").fadeOut('fast');
		  $(id).fadeIn('slow');
		  $('.back-to-top').removeClass('hide');
		}
	}
	$(".toggle-link").click(function(){
		var id = $(this).attr('href')
	    toggleInfoContent(id);
	    return false;
	});
	
	//------

//Tooltips
//see: http://craigsworks.com/projects/qtip/
//---------------------------------------------------------------------------------
$.plugin('tooltips', {
	files:		['scripts/jquery.qtip-1.0.0-rc3.min.js'],
	selectors:	['.tooltips, div.error'],
	callback:	function() {
		//qtip global styles
		$.fn.qtip.styles.social_media = { // Last part is the name of the style
		   width: 200,
		   background: '#fffef3',
		   color: '#537197',
		   textAlign: 'center',
		   border: {
		      width: 3,
		      radius: 5,
		      color: '#e6dfbb'
		   },
		   tip: 'bottomRight',
		   name: 'dark' // Inherit the rest of the attributes from the preset dark style
		}//end tooltip options
		
		//$('ID HERE').qtip({
		//content: false,
		//show: 'mouseover',
		//hide: 'mouseout',
		//style: 'social_media',
		//	position: {
		//		corner: {
		//			target: 'topMiddle',
		//			tooltip: 'bottomRight'
		//		}
		//	}
		//});
	}//end callback

});//end $.plugin for qtip



//Slideshows
//---------------------------------------------------------------------------------
	//sets a class to the slideshow to set dimensions
	$('.slideshow-wrapper').addClass('jq');

	//load cycle on-demand...
	$.plugin('cycle', {
		files:		['scripts/jquery.cycle.all.min.js'],
		selectors:	['#slideshow-home, #office-tour'],
		callback:	function() {//run function
			if($('#slideshow-home').length > 0) {
				//Home Page Slideshow 
				var $ss = $('#slideshow-home'); 
			         
			    // add slides to slideshow (images 2-8) 
			    for (var i = 2; i < 7; i++) 
			        $ss.append('<img src="images/photos/slideshow-home/slide'+i+'.jpg" width="834" height="316" />'); 
			 
			    // start the slideshow 
			    $('#slideshow-home img:first').fadeIn(1000, function() {
				    $ss.cycle({
				        fx:     'blindY',
				        speed:   'slow',
				        timeout: 7000
				    });
				});
			}else if($('#office-tour').length > 0) {	
				//Office Tour
				$('#office-tour')
				.before('<div id="slideshow-nav">')
				.cycle({
					cleartype: 1,
					cleartypeNoBg: true,
					speed: 2000,
					timeout: 5000,
					pager:  '#slideshow-nav',
					before: function() {
						$('span', this).hide();
					},
					after: function() {
						$('span', this).fadeIn();
					}
				});
			}else{
				return false;
			}//end cycle callback
		}//end $.plugin callback
	});


// Standard Flash Modules
//-------------------------------------------------------------------------------
/* setup dynamic loading */	
$.plugin('flash', {
	files:		['scripts/jquery.flash.js'],
	selectors:	["div[id^='flash-'], div[id^='video']"],
	callback:	function() {
		// Define the default configuation values
		// followed by individual module configuration.
		// Values for individual modules will override the defaults
		
		var flashModules = {
			
			defaults: {			
				width: 500,
				height: 300,
				wmode: 'transparent',
				flashvars: {
					autoPlay: 'false', // change value to 'true'to play on start
					thisColor: '0x' + '603329' // change global hex color (default=639CCE)
				},
				pluginOptions: {version: 9}
			},
		
		modules: [
		  // Define the configuration values for each flash module.
		  // Change item values in any 'flashvars' section to false to omit,
		  // Add any value to override the default value in flashModuleDefaults.
		  
		  {name: 'home', config: {width:541, height:219}},
		  {name: 'braces-diagram', config: {height: 375}},
		  {name: 'brace-painter', config: {height: 430, wmode:'opaque'}},
		  
		  	
		  {name: 'brushing-and-flossing-ortho',
		    config: {
		      flashvars: {
		        brushing: 'true',
		        flossing: 'true'
		      }
		    }
		  },
		  {name: 'brushing-and-flossing-dental',
		    config: {
		      flashvars: {
		        brushing: 'true',
		        flossing: 'true'
		      }
		    }
		  },
		  
		  {name: 'color-your-retainer', config: {width: 300, height: 300}},
		  
		  {name: 'common-treatments',
		    config: {
		      flashvars: {
		        crowding: 'true',
		        openbite: 'true',
		        deepOverbite: 'false',
		        missing: 'false',
		        underbite: 'true',
		        spacing: 'true',
		        overbite: 'true',
		        nonBraces: 'false',
		        phaseI: 'false'
		      }
		    }
		  },
		  
		  {name: 'the-damon-system-comparison', config: {width:250, height:165, wmode:'opaque'}},
		  
		  {name: 'emergency-care',
		    config: {
		      flashvars: {
		        pokingWire: 'true',
		        bracket: 'true',
		        looseWire: 'true',
		        appliance: 'true',
		        headgear: 'false',
		        soreness: 'true'
		      }
		    }
		  },
		  
		  {name: 'ibraces-logo', config: {width:200, height:135, wmode:'opaque'}},
		  
		  {name: 'know-your-teeth', config: {width:500, height:400}},
		  
		  {name: 'office-tour',
		    config: {width:500, height:375, wmode:'opaque',
			  flashvars: { 
				caption01: '',
				caption02: 'Entry way',
				caption03: 'Reception area',
				caption04: 'Coffee tables and chairs',
				caption05: 'Coffee bar',
				caption06: 'Family waiting room',
				caption07: 'Adult waiting room',
				caption08: 'Game room',
				caption09: 'Exam and consultation room',		  
				caption10: 'Records room',		  
				caption11: 'X-ray room',
				caption12: 'Sterilization area',
				caption13: 'Brushing area',
				caption14: 'Open treatment bay',
				caption15: '',
				caption16: ''		  
		      }	  
		    }
		  },
		
		  {name: 'palatal-expander', config: {width: 200, height: 150}},
		  {name: 'patient-care', config: {height: 375}},
		
			{name: 'smile-gallery',
		    config: {
		      flashvars: {
		        bonding: "true",
		        bridges: "true",
		        crowns: "true",
		        fillings: "true",
		        implants: "true",
		        invisalign: "true",
		        veneers: "true",
		        whitening: "true"
		      }
		    }
		  },
		  
		  {name: 'types-of-appliances',
		    config: {
		      flashvars: {
		        elastics: 'true',
		        headgear: 'false',
		        herbst: 'false',
		        palatal: 'true',
		        positioners: 'false',
		        separators: 'true'
		      }
		    }
		  },
		  
		  {name: 'types-of-braces',
		    config: {
		      flashvars: {
		        metal: 'true',
		        gold: 'false',
		        ceramic: 'true',
		        invisible: 'true',
		        lingual: 'false'
		      }
		    }
		  }
		]
		};
		
		// Loop through the defined modules 
		// and do flash replacement for any that are on the current page
		for (var j = flashModules.modules.length - 1; j >= 0; j--){
			var module = flashModules.modules[j];
			// combine default config settings with individual module config settings
			var modConfig = $.extend({}, flashModules.defaults, module.config);
			// combine default flashvars with module flashvars
			modConfig.flashvars = $.extend({}, flashModules.defaults.flashvars, module.config.flashvars);
			modConfig.src = 'flash/' + module.name + '.swf';
			$('#flash-' + module.name).flash(modConfig, flashModules.defaults.pluginOptions);
		}
		
		// Flash Video functions
		//-------------------------------------------------------------------------------
		
		var flashVideos = {
		
			defaults: {
			  // Define the configuation values applied to each module.
			  // Each module in flashModules can override these values.
			  
			  src: 'video/flvPlayer.swf',
			  width: 320,
			  height: 266,
			  wmode: 'transparent',
			  menu: false,
			  allowFullScreen: true,
			  flashvars: {
			    autoStart: "false", // change value to true to play on start
			    showScaleModes: "false", //set to false to disable scale modes menu
			    smoothVideo: "true" //set to false to disable video smoothing 
			  },
			  pluginOptions: {version: 9}
			},
		
			videos: [
				{name: 'the-damon-system',config:{width: 240, height: 206}},
				{name: 'the-damon-system-2',config:{width: 400, height: 330}},
				{name: 'in-ovation',config:{}},
				{name: 'ibraces-1',config:{}},
				{name: 'ibraces-2', config: {width: 352}},
				{name: 'ibraces-3', config: {width: 352}},
				{name: 'invisalign', config: {width: 360}},
				{name: 'suresmile-01', config: {height: 206}}
			]
		};
		for (var j=0; j < flashVideos.videos.length; j++) {
			var video = flashVideos.videos[j];
			// combine default config settings with module config settings
			var vidConfig = $.extend({}, flashVideos.defaults, video.config);
			// combine default flashvars with module flashvars
			vidConfig.flashvars = $.extend({}, flashVideos.defaults.flashvars, video.config.flashvars);
			vidConfig.flashvars.flvToPlay = video.name + '.flv';
			vidConfig.flashvars.startImage = 'video/' + video.name + '.jpg';
			$('#video-' + video.name).flash(vidConfig, flashVideos.defaults.pluginOptions);
		};
	}//end callback
});

// Game room
//-------------------------------------------------------------------------------
	

	//Partial Sliding (Only show some of background)  
    $('ul#sesame-games li').hover(function(){  
        $(".cover", this).stop().animate({top:'36px'},{queue:false,duration:160});  
    }, function() {  
        $(".cover", this).stop().animate({top:'0px'},{queue:false,duration:160});  
    });  

    
//PrettyPhoto
//---------------------------------------------------------------------------------
/*gets plugin then runs function*/
$.plugin('prettyPhoto', {
		files: 		['scripts/jquery.prettyPhoto.js'],
		selectors:	["a[rel^='prettyPhoto']"],
		callback:	function() {
						$("a[rel^='prettyPhoto']").prettyPhoto({
							animationSpeed: 'normal', /* fast/slow/normal */
							padding: 36, /* padding for each side of the picture */
							opacity: 0.45, /* Value betwee 0 and 1 */
							showTitle: true, /* true/false */
							allowresize: true, /* true/false */
							counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
							theme: 'light_square', /* light_rounded / dark_rounded / light_square / dark_square */
							hideflash: false /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
						}); 
					}
});


//Basic HTML functions
//---------------------------------------------------------------------------------

	//Back to top
	if ($('#content').height() > $(window).height()) {
		$('.back-to-top').removeClass('hide');
	}
	

	//prepend "More in this Section" to sub_nav
	$('p.sub_nav').prepend('<strong>More in this section: </strong>');
	
	// Open external links in new windows
	$('a[href^="http://"], a[href^="https://"]').not('[href*="orthosesame.com"],[href*="marrisortho.com"]').addClass('external').attr('target', '_blank');
	
	// Open pdf links in new windows + add icon
	$('a[href$=".pdf"]').attr('target', '_blank').not('[class*="noicon"]').parent().append('<span/>').addClass('pdf');

	// add icons to links which open in prettyPhoto
	$("a[rel^='prettyPhoto[flash]']").parent('li').append('<span/>').addClass('video-link');

 
	//Ordered List Style
	$('ol.alpha, ol.numeric').addClass('js');
	$("ol li").each(function (i) {
	    $(this).wrapInner('<span/>');
    });
    
    //fancy Q & A
    $('ul.q-and-a li').each( function() {
    	$(this).find('h2,h4,h3').prepend('<span>Q: </span>');
    	$(this).find('div').prepend('<span>A: </span>');
	});
	

	

//Form Functions
//---------------------------------------------------------------------------------
		//Hide all items with class of "hidden-content"
		$('.hidden-content').css('display', 'none');
		
		//Sequential numbering of comment form li's
		$(".sequential-list li").each( function(i) {
		    i = i+1;
		    $(this).prepend('<span class="comment-number">' + i + '. </span>');
		});
		
		//toggle hidden fields on Appointment Request Form
		//New Patient Toggle...
		$("input[name^='Current_Patient']").click( function() {
			 if ($("input[name^='Current_Patient']:checked").val() == 'No')
			 	//not current patient, ask where they found us
			 	$('.hidden-content').fadeIn('slow');
			else 
				//current patient, hide content
				$('.hidden-content').fadeOut();
					if($('#found-other').css('display') != 'none') {
						$('#found-other').fadeOut();
					}
		});
		//Where did you hear about us toggle 
		$('#Found').change(function() {
			var selected = $('#Found option:selected');
			if(selected.val() == 'Other') {
				$('#found-other').fadeIn('slow');
			} else {
				$('#found-other').fadeOut();
			}
		});  

		//Comment form "May We Contact You" toggle
		$("input[name^='Contact_Me']").click( function() {
			 if ($("input[name^='Contact_Me']:checked").val() == 'Yes')
			 	//not current patient, ask where they found us
			 	$('.hidden-content')
			 		.fadeIn('slow');
			else 
				//current patient, hide content
				$('.hidden-content').fadeOut();
		});

		//Referral form "Radiographs Sent" toggle
		$("input[name^='Radiographs_Sent']").click( function() {
			 if ($("input[name^='Radiographs_Sent']:checked").val() == 'Yes')
			 	//not current patient, ask where they found us
			 	$('.hidden-content')
			 		.fadeIn('slow');
			else 
				//current patient, hide content
				$('.hidden-content').fadeOut();
		});
		
		/* Toggle Submit after Agreeing to Terms */
		$('input[name^="Disclaimer"]').click( function() {
			 if ($("input[name^='Disclaimer']:checked").val() == 'I Agree')
			 	//not current patient, ask where they found us
			 	$('.hidden-content').fadeIn('slow');
			else 
				//current patient, hide content
				$('.hidden-content').fadeOut();
		});
		
		//clear form fields with "clearme" class when clicked
		$('.clearme').one("focus", function() {
				$(this).val("");
		});
	
		//add red asterisk to label of required fields
		$('label.required').each(function(i) {
			$(this).append('<em> * </em>');
		});
		
		//Form validation
		//---------------------------------------------------------------------------------
		$.plugin('forms', {
				files: 		['scripts/jquery.validate.js',
							 'scripts/jquery.maskedinput-1.2.2.min.js'],
				selectors:	['form'],
				//run Form Validation function
				callback:	function() {
								//masked input
								$(".date-mask").mask("99/99/9999");
								$(".phone-mask").mask("(999) 999-9999");
							
								//additional validation methods
								$.validator.addMethod("phone", function(phone_number, element) {
								    phone_number = phone_number.replace(/\s+/g, ""); 
									return this.optional(element) || phone_number.length > 9 &&
										phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
								}, "Please specify a valid phone number");
							
								//validator
								$(".validate").each(function() {
									$(this).validate({errorElement: "div",
										errorClass: "error tooltips",
										success: function(label) {label.text("ok!").addClass("success");},
										rules: {
											First_Name: 					{required:true,minlength:2},
											Last_Name: 						{required:true,minlength:2},
											Doctor_First_Name: 				{required:true,minlength:2},
											Doctor_Last_Name: 				{required:true,minlength:2},
											Patient_First_Name: 			{required:true,minlength:2},
											Patient_Last_Name: 				{required:true,minlength:2},
											Patient_Email: 					{required:true,email:true},
											Referred_Patient_First_Name:	{required:true,minlength:5},
											Referred_Patient_Last_Name: 	{required:true,minlength:5},
											Doctor_Patient_Referring: 		{required:true,minlength:5},
											Doctor_Email: 					{required:true,email:true},
											Appointment_Email: 				{required:true,email:true},
											Daytime_Phone: 					{required:true,phone:true},
											Alternate_Phone: 				{phone:true},
											Patient_Phone: 					{required:true,phone:true},
											Message: 						{required:true,minlength:12},
											Would_Like_To: 					{required:true},
											Patient_Name: 					{required:"#Contact_Me_Yes:checked",minlength:5},
											Email: 							{required:"#Contact_Me_Yes:checked",email:true},
											txtNumber: 						{required:true,minlength: 5}
										}
									});
								});
							}
		});
			

//-------------------------------------------------------------------------------
	
	
});//end document.ready
