﻿/// <reference path="jquery-1.2.6.min.js" />
/// <reference path="swfobject.js" />

var STRINGS = {
	MESSAGES_EXTERNAL_POP: {
		External: "You are leaving " + window.location.host + ", a website of Genzyme Corporation. Genzyme Corporation does not review or control the content of non-Genzyme websites, and this hyperlink does not constitute an endorsement by Genzyme of the site&#8217;s content. Genzyme&#8217;s privacy procedures do not apply to the owners of a non-Genzyme website.",
		GenzymeOther: "You are leaving " + window.location.host + " to view another Genzyme Corporation website.",
		ProceedToWebsite: "Proceed to Website",
		StayOnWebsite: "Stay on " + window.location.host,
		FormConfirmationTitle: "You are submitting information to Genzyme",
		FormConfirmationContent: "<p>Genzyme Corporation (\"Genzyme\") respects individual privacy and values the confidence of its customers, partners, patients and employees.</p><p>This Privacy Policy and Notice of Information Practices sets forth Genzyme's practices regarding the collection, use and disclosure of information that you may provide through this site. Whenever you submit information through this site to Genzyme, you agree with the terms of Genzyme's Privacy Policy and Notice of Information Practices. Please review the <a href=\"/privacy-policy.aspx\">privacy policy</a> before submitting information through this website. By selecting \"continue\" you are agreeing to the terms of Genzyme's privacy policy.</p>",
		SanofiContactContent: "You are leaving " + window.location.host + " and being directed to www.sanofi.us, our parent company, where all product inquiries are handled.",
		FormConfirmationContinue: "Continue",
		FormConfirmationGoBack: "Go Back"
	},
	PAGE_UTILITY_STRINGS: {
		EmailThisPage: "Email this Page",
		PrintThisPage: "Print this Page",
		TextSize: "Text Size"
	},
	THICKBOX_STRINGS: {
		StringClose: "close",
		StringCloseTitle: "Close",
		StringOrESCKey: "or Esc Key"
	}
};

$j(document).ready(function() {
	
	//if there's no title tag then it says undefined
	$j(".prettyPhoto, a[rel^='prettyPhoto']").each(function(){
		if($j(this).attr('title') == undefined)
			$j(this).attr('title', '');
	});
	$j(".prettyPhoto").prettyPhoto({animationSpeed:'fast',slideshow:10000, social_tools:'', show_title:false, overlay_gallery:false});

	// IE6 only -- workaround broken button behavior
	// see http://www.kopz.org/public/documents/css/multiple_buttons_ie_workaround.html	    
	if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
		$j("button").bind("click", function() {
			// do nothing if this page isn't valid
			if (typeof Page_IsValid == "boolean") {
				if (Page_IsValid == false)
					return false;
			}
			// save and then remove the other button's name attribute (which prevents wrong asp.net events from firing)
			$j("button").not(this).each(function() {
				var $this = $j(this);
				$this.data("saved_name", $this.attr("name"));
				$this.removeAttr("name");
			});
		});

		// add hover state for ie6 buttons
		$j("button").hover(
			function() { $j(this).addClass("iehover"); },
			function() { $j(this).removeClass("iehover"); }
	    );
	    
	    // prevent ie6 flicker
        try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}


	}

	// turn on Javascript specific styles.
	$j('html').addClass('js');

	// Bind the confirmation dialog popup to external links
	$j("a.external, a.genzymeother, a.formconfirmation, a.sanoficontact").bind("click", buildExternalModalBox);

	// Change all a.flash tags to swf object
	setTimeout(insertSWF, 50);

	// Initializes the STRINGS object
	localize_string_objects(STRINGS);

	// implement 'rel="external"' (target="_blank" alternative)
	$j('A[rel="external"]').click(function() {
		window.open($j(this).attr('href'));
		return false;
	});
});

// changes all links with .flash to their respective swfs
// uses swfobject
var insertSWF = function() {
	$j("a.flash").each(function(i) {
		var $this = $j(this);
		$this.attr("id", "noncollidingidvalue");
		var params = $this.attr("class").split(" ");
		var height = params[1];
		var width = params[2];
		// params[1] = height & params[2] = width
		swfobject.embedSWF($this.attr("href"), $this.attr("id"), width, height, "8");
		$j("#noncollidingidvalue").removeAttr("id");
	});

};

