$.extend({ford: {}});
$.extend($.ford, {vars:  { }});
$.extend($.ford, {Page:  { }}); // Clean this up
$.extend($.ford, {pages: { }});
$.extend($.ford, {modal: { }});
$.extend($.ford, {Modal: $.ford.modal}); // Clean this up
$.extend($.ford, {nav:   { }});
$.extend($.ford, {WT:    { }});
$.extend($.ford, {cufon: { }});
$.extend($.ford, {ie:    { }});
$.extend($.ford, {replacePlaceholder: { }});
$.extend($.ford, {flash: { }});
$.extend($.ford.vars, {vars: { }}); // $.ford.vars.vars is where the vars live when using getter and setter
$.extend($.ford.vars, {set: function(name, value) {
	$.ford.vars.vars[name] = value;
	// make code backward compatible
	// clean code up
	if(name != 'set' && name != 'get') {
		$.ford.vars[name] = value;
	}
}});
$.extend($.ford.vars, {get: function(name) {
	if(name != null && name.length > 0) {
		return $.ford.vars.vars[name];
	}
	return null;
}});
$.extend($.ford.replacePlaceholder, {init : function(){
		
	if($.support.placeholder) {
		return;
	}
	$('input:text[placeholder]').val(function() {
		$(this).addClass('placeholder');
		return $(this).attr('placeholder');
	});
	$('input:text[placeholder]').bind('focus', function() {
		if($(this).val() == $(this).attr('placeholder')) {
			$(this).val('');
			$(this).removeClass('placeholder');
		}
	}).bind('focusout', function() {
		if($(this).val().length == 0) {
			$(this).addClass('placeholder');
			$(this).val($(this).attr('placeholder'));
		}
	}).parents('form').bind('submit', function() {
	   $(this).children('input:text[placeholder]').val(function() {
		   if($(this).val() == $(this).attr('placeholder')) {
			   $(this).removeClass('placeholder');
			   return "";
		   }
		   return $(this).val();
	    });
	});
}});
$.extend($.ford.modal, {init: function() {
	$('._js_modal_leave').bind('click', function(e) {
		e.stopImmediatePropagation();
		e.preventDefault();
		$.ford.modal.leave.open(e);
		return false;
	});
	$('._js_modal_lincoln').bind('click', function(e) {
		e.stopImmediatePropagation();
		e.preventDefault();
		$.ford.modal.lincoln.open(e);
		return false;
	});
}});
$.extend($.ford.modal, {postal: {
	obj: null,
	load: function() {
		$.ford.modal.postal.obj = $('<div>').dialog(
			{
				autoOpen: false, 
				modal: true,
				resizable: false,
				width: 442
			}
		);
		$.ford.modal.postal.obj.html('Loading...');
		$.ajax({
			url: _F.root + '/' + _F.lang + '/modal/postalCode.html',
			success: function(data) {
				$.ford.modal.postal.obj.html(data);
				$('.js_enter_postal').focus();
				$('.js_modal_save').bind('click', function() {
					if($.ford.validation.isPostal($('.js_enter_postal').val())) {
						$('.js_enter_postal').removeClass('error');
						$.ford.common.postalCode.change($('.js_enter_postal').val());
						$('html').trigger('postalChange');
						$.ford.modal.postal.close(true);
						
					} else {
						$('.js_enter_postal').addClass('error');
					}
				});
				$('.js_modal_close').bind('click', function() {
					$.ford.modal.postal.close($(this).hasClass('js_cookie'));
				});
			}
		});
	},
	open: function() {
		if($.ford.modal.postal.obj == null) {
			$.ford.modal.postal.load();
		}
		$.ford.modal.postal.obj.dialog('open');
	},
	close: function(setCookie) {
		if($.ford.modal.postal.obj != null) {
			$.ford.modal.postal.obj.dialog('close');
		}
		if(setCookie == true) {
			$.cookie('zip_ignore', 'true', { expires: 365, path: '/', domain: null, secure: false});
		}
	}
}});
$.extend($.ford.modal, {leave: {
	obj: null,
	load: function(e) {
		$.ford.modal.leave.obj = $('<div>').dialog({
			autoOpen: false, 
			modal: true,
			resizable: false,
			width: 442
		});
		$.ford.modal.leave.obj.html('Loading...');
		$.ajax({
			url: _F.root + '/' + _F.lang + '/modal/leaveFord.html',
			cache: false,
			success: function(data) {
				$.ford.modal.leave.obj.html(data);
				$('.js_modal_close').bind('click', function(e) {
					$.ford.modal.leave.close();
				});
				$('.js_continue').bind('click', function() {
					$.ford.common.url.goTo($(e.currentTarget).attr('href'), $(e.currentTarget).attr('target'));
					$.ford.modal.leave.close();
				});
			}
		});					
	},
	open: function(e) {
		if($.ford.modal.leave.obj == null) {
			$.ford.modal.leave.load(e);
		}
		// clean this up later, RB (without this re-binding, all modals on a page will go to the first external url visited!)
		$('.js_continue').unbind('click');
		$('.js_continue').bind('click', function() {
			$.ford.common.url.goTo($(e.currentTarget).attr('href'), $(e.currentTarget).attr('target'));
			$.ford.modal.leave.close();
		});
		// end of what needs cleaned up
		$.ford.modal.leave.obj.dialog('open');
	},
	close: function() {
		if($.ford.modal.leave.obj != null) {
			$.ford.modal.leave.obj.dialog('close');
		}
	}		
}});
$.extend($.ford.modal, {lincoln: {
	obj: null,
	load: function(e) {
		$.ford.modal.lincoln.obj = $('<div>').dialog({
			autoOpen: false, 
			modal: true,
			resizable: false,
			width: 442
		});
		$.ford.modal.lincoln.obj.html('Loading...');
		$.ajax({
			url: _F.root + '/' + _F.lang + '/modal/leaveLincoln.html',
			success: function(data) {
				$.ford.modal.lincoln.obj.html(data);
				$('.js_modal_close').bind('click', function(e) {
					$.ford.modal.lincoln.close();
				});
				$('.js_continue').bind('click', function() {
					$.ford.common.url.goTo($(e.currentTarget).attr('href'), $(e.currentTarget).attr('target'));
					$.ford.modal.lincoln.close();
				});
			}
		});					
	},
	open: function(e) {
		if($.ford.modal.lincoln.obj == null) {
			$.ford.modal.lincoln.load(e);
		}
		// clean this up later, RB (without this re-binding, all modals on a page will go to the first external url visited!)
		$('.js_continue').unbind('click');
		$('.js_continue').bind('click', function() {
			$.ford.common.url.goTo($(e.currentTarget).attr('href'), $(e.currentTarget).attr('target'));
			$.ford.modal.lincoln.close();
		});
		// end of what needs cleaned up
		$.ford.modal.lincoln.obj.dialog('open');
	},
	close: function() {
		if($.ford.modal.lincoln.obj != null) {
			$.ford.modal.lincoln.obj.dialog('close');
		}
	}		
}});
$.extend($.ford.nav, {init: function() {
	$('div#fordNav ul li:visible').bind('mouseenter', function() {
		$(this).find('div.navLeft').toggleClass('leftHover');/*ie6 fix*/
		$(this).find('div.navRight').toggleClass('rightHover');/*ie6 fix*/
		$(this).find('div.navLeft, div.navRight, p').toggleClass('hover');
		$(this).find('div.sub').show();
	});	
	$('div#fordNav ul li:visible').bind('mouseleave', function() {
		$(this).find('div.navLeft').toggleClass('leftHover');/*ie6 fix*/
		$(this).find('div.navRight').toggleClass('rightHover');/*ie6 fix*/
		$(this).find('div.navLeft, div.navRight, p').toggleClass('hover');
		$(this).find('div.sub').hide();
	});
	$('div#fordNav ul li.on:visible').bind('mouseenter', function() {
		Cufon.replace('#fordNav > ul > li.on p.js_fontAntenna', {
			color: '#004B8D'
		});
		Cufon.now();
	});
	$('div#fordNav ul li.on:visible').bind('mouseleave', function() {
		Cufon.replace('#fordNav > ul > li.on p.js_fontAntenna', {
			color: '#fff'
		});
		Cufon.now();
	});
	$('div#fordNav ul li:hidden, div#lincNav').bind('mouseenter', function() {
		$(this).toggleClass('hover');
	});
	$('div#fordNav ul li:hidden, div#lincNav').bind('mouseleave', function() {
		$(this).toggleClass('hover');
	});
	$('div#fordNav li[data-url], div#fordNav p#pnsSplashPageLink').bind('click', function() {
		var _url = $(this).data('url');
		if($(this).data('acode')) {
			_url = $(this).data('url') + '?acode=' + $(this).data('acode');
		}
		$.ford.common.url.goTo(_url, $(this).attr('target'));
	});
}});
$.extend($.ford.WT, {init: function() {
	$('#_js_wt_page:first').each(function(cnt, object) {
		var group = $(this).attr('data-wtGroup');
		if(group == undefined) {
			group = $(this).parents('[data-wtGroup]:first').data('wtGroup');
		}
		var scenario = $(this).attr('data-wtScenario');
		if(scenario == undefined) {
			scenario = $(this).parents('[data-wtScenario]:first').data('wtScenario');
		}
		
		Ford.Common.WT(group, $(this).attr('data-wtSubGroup'), scenario, $(this).attr('data-wtSubScenario'), $(this).attr('data-wtAdClick'));
	});
	$('._js_wt').live('click', function() {
		var group = $(this).attr('data-wtGroup');
		if(group == undefined) {
			group = $(this).parents('[data-wtGroup]:first').data('wtGroup');
		}
		var scenario = $(this).attr('data-wtScenario');
		if(scenario == undefined) {
			scenario = $(this).parents('[data-wtScenario]:first').data('wtScenario');
		}
		var subgroup = $(this).attr('data-wtSubGroup');
		if (subgroup == undefined) {
			subgroup = $(this).parents('[data-wtSubGroup]:first').data('wtSubGroup');
		}
		$.ford.common.WT(group, subgroup, scenario, $(this).attr('data-wtSubScenario'), $(this).attr('data-wtAdClick'));
	});
}});
$.extend($.ford.cufon, {init: function() {
	$.ford.cufon.run();		
	$('html').ajaxComplete(function() {
		$.ford.cufon.run();
		$('._js_modal_leave').bind('click', function(e) {
			e.stopImmediatePropagation();
			e.preventDefault();
			$.ford.modal.leave.open(e);
		});
		$('._js_modal_lincoln').bind('click', function(e) {
			e.stopImmediatePropagation();
			e.preventDefault();
			$.ford.modal.lincoln.open(e);
		});
	});
}});
$.extend($.ford.cufon, {run: function() {
	 
	Cufon.replace('.js_fontAntenna');
	Cufon.now();		
}});
$.extend($.ford.ie, {init: function() {
	if($.browser.msie == true) {
		/*$('#findDealer').corners("10px bottom-left");
		$('#languageSwitch').corners("10px bottom-right");
		$('#videoContent').corners("5px top");
		$('#footer').corners("6px bottom");
		$('#vpLeftNav #top').corners("5px top-left");
		$('#vpMainTabs').corners("5px top-right");
		$('#vpMainTabs li.on').corners("5px top");*/
	}
}});
$.extend($.ford, {init: function(){
	/* -- Header Search -- */
	$('#bingButton').bind('click', function() {
		$('#searchForm').submit();
	}).live("keypress", function(e) {
		if(e.keyCode == 13) {
			$('#dealerSearchButton').trigger('click');
		}
	});
	$('.bingSearch').bind('focus', function() {
		$(this).addClass('bingSearchActive');
	}).bind('focusout', function() {
		if($(this).val().length == 0) {
			$(this).removeClass('bingSearchActive');
		}
	});		
	/* -- Header Postal Code Changer Setup -- */
	$('.js_postal_changer').bind('click', function() {
		$.ford.modal.postal.open();
	});
	$('html').bind('getPostal', function() {
		$.ford.modal.postal.open();
	});
	/*-- Footer Disclosure Setup -- */
	$('div#disclosure').live('click', function() {
		var $this = $(this);
		var obj = $this.parents('#disclosureWrapper').children('div#disclosureTerms');
		var url = $this.data("url");
		if(!url) url = _F.root + "/" + _F.lang + "/modal/legal.html";
		if($(obj).is(':visible')) {
			$(obj).hide();
			$('#disclosureStatus').removeClass("on");
		} else {
			$(obj).show();
			$('#disclosureStatus').addClass("on");
			$.ajax({
				url: url,
				success: function(data) {
					$(obj).html(data);
					$('.ui-widget-overlay').css('height', ($('.ui-dialog').height() + 120) + 'px');
				}
				
			});
		}
	});
	$('.js_navDropDown').parent().children('h2').bind('click', function() {
	    if($(this).parent().children('ul').is(":visible")) {
	        $(this).parent().children('ul').hide();
	    } else {
	        $(this).parent().children('ul').show();
	    }
	});	
}});

