/////////////////////////////////////////////////////////////////////////////
// - CONSTANTS - ////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
var URL='http://www.dropweight.com';
var IE6=/MSIE 6/i.test(navigator.userAgent) ? true : false;

/////////////////////////////////////////////////////////////////////////////
// - Live Function (Performance improvement) - //////////////////////////////
/////////////////////////////////////////////////////////////////////////////

$.live = function(selector, type, fn)
{
    var r = $([]);
    r.selector = selector;
    if(type && fn) {
        r.live(type, fn);
    }
    return r;
};

/////////////////////////////////////////////////////////////////////////////
// - USEFUL FUNCTIONS - /////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Performs useful fixes (text replacement, PNG fix, Ajax links hover state)
function performFixes() {
		
	// Auto wrap additional layout divs

	//MOVED TO PHP QUERY OUTPUT BUFFER (Although this is still used for JSON incoming files)
	eleToWrap = $('.fullWidth, .threeQuartersWidth, .twoThirdsWidth, .halfWidth, .thirdWidth, .quarterWidth').not('.fixed');
	eleToWrap.wrapInner('<div class="innerBottom"><div class="innerWidth"></div></div>');
	
	eleToWrap.each(function(){
		this.className += ' fixed';
	});

	
	Cufon.set('fontFamily', 'bliss-bold');
	Cufon.replace('h2 span.pink, #user_info h2, #popup_title, .large_quote, .testimonial_block h4, .bold_replace');
	
	// Cufon.replace('.x_small_button, .small_button, .medium_button, .large_button, .x_large_button');
	Cufon.set('fontFamily', 'bliss-light');
	Cufon.replace('h2, h3:not(.bold_replace), h4:not(.bold_replace)');// #user_info h3
	Cufon.replace('.main_info_title, .view_enquiry_label, .view_enquiry_label_block, .section_links li a');
	Cufon.replace('#nav a, div.second_level_nav a, .testimonial_block .user_programme',{fontSize: '12px'})
	Cufon.replace('.ofp_option_name, .ofp_option_quantity, .ofp_totals_label, .ofp_totals_value, .fp_option_name');
	
	// PNG Fix - Check for IE6
	if(IE6) {
		DD_belatedPNG.fix('.png');// Apply fix to any elements with png class		
	}
	
	// Add href attributes to any anchors missing them (to make link clickable)
	$('a').not('a[href]').attr('href', '#').click(function() {
		return false;													   
	}); 	
	
	// Mute flash if this is pressed
	$.live('.mute_flash', 'click', function(event) {
		if(window.flash_cont) window.document["flash_cont"].SetVariable("muted_external", true);
		if(document.flash_cont) document.flash_cont.SetVariable("muted_external", true);
		window.open($(this).attr('href'));
        return false;
	});
	
	// Open links with rel="external" as a pop-up
	$.live('a[rel="external"]', 'click', function(event) {
        window.open($(this).attr('href'));
        return false;
	});	
	
	// Make our recording links open in a new window
	$.live('a.recording_link', 'click', function(event) {	
		// Get the href attribute
		var target=$(this).attr('href');
		window.open(target, "recording", "status=0, toolbar=0, location=0, menubar=0, direcotories=0, resizable=0, scrollbars=0, height=230, width=280");
		return false;
	});
	
}
// Checks whether a date is valid according to the gregorian calendar
function checkDate(day, month, year) {
	var myDate = new Date();
	myDate.setFullYear( year, (month - 1), day );
	return ((myDate.getMonth()+1) == month && day<32); 
}
function convertPoundsAndKilograms(pounds, kilograms) {
	var factor=2.20462262;
	if(pounds) {
		return !isNaN(pounds) && pounds>0 ? (pounds/factor) : false;
	} else {
		return !isNaN(kilograms) && kilograms>0 ? (kilograms*factor) : false;
	}
}
function convertInchesAndCentimeters(inches, centimeters) {
	var factor=2.54;
	if(inches) {
		return !isNaN(inches) && inches>0 ? (inches*factor) : false;
	} else {
		return !isNaN(centimeters) && centimeters>0 ? (centimeters/factor) : false;
	}
}
function performConversion(obj) {
	// Config settings for each unit type
	var units=[];
	units['st']		= {'dp' : 0};
	units['lb']		= {'dp' : 1};
	units['kg']		= {'dp' : 1};
	units['ft']		= {'dp' : 0};
	units['inches']	= {'dp' : 1};
	units['m']		= {'dp' : 0};
	units['cm']		= {'dp' : 1};
	
	// Get the name attribute of the box we are converting from
	var objName=obj.attr('name');
	var objUnits=objName.substring(objName.lastIndexOf('_')+1);
	// Check whether the value is invalid
	if(isNaN(obj.val()) || obj.val()=='' || Number(obj.val())<0) {
		// Set the value to zero if it is invalid
		obj.val('0');
	} else {
		// Otherwise round it to the number of dp specified in our units array
		var roundedVal=roundNumber(obj.val(), units[objUnits].dp);
		obj.val(roundedVal);	
	}
	// Grab our object value
	var objVal=Number(obj.val());
	// Grab our fields cntainer so we dont have to select it again
	var fieldWrapper=obj.parents('.form_field:first');
	// Switch depending which box we are converting from
	switch(objUnits) {
		case 'st':
			// We are in stones so convert stones to pounds and add any additional pounds specified
			var pounds=(objVal*14)+Number(fieldWrapper.find("input[name$='_lb']").val());
			// Convert our pounds to kilograms
			var convertedVal=convertPoundsAndKilograms(pounds, null);
			// Update our kgs field
			fieldWrapper.find("input[name$='_kg']").val(roundNumber(convertedVal, units['kg'].dp));
			break;
		case 'lb':
			var pounds=objVal;
			var stonesField=fieldWrapper.find("input[name$='_st']");
			// Check if there is a stones text box aswell as this lbs one
			if(stonesField.length) {
				// Dont allow 14 or more pounds if we are specifying stones
				if(pounds>=14) {
					obj.val('0');
					pounds=0;
				}
				// Add on our stones aswell
				pounds=pounds+(Number(stonesField.val())*14);
			}
			// Now convert our pounds into kilograms
			var convertedVal=roundNumber(convertPoundsAndKilograms(pounds, null),1);
			// Update our kgs field
			fieldWrapper.find("input[name$='_kg']").val(roundNumber(convertedVal, units['kg'].dp));
			break;
		case 'kg':
			// The value is in kg so we convert to stones/stones & lbs.
			var convertedVal=convertPoundsAndKilograms(null, objVal);
			// Now check whether there is a stones box or just pounds
			if(fieldWrapper.find("input[name$='_st']").length) {
				// There is a stones box so calculate the number of stones first
				var stones=Math.floor(convertedVal/14);
				var pounds=convertedVal-(stones*14);
				if(pounds==14) {
					stones++;
					pounds=0;
				}
				fieldWrapper.find("input[name$='_st']").val(roundNumber(stones, units['st'].dp));
				fieldWrapper.find("input[name$='_lb']").val(roundNumber(pounds, units['lb'].dp));
			} else {
				fieldWrapper.find("input[name$='_lb']").val(roundNumber(pounds, units['lb'].dp));				
			}
			break;
		case 'ft':
			// We are in feet so convert feet to inches and add any additional inches specified
			var inches=(objVal*12)+Number(fieldWrapper.find("input[name$='_inches']").val());
			// Convert our inches to cms
			var convertedVal=convertInchesAndCentimeters(inches, null);
			// Select our equivalent meters field
			var metersField=fieldWrapper.find("input[name$='_m']");
			// Check whether any meters fields were found
			if(metersField.length) {
				var meters=Math.floor(convertedVal/100);
				var centimters=convertedVal-(meters*100);
				metersField.val(roundNumber(meters, units['m'].dp));
				fieldWrapper.find("input[name$='_cm']").val(roundNumber(centimters, units['cm'].dp));
			} else {
				fieldWrapper.find("input[name$='_cm']").val(roundNumber(convertedVal, units['cm'].dp));
			}
			break;
		case 'inches':
			var inches=objVal;
			var feetField=fieldWrapper.find("input[name$='_ft']");
			// Check if there is a feet text box aswell as this inches one
			if(feetField.length) {
				// Dont allow 12 or more inches if we are specifying feet
				if(inches>=12) {
					obj.val('0');
					inches=0;
				}
				// Add on our feet aswell
				inches=inches+(Number(feetField.val())*12);
			}
			// Now convert our inches into centimeters
			var convertedVal=convertInchesAndCentimeters(inches, null);
			// Select our equivalent meters field
			var metersField=fieldWrapper.find("input[name$='_m']");
			// Check whether any meters fields were found
			if(metersField.length) {
				var meters=Math.floor(convertedVal/100);
				var centimters=convertedVal-(meters*100);
				metersField.val(roundNumber(meters, units['m'].dp));
				fieldWrapper.find("input[name$='_cm']").val(roundNumber(centimters, units['cm'].dp));
			} else {
				fieldWrapper.find("input[name$='_cm']").val(roundNumber(convertedVal, units['cm'].dp));
			}
		break;
		case 'm':
			// We are in meters so convert meters to cm and add any additional cm specified
			var centimeters=(objVal*100)+Number(fieldWrapper.find("input[name$='_cm']").val());
			// Convert our cms to inches
			var convertedVal=convertInchesAndCentimeters(null, centimeters);
			// Select our equivalent feet field
			var feetField=fieldWrapper.find("input[name$='_ft']");
			// Check whether any feet fields were found
			if(feetField.length) {
				var feet=Math.floor(convertedVal/12);
				var inches=convertedVal-(feet*12);
				feetField.val(roundNumber(feet, units['ft'].dp));
				fieldWrapper.find("input[name$='_inches']").val(roundNumber(inches, units['inches'].dp));
			} else {
				fieldWrapper.find("input[name$='_inches']").val(roundNumber(convertedVal, units['inches'].dp));
			}
			break;
		case 'cm':
			var centimeters=objVal;
			var metersField=fieldWrapper.find("input[name$='_m']");
			// Check if there is a meters text box aswell as this centimeters one
			if(metersField.length) {
				// Dont allow 12 or more inches if we are specifying feet
				if(centimeters>=100) {
					obj.val('0');
					centimeters=0;
				}
				// Add on our meters aswell
				centimeters=centimeters+(Number(metersField.val())*100);
			}
			// Now convert our centimeters into inches
			var convertedVal=convertInchesAndCentimeters(null, centimeters);
			// Select our equivalent feet field
			var feetField=fieldWrapper.find("input[name$='_ft']");
			// Check whether any feet fields were found
			if(feetField.length) {
				var feet=Math.floor(convertedVal/12);
				var inches=convertedVal-(feet*12);
				feetField.val(roundNumber(feet, units['ft'].dp));
				fieldWrapper.find("input[name$='_inches']").val(roundNumber(inches, units['inches'].dp));
			} else {
				fieldWrapper.find("input[name$='_inches']").val(roundNumber(convertedVal, units['inches'].dp));
			}
		break;
	}
}
// Rounds a number to a given number of decimal places
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
// Calculates the BMI for a given weight and height
function calculateBMI(weight, height) {
	if(!isNaN(weight) && weight>0 && !isNaN(height) && height>0) {
		var bmi=weight/((height/100) * (height/100));
		return roundNumber(bmi,1);
	} else {
		return false;	
	}
}
// Unserializes a name=value style string returning an object
function unserialize(url) {
	var params=url;
	if (url.match(/\?(.+)$/)) {
		// in case it is a full query string with ?, only take everything after the ?
		params = RegExp.$1;
	}
	// split the params
	var pArray = params.split("&");
	// hash to store result
	var pHash = {};
	// parse each param in the array and put it in the hash
	for(var i=0;i<pArray.length;i++) {
		var temp = pArray[i].split("=");
		pHash[temp[0]] = unescape(temp[1]);
	}
	return pHash;
}
// Performs simple validation on a set of form elements and returns true/false as to whether it passed validation
function simpleValidation(formElements) {
	var noErrors=true;
	$.each(formElements, function() {
		if($(this).val()=='') {
			// Check whether errors are there already
			if(!$(this).parents('.form_field').find('.error_msg').length) {
				// Add class to wrapper
				$(this).parents('form_field:first').children().eq(1).addClass('invalid_field');
				// Add invalid message after field
				$(this).after('<span class="error_msg"><span class="hidden">Invalid Field</span></span>');
			}
			noErrors=false;
		} else {
			$(this).parents('.form_field').find('.invalid_field').removeClass('.invalid_field');
			$(this).parents('.form_field').find('.error_msg').remove();
		}
	});
	return noErrors;
}

