/*
 *  Fix IE background image flicker (via http://www.mister-pixel.com/)
 */
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

var propecia = function($) {
	$.fn.openNewWindow = function(options)
	{
		var defaults =
		{
			windowName: "popup",
			status: 0,
			toolbar: 0,
			location: 0,
			menubar: 0,
			directories: 0,
			resizable: 0,
			scrollbars: 0,
			width: 600,
			height: 550
		};
		var settings = $.extend({}, defaults, options);
		
		return this.bind("click.openNewWindow", function(){
			var newWindow = window.open($(this).attr("href"), settings.windowName, "status=" + settings.status + ",toolbar=" + settings.toolbar + ",location=" + settings.location + ",menubar=" + settings.menubar + ",directories=" + settings.directories + ",resizable=" + settings.resizable + ",scrollbars=" + settings.scrollbars + ",width=" + settings.width + ",height=" + settings.height);
			if (newWindow) newWindow.focus();
			
			return false;
		});
	};
	
	$.fn.toggleDataListInfoDisplay = function(options)
	{
		var defaults =
		{
			hoverClassName: "over",
			offClassName: "off",
			onClassName: "on"
		};
		var settings = $.extend({}, defaults, options);
		
		return this.each(function(){
			$("dd", this).hide(); // Hide Info
			
			$("dt strong", this).addClass(settings.offClassName); // Add "off" styles to give link look
			
			// Add hover functionality
			$("dt strong", this).hover(function(){
				$(this).addClass(settings.hoverClassName);
			}, function(){
				$(this).removeClass(settings.hoverClassName);
			});
			
			// Add show/hide functionality
			$("dt strong", this).click(function(){
				if ($(this).hasClass(settings.offClassName))
				{
					$(this).removeClass(settings.offClassName).addClass(settings.onClassName);
				}
				else
				{
					$(this).removeClass(settings.onClassName).addClass(settings.offClassName);
				}
				// Toggle visibility of corresponding Info
				$(this).parent().next("dd").toggle();
			});
		});
	};
		
	$.fn.hairLossTrivia = function()
	{
		var thisClass = this;
		
		return this.each(function(){
			$("#result", this).hide(); // Hide Answer
			
			$("form", this).show().submit(function(){
				
				$(this).hide();
				$("#result", thisClass).show();
							
				return false;
			});
		});
	};
}(jQuery);

/*
 *	sIFR
 */
var SIFR = {
	init: function()
	{
		if (typeof sIFR == "function")
		{
			sIFR.replaceElement("h1", named({sFlashSrc: "/propecia/consumer/flash/helvetica-neue-med-cond.swf", sColor: "#1E1714"}));
		}
	}
};

/*
 *	Find A Doctor SDC tagging functionality (capture zipcode and mile range)
 */
var FindADoctor = {
	init: function()
	{
		var thisClass = this;
		
		$("#propecia_cns_searchbyzip").submit(function(){
			thisClass.sdcTagging();
			
			return thisClass.validate();
		});
	},
	
	sdcTagging: function()
	{
		dcsMultiTrack(
			'DCSext.DocFindZipCode',$("#postalcode").val(),
			'DCSext.DocFindMileRad',$("#distance").val(),
			'WT.tx_e','',
			'WT.tx_id','',
			'WT.tx_it','',
			'WT.tx_sku','',
			'WT.pi','',
			'WT.seg_1','',
			'WT.tx_s','',
			'DCSext.QualityIndex','',
			'DCS.dcsuri',window.location.pathname.slice(0,window.location.pathname.lastIndexOf('.'))+'.form'
		);
	},
	
	validate: function()
	{
		// Set variables
		var errMessage = ""; // 
		var errFields = [];
		
		// Get form values	
		var postalcode = $.trim($("#postalcode").val());
		
		if(postalcode == "") // postalcode field is empty
		{
			errMessage = errMessage + "Please enter a ZIP Code.\r\n";
			errFields.push("postalcode");
		}
		else
		{
			if (!validateUSZip(postalcode)) // Check zip code is in valid format
			{
				errMessage = errMessage + "Please enter a valid 5 digit ZIP Code.\r\n";
				errFields.push("postalcode");
			}
		}
		
		if (errFields.length > 0)
		{
			alert(errMessage);
			
			$("input#" + errFields).focus();
			
			return false;
		}
		
		return true;
	}
};

/*
 *  methods to run on DOM ready
 */
$(document).ready(function() {
    SIFR.init();
	
	$("#trivia").hairLossTrivia();
	
	$("#copy dl.toggle").toggleDataListInfoDisplay();
	
	var printWindowProperties = {toolbar: 1, menubar: 1, resizable: 1, scrollbars: 1};
	$("a.print").openNewWindow(printWindowProperties);
	
	var norwoodWindowProperties = {width: 760, height: 650};
	$("#norwood").openNewWindow(norwoodWindowProperties);
	
	FindADoctor.init();
});

/*
 *	detach all handlers
 */
$(window).unload(function(){
    $("*").unbind();
});


/*
 *	DESCRIPTION: Validates required fields for order forms
 *
 *	PARAMETERS: form to validate
 *
 *	RETURNS: True if valid, alert window with errors if false.
 */
