/**
 * Mutes firebug console code and errors on browsers where firebug is not installed
 */
if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i) {
        window.console[names[i]] = function() {};
	}
}

// extend prototype's observe to be conditional on element being present
Object.extend(Event, {
	condObserve: function(el, evt, f) {
		el = $(el);
		if (el) {
			el.observe(evt, f);
		}
	}
});

var TOOSite = {
	/**
   * Allows you to have "instructional text" in a text input that blanks out when it gains focus if now user information
   * has been entered. e.g.: input field defaults to "Enter Zip Code".  When you click on or tab over to the input field,
   * the default text disappears.  If you tab off or click elsewhere, the default text returns.  If you enter information,
   * the new entry remains.
   * @param {Object} el Element or id of form element to "clean"
   * @param {Object} className optional class name to add to form element when default value is shown
   */
  clickClean: function(el, options) {
		
    el = $(el);
    
    options =  options || {};
    
    el.addClassName(options.className);
    
    el.observe("focus", onfocus);
    el.observe("blur", onblur);
		
		function onfocus(evt) {
			if ($F(el) == el.defaultValue) { 
        el.value = "";
      }
      
      el.removeClassName(options.className);
      
      if (options.maxlength) {
        el.maxLength = options.maxlength;
      }
			
		}
		
		function onblur(evt){
			var el = evt.element();
      if ($F(el).empty()) {
        el.removeAttribute('maxLength');
        
        el.value = el.defaultValue;
        
        el.addClassName(options.className);
      }
    }
    
  },
	
	swapPassword: function() {
		var password = $('password');
		var dummyPassword = $('dummyPassword');
		
		if (password.visible() && $F('password').empty()) {
			password.toggle();
			dummyPassword.toggle();
			//dummyPassword.focus();
		} else if (dummyPassword.visible()) {
			password.toggle();
			dummyPassword.toggle();
			password.focus();
		}
	},
	
	isHttps: function() {
		//return true;
		return (window.location.toString().indexOf('https') != -1);
	},
	
	isLoginPage: function() {
		return (window.location.toString().indexOf('OwnersLogin') != -1);
	},
	
	isForgotPasswordPage: function() {
		return (window.location.toString().indexOf('/Owners/ssl/nonauth/forgotPassword') != -1);
	},
	
	isRegistrationPage: function() {
		return (window.location.toString().indexOf('/Owners/ssl/nonauth/registration') != -1);
	},
	
	isDealerLocatorPage: function() {
		return (window.location.toString().indexOf('/Owners/locator') != -1 ||
			window.location.toString().indexOf('/Owners/find_dealers') != -1);
	},
	
	isLoginPrecheckPage: function() {
		return (window.location.toString().indexOf('/Owners/login_precheck') != -1 ||
			window.location.toString().indexOf('/Owners/mytoyota/login_check') != -1);
	},
	
	isRemoveVehicleNotLoggedInPage: function() {
		return (window.location.toString().indexOf(
			'Owners/ssl/nonauth/vehicle/removeVehicleNotLoggedIn') != -1);
	},
	
	
  _isEmail: function(email) {
	return /^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/.test(email);
  },
  
  _isZip: function(zip) {
	return /^\d{5}([\-]\d{4})?$/.test(zip);
  },
  
  _match: function(a, b) {
    return (a === b);
  },
	
	_isSimplePhone: function(phone) {
    return /.*\d.*\d.*\d.*\d.*\d.*\d.*\d.*\d.*\d.*\d.*/.test(phone);
	},
	
	_isVIN: function(input) {
		var vChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		var IsVIN=true;
		var Char;
		
		IsVIN = (input.length == 17);
		
		for (i = 0; i < input.length && IsVIN === true; i++)
		{
			Char = input.charAt(i);
			if (vChars.indexOf(Char) == -1)
			{
				IsVIN = false;
			}
		}
		
		return IsVIN;
	},
	analytics: function() {
		// these are the internal variables based on omniture. they will need to be 
		// expanded upon as more analytic services are added.
		var parameters = {
			pageName: '',
			server: '',
			channel: '',
			pageType: '',
			properties: [],
			campaign: '',
			state: '',
			zip: '',
			events: '',
			products: '',
			purchaseID: '',
			eventVars: [],
			linkTrackVars: '',
			linkTrackEvents: ''
		};

		/**
		 * Function to send data to analytics.
		 */
		function sendPageView() {
			// send tag to analytics providers
			mapParams(parameters);
			$A(providers).invoke('sendPageView');
			console.info("sendPageView:" + $H(parameters).toJSON());
		}

		function sendEvent() {
			// this makes a deep copy of current parameters
			var temp = Object.clone(parameters);
			temp.properties = Object.clone(parameters.properties);
			temp.eventVars = Object.clone(parameters.eventVars);
			
			$A(providers).invoke('mapParams', Object.extend(temp, arguments[0]));
			$A(providers).invoke('sendEvent');
			$A(providers).invoke('mapParams', parameters);
			console.info("sendEvent:" + $H(parameters).toJSON());

		}

		/**
		 * Function that writes the generic params to the provider 
		 */
		function mapParams(paramsArg) {
			$A(providers).invoke('mapParams', paramsArg);
		}

		function set() {
			Object.extend(parameters, arguments[0]);
			mapParams(parameters);
		}

		function sendTrackingLink() {
			var temp = Object.clone(parameters), $providers = $A(providers);
			temp.properties = Object.clone(parameters.properties);
			temp.eventVars = Object.clone(parameters.eventVars);
			temp.pageName = '';
			
			$providers.invoke('mapParams', Object.extend(temp, arguments[0]));
			$providers.invoke('sendTrackingLink', Object.extend(temp, arguments[0]));
			$providers.invoke('mapParams', parameters);
		}

		/**
		 * Hash of parameters.
		 */
		var providers = [
			{
				provider: 'Omniture',			
				sendPageView: function() {
					s.t();
				},
				sendEvent: function() {
					s.t();
				},
				sendTrackingLink: function(trackParams) {
					s.tl(s, trackParams.linkTrackType, trackParams.linkTrackName);
				},
				mapParams: function(paramsArg) {
					s.pageName = paramsArg.pageName || '';
					s.server = paramsArg.server || '';
					s.channel = paramsArg.channel || '';
					s.pageType = paramsArg.pageType || '';
					s.campaign = paramsArg.campaign || '';
					s.state = paramsArg.state || '';
					s.zip = paramsArg.zip || '';
					s.events = paramsArg.events || '';
					s.products = paramsArg.products || '';
					s.purchaseID = paramsArg.purchaseID || '';
					s.linkTrackVars = paramsArg.linkTrackVars || '';
					s.linkTrackEvents = paramsArg.linkTrackEvents || 'None';
					s.linkTrackType = paramsArg.linkTrackType || 'o';
					s.linkTrackName = paramsArg.linkTrackName || 'Internal Campaign Click';

				


					// wipe out existing values of properties and eVars
					for (var i = 1; i<=50; i++) {
						s['prop' + i] = '';
						s['eVar' + i] = '';
					}

					$H(paramsArg.properties).each(
						function(pair) {
							s['prop' + pair.key] = pair.value;
						}
					);

					// this is a hardcoded business logic rule that has to fire when pageName is set
					if (paramsArg.pageName && paramsArg.pageName.length > 0) {
						var pairs = paramsArg.pageName.split(" : ");
						s.prop10 = pairs[0];
						s.prop11 = pairs[0] + " : " + pairs[1];
					}

					$H(paramsArg.eventVars).each(
						function(pair) {
							s['eVar' + pair.key] = pair.value;
						}
					);
				}
			}
		];
		return {
			sendPageView: sendPageView,
			sendEvent: sendEvent,
			sendTrackingLink: sendTrackingLink,
			set: set
		};
	}(),
	// GLOBAL ANALYTICS PARAMETERS
	channel: (((window.location.toString().indexOf('https') != -1) || (window.location.toString().indexOf('toyota.dev') != -1)))?('GM : Owners : MyToyota'):('GM : Owners')

};
function flashPutHref(href) { location.href = href; }