// Creates the confirmation dialog popup for when a user clicks an external link
function buildExternalModalBox(e) {
	var $this = $j(this);
	var $offset = $this.offset();

	var isFormConfirmation = $this.hasClass("formconfirmation");
	var isSanofiContact = $this.hasClass("sanoficontact");	
	var isExternal = $this.hasClass("external");
	
	//determine the popup content
	var note = "";
	if (isFormConfirmation == true) {
		note = "<h4>" + STRINGS.MESSAGES_EXTERNAL_POP.FormConfirmationTitle + "</h4>";
		if (STRINGS.MESSAGES_EXTERNAL_POP.FormConfirmationContent.substr(0, 1) != "<")
			note += "<p>" + STRINGS.MESSAGES_EXTERNAL_POP.FormConfirmationContent + "</p>";
		else
			note += STRINGS.MESSAGES_EXTERNAL_POP.FormConfirmationContent;
	} else if (isSanofiContact == true) {
		note = "<p>" + STRINGS.MESSAGES_EXTERNAL_POP.SanofiContactContent + "</p>";
	} else if (isExternal == true) {
		note = "<p>" + STRINGS.MESSAGES_EXTERNAL_POP.External + "</p>";
	} else {
	    note = "<p>" + STRINGS.MESSAGES_EXTERNAL_POP.GenzymeOther + "</p>";
	}

	//determine the popup confirm button text
	var confirm = (isFormConfirmation == true)
        ? STRINGS.MESSAGES_EXTERNAL_POP.FormConfirmationContinue
        : STRINGS.MESSAGES_EXTERNAL_POP.ProceedToWebsite;

	//determine the popup cancel button text
	var stay = (isFormConfirmation == true)
        ? STRINGS.MESSAGES_EXTERNAL_POP.FormConfirmationGoBack
        : STRINGS.MESSAGES_EXTERNAL_POP.StayOnWebsite;

	//build the popup html
	if (!document.getElementById("exitconfirm")) {
		var $exitconfirm = $j('<div id="exitconfirm"><div id="exitconfirmmessage"></div><ul><li><a class="btn" id="confirm-goto" href="#"><span>' + confirm + '</span></a></li><li><a class="btn" id="confirm-stay" href="#"><span>' + stay + '</span></a></li></ul></div>');
		$exitconfirm.appendTo("body");
		// do omniture exit tracking when clicking proceed
		$j("#confirm-goto").click(function() {
			if (typeof s == "object" && typeof s.trackExternalLinks == "boolean" && s.trackExternalLinks == false && typeof s.tl == "function") {
				s.tl(this, 'e', this.href);
			}
			$j("#exitconfirm").hide();
		});
		$j("#confirm-stay").click(function(e) { $j("#exitconfirm").jqmHide(); e.preventDefault(); });
	}
	//set the popup content
	$j("#exitconfirmmessage").html(note);
	$j("#confirm-goto").attr("href", $this.attr("href"));
	if (typeof $this.attr("target") == "string") {
		$j("#confirm-goto").attr("target", $this.attr("target")).click(function() { $j("#exitconfirm").jqmHide(); });
	} else {
		$j("#confirm-goto").removeAttr("target");
	}
	$j("#exitconfirm").jqm();
	$j("#exitconfirm").jqmShow();

	// IE6 throws up on position:fixed, so it gets position: absolute in the css.
	// this code sets top correctly for IE6
	if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
		var ieoffset = document.documentElement.clientHeight / 4 + document.documentElement.scrollTop;
		$j("#exitconfirm").css("top", ieoffset + "px");
	}
	e.preventDefault();
}

function doFormValidation(validationGroup, requiredClass, summaryClass) {
	//    if (typeof(Page_ClientValidate) == 'function') 
	//        Page_ClientValidate(validationGroup); 
	//
	if (typeof Page_IsValid != "boolean")
		return true; // ASP.NET client side validation not properly loaded

	if (Page_IsValid == false) {
		var label = undefined;
		if (Page_Validators) {
			var groupClear = 0;
			var invalidArrayIndex = 0;
			var invalidArray = Array();
			for (var index = 0; index < Page_Validators.length; index++) {
				var validator = Page_Validators[index];
				var controlName = validator.controltovalidate;
				if (controlName == undefined)
					continue;
	            label = $j("label[for='" + controlName + "']");
	            groupClear = 1;
	            // checkboxlist (uses P as fieldset "label")
				if (label.length == 0)				    
				    label = $j(".checkboxlist:has(#" + controlName + ") p");
				// radiobuttonlist (uses P as fieldset "label")
				if (label.length == 0)
				    label = $j(".radiobuttonlist:has(#" + controlName + ") p");
			    // if no direct label search within the phonenumber fieldset
				if (label.length == 0) {
				    label = $j(".phonenumber:has(#" + controlName + ") label");					
					groupClear = 0;
				}				
				if (validator.isvalid == false) {
					label.addClass(requiredClass);
					invalidArray[invalidArrayIndex] = controlName;
					invalidArrayIndex = invalidArrayIndex + 1;
				}
				else {
					if (jQuery.inArray(controlName, invalidArray) == -1 && groupClear == 1)
						label.removeClass(requiredClass);
				}
			}
		}
		if (label != undefined) {
			label.parents("fieldset").find("." + summaryClass).show();
		}
		return false;
	}
	return true;
}
function validate_checkboxlist(sender) {
    return ($j("#" + sender.controltovalidate).parent().parent(".checkboxlist").find("input:checked").length > 0);
}
function validate_radiobuttonlist(sender) {
    return ($j("#" + sender.controltovalidate).parent().parent(".radiobuttonlist").find("input[type='radio']:checked").length > 0);
}


