var currClass = "lan_row";

function isNumeric(x) { 
	// regular expression that validates a value is numeric 
	var RegExp = /^(-)?(\d*)(\.?)(\d*)$/; 
	var result = x.match(RegExp); 
	return result; 
}


function runCalc(){
	var f = document.he4calcform;
	var ca125 = f.ca125.value;
	var he4 = f.he4.value;
	var index = "";
	var risk = "";
	//var fx = new Fx.Styles($('riskDiv'), {duration: 500, wait: false});
	
	$('#riskInput').html("");

	if(!isNumeric(ca125) || !isNumeric(he4)){
		alert("You must enter numbers for your CA 125 Value and your HE4 Value.");
		return;
	}
	
	
	if(f.meno[0].checked) {
		index = (-12) + (2.38*(Math.log(he4))) + (0.0626*(Math.log(ca125)));
	} else if (f.meno[1].checked){
		index = (-8.09) + (1.04*(Math.log(he4))) + (0.732*(Math.log(ca125)));
	} else{
		alert("You must chose Premenopausal or Postmenopausal.");
		return;
	}
	risk = (Math.exp(index) / (1+Math.exp(index)) *100 );
	risk = Math.round(risk*10)/10;
	
	$('#riskInput').html(risk + "%");
	
	var width = 160 * (risk/100);
	
	$("#riskDiv").animate({  width: width}, 500 );
	
}

var myLocation = window.location.href;
var locArray = new Array("staging","french","french_staging","italian","italian_staging","german","german_staging","spanish","spanish_staging");
var locprefix = "";

for(i=0; i<locArray.length; i++){
	if(myLocation.indexOf(locArray[i]) > -1){
		locprefix = locArray[i];
	}
}
if(locprefix == "") locprefix = "www";


var USPage = (window.location.href.indexOf("staging") != -1) ? "http://staging.he4test.com/us/ushome.html" : "http://www.he4test.com/us/ushome.html";
var ROWPage = (window.location.href.indexOf("staging") != -1) ? "http://staging.he4test.com/row/rowhome.html" : "http://www.he4test.com/row/rowhome.html";

var localPage = "http://" + locprefix + ".he4test.com/row/rowhome.html";
var localPageRoot = "http://" + locprefix + ".he4test.com/row/";


