// Cufon
Cufon.replace('h1, h2, .ctahead, .homectalink, .ctalink, .adheader, .printCAform, .direction, .tabbedcta, .homectahead, .adlink, .fightheader, .fightlink, .listitem a, .quizhead, .resultshead, #step1goto, #step2goback, #step2goto, #labelmessage, #returnmessage a, .homepanelhead, .zigg, .prescribeCallOut .head', { fontFamily: 'Ziggurat-Black' });
Cufon.replace('h3', { fontFamily: 'Avenir-Heavy', textShadow: '1px 1px rgba(255, 255, 255, 3)' });
Cufon.replace('h1 strong, .rightcallout, .panelhead, .ziggit', { fontFamily: 'Ziggurat-BlackIT' });


// home animations
var HomePanels = {
	options: {
		fx: {
			link: "cancel",
			property: "left",
			duration: 500
		}
	},
	
	curr: null,
	
	init: function() {
		
		this.toggles = $$(".forme a, .lovedone a");
		this.toggled = [
			$$(".formepanel, .formepanel2"),
			$$(".lovedonepanel, .lovedonepanel2")
		];
		
		this.toggles.each(function(el, i) {
			el.addEvent("click", function(e) {
				e.preventDefault();
				this.toggle(i);
			}.bind(this));			
		}, this);
		
		
		
		// make fx instances for each panel
		this.fx = [];
		this.toggled.each(function(arr, i) {
			this.fx.push([]);						
			
			for (var j = 0; j < arr.length; j++) {				
				this.fx[i].push(new Fx.Tween(arr[j], this.options.fx));
			}
			
		}, this);
		
		// show functions
		this.shows = [];
		this.shows.push(
			function() {					
				this.fx[0][1].element.setStyle("left", this.values[0][0][1]);
				this.fx[0][1].start(this.values[0][1][1]);
			}.bind(this),
			
			function() {
				this.fx[1][1].element.setStyle("left", this.values[1][0][1]);
				this.fx[1][1].start(this.values[1][1][1]);			
			}.bind(this)
		);
		
		// hide functions
		this.hides = [];
		this.hides.push(
			function() {								
				this.fx[0][1].element.setStyle("left", this.values[0][1][0]);
				this.fx[0][0].start(this.values[0][0][0]);
				
				if (this.curr === 0) this.curr = null;
			}.bind(this),
			
			function() {
				this.fx[1][1].element.setStyle("left", this.values[1][1][0]);
				this.fx[1][0].start(this.values[1][0][0]);			
				
				if (this.curr === 1) this.curr = null;
			}.bind(this)
		);
		
		this.values = [
			[
				[30, 273],
				[30, 516]
			],
			
			[
				[274, 514],
				[274, 754]
			]
		];
	},
	
	toggle: function(index) {
		var curr = this.curr,
			state = this.toggles[index].retrieve("panelstate") == "open",
			currstate = !!((curr !== null) ? this.toggles[curr].retrieve("panelstate") : null);
		
		this.curr = index;
		
		// there's a current one, and its not the one being clicked
		if (curr !== null && curr !== index) {			
			this[currstate ? "hide" : "show"](curr);
			this.toggles[curr].store("panelstate", currstate ? "closed" : "open");
		}
		
		this[state ? "hide" : "show"](index);
		this.toggles[index].store("panelstate", state ? "closed" : "open");

		return this;
	},
	
	show: function(index) {		
		var fxs = this.fx[index];
		
		// remove existing events
		fxs.each(function(fx, i) {
			fx.removeEvents("complete");			
		});
		
		
		fxs[0].addEvent("complete", this.shows[index]);
		fxs[0].start(this.values[index][0][1]);
		
		return this;
	},
	
	hide: function(index) {		
		var fxs = this.fx[index];
		
		// remove existing events
		fxs.each(function(fx, i) {
			fx.removeEvents("complete");			
		});
		
		
		fxs[1].addEvent("complete", this.hides[index]);		
		fxs[1].start(this.values[index][0][1]);
		
		return this;
	}
};