// Hide from the global scope
(function() {
	/*
	 * "GLOBAL" VARS
	 */
	var user_data;
	var userDataUrl = '/Owners/mytoyota-sessioninfo-js.do';
	//var userDataUrl = '/pub-share/js/userdata.js';
	
	/*
	 * TEMPLATES
	 */
	var user_info = new Template('Hello #{userName}<br />(<a href="/Owners/mytoyota/auth/ssl/OwnersLogout.do" class="logout">Log Out</a>)');
	var dealerTpl = new Template(['<div class="dealer">',
														 '<strong class="name">',
														 '<a href="javascript:MM_openBrWindow(\'/Owners/Owners/dealer-details.do?cid=#{id}\',\'dealers\',\'scrollbars=yes,resizable=yes,width=620,height=350\')">#{name}</a>',
														 '</strong>',
														 '<span class="phone">#{phone}</span>',
														 '<a href="#{apptUrl}" class="btn_sm_fff" style="display:#{display};"><span>Schedule Appointment</span></a></div>'].join(''));
	
	
	/*
	 * CACHED DOM REFERENCES
	 * These are dom elements that are used more then once in this scope. We declare the vars here
	 * and then initialize them within the DOM Loaded callback
	 */
	var savedVehiclesSelect;
	
	// if the page is being served from https, grab the json user data
	if (TOOSite.isHttps() && !TOOSite.isLoginPage() && !TOOSite.isForgotPasswordPage() && !TOOSite.isRegistrationPage() && !TOOSite.isDealerLocatorPage() && !TOOSite.isLoginPrecheckPage() && !TOOSite.isRemoveVehicleNotLoggedInPage()) {

		// get a random number to ensure our request isn't cached
		var rnd = new Date().getTime();
		
		// fetch the user data object
		new Ajax.Request(userDataUrl, {
			method: 'get',
			parameters: 'rnd=' + rnd,
			onSuccess: function(response) {
				console.log("user data is loaded");
				// eval the returned JSON
				user_data = response.responseText.evalJSON();
				
				// verify that the user is logged in...
				if (user_data.loggedin) {
					// and fire the userdata:loaded event
					document.fire('userdata:loaded');
				} else {
					console.log('not logged in');
					// show the alert and redirect
					alert('Your MyToyota session has expired. You will now be redirected to the MyToyota Login page.');
					//alert(response.responseText);
					//alert(user_data.toJSON());
					window.location = '/Owners/mytoyota/auth/ssl/OwnersLogin.do';
				}
			}
		});
	} else {
		console.log('not https');
	}
	
	
	// When the DOM is Loaded...
	document.observe("dom:loaded", function() {
		console.log("document is loaded");
		
		// Initialize the dom element references
		savedVehiclesSelect = $('savedVehiclesSelect');
		
		// if the user_data is undefined...
		if (user_data === undefined) {
			// wait for the user_data to be loaded...
			document.observe("userdata:loaded", function() {
				// and then render it
        renderUserData();
			});
		} else {
      // otherwise, if the user is loggedin... 
			if (user_data.loggedin) {
	      // go ahead and render the user session data
	      renderUserData();
			}
		}
		
		// init analytics
		initAnalytics();
		
		// initialize the login form
		initLogin();
		
		// initialize the owner's manual search form
		initOwnersManual();
		
		// initialize dealer gadget forms
		initDealerGadgets();
		
		
		// grab the zip fields and add click clean to them
		$$('input.zipfield').each(function(el) {
			TOOSite.clickClean(el);
		});
		
		// if the user selects one of their saved vehicles...
		if (savedVehiclesSelect) {
			savedVehiclesSelect.observe('change', function() {
				// send them to the My Vehicles page with that vehicle selected
				window.location = '/Owners/mytoyota/setpvid.do?pvid=' + $F('savedVehiclesSelect');
			});
		}

	});
	
	/*
	 * "GLOBAL" FUNCTIONS
	 */
	function renderUserData() {
		if (!$('globalHeader')) { return; }
		
		//Change top-navigation for logged-in status
		$('primaryNav').addClassName('loggedIn');
		
		// write out the user's name
		var userInfo = $('userInfo');
		if (userInfo) {
			$('userInfo').update(user_info.evaluate({userName: user_data.firstName}));
		}
		
		if (savedVehiclesSelect) {
			// their saved vehicles
			savedVehiclesSelect.update(
		    ['<option value="">My Saved Vehicles: </option>'].concat(user_data.vehicles.collect(function(s) {
		      return '<option value="' + s.id + '">' + s.year + ' ' + s.model + '</option>';
		    })).join()
			);
		}
		
		// update the Home Link/Toyota Logo (homeLink)
		$('homeLink').href = '/Owners/account-overview.do';
		
		// update the global links
		$('globalLinks').update('<li><a href="/Owners/mytoyota/auth/ssl/OwnersLogout.do" class="logout">Log Out</a></li><li class="last"><a href="/Owners/mytoyota-locator.do">Find a Dealer</a></li>');
		
		// modify the stories link
		$$('#stories a')[0].href = '/Owners/mytoyota-stories.do';
		
		// show the subnav
		$('myToyota').show();
		
		
		// and their dealers, if there are any and the module is present
		var myToyotaDealer = $('myToyotaDealer');
		var dealersList = $('dealersList');
		if (myToyotaDealer) {
			$A(user_data.dealers).each(function(dealer, count) {
				dealer.display = (dealer.apptUrl.empty())?('none'):('block');
				if (dealersList) {
					dealersList.insert({'bottom': dealerTpl.evaluate(dealer)});
				}
			});
			myToyotaDealer.show();

			// fire Omniture tag when adding / removing dealers
			Event.observe('myToyotaDealerAddRemove', 'click', function(){
				TOOSite.analytics.sendEvent({
					pageName: TOOSite.channel + " : Profile : Add/Remove Dealers"
				});
			});
		}
		
		
		// if the landing page module is present, do that
		var myDealerSearch = $('my-dealer');
		if (myDealerSearch) {
			if (user_data.dealers[0]) {
				$(myDealerSearch.getElementsByTagName('p')[0]).update(new Template('<strong>#{name}</strong><span><a href="#{url}">Visit Dealer Website</a></span><span>#{address1} #{address2}</span><span>#{city}, #{state} #{zipcode}</span><span>#{phone}</span>').evaluate(user_data.dealers[0]));
			}
		}
		
		// handle the "zipInSet" behavior
		var finance = $('finance');
		if (finance) {
			switch (user_data.zipInSET) {
				case 'Y':
					$('setAd').show();
				break;
				
				case 'N':
					$('non-setAd').show();
				break;
			}
		}

		// fire a logout event
		$$('.logout').each(function(lnk) {
			lnk.observe('click', function(evt) {
				TOOSite.analytics.sendEvent({
					pageName: TOOSite.channel + " : Logout"
				});
			});
		});
			
	}
	
	function initLogin() {
    // if the login form exists ...
    var loginForm = $('loginFrm');
    if (loginForm) {
			// watch form submit
			loginForm.observe('submit', validateLogin);
      // cache fields
      var userName = $('userName');
      var password = $('password');
      
      // attach clickClean to username and password
      TOOSite.clickClean(userName);
    }
  }
	
	function validateLogin(e) {
    var errors = '';
	if ($F('userName') == '' || $F('userName') == $('userName').defaultValue) { errors += 'Please enter your User Name.\n'; }
    if ($F('password') == '' || $F('password') == $('password').defaultValue) { errors += 'Please enter your Password.\n'; }

    if (errors != '') {
      if (e) { Event.stop(e); }
      alert(errors);
      return false;
    } else { return true; }
	}
	
	function initOwnersManual() {
		var findOwnersManual = $('findOwnersManual');
		
		if (findOwnersManual) {
			findOwnersManual.observe('submit', validateOwnersManual);
			var pv = $('pv');
			var py = $('py');
			
			// assign listeners to the form
			pv.observe('change', function() {
				// look through the vehicle data and populate year
				if ($F('pv') != 'Select Vehicle Model') {
	        py.update('');
	        py.insert('<option value="" selected="selected">Select Year</option>', {position: 'top'});
					vehicleData[$F('pv')].each(function(value, index) {
	          py.insert('<option value="' + value + '">' + value + '</option>');
					});
					py.enable();
				}
			});
			
			findOwnersManual.select("a.submit").each(function(link){
				link.observe('click',function(e) {
					Event.stop(e);
					if (validateOwnersManual()) {
						findOwnersManual.submit();
					}
				});
			});
		}
	}

  function validateOwnersManual(e) {
    var errors = '';
    if ($F('pv') == '') errors += '\n\tVehicle Model';
    if ($F('py') == '' && $F('publication') == '' && $('publication').type == "text") errors += '\n\tModel Year OR Publication Number';
    if ($F('py') == '' && $('publication').type == "hidden") errors += '\n\tModel Year';
    if (errors != '') {
      alert('You forgot to enter some important information:\n'+errors);
      if (e) { Event.stop(e); }
      return false;
    } else {
      return true;
    }
  }
  
  /* validate dealer gadgets */
	function initDealerGadgets() {
		var dealerGadget = $('dealerFormGadget');
		if (dealerGadget) {
			dealerGadget.observe('submit', validateDealerZip);
      dealerGadget.select("a.submit").each(function(link){
        link.observe('click',function(e) {
          Event.stop(e);
          if (validateDealerZip()) {
            dealerGadget.submit();
          }
        });
      });
		}
	}

  function validateDealerZip(e) {
    var errors = '';
    if ($F('zipcode') == '') { errors = 'Please enter a Zip Code.'; }
    if (!/^\d{5}([\-]\d{4})?$/.test($F('zipcode')) && $F('zipcode') != '') {
      errors = 'Please enter a valid 5-digit Zip Code.';
    }
    if (errors != '') {
      if (e) { Event.stop(e); }
      alert(errors);
      return false;
    } else { return true; }
  }


})();  

