/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 03/01/2009 +r14
 */
(function(o){o.fn.jqm=function(f){var e={overlay:50,overlayClass:"jqmOverlay",closeClass:"jqmClose",trigger:".jqModal",ajax:n,ajaxText:"",target:n,modal:n,toTop:n,onShow:n,onHide:n,onLoad:n};return this.each(function(){if(this._jqm){return l[this._jqm].c==o.extend({},l[this._jqm].c,f)}p++;this._jqm=p;l[p]={c:o.extend(e,o.jqm.params,f),a:n,w:o(this).addClass("jqmID"+p),s:p};if(e.trigger){o(this).jqmAddTrigger(e.trigger)}})};o.fn.jqmAddClose=function(f){return k(this,f,"jqmHide")};o.fn.jqmAddTrigger=function(f){return k(this,f,"jqmShow")};o.fn.jqmShow=function(e){return this.each(function(){e=e||window.event;o.jqm.open(this._jqm,e)})};o.fn.jqmHide=function(e){return this.each(function(){e=e||window.event;o.jqm.close(this._jqm,e)})};o.jqm={hash:{},open:function(B,A){var m=l[B],q=m.c,i="."+q.closeClass,v=(parseInt(m.w.css("z-index"))),v=(v>0)?v:3000,f=o("<div></div>").css({height:"100%",width:"100%",position:"fixed",left:0,top:0,"z-index":v-1,opacity:q.overlay/100});if(m.a){return n}m.t=A;m.a=true;m.w.css("z-index",v);if(q.modal){if(!a[0]){j("bind")}a.push(B)}else{if(q.overlay>0){m.w.jqmAddClose(f)}else{f=n}}m.o=(f)?f.addClass(q.overlayClass).prependTo("body"):n;if(c){o("html,body").css({height:"100%",width:"100%"});if(f){f=f.css({position:"absolute"})[0];for(var w in {Top:1,Left:1}){f.style.setExpression(w.toLowerCase(),"(_=(document.documentElement.scroll"+w+" || document.body.scroll"+w+"))+'px'")}}}if(q.ajax){var e=q.target||m.w,x=q.ajax,e=(typeof e=="string")?o(e,m.w):o(e),x=(x.substr(0,1)=="@")?o(A).attr(x.substring(1)):x;e.html(q.ajaxText).load(x,function(){if(q.onLoad){q.onLoad.call(this,m)}if(i){m.w.jqmAddClose(o(i,m.w))}h(m)})}else{if(i){m.w.jqmAddClose(o(i,m.w))}}if(q.toTop&&m.o){m.w.before('<span id="jqmP'+m.w[0]._jqm+'"></span>').insertAfter(m.o)}(q.onShow)?q.onShow(m):m.w.show();h(m);return n},close:function(f){var e=l[f];if(!e.a){return n}e.a=n;if(a[0]){a.pop();if(!a[0]){j("unbind")}}if(e.c.toTop&&e.o){o("#jqmP"+e.w[0]._jqm).after(e.w).remove()}if(e.c.onHide){e.c.onHide(e)}else{e.w.hide();if(e.o){e.o.remove()}}return n},params:{}};var p=0,l=o.jqm.hash,a=[],c=o.browser.msie&&(o.browser.version=="6.0"),n=false,d=o('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),h=function(e){if(c){if(e.o){e.o.html('<p style="width:100%;height:100%"/>').prepend(d)}else{if(!o("iframe.jqm",e.w)[0]){e.w.prepend(d)}}}g(e)},g=function(f){try{o(":input:visible",f.w)[0].focus()}catch(e){}},j=function(e){o()[e]("keypress",b)[e]("keydown",b)[e]("mousedown",b)},b=function(m){var f=l[a[a.length-1]],i=(!o(m.target).parents(".jqmID"+f.s)[0]);if(i){g(f)}return !i},k=function(e,f,i){return e.each(function(){var m=this._jqm;o(f).each(function(){if(!this[i]){this[i]=[];o(this).click(function(){for(var q in {jqmShow:1,jqmHide:1}){for(var r in this[q]){if(l[this[q][r]]){l[this[q][r]].w[q](this)}}}return n})}this[i].push(m)})})}})(jQuery);




/* ***** Landing Page ***** */
	function toggleKitMail(){
		if($("#opt-mail-input:checked").length > 0){
			$("#opt-mail-sec").slideDown();
		}else{
			$("#opt-mail-sec").slideUp();
		}
	}

/* ***** Pain Report Page ***** */		
	/* Generating the results tab content */
	function popResults(){
		var questionsAnswered = false;
		var painChartActive = false;
	
		/* Testing to see if any pained areas were selected on the body chart */
		var partSet = $("#pain-chart img");
		var partSetLength = $(partSet).length;
		for(var i = 0; i < partSetLength; i++){
			if($(partSet[i]).data("painLevel") > 0){
				painChartActive = true;
				break;
			}
		}
		
		/* Testing to see if any questionnaire questions were answered */
		/* See if any checkboxes were checked */
		if($("input[type='checkbox']:checked").length > 0){
			questionsAnswered = true;
		}
		/* See if any answers were selected from the drop-downs */
		var selectSet = $("select");
		var selectSetLength = $(selectSet).length;
		for(var j = 0; j < selectSetLength; j++){
			if($(selectSet[j]).attr("value") != "(No answer)"){
				questionsAnswered = true;
				break;
			}
		}		
		/* See if anything was entered into the textarea */
		if(jQuery.trim($("textarea").attr("value")) !== ""){
			questionsAnswered = true;
		}
		
		/* Finally, if the user has done anything, we can show some results */
		if(painChartActive == true || questionsAnswered == true){
			/* Show messaging and hide the no results message */
			$("#results .print-results, #results .intro span").show();
			$("#results .intro a").hide();

			/* If there's pain chart information, create a pain chart */
			if(painChartActive == true){
				var painChartTemp = $("#pain-chart").clone();
				$(painChartTemp).children("a").remove();
				$(painChartTemp).children("p").remove();
				if($("#pain-chart-results").length == 0){
					$("#results p.intro").after("<div id='pain-chart-results'></div>");
				}
				$("#pain-chart-results").html($(painChartTemp).html());
/* IMPORTANT: Update the src below to correctly display this image */				
				$("#pain-chart-results").append("<img class='print-img' src='healthyspine/hsk-pain-chart-bg.gif' />")
			}else{
				$("#pain-chart-results").remove();
			}
			/* If any of the questionnaire was answered, populate results for it */
			if(questionsAnswered == true){
				if($("#questionnaire-results").length == 0){
					$("#results #footer-print-content").before("<div id='questionnaire-results'><h4>Questionnaire results</h4><ol></ol></div>");
				}
				var itemSet = "";
				var tempLI;
				/* Build result HTML for each question in the questionnaire */
				$("#questions ol li").each(function(){
					tempLI = "<li><h5>";
					tempLI += $(this).children(":first-child").text();
					tempLI += "</h5>";
					if($(this).children("select").length > 0){
						tempLI += "<p>" + $(this).children("select").attr("value") + "</p>";
					}else if($(this).find("input:checked").length > 0){
						$(this).find("input:checked").each(function(){
							tempLI += "<p>" + $(this).parent().text() + "</p>";
						});
					}else if($(this).children("textarea[value!='']").length >0){
						tempLI += "<p>" + $(this).children("textarea").attr("value") + "</p>";
					}else{
						tempLI += "<p>(No answer)</p>";
					}
					tempLI += "</li>";
					itemSet += tempLI;
				});
				$("#questionnaire-results ol").html(itemSet);
			}else{
				$("#questionnaire-results").remove();
			}
		}else{
			/* Reset the results */
			$("#results div:not('.print-content')").remove();
			$("#results .print-results, #results .intro span").hide();
			$("#results .intro a").show();
		}
	}


/* **********************************************
   ********** DOM LOADED FUNCTIONALITY **********
   ********************************************** */
jQuery().ready(function(){

/* ***** Landing Page ***** */
	if($("#opt-mail-input").length > 0){
		$("#opt-mail-input").click(
			function(){
				toggleKitMail();
			}
		) 
		toggleKitMail();
	}

/* ***** Pain Report Page ***** */
	if($("#pain-report-title").length > 0){
	
		$("body > div").addClass("pain-chart-content");

	
	/* Initialize pain popup modal */
		$("#jqm-pain-popup").jqm({
			modal: true,
			overlay: 50
		});

	/* Fade images, set display to block, add click and mouseover events */	
		var partSet = $("#pain-chart img");
		$(partSet).data("painLevel", 0);
		$(partSet).fadeTo(0, 0)
		.show()
		.bind("click", function(){
			var sliderPos = 2 + ($(this).data("painLevel") * 36);
			$(this).addClass("active");
			$("#pain-slider-tab").css("left", sliderPos);
			$("#jqm-pain-popup").jqmShow();
			
			/* Included to prevent an IE6 display issue (otherwise, the pain
			 * chart area would shift to the right for some reason)
			 */
			$("#pain-chart").css("left", 0);
			
		})
		.hover(
			function(){
				$(this).stop().fadeTo(400, 1);
			},
			function(){
				if(!$(this).hasClass("active")){
					$(this).stop().fadeTo(400, ($(this).data("painLevel")/10));
				}
			}
		);

	/* Code for dragging the slider and positioning it on click */	
		var dragging;
		var offset;
		var coord;
		jQuery("#jqm-pain-popup div").bind("mousedown", function(){
			dragging = true;
			offset = $("#jqm-pain-popup").offset();
			offset = offset.left;
			return false;
		}).bind("mouseup", function(){
			dragging = false;
		}).bind("mouseleave", function(){
			dragging = false;
		}).bind("mousemove", function(e){
			if(dragging == true){
				coord = Math.min(Math.max(e.clientX - offset - 35, 2), 362);
				coord = (Math.round(coord / 36)) * 36 + 2;
				$(this).children().css("left", coord);
			}
		}).bind("click", function(e){
			coord = Math.min(Math.max(e.clientX - offset - 35, 2), 362);
			coord = (Math.round(coord / 36)) * 36 + 2;
			$(this).children().css("left", coord);
		});
	
	/* Hooking up functionality for the "OK" button in the pain popup */
		$("#pain-popup-ok").bind("click", function(){
			var offsetNum = $("#jqm-pain-popup").offset();
			offsetNum = offsetNum.left;			
			var tabPos = $("#pain-slider-tab").offset();
			tabPos = tabPos.left - offsetNum - 30;
			
			var activePart = $("img.active");
		/* Set pain level to selected value (determined by offets) */
			$(activePart).data("painLevel", tabPos / 36);

		/* Add or remove a numbered circle image */
			if ($(activePart).data("painLevel") > 0){
				var newPainNum = "<div>" + $(activePart).data("painLevel") + "</div>"
				$(activePart).next("div").die("click").remove();
				$(activePart).after(newPainNum);	
				var activePos = $(activePart).position();
				$(activePart).addClass("visible").next().css({
					left: activePos.left + ($(activePart).width() / 2) - 10,
					top: activePos.top + ($(activePart).height() / 2) - 10
				});
			}else{
				$(activePart).removeClass("visible").next("div").die("click").remove();
			}
		/* Remove active class and hide the pain popup */	
			$(activePart).removeClass("active").mouseout();
			$("#jqm-pain-popup").jqmHide();
			return false;
		});
	
	/* Making sure that the circle icons are also clickable */
		$("#pain-chart div").live("click", function(){
			$(this).prev().click();
		});
		
	/* Tab functionality */
		var tabInProgress = false;
		$("#pain-report-title ul li").bind("click", function(){
			if($(this).children("a").hasClass("active") || tabInProgress == true){
				return false;
			}else{
				tabInProgress = true;

				if($(this).hasClass("results")){
					popResults();
				}
				var clickedLI = $(this);
				var prevTabLink = $("a.active");
				var prevTabContent = $("div.active");
				var newTabContent = $("#" + $(clickedLI).attr("class"));
				$(prevTabLink).removeClass("active");
				$(prevTabContent).slideUp(300, function(){
					$(prevTabContent).removeClass("active");
					$(newTabContent).slideDown(300, function(){
						$(newTabContent).addClass("active");
						tabInProgress = false;
					});
				});
				$(clickedLI).children("a").addClass("active");
				return false;
			}
		});
	/* Next Button functionality */
		$(".next-btn").bind("click", function(){
			$("#pain-report-title ul li a.active").parent().next().click();
			return false;
		});	
	
	/* "To Step 1" link */
		$("#to-step-1").bind("click",function(){
			$("li.pain-chart").click();
			return false;
		});
	
	/* Maxlength enforcement on textarea */
		function textareaMax(ref, e){
			e = e || window.event;
			var key = e.keyCode;
			if (ref.value.length > 1999 && (key > 47 || key == 13 || key == 32)){
				ref.value = ref.value.substring(0, 2000);
				return false;
			}else{
				return true;
			}
		}
		jQuery("textarea").bind("change",
			function(e){
				return textareaMax(this, e);
			}
		).bind("keydown",
			function(e){
				return textareaMax(this, e);
			}
		);	
		
	/* Hooking up the print link */
		$(".print-results a").bind("click", function(){
			window.print();
			return false;
		});	
		
	/* Putting the date into the print view */
		var date = new Date();
		var prettyMonth;
		switch (date.getMonth()){
			case 1:
			prettyMonth = "January";
			break;
			case 2:
			prettyMonth = "February";
			break;
			case 3:
			prettyMonth = "March";
			break;
			case 4:
			prettyMonth = "April";
			break;
			case 5:
			prettyMonth = "May";
			break;
			case 6:
			prettyMonth = "June";
			break;
			case 7:
			prettyMonth = "July";
			break;
			case 8:
			prettyMonth = "August";
			break;
			case 9:
			prettyMonth = "September";
			break;
			case 10:
			prettyMonth = "October";
			break;
			case 11:
			prettyMonth = "November";
			break;
			case 12:
			prettyMonth = "December";
			break;																																	
		}
		var displayDate = prettyMonth + " " + date.getDate() + ", " + date.getFullYear();
		$(".print-content h2").html(displayDate);	
	}
});