// initialize localized strings (override STRINGS child object strings if localized objects are redefined in global scope)
// -- ie those defined in /layouts/ExternalStringData.ashx?language=xx
function localize_string_objects(stringObjects) {
	jQuery.each(stringObjects, function(index, val) {
		if (typeof window[index] == "object") {
			var objName = index;
			var obj = val;
			jQuery.each(obj, function(index, val) {
				if (typeof obj[index] == typeof window[objName][index])
					obj[index] = window[objName][index];
			});
		}
	});
	return stringObjects;
}

function standard_email_tb_init(element) {
	var STRINGS = localize_string_objects({
		THICKBOX_STRINGS: {
			Close: "close",
			CloseTitle: "Close",
			OrEscKey: "or Esc Key"
		}
	});
	tb_init(element, {
		// localized thickbox strings
		StringClose: STRINGS.THICKBOX_STRINGS.Close,
		StringCloseTitle: STRINGS.THICKBOX_STRINGS.CloseTitle,
		StringOrESCKey: STRINGS.THICKBOX_STRINGS.OrEscKey,
		// this eventHandler is call just before the thickbox is removed
		CallbackPostRemove: standard_email_tb_PostRemove,
		// this eventHandler is run after $j("#TB_ajaxContent).load has completed, but before the content is displayed
		CallbackAjaxContentLoaded: standard_email_tbAjaxContentLoaded
	});
}

var standard_email_tb_PostRemove = function() {
	if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
		// IE6 needs a workaround for multiple button tags on that same page that disables all button tags besides the one used for submit.
		// This can leave disabled buttons (search at least) on the page when the thickbox is closed after an ajax update.
		// Therefore, this workaround is used to turn back on any previously enabled buttons after the update completes.
		$j("button").each(function() {
			var $this = $j(this);
			var saved_name = $this.data("saved_name");
			if (typeof saved_name == "string") {
				$this.attr("name", saved_name);
				$this.removeData("save_name");
			}
		});
	}
};

var standard_email_tbAjaxContentLoaded = function() {
	var STRINGS = localize_string_objects({
		FORM_BUTTON_STRINGS: {
			Cancel: "Cancel",
			Close: "Close"
		}
	});
	// define function to get thickbox close button markup
	var get_tb_remove_button = function(cls, text) { return '<button onclick="tb_remove(); return false;" class="' + cls + '" text="' + text + '"><span>' + text + '</span></button>'; };
	// asp.net ajax events
	var prm = Sys.WebForms.PageRequestManager.getInstance();
	prm.add_beginRequest(function(sender, args) {
		// if there is more than one form defined by aspnet (theForm), save the former and switch to the new one
		if (typeof theForm[0].tagName == "string" && theForm[0].tagName == "FORM") {
			if (theForm.length == 2) {
				$j(theForm[1]).data("thePreThickboxForm", theForm[0]);
				theForm = theForm[1];
			}
		}
	});
	prm.add_pageLoaded(function(sender, args) {
		// run when asp.net ajax has loaded content onto the page dynamically (UpdatePanel)
		if (prm.get_isInAsyncPostBack() == true) {
			// add a close button to the response, if not yet present
			if ($j("#TB_window button.close").length == 0) {
				var btn = get_tb_remove_button('close', STRINGS.FORM_BUTTON_STRINGS.Close);
				$j("#TB_window #primary").append(btn);
			}
		}
	});
	prm.add_endRequest(function(sender, args) {
		// restore a previously saved aspnet form (theForm) if present
		var thePreThickboxForm = $j(theForm).data("thePreThickboxForm");
		if (typeof thePreThickboxForm == "object") {
			theForm = thePreThickboxForm;
		}
		// hack around missing form._events due to multiple forms, which will cause asp.net ajax js errors
		sender._form._events = { submit: [], click: [] };
	});

	// change behavior of button.send to submit through asp.net ajax
	var $send = $j("#TB_window button.send");
	$send.click(function() {
		if (typeof Page_IsValid == "boolean") {
			if (Page_IsValid == false)
				return false;
		}
		prm._form = this.form;
		prm._doPostBack($send.attr("name"), '');
		return false;
	});
	// add cancel button to form
	$send.after(get_tb_remove_button('cancel', STRINGS.FORM_BUTTON_STRINGS.Cancel));
};


function QueryString(parameterName) {
	var ret = "";
	// get the raw query string without leading ?
	var queryString = window.location.search.substring(1);
	if (queryString != "") {
		var params = queryString.split("&");
		for (i = 0; i < params.length; ++i) {
			var parameter = params[i].split("=");
			if (parameter[0] == parameterName) {
				ret = parameter[1];
			}
		}
	}

	return ret;
}

// jQuery plugin traps all keystrokes other than numeric, return,backspace and delete.  use for number-only form fields.
// usage: $j('selector').filterAlphaInput();
jQuery.fn.filterAlphaInput = function(){
    this.keypress(function(e){  
        var key = e.which;
        console.log(key);
        if (key == 13 || key == 8 || key == 46 || key == 0 || (key > 47 && key < 58)  ) { return true; } // pass if key is return, backspace, delete, tab, or numeric
        else { return false }
    });
};