// legacy window functions
function MM_openBrWindow(theURL,winName,features) { //v2.0
  newWindow = window.open(theURL,winName,features);
  newWindow.focus();
}

function openInterstitial(URL){
  instWin = window.open('/interstitial.php?targetURL='+URL, "instWin", "height=460,width=800,scrollbars=1,toolbar=1,location=1,menubar=1,resizable=1,top=10,left=10")
  instWin.focus();
}

function popupWindow(url) {
  newWindow = window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width=600,height=500,screenX=150,screenY=150,top=150,left=150');
  newWindow.focus();
}

function printWindow() {
  bV = parseInt(navigator.appVersion); 
  if (bV >= 4) window.print();
}

function loadinparent(url, closeSelf){
	self.opener.location = url;
	if(closeSelf) self.close();
}

function initAnalytics() {
	// GLOBAL ANALYTICS EVENTS
	// FOOTER LINKS
	Event.condObserve('ftTcomLnk', "click", function(){
		TOOSite.analytics.sendEvent({
			pageName: TOOSite.channel + " : Footer : Toyota.com"
		});
	});
	
	Event.condObserve('financialLnk', "click", function(){
		TOOSite.analytics.sendEvent({
			pageName: TOOSite.channel + " : Footer : TFS"
		});
	});
	
	Event.condObserve('ftWarrantyLnk', "click", function(){
		TOOSite.analytics.sendEvent({
			pageName: TOOSite.channel + " : Footer : Warranty"
		});
	});
	
	Event.condObserve("ftContactLnk", "click", function(){
		TOOSite.analytics.sendEvent({
			pageName: TOOSite.channel + " : Footer : Contact"
		});
	});
	
	Event.condObserve("smgLnk", "click", function(){
		TOOSite.analytics.sendEvent({
			pageName: TOOSite.channel + " : Maintenance"
		});
	});
	
	Event.condObserve("vehRefGuideLnk", "click", function(){
		TOOSite.analytics.sendEvent({
			pageName: TOOSite.channel + " : Header : Vehicle Reference Guide"
		});
	});
	
	Event.condObserve("storiesLnk", "click", function(){
		TOOSite.analytics.sendEvent({
			pageName: TOOSite.channel + " : Header : Stories"
		});
	});
	
	var serviceBanner = $('serviceBanner');
	if(serviceBanner) {
		serviceBanner.observe("click", function(){
			TOOSite.analytics.sendEvent({
				pageName: TOOSite.channel + " : Due for Service Link"
			});
		});
	}
	
				
	
	// RAP COLLINS LINKS
	// parse the uri
	var urlParams = window.location.toString().toQueryParams();
	if (urlParams.regsuccess == 'true') {	
		TOOSite.analytics.sendEvent({
			events: "event1",
			pageName: TOOSite.channel + " : Registration Complete"
		});
	}
	
	if (urlParams.loginsuccess == 'true') {
		TOOSite.analytics.sendEvent({
			events: "event2",
			pageName: TOOSite.channel + " : Login Complete"
		});
		
	}
	
}

function submitForm(formId, elementId, val) {
	$(elementId).value = val;
	$(formId).submit();	
}

// REMEMBER ME FUNCTIONS:
function createCookie(name,value,days) {
	
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	if (document.cookie.indexOf(nameEQ) == -1) {
    	return '';
    }
    
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



function createRememberMeCookie(value) {
	createCookie('theUsername', value, 365);
}

function deleteRememberMeCookie() {
	eraseCookie('theUsername');
}

function readRememberMeCookie() {
	return readCookie('theUsername');
}
//End REMEMBER ME

//FUNCTIONS FOR LOGIN FORM TO SUBMIT WHEN ENTER BUTTON IS PRESSED
	if ("HTMLElement" in window) {
		HTMLElement.prototype.click = function() {
			var evt = this.ownerDocument.createEvent('MouseEvents');
			evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
			this.dispatchEvent(evt);
		} 
	}

	function clickSubmitOnEnter(e) {
		if (e.keyCode == 13) {
			$('loginBtn').click();
		}
	}