var Ford = $.ford;
F = $.ford;
var _F = $.ford.vars;

$(function() {
	$.init($.ford);
});

$.extend({init: function(object){
	if(object['init']) {
		object['init'].apply(this, Array.prototype.slice.call( arguments, 1 ));
	}
	$.each(object, function() {
		if($.isPlainObject(this)) {
			$.init(this);
		}
	});
}});

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
	if($.ford.vars.isSsl && options.secure) {
		options.url = 'https://' + location.host + options.url;
	}
});

/**
 * Add function to make getting to the data attr a little easer
 * Mark Determan March 6, 2011 
**/
(function( $ ){
	$.fn.escape = function(val) {
		if(val == undefined) {
			return escape(this.val());
		}
		return escape(val);
	};
	$.fn.unescape = function(val) {
		if(val == undefined) {
			return unescape(this.val());
		}
		return unescape(val);
	};
})( jQuery );

$.extend($.support, { placeholder: !!('placeholder' in document.createElement('input')) });

/**
 * Over ride the text function to make sure that it escapes the text every time.
 * Mark Determan March 8, 2011
 */
jQuery.fn._data = jQuery.fn.data;
jQuery.fn.data = function(name, data) {
	if(data == undefined) {
		return $(this).attr('data-' + name);
	} else {
		$(this).attr('data-' + name, data);
	}
};
jQuery.fn._text = jQuery.fn.text;
jQuery.fn.text = function(text) {
	if ( jQuery.isFunction(text) ) {
		return this.each(function(i) {
			var self = jQuery( this );
			self.text( text.call(this, i, self.text()) );
		});
	}
	
	if ( typeof text !== "object" && text !== undefined ) {
		return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( unescape(text) ) );
	}
	
	return jQuery.text( this );
};

