try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {}

/**
 * @author Mathieu Beausoleil
 */
ShbCore = {
	dependencies: [],
	postInitHook: [],
	ready: false,

	/**
	 * This method will check if dependencies are respected and then call the postInit method
	 * to initialize the system.
	 * 
	 * @todo Rename this method to preInit() and remove the postInit() call
	 */
	init: function() {
		 if (!this.ready) {
			 this.checkDependencies();
			 return false;
		 }
		 
		 this.postInit();
	},
	
	/**
	 * Initializing the system.
	 * 
	 * @todo Move everything in seperate method
	 * @todo Rename this method to init and call the preInit() method
	 */
	postInit: function() {
		if ($.browser.chrome == undefined) {
			var userAgent = navigator.userAgent.toLowerCase();
			$.browser.chrome = /chrome/.test( userAgent );
		}
		
		 $(document).ready(function(){
			$('#lMore ul a, a[href*="http://"]:not(a[href^="http://' + window.location.host + '"])').click(function(event){
				event.preventDefault();
				if ($(this).is('#lMore ul li.customerSupport a')) {
					window.open(this.href, '_blank', 'width=865,height=500,scrollbars=yes');
					event.preventDefault();
				} else if ($(this).is('#lMore ul a')) {
					window.open(this.href, '_blank', 'width=600,height=400,scrollbars=yes');
					event.preventDefault();
				} else {
					window.open(this.href);
				}
			});

			$('input[name*="credit"][name*="number"],input[name*="credit"][name*="cvv"]').attr('autocomplete', 'off');

			if (ShbCore.postInitHook.length > 0) {
				for(myInt=0;myInt<ShbCore.postInitHook.length;myInt++) {
					hook = ShbCore.postInitHook[myInt];
					
					ShbCore.executePostInitCallback(hook);
				}
			}
			
			$('form#bmiForm').submit(function(event){
				myHeightBigUnitMultiple = $('input[name="bmi[measures]"]').val() == 'metric' ? 100 : 12;
				myHeightBigUnit = parseInt($('select[name="bmi[height][bigunit]"]').val());
				myHeightBigUnit = (isNaN(myHeightBigUnit) ? 0 : myHeightBigUnit);
				myHeightSmallUnit = parseInt($('select[name="bmi[height][smallunit]"]').val());
				myHeight = (myHeightBigUnit * myHeightBigUnitMultiple) + myHeightSmallUnit
				myWeight = parseInt($('input[name="bmi[weight][current]"]').val());
				myWeightGoal = parseInt($('input[name="bmi[weight][goal]"]').val());
				myAge = parseInt($('input[name="bmi[age]"]').val());
				myGender = $('select[name="bmi[gender]"]').val();
				
				isValidWeightGoal = !isNaN(myWeightGoal) && myWeightGoal > 0;
				
				userParams = {
					height: myHeight,
					weight: myWeight,
					age: myAge,
					gender: myGender
				};
				
				isValidBmi = ShbCore.Widget.Bmi.isValid(userParams);
				isValidBmr = ShbCore.Widget.Bmr.isValid(userParams);

				if (!isValidBmi || !isValidBmr || !isValidWeightGoal) {
					
					event.preventDefault();
					
					$('form#bmiForm div.field.errors').removeClass('errors');
					$('form#bmiForm ul.errors').remove();
					
					errors = new Array;
					
					if (!isValidWeightGoal) {
						errors.push({field:'weightGoal',message:'Weight Goal must be a number'});
					}
					
					errors = errors.concat(ShbCore.Widget.Bmi.getErrors());
					errors = errors.concat(ShbCore.Widget.Bmr.getErrors());
					
					for(i=0;i<errors.length;i++) {
						switch(errors[i].field) {
							case 'weight':
								myContainer = $('input[name="bmi[weight][current]"]').parents('div.elements');
								break;
							case 'weightGoal':
								myContainer = $('input[name="bmi[weight][goal]"]').parents('div.elements');
								break;
							case 'height':
								myContainer = $('select[name="bmi[height][smallunit]"]').parents('div.elements');
								break;
							case 'age':
								myContainer = $('input[name="bmi[age]"]').parents('div.elements');
								break;
							case 'gender':
								myContainer = $('select[name="bmi[gender]"]').parents('div.elements');
								break;
						}
						error = '<li>' + errors[i].message + '</li>';

						if ($('ul.errors', myContainer).length == 0) {
							error = '<ul class="errors">' + error + '</ul>';
							myContainer.append(error);
						}

						myContainer.parents('div.field').addClass('errors');
					}

					alert("There is error(s) in the form. Please verify and try again.");
				}
			});
		});
	},

	executePostInitCallback: function(hook) {
		isConditionRespected = eval("(" + hook.condition + ")");

		if (isConditionRespected) {
			eval(hook.callback + "()");
		}
	},
	
	/**
	 * Verify if JS dependencies are loaded or wait
	 */
	checkDependencies: function() {
		respectedDependencies = 0;
		for(i=0;i<this.dependencies.length;i++) {
			try {
				dependency = eval(this.dependencies[i]);
				respectedDependencies++;
			} catch(e) {}
		}
		
		respected = (respectedDependencies == this.dependencies.length);
		
		if (!respected) {
			setTimeout("ShbCore.checkDependencies()", 20);
		} else {
			this.ready = true;
			this.postInit();
		}
	},
	
	loadLibrary: function(file, dependency) {
		if (dependency != undefined) {
			this.dependencies.push(dependency);
		}
		
		library = document.createElement('script');
		library.src = file;
		library.type = 'text/javascript';
		document.getElementsByTagName("head")[0].appendChild(library);
	},
	Form: {},
	Widget: {
		Retention: {
			redirectUrl: null,
			message: null,
			init: function(message, redirectUrl){
				this.message = message;
				if (redirectUrl != undefined) {
					this.redirectUrl = redirectUrl;
				}

				window.onbeforeunload = ShbCore.Widget.Retention.trigger;
				this.preventRetentionOnLocalEvent();
			},
			preventRetentionOnLocalEvent: function() {
				$('a').click(function(){ window.onbeforeunload = null });
				$('form').click(function(){ window.onbeforeunload = null });
			},
			trigger: function(){
				window.onbeforeunload = null;
				
				$.post('./markLeadAs', {'status': 'unmotivated'});
				
				if (ShbCore.Widget.Retention.redirectUrl != null) {
					window.location.href = ShbCore.Widget.Retention.redirectUrl;
				}
				
				return ShbCore.Widget.Retention.message;
			}
		},
		Upsell: {
			timer: null,
			widgetIdentifier: 'oneClickOrderWidget',
			markup: '<div id="oneClickOrderWidget"><div class="background">&nbsp;</div><div class="container"><div class="products"></div><a href="#" class="buyNow" onclick="ShbCore.Widget.Upsell.buyProduct(); return false;"><span>Buy Now</span></a><a href="#" class="noThanks" onclick="ShbCore.Widget.Upsell.noThanks(); return false;"><span>No Thanks</span></a><div class="loader"><span>Loading...</span></div></div></div>',
			init: function(){
				if ($('#' + this.widgetIdentifier).length == 0) {
					$('body').append(this.markup);
					this.resize();
				}
			},
			getURLParam: function(strParamName){
				var strReturn = "";
				var strHref = window.location.href;
				if ( strHref.indexOf("?") > -1 ){
					var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
					var aQueryString = strQueryString.split("&");
					for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
						if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
							var aParam = aQueryString[iParam].split("=");
							strReturn = aParam[1];
							break;
						}
					}
				}
				return unescape(strReturn);
			},
			resize: function(){
				windowHeight = $('html').height().toString() + 'px';
				$('#' + this.widgetIdentifier).height(windowHeight);
				$('#' + this.widgetIdentifier + ' .background').height(windowHeight);
			},
			show: function(){
				$('html').css('overflow', 'hidden');
				$('#' + this.widgetIdentifier).show();

				this.nextProduct();
			},
			hide: function(){
				$('html').css('overflow-y', 'auto');
				$('#' + this.widgetIdentifier).hide();
			},
			addOffer: function(productName){
				switch(productName){
					case 'prdeliveryxt':
					case 'prdeliverynh':
						productId = 85;
						cycleId = 90;
						break;
					case 'discreetshippingnh':
					case 'discreetshippingxt':
						productId = 88;
						cycleId = 87;
						break;
					case 'xtprogram':
						productId = 65;
						cycleId = 24;
						break;
					case 'totalean':
						productId = 44;
						cycleId = 22;
						break;
					case 'flushex':
						productId = 43;
						cycleId = 22;
						break;
					case 'mhvex':
						productId = 86;
						cycleId = 47;
						break;
					case 'mhdap':
						productId = 87;
						cycleId = 47;
						break;
				}
				
				$('#oneClickOrderWidget .products').prepend('<div class="product" id="p-' + productName + '" rel="pid=' + productId + ',cid=' + cycleId + ',t=' + productName + '">&nbsp;</div>');
			},
            addOfferData: function(productName,productId,cycleId,oldCycleId){
                $('#oneClickOrderWidget .products').prepend('<div class="product" id="p-' + productName + '" rel="pid=' + productId + ',cid=' + cycleId + ',ocid=' + oldCycleId + ',t=' + productName + '">&nbsp;</div>');
            },
			nextProduct: function() {
				this.timer = new Date();
				
				$('#oneClickOrderWidget .products .product:not(.active)').css('zIndex', '1');
				currentProduct = $('#oneClickOrderWidget .products .product.active').css('zIndex', '3');
				
				if (currentProduct.length == 1) {
					nextProduct = $('#oneClickOrderWidget .products .active').next();
				} else {
					nextProduct = $('#oneClickOrderWidget .products .product:first-child');
				}
				
				if (nextProduct.length == 0) {
					this.hide();
					return false;
				}
				
				nextProduct.css('zIndex', '2').addClass('active');
				currentProduct.fadeOut("normal", function(){
					$(this).removeClass('active');
				});
			},
			displayError: function(message) {
				if (!message) {
					message = "Unable to complete this action.\nThis product has NOT been billed.";
				}
				
				this.hide();
				alert(message);
			},
	
			showLoader: function(){
				$('#oneClickOrderWidget .container > a').hide();
				$('#oneClickOrderWidget .container > .loader').show();
			},
			hideLoader: function(){
				$('#oneClickOrderWidget .container > a').show();
				$('#oneClickOrderWidget .container > .loader').hide();
			},
			getDelay: function(){
				now = new Date();
				delay = (now.getTime() - this.timer.getTime()) / 1000;
				this.timer = null;
				return Math.round(delay);
			},
			noThanks: function() {
				var delay = this.getDelay();
				
				this.nextProduct();
				actualTour = $('#oneClickOrderWidget .products .active').attr('id').replace('p-', '');
				try {
					pageTracker._trackEvent('Upsell', 'Not Interested', actualTour, delay);
				} catch(err) {}
			},
			buyProduct: function() {
				var delay = this.getDelay();
				this.showLoader();
				
				var orderData = {
					'tid': ShbCore.Widget.Upsell.getURLParam('tid'),
					'mid': ShbCore.Widget.Upsell.getURLParam('mid'),
					'email': ShbCore.Widget.Upsell.getURLParam('email')
				};
	
				productData = nextProduct.attr('rel').split(',');
				for(i=0;i < productData.length;i++) {
					myParam = productData[i].split('=');
					if (myParam[0] == 't') {
						var actualTour = myParam[1];
					}
					eval('orderData.' + myParam[0] + ' = "' + myParam[1] + '"');
				}
				
				$.post('./oneclickpurchase', orderData, function(data, textStatus){
					ShbCore.Widget.Upsell.hideLoader();
					if (data.status == 1) {
						ShbCore.Widget.Upsell.nextProduct();
						try {
							pageTracker._trackEvent('Upsell', 'Payment', actualTour, delay);
							
							eval(data.tracking);
						} catch(err) {}
					} else {
						if (data.message) {
							ShbCore.Widget.Upsell.displayError(data.message);
							try {
								pageTracker._trackEvent('Upsell', 'Error (' + data.message + ')', actualTour, delay);
							} catch(err) {}
						} else {
							ShbCore.Widget.Upsell.displayError();
							try {
								pageTracker._trackEvent('Upsell', 'Error', actualTour, delay);
							} catch(err) {}
						}
					}
				}, "json");
				
			}
		},
		/**
		 * Body Mass Index calculation function.
		 * 
		 * How it work:
		 * Just call ShbCore.Widget.Bmi.calculate(params) and the system will
		 * return the value (float) or false (in case of errors).
		 * 
		 * The errors may be retreived with ShbCore.Widget.Bmi.getErrors();
		 * 
		 * Params must be in the following format:
		 *  
		 * params = {
		 * 		height: 69, // required inches int
		 * 		weight: 145 // required pounds int
		 * }
		 * 
		 * @author Mathieu Beausoleil
		 */
		Bmi: {
			errors: [],
			
			/**
			 * Verify if the user params respect the required structure and prepare
			 * errors messages if necessary.
			 * 
			 * @param object
			 * @return bool
			 */
			isValid: function(params) {
				errors = [];
				
				if (params == undefined) {
					errors.push({message: "Params must be passed to ShbCore.Widget.Bmi API"});
				} else {
					params.weight = parseInt(params.weight);
					params.height = parseInt(params.height);
					
					if (params.weight == undefined || isNaN(params.weight) || params.weight <= 0) {
						errors.push({field: 'weight', message: "Weight must be a number"});
					}
					if (params.height == undefined || isNaN(params.height) || params.height <= 0) {
						errors.push({field: 'height', message: "Height must be a number"});
					}
				}
				
				this.errors = errors;
				return (errors.length == 0);
			},

			/**
			 * Return the errors generated by isValid()
			 */
			getErrors: function() {
				return this.errors;
			},
			
			/**
			 * Calculate the BMI
			 * 
			 * @param object (see Bmi documentation)
			 * @return float|false
			 */
			calculate: function(params) {
				if (!this.isValid(params)) return false;
				
				return (parseInt(params.weight) / Math.pow(parseInt(params.height), 2)) * 703;
			}
		},

		/**
		 * Basal Metabolic Rate calculation function.
		 * 
		 * How it work:
		 * Just call ShbCore.Widget.Bmr.calculate(params) and the system will
		 * return the value (float) or false (in case of errors).
		 * 
		 * The errors may be retreived with ShbCore.Widget.Bmr.getErrors();
		 * 
		 * Params must be in the following format:
		 *  
		 * params = {
		 * 		gender: 'male', // required male or female string
		 * 		age: 25, // required int
		 * 		height: 69, // required inches int
		 * 		weight: 145 // required pounds int
		 * }
		 * 
		 * @author Mathieu Beausoleil
		 */
		Bmr: {
			errors: [],

			/**
			 * Verify if the user params respect the required structure and prepare
			 * errors messages if necessary.
			 * 
			 * @param object
			 * @return bool
			 */
			isValid: function(params) {
				errors = [];
				
				if (params == undefined) {
					errors.push({message: "Params must be passed to ShbCore.Widget.Bmr API"});
				} else {
					params.age = parseInt(params.age);
					params.weight = parseInt(params.weight);
					params.height = parseInt(params.height);
					if (params.gender == undefined || params.gender != 'male' && params.gender != 'female') {
						errors.push({field: 'gender', message: "Gender must be male or female"});
					}
					if (params.age == undefined || isNaN(params.age) || params.age <= 0) {
						errors.push({field: 'age', message: "Age must be a number"});
					}
					if (params.weight == undefined || isNaN(params.weight) || params.weight <= 0) {
						errors.push({field: 'weight', message: "Weight must be a number"});
					}
				}
				
				this.errors = errors;
				return (errors.length == 0);
			},
			
			/**
			 * Return the errors generated by isValid()
			 */
			getErrors: function() {
				return this.errors;
			},
			
			/**
			 * Calculate the BMR
			 * 
			 * @param object (see Bmr documentation)
			 * @return float|false
			 */
			calculate: function(params) {
				if (!this.isValid(params)) return false;
				
				if (params.gender == 'male') {
					baseNumber = 66;
					poundsProduct = 6.23;
					heightProduct = 12.7;
					ageProduct = 6.8;
				}
				else if (params.gender == 'female') {
					baseNumber = 655;
					poundsProduct = 4.35;
					heightProduct = 4.7;
					ageProduct = 4.7;
				}
				
				return baseNumber + (poundsProduct * parseInt(params.weight)) + (heightProduct * parseInt(params.height)) - (ageProduct * parseInt(params.age));
			}
		}
	}
}