$.fn.clearForm = function() {
	return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form')
			return $(':input',this).clearForm();
		if (type == 'text' || type == 'password' || tag == 'textarea')
			this.value = '';
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
};

/*
 * Title Caps
 * 
 * Ported to JavaScript By John Resig - http://ejohn.org/ - 21 May 2008
 * Original by John Gruber - http://daringfireball.net/ - 10 May 2008
 * License: http://www.opensource.org/licenses/mit-license.php
 */

(function(){
	var small = "(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v[.]?|via|vs[.]?)";
	var punct = "([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]*)";
  
	this.titleCaps = function(title){
		var parts = [], split = /[:.;?!] |(?: |^)["Ò]/g, index = 0;
		
		while (true) {
			var m = split.exec(title);

			parts.push( title.substring(index, m ? m.index : title.length)
				.replace(/\b([A-Za-z][a-z.'Õ]*)\b/g, function(all){
					return /[A-Za-z]\.[A-Za-z]/.test(all) ? all : upper(all);
				})
				.replace(RegExp("\\b" + small + "\\b", "ig"), lower)
				.replace(RegExp("^" + punct + small + "\\b", "ig"), function(all, punct, word){
					return punct + upper(word);
				})
				.replace(RegExp("\\b" + small + punct + "$", "ig"), upper));
			
			index = split.lastIndex;
			
			if ( m ) parts.push( m[0] );
			else break;
		}
		
		return parts.join("").replace(/ V(s?)\. /ig, " v$1. ")
			.replace(/(['Õ])S\b/ig, "$1s")
			.replace(/\b(AT&T|Q&A)\b/ig, function(all){
				return all.toUpperCase();
			});
	};
    
	function lower(word){
		return word.toLowerCase();
	}
    
	function upper(word){
	  return word.substr(0,1).toUpperCase() + word.substr(1);
	}
})();

// Starts any loading indicators
function startLoading() {
	if(!$('#loading').length) {
		$('body').prepend('<div id="loading"><span id="loading_text">Loading...</span></div>');
	}
}
// Ends any loading indicators
function endLoading() {
	$('#loading').remove();	
}
/////////////////////////////////////////////////////////////////////////////
// - COMMON OPERATIONS - ////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
$(document).ready(function() {
						   
	// Perform text replacement, png fixes etc
	performFixes();
	
	/////////////////////////////////////////////////////////////////////////////
	// - FORMS - ////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////
	// Form field focus class
	
	$('input, select, textarea').focus(function() {
		$(this).addClass('form_focus');											
	});
	$('input, select, textarea').blur(function() {
		$(this).removeClass('form_focus');											
	});

	/////////////////////////////////////////////////////////////////////////////
	// - UNIT CONVERSIONS - /////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////
	$("input[name$='_st'], input[name$='_lb'], input[name$='_kg'], input[name$='_ft'], input[name$='_inches'], input[name$='_m'], input[name$='_cm']").each(function() {
		// Start each field with a zero value if no value is entered already
		if($(this).val()=='') {
			$(this).val('0');	
		}
		// Attach our conversion function to the blur event on each field
		$(this).blur(function() {
			performConversion($(this));
		});
	});

	/////////////////////////////////////////////////////////////////////////////
	// - COLLAPSABLE DIVS - /////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////	
	$('.collapsable_content').hide();
	
	$.live('.collapsable_control', 'click', function(event) {	
		if($(this).siblings('.collapsable_content:visible').length) {
			$(this).removeClass('collapsable_control_down');
			$(this).siblings('.collapsable_content').slideUp('medium');
		} else {
			$(this).addClass('collapsable_control_down');
			$(this).siblings('.collapsable_content').slideDown('medium');			
		}
	});
	/////////////////////////////////////////////////////////////////////////////
	// - LOGIN LINKS - //////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////
	$.live('a.login_link', 'click', function(event) {
		$('#login_email').focus();
		//return false;
	});

	/////////////////////////////////////////////////////////////////////////////
	// - RESTRICTED AREA COVERS - ///////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////

	var registerCoverContent = '<div class="faded_cover">'+
							'<p>Get access to these tools for free!</p>'+
							'<a href="'+URL+'/register/?registration_type=free"><img src="'+URL+'/graphics/buttons/free_registration_medium_white_bg.jpg" width="177" height="38" alt="Free Registration"></a><br /><br />'+
							'<a href="'+URL+'/login/">Already Registered?</a>'+
							'</div>';
	var subscribeCoverContent = '<div class="faded_cover">'+
							'<p>Purchase for access to these tools!</p>'+
							'<a href="'+URL+'/subscribe/"><img src="'+URL+'/graphics/buttons/purchase_now_medium_white_bg.jpg" width="177" height="38" alt="Free Registration"></a><br /><br />'+
							'<a href="'+URL+'/login/">Already Purchased?</a>'+
							'</div>';
	var shopComingSoonContent = '<div class="faded_cover">'+
							'<p class="cover_title pink">Shop coming soon!</p>'+
							'<p>The DROPweight shop will be home to great deals on weight loss accessories, audio resources, DVDs and literature... <strong>and much more!</strong></p>'+
							'</div>';
	var moreDataRequiredContent = '<div class="faded_cover">'+
							'<p class="cover_title pink">More data required</p>'+
							'<p>Sorry, you need to input more data to access this feature.</p>'+
							'<p><a href="/account/data-entry/">Add Data</a> &bull; <a href="/account/goals/">Add a Goal</a></p>'+
							'</div>';
	var comingSoonContent = '<div class="faded_cover">'+
							'<p class="cover_title pink">Feature coming soon!</p>'+
							'<p>Sorry, this feature is not available yet and will be released soon.</p>'+
							'</div>';									

	$('.status_preview .register_now_block, .status_preview .subscribe_now_block, .status_non_member .subscribe_now_block, .shop_coming_soon_block, .status_member .more_data_required, .status_non_member .feature_coming_soon, .status_member .feature_coming_soon').hover(
		function(){
			
			var eleBlock = $(this);
			
			var wrapWidth = (eleBlock.width() - 4);
			var wrapHeight = (eleBlock.height() - 4);
			
			if(eleBlock.find('.faded_cover').length == 0) {
				
				if(eleBlock.hasClass('feature_coming_soon')) {
					var coverContent = comingSoonContent;					
				}else if(eleBlock.hasClass('register_now_block')) {
					var coverContent = registerCoverContent;
				}else if(eleBlock.hasClass('shop_coming_soon_block')) {
					var coverContent = shopComingSoonContent;
				}else if(eleBlock.hasClass('subscribe_now_block')) {
					var coverContent = subscribeCoverContent;					
				}else if(eleBlock.hasClass('more_data_required')) {
					var coverContent = moreDataRequiredContent;			
				}

				eleBlock.prepend(coverContent)
						.find('.faded_cover')
						.show()
						.css('opacity',0)
						.width(wrapWidth)
						.height(wrapHeight)
						.animate({'opacity':0.95},{ queue:false, duration:170 });	
			}
		},
		function(){
			var eleBlock = $(this);
			eleBlock.find('.faded_cover').animate( {'opacity':0}, {queue:false, duration:350, complete:function(){$(this).remove()} } );
		}
	);


	/////////////////////////////////////////////////////////////////////////////
	// - AJAX LOADING - /////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////	
	if(!IE6) {
		$().ajaxSend(function() {
			startLoading();
		});
		$().ajaxComplete(function() {							  
			endLoading();
			performFixes();
		});
	}
	
});
