// General Support v1.0
// Andrew Pettican (February 2010)
// NB: This is a core script, and is relied upon by other scripts.
//
// Changelog:
// v1.0 - 18/02/2010 - Initial build
//////////////////////////////////////////////////////////////////

// ---------------------------------------------------------------
// Parameters
// ---------------------------------------------------------------

var gs_link_fade_duration = 500; // Duration of a link colour fade
var gs_bg_img_prefix = "bg_img-"; // Background img id prefix
var gs_debug_mode = false; // Generate debug statements (to #hash / #debug elements)?
var gs_insert_contact_id_prefix = "insert_contact-"; // Insert contact link prefix
var gs_title_prefix = "WildWest | ";

// Page load animations
var gs_fade_duration = 1500; // Duration of fade animations
var gs_slide_duration_init = 1500; // Duration of sliding animations during initialisation
var gs_slide_duration_uninit = 1000; // Duration of sliding animations during uninitialisation
var gs_easing_mode_init = 'easeOutExpo'; // Easing mode during initialisation NB: Could use linear, swing, easeOutBack, easeOutCubic, easeOutExpo
var gs_easing_mode_uninit = 'easeInCubic'; // Easing mode during uninitialisation NB: Could use linear, swing, easeInBack, easeInCubic, easeInExpo
var gs_min_anim_lpos_detail = 0; // Minimum left position of #detail_layers & #detail_content blocks (in px)
var gs_max_anim_lpos_detail = 500; // Maximum left position of #detail_layers & #detail_content blocks (in px)
var gs_min_anim_lpos_detail_layer_info = 34; // Minimum left position of #detail_layers & #detail_content blocks (in px)
var gs_max_anim_lpos_detail_layer_info = 534; // Maximum left position of #detail_layers & #detail_content blocks (in px)
var gs_min_anim_lpos_strip = -538; // Minimum left position of #strip_bg & #strip_content blocks (in px)
var gs_max_anim_lpos_strip = 0; // Maximum left position of #strip_bg & #strip_content blocks (in px)
var gs_min_anim_opac_bg_filter = 0; // Minimum opacity of #bg_filter block
var gs_max_anim_opac_bg_filter = 1; // Maximum opacity of #bg_filter block

// ---------------------------------------------------------------
// Parameters End
// ---------------------------------------------------------------



// ---------------------------------------------------------------
// JS Events
// ---------------------------------------------------------------

