/*
	
Synvisc-One Global Javascript Functions
By  - ISITE Design

*/

var $j = jQuery.noConflict();

// global variable used on the homepage to store the value of the knee pain assessment question
var selectedKneePainValue = "";

//start the jQuery functions
$j(document).ready(function() {

	// add class to drop downs and buttons for IE <6
	if (document.all) {
		$j("#nav li, button, #secondary p").hover(
			function() { $j(this).addClass("over"); },
			function() { $j(this).removeClass("over"); }
	    );
	} // if document.all


	// insert page utility links
	// email this page, print this page
	if ($j("body.assessment").length == 0) {
		var mailurl = "/email-a-friend.aspx?height=535&width=440&url=" + window.location;
		$j("#nav-page-utility-placeholder").replaceWith('<ul id="nav-page-utility">' +
	    '<li class="email"><a class="thickbox" href="' + mailurl + '">' + STRINGS.PAGE_UTILITY_STRINGS.EmailThisPage + '</a></li>' +
	    '<li class="print"><a onclick="return TrackPrintLink(this)" href="#">' + STRINGS.PAGE_UTILITY_STRINGS.PrintThisPage + '</a></li></ul>');
		$j("#nav-page-utility .print, .printquestions").click(function() {
			window.print();
			return false;
		});
		tb_init('#nav-page-utility a.thickbox');
		// text size
		$j("#nav-text-size-placeholder").replaceWith('<div id="text-size"><p>' + STRINGS.PAGE_UTILITY_STRINGS.TextSize + ': <a href="#" id="small">A</a>&nbsp;<a href="#" id="regular">A</a>&nbsp;<a href="#" id="large">A</a></p></div>');
	}


	// FAQ
	/*makeFAQ();
	if (document.getElementById("faq") && window.location.hash) {
	setTimeout(function() { $j("a[name=" + window.location.hash.substr(1) + "]").parent().click(); }, 750);
	}*/
	$j('#faq').makeFAQ();


	//countries 
	$j('.countries').hide();
	$j('.continents h2').toggle(function() {
		$j(this).next('.countries').fadeIn();
		$j(this).addClass('close');
	}, function() {
		$j(this).next('.countries').fadeOut();
		$j(this).removeClass('close');
	}); // end countries

	// table row highlight
	$j("tr").hover(
		function() { $j(this).addClass("over"); },
		function() { $j(this).removeClass("over"); }
	);

	// select box anchor jump bevahior (for /outsidedistributors.aspx, and here because js inside the sitecore rte doesn't work right)
	$j("select.anchorjump").change(function() { window.top.location = this.options[this.selectedIndex].value; });

	// questions to ask doctor print toggling
	if ($j(".questionstoprint").length > 0) { printQuestions(); }

	// glossary tooltips
	$j(".glossary").tooltip({
		showURL: false,
		showBody: " - "
	});

	// knee pain flash application.
	$j("a.flashapp").each(function(i) {
		var $this = $j(this);
		var existingID = $this.attr("id");
		if (existingID == "")
			$this.attr("id", "noncollidingidvalue");
		var params = $this.attr("class").split(" ");
		var height = params[1];
		var width = params[2];

		// Key : Name Pair Configurations
		// flash variables
		var flashvars = {
			base_path: "/sites/Synvisc-One/_resources/flash/knee-pain-assessment",
			xml_path: "/survey.xml",
			template_path: "/reportTemplate.html",
			service_provider: "http://" + window.location.hostname + "/sites/Synvisc-One/_resources/flash/knee-pain-assessment/AssessmentHelper.asmx?WSDL",
			email_from: "DoNotReply-Synviscl@synviscone.com",
			email_subject: "Your Knee Pain Assessment You Requested from Synvisc-One",
			generic: "true"
		};

		// set first page according to the selected radio button
		flashvars.first_page = QueryString("first_page");

		// parameters on the object tag
		var parameters = {
			quality: "high",
			pluginspage: "http://www.macromedia.com/go/getflashplayer",
			align: "middle",
			play: "true",
			loop: "true",
			scale: "showall",
			wmode: "transparent",
			devicefont: "false",

			bgcolor: "#fefefe",
			name: "synvisc",
			menu: "true",
			allowFullScreen: "false",
			allowScriptAccess: "sameDomain",
			movie: "synvisc",
			salign: ""
		};
		// html attributes to be placed on the resulting object tag
		//var attributes = { codebase: "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" };
		swfobject.embedSWF($this.attr("href"), $this.attr("id"), width, height, "8", "", flashvars, parameters);
		if (existingID == "") {
			$j("#noncollidingidvalue").removeAttr("id");
		}
	});

	$j("a.brightcove-thickbox").each(function() {
		var $this = $j(this),
	    baseurl = $this.attr('href'),
	    classes = $this.attr('class'),
	    getPresent = /\?/.test(baseurl),
	    heightVal = /h-[0-9]+/.exec(classes),
	    widthVal = /w-[0-9]+/.exec(classes),
	    width = widthVal ? parseInt(widthVal.toString().substr(2)) - 29 : 457,
	    height = heightVal ? parseInt(heightVal.toString().substr(2)) + 8 : 420,
	    thickboxString = (getPresent) ? '&TB_iframe=true&height=' + height + '&width=' + width : '?TB_iframe=true&height=' + height + '&width=' + width;
		$this.attr('href', baseurl + thickboxString);
		tb_init(this);
	});

	$j("a.player-thickbox").each(function() {
		var $this = $j(this),
	    baseurl = $this.attr('href'),
	    getPresent = /\?/.test(baseurl),
	    thickboxString = (getPresent) ? '&TB_iframe=true' : '?TB_iframe=true';
		$this.attr('href', baseurl + thickboxString);
		tb_init(this);
	});
	
	// email form thickbox needs special help for ff.
	if($j.browser.mozilla) { $j('#email-widget').parents('body').prepend('<style type="text/css">#TB_window iframe { overflow-y:hidden; }</style>');}


	// special thickbox setup for kneepain assessment flash tool widget on home page
	tb_init("a.knee-pain-thickbox", {
		// once the content is loaded do the work of embedding the flash
		CallbackAjaxContentLoaded: function() {
			$j("a.flashapp").each(function(i) {
				var $this = $j(this);
				var existingID = $this.attr("id");
				if (existingID == "")
					$this.attr("id", "noncollidingidvalue");
				var params = $this.attr("class").split(" ");
				var height = params[1];
				var width = params[2];

				// Key : Name Pair Configurations
				// flash variables
				var flashvars = {
					base_path: "/sites/Synvisc-One/_resources/flash/knee-pain-assessment",
					xml_path: "/survey.xml",
					template_path: "/reportTemplate.html",
					service_provider: "http://" + window.location.hostname + "/sites/Synvisc-One/_resources/flash/knee-pain-assessment/AssessmentHelper.asmx?WSDL",
					email_from: "DoNotReply-Synviscl@synviscone.com",
					email_subject: "Your Knee Pain Assessment You Requested from Synvisc-One",
					generic: "true"
				};

				// set first page according to the selected radio button
				flashvars.first_page = selectedKneePainValue;

				// parameters on the object tag
				var parameters = {
					quality: "high",
					pluginspage: "http://www.macromedia.com/go/getflashplayer",
					align: "middle",
					play: "true",
					loop: "true",
					scale: "showall",
					wmode: "window",
					devicefont: "false",

					bgcolor: "#fefefe",
					name: "synvisc",
					menu: "true",
					allowFullScreen: "false",
					allowScriptAccess: "sameDomain",
					movie: "synvisc",
					salign: ""
				};
				// html attributes to be placed on the resulting object tag
				//var attributes = { codebase: "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" };
				swfobject.embedSWF($this.attr("href"), $this.attr("id"), width, height, "8", "", flashvars, parameters);
				if (existingID == "") {
					$j("#noncollidingidvalue").removeAttr("id");
				}
			});
		},
		CallbackPostRemove: function() {
			var url = "http://" + window.location.hostname;
			if (surveyFinished) {
				url = url + "/survey/finished.aspx?height=400&width=330";
			}
			else {
				url = url + "/survey/not-finished.aspx?height=400&width=330";
			}

			// Open the post knee pain survey on a delay to allow the first thickbox to finish being removed.
			setTimeout(function() {
				tb_show("We need your feedback on the Knee Pain Assessment", url, false);
			}, 750);
		}
	});

	// create click event to set a global varible used to pass to a flashvar
	$j("div.knee-pain-assessment input[type=radio]").click(function() {
		selectedKneePainValue = $j(this).attr("value");
	});
	
    $j('.type-numeric').filterAlphaInput();
    
	$j(".tabs").IX_tabs();
	
	textSize();

    if( $j('body.team-hank').length && $j('#donation-progress').length) {
	    var query = FB.Data.query('SELECT fan_count, page_url FROM page WHERE page_id='+291833624194);
	    query.wait(function(rows) {
            var fancount = rows[0].fan_count; 
	        $j("#donation-progress").progressWidget(fancount);
	    });
	}


});      // document ready / end jquery functions
/**/
var IX_open = window.open;
window.open = function(u, n, f, r){
    if (u == "http://www.surveymonkey.com/jsPopInvite.aspx?sm=F5ILTsXQgfNEEF%2fK1ncNYA%3d%3d" ) { 
        var $window = $j(window),
            left = ($window.width()-969)/2 + 70,
            top = (window.outerHeight) ? window.outerHeight - $window.height() + 150 : 180,
            duration = 600,
            currentLeft = 0,
            step = 0,
            stepLength = 50,
            steps = duration/stepLength;
            
        sm_window = IX_open('', n, f+',top='+top, r);
        
        var moveit = function(){
            if (++step < duration/stepLength) {
                sm_window.moveBy(left/steps,0);
                
            } else {
                clearInterval(interval);
                sm_window.resizeTo(300, 220);
                sm_window.location = u;
            }
        };
        
        var interval = setInterval(moveit, stepLength);
    }
   else { IX_open(u, n, f, r); }
    
}


