// Glossary
// Term, definition - display on glossary page
var glossary = [
    ["Angina", ["Angina"], "Chest pain caused by lack of oxygen to the heart"],
    ["Arthritis", ["Arthritis"], "Pain and swelling of the joints"],
    ["Arteries", ["Arteries"], "Blood vessels that carry oxygenated blood"],
    ["Cholesterol", ["Cholesterol"], "A fat needed by the body to make hormones and essential cell components. Too much cholesterol in the blood can cause clogging of arteries."],
    ["Coronary artery disease", ["Coronary artery disease"], "When the heart is starved of oxygen and nutrients because of blocked or constricted arteries."],
    ["Coronary heart disease", ["Coronary heart disease"], "See coronary artery disease"],
    ["Diabetes", ["Diabetes"], "A condition in which a person is unable to regulate their blood sugar levels properly."],
    ["Familial hypercholesterolaemia", ["Familial hypercholesterolaemia"], "An inherited disorder in which members of a family have very high levels of LDL cholesterol."],
    ["Heart attack", ["Heart attack"], "Damage or death of some heart muscle due to interruption of its blood supply."],
    ["HDL cholesterol", ["HDL cholesterol"], "High-density lipoprotein cholesterol or 'good' cholesterol. There is evidence that HDL cholesterol actually reduces the amount of LDL (bad) cholesterol in the blood."],
    ["LDL cholesterol", ["LDL cholesterol"], "Low-density lipoprotein cholesterol or 'bad' cholesterol. LDL cholesterol causes fatty deposits in the inner lining of arteries, which can increase your risk of heart disease."],
    ["Plaque", ["Plaque"], "Is a deposit of cholesterol and other materials inside the wall of a blood vessel. It can cause the blood vessel to narrow (atherosclerosis) or rupture, leading to a heart attack or stroke."],
    ["Saturated fat", ["Saturated fat"], "Is usually found in animal products such as whole milk, eggs, and meats, and in some plant foods such as coconut or palm oils or hydrogenated oils. It is the main dietary culprit in raising blood cholesterol."],
    ["Stroke", ["Stroke"], "Damage or death of some brain tissue due to interruption to its blood supply."],
    ["TC (Total cholesterol)", ["Total cholesterol"], "Total cholesterol is mainly made up of LDL cholesterol, with some HDL cholesterol."],
    ["Triglycerides", ["Triglycerides"], "Another type of blood fat. High triglyceride levels often mean your HDL (good) cholesterol levels are too low. High triglyceride combined with high LDL (bad) cholesterol can further increase heart disease risk."]
];

function insertVideo(video,videoLoop,width,height){
    if(siteVersion == 'high')
    {
        // Check if we've played before and loop if so
        var flvPlay = (readCookie("video"+video)==null)?"flvMain":"flvLoop";
        createCookie("video"+video, true);
        // Write video player
        var so = new SWFObject("/Common/Flash/video.swf?flvMain=/Common/Flash/"+video+".flv&flvLoop=/Common/Flash/"+videoLoop+".flv&flvPlay="+flvPlay,video,width,height,8, "#000");
        so.addParam("wmode", "transparent");
        if (so.write("flash")) return;
    }
    $(".videoAlt").show();
}

function spotlight(src, type, cat, ord) {
    var axel = Math.random()+"";
    var a = axel * 10000000000000;
    $("body").append('<img src="http://ad.au.doubleclick.net/activity;src='+src+';type='+type+';cat='+cat+';ord='+ord+';num='+a+'?" width="1" height="1" border="1" alt="Spotlight"/>');
}

// jQuery plugin to fix images with transparent png source.
// Requires a single pixel transparent gif
// Explicitly sets the width
// Also applies a rollover if class of image is 'rollover'
jQuery.fn.pngFix = function() {
  return this.each(function(){
    jQuery(this).css({width: jQuery(this).width(), height: jQuery(this).height(), filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + jQuery(this).attr('src') + "\', sizingMethod='scale')"}).attr('src', '/Common/Images/x.gif').hover(function(){if (jQuery(this).is('.rollover')){jQuery(this).css({filter: jQuery(this).css("filter").split('_off').join('_on')})}}, function(){if (jQuery(this).is('.rollover')){jQuery(this).css({filter: jQuery(this).css("filter").split('_on').join('_off')})}});
  });
};

function validateDate(source,args){
    try {
        args.IsValid = true;
        var date = args.Value.split("/");
        var x = new Date(date[2], (date[1]-1), date[0]);
        args.IsValid = (parseInt(date[0]) == x.getDate() && parseInt(date[1]-1) == x.getMonth() && parseInt(date[2]) == x.getFullYear());
    } catch (err) {
        args.IsValid = false;
    }
}