jQuery(document).ready(function()
{
	// Preload some images
	//////////////////////////////////////////////////////////////
	jQuery('<img>').attr('src', '/assets/templates/wildwest/layout_images/detail_layer_next.png');
	jQuery('<img>').attr('src', '/assets/templates/wildwest/layout_images/detail_layer_prev.png');
	jQuery('<img>').attr('src', '/assets/templates/wildwest/layout_images/bullet-blue.gif');
	jQuery('<img>').attr('src', '/assets/templates/wildwest/layout_images/bullet-grey.gif');
	
	
	// When the mouse hovers over a #nav link element, animate the colour change
	//////////////////////////////////////////////////////////////
	$('#nav .nav li a').live("mouseover mouseout", function(event)
	{
		// Determine if we are activating or deactivating the hover
		var activate_hover = (event.type == "mouseover");
		// alert("Mouse Nav Event - " + event.type);
		
		// Fetch the parent li and ul elements
		var parent_li = this.parentNode;
		var parent_ul = parent_li.parentNode;
		
		// Animate the link based on the parent element classes and if we are activating or deactivating the hover state
		if($(parent_ul).hasClass('nav'))
		{
			// Root Nav Level element: <ul.nav><li><a>
			if($(parent_li).hasClass('active'))
			{
				// Active Root Nav Level element: <ul.nav><li.active><a>
				if(activate_hover) {
					$(this).stop().animate({ color: '#FFFFFF' }, gs_link_fade_duration);
				} else {
					$(this).animate({ color: '#FFFFFF' }, gs_link_fade_duration);
				}
			}
			else
			{
				// Inactive Root Nav Level element: <ul.nav><li><a>
				if(activate_hover) {
					$(this).stop().animate({ color: '#FFFFFF' }, gs_link_fade_duration);
				} else {
					$(this).animate({ color: '#6FC8F3' }, gs_link_fade_duration);
				}
			}
		}
		else
		{
			// Sub Nav Level element: <ul.nav><li><ul><li><a>
			if($(parent_li).hasClass('active'))
			{
				// Active Sub Nav Level element: <ul.nav><li><ul><li.active><a>
				if(activate_hover) {
					$(this).stop().animate({ color: '#6FC8F3' }, gs_link_fade_duration);
				} else {
					$(this).animate({ color: '#6FC8F3' }, gs_link_fade_duration);
				}
			}
			else
			{
				// Inactive Sub Nav Level element: <ul.nav><li><ul><li><a>
				if(activate_hover) {
					$(this).stop().animate({ color: '#6FC8F3' }, gs_link_fade_duration);
				} else {
					$(this).animate({ color: '#FFFFFF' }, gs_link_fade_duration);
				}
			}
		}
	});
	
	
	// When the mouse hovers over a .strip_list link element, animate the colour change
	//////////////////////////////////////////////////////////////
	$('.strip_list li a').live("mouseover mouseout", function(event)
	{
		// Determine if we are activating or deactivating the hover
		var activate_hover = (event.type == "mouseover");
		// alert("Mouse Strip List Event - " + event.type);
		
		// Fetch the parent li element
		var parent_li = this.parentNode;
		
		// Animate the link based on the parent element class and if we are activating or deactivating the hover state
		if($(parent_li).hasClass('active'))
		{
			// Active element: <ul.strip_list><li.active><a>
			if(activate_hover) {
				$(this).stop().animate({ color: '#6FC8F3' }, gs_link_fade_duration);
			} else {
				$(this).animate({ color: '#6FC8F3' }, gs_link_fade_duration);
			}
		}
		else
		{
			// Inactive element: <ul.strip_list><li><a>
			if(activate_hover) {
				$(this).stop().animate({ color: '#6FC8F3' }, gs_link_fade_duration);
			} else {
				$(this).animate({ color: '#FFFFFF' }, gs_link_fade_duration);
			}
		}
	});	
	
	
	// When using iPad, allow scrolling through Work section by swiping the finger
	//////////////////////////////////////////////////////////////	
		
	// Allow this functionality on Work and terms pages only as it blocks resizing page with fingers
	//if(window.location.hash && ((window.location.hash.indexOf('#work/')!=-1) || (window.location.hash.indexOf('#terms-conditions')!=-1)) ) {
		if($('#detail').length){
			var def = false;
			if(navigator.userAgent.match(/iPad/i)){
				var def = true;
			}
			$('#detail').touchwipe({
				wipeLeft: function() {
					$('#detail_layers').cycle('next');  
				},
				wipeRight: function() {
					$('#detail_layers').cycle('prev');
				},
				preventDefaultEvents: def
			});
		}
	//}
	//}
	if(navigator.userAgent.match(/iPhone/i)){
		// hide the address bar and top strip
		window.scrollTo(0, 20);
	}
	/*
	// to have different styles dependent if iphone profile or landscape.
	var updateLayout = function() {
	  if (window.innerWidth != currentWidth) {
		currentWidth = window.innerWidth;
		var orient = (currentWidth == 320) ? "profile" : "landscape";
		document.body.setAttribute("orient", orient);
		window.scrollTo(0, 1);
	  }
	};
	
	iPhone.DomLoad(updateLayout);
	setInterval(updateLayout, 500);
	
	//ccs to use
	//body[orient="portrait"] {
	//	property: value;
	//}
	//body[orient="landscape"] {
	//	property: value;
	//}
	*/
	
});

// ---------------------------------------------------------------
// JS Events End
// ---------------------------------------------------------------



// ---------------------------------------------------------------
// Functions
// ---------------------------------------------------------------

/**
 * Email link generator
 */
function insertContact(theName, linkText, linkclass)
{
	var theDomain = ('design' + 'wild' + 'west' + '.' + 'com');
	
	var theClass = "";
	if(typeof(linkclass) == "string")
	{
		theClass = 'class="' + linkclass + '" ';
	}
	
	var theAddress = (theName + '&#064' + theDomain);
	if(typeof(linkText) != "string")
	{
		linkText = theAddress;
	}
	document.write('<a ' + theClass + 'href="mailto:' + theAddress +'">' + linkText + '<\/a>');
}


/**
 * Email address generator
 */
function generate_email(theName)
{
	var theDomain = ('design' + 'wild' + 'west' + '.' + 'com');
	return (theName + '@' + theDomain);
}


/**
 * Initialises the page, this involves a number of steps:
 * 1. Initialise the scripts required for popups and external links to work
 * 2. Rearrange the position and opacity of specific dom elements (optionally using animations) to put them in their final state ready for user interaction
 */
