﻿String.format = function(text)
{
	//check if there are two arguments in the arguments list
	if (arguments.length <= 1)
	{
		//if there are not 2 or more arguments there’s nothing to replace
		//just return the original text
		return text;
	}

	//decrement to move to the second argument in the array
	var tokenCount = arguments.length - 2;
	for (var token = 0; token <= tokenCount; token++)
	{
		//iterate through the tokens and replace their placeholders from the original text in order
		text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
	}

	return text;
};

/**
Send email entered in sidebar to passed url in post
*/
function signupNewsletter(url, errMsg)
{
	var email = document.getElementById('newsletter_email').value;

	if (!errMsg || validEmail(email))
	{
		post_to_new_win(url, { 'email': email });
	}
	else
	{
		alert(errMsg);
	}
}

/**
Validate groups of radio buttons where each group name has the same prefix and is indexed from 1 to n, continuously.
Returns true if each group has a value selected, false otherwise.
Display the err msg if returning false.
*/
function validateRadioGroups(prefix, max_index, errmsg)
{
	var valid = true;
	for (var i = 1; i <= max_index; i++)
	{
		if (getRadioSelectedValue(prefix + i) == '')
		{
			valid = false;
			alert(errmsg);
			break;
		}
	}
	return valid;
}

//Returns the selected value of a radio button group, or empty string if nothing is selected
function getRadioSelectedValue(radioName)
{
	var group = document.getElementsByName(radioName);
	var selectedValue = '';

	for (i = 0; i < group.length; i++)
	{
		if (group[i].checked)
		{
			selectedValue = group[i].value;
			break;
		}
	}

	//alert(radioName + "=" + selectedValue);
	return selectedValue;
}


/**
Expand list of items
*/
function expand(className, linkName, newLabel)
{
	$("." + className).slideDown(400);

	if (linkName && newLabel)
	{
		var oldLabel = $("#" + linkName).html();
		$("#" + linkName).attr("href", "javascript:collapse('" + className + "','" + linkName + "','" + oldLabel + "')").html(newLabel);
	}
}

/**
Collapse list of items
*/
function collapse(className, linkName, newLabel)
{
	$("." + className).slideUp(400);

	if (linkName && newLabel)
	{
		var oldLabel = $("#" + linkName).html();
		$("#" + linkName).attr("href", "javascript:expand('" + className + "','" + linkName + "','" + oldLabel + "')").html(newLabel);
	}
}

/**
Hide one selector and then shows another
*/
function swap(toHide, toShow, hideSpeed, showSpeed)
{
	$(toHide).hide(hideSpeed);
	$(toShow).show(showSpeed);
}


/**
Display the requested "page" in the passed Response Related Question group
*/
function viewRRLink(rrq, page)
{
	$(".ArticleLinks ul#" + rrq + " li").hide(400);
	$(".ArticleLinks ul#" + rrq + " li.artGroup" + page).show(400);

	$(".ArticleLinks .pagination span#pageLinks_" + rrq + " a.rrPageCurrent").removeClass("rrPageCurrent")
	$(".ArticleLinks .pagination span#pageLinks_" + rrq + " a").eq(page).addClass("rrPageCurrent");
}


/**
Populate Response Related articles pagination links
*/
function popRRPageLinks()
{
	/*
	Procedure:
	- Determine total number of "pages"
	- Get all <ul> of class ArticleLinks, and check class name for each <ul> to match rrq<i>
	- Use rrq<i> and artGroup index to popuplate spans with javascript links for pagination
	*/

	$(".ArticleLinks ul").each(function()
	{
		var rrq = $(this).attr("id");

		if (rrq.match(/^rrq[\d]+$/))
		{
			var groupCount = getSelectorGroupCount("#" + rrq + " .artGroup");
			var links = "";
			for (var i = 0; i < groupCount; i++)
			{
				links += "<a href=\"javascript:viewRRLink('" + rrq + "', " + i + ")\""
				if (i == 0) links += "class=\"rrPageCurrent\"";
				links += ">" + (i+1) + "</a> ";
			}
			$(".ArticleLinks .pagination span#pageLinks_" + rrq).html(links);
		}
	});
}


/**
Get total number of existing selectors with format <class_prefix><index>
- Assumes that the sequence is uninterrupted and starts at 0!
*/
function getSelectorGroupCount(prefix)
{
	var i = 0;
	var len;
	while ($(prefix + i).length > 0) i++;
	return i;
}


/**
Opens the clinic locator in a new window.
*/
function openClinicLocator(langid)
{
	if (!langid) langid = 0;

	var postal_code = $(".ClinicLocatorBox input#clinic_input").val();
	if (postal_code.match(/^[abceghjklmnprstvxy][0-9][abceghjklmnprstvwxyz][\s\-]{0,1}[0-9][abceghjklmnprstvwxyz][0-9]{1}$/i))
	{
		window.open("http://cliniclocator.mediresource.com/SearchResult.aspx?exp=10&from=" + postal_code);
	}
	else
	{
		var msg;
		switch (langid)
		{
			case 1:
				msg = "Veuillez entrer votre code postal(A1B-2C3)";

			default:
				msg = "Please enter your postal code (A1B 2C3)";
		}
		alert(msg);
	}
}


/**
Handles watermark behavior
*/
function watermark(e)
{
	e.value = "";
}



/**
Functions to post email to newsletter pages
*/

//IE safe version (tested on IE7)
function post_to_new_win(url, values)
{
	var myWin = window.open();
	myWin.document.write("<html><head></head><body><form id=\"myForm\" action=\"" + url + "\" method=\"post\">");
	var vars = "<input type=\"hidden\" name=\"{0}\" value=\"{1}\" />"
	
	for (var property in values)
	{
		if (values.hasOwnProperty(property))
		{
			var value = values[property];
			if (value instanceof Array)
			{
				for (var i = 0, l = value.length; i < l; i++)
				{
					myWin.document.write(String.format(vars, property, value[i]));
				}
			}
			else
			{
				myWin.document.write(String.format(vars, property, value));
			}
		}
	}
	
	myWin.document.write("</form></body></html>");
	myWin.document.getElementById("myForm").submit();
}

function HtmlPop(width, height, htmlText)
{
	var generator = window.open('', 'name', 'height=' + height + ',width=' + width + "'");
	generator.document.write('<html><head><title>Popup</title>');
	generator.document.write('<link rel="stylesheet" href="Css/Screen.css">');
	generator.document.write('</head><body>');
	generator.document.write(htmlText);
	generator.document.write('<p><a href="javascript:self.close()">Close</a> the window.</p>');
	generator.document.write('</body></html>');
	generator.document.close();
}

function validEmail(email)
{
	var reg = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return reg.test(email);
}