function validateDateInfo(source,args){
    try {
        if (args.Value == "dd/mm/yyyy" || args.Value == "")
        return args.IsValid = true;
        var date = args.Value.split("/");
        var x = new Date(date[2], (date[1]-1), date[0]);
        args.IsValid = (parseInt(date[0]) == x.getDate() && parseInt(date[1]-1) == x.getMonth() && parseInt(date[2]) == x.getFullYear());
    } catch (err) {
        args.IsValid = false;
    }
}

function addGlossary(element){
    if(!element) return false;
	// Recurse backwards through the child nodes so we miss out on any ones we've just added.
	for (var i=element.childNodes.length-1; i>=0; i--)
		addGlossary(element.childNodes[i]);

	// Tag specifically titled elements
	if (element.title != "")
		for (var i=0; i<glossary.length; i++)
			for (var j=0; j<glossary[i][1].length; j++)
				if (element.title == glossary[i][1][j])
					tagElement(element, glossary[i]);

	// Process the current node if it's a text node and it's got a parent (why wouldn't it!?)
	if (element.nodeType == 3
	    && element.parentNode
	    && element.parentNode.tagName != 'A'
	    && element.parentNode.tagName != 'H2'
	    && element.parentNode.tagName != 'H3'
	    && element.parentNode.parentNode.className != 'references')
	{
		var text = element.data;
		var newText = null;
		var completed = 0;
		var cNext = "";
		var cPrev = "";
		var punc = "().,'\" :";
		var length = 0;
		while (completed < element.data.length)
		{
			var index = 0;
			var item = null;
			var position = text.length;
			
			// Find the next glossary term usage
			for (var i=0; i<glossary.length; i++)
				for (var j=0; j<glossary[i][1].length; j++)
				{
					index = text.toLowerCase().indexOf(glossary[i][1][j].toLowerCase(), completed);
					cNext = (index < text.length)?text.substring(glossary[i][1][j].length + index, glossary[i][1][j].length + index+1):"";
					cPrev = (index > 0)?text.substring(index-1, index):"";
					if (index < position && index != -1 && punc.indexOf(cPrev) != -1 && punc.indexOf(cNext) != -1)
					{
						position = index;
						item = glossary[i];
						length = glossary[i][1][j].length;
					}
				}
			
			// Add the data from before any found data
			element.parentNode.insertBefore(document.createTextNode(text.substring(completed, position)), element);
			completed = position;
			
			// Add found data with title tag.
			if (item != null)
			{
				var gloss = document.createElement("dfn");
				gloss.innerHTML = text.substring(completed, completed+length).replace(/&/, "&amp;");
				tagElement(gloss, item);
				element.parentNode.insertBefore(gloss, element);
				completed += length;
			}
		}
		// Remove the origional text node
		element.parentNode.removeChild(element);
	}
}

function tagElement(element, glossary){
	element.className = "glossary";
	element.title = glossary[0]
		+ ((glossary[1][0] != glossary[0] && glossary[2] != "")?" (" + glossary[1][0] + ")":"")
		+ ((glossary[2] != "")?": " + glossary[2].replace(/<(.|\n)+?>/g, ""):"");
}


// rotating content function
// the only variable is c a jQuery object of elements to rotate through
// i (current) and j (next) are calculated indices of the objects
function rotate(c){
    var i = $(c).index($(c+":visible")[0]);
    var j = (i+1 == $(c).size()) ? 0 : i +1;
    if ($.browser.msie && ($.browser.version == 6)) {
        $(c+":eq("+i+")").hide();$(c+":eq("+j+")").show();
    } else {
        $(c+":eq("+i+")").fadeOut(600, function(){$(c+":eq("+j+")").fadeIn();});
    }
}

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);
}

var textSize = readCookie('pcholTextSize');
var siteVersion = readCookie('pcholSiteVersion');
var survey = readCookie('pcholSurvey'); //eraseCookie('pcholSurvey');
var surveyTime = readCookie('pcholSurveyTime');
var currTime = new Date().getTime();