function validate(frm) {


	// Set variables
	var isErr = false; // for any type of error
	var errMessage = ""; // 
	var errField = ""; // if there is an error, focus on the first required form field error
	
	// Get form values
	var email = frm.email.value;
	var firstname = frm.firstname.value;
	var lastname = frm.lastname.value;
	var address1 = frm.address1.value;
	var city = frm.city.value;
	var state = frm.state.value;
	var postalcode = frm.postalcode.value;


	if (!frm.gender[0].checked && !frm.gender[1].checked) {
		isErr = true;
		errMessage = errMessage + "Please select Male or Female\r\n";
		if (errField.length <= 0) errField = "gender[0]";
	}
	if (validateIsEmpty(firstname)) {
		isErr = true;
		errMessage = errMessage + "Please enter First Name\r\n";
		if (errField.length <= 0) errField = "firstname";
	}
	if (validateIsEmpty(lastname)) {
		isErr = true;
		errMessage = errMessage + "Please enter Last Name\r\n";
		if (errField.length <= 0) errField = "lastname";
	}
	if (validateIsEmpty(email)) {
		isErr = true;
		errMessage = errMessage + "Please enter an E-mail address\r\n";
		if (errField.length <= 0) errField = "email";
	} else {
		email = email.trim(); // remove whitespace around value
		var x = email.search(/ /); // look for spaces in value
		var y = email.search(/,/); // look for commas in value
		var z = email.search(/;/); // look for semicolons in value
		
		if ((x != -1) || (y != -1) || (z != -1)) { // Check for more than one email address
			isErr = true;
			errMessage = errMessage + "You are only allowed to enter one E-mail address at a time.\r\n";
			if (errField.length <= 0) errField = "email";
		}
		if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) { // Check for valid email address
			isErr = true;
			errMessage = errMessage + "Please enter a valid E-mail address\r\n";
			if (errField.length <= 0) errField = "email";
		}
	}
	if (validateIsEmpty(address1)) {
		isErr = true;
		errMessage = errMessage + "Please enter an Address\r\n";
		if (errField.length <= 0) errField = "address1";
	}
	if (validateIsEmpty(city)) {
		isErr = true;
		errMessage = errMessage + "Please enter a City\r\n";
		if (errField.length <= 0) errField = "city";
	}
	if (validateIsEmpty(state)) {
		isErr = true;
		errMessage = errMessage + "Please enter a State\r\n";
		if (errField.length <= 0) errField = "state";
	}
	if(validateIsEmpty(postalcode)) {  // postalcode field is empty
		isErr = true;
		errMessage = errMessage + "Please enter ZIP Code\r\n";
		if (errField.length <= 0) errField = "postalcode";
	} else {
		postalcode = postalcode.trim(); // remove whitespace around value
		if (!validateUSZip(postalcode)) { // Check zip code is in valid format
			isErr = true;
			errMessage = errMessage + "Please enter a valid ZIP Code in 5 digit format.\r\n";
			if (errField.length <= 0) errField = "postalcode";
		}
	}
	
	if (isErr) {
		alert(errMessage);
		
		eval("frm." + errField + ".focus()");
		
		return false;
	}
	
	return true;
}

/*
 *	DESCRIPTION: Validates that a string is a United States zip code in 5 digit format or zip+4 format. The following are acceptable:
 *		12345
 *		12345-1234
 *		12345+1234
 *		12345 1234
 *		123451234
 *
 *	PARAMETERS: strValue - String to be tested for validity
 *
 *	RETURNS: True if valid, otherwise false.
 */
function validateUSZip(strValue) {
	if (strValue.search(/(^\d{5}$)|(^\d{5}-\d{4}$)|(^\d{5}\+\d{4}$)|(^\d{5}\W+\d{4}$)|(^\d{9}$)/) == -1) return false;
	return true;
}

/*
 *	DESCRIPTION: Checks if a string is empty
 *
 *	PARAMETERS: strValue - String to be tested for validity
 *
 *	RETURNS: True if valid (empty), otherwise false (not empty).
 */
function validateIsEmpty(strValue) {
	strValue = strValue.trim();
	if(strValue.length > 0) return false;
	return true;
}

/*
 *	DESCRIPTION: Removes leading and trailing spaces.
 *
 *	PARAMETERS: Source string from which spaces will be removed;
 *
 *	RETURNS: Source string with whitespaces removed.
 */
function trimString (strValue) {
	strValue = this != window? this : strValue;
	return strValue.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

// Added as a method to the String.prototype
String.prototype.trim = trimString;

/*
 *	Script to open full size new widow
 */
function openFullPodcast(product, url) {	
	if (window.screen) {
		window.moveTo(0,0);
		window.outerHeight = screen.availHeight;
		window.outerWidth = screen.availWidth;
		}

	
	var name="new"+Math.floor(Math.random()*5); /* This line will give new name to each popup window, so that with every click a new window will open */
	var height = window.outerHeight;
	var width = window.outerWidth;

    var externalWin = window.open(url,name,"toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,top=0,left=0,width=" + width + ",height=" + height);
    if (externalWin.opener == null) {
    	externalWin.opener=window;
        externalWin.opener.name="opener";
	}
}


/* Validate Terms & conditions checkbox */
function validatePromise(frm) {
	var errMessage = "";	
	if(frm.consent.checked != true) {
		errMessage = errMessage + "Please check Terms and Conditions.\r\n";
		}
		return errMessage;
	}
	
	
	

