
(function ($) {
	// dealer.com logo
	var so = new SWFObject('/apps/ddc/media/flash/ddc_pulse_logo_int.swf', 'flashlogo', '310', '72', '8', '')
	so.addParam('wmode', 'transparent');
	so.addParam('scale', 'noborder');
	so.addParam('salign', 'tr');
	so.write('logo');
	
	// form setup
	if ($('form').size() > 0 ) {
		// country setup
		$('.contactAddressCountry select').change( function () {
			if ( $(this).attr('value') == "USA" ) {
				$('.contactAddressState').show();
				$('.contactAddressState select').addClass('required').parents('label').show();
				$('.contactAddressProvince select').removeClass('required').parents('label').hide();
				$('.contactAddressPostalCode span').html('*Zip Code');
			}
			else if ( $(this).attr('value') == "Canada" ) {
				$('.contactAddressProvince').show();
				$('.contactAddressProvince select').addClass('required').parents('label').show();
				$('.contactAddressState select').removeClass('required').parents('label').hide();
				$('.contactAddressPostalCode span').html('*Postal Code');
			}
			else {
				$('.contactAddressProvince, .contactAddressState').hide();
				$('.contactAddressProvince select, .contactAddressState select').removeClass('required');
				$('.contactAddressPostalCode span').html('*Postal Code');
			}
		});
		// add custom validation methods
		$.validator.addMethod('state', function (value) {
			return /^([a-z]|[A-Z]){2}$/.test(value);
		}, 'Please enter a valid two-character state code.');

		$.validator.addMethod('phone', function (value, el, params) {
			return this.optional(el) || /^[01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4}$/.test(value);
		}, 'Please enter a valid US or Canadian phone number.');

		$.validator.addMethod('email', function (value, el, params) {
			return this.optional(el) || /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test(value);
		}, 'Please enter a valid email address.');

		$.validator.addMethod('postalCode', function (value) {
			return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value);
		}, 'Please enter a valid US or Canadian postal code.');

		$.validator.addMethod('dependsOn', function (value, el, params) {
			return !$(params.el).is(params.being) || $(el).is(':filled');
		}, 'This field is required.');

		// add custom validation rules
		$.validator.addClassRules({
			name: {
				required: true,
				rangeLength: [2, 24]
			},
			dealerName: {
				required: true,
				rangeLength: [2, 64]
			},
			phone: {
				required: true,
				phone: true
			},
			mobilePhone: {
				required: false,
				phone: true
			},
			email: {
				required: true,
				email: true
			},
			postalCode: {
				required: true,
				postalCode: true
			},
			date: {
				required: true
			},
			state: {
				required: true
			}
		});

		// validate		
		$('form').each(function(){
			var validator = $(this).validate({
				debug: true,
				success: function (label) {
					$(label).html('Valid.').parent('label').children().addClass('valid');
				}
			});
		});

	}
	
	$.fn.extend({
		defaultInput: function (settings) {
			settings = $.extend({
				defaultAttribute: 'default',
				defaultClass: 'default'
			}, settings);
			
			return $(this).each(function () {
				// default value
				$('input[' + settings.defaultAttribute + '], textarea[' + settings.defaultAttribute + ']', this).each(function () {
					if (!$(this).val())
						$(this).val($(this).attr(settings.defaultAttribute));
					if ($(this).val() === $(this).attr(settings.defaultAttribute))
						$(this).addClass(settings.defaultClass);
					else
						$(this).removeClass(settings.defaultClass);
					$(this).focus(function () {
						if ($(this).val() === $(this).attr(settings.defaultAttribute))
							$(this).removeClass('default').val('');
					}).blur(function () {
						if (!$(this).val() || ($(this).val() === $(this).attr(settings.defaultAttribute)))
							$(this).val($(this).attr(settings.defaultAttribute)).addClass(settings.defaultClass);
					});
				});
				$(this).submit(function () {
					$('input[' + settings.defaultAttribute + '], textarea[' + settings.defaultAttribute + ']', this).each(function () {
						var self = this;
						if ($(this).val() === $(this).attr(settings.defaultAttribute)) {
							$(this).val('');
							setTimeout(function () {
								$(self).addClass(settings.defaultClass).val($(self).attr(settings.defaultAttribute));
							}, 500);
						}
					});
				});
			});
		},
		/* buttonize */ 
		buttonize: function (settings) {
			settings = $.extend({
				className: 'submit',
				value: 'Submit'
			}, settings);

			return $(this).each(function () {
				$(this).after('<a class="button ' + (settings.className) + '" href="/" tabindex="27" title="' + (settings.value)  + '"><span>' + (settings.value) + '</span></a>').remove();
			});
		},
		/* hoverClass plugin
		 * Auto-adds/removes a class on hover
		 */
		hoverClass: function (settings) {
			settings = jQuery.extend({
				className: 'hover'
			}, settings);
			
			var handleEnter = function () {
					$(this).addClass(settings.className);
			};
			var handleLeave = function () {
					$(this).removeClass(settings.className);
			};
			
			return $(this).each(function () {
				$(this).bind('mouseenter', handleEnter)
				$(this).bind('mouseleave', handleLeave);
			});
		},
		/* external links plugin
		 * handles extrenal links without target attr
		 */
		externalLinks: function (settings) {
			return $(this).each(function () {
				if ((this.hostname && this.hostname !== location.hostname) && ($(this).attr('rel') != 'internal')) {
					$(this).addClass('external');
					$(this).click( function() {
						var newWindow = window.open($(this).attr('href'), 'newWindow');
						newWindow.focus();
						return false;
					});
				}
			});
		},		
		/* teaserSplit plugin
		 * hides all content after first paragraph
		 *customized for Press page
		 */
		teaserSplit: function (settings) {
			settings = $.extend({
				openTitle: 'Read Full Press Release',
				closeTitle: 'Close Press Release'
			}, settings);

			return $(this).each(function () {
				$('p:eq(0)', this).addClass('teaser');
				$(this).children('.teaser').nextAll().not('a.button').hide();
				$(this).append('<a class="button read-more" href="/" title="' + (settings.openTitle) + '"><span>' + (settings.openTitle) + '</span></a>');

				$('.read-more', this).toggle( function() {
					$(this).parent().children().nextAll().not('a.button').slideDown();
					$(this).children('span').text(settings.closeTitle);
					$(this).parent().children('h3').children('a').click();
					return false;
				},function(){
					$(this).parent().children('h3').children('a').click();
					$(this).parent().children().nextAll().not('a.button').not('.teaser').slideUp();
					$(this).children('span').text(settings.openTitle);
					return false;
				});
			});
		},
		/* video script plugin  */
		videoScript: function (settings) {
			settings = $.extend({
				openTitle: 'see transcript',
				closeTitle: 'hide transcript'
			}, settings);

			return $(this).each(function () {
				$(this).append('<a class="toggle-script" href="/" title="' + (settings.openTitle) + '"><span>' + (settings.openTitle) + '</span></a>');

				$('.toggle-script', this).toggle( function() {
					$(this).parent().children().not('a.toggle-script').slideDown(500, 'easeOutQuad');
					$(this).children('span').text(settings.closeTitle);
					return false;
				},function(){
					$(this).parent().children().not('a.toggle-script').slideUp(500, 'easeInQuad');
					$(this).children('span').text(settings.openTitle);
					return false;
				});
			});
		},		
		autoScroll: function (settings) {
			settings = $.extend({
				setClass: false,
				className: 'default',
				autoFade: false,
				startColor: '#000000',
				endColor: '#111111',
				bgColorExists: false,
				inDuration: 200,
				outDuration: 2000,
				timeOut: 750
			}, settings);
			//animate scrolling without plugin
		  	//Based on work by Karl Swedberg [englishrules.com]
			function filterPath(string) {
				return string
				  .replace(/^\//,'')
				  .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
				  .replace(/\/$/,'');
			}
			if (settings.setClass == true) { $lastTarget = ''; }
			$(this).each(function() {			
				if ( filterPath(location.pathname) == filterPath(this.pathname)
				&& location.hostname == this.hostname
				&& this.hash.replace(/#/,'') ) {
					var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
					var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;			  
					if ($target) {				  
						$(this).click(function() {
							//update targetOffset & scroll
							targetOffset = $target.offset().top;
							$('html, body').animate({scrollTop: targetOffset}, {duration: 750, easing: "easeOutQuad"});
							if (settings.setClass == true) {
							   //if lastTarget has value, remove scrollhighlight class
								if ($lastTarget != '') { $lastTarget.removeClass(settings.className) };
								//update target
								$lastTarget = $target;
								$target.addClass(settings.className);
								if (settings.autoFade == true) {
									if (settings.bgColorExists == true) {
										var toColor =  $target.css('backgroundColor');
									} else {
										var toColor = settings.endColor;
									}
									//perform color animation
									$target.animate({ backgroundColor: settings.startColor }, { queue: false, duration: settings.inDuration });
									if (toColor == 'transparent') {
										var color;
										attr = "backgroundColor"; 
										do {
											color = $target.css(attr);
											if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
												break; 
											attr = "backgroundColor";
										} while ( elem = elem.parentNode );
										toColor = color;
									}
									setTimeout( function() { $target.stop().animate({ backgroundColor: toColor }, { queue: false, duration: settings.outDuration }) }, settings.timeOut);
								}
							}
							return false;
						});
					}
				}
			});
			
		},		
		/* printPage plugin
		 * window.print() on printPage class
		 */
		printPage: function (settings) {
			return $(this).each(function () {
				$(this).click( function() {
					window.print();
					return false;
				});
			});
		},
		/* selector plugin
		 * Turns an unordered list of links into a
		 * single selection field.
		 * The ul gets an extra member:  .value, which is
		 * the title of the currently selected element
		 */
		selector: function (settings) {
			settings = jQuery.extend({}, settings);
			
			return $(this).each(function () {
				var s = $(this),				// self
					sc = $('.selected', this),	// selected children
					handleClick = function (e) {
						var itemEl = $(e.target).parents('a').parent('li');
						if (itemEl.is('li') && !itemEl.is('.selected') && !itemEl.parent('ul').is('.disabled')) {
							s.find('.selected').removeClass('selected');
							itemEl.addClass('selected');
							s[0].value = (itemEl.attr('title') || null);
							s.trigger('change').trigger('mouseleave');
						}
						return false;
					};
				
				s.click(handleClick);
				$('> li', s).hoverClass();	// hover class for children
				s.bind('disable', function () { $(this).addClass('disabled'); });
				s.bind('enable', function () { $(this).removeClass('disabled'); });
				
				// extra convenience properties
				s[0].value = (sc.size() > 0) ? sc.attr('title') : null;		// initialize value of self
				s[0].select = function (value) {
					// select by index
					if (typeof value === 'number') {
						$('li', s).removeClass('selected');
						if ($('li:eq(' + value + ')', s).size() > 0) {
							s[0].value = $('li:eq(' + value + ')', s).attr('title');
							$('li:eq(' + value + ')', s).addClass('selected');
						} else {
							s[0].value = null;
						}
					}
					// select by string value
					if (typeof value === 'string') {
						$('li', s).removeClass('selected');
						if ($('li.' + value, s).size() > 0) {
							s[0].value = value;
							$('li.' + value + ':eq(0)', s).addClass('selected');
						} else {
							s[0].value = null;
						}
					}
					s.trigger('change');
				};
				s[0].remove = function (value) {
					$('li[title=' + value +']', s).remove();
					if (value === s[0].value) {
						s[0].value = undefined;
						s.trigger('change');
					}
				};
			});
		},
		
		/* dropdown plugin
		 * turns an unordered list with an unordered list
		 * of links into a dropdown single selection field.
		 */
		dropDown: function (settings) {
			settings = jQuery.extend({}, settings);
			
			return $(this).each(function () {
				var s = $(this),					// self
					st = $('strong', this),			// strong indicator element
					d = $('ul', this);				// dropDown
				
				// make dropDown list a selector element
				d.selector();
				
				s[0].value = d[0].value;
				
				s[0].select = function (value) {
					d[0].select(value);
					s[0].value = d[0].value;
					st.html($('.selected', d).text());
				};
				
				d.change(function () {
					st.html($('.selected', this).text());
					s[0].value = d[0].value;
					s.trigger('change').trigger('mouseleave');
				});
				
				// hoverClass
				s.hoverClass();
				
				// auto-select selected item
				if ($('.selected', d).size() > 0)
					s[0].select($('.selected', d).text());
				
				s.bind('disable', function () {
					$(this).addClass('disabled');
					d.trigger('disable');
				});
				
				s.bind('enable', function () {
					$(this).removeClass('disabled');
					d.trigger('enable');
				});
			});
		},
		
		/* zoom
		 * makes any image zoomable
		 */
		zoom: function (settings) {
			settings = jQuery.extend({
				activateEvent: 'mouseover',
				deactivateEvent: 'mouseout',
				growthPercent: 40,
				speed: 'medium',
				cloneClass: 'zoomClone'
			}, settings);
			
			var zoomImage = function () {
				var clone = $(this).clone(false),
					curWidth = $(this).width(),
					curHeight = $(this).height(),
					targetWidth = curWidth + (curWidth * (settings.growthPercent / 100)),
					targetHeight = curHeight + (curHeight * (settings.growthPercent / 100)),
					curLeft = $(this).position().left /*+ $(document).scrollLeft()*/,
					curTop = $(this).position().top /*+ $(document).scrollTop()*/,
					targetLeft = curLeft - ((targetWidth - curWidth) / 2),
					targetTop = curTop - ((targetHeight - curHeight) / 2);
				
				var removeClones = function () { $('.' + settings.cloneClass).remove(); };
				
				$(clone).addClass(settings.cloneClass).css({
					position: 'absolute',
					top: curTop,
					left: curLeft,
					opacity: 0
				}).insertAfter(this).animate({
					top: targetTop,
					left: targetLeft,
					width: targetWidth,
					height: targetHeight,
					opacity: 1
				}, settings.speed).bind(settings.deactivateEvent, removeClones);
			};
			
			return $(this).each(function () {
				$(this).bind(settings.activateEvent, zoomImage);
			});
		}
	});
})(jQuery);

jQuery.fn.lvlc = function() {
	return this.each(function() {
		$(this).defaultInput();
		
		var franchiseCheck = false;
		$('a#no-slide', this).click( function() {
			if (franchiseCheck == true) {
				$(this).hide();
				$('#main').addClass('back');
				$('form#lvlc fieldset#details').fadeIn(600).slideDown(500);
				$('.more-info').fadeOut();
				$('#main').css("z-index", "0");
				$('form#lvlc select#franchise').focus();
			}
			return false;
		});
		
		$('.close', this).click( function() {
			$('a#no-slide').show();
			$('form#lvlc fieldset#details').fadeOut(600).slideUp(500);
			$('.more-info').fadeIn();
			$('form#lvlc select#franchise').focus();
			$('#main').css("z-index", "9999");
			return false;
		});
		
		$('select', this).change( function() {
			if ( ($(this, 'option').attr('value')) != 'none') {
				$('form#lvlc a.buttonLarge').removeClass('inactive');
				franchiseCheck = true; }
			else {
				$('form#lvlc a.buttonLarge').addClass('inactive');
				$('form#lvlc label.franchise select').addClass('error');
				franchiseCheck = false;}
		});
		
		$('a.submit', this).click( function() { return false; });
	});
};
jQuery.fn.report = function() {
	return this.each(function() {
		$('tr', this).hoverClass();
		$('tr:nth-child(odd)', this).addClass('odd');

		if ($('#map').size() > 0) {
			var postalCode = $('#map').attr('title');	
			$('#map').jmap({
				mapControlSize: 'none',
				mapCenter:[44.47,-73.15],
				mapDimensions: [460, 200],
				mapEnableDragging: false,
				mapEnableInfoWindows: false,
				mapShowType: false,
				mapZoom: 8
			});
			if (!isNaN(postalCode)) {
				$('#map').searchAddress({
					address: postalCode,
					addMarker: false
				});
			}
		}
	});
};