function landingBmiAddMeasureUnits() {
	changeUnitMarkup = '';
	changeUnitMarkup += '<div class="field measure">';
	changeUnitMarkup += '	<label>Measures</label>';
	changeUnitMarkup += '	<div class="elements">';
	changeUnitMarkup += '		<label for="bmi-measures-imperial" class="imperial">';
	changeUnitMarkup += '			<input type="radio" name="bmi[measures]" id="bmi-measures-imperial" value="imperial" checked="checked" />';
	changeUnitMarkup += '			<span>Imperial</span>';
	changeUnitMarkup += '		</label>';
	changeUnitMarkup += '		<label for="bmi-measures-metric" class="metric">';
	changeUnitMarkup += '			<input type="radio" name="bmi[measures]" id="bmi-measures-metric" value="metric" />';
	changeUnitMarkup += '			<span>Metric</span>';
	changeUnitMarkup += '		</label>';
	changeUnitMarkup += '	</div>';
	changeUnitMarkup += '</div>';

	$('#bmiForm fieldset.profile .fields').prepend(changeUnitMarkup);

	var metricBigUnits = '<option></option>';
	for(i=0;i<=2;i++) {
		metricBigUnits += '<option>' + i + '</option>';
	}
	var metricSmallUnits = '<option></option>';
	for(i=90;i<250;i++) {
		metricSmallUnits += '<option>' + i + '</option>';
	}
	var imperialBigUnits = '<option></option>';
	for(i=4;i<=7;i++) {
		imperialBigUnits += '<option>' + i + '</option>';
	}

	var imperialSmallUnits = '<option></option>';
	for(i=0;i<12;i++) {
		imperialSmallUnits += '<option>' + i + '</option>';
	}

	$('input[name="bmi[measures]"]').click(function(){
		switch($(this).val()) {
			case 'metric':
				$('div.goal .elements label span, div.weight .elements label span').text('kg');
				$('label[for="bmi-height-bigunit"] span').text('m');
				$('label[for="bmi-height-smallunit"] span').text('cm');
				$('label[for="bmi-height-bigunit"]').hide();
				$('label[for="bmi-height-bigunit"] select').html(metricBigUnits);
				$('label[for="bmi-height-smallunit"] select').html(metricSmallUnits);
				$('label[for="bmi-height-bigunit"] abbr').attr('title', 'meters').hide();
				$('label[for="bmi-height-smallunit"] abbr').attr('title', 'centimeters');
				$('abbr[title="pounds"]').attr('title', 'kilograms');
				break;
			default:
				$('label[for="bmi-height-bigunit"]').show();
				$('label[for="bmi-height-bigunit"] select').html(imperialBigUnits);
				$('label[for="bmi-height-smallunit"] select').html(imperialSmallUnits);
				$('label[for="bmi-height-bigunit"] abbr').attr('title', 'feets').show();
				$('label[for="bmi-height-smallunit"] abbr').attr('title', 'inches');
				$('abbr[title="kilograms"]').attr('title', 'pounds');
				$('label[for="bmi-height-smallunit"] span').text('in');
				$('label[for="bmi-height-bigunit"] span').text('ft');
				$('div.goal .elements label span, div.weight .elements label span').text('lbs');
		}
	});
	$('input[name="bmi[measures]"]:checked').trigger('click');
	
}

