/*
	
	Project Name Global Javascript Functions
	By  - ISITE Design

*/

// jquery no conflict. use $j or jQuery outside of ready function
var $j = jQuery.noConflict();
var flashXmlPath = "/sites/SynviscOneUS/_resources/flash/home.xml";
var flashWidth = "948";
var flashHeight = "362";




// jQuery document ready
jQuery(function($) {

// 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/SynviscOneUS/_resources/flash/knee-pain-assessment",
                    xml_path: "/survey.xml",
                    template_path: "/reportTemplate.html",
                    service_provider: "http://" + window.location.hostname + "/sites/SynviscOneUS/_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() {
            //NOTE:Only commentted out the code because they may choose to bring this back.
            //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);
        }
    });


	$("a[rel^='prettyPhoto']").prettyPhoto({animationSpeed:'fast',slideshow:10000});

	// JS enabled
	$('html').addClass('js');

	// Few setups for IE6
	if (document.all) {
		//add class to drop downs and buttons 
		$('#nav li, button').hover(
			function() { $(this).addClass('over'); },
			function() { $(this).removeClass('over'); }
	    );
	} // if document.all

	// real time testing of secondary body classes on any layout.
	//$("body").bodyClassControl();

	// sets value of upper right search box to label; clears value on focus and resets to label on blur.
	$("#utility-search input").inputSetter();

	// adds slide-down functionality to language chooser.
	$('#utility-language-toggle').listingToggle();

	// adds print and email page links and binds printing/email functionality.  
	// send true to insertSharingLinks to get thickbox functionality.
	//$('<div id="share-page"></div>').appendTo('#utilities-page').insertSharingLinks(true);

	if ($('.tabs').length) { $('.tabs').IX_Tabs(); }

	if ($('.videos .tabs').length) {
		$('li', this).hover(
			function() { if ($(this).hasClass('active')) { return; } else { $(this).addClass('over'); } },
			function() { $(this).removeClass('over'); }
		).find('.summary').wrapInner('<div class="content"></div>').click(function() { $(this).prev().click().end().parent('li').removeClass('over'); });
	}

	if (('#flash-promo').length) {
		var flashvars = {};
		flashvars.base_path = "";
		flashvars.img_path = "";
		flashvars.xml_path = flashXmlPath;
		flashvars.css_path = "/sites/SynviscOneUS/_resources/css/flash.css";
		var params = {scale:"noScale"};
		var attributes = {};
		swfobject.embedSWF("/sites/SynviscOneUS/_resources/flash/home_flash.swf", "flash-promo", flashWidth, flashHeight, "9.0.0", false, flashvars, params, attributes);
	}

	if ($('#hcp-flash-promo').length) {
		var flashvars = {};
		flashvars.base_path = "";
		flashvars.img_path = "/sites/SynviscOneUS/_resources/flash/images/";
		flashvars.xml_path = "/sites/SynviscOneUS/_resources/flash/hcp.xml";
		var params = {};
		params.wmode = "transparent";
		var attributes = {};
		swfobject.embedSWF("/sites/SynviscOneUS/_resources/flash/hcp_flash.swf", "hcp-flash-promo", "948", "362", "9.0.0", false, flashvars, params, attributes);
	}

	// glossary tooltips
	$('.glossary_term').tooltip({
		track: false,
		showURL: false,
		showBody: " - ",
		extraClass: "definition",
		top: 20,
		left: -26
	});

	$('.faq').makeFAQ();

});      // document ready


// application logic


// jQuery plugins
/*
	Input Setter
	pull label and insert as field. clear with click.	
	optional lower param if == 1, string toLowerCase	

	ex: $("#sitesearch input").inputSetter(1); // makes default text lowercase
		$("#sitesearch input").inputSetter(); // no lowercasing
*/

jQuery.fn.inputSetter = function(lower) {	
	return this.each(function() {
		var $input = $j(this);
		var $label = $j("label[for='"+$input.attr("id")+"']");
		var labeltext = lower && lower==1 ? $label.text().toLowerCase() : $label.text();
		$label.hide();	
		$input.val(labeltext);		
		$input.focus(function() { if (this.value == labeltext) { this.value = ""; }	})
			  .blur(function() { if (!this.value.length) { this.value = labeltext; } });		
	});
};