function initialise_page(callback)
{
	// Flag indicating if the callback function needs to be executed
	var execute_callback = (typeof(callback) == "function");
	
	// Debug
	if(gs_debug_mode) {
		$('#debug').html($('#debug').html() + ", ip");
	}
	
	// Initialise popups
	initialise_links_and_popups();
	
	// Perform loading animations?
	if(perform_loading_animations)
	{
		// Temporary var for calculating animation durations
		var tmp_anim_duration = 0;
		
		// Animate detail layers/content?
		if($('#detail_layers, #detail_content').length > 0)
		{
			// Animating down from 500 -> 0, calculate the required duration
			tmp_anim_duration = Math.round((1 - determine_percentage_to_target(gs_min_anim_lpos_detail, gs_max_anim_lpos_detail, $('#detail_layers').css('left'), false)) * gs_slide_duration_init);
			
			// Debug
			if(gs_debug_mode) {
				$('#debug').html($('#debug').html() + ", #detail_layers ai" + tmp_anim_duration + "(" + gs_slide_duration_init + ")");
			}
			
			$('#detail_layers, #detail_content').stop().animate({ left: gs_min_anim_lpos_detail+"px" },
			{
				duration: tmp_anim_duration, 
				easing: gs_easing_mode_init, 
				complete: function()
				{
					// Animation complete.
					$('#detail_layers, #detail_content').animate({ borderTopColor: '#353F48', borderRightColor: '#353F48', borderBottomColor: '#353F48' }, { duration: gs_fade_duration, queue: false });
				}, 
				queue: false
			});
			
			if($('#detail_layer_info').length > 0)
			{
				// Animating down from 534 -> 34, calculate the required duration
				tmp_anim_duration = Math.round((1 - determine_percentage_to_target(gs_min_anim_lpos_detail_layer_info, gs_max_anim_lpos_detail_layer_info, $('#detail_layer_info').css('left'), false)) * gs_slide_duration_init);
				
				// Debug
				if(gs_debug_mode) {
					$('#debug').html($('#debug').html() + ", #detail_layer_info ai" + tmp_anim_duration + "(" + gs_slide_duration_init + ")");
				}
				
				$('#detail_layer_info').stop().animate({ left: gs_min_anim_lpos_detail_layer_info+"px" }, { duration: tmp_anim_duration, easing: gs_easing_mode_init, queue: false });
			}
		}
		
		
		// Animate strip
		// Animating up from -538 -> 0, calculate the required duration
		tmp_anim_duration = Math.round((1 - determine_percentage_to_target(gs_min_anim_lpos_strip, gs_max_anim_lpos_strip, $('#strip_bg').css('left'), true)) * gs_slide_duration_init);
		
		// Debug
		if(gs_debug_mode) {
			$('#debug').html($('#debug').html() + ", #strip_bg ai" + tmp_anim_duration + "(" + gs_slide_duration_init + ")");
		}
		
		$('#strip_bg, #strip_content').stop().animate({ left: gs_max_anim_lpos_strip+"px" }, 
		{
			duration: tmp_anim_duration, 
			easing: gs_easing_mode_init, 
			complete: function()
			{
				// Animation complete.
				initialise_detail_layers();
				
				// This will no longer be the first initialisation
				as_first_initialisation = false;
				
				// Execute the callback
				// NB: Make sure this runs after the slowest animation (gs_slide_duration_init)
				if(execute_callback)
				{
					execute_callback=false;
					callback();
				}
			}, 
			queue: false
		});
		
		
		// Animate BG filter
		// Animating down from 1 -> 0, calculate the required duration
		tmp_anim_duration = Math.round((1 - determine_percentage_to_target(gs_min_anim_opac_bg_filter, gs_max_anim_opac_bg_filter, $('#bg_filter').css('opacity'), false)) * gs_fade_duration);
		
		// Debug
		if(gs_debug_mode) {
			$('#debug').html($('#debug').html() + ", #bg_filter ai" + tmp_anim_duration + "(" + gs_fade_duration + ")");
		}
		
		$('#bg_filter').stop().animate({ opacity: gs_min_anim_opac_bg_filter },
		{
			duration: tmp_anim_duration, 
			complete: function()
			{
				// Animation complete.
				$('#bg_filter').css('display', 'none');
			}, 
			queue: false
		});
	}
	else
	{
		// Final state - Detail layers
		$('#detail_layers, #detail_content').css('left', gs_min_anim_lpos_detail+"px").css('border-top-color', '#353F48').css('border-right-color', '#353F48').css('border-bottom-color', '#353F48');
		$('#detail_layer_info').css('left', gs_min_anim_lpos_detail_layer_info+"px");
		
		// Final state - Strip
		$('#strip_bg, #strip_content').css('left', gs_max_anim_lpos_strip+"px");
		
		// Final state - BG filter
		$('#bg_filter').css('opacity', gs_min_anim_opac_bg_filter).css('display', 'none');
		
		// Initialise detail layers
		initialise_detail_layers();
		
		// This will no longer be the first initialisation
		as_first_initialisation = false;
		
		// Execute the callback
		if(execute_callback)
		{
			execute_callback=false;
			callback();
		}
	}
}