var Site = {
    init: function() {
        var navs = $$("#navmenu > li"),
            nav = document.id("navmenu"),
            currNav = document.getElement("#navmenu > .active"),
            over = null,
            activeClass = "active",
            inactiveClass = "inactive";

        if (currNav) {
            navs.each(function(el, i) {
                el.addEvents({
                    "mouseenter": function(e) {
                        if (currNav != this) {
                            currNav.removeClass("active").addClass("inactive").addClass("bluelink");
                        }
                        over = this.addClass("active");
                    },
                    "mouseleave": function() {
                        if (this != currNav && over == this) {
                            this.removeClass("active").removeClass("bluelink").addClass("inactive");
                            currNav.removeClass("inactive").removeClass("bluelink").addClass("active");
                        }
                    }
                });
            });

            nav.addEvent("mouseleave", function(e) {
                if (over != currNav) currNav.removeClass("inactive").addClass("active").removeClass("bluelink");
                over = null;
            });

        }
    },

    TalkToNurse: {
        init: function() {
            Site.RegFields = new FieldsManager("nurseForm", {
                labelSelector: ".longField label, .dobMonth label, .dobDay label",
                inputSelector: ".longField input[type=text], .dobMonth input[type=text], .dobDay input[type=text]"
            });
        }
    },
    ObcRegistration: {
        init: function() {
            Site.RegFields = new FieldsManager("obcRegForm", {
                labelSelector: ".longField label",
                inputSelector: ".longField input[type=text]"
            });
        }
    },
    Registration: {
        init: function() {
            Site.RegFields = new FieldsManager("regFormWrap", {
                labelSelector: ".longField label, .dobMonth label, .dobDay label",
                inputSelector: ".longField input[type=text], .dobMonth input[type=text], .dobDay input[type=text]"
            });

            //	============
            //	Toggle Forms
            //	============
            var radioButton = $$('.radioBtn');
            radioButton.addEvent('click', function(e) {
                e.preventDefault();
                this.addClass('radioSelected');
                this.getSiblings('.radioBtn').removeClass('radioSelected');
                var formWrapper = $$('.' + this.getProperty('rel')),
			formSiblings = formWrapper.getSiblings('.inFormLoop'),
			formSubToggle = $$('.formSubToggle');
                formWrapper.addClass('activeForm');
                $$(formSiblings).removeClass('activeForm');
                if (this.getProperty('rel') != 'form01') {
                    $$(formSubToggle).removeClass('activeForm');
                }
            });

            var curr = null,
			choiceBoxes = $$("#regFormWrap .takingNiaspan .choice"),
			choiceInputs = $$("#regFormWrap .takingNiaspan .choice .input input"),
			choiceQuestions = $$("#choiceQuestions .amTaking, #choiceQuestions .notTaking"),
			choiceIntros = $$("#choiceIntros .amTaking, #choiceIntros .notTaking"),
			register = document.getElement("#regFormWrap .siteForm"),
            registerIntros = document.getElement("#choiceIntros"),
            freeTrialOffer = document.getElement("#freeTrialOffer");

            var toggleChoice = function(index) {
                // deselect current if it exists
                if ($chk(curr) && index !== curr) {

                    choiceBoxes[curr].removeClass("active");
                    choiceInputs[curr].checked = false;
                    choiceQuestions[curr].hide();
                    choiceIntros[curr].hide();
                }
                // select choice
                choiceBoxes[index].addClass("active");
                choiceInputs[index].checked = true;
                choiceQuestions[index].show();
                choiceIntros[index].show();

                register.show();
                registerIntros.show();
                freeTrialOffer.hide();

                curr = index;
            };

            choiceInputs.each(function(input, i) {
                input.addEvent("click", function() {
                    if (this.checked) {
                        document.getElementById("choice").removeClass("active");
                        document.getElementById("choice2").removeClass("active");
                        toggleChoice(i);
                    }
                    else {
                        register.hide();
                        registerIntros.hide();
                        freeTrialOffer.show();
                        choiceBoxes[i].removeClass("active");
                    }

                });

                if (input.checked) input.fireEvent("click");

            });
        }
    },

    Locator: {
        init: function() {
            Site.LocatorFields = new FieldsManager("genForm", {
                labelSelector: ".longField label,  .zipField label",
                inputSelector: ".longField input[type=text],.zipField input[type=text]"
            });
        }
    },


    Ecard: {
        init: function() {
            Site.MyEcard = new EcardManager({
                0: $$("#step2goback"),
                1: $$("#step1goto, #step3goback"),
                2: $$("#step2goto")
            });

            var slides = [];
            slides.push(


            /* slide 1 */
				new EcardSlide(
					Site.MyEcard,
					function() {
					    this.radios = $$("#tab_step1 .inputs input[type=radio]");
					    this.radioToggles = $$("#tab_step1 .toggle");
					    this.cards = $$("#tab_step1 .card");

					    this.radioToggles.each(function(tog, i) {
					        tog.addEvent("click", function(e) {
					            if (i === this.choice) return;

					            if ($chk(this.choice)) this.cards[this.choice].hide();
					            this.cards[i].show()
					            this.radios[i].set("checked", "checked");

					            //omniture
					            e9 = (i < 2) ? "To Patient" : "To Caregiver";
					            var fullImgUrl = this.cards[i].getChildren()[0].src;
					            e10 = fullImgUrl.substring(fullImgUrl.lastIndexOf('/') + 1, fullImgUrl.length);

					            this.fireEvent("pick", [i]);

					            this.choice = i;
					        } .bind(this));
					        if (this.radios[i].get("checked")) tog.fireEvent("click");
					    }, this);
					},
					{
					    show: function() { },
					    hide: function() { },
					    reset: function() { },
					    valid: function() {
					        return true;
					    },
					    extendWith: {
					        choice: null
					    }
					}
				),


            /* slide 2 */
				new EcardSlide(
					Site.MyEcard,
					function() {
					    this.cards = $$("#tab_step2 .card");

					    var errorMsg = document.id("step2FormError");
					    this.validator = new Form.Validator(document.id("step2Form"), {
					        onFormValidate: function(passed, myform, e) {
					            this.isValid = passed;
					            this.fireEvent("fields", [this.validator.fields]);
					            errorMsg[(passed) ? "hide" : "show"]();
					        } .bind(this),
					        ignoreHidden: false
					    });
					    new FieldsManager("step2Form", {
					        labelSelector: ".longField label",
					        inputSelector: ".longField input[type=text]"
					    });


					    this.toName = document.id("toName");
					    this.fromName = document.id("fromName");

					    this.form = $$("body>form")[0];

					    this.sendBtn = document.id("step2goto");

					    this.sendBtn.addEvent("click", function() {
					        if (this.valid()) {
					            this.hasSent = true;
					            this.fireEvent("sent", true);
					            this.form.send();
					        }
					    } .bind(this));



					},
					{
					    show: function(i, manager) {
					        if (i === 1) {
					            this.visible = true;
					        }
					    },
					    hide: function(i, manager) {
					        if (i === 1) {
					            this.visible = false;
					        }
					    },
					    reset: function() { },
					    valid: function() {
					        return this.validator.validate();
					    },
					    extendWith: {
					        curr: null,
					        isValid: false,
					        hasSent: false,
					        show: function(index) {
					            if ($chk(this.curr)) {
					                this.cards[this.curr].hide();
					            }
					            this.cards[index].show();
					            this.curr = index;
					        }
					    }
					}
				),


            /* slide 3 
            new EcardSlide(
            Site.MyEcard, 
            function() {
            this.cards = $$("#tab_step3 .card");
            this.toName = document.id("toName");
            this.fromName = document.id("fromName");
						
						this.form = $$("body>form")[0];

						this.sendBtn = document.id("step3goto");						

						this.sendBtn.addEvent("click", function() {														
            this.hasSent = true;
            this.fireEvent("sent", true);							
            this.form.send();							
            }.bind(this));					
            },
            {
            show: function() {},
            hide: function() {},
            reset: function() {},
            valid: function() {							
            return this.hasSent;
            },
            extendWith: {
            curr: null,
            show: function(index) {								
            if ($chk(this.curr)) {
            this.cards[this.curr].hide();
            }
            this.cards[index].show();
            this.curr = index;
            },
            updateFields: function(toField, fromField) {
            this.toName.set("html",toField.get("value"));
            this.fromName.set("html",fromField.get("value"));
            }
            }
            }
            ),
            slide 3 */

            /* slide 4 */
				new EcardSlide(
					Site.MyEcard,
					function() {
					},
					{
					    show: function(id) {
					        if (id === 2 && !slides[1].hasSent) {
					            slides[1].sendBtn.fireEvent("click");
					        }
					    },
					    hide: function() { },
					    reset: function() { },
					    valid: function() {
					        return this.hasSent;
					    },
					    extendWith: {
					        hasSent: false
					    }
					}
				)
			);
            // show the initial image in other slides
            slides[1].show(slides[0].choice);
            //slides[2].show(slides[0].choice);			

            // change image in other slides when first slide changes			
            slides[0].addEvent("pick", function(i) {
                slides[1].show(i);
                //slides[2].show(i);
            });
            // update to and from in slide 3
            slides[1].addEvent("fields", function(fields) {
                //slides[2].updateFields(fields[2], fields[0]);
            });
            // prevent confirmation msg from showing till they've actually clicked "send"			
            slides[1].addEvent("sent", function(sent) {
                Site.MyEcard.show(3);
            });


            Site.MyEcard.loads(slides);
            Site.MyEcard.show(0);


        }
    }

};