// adds animation to language toggle
jQuery.fn.listingToggle = function() {
	return this.each(function(){
		var $this = $j(this);
		var $control = $j($this.find('.control'));
		var $list = $j($this.find('ul'));
		
		// set current langage in heading (h5)
		$this.find('h5').text($list.find('.on').text());
		
		$this.click(function(){
			if ($control.hasClass('open')) {
				$list.slideUp('fast', function(){$control.removeClass("open");});
				
			} else {
				$control.addClass('open');
				$list.slideDown('fast');
			}
		});
		return false;
	});
};


// end inputSetter
// creates a simple accordian FAQ; expects a dl.
jQuery.fn.makeFAQ = function() {
	$j(this).addClass('IX_faq')
	.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);
	}

}


// generic tab builder
jQuery.fn.IX_Tabs = function() {
	var counter = 0;
	return this.each(function() {
		var $container = jQuery(this), 
			tabs = $j("a", this),
	 		panes = new Array(),
			intro = $j('.introduction', $container.parent());
			intro.attr("id", "intro-"+(++counter));

		tabs.each(function () {
			var $this = jQuery(this);

			// using the href to make the collection of panes			
			var pane = $this.attr('href');
		 	panes.push(pane);

			$this.bind("click", function(){
				//build the jq selector. cheap.
				$j(panes.join(",")).hide();

				//do some class switching
				$container.find('.active').removeClass('active');
				$this.parent("li").addClass("active");

				$j(pane).show();
				return false;
			})
		})
		if (intro.length) { $j(panes.join(",")).hide(); panes.push('#intro-'+counter); } else { $container.find("a:first").click(); }

	});
};




jQuery.fn.bodyClassControl = function() {
	
	var layoutContainers = "#primary, #secondary, #tertiary, #footer";
	
	$j(layoutContainers).addClass("layout");
	
	if (this.get(0).tagName == "BODY") { var $body = this; }
	else { var $body = $("body"); }
	var baseClass = $body.attr("class");
	
	switch(baseClass) {
		case "page-support":
			var classList = Array("home", "landing", "base", "base-feature", "interior", "interior-feature", "interior-landing", "interior-landing-feature");
			break;
		case "page-branching":
			var classList = Array("home", "landing");
			break;
		case "page-content":
			var classList = Array("base", "base-feature", "interior", "interior-feature", "interior-landing", "interior-landing-feature");
			break;
		default:
			alert("Error in bodyClassControl: class "+baseClass+" not recognized.");
			return false;
	}
	
	var $selector = $j("<select id='jqBodyClassControl'></select>");
	$selector.append("<option value='-1' selected>no class appended</option>");
	for(i=0; i<classList.length; i++) {
		$selector.append("<option value='"+i+"'>"+classList[i]+"</option>");
	}
	$selector.change(function(e) {changeClass(e)});
	$body.append($selector);
	
	var changeClass = function(e) {
		
		var newClass = (e.target.value > -1) ? " "+classList[e.target.value] : "";
		$body.attr("class", baseClass+newClass);
	}
};

// utility functions

// simple print page
function printCall() { window.print(); }

// 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";
}
// end cookies


// 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.");


// IE6 fixes
// make sure IE has the abbr and acronym tag
if(document.all){
	document.createElement("abbr");
	document.createElement("acronym");
}
// prevent IE6 flicker
try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}

// Text size widget
$j(window).load(function() {
	
	var baseSize = 16; // ie fails detecttion. parseFloat($j('html').css('font-size'), 10);
	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('html').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 the size on clicks
	$j('#utility-text-size a').click(function() {
		
		var id = $j(this).attr("id");
		switch(id) {
			case "regular":
				FontController.Reset();
				break;
			case "large":
				FontController.Increment();
				break;
			case "small":
				FontController.Decrement();
				break;
		}
		
		//$j('#resizer a').removeClass("on");
		//$j(this).addClass("on");	
		
		return false;
	});	

});

 // 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/SynviscOneUS/_resources/flash/knee-pain-assessment",
            xml_path: "/survey.xml",
            template_path: "/reportTemplate.html",
            service_provider: "http://" + window.location.hostname + "/sites/SynviscOneUS/_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");
        }
    });