/**
 * Uninitialises the page, this involves a number of steps:
 * 1. Rearrange the position of the relevant dom elements (if animations are enabled) to put them in their uninitialised state
 * 2. Optionally, fade the entire page out at the same time
 * 3. Execute a callback function then the animations are complete (e.g. to initialise a new page)
 */
function uninitialise_page(unload_nav, unload_strip, unload_detail, new_bg_img, callback, with_fade_out)
{
	// Flag indicating if the callback function needs to be executed
	var execute_callback = (typeof(callback) == "function");
	
	// Debug
	if(gs_debug_mode) {
		$('#debug').html($('#debug').html() + ", up");
	}
	
	// Update the flag to show that detail layers are uninitialised
	dls_layers_initialised = false;
	
	// Load the new BG image?
	if(new_bg_img != "")
	{
		switch_image(new_bg_img);
	}
	
	// Perform loading animations?
	if(perform_loading_animations)
	{
		// Temporary var for calculating animation durations
		var tmp_anim_duration = 0;
		
		// Animate with a fade effect?
		with_fade_out = (typeof(with_fade_out) == "boolean") ? with_fade_out : false;
		
		// Animate detail layers/content?
		// NB: we will only unload the detail layer if requested, and if it is already loaded!
		unload_detail = (unload_detail && $('#detail_layers, #detail_content').length > 0);
		if(unload_detail)
		{
			// Slide out detail layers/content
			// Animating up from 0 -> 500, calculate the required duration
			tmp_anim_duration = Math.round((1 - determine_percentage_to_target(gs_min_anim_lpos_detail, gs_max_anim_lpos_detail, $('#detail_layers').css('left'), true)) * gs_slide_duration_uninit);
			
			// Debug
			if(gs_debug_mode) {
				$('#debug').html($('#debug').html() + ", #bg_filter au" + tmp_anim_duration + "(" + gs_slide_duration_uninit + ")");
			}
			
			// Fade out borders and slide out
			$('#detail_layers, #detail_content').stop();
			$('#detail_layers, #detail_content').animate({ borderTopColor: '#FFFFFF', borderRightColor: '#FFFFFF', borderBottomColor: '#FFFFFF' }, { duration: gs_fade_duration, queue: false });
			$('#detail_layers, #detail_content').animate({ left: gs_max_anim_lpos_detail+"px" }, 
			{
				duration: tmp_anim_duration, 
				easing: gs_easing_mode_uninit, 
				complete: function()
				{
					// Animation complete.
					
					// Execute the callback?
					// NB: Make sure this runs after the slowest animation (gs_slide_duration_uninit)
					if(execute_callback)
					{
						execute_callback=false;
						callback();
					}
				}, 
				queue: false 
			});
			
			// Slide out detail layer info (if available)
			if($('#detail_layer_info').length > 0)
			{
				// Animating up from 34 -> 534, calculate the required duration
				tmp_anim_duration = Math.round((1 - determine_percentage_to_target(gs_min_anim_lpos_detail_layer_info, gs_max_anim_lpos_detail_layer_info, $('#detail_layer_info').css('left'), true)) * gs_slide_duration_uninit);
				
				// Debug
				if(gs_debug_mode) {
					$('#debug').html($('#debug').html() + ", #detail_layer_info au" + tmp_anim_duration + "(" + gs_slide_duration_uninit + ")");
				}
				
				$('#detail_layer_info').stop().animate({ left: gs_max_anim_lpos_detail_layer_info+"px" }, { duration: tmp_anim_duration, easing: gs_easing_mode_uninit, queue: false });
			}
		}
		
		
		// Animate strip?
		if(unload_strip)
		{
			// Animating down from 0 -> -538, calculate the required duration
			tmp_anim_duration = Math.round((1 - determine_percentage_to_target(gs_min_anim_lpos_strip, gs_max_anim_lpos_strip, $('#strip_bg').css('left'), false)) * gs_slide_duration_uninit);
			
			// Debug
			if(gs_debug_mode) {
				$('#debug').html($('#debug').html() + ", #strip_bg au" + tmp_anim_duration + "(" + gs_slide_duration_uninit + ")");
			}
			
			$('#strip_bg, #strip_content').stop().animate({ left: gs_min_anim_lpos_strip+"px" }, 
			{
				duration: tmp_anim_duration, 
				easing: gs_easing_mode_uninit, 
				complete: function()
				{
					// Animation complete.
					
					// Execute the callback?
					// NB: Make sure this runs after the slowest animation (gs_slide_duration_uninit)
					if(execute_callback)
					{
						// Debug
						if(gs_debug_mode) {
							$('#debug').html($('#debug').html() + ", upcb");
						}
						
						execute_callback=false;
						callback();
					}
				}, 
				queue: false
			});
		}
		
		
		// Were any animations performed?
		if(unload_nav || unload_strip || unload_detail)
		{
			// Animate BG filter?
			if(with_fade_out)
			{
				$('#bg_filter').css('display', 'block');
				
				// Animating up from 0 -> 1, calculate the required duration
				tmp_anim_duration = Math.round((1 - determine_percentage_to_target(gs_min_anim_opac_bg_filter, gs_max_anim_opac_bg_filter, $('#bg_filter').css('opacity'), true)) * gs_fade_duration);
				
				// Debug
				if(gs_debug_mode) {
					$('#debug').html($('#debug').html() + ", #bg_filter au" + tmp_anim_duration + "(" + gs_fade_duration + ")");
				}
				
				$('#bg_filter').stop().animate({ opacity: gs_max_anim_opac_bg_filter }, { duration: tmp_anim_duration, queue: false });
			}
		}
		
		// No animations were performed, execute the callback?
		else if(execute_callback)
		{
			// Debug
			if(gs_debug_mode) {
				$('#debug').html($('#debug').html() + ", upcb");
			}
			
			execute_callback=false;
			callback();
		}
	}
	else if(execute_callback)
	{
		// Debug
		if(gs_debug_mode) {
			$('#debug').html($('#debug').html() + ", upcb");
		}
		
		execute_callback=false;
		callback();
	}
}