$(document).ready(function () {
							
	if($("body").attr('id') == "disclosure"){
		if($.cookie('disclosureROW') && $.cookie('disclosureROW') == "yes"){
			window.location = localPage;								 
		}
		
		$("#acceptCookie").bind("click", function(e){
			 e.preventDefault();
			$.cookie('disclosureROW', "yes", {path: '/' });
			window.location = localPage;
		});
	}
		
	if($("body").attr('id') != "surveyPop" && $("body").attr('id') != "thanks"){	
		if($.cookie('disclosureUS') && $.cookie('disclosureUS') == "yes"){
			$("option.lan_usa").attr('value',USPage);						 
		}
			
		if($.cookie('disclosureROW') && $.cookie('disclosureROW') == "yes"){
			$("option.lan_row").attr('value',ROWPage);	
		
		} else{
			
		}
	
	
		$("#langSel").sSelect();
		
		$("#langSel").bind("change",function(){
				window.location=$("#langSel option:selected").attr("value");
				
		 });
		
		if($("body").attr("id") == "calcPage"){
			runCalc();
			$('#calc_submit').bind('click', function(){runCalc();});
		}
		
		//show graphs if on last page of case study
		if($("body").hasClass("chartBody")){
			if(v1 != 0 || v2 != 0 || v3 != 0 || v4 != 0) {buildGraph(v1,v2, v3, v4, "myGraph" );}
			if(v5 != 0 || v6 != 0 || v7 != 0 || v8 != 0) {buildGraph(v5,v6, v7, v8, "myGraph2" );}
		}
		
		//if on a case study page
		if($("body").hasClass("questions")){
			//hide "other" text box
			$("#othertext1, #othertext2").addClass("invisible");
			
			//bind the submit button, which is on the question 2 page of the case study
			$("#submitButton").bind("click",function(e){
				//assign the cookie name from the class on the submit button
				//class on this button is based on which case study it is
				cookName = $(this).attr("class");
				//check to see if question 1 was answered and put in a cookie
				if($("input:checked").length != 0 && $.cookie(cookName)){
					value = $.cookie(cookName);
					
					//fill in hidden value in form
					$("#differentialdiagnoses").val(value);
					
					if(value == "other"){
						value2 = $.cookie("otherText");	
						$("#othertext1").val(value2);
					}
					
					//submit the form
					$("#casequestionsform").submit();
				}
				
				else{
					//if question 1 was not answered show the warning
					$("#questionWarning").removeClass("invisible");	
				} 
			 });
			
			//this binds the back/next buttons when clicked
			//saves the value from question 1 into a cookie
			$("#cookieButton, .cookie2 a").bind("click",function(e){
				if($("input:checked").length != 0){
					//save the cookie if an option was picked
					cookName = $(this).attr("class");
					$.cookie(cookName, null, {path: '/', domain: 'he4test.com'});
					$.cookie("otherText", null, {path: '/', domain: 'he4test.com'});
					
					
					if(cookName != "on"){
						
						value = $("input:radio[name='differentialdiagnoses']:checked").val();
						$.cookie(cookName, value, {path: '/', domain: 'he4test.com'});
						
						if (value = "other"){
							
							
							value2 = $("#othertext1").val();
							
							$.cookie("otherText", value2, {path: '/', domain: 'he4test.com'});
						}
					}
					
					
				} 									 
			});
			//show/hide the "other" input text boxes
			$("form input:radio[name='differentialdiagnoses']").bind("click", function(){
				if ($("#other1").attr("checked")){		
					$("#othertext1").removeClass("invisible");
					
				} else{
					$("#othertext1").addClass("invisible");
				}	
			});
			
			$("form input:radio[name='differentialdiagnoses2']").bind("click", function(){
				if ($("#other2").attr("checked")){		
					$("#othertext2").removeClass("invisible");
					
				} else{
					$("#othertext2").addClass("invisible");
				}	
			});
			
			
		}
		
	}
	if($("body").attr("id") != "thanks" && $("body").attr("id") != "surveyPop"){
		Shadowbox.init({
		  players:    ["swf", "iframe"]
		});
	}
	
	var windowLocation = window.location.href;
	if(windowLocation.indexOf("romatools") == -1 && windowLocation.indexOf("romastaging") == -1) surveyStuff();	

});// JavaScript Document



/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};




var whichSurvey = Math.floor(Math.random()* 2 + 1);
var popupStatus = 0;
var leaving = true;

function setLeaving(){
	leaving = false;	
}

function setSurveyCookie(){
	
	$.cookie('survey', whichSurvey, {path: '/', domain: 'he4test.com'});
	$.cookie('taken', 'no', {path: '/', domain: 'he4test.com'});
	//$.cookie('pages',0, {path: '/', domain: 'taketherightpath.com'});
}

function surveyStuff(){
	if($("body").attr("id") == "thanks"){
		$.cookie('taken',"yes", {path: '/', domain: 'he4test.com'});
		surveyType = ($.cookie('survey')*1 == 1) ? "Pre-Survey" : "Post-Survey";
		
		$("#surveyType").attr("value",surveyType);
		$("#nothanks").click(function(){
			if(window.opener) window.close();
			else location.href = "http://www.he4test.com";						  
		});
		
	}
	else if($("body").attr("id") == "surveyPop"){
		
		loadPopup();
	}
	else if($.cookie('taken') && ($.cookie('taken') !=  "no")){
		//do nothing	
	}
	 else if(!$.cookie('survey') || $.cookie('survey') == ""){
		setSurveyCookie();
		
		if($.cookie('survey')*1 == 1) loadPopup();
		if($.cookie('survey')*1 == 2) postSurveyFunctions();
		
	}
	
		
	else{
		if($.cookie('survey')*1 == 2 || ($.cookie('survey') == 1 && $.cookie('taken') == "no")){
			
			if($.cookie('survey')*1 == 1 && $.cookie('taken') == "no") loadPopup();
			if($.cookie('survey')*1 == 2 && $.cookie('taken') == "no"){
				
				postSurveyFunctions();
			
			}
		}
	}
	
}