/**
 * Create new Ford namespace for jQuery for Ford Plugins.
 * Mark Determan May 10, 2011
 */
(function($){
	
	var _tabs_settings = {
		onClass: "on",
//		hoverClass: "",
		tabPrefix: "tab",
		dataKey: "key",
		defaultTab: null,
		showMethod: null
	};
	
	var methods = {
		tabs: function(options) {
			// make usre options are defined
			if(!options)  options = {};
			// merge options from the default settings
			var opt = {};
			$.extend(true, opt, _tabs_settings, options);
			// loop through each element in the $('SELECT')
			
			// only work if defaultTab is null
			if(opt['defaultTab'] == null) {
				// may need to make this smarter: example buzz:youtub
				var hash = location.hash.substring(1);
				var hashArray = hash.split(':');
				// set the defaultTab based on the location hash
				this.each(function(_index) {
					var _this = this;
					$.each(hashArray, function(index){
						if(this == $(_this).data(opt['dataKey'])) {
							opt['defaultTab'] = _index + 1;
						}
					});
				});
			}
			// if defaultTab is null make sure we select the first tab
			if(opt['defaultTab'] == null) {
				opt['defaultTab'] = 1;
			}
			return this.each(function(index) {
				if($(this).hasClass('_skip')) {
					return;
				};
				$(this).bind('click', function(event, forceReload) {
					// away to force a reload of a tab
					// ex: $(this).trigger('click', [true]);
					if(forceReload === true) $(this).removeClass(opt['onClass']);
					// skip if object has onClass
					if($(this).hasClass(opt['onClass'])) return;
					// remove onClass from all children of parent
					$(this).parent().children().removeClass(opt['onClass']);
					// add onClass to current object
					$(this).addClass(opt['onClass']);
					// Make sure cufon is updated on the page
					$.ford.cufon.run();
					//Hide all tabs
					$.each($(this).parent().children(), function() {
						$("#" + opt['tabPrefix'] + "_"+ $(this).data(opt['dataKey'])).hide();
					});
					// opens tab
					if(jQuery.isFunction(opt['showMethod'])) {
						opt['showMethod'].apply(this, Array.prototype.slice.call( arguments, 1 ));
					} else {
						$("#" + opt['tabPrefix'] + "_"+ $(this).data(opt['dataKey'])).show();
					}
				});
				// auto click the defaultTab (without firing a possible web trends tag)
				if((index+1) === opt['defaultTab']) {
					if ( $(this).hasClass('_js_wt') ) {
						$(this).removeClass('_js_wt');
						$(this).trigger('click');
						$(this).addClass('_js_wt');
					} else {
						$(this).trigger('click');
					};
				}
			});
		}
	};
	
	$.fn.ford = function(method, options) { 
		 if (methods[method]) {
			 return methods[method].apply(this, Array.prototype.slice.call( arguments, 1 ));
		 }
	};
})( jQuery );