$(document).ready(function() {

    // Initiates the glossary function
    addGlossary(document.getElementById("text"));
    addGlossary(document.getElementById("cmp"));

    // checks for textSize cookie and creates user preferred setting
    if(!textSize || (textSize == 'normal')){
        $('.copy').css({fontSize: '1em'}); //10px
    } else if (textSize == 'small') {
        $('.copy').css({fontSize: '0.9em'}); //9px
    } else if (textSize == 'large') {
        $('.copy').css({fontSize: '1.4em'}); //14px
    }
    
    // checks for siteVersion cookie and displays the bandwidth selector
    // window if nothing has been set, or the user preferred site version
    if(!siteVersion){
        $('body').addClass('init');
        tb_show('','#TB_inline?height=300&width=600&inlineId=popBandwidth&modal=true;','');
    } else if (siteVersion == 'high'){
        $('a.highSpeed').addClass('selected');
    } else if (siteVersion == 'low'){
        $('a.lowSpeed').addClass('selected');
    }
    
    if(!survey){
        if(!surveyTime){
            createCookie('pcholSurveyTime',currTime,'')
        } else if(surveyTime<currTime-120000){
            $('a').click(function(){
                window.open('/Survey.aspx','surveypage','width=710,height=571');
                window.focus();
                createCookie('pcholSurvey','true',30);
            });
        }
    }
    
    // sets suckerfish nav classes in IE
    if ($.browser.msie) {
        $('.navigation li').hover(function(){$(this).addClass('sfhover');},function(){$(this).removeClass();});
        if ($.browser.version == 6) {
			$('.navProfile img, .navProfile input, #profileStart a img').each(function(){$(this).pngFix()});
		}
    }

    $("a[rel='external']").attr("target","_blank").click(function(){
        if(!$(this).attr('href').match('.pdf')){alert("You are about to leave " + document.domain + " and open a new website.\n\nThe information you are about to access is not provided by Pfizer Australia and may not comply with the Australian regulatory environment.\n\nThis link is provided for information only and does not constitute advice from Pfizer Australia. \n\nAny information should be discussed with your health care professional and does not replace their advice."); return true;}
    });
        
	$(".rollover").hover(function(){$(this).attr("src", $(this).attr("src").split('_off').join('_on'))}, function(){$(this).attr("src", $(this).attr("src").split('_on').join('_off'))});
	$('#siteVersion li:eq(0)').css({borderRight: '1px solid #666'});
	$('#quickLinks dd').hide();
	$('#quickLinks dt a').click(function(){$('#quickLinks dd').toggle()});
	
	$('#ddResults dd').hide();
	$('#ddResults dt').click(function(){$('#ddResults dd').toggle()});
	$('#ddResults li').each(
	    function(){
	        $(this).click(function(){var t = $(this).text();$('#ddResults dt span').text(t);$('#ddResults dd').hide();});
	    }
	);
	
	// set font and cookie state for textSize
	$('#textSize .small').click(function(){$('.colLeft div:eq(0), .control').css({fontSize: '0.9em'});createCookie('pcholTextSize','small',21);}); //9px
	$('#textSize .normal').click(function(){$('.colLeft div:eq(0), .control').css({fontSize: '1em'});createCookie('pcholTextSize','normal',21);}); //10px
	$('#textSize .large').click(function(){$('.colLeft div:eq(0), .control').css({fontSize: '1.4em'});createCookie('pcholTextSize','large',21);}); //14px
	
	// set click state for siteVersion controls
	$('a.lowSpeed').click(function(){
	    createCookie('pcholSiteVersion','low',21);          // set 'low bandwidth' cookie
	    $('a.highSpeed').removeClass('selected');           // remove selected class from broadband link
	    $(this).addClass('selected');                       // add selected class to dial up link
	    tb_remove();                                        // close lightbox
	    $('body').removeClass();                            // removse initial body class
	    window.location.reload();                           // reload page
	});
	$('a.highSpeed').click(function(){
	    createCookie('pcholSiteVersion','high',21);         // set 'high bandwidth' cookie
	    $('a.lowSpeed').removeClass('selected');            // remove selected class from dial up link
	    $(this).addClass('selected');                       // add selected class to broadband link
	    tb_remove();                                        // close lightbox
	    $('body').removeClass();                            // removse initial body class
	    window.location.reload();                           // reload page
    });
	
	$('.breadcrumbs li:eq(0)').css({borderWidth:'0'});
	$('.navigation ul').each(function(){$('li:eq(0) a', this).css({borderWidth:'0'})});
	
	$('.s1 .stripe tbody tr:odd').css({backgroundColor:'#dcb792'});
	$('.s2 .stripe tbody tr:odd').css({backgroundColor:'#96b6d7'});
	$('.s3 .stripe tbody tr:odd').css({backgroundColor:'#aa95a1'});
	$('.s4 .stripe tbody tr:even').css({backgroundColor:'#dbd2cc'});
	$('.s5 .stripe tbody tr:even').css({backgroundColor:'#dbb3b3'});
	
	$('.faq dd').hide();
	$('.faq dt').click(
	    function(){
	        if ($(this).next().css('display')=='block'){    // checks to see whether associated answer is currently open
	            $('.faq dd').hide();                        // hides all dd
	            $('.faq dt').removeClass('open');           // sets image state to closed
	        } else {                                        // *otherwise*
	            $('.faq dd').hide();                        // hides all dd
	            $('.faq dt').removeClass('open');           // sets all image state to closed
	            $(this).addClass('open').next().show();     // sets the current image state to open and displays associated answer
	        }
	    }
	);
	
	$('#results a').click(
	    function(){$('#results').hide();$('#calculator').show();$('#infoCalculator').empty().append('To calculate your BMI, simply enter your height (in cms) and your weight (in kgs). If you need to convert your measurements to metric <a href="">click here</a>.');}
	);
	
	$('#print, #printProfile a, .recipeMeta .print a').click(function(){window.print();});
	
	$('.calculate').click(
	    function(){
	        var cm = $("#BmiHeight").val();
	        var kg = $("#BmiWeight").val();
	        if((isNaN(cm))||(isNaN(kg))){
	            alert('Please enter a value for both your height and weight');
	            return false;
	        }
	        var result = parseInt(kg/Math.pow((cm*0.01),2));
	        $('#calculator').hide();
	        
	        if(result<20){
	            $('#results').show().removeClass().addClass('negative');
	            $('#results div span').text('Underweight');
	        } else if(result>25) {
	            $('#results').show().removeClass().addClass('negative');
	            $('#results div span').text('Overweight');
	        } else {
	            $('#results').show().removeClass().addClass('positive');
	            $('#results div span').text('Healthy');
	        }
            
            $('#infoCalculator').text('REMEMBER that the BMI calculator gives a general indication of your weight range. It is not suitable for everyone. Please consult your doctor if you have any questions about your BMI.');
            $('#results .height span').text(cm);
            $('#results .weight span').text(kg);
            $('#results em').text(result);
            return false;
	    }
	);
	
	$('#inlineBmi a').click(
	    function(){
	        var cm = $("#inlineBmi input:eq(0)").val();
	        var kg = $("#inlineBmi input:eq(1)").val();
	        if((isNaN(cm))||(isNaN(kg))){
	            alert('Please enter a value for both your height and weight');
	            return false;
	        }
	        var result = parseInt(kg/Math.pow((cm*0.01),2));
	        
	        var range = 'Healthy';
	        if (result > 25) {
	            var range = 'Overweight';
            } else if (result < 20) {
                var range = 'Underweight';
            }
	        
	        if (result > 25) {
	            $('#profileWeight input:eq(0)').attr({checked: true});
	        } else {
	            $('#profileWeight input:eq(1)').attr({checked: true});
	        }
	        $('#inlineBmi').hide();
	        $('#inlineBmiResult').empty().prepend('<p>BMI of '+result+', in the '+range+' range.</p>').show();
    });
    
    $("#submitAnswers").click(
        function(){
            var results = 0;
            $("#quiz input:checked").each(
                function(){
                    results += parseInt($(this).val());                     // adds selected input values to calculate a result
                    var q = parseInt($(this).attr('name').slice(-1))-1;     // determines which question has been answered (since it is possible that a question remain unanswered)
                    var a = $(this).attr('title');                          // gets the title (A,B,C,D) of the selected answer
                    $('#result strong').eq(q).text(a);                      // places the answer in the relevant results section
                }
            );
            $('#score strong').text(results);                               // appends result total
            $('#quizQuestions').hide();
            $('#quizResults').show();
        }
    );
  
    $('.searchResults tr:even td').css({backgroundColor: '#ebebeb;'});
    
    $('#guides .guide').hover(
        function(){$(this).css({background: '#e9e0da url(/Common/Images/bgGuide_on.jpg) 0 0 scroll no-repeat;', background: '#e9e0da'});$('a', this).css({background: 'url(/Common/Images/guideLink_on.gif) 0 100% scroll no-repeat'})},
        function(){$(this).css({background: '#e0d5ce url(/Common/Images/bgGuide_off.jpg) 0 0 scroll no-repeat', backgroundColor: '#e0d5ce'});$('a', this).css({background: '#dfd5cd url(/Common/Images/guideLink_off.gif) 0 100% scroll  no-repeat'})}
    ).click(
        function(){window.open($('a', this).attr('href'));return false;} //applies the anchor url to the entire guide panel, returns false so that two instances aren't triggered if the user clicks the anchor
    );
    
    if($('.datePicker').get(0)) {
        //if ($('.datePicker').val() == ""){$('.datePicker').val('dd/mm/yyyy');}
        $('.datePicker').datepicker({ showStatus: false, minDate: new Date(1920, 1, 1), yearRange: '1920:2008', buttonText: 'Calendar', buttonImage: '/Common/Images/iconCalendarPicker.gif', dateFormat: 'dd/mm/yy', showOn: 'both', buttonImageOnly: true});
    }
    
    $('#cholesterolTypes dt:odd, #cholesterolTypes dd:odd').css({backgroundColor: '#dcb792'});
    $('#cholesterolTypes dd:last').css({paddingBottom: '20px', background: '#dcb792 url(/Common/Images/cholesterolTypesBase.gif) scroll 0 100% no-repeat'});
    
    $('#profiler li').slice(1).hide();
    //$('#profiler li').not(':eq(1)').hide();
    $('#profileStart a').click(function(){
        try {
            spotlight(1751325, 'chole499', 'start504', 1);
        } catch(err) {
        }
        try {
            document.pageTracker._trackPageview('/goal/hhp/step1.html');
        } catch(err) {
        }
        $('#profiler li').hide();
        $('#profiler li#profileSmoke').show();
        $('#profilerStep').removeClass().addClass('step1');
    });
    $('.navProfile img:even()').click(function(){var i = $('#profiler li').index($('#profiler li:visible')[0]);document.pageTracker._trackPageview('/goal/hhp/step'+(i-1).toString()+'.html');$('#profiler li').hide();$('#profiler li:eq('+(i-1)+')').show();$('#profilerStep').removeClass().addClass('step'+(i-1));});
    $('.navProfile img:odd()').click(function(){var i = $('#profiler li').index($('#profiler li:visible')[0]);document.pageTracker._trackPageview('/goal/hhp/step'+(i+1).toString()+'.html');$('#profiler li').hide();$('#profiler li:eq('+(i+1)+')').show();$('#profilerStep').removeClass().addClass('step'+(i+1));});
    $('#inlineBmi, #inlineBmiResult').hide();
    $('#profileWeight input:eq(0), #profileWeight input:eq(1)').click(function(){$('#inlineBmi').hide();});
    $('#profileWeight input:eq(2)').click(function(){$('#inlineBmi').show();$('#inlineBmiResult').show();});
    
    $('#progress .control:first').css({background: 'url(/Common/Images/panelProgress.gif) 0 0 no-repeat'});
    
    if ($('.glossary').get(0)) {$('.glossary').Tooltip({track: true,delay: 0,showURL: false});}
    $('input.outlook').Tooltip({track: true,delay: 0,showURL: false});
    

    $('#messagePreview li').slice(1).hide();
    $('#messageTheme input:radio').click(function(){
        $('#messagePreview li').hide().eq($("#messageTheme input").index($("#messageTheme input:checked")[0])).show()
    });
    
    $('#pollSubmit').click(function(){
        jQuery.ajax({
            type:'GET',
            url:'/Common/Xml/userPoll.aspx',
            process:'true',
            dataType:'json',
            data:'answer='+$('#sidePoll fieldset input:checked').val(),
            error:function(XMLHttpRequest, textStatus, errorThrown){$('#sidePoll fieldset').empty().text('There has been an error.');},
            success:function(xmlData){
                $('#sidePoll input, #pollSubmit').remove();
                $('#sidePoll label').each(function(i){
                    $(this).append('<span><em></em>' + $(xmlData)[i] + '%</span>');
                    $('em', this).width($('em', this).width()*$(xmlData)[i]/100);
                    if(i%2)
                        $(this).addClass('odd')
                });
            }
        });
    });
    
});

$(window).load(function(){
    // rotating sidebar boxes
    // $('.feature').hide();
    // $('.feature:eq('+Math.floor(Math.random()*4)+')').show();
    
    $("div.feature").hover(function(){clearInterval(headline_interval);},function(){headline_interval = setInterval("rotate('div.feature')",6000);}).slice(1).hide();
    headline_interval = setInterval("rotate('div.feature')",5100);
    
    $("#callout h2").hover(function(){clearInterval(callout_interval);},function(){callout_interval = setInterval("rotate('#callout h2')",9000);}).slice(1).hide();
    callout_interval = setInterval("rotate('#callout h2')",9000);
});