/**
 * Initialises popups, external links and email links
 */
function initialise_links_and_popups()
{
	// Create all contact links
	$('a.insert_contact').each(function()
	{
		// Determine the email address
		var contact_name = $(this).attr('rel').substr(gs_insert_contact_id_prefix.length);
		var contact_email = generate_email(contact_name);
		
		// Update the link with the correct email address
		$(this).attr('href', "mailto:"+contact_email);
		if($(this).html() == "")
		{
			$(this).html(contact_email);
		}
	});
	
	
	// Create a popup window
	$('a[rel=popup]').each(function()
	{
		// Clear rel and update titles
		$(this).attr("rel", "");
		var old_title = $(this).attr("title");
		if(old_title !== "")
		{
			$(this).attr("title", old_title+" [Opens in new window]");
		}
		else
		{
			$(this).attr("title", "[Opens in new window]");
		}
		
		// Perform the popup when clicked
		$(this).bind("click", function()
		{
			// Default window attributes
			var window_width = 400;
			var window_height = 400;
			var window_resizable = 0;
			var window_status = 1;
			var scrollbars_status = 0;
			var d = new Date();
			var window_name = 'popup_'+d.getTime();
			
			// Determine window attributes
			// These should be attached to the "rev" attribute of the <a> tag in the format:
			// width=300; height=300; status=1; resizable=0; name=blahblah
			var window_attributes = $(this).attr("rev").split(";");
			for(i=0; i<window_attributes.length; i++)
			{
				if(window_attributes.hasOwnProperty(i))
				{
					var attrib_parts = window_attributes[i].split("=", 2);
					if(attrib_parts.length == 2)
					{
						// Determine what the value of this attribute is.
						// NB: attributes should alway be an integer
						var attribute_key = jQuery.trim(attrib_parts[0]);
						var attribute_value_str = jQuery.trim(attrib_parts[1]);
						var attribute_value = parseInt(attribute_value_str, 10);
						if(!isNaN(attribute_value))
						{
							if(attribute_key == "width" && attribute_value >= 100)
							{
								window_width = attribute_value;
							}
							else if(attribute_key == "height" && attribute_value >= 100)
							{
								window_height = attribute_value;
							}
							else if(attribute_key == "resizable" && attribute_value >= 0)
							{
								window_resizable = attribute_value;
							}
							else if(attribute_key == "status" && attribute_value >= 0)
							{
								window_status = attribute_value;
							}
							else if(attribute_key == "scrollbars" && attribute_value >= 0)
							{
								scrollbars_status = attribute_value;
							}
						}
						
						// For handling string attributes
						if(attribute_key == "name" && attribute_value_str != "")
						{
							window_name = attribute_value_str;
						}
					}
				}
			}
			
			var output_attributes = "width="+window_width+", height="+window_height+", resizable="+window_resizable+", status="+window_status+", scrollbars="+scrollbars_status+"";
			//alert(output_attributes +'\n'+ window_name);
			
			window.open(this.href,window_name,output_attributes);
			return false;
		});
	});
	
	
	// Load the page in a new window
	$('a[rel=external]').each(function()
	{
		// Set target, clear rel and update titles
		$(this).attr("target", "_blank").attr("rel", "");
		var old_title = $(this).attr("title");
		if(old_title !== "")
		{
			$(this).attr("title", old_title+" [Opens in new window]");
		}
		else
		{
			$(this).attr("title", "[Opens in new window]");
		}
	});
	
	
}