// Commented out for an IE 7 bug, review.

// $.trends('dblclick', {u6: 'test'});
// (function($){
// 	
// 	var _dblclick_settings = {
// 		type: '',		// custom
// 		cat: '',		// custom
// 		u1: '',			// custom
// 		u2: '',			// custom
// 		u3: '',			// custom
// 		u4: $.ford.vars.get('lang'),
// 		u5: $('title').text(),
// 		u6: '',			// custom
// 		u7: '',			// custom
// 	};
// 	
// 	var methods = {
// 		dblclick: function(options) {
// 			
// 			var url = "";
// 			
// 			// make usre options are defined
// 			if(!options)  options = {};
// 			// merge options from the default settings
// 			var opt = {};
// 			$.extend(true, opt, _dblclick_settings, options);
// 			
// 			var axel = Math.random() + "";
// 			var a = axel * 10000000000000;
// 
// 			url += 'src=1906242;';
// 			url += 'type=' + opt['type'] + ';';
// 			url += 'cat=' + opt['cat'] + ';';
// 			url += 'u1=' + opt['u1'] + ';';
// 			url += 'u2=' + opt['u2'] + ';';
// 			url += 'u3=' + opt['u3'] + ';';
// 			url += 'u4=' + opt['u4'] + ';';
// 			url += 'u5=' + opt['u5'] + ';';
// 			url += 'u6=' + opt['u6'] + ';';
// 			url += 'u7=' + opt['u7'] + ';';
// 			url += 'ord=1;';
// 			url += 'num=' + a + ';';
// 			$('body').append($('<iframe>').attr('src', 'http://fls.doubleclick.net/activityi;' + encodeURI(url)).attr('height', 0).attr('width', 0).attr('frameborder', 0));
// 		}
// 	};
// 	
// 	$.trends = function(method, options) { 
// 		 if (methods[method]) {
// 			 return methods[method].apply(this, Array.prototype.slice.call( arguments, 1 ));
// 		 }
// 	};
// })( jQuery );