ShbCore.loadLibrary('/library/jquery-1.3.2.min.js', '$');

ShbCore.postInitHook.push({'condition': "$('body#landing form#bmiForm').length == 1", 'callback': 'landingBmiAddMeasureUnits'});
function paymentFormPostInit() {
	$('#billing div.field:not(.textual)').hide();
	$('#billing div.field.textual').show();
	
	$('#billing div.field.textual .edit').click(function(){
		$('#billing div.field.textual').hide();
		$('#billing div.field:not(.textual)').show();
	});
	
	$('#supplies input:checked').parents('div.element').addClass('highlight');
	$('#supplies input').change(function(){
		$('#supplies div.highlight').removeClass('highlight');
		$('#supplies input:checked').parents('div.element').addClass('highlight');
	});
	$('#supplies div.element').css('cursor', 'pointer').click(function(){
		radioButton = $('input', this);
		radioButton[0].checked = 'checked';
		radioButton.trigger('change');
	});
}
ShbCore.postInitHook.push({'condition': "$('body#payment form#purchaseForm').length == 1", 'callback': 'paymentFormPostInit'});



function appendLivePerson() {	
	livechatUrl = "https://server.iad.liveperson.net/hc/5896788/?cmd=file&file=visitorWantsToChat&site=5896788&SESSIONVAR!skill=" + ((typeof livepersonSkill) == 'string' ? livepersonSkill : 'default') + "&referrer=" + escape(document.location);

	livePersonScript = '';
	livePersonScript += '<!-- BEGIN LivePerson Button Code -->' + "\n";
	livePersonScript += '<div id="livePersonContainerElement"><a href="#" onclick="window.open(\'' + livechatUrl + '\',\'chat5896788\',\'width=475,height=400,resizable=yes\'); return false;"><span>Live Chat</span></a></div>' + "\n";
	livePersonScript += '<!-- END LivePerson Button code -->' + "\n";
	
	
	$('body').append(livePersonScript);
}
ShbCore.postInitHook.push({'condition': "$('body').length == 1", 'callback': 'appendLivePerson'});


ShbCore.init();