var GLOBAL_font_adjustment = 1;
var GLOBAL_font_default = 12;
var GLOBAL_font_cookie = 'ep-rz-tx';

/* Setup common page elements *after* the page loads */
/* Note: This is done to ensure all elements are in DOM before attempting to manipulate them */
Event.observe(window, 'load', function() {
	/* Fix Multi-Column Styles if .helperMod is present */
	fixColumns('#content .section', '#content .helperMod', 'helperMod', 'twoColumn');

	/* Register Popup/Newpage Links */
	Popup.register(new PopupWindow('helpcenter', 				'helpCenter.jspx', {width: 850, height: 550, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('faq', 						'faq.jspx', {width: 850, height: 550, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('contactus', 				'contactus.jspx', {width: 850, height: 550, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('forgotpassword', 			'flowAction.jspx?_flowId=forgotPassword', {width: 850, height: 550, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('forgotMemberId', 			'flowAction.jspx?_flowId=forgotMemberId', {width: 850, height: 550, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('enrollment-core', 			siteRoot + '/flowAction.jspx?_flowId=enrollment', {width: 850, height: 550, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('enrollment-mastercard', 	'https://www.esnapw.com/rses/ESnapServlet?MerchantNumberSent=99994', {fullWindow: true}));
	Popup.register(new PopupWindow('newmember-core', 			'flowAction.jspx?_flowId=activation', {width: 850, height: 550, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('newmember-business', 		'flowAction.jspx?_flowId=activation', {width: 850, height: 550, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('store-locator', 			'http://www.bestbuy.com/site/olspage.jsp?id=cat12090&type=page', {fullWindow: true}));
	Popup.register(new PopupWindow('weekly-insert', 			'http://bestbuy.shoplocal.com/bestbuy/new_user_entry.aspx?adref=header', {fullWindow: true}));
	Popup.register(new PopupWindow('member-id', 				'memberIdCard.jspx', {width: 240, height: 160, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('ordernumber', 				'displayImage.jspx?type=1', {width: 700, height: 300, scrollbars: 'yes',resizable: 'yes'}));
	Popup.register(new PopupWindow('customerservicepin', 		'displayImage.jspx?type=2', {width: 450, height: 750, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('wheretofind', 				'wheretofind.jspx', {width: 240, height: 160, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('displayImage', 				'', {width: 785, height: 700, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('displayPdf', 				'', {width: 785, height: 600, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('cservertc', 						'cservertc.jspx', {width: 850, height: 550, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('gamerstc', 						'gamerstc.jspx', {width: 850, height: 550, scrollbars: 'yes', resizable: 'yes'}));
	Popup.register(new PopupWindow('showVideo', 						'showVideo.jspx', {width: 340, height: 260}));

	/* Setup Saved Text Size */
	loadSavedFontSize();

	/* Setup Missing Image Defaults */
	var defaultOfferImage = 'images/offers-thumbnails/offer-bestbuy.png';
	new ImgErrorFix('div.offers div.offer img', defaultOfferImage);
	new ImgErrorFix('div.offerDetails img', defaultOfferImage);

	/* Setup Selectors */
	new SelectorUI('div.programOverview .type', {activeClass: 'selectedType'});
	
	setupQuickTab();
});

function setupQuickTab() {
	if($$('input[name="phone1"]').size() > 0) {
		var phone1 = $$('input[name="phone1"]')[0];
		var phone2 = $$('input[name="phone2"]')[0];
		var phone3 = $$('input[name="phone3"]')[0];
		
		quickTab(phone1, phone2, 3);
		quickTab(phone2, phone3, 3);
	}
	
	if($$('input[name="cellPhone1"]').size() > 0) {
		var cphone1 = $$('input[name="cellPhone1"]')[0];
		var cphone2 = $$('input[name="cellPhone2"]')[0];
		var cphone3 = $$('input[name="cellPhone3"]')[0];
		
		quickTab(cphone1, cphone2, 3);
		quickTab(cphone2, cphone3, 3);
	}
}

function quickTab(field, nextfield, charcount) {
	Event.observe(field, 'keyup', function(event) {
		var currentfield = Event.element(event);
		if(currentfield.getValue().length >= charcount) {
			nextfield.activate();
		}
	});
}


function signUpLink(signUpLink) {
	
	
	if (signUpLink == "enrollment-core" ) 
	{
		window.location = "flowAction.jspx?_flowId=enrollment";
	}
	else if (signUpLink == "enrollment-mastercard")
	{
		window.location = "https://www.esnapw.com/rses/ESnapServlet?MerchantNumberSent=99994";
	}
	}

function fixColumns(selector, colSelector, colClass, applyClass) {
	var colElements = $$(colSelector);
	if (colElements.size() > 0) {
		var selectedElements = $$(selector);
		selectedElements.each(function(item) {
			if(!item.hasClassName(colClass)) {
				item.addClassName(applyClass);
			}
		}.bind(this));
	}
}

function defaultFont() {
	changeFontSize(GLOBAL_font_default);
}

function increaseFont() {
	changeFontSize(getFontSize() + GLOBAL_font_adjustment);
}

function decreaseFont() {
	changeFontSize(getFontSize() - GLOBAL_font_adjustment);
}

function changeFontSize(size) {
	var fontElement = $$('html')[0];
	fontElement.style.fontSize = size + 'pt';
	saveFontSize(size);
}

function getFontSize() {
	var fontElement = $$('html')[0];
	var currentSize = GLOBAL_font_default;
	if(fontElement.style.fontSize) {
		currentSize = fontElement.style.fontSize;
		currentSize = parseInt(currentSize.substr(0, currentSize.length - 2));
	}
	return currentSize;
}

function loadSavedFontSize() {
	var savedFontSize = getSavedFontSize();
	if(savedFontSize != null) {
		changeFontSize(savedFontSize);
	}
}

function saveFontSize(size) {
	getCookieJar().put(GLOBAL_font_cookie, size);
}

function getSavedFontSize() {
	return getCookieJar().get(GLOBAL_font_cookie);
}

function getCookieJar() {
	options = {
		expires: '157680000',  	// time in seconds (5 Years) (defualt: 3600)
		path: '/',     			// cookie path
		domain: '',   			// cookie domain
		secure: ''    			// secure ?
	};
	return new CookieJar(options);
}

function submitLogin(){
	document.loginForm.submit();
}

function validateInterestsSurvey(formName) {
	var form = $(formName);
	var radios = Form.getInputs(form, "radio");
	if(radios.size() > 0) {
		var errorField = radios.first().ancestors().first().getElementsBySelector('.errorMarker').first();
		var isSelected = false; 
		radios.each(function(item){ if(item.checked){isSelected = true;} });
		if(!isSelected) {
			addError(errorField, "This question is required.");
		}
		else {
			removeError(errorField);
		}
		return isSelected;
	}
	else {
		return true;
	}
}


function validateBusinessSurvey(formName) {
	var form = $(formName);
	var field1 = form['_SV_OE_10854']; //Num Employees
	var field2 = form['_SV_OE_10870']; //Date Started
	var field3 = form['_SV_RB_10855']; //Biz Type
	return validateSurvey(field1, field2, field3);
}

function validateSurvey(field1, field2, field3) {
	var valid = true;
	if(field1 != null && field2 != null && field3 != null) {
		if(!isNumber($F(field1))) { valid = false; addError(field1, 'Please enter a number.'); } else {removeError(field1);}
		if(!isValidDate($F(field2))) { valid = false; addError(field2, 'Please enter a valid date - MM/DD/YYYY'); } else {removeError(field2);}
		if(isEmpty($F(field3))) { valid = false; addError(field3, 'Please choose one.'); } else {removeError(field3);}
	}
	return valid;
}

function isEmpty(value) {
	var isValid = false;
	if(value == null) {isValid = true;}
	if(value == "") {isValid = true;}
	return isValid;
}

function isNumber(value) {
	var isValid = true;
	if(isEmpty(value)) {isValid = false;}
	if(isNaN(value)) {isValid = false;}
	return isValid;
}

function isValidDate(value) {
	var isValid = true;
	if(isEmpty(value)) {isValid = false;}
	var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
	if(!value.match(RegExPattern)) {isValid = false;}
	return isValid;
}

function addError(field, msg) {
	var sibs = field.nextSiblings();
	var found = false;
	sibs.each(function(item) {
		if(item.hasClassName('error')) {found = true;}
	});
	if(!found) {
		new Insertion.After(field, '<div class="error">' + msg + '</div>');
	}
}

function removeError(field) {
	var sibs = field.nextSiblings();
	sibs.each(function(item) {
		if(item.hasClassName('error')) {item.remove();}
	});
}