/*****************************************************************************************************
*** @title		RiskQuiz2 Lib
*** @summary	RiskQuiz2's controlling functions
***
*** @author		mrc based on a sample script by www.iamproheart.com
*** @since		Version 1.0
*** @copyright	Copyright (c) 2010, The Cactus Group
******************************************************************************************************/

// BMI safe value variable
var maxSafeBMI = 25;

// questions required data, organized in an array as follows: 
//		first line  = question number;
//		second line = question;
//		third line	= answers value for risk's calc
//		fourth line	= posible options
var questions = {
    1:
	{ question: "Pick One:",
        'none': 0, //Removed 'Man': 'Male', - So it doesn't flag male as a risk factor
        options: ['Man', 'Woman']
    },

    2:
	{ question: "Pick One:",
        '40more': 1,
        options: ['Under 40', '40more']
    },

    3:
	{ question: "Pick One:",
        'African American': 1,
        optbtn: ['btnRiskCaucasian',
	           'btnRiskAfricanAm',
	           'btnRiskAsian',
	           'btnRiskHispanic',
	           'btnRiskAmIndian',
	           'btnRiskOther'],
        options: ['Caucasian',
				'African American',
	    	    'Asian/Pacific Islander',
	    	    'Hispanic',
	    	    'American Indian',
	    	    'Other']
    },

    4:
	{ question: "Does heart disease run in your family?",
        'Yes': 'Family History of Heart Disease',
        options: ['Yes', 'No']
    },

    5:
	{ question: "Do you have high blood pressure, 140/90 or higher?",
        'Yes': 'High Blood Pressure',
        options: ['Yes', 'No', 'Don\'t Know']
    },

    6:
	{ question: "Are you a smoker or have you been a smoker in the last 3 years?",
        'Yes': "Smoker",
        options: ['Yes', 'No']
    },

    7:
	{ question: "Do you exercise for 30 minutes or more on most days?",
        'No': "Physical Inactivity",
        options: ['Yes', 'No']
    },

    8:
	{ question: "Do you have diabetes or take medicine for your blood sugar? ",
        'Yes': 'Diabetes',
        options: ['Yes', 'No']
    },

    9:
	{ question: "Have you had a heart attack?  ",
        'Yes': 'Previous Heart Attack',
        options: ['Yes', 'No']
    },

    10:
	{ question: "Have you had a stroke or TIA (mini-stroke)?  ",
        'Yes': 'Previous Stroke',
        options: ['Yes', 'No']
    },

    11:
	{ question: "Do you have high cholesterol, 200 mg/dL or higher? ",
        'Yes': 'High Cholesterol',
        options: ['Yes', 'No', 'Don\'t Know']
    },

    12:
	{ question: "Is your HDL (GOOD) cholesterol less than 40mb/dl? ",
        'Yes': 'Low HDL Cholesterol',
        options: ['Yes', 'No', 'Don\'t Know']
    },

    13:
	{ question: "What is your body mass index (BMI)?",
        input: ['HEIGHT', 'WEIGHT']
    }
}


function onDocumentReady() {
    setupPageClicks();
}


function setupPageClicks() {
    setupBtnHover();			// activates switch between button's images for over/out mouse events
    showWarningSignsTrigger();  // displays 'read more' info at the bottom of the page
    
	$('#startQuiz').click(function(event){
		//alert("estoy entrando al evento click");
        quiz(1, 0, 0);
    });
}


function setupBtnHover() {	// activates switch between button's images for over/out mouse events
    $("img.btnHover").live('mouseover', function() {
        imgsrc = $(this).attr('src').replace(/\.gif/, 'Hover.gif').replace(/(Hover)+/, 'Hover');
        $(this).attr('src', imgsrc);
    }).live('mouseout', function() {
        imgsrc = $(this).attr('src').replace(/(Hover)*\.gif/, '.gif');
        $(this).attr('src', imgsrc);
    });
}


function showWarningSignsTrigger() {	// displays 'read more' info at the bottom of the page
    $("#warningSignsTrigger").show();
    $("#warningSignsTrigger a").live("click", function() {
        $('#warningSignsMore').show('slow');
        $("#warningSignsTrigger").hide();
        $("#warningSignsMore").live("click", function() {
            $("#warningSignsMore").hide('slow');
            showWarningSignsTrigger();
            return false;
        });
        return false;
    });
}


function quiz(questionNum, answerNum, answer) {
	//alert("entrando a la funcion quiz");
    if (answerNum > 0) {
        saveLastAnswer(answerNum, answer);
    } else {
        riskHtml = ''; // reset when they start over
    }

    //questionNum = isdigit(questionNum) ? questionNum : 1;
    var html = '';
    var q = questions[questionNum];

    html += '<p>Question ' + questionNum + ' of 13</p><h5>'
         + q.question
    	 + '</h5>';
    
	if (q['input']) {
        //html += $('#bmiform').html;
        html += bmiHtml();
    } else {
        nextNum = questionNum + 1;
		
        for (var opt = 0; opt < q.options.length; opt++) {
            //if (opt == 3) html += '<div class="quizOptionSpacer">';

			if (q.optbtn) {
				img = q.optbtn[opt];
			} else {
				img = 'btnRisk' + q.options[opt].replace(/[' ]/g, ''); // btnRiskDontKnow
			}
			
			html += "<span class='quizButton'><img onclick='quiz(" + nextNum
			+ "," + questionNum + "," + opt + "); return false;' class='btnHover' src='/html/images/knowrisk/quiz2/"
			+ img + ".gif'></img></span>";
			
        }
    }
	
    $("#quizId").data('orightml', $("#quizId").html());
    $("#quizId").html(html);
    return false;
}

function saveLastAnswer(num, answer) {
    q = questions[num];
    if (q[q.options[answer]] != undefined) {
        factor = q[q.options[answer]] == 1 ? q.options[answer] : q[q.options[answer]];
		if (factor == "40more") factor = "40+";
        riskHtml += '<li>' + factor + '</li>';
    }
}

function bmiHtml() {
    return '<div class="quizBMI clearfix form">'
		    + '<label>Height (centimeters):</label>'
		    + '<input class="input" type="text" id="bmiCentimeters" />'
			+ '<br />'
		    + '<label>Weight (kilograms):</label>'
		    + '<input class="input" type="text" id="bmiKg" />'
		    + '<label id="bmiError"> &nbsp;</label><div class="submitdiv clearfix">'
		    + '<img id="submitBMI" onclick="quizCalc(); return false;" class="btnHover" src="/html/images/knowrisk/quiz2/btnRiskSubmit.gif">'
		    + '</div><div class="spacer"></div></div>';
}

function quizCalc() {
    // validate BMI
    n = {};
    valid = true;
    $.each(['bmiKg', 'bmiCentimeters'], function(index, id) {
        n[id] = parseInt($('#' + id).attr('value'));
        if (isNaN(n[id]) || (n[id] < 0) || (n[id] > 800)) {
            valid = false;
        }
    });
    if (!valid) {
        $(".quizBMI input").attr('value', '');
        $("#bmiError").html('Valid Numbers, Please');
        return;
    }
    bmi = cal_bmi(parseInt(n['bmiKg']), parseInt(n['bmiCentimeters']));
    //alert(bmi);
    if (bmi > maxSafeBMI) {
        riskHtml += '<li>BMI is ' + bmi + '</li>';
    }

    html = "<div class='quizResults'>" 
		//+ $('#quizHeader').html() 
		+ "<div id='quizResultsContent'>";
    if (riskHtml.length == 0) {
        html += $("#quizNoRisk").html();
    } else {
        html += $("#quizYesRisk").html();
    }
    $("#quizId").html(
		html + "</div>" 
		//+ $("#quizFooter").html() 
		+ $('#quizHeader').html() 
		+ "</div>");
	
	$('#btShare').open();

    if (riskHtml.length > 0) {
        $('#listRiskyFactors').html(riskHtml);
    }
    updateQuizLinks();
}


function updateQuizLinks() {

    $('#quizId .printQuiz').live("click", function(event) {
        event.preventDefault();
        resultsHtml = $('#quizResultsContent').html();

        var printForm = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
        + ' <html xmlns="http://www.w3.org/1999/xhtml" >'
        + ' <head>'
        + '     <title>CardioRisk Quiz Results</title>'
		+ '		<style type="text/css">'
		+ '			p.destacado {font-weight: 700; margin: 10px 0;}'
		+ '			ul {text-align: left; list-style-type: circle; list-style-position: inside;}'		
		+ '		</style>'
        + ' 	<link rel="STYLESHEET" href="/html/css/print.css" type="text/css" media="all">'
        + ' </head>'
        + ' <body id="bodyId" style="background-color: #FFFFFF;">'
		+ ' <div id="Wrapper">'
        + ' 	<div id="Header">'
		+ '			<div class="container">'
		+ '				<div id="Logo">'
        + '					<a href="/scripts/pages/en/home.php">'
        + '					<img src="/html/images/main/logo_aspirin_heather.gif" alt="">'
        + '					</a>'
		+ '				</div> <!-- fin de Logo-->'
		+ ' 		</div> <!-- find de container-->'
        + ' 	</div> <!-- find de Header-->'
        + '		<div id="ContentShadow"></div>'
		+ '		<div id="FlashStage" class="static-content">'
		+ '			<div class="container">'
		+ '				<h2>CardioRisk Quiz Results</h2>'
								+ resultsHtml +
		+ '	 	</div> <!-- find de container-->'
		+ '		</div><!-- find de FlashStage-->'
		+ '		<div id="ContentShadow"></div>'
        + '		<div id="Footer">'
		+ '			<div class="container">'
        + ' 			<div id="copyright">'
		+ '					Copyright 2009 Bayer HealthCare LLC. All Rights Reserved<br>'
		+ ' 				Unless otherwise indicated, all trademarks are owned by Bayer HealthCare LLC or licensed for its use. <br>'
		+ ' 				This site is intended to provide information to an international audience. Not all products discussed<br> on this site may be available'
		+ '					in your country and local prescribing information and approved<br> indications may differ from country to country.</div>'
		+ ' 			</div><!-- fin de copyright-->'
		+ ' 		</div> <!-- fin de container-->'
		+ '		</div> <!-- fin de Footer-->'
		+ '</div> <!-- fin de Wrapper-->'
        + '</body>'
        + '</html>'

        var w = window.open('QuizResults.htm', "Print", "status=0,menubar=1,toolbar=0");
        w.document.open();
        w.document.write(printForm.replace('NaN', ''));
        w.document.close();

    });
    $('#quizId .startOverQuiz').live("click", function() { quiz(1, 0, 0); });
    $('#quizId .shareQuiz').live("click", function() {
        html = "<div class='quizResults'>" + $('#quizHeader').html();
        html += $('#quizShare').html() + '</div>';
        $("#quizId").html(html);
		$('#btShare').open();
        $('#quizId #submitShareQuiz').live("click", function() { submitShareQuizProcess(); });
        updateQuizLinks();
    });
}


function printQuizResults() {

    resultsHtml = $('#quizResultsContent').html();

    $('#bodyId').html('<div id="quizPrintable"></div><div style="display:none">' + $('#bodyId').html() + '</div>');
    $('#quizPrintable').html(
			  '<img src="img/i_am_proHeart-logo-white-bg.jpg" width="273px" height="109px"></img>'
			  + '<div id="quizHeader2" style="text-align: center;">'
			  + '    <img src="img/icon-share.jpg"> <a href="/scripts/pages/en/tell_a_friend.php?p=/scripts/pages/en/prevention/cardio_risk_quiz.php" class="redlink" id="hypTellAFriend">Share</a>&nbsp;|&nbsp;'
			  + '	 <img src="img/icon-print.jpg"> <a href="javascript:window.print();" class="redlink printQuiz" id="hypPrint">Print</a>&nbsp;|&nbsp;'
			  + '    <p></p>'
			  + '</div>'
			  + '<div class="content clearfix">' + resultsHtml + '</div>'
			  + '<h3>www.aspirin.com</h3>');

	$('#hypTellAFriend').open();

    $('#bodyId').css({
        'background-image': 'none',
        'background-color': '#FFFFFF'
    });

    window.print();
}


function submitShareQuizProcess() {
    html = "<div class='quizResults'>"
		 + $('#quizHeader').html()
		 + $('#quizShareThanks').html()
		 + '</div>';
    $("#quizId").html(html);
	$('#btShare').open();
    updateQuizLinks();
}

// BMI Metrics: 1 meter = 100cms
// BMI = weight in kg / height in meters squared
function cal_bmi(kg, centimeters) {
    var meters = centimeters / 100;

    var bmi     = kg / Math.pow(meters,2);
	bmi = Math.round(bmi*100)/100; //round result to two decimals

	return bmi;
}