// creates a FAQ; expects a dl.
jQuery.fn.makeFAQ = function() {
	$j(this).find("dd").hide().end().find("dt").click(function() {
		var answer = $j(this).next();
		if (answer.is(":visible")) {
			answer.slideUp();
		} else {
			answer.slideDown("slow");
		}
	});
	if (window.location.hash) {
		setTimeout(function() { $j("a[name=" + window.location.hash.substr(1) + "]").parent().click(); }, 750);
	}

};
jQuery.fn.progressWidget = function(fancount){
    if(fancount) this.text('$'+fancount);
	return this.each(function(){
		var $this = jQuery(this),
			val = parseInt($this.text().replace('$','').replace(',','')/100);
		if (val > 10000) { val = 10000; }
		if (val < 0) { val = 0; }
			
		var backgroundTop = -24 - val;
		
		$this.addClass('IX_progressWidget').wrapInner('<div class="level"></div>').prepend('<div class="thermometer"></div>');
		$this.css('background-position', '-55px '+backgroundTop+'px').find('.level').css('margin-top', 98 - val +'px');
	});
}

// generic tab builder
jQuery.fn.IX_tabs = function(tab) {	
	return this.each(function() {
		var $container = jQuery(this), 
			$tabs = jQuery("a", this),
	 		panes = new Array();

		$tabs.each(function () {
			var $this = jQuery(this);

			// using the href to make the collection of panes			
			var pane = $this.attr('href');
			if (pane.indexOf("#") != 0) {
				return true; 
			};
		 	panes.push(pane);

			$this.bind("click", function(){
				//build the jq selector. cheap.
				jQuery(panes.join(",")).hide();

				//do some class switching
				$container.find('.active').removeClass('active');
				$this.parent("li").addClass("active");

				jQuery(pane).show();
				return false;
			});
		});
		
		// set which tab to show
		// if .default is available, get its index and set it. else, check for a tab index passed in or set to 0
		var show = jQuery('a.default',$container).length ? $tabs.index(jQuery('a.default')) : tab || 0;
				
		// this line is pretty gross, but cheap
		// make sure the tab we think we can show is actually there. if so, click it. else click the first tab
		$tabs.eq(show).length ? $tabs.eq(show).click() : $tabs.eq(0).click();
	});
};