window.addEvent("domready", function() {
	Site.init();
});


// Cookies
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];		
		while (c.charAt(0)==' ') c = c.substring(1,c.length); 
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}

// text size
var currentEl = null;
var currentSize = 1;

function setFontSize(size, el) {
    if (document.getElementById(el)) {
        clearOnClass();
        document.getElementById(el).style.color = '#666666';
    }
        var elements = $$("#textsizewrap, .textsizewrap");
        elements.setStyle("fontSize", size + 'em');
 /*   if (document.getElementById("textsizewrap")) {
        document.getElementById("textsizewrap").style.fontSize = size + 'em';
    }*/
    createCookie("font_sizer", size, "30");
}

function loadFontSize() {
    if (readCookie('font_sizer') == null) {
        currentSize = '1';
    } else {
        currentSize = readCookie('font_sizer');
    }

    if (currentSize == '1') { currentEl = 'smallTxt' }
    if (currentSize == '1.15') { currentEl = 'medTxt' }
    if (currentSize == '1.25') { currentEl = 'lrgTxt' }
    setFontSize(currentSize, currentEl);
}

function clearOnClass() {
    document.getElementById('smallTxt').style.color = '#0d5682';
    document.getElementById('medTxt').style.color = '#0d5682';
    document.getElementById('lrgTxt').style.color = '#0d5682'; 
}