(function($) {
	$.log = {
		level: 'trace',
		trace: function() {
				var array = Array.prototype.slice.call(arguments);
				array.unshift('trace');
				$.log.log.apply({}, array);
			},
		debug: function() {
				var array = Array.prototype.slice.call(arguments);
				array.unshift('debug');
				$.log.log.apply({}, array);
			},
		info: function() {
				var array = Array.prototype.slice.call(arguments);
				array.unshift('info');
				$.log.log.apply({}, array);
			},
		warn: function() {
				var array = Array.prototype.slice.call(arguments);
				array.unshift('warn');
				$.log.log.apply({}, array);
			},
		error: function() {
				var array = Array.prototype.slice.call(arguments);
				array.unshift('error');
				$.log.log.apply({}, array);
			},
		log: function() {
				if(window.console && ($.log.getLevel($.log.level) <= $.log.getLevel(arguments[0]))) {
					var object = Array.prototype.slice.call(arguments);
					if($.browser.msie == true) {
						object = object.toString();
					}
					if(arguments[0] == 'warn') {
						window.console.warn(object);
					} else if(arguments[0] == 'error') {
						window.console.error(object);
					} else {
						window.console.log(object);
					}
				}
			},
		getLevel: function(method) {
			switch(method) {
				case 'trace': 
					return 0;
				case 'debug': 
					return 1;
				case 'info': 
					return 2;
				case 'warn': 
					return 3;
				case 'error': 
					return 4;
				default: 
					return 5;
			}
		}
	};
})( jQuery );

// Class for presenting a modal dialog. This needs to be converted to a JQuery plugin.
function ModalMessage() {
	this.obj = null;
	this.url = '';
	this.onAccept = null;
	this.onCancel = null;
};

ModalMessage.prototype.close = function() {
	if(this.obj != null) {
		this.obj.dialog('close');
	}
};

ModalMessage.prototype.load = function() {
	this.obj = $('<div>').dialog({
			autoOpen: false, 
			modal: true,
			resizable: false,
			width: 442
	});
	this.obj.html('Loading...');
	var modalMessage = this;
	$.ajax({
		url: this.url,
		success: function(data) {
			modalMessage.obj.html(data);
			$('.js_modal_close').bind('click', function(e) {
				modalMessage.close();
				if($.isFunction(modalMessage.onCancel)) {
					modalMessage.onCancel();
				}
			});
			$('.js_modal_ok').bind('click', function(e) {
				modalMessage.close();
				if($.isFunction(modalMessage.onAccept)) {
					modalMessage.onAccept();
				}
			});
		}
	});
};

ModalMessage.prototype.open = function() {
	if(this.obj == null)  {
		this.load();
	}
	this.obj.dialog('open');
};

ModalMessage.prototype.setUrl = function(newUrl) {
	this.url = newUrl;
};

ModalMessage.prototype.setOnAccept = function(func) {
	this.onAccept = func;
};

// This adds the indexOf method if it doesn't exist for the Array object (needed for IE).
$(function() {
	if(!Array.indexOf){
		Array.prototype.indexOf = function(obj) {
			for(var i = 0; i < this.length; i++) {
				if(this[i] == obj) {
					return i;
				}
			}
			return -1;
		};
	}
});