/**
 * Switches the background image
 * NB: new_image must be a .jpg image located in the assets/images/backgrounds/ directory
 */
function switch_image(new_image)
{
	// Perform loading animations?
	if(perform_loading_animations)
	{
		// Add the new image to the dom with 0% opacity
		$('#bg_image').append('<img id="'+gs_bg_img_prefix+new_image+'" src="assets/images/backgrounds/'+new_image+'.jpg" alt="" style="opacity:0; filter:alpha(opacity=0);" />');
		
		// Fade in the latest image (this will be in front of any old ones)
		$('#bg_image img:last').animate({ opacity: 1 },
		{
			duration: gs_fade_duration, 
			complete: function()
			{
				// How many images have we got, and what is the opacity of the last one?
				var num_images = $("#bg_image img").length;
				var last_img_opac = parseFloat($('#bg_image img:last').css('opacity'));
				
				// Do not remove any images unless there are multiple images in the container, and the last one is at 100% opacity.
				if(num_images > 1 && last_img_opac >= 1)
				{
					$("#bg_image img:lt("+(num_images-1)+")").remove();
				}
			}, 
			queue: false
		});
	}
	else
	{
		// Add the new image to the dom with 100% opacity
		$('#bg_image').append('<img src="assets/images/backgrounds/'+new_image+'.jpg" alt="" style="opacity:1; filter:alpha(opacity=100);" />');
		
		// How many images have we got, and what is the opacity of the last one?
		var num_images = $("#bg_image img").length;
		
		// Do not remove any images unless there are multiple images in the container.
		if(num_images > 1)
		{
			$("#bg_image img:lt("+(num_images-1)+")").remove();
		}
	}
}


/**
 * Determines the percentage that a numeric value is to its min/max value
 * 
 * Examples:
 * (0, 100, 62, true)		= 0.62 (62 is 62% of the way towards 100, starting from 0)
 * (0, 100, 62, false)		= 0.38 (62 is 38% of the way towards 0, starting from 100)
 * (50, 100, 62, true)		= 0.24 (62 is 24% of the way towards 100, starting from 50)
 * (50, 100, 62, false)		= 0.76 (62 is 76% of the way towards 50, starting from 100)
 * (-500, 0, -250, true)	= 0.50 (-250 is 50% of the way towards 0, starting from -500)
 */
function determine_percentage_to_target(min_value, max_value, current_value, rising)
{
	// Ensure we have valid numeric / boolean values to work with
	min_value = parseFloat(min_value);
	max_value = parseFloat(max_value);
	current_value = parseFloat(current_value);
	rising = (typeof(rising) == "boolean" ? rising : true);
	
	// Sanity checks
	if(min_value < max_value && current_value >= min_value && current_value <= max_value)
	{
		// Calculate the percentage that the current_value is towards the max_value (this should be between 0.0 and 1.0)
		var percent_to_max = Math.min(1, Math.max(0, (current_value - min_value) / (max_value - min_value)));
		
		// Rising?
		if(rising)
		{
			return percent_to_max;
		}
		else
		{
			return 1-percent_to_max;
		}
	}
	else
	{
		return 0;
	}
}

// ---------------------------------------------------------------
// Functions End
// ---------------------------------------------------------------