function increaseFont() {
    if (currentSize == '1') { currentSize = '1.15' }
    else if (currentSize == '1.15') { currentSize = '1.25' }
    else { return }
    setFontSize(currentSize, null)
}

function decreaseFont() {
    if (currentSize == '1.25') { currentSize = '1.15' }
    else if (currentSize == '1.15') { currentSize = '1' }
    else { return }
    setFontSize(currentSize, null)
}


// Query string gatherer
function $get(key,url){
  if(arguments.length < 2) url =location.href;
  if(arguments.length > 0 && key != ""){
	  if(key == "#"){
		  var regex = new RegExp("[#]([^$]*)");
	  } else if(key == "?"){
		  var regex = new RegExp("[?]([^#$]*)");
	  } else {
		  var regex = new RegExp("[?&]"+key+"=([^&#]*)");
	  }
	  var results = regex.exec(url);
	  return (results == null )? "" : results[1];
  } else {
	  url = url.split("?");
	  var results = {};
		  if(url.length > 1){
			  url = url[1].split("#");
			  if(url.length > 1) results["hash"] = url[1];
			  url[0].split("&").each(function(item,index){
				  item = item.split("=");
				  results[item[0]] = item[1];
			  });
		  }
	  return results;
  }
}	  

// v2.0
function MM_openBrWindow_(theURL, winName, features) {
    window.open(theURL, winName, features);
}

function openDisclaimer(url) {
    MM_openBrWindow_('/common/modal/Exitsite.aspx?url=' + url, 'winDisclaimer', 'width=424,height=400');
}

function openSendFriend() {
    window.open('/common/modal/EmailFriend.aspx?url=' + escape(window.location.href),null,'scrollbars=no,resizable=no,width=424,height=400');
}

// v1.0
function openwindow(url) {
    window.open(url, 'interstitial', 'toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=490,height=400');
}

function openprintable(url) {
    window.open(url, '_blank', 'scrollbars=yes,resizable=yes,width=800,height=600');
}


function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');

    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

// flash movie functions
function thisMovie(movieName) {
	 if (navigator.appName.indexOf("Microsoft") != -1) {
		 return document.getElementById(movieName);//window[movieName];
	 } else {
		 return document[movieName];
	 }
}
function playVideo()
{
	thisMovie("videoHomePage").playVideo();
}
function resumeVideo()
{
	thisMovie("videoHomePage").resumeVideo();
}
function pauseVideo()
{
	thisMovie("videoHomePage").pauseVideo();
}
function stopVideo()
{
	thisMovie("videoHomePage").stopVideo();
}
function seekVideo(offset)
{
	thisMovie("videoHomePage").seekVideo(offset);
}
function setVideoVolume(level)
{
	thisMovie("videoHomePage").setVideoVolume(level);
}
function fullScreenVideo()
{
	thisMovie("videoHomePage").fullScreenVideo();
}
function loadVideoById(id)
{
	thisMovie("videoHomePage").loadVideoById(id);
}
function loadVideoPlayList(stringArray)
{
	thisMovie("videoHomePage").loadVideoPlayList(stringArray);
}
function goToVideoChapter(videoId, chapterId)
{
	thisMovie("videoHomePage").goToChapter(videoId, chapterId);
}
function videoOnLoad(id) {	
}
function videoOnPlay(id) {	
}
function videoOnStop(id) {	
}

function callFloodlight_new(catId) {
    var tag_url="http://fls.doubleclick.net/activityi;src=2644366;type=niasp995;cat="+catId+";ord="+Math.floor(Math.random()*999999)+"?";
    if (document.getElementById("DCLK_FLDiv")) { var flDiv = document.getElementById("DCLK_FLDiv"); }
    else { var flDiv = document.body.appendChild(document.createElement("div")); flDiv.id = "DCLK_FLDiv"; flDiv.style.display = "none"; }
    var DCLK_FLIframe = document.createElement("iframe");
    DCLK_FLIframe.id = "DCLK_FLIframe_" + Math.floor(Math.random() * 999999);
    DCLK_FLIframe.src = tag_url;
    flDiv.appendChild(DCLK_FLIframe);
}

window.addEvent("load", function() {
   loadFontSize();     
});