// toggle visibility of questions in print view
function printQuestions() {

	$j(".questionstoprint input").change(function() {
		$j(this).parent().toggleClass("print");
	});
	$j(".checkall input").click(function() {
		if ($j(this).is(":checked")) {
			$j(".questionstoprint input").attr("checked", "checked").parent(":not(.print)").addClass("print");
			$j(".checkall input").attr("checked", "checked");
		} else {
			$j(".questionstoprint input").removeAttr("checked").parent().removeClass("print");
			$j(".checkall input").removeAttr("checked");
		}
	});

}

function makeFAQ() {
	$j("#faq").find("dd").hide().end().find("dt").click(function() {
		var answer = $j(this).next();
		if (answer.is(":visible")) {
			answer.slideUp();
		} else {
			answer.slideDown("slow");
		}
	});
}






function internalPop(e) {

	// hide external
	$j("#exitconfirm").hide();

	var $this = $j(this);
	var $offset = $this.offset();

	// clean up
	if ($this.hasClass("popped")) {
		$j("#internal").hide();
		$this.removeClass("popped");
		return false;
	}

	$this.addClass("popped");

	// text messages for external and genzyme sites
	var parts = $this.attr("title").split(" - ");
	var message = {
		title: parts.length > 1 ? "<h3>" + parts[0] + "</h3>" : "",
		contents: parts.length > 1 ? "<p>" + parts[1] + "</p>" : "<p>" + parts[0] + "</p>"
	};
	var note = message.title + message.contents;

	if (!document.getElementById("internal")) {
		var $exitconfirm = $j('<div id="internal"><div id="internalmessage"></div></div>').css('visibility', 'hidden');
		$exitconfirm.appendTo("body");
	}
	$j("#internalmessage").html(note);
	$j("#internal").css({ left: $offset.left + "px", top: ($offset.top - $j("#internal").height() - 26) + "px", visibility: "visible" }).show();

	e.preventDefault();
}