function postSurveyFunctions(){
	
	$(window).unload( function(){
		if($.cookie('taken') == "no" && leaving && 
		  ($("body").attr("id") != "surveyPop" && $("body").attr("id") != "thanks") &&
		   $.cookie('frompop') != "y") {
			var windowWidth = document.documentElement.clientWidth;
			var windowHeight = document.documentElement.clientHeight;
			myTop = (windowHeight/2-280/2);
			myLeft =  (windowWidth/2-515/2);
			windowVars = "height=308,width=488,top=" + myTop + ",left=" + myLeft + ",scrollbars=yes,resizable=yes,menubar=no,location=no,status=no,titlebar=no,toolbar=no";
			var myWindow = window.open("/limesurvey/ask.html", "surveyask", windowVars);
		} else if   ($.cookie('frompop') == "y"){
			$.cookie('frompop',null,{path: '/', domain: 'he4test.com'});
		}
	});
	
	$("a[href^='http']").attr('target','_self');
	$("a").click(function(){
		if (this.href.indexOf("://") == -1 || this.href.indexOf(window.location.host) > -1){
			leaving = false;
			
		} else{
			if( $.cookie('taken') == "no" && this.href.indexOf(window.location.host) == -1) {
				loadPopup();
				$(this).attr("target","_blank");
				return false;
			}
		}
	})
	
}

function popUpNoSurvey(){
	killSurvey("never");
	if(window.opener) window.close();
	else { window.parent.Shadowbox.close();	}	
}

function buildHtml(){
	var html = "<div id=\"popupSurvey\" class=\"popupWindow\">"
	html += "<p>We'd like to invite you to participate in an online survey to help us improve your experience on He4Test.com. There are only 8 questions and it will only take 5 minutes. </p>";
	html += "<p>Would you like to participate? </p>";
	html += "<p><a href=\"javascript:surveyHref()\" id=\"yessurvey\">Yes</a>";	
	html += "<br /><a href=\"javascript:popUpNoSurvey()\" id=\"nosurvey\">No, thank you.</a></p>";
	
	surveyType = ($.cookie('survey')*1 == 1) ? "Pre-Survey" : "Post-Survey";
	
	//html += "<p>(Test Purposes: " + surveyType + ")</p>";
	
	html += "</div>";
	
	return html;
}

function surveyHref(){
	myhref = "";
	if($.cookie('survey') == 1){
		 myhref = "http://www.he4test.com/limesurvey/index.php?sid=73137&lang=en";
	} else {
		 myhref = "http://www.he4test.com/limesurvey/index.php?sid=55579&lang=en";
	}
	
	if($("body").attr('id') == "surveyPop"){
		if(window.opener){
			$.cookie('frompop','y',{path: '/', domain: 'he4test.com'});
			window.opener.location.href = myhref;
			window.close();
		} else if (window.parent){
			window.parent.location.href = myhref;		
		}
		else{
			//window.moveTo(0,0);
			window.resizeTo(800,600);
			window.location.href = myhref;
		}
	} else{
		top.location.href = myhref;	
	}
}

function loadPopup(){
	html = buildHtml();
	if($("body").attr("id") == "surveyPop"){
		$("body").append(html);
	} else{
		window.setTimeout( openSurvey, 3000 ); 
		
	}
}

function openSurvey(){
	openShadowbox("/limesurvey/ask.html","iframe",488,308);
}

function openShadowbox(content, player, width, height){
	Shadowbox.open({
			content:    content,
			player:     player,
			width:     	width,
			height:     height
			
		});
}



function killSurvey(value){
	$.cookie('taken',value, {path: '/', domain: 'he4test.com'});	
}
