/* function onYouTubePlayerReady ()
{
	ytplayer = document.getElementById('player');
}

function playVideo ()
{
	if (typeof ytplayer == 'undefined')
	{
		try{playVideo();}catch(ex){}
	}
	else
	{
		ytplayer.seekTo(0, true);
		ytplayer.playVideo();
	}
} */

Array.prototype.clone = function () {var a = new Array(); for (var property in this) {a[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return a}

// Array prototype for min and max value in an array
// @see http://ejohn.org/blog/fast-javascript-maxmin/
Array.max = function( array )
{
    return Math.max.apply( Math, array );
}

Array.min = function( array )
{
    return Math.min.apply( Math, array );
}

function clean_array(array, deleteValue)
{
  for (var i = 0; i < array.length; i++)
  {
    if (array[i] == deleteValue) 
    {         
      array.splice(i, 1);
      i--;
    }
    array[i] = array[i] * 1;
  }
  return array;
}

function replace_values(array,value,replace)
{	
  for (var i = 0; i < array.length; i++)
  {
    if (array[i] == value) 
    {
      array[i] = replace
    }
   // this[i] = parseInt(this[i]);
  }
  return array;
}

Math.roundTo = function(number, digits) 
{
	var multiple = Math.pow(10, digits);
	var rndedNum = Math.round(number * multiple) / multiple;
	return rndedNum;
}

// Time parsing function
function parseTime(s) 
{
   var c = s.split(':');
   return parseInt(c[0]) * 60 + parseInt(c[1]);
}

$(document).ready(function ()
{
	// setup external links
	$('a[rel=external]').click(function() {
		$(this).attr('target', '_blank');
	});

	// setup video
	ytlink = $('#video a').attr('href');

	$('#video a').click(function ()
	{
		$('.copy').addClass('wide');
		$('#splash-video').show();
		window.scroll(null, 344);
		pageTracker._trackPageview('/event/play-video');
		return false;
	});

	$('#form-login').each(function(index) {
		var $form = $(this);
		$form.validate({
			rules: {
				username: {
					required: true,
					email: true
				},
				password: "required"
			}
		});
		
		$('.button a[href*="#forgot-password"]', $form).click(function()
		{
			$form.parent().hide();
			$('#forgot-password').show();
		});
	});

	$('#form-forgot_password').each(function(index) {
		var $form = $(this);
		$form.validate({
			rules: {
				email: {
					required: true,
					email: true
				}
			}
		});
		$('.button a', $form).click(function()
		{
			$form.parent().hide();
			$('#login').show();
		});
	});


	$('body.nutrition').each(function(){
		$('.lo').each(function(){
			$(this).before('<img src="/themes/site_themes/default/images/icon-recipe-left-overs.png" style="float:left;padding-right:5px;" />')
		});
		
		$('.me').each(function(){
			$(this).before('<img src="/themes/site_themes/default/images/icon-recipe-make-extra.png" style="float:left;padding-right:5px;" />')
		});
	});
	
	$('.subscribe').validate();

	$('#form-register').each(function(index) {

		var $form = $(this);
		var $submit_button = $("input[type=image]", $form).removeAttr("disabled");

		$form.validate({
			//debug: true,
			submitHandler: function(form){
				// $submit_button.replaceWith("<p style='margin-bottom:18px;'><strong>Processing your payment...</strong></p>");
				if (confirm("Your credit card will be processed immediately. Please don't submit the form more than once."))
				{
					form.submit();
				}				
			},
			rules: {
				first_name: "required",
				last_name: "required",
				username: {
					required: true,
					email: true
				},
				screen_name: "required",
				password: {
					required: true,
					minlength: 5
				},
				password_confirm: {
					required: true,
					equalTo: "#register-password"
				},

				email_confirm: {
					required: true,
					equalTo: '#register-email'
				},
				"Nsm_commerce[purchase][account]": {
					required: true,
					creditcard: true
				},
				"Nsm_commerce[purchase][type]" : "required"
			}
		});

		$("#payment-options", $form).each(function(index) {
			var $self = $(this);
			var $radios = $(':radio', $self);
			var $labels = $('label', $self);
			$radios.click(function() {
				$labels.removeClass("checked");
				$(this).parent().addClass("checked");
			});
		});
		
		
		// Show and hide the Round 1 screen name input
		$screen_name = $('#round_one_screen_name',$form);
		$completed = $('#round_one_completed');
		
		function toggleScreenName()
		{
			n = $completed.filter(':checked').length;
			
			if(n != 0)
			{
				$screen_name.show();
			}
			else
			{
				$screen_name.hide();
			}
		}
		
		// Hide or show the box initially
		toggleScreenName();
		$('#round_one_completed').click(toggleScreenName);

	});

	$('.tabgroup').each(function(index) {
		var $triggers = $('> ul a, > ol a', this);
		var $targets = $(' > div', this);
		$targets.first().show();
		$triggers.click(function()
		{
			$triggers.parent().removeClass('active');
			$targets.removeClass('active').hide()

			$(this).parent().addClass('active');

			if(this.hash == "#all")
			{
				$targets.addClass("active").show();
			}
			else
			{
				$targets.filter(this.hash).addClass("active").show();
			}
			return false;
		});
	});

	$('#program-menu').each(function(index) {
		var $triggers = $('a', this);
		var $targets = $('table.workout-day');
		$triggers.first().parent().addClass('active');
		$triggers.click(function()
		{
			$triggers.parent().removeClass('active');
			$targets.removeClass('active').hide();

			$(this).parent().addClass('active');

			if(this.hash == "#all")
			{
				$targets.addClass("active").show();
			}
			else
			{
				$targets.filter("." + this.hash.substr(1)).addClass("active").show();
			}
			return false;
		});
	});
	
	$workout_types = $(".workout-type:not('.stretch)");
	$("select#workout-type-trigger").change(function() {
	   var $self = $(this);
	   var target = $self.val();
		if(target == "all")
		{
			$workout_types.show();
		}
		else
		{
			$workout_types.hide().filter(".workout-type." + target).show();
		}
		$("table.workout-day tbody tr:visible").removeClass("odd").filter(":odd").addClass("odd");
			
	}).change();

	$workout_levels = $(".workout-level");
	$("select#workout-level-trigger").change(function() {
	   var $self = $(this);
	   var target = $self.val();
		if(target == "all")
		{
			$workout_levels.show();
		}
		else
		{
			 $workout_levels.hide().filter(".workout-level#" + target).show();
		}
	}).change();
	
	$('#my-stats-quickview').each(function(index)
	{
		$.getJSON('/json/stats/',function(data)
		{
			// Metric by default
			metric = true;

			if(data.measurement_system == 'imperial')
			{
				metric = false;
				
				// If they haven't entered inches
				inches = (data.height != false) ? data.height : 0;
				
				// If they haven't entered feet
				feet = (data.height_feet != false) ? data.height_feet : 0;
				
				// Convert the height into straight inches
				data.height = parseInt(12 * feet) + parseInt(inches);
			}
			
			array_1 = data.metrics.weight.clone()
			array_2 = data.metrics.weight.clone()
			
			values 		 = replace_values(array_2,'','0');
			clean_values = clean_array(array_1,false)
			
			current_weight = clean_values[clean_values.length - 1];		
			
			if(data.wk0_weight === false)
			{
				start_weight =  values[0];
			}
			else
			{
				start_weight = data.wk0_weight;
			}

			weightl	= calculateWeightLoss(start_weight,current_weight);
			bmi 	= calculateBmi(weightl.current,data.height,metric);
			bmr 	= calculateBmr(data.gender,weightl.current,data.height,data.age,metric);
			
			if(weightl.current != 0)
			{
				//$('#my-stats-current-weight').text(weight.current)
			}
			
			if(weightl.start != 0)
			{
				$('#my-stats-start-weight').text(weightl.start)
			}
			
			if(weightl.difference != 0)
			{
				$('#my-stats-weight-loss').text(weightl.difference)
			}
			
			$('#my-stats-percentage-weight-loss').text(weightl.percentage)
			
			$('#my-stats-bmi').text(bmi);
			$('#my-stats-bmr').text(bmr);
			
			$('#chart').each(function(){
				$(this).createGraph(array_2)
			});
		});
	});
	
	$.validator.addMethod('time',function(value,element){
		return this.optional(element) || /^\d+:\d{1,2}$/.test(value)
	},
		'Time must be in the mm:ss format'
	);
	
	$.validator.addMethod('custom_number',function(value, element) {
		return this.optional(element) || /^[-\+]?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
	});
	
	v = $('#member_form').validate({
		focusInvalid:false,
		focusCleanup:true,
		errorContainer: '#my_stats_errors',
		errorPlacement:function(error, element){},
		unhighlight: function( element, errorClass, validClass   ) {
			$(element).removeClass(errorClass).addClass(validClass);
			delete v.invalid[element.name];
		}
	});
	
	$('#member_form #measurement_system').change(function(){
		mystats = $('#my-stats');
		metric = mystats.hasClass('metric');
				
		$('.note',mystats).each(function(){
		
			id = $(this).parent().parent().attr('id');

			if(metric == false)
			{
				if(id == 'sit_and_reach')
				{
					new_content = $(this).text().replace('(+/- in)','(+/- cm)');
				}
				else if(id == 'weight')
				{
					new_content = $(this).text().replace('(lb)','(kg)');
				}
				else if(id == 'height')
				{
					new_content = $(this).text().replace('(ft/in)','(cm)');
				}
				else
				{
					new_content = $(this).text().replace('(in)','(cm)');
				}

				mystats.removeClass('imperial').addClass('metric');
			}
			else if(metric == true)
			{
				if(id == 'sit_and_reach')
				{
					new_content = $(this).text().replace('(+/- cm)','(+/- in)');
				}
				else if(id == 'weight')
				{
					new_content = $(this).text().replace('(kg)','(lb)');
				}
				else if(id == 'height')
				{
					new_content = $(this).text().replace('(cm)','(ft/in)');
				}
				else
				{
					new_content = $(this).text().replace('(cm)','(in)');
				}

				mystats.removeClass('metric').addClass('imperial')
			}

			$(this).text(new_content)
		})
	});
	
	$('#update-billing-details').parent().validate();
	
	$('#beginner a, #intermediate a, #advanced a').attr('target', '_blank');
});

function calculateWeightLoss(start_weight,current_weight)
{
	if(isNaN(start_weight))
		start_weight = 0
	
	if(isNaN(current_weight) || current_weight == 0)
		current_weight = start_weight
	
	weight_lost 	= Math.roundTo((current_weight - start_weight),2);
	percentage 		= Math.roundTo(100 - ((1 - (weight_lost / start_weight)) * 100),1);
	
	if(percentage > 0)
	{
		percentage = '+' + percentage
	}
	
	if(weight_lost >  0)
	{
		weight_lost = '+' + weight_lost 
	}
	
	if(isNaN(percentage))
	{
		percentage = '0';
	}
	
	return {
		start:start_weight,
		current:current_weight,
		difference:weight_lost,
		percentage:percentage + '%'
	}
}

function calculateBmi(weight,height,metric)
{
	if(height == false || weight == false)
	{
		return 'N/A';
	}
	
	if(metric === true)
	{
		bmi = (weight / Math.pow((height / 100), 2))
	}
	else
	{
		bmi = (weight * 703) / Math.pow((height),2)
	}

	bmi = Math.roundTo(bmi,2);
	
	if(isNaN(bmi))
	{
		bmi = 'N/A'
	}
		
	return bmi; 
}

function calculateBmr(gender,weight,height,age,metric)
{
	if(height == false || age == false || weight == false)
	{
		return 'N/A';
	}
	
	if(metric === true)
	{
		if(gender == 'female')
		{
			return Math.round(655 + (9.6 * weight) + (1.8 * height) - (4.7 * age))
		}
		else if(gender == 'male')
		{
			return Math.round(66 + (13.7 * weight) + (5 * height) - (6.8 * age))
		}
		else
		{
			return 'N/A';
		}
	}
	else
	{
		if(gender == 'female')
		{
			return Math.round(655 + (4.35 * weight) + (4.7 * height) - (4.7 * age))
		}
		else if(gender == 'male')
		{
			return Math.round(66 + (6.23 * weight) + (12.7 * height) - (6.8 * age))
		}
		else
		{
			return 'N/A';
		}
	}
}

jQuery.fn.createGraph = function(values,options)
{
	// Chart options
	var config = {
		url: 'http://chart.apis.google.com/chart?',
		min: 0,
		max: Array.max(values),
		params: {
			cht:'bvs',
			chs:'458x119',
			chxt:'x,y',
			chco:'56226b',
			//chm :'N,F,0,-1,11,,lb:-7:5',
			chbh: 'a'
		}
	}
	if(options) $.extend(config,options)

	config.params.chxl = '0:|';
	markers = new Array();

	for(i = 0; i < values.length; i++)
	{
		// Ignore missing weeks
		if(values[i] !== false)
		{
			// The start week should say 'Start' instead of week 0
			if(i == 0)
			{
				config.params.chxl = config.params.chxl + 'Start|';
			}
			else
			{
				config.params.chxl = config.params.chxl + i + '|'
			}
		}
		
		if(values[i] != '0')
		{
			markers.push('N,FFFFFF,0,'+i+',11,,lb:-7:-12')
		}
	}
	
	config.params.chm = markers.join('|') 

	config.params.chxl = config.params.chxl + '1:|'+config.min+'|' + Math.round(config.max / 2) + '|' + config.max
		
	// Chart data
	config.params.chd = 't:' + values.join(',')
	
	// Chart min and max
	config.params.chds = config.min + ',' + config.max

	return $(this).append('<img src="'+config.url+jQuery.param(config.params)+'" />')
}

jQuery.fn.summariseStats = function(options)
{
	var config = {
		rows:'tbody tr',
		summary_class:'summary',
		increase_class:'increase',
		decrease_class:'decrease'
	}

	if(options) $.extend(config,options)
	
	// My stats summaries
	$(this).find(config.rows).each(function(row)
	{
		var td 			= $(this).find('td');
		var start 		= td.eq(0).children('span').text();
		var end 		= td.eq(3).children('span').text();
		var span_class  = '';
		
		// Time fields are formatted differently
		if($(this).hasClass('time_trial') || $(this).hasClass('wall_sit'))
		{
			summary = end;
		}
		else
		{
			summary = parseInt(end) - parseInt(start);
			
			if(isNaN(summary))
			{
				summary = "-"
			}
			else if(summary > 0)
			{
				span_class = config.increase_class;
				summary = '+' + summary;
			}
			else
			{
				span_class = config.decrease_class;
			}
		}
				
		$('.' + config.summary_class + ' span',this).text(summary).addClass(span_class);
	});
}