function TrackPrintLink(obj) {
	var s = s_gi(s_account);
	s.tl(obj, "o", "Print this page");
}

// Text size widget
var textSize = function() {

	var baseSize = 12;
	var textsize = getCookie("textsize");
	var coefficient = 1.0;
	if (textsize) {
		coefficient = parseFloat(textsize, 10);
	} else {
		setCookie("textsize", 1.0);
	}

	var FontController = {
		BaseSize: baseSize,
		Coefficient: coefficient,
		IncrementBy: 0.2,
		Minimum: .6,
		Maximum: 1.4,

		SetSize: function() {
			var newSize = this.BaseSize * this.Coefficient;
			setCookie("textsize", this.Coefficient);
			$j('body').css({ fontSize: newSize });
			// prevent change rendering bug in IE <6 on search results page
			if (document.all) {
				$j(".search button").focus().blur();
			} // if document.all			
		},

		Increment: function() {
			var newCo = this.Coefficient + this.IncrementBy;
			if (newCo <= this.Maximum) {
				this.Coefficient = newCo;
				this.SetSize();
			}
		},

		Decrement: function() {
			var newCo = this.Coefficient - this.IncrementBy;
			if (newCo >= this.Minimum) {
				this.Coefficient = newCo;
				this.SetSize();
			}
		},

		Reset: function() {
			this.Coefficient = 1.0;
			this.SetSize();
		}

	};

	if (coefficient != 1.0) {
		FontController.SetSize();
	}

	// Set up onclick functions	
	$j("#regular").click(function() {
		FontController.Reset();
		return false;
	});
	// Increase Font Size
	$j("#large").click(function() {
		FontController.Increment();
		return false;
	});
	// Decrease Font Size
	$j("#small").click(function() {
		FontController.Decrement();
		return false;
	});

}; // textSize


// variable and functions for the survey which follows filling out the knee pain assessment flash tool
var surveyFinished = false;
function set_flag(surveyAction) {
	if (surveyAction == "print" || surveyAction == "email") {
		surveyFinished = true;
	}
}




// clean console.log
function cl(logit) { if (window.console && window.console.firebug) { console.log(logit) } }; //cl()
// example: cl("If you use cl() instead of console.log(), it won't break IE when you forget to take it out.");

// todo - Move to universal.js
// Cookies get/set/delete
function getCookie(name) {
	var start = document.cookie.indexOf(name + "=");
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring(0, name.length))) {
		return null;
	}
	if (start == -1) return null;
	var end = document.cookie.indexOf(";", len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
}
function setCookie(name, value, expires, path, domain, secure) {
	var today = new Date();
	today.setTime(today.getTime());
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + (expires));
	document.cookie = name + "=" + escape(value) +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}
function deleteCookie(name, path, domain) {
	if (getCookie(name)) document.cookie = name + "=" +
			((path) ? ";path=" + path : "") +
			((domain) ? ";domain=" + domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function select_row(row, color) {
	if (row.parentNode.parentNode.style.backgroundColor != color) {
		row.parentNode.parentNode.style.backgroundColor = color;
		row.parentNode.parentNode.className = 'print-yes'
	} else {
		row.parentNode.parentNode.style.backgroundColor = '';
		row.parentNode.parentNode.className = 'print-no'
	}
}
