/*
 * plug in for working with tests on the front end of the site
 */
(function($){
	
	//CONSTSANTS
	//var HIDEBUTTON 		= '<img src="/travel/_tnz/view/site/css/trade/pics/bullets/hide-module-test.gif" width="16" height="16" class="float-right" alt="hide" onclick="$.frontEndTest.toggleTheTest();" />';
	var HIDEBUTTON 			= ''; /* This value is now set in the toggleTheTest function */
	
	//var SHOWBUTTON 		= '<img src="/travel/_tnz/view/site/css/trade/pics/bullets/show-module-test.gif" width="16" height="16" class="float-right" alt="show" onclick="$.frontEndTest.toggleTheTest();" />';
	var SHOWBUTTON			= ''; /* This value is now set in the toggleTheTest function */
		
	var LOADING			= '<div align="center" width="100%"><img src="/travel/_tnz/view/site/assets/trade/modules/ajax-loader.gif" /></div>';
	var SAVING			= '<div align="center" width="100%"><img src="/travel/_tnz/view/site/assets/trade/modules/ajax-loader.gif" /></div>';
	
	//For the ajax calls
	var COMPONENT	= "travel._tnz.view.site.templates.trade.training.modules.module.cfc.GateWay";
	var TYPE		= "POST";
	
	var THETEST			= "#the-test";
	var TESTINFO		= "#test-info";	
	var TESTINFO_NUMBERS= "#test-info ul";	
	var THETESTSHOWHIDE	= "#test-info-showhide-button";
	var THECONTAINER	= "#module-test";
	var MODULEUUIDINPUT	= "#__moduleUUID";
	var NEXTBUTTON		= "#test-question-next-button";
	var QUESTIONLINKS	= "#test-info-question-links";
	var QUESTIONNUMBERS	= "span[class^='test-info-question']";
	
	var INTERVAL		= 1000 * 60 * 5;
	
	var __questions		= [];
	
	var TESTCOMPLETE 	= false;	
	
	var __ie6setpos	= function()
	{
		if ( __isIE6() )
		{
			//do this to cause the scrollfollow pluging to redraw
			$( document ).scrollTop(  $( document ).scrollTop() + 1);
			$( document ).scrollTop(  $( document ).scrollTop() - 1);
		}		
	}
	var __ie6hidetest = function()
	{
		$( THECONTAINER ).css('height', '25px');
		$( THETEST ).hide();
		$( TESTINFO_NUMBERS ).hide();
		$( TESTINFO ).css('height', '25px');
		$( THECONTAINER ).css('marginBottom', '0px');					
	
		__ie6setpos();//jiggle the browser
	}	
	var __ie6showtest = function()
	{
		$( THETEST ).show();
		$( TESTINFO_NUMBERS ).show();
		$( TESTINFO ).css('height', '51px');
		$( THECONTAINER ).css('height', '232px');	
		$( THECONTAINER ).css('marginBottom', '-6px');					
		
		__ie6setpos();	
	}	
	var __isIE6		= function()
	{
		return ( $.browser.msie &&  $.browser.version <= 6 );
	}
	var __setQuestionHoverState = function()
	{
		$(QUESTIONNUMBERS).hover(
			  function(){ $(this).addClass("test-info-question-hover"); }
			, function(){ $(this).removeClass("test-info-question-hover"); }
		);
	}
	var __nextButton	= function( question )//sets the Next Question to submit test if all the question are answered
	{
		var sHTML	= '<input type="image" src="/travel/_tnz/view/site/css/trade/pics/TNZ0684/next-question_' + $( "#__moduleLang" ).val() + '.png" class="button" />';
		
		$( NEXTBUTTON ).unbind("click");
		
		/*Use this if checking the DB for test completion*/
		$.frontEndTest.isTestComplete( question, $(MODULEUUIDINPUT).val() );				
		
		
		// Debug info (comment when not needed)
		/*var numberOfElements = $(".test-info-question-completed").length;		
		$("#debug_questions_answered").html( "<strong>Q's completed: " + numberOfElements + "</strong>" );
		$("#debug_test_complete_db").html( "<strong>Test Complete: " + TESTCOMPLETE + "</strong>" );*/
		// END Debug info (comment when not needed
		
		if(
			(
				$(".test-info-question-completed").length 			>= 19//19 others answered 
				&& $("input[name ='qi"+question+"']:checked").length == 1//current one is answered
			) 
			
			|| TESTCOMPLETE //(also complete in according to DB? )
		) 			
		{
			sHTML	= '<input type="image" src="/travel/_tnz/view/site/css/trade/pics/buttons/submit-question_' + $( "#__moduleLang" ).val() + '.gif" class="button" />';
			$( NEXTBUTTON ).bind('click' , function(){ $.frontEndTest.submitTest(); });
		}
		else
		{
			var nextQuestion = question + 1;
			if(nextQuestion > 20 )
			{
				nextQuestion = 1;
			}
			$( NEXTBUTTON ).bind( 'click' , function(){ 
				$.frontEndTest.showQuestion( nextQuestion ,$(MODULEUUIDINPUT).val()); 
			});
		}
		
		$( NEXTBUTTON ).html( sHTML );
		$( NEXTBUTTON ).removeAttr("onclick");	
	}
	var __disableNext	= function()//prevent the user changing question
	{
		
		$(QUESTIONNUMBERS).each(
			function (i) {
				$( this ).removeAttr("onclick");
	      });
		$().unbind( "click" ); 
		$(QUESTIONNUMBERS).unbind('mouseenter mouseleave'); 
		$(QUESTIONNUMBERS).css('cursor','auto'); 
		$( NEXTBUTTON ).html( SAVING );
	}
	var __enableNext	= function()//enable the user to change question 
	{
		$(QUESTIONNUMBERS).each(
			function (i) {
				var questionNum	= $(this).html() * 1;
				$( this ).bind('click', function(){
					$.frontEndTest.showQuestion( questionNum , $(MODULEUUIDINPUT).val() );
				});
			}
		);
		$(QUESTIONNUMBERS).css('cursor','pointer'); 
	}
	
	$.extend
	({
		frontEndTest:{
			
				toggleTheTest	: function()
				{					
					if( $( THETEST ).is(':visible') ) 
					{
						// use shado translated element for the text if it exists yet (only gets loaded when page is ready via FrontEndTestHelper.cfc)	
						if(typeof(sTranslatedShowText) !== 'undefined'){
							SHOWBUTTON			= '<a href="javascript:void(0)" onclick="$.frontEndTest.toggleTheTest();"><strong>' + sTranslatedShowText + '</strong><img src="/travel/_tnz/view/site/css/trade/pics/TNZ0684/show-module-test.gif" alt="show"  height="16" width="16"></a>';
						}else{ // hardcode it	
							SHOWBUTTON			= '<a href="javascript:void(0)" onclick="$.frontEndTest.toggleTheTest();"><strong>Show Test</strong><img src="/travel/_tnz/view/site/css/trade/pics/TNZ0684/show-module-test.gif" alt="show"  height="16" width="16"></a>';
						}
												
						if( __isIE6() )
						{
							__ie6hidetest();							
						}
						else
						{							
							$( THECONTAINER ).animate({bottom:"-200px"},500);
							$( THETEST ).css("min-height","0px");
							$( THETEST ).slideUp(  function(){ } );						
							
						}
					
						$( THETESTSHOWHIDE ).html( SHOWBUTTON ); 
						$.testconfig.testVisible( $( MODULEUUIDINPUT ).val() , false );
						
					}
					else
					{
						// use shado translated element for the text if it exists yet (only gets loaded when page is ready via FrontEndTestHelper.cfc)	
						if(typeof(sTranslatedHideText) !== 'undefined'){
							HIDEBUTTON 		= '<a href="javascript:void(0)" onclick="$.frontEndTest.toggleTheTest();"><strong>' + sTranslatedHideText + '</strong><img src="/travel/_tnz/view/site/css/trade/pics/TNZ0684/hide-module-test.gif" alt="hide"  height="16" width="16"></a>';
						}else{ // hardcode it	
							HIDEBUTTON			= '<a href="javascript:void(0)" onclick="$.frontEndTest.toggleTheTest();"><strong>Hide Test</strong><img src="/travel/_tnz/view/site/css/trade/pics/TNZ0684/show-module-test.gif" alt="show"  height="16" width="16"></a>';
						}
						
						if( __isIE6() )
						{
							__ie6showtest();							
						}
						else
						{
							
							$( THETEST ).slideDown( function(){ $( THETEST ).css("min-height","172px"); } );
							$( THECONTAINER ).animate({bottom:"0px"},500);
						}
					
						$( THETEST ).show();
					
						$.testconfig.testVisible( $( MODULEUUIDINPUT ).val() , true );
						$( THETESTSHOWHIDE ).html( HIDEBUTTON ); 
					}					
					
				}
			,	displayUserLogin	: function( reason )
				{					
					$( THETEST ).html( LOADING );
					$( QUESTIONLINKS ).fadeOut();
					$.frontEndTest.getContent("login" ,
						function( result )
						{
							$( THETEST ).html( result.theTest );
							$.frontEndTest.fixPngButtonsIE6();
							
						} 
						, reason
					);					
				}
			,	loadUserTest		: function()
				{
					$.TNZCFC.invoke({
						  component 			: COMPONENT
						, method 				: "loadTest"		
						, args					: { moduleUUID : $( MODULEUUIDINPUT ).val() }		
						, resultHandler 		: function( result )
													{
														if( result.status)
														{
														__questions = result.questionArray;
															$( TESTINFO ).html( result.testInfo );
															$( THETEST ).html( result.theTest );
															
															if( $.testconfig.testVisible( $( MODULEUUIDINPUT ).val() ) == false )
															{
																if( __isIE6() )
																{
																	__ie6hidetest();							
																}else{
																	$( THETEST ).hide();
																	$( THECONTAINER ).css("bottom","-200px");																	
																}																																
															}else if( __isIE6() )
															{
																__ie6showtest();//do this to correct ie6 marginBottom issues			
															}														
															
															$( THECONTAINER ).show();
															//bind the hover effect
															__setQuestionHoverState();
															
														}														
													
														$.frontEndTest.fixPngButtonsIE6();
													}
						, dataType				: "json"
						, type					: TYPE
					});		
					
					//add some whitespace on test load so that no content of the page is hidden				
					$(".training-module .module-content").css("padding-bottom", "280px");					
					
				}
			,	getContent			: function( type , callback , reason )//function to get some content from the server
				{
				
					var oArgs	= { type : type, moduleUUID : $( MODULEUUIDINPUT ).val() };
					if( reason )
					{
						oArgs.reason = reason;
					}
				
					$.TNZCFC.invoke({
						  component 			: COMPONENT
						, method 				: "getContent"		
						, args					: oArgs		
						, resultHandler 		: callback
						, dataType				: "json"
						, type					: TYPE
					});									
				}
			,	showQuestion		: function ( question , moduleUUID )
				{ 
					var cssSuffix = "";
					
					$.testconfig.currentQuestion( question  , moduleUUID  );		
										
					if( $("input[name^='qi']:checked").length == 0 )//no answer picked
					{
						cssSuffix = ( $(".test-info-question-current" ).hasClass("question-incorrect")?" question-incorrect":"" );					
						
						$(".test-info-question-current").attr("class", "test-info-question" + cssSuffix);
					}
					else
					{
						$(".test-info-question-current").attr("class", "test-info-question-completed" + cssSuffix);
						
					}
					
					cssSuffix = ( $("#test-info-question-" + question ).hasClass("question-incorrect")?" question-incorrect":"" );
					$("#test-info-question-" + question ).attr("class", "test-info-question-current" + cssSuffix);
					
					//get the questions all the time now.  Only way radio buttons are correctly checked and fixes bug where userAnswer is strangely undefined
						$( THETEST ).html( LOADING );
						$.frontEndTest.getQuestionsArray(
							function( result )
							{
								__questions = result.questions;
								
								$( THETEST ).html( __questions[ question ] );
								
								$.frontEndTest.fixPngButtonsIE6();	

							}
						);	
					
					
					/*if( __questions.length == 0 )//lets go get the questions
					{
						$( THETEST ).html( LOADING );
						$.frontEndTest.getQuestionsArray(
							function( result )
							{
								__questions = result.questions;
								$( THETEST ).html( __questions[ question - 1 ] );
							}
						);						
					}
					else//we have them already, so let load them in to the test
					{*/
					
										
					//note fadeOut here seems to cause some issues - not certain but have a strong hunch (therefore removed)
					/*$( THETEST + " > .inner").fadeOut(
						function()
						{*/
							$( THETEST ).html( __questions[ question ] );
							if( question != 0 )
							{
								
								var userAnswer = $('#user-answer-' + question).val();
								
								//if( typeof(userAnswer) == 'undefined'){ // don't need this error handling anymore as the test is reloaded everytime
								//	$.frontEndTest.reloadOnError();											
								//}
								 
								
								if (userAnswer.length != 0) {
									$("#" + userAnswer + "-" + question).attr("checked", "checked");//check the value
									//hide the red cross if it exists
									$("#img_cross_question-"+question).hide();
								}
									
							}
							
							__nextButton( question );
						/*}
					);*/
						
					//}
					if( !$( THETEST ).is(':visible') )	$.frontEndTest.toggleTheTest();									
				}
			,	showIntro		: function ( elem )
				{				
					$( ".test-info-question-current" ).removeClass("test-info-question-current").addClass("test-info-question");
					$( elem ).addClass("test-info-question-current");						
					$("#the-test").css("display","hidden");
					
				}	
				
			,	answerQuestion		: function( question )
				{ 
					var value	= $("input[name ='qi"+question+"']:checked").val();
					var _instanceName	= $("#_InstanceName").val();
					
					__disableNext();
					
					//if the we have loaded the question, but date the value in the array
					if( __questions.length != 0 )
					{
						$("#user-answer-" + question).val( value  );
						__questions[ question - 1 ] = $( THETEST ).html();
					}
					
					//hide the red cross if it exists
					$("#img_cross_question-"+question).hide();
					
					//now send it to the server
					$.TNZCFC.invoke({
							  component 			: COMPONENT
							, method 				: "answerQuestion"		
							, args					: { moduleUUID : $( MODULEUUIDINPUT ).val() , question : question , answer : value , _instanceName : _instanceName }		
							, dataType				: "json"
							, type					: TYPE
							, errorResultHandler	: $.frontEndTest.errorHandler
							, cache					: false
							, resultHandler 		: function ( result )
								{
								  	if( !result.status === true )
								  	{
								  		//load the log in
								  		$( THETEST ).html( result.theTest   );
								  		$( QUESTIONLINKS ).fadeOut();
								  		__questions	= [];
								  		loginBoxControl.loadButton();
								  	}
								  	else
								  	{										
								  		__enableNext();
										__nextButton( question );
								  		__setQuestionHoverState();
								  	}
									
									setTimeout("$.frontEndTest.fixPngButtonsIE6();",1);		
								}
					});	
					
				}
			,	submitTest			: function()
				{
					//show the summary label with current marker and remove marker from where it was
					$(".test-info-question-current" ).attr("class", "test-info-question");
					$("#test_info_question_summary").css("visibility","visible");
											
					$( QUESTIONLINKS ).fadeOut();
					$( THETEST ).html( LOADING );
					$.TNZCFC.invoke({
							  component 			: COMPONENT
							, method 				: "submitTest"		
							, args					: { moduleUUID : $( MODULEUUIDINPUT ).val() }		
							, resultHandler 		: function ( result )
													{
													  	$( THETEST ).html( result.theTest );
													  	$( QUESTIONLINKS ).fadeOut();
													  	$.frontEndTest.fixPngButtonsIE6();
													}
							, errorResultHandler	: $.frontEndTest.errorHandler
							, dataType				: "json"
							, type					: TYPE
					});	
					
					// reload the test info to show results instantly (appears to need to wait a little for processing before reloading test info or if will not be correct)
					setTimeout("$.frontEndTest.reloadTestInfo();",200);	
					
				}
			,	cheat			: function( type )
				{	
					//show the summary label with current marker and remove marker from where it was
					$(".test-info-question-current" ).attr("class", "test-info-question"); 
					$("#test_info_question_summary").css("visibility","visible");
					
					$( QUESTIONLINKS ).fadeOut();
					$( THETEST ).html( LOADING );
					$.TNZCFC.invoke({
							  component 			: COMPONENT
							, method 				: "cheat"		
							, args					: { moduleUUID : $( MODULEUUIDINPUT ).val() , type : type }		
							, resultHandler 		: function ( result )
													{
													  	$( THETEST ).html( result.theTest );
													}
							, dataType				: "json"
							, type					: TYPE
					});	
					
					// reload the test info to show results instantly (appears to need to wait a little for processing before reloading test info or if will not be correct)
					setTimeout("$.frontEndTest.reloadTestInfo();",600);
					
				}
				
			, reloadTestInfo	: function(){
				
				//call loadTest again but only use for reloading test info
				$.TNZCFC.invoke({
						  component 			: COMPONENT
						, method 				: "loadTest"		
						, args					: { moduleUUID : $( MODULEUUIDINPUT ).val(), renderState : 1 }		
						, resultHandler 		: function( result )
													{		
														if( result.status)
														{
														__questions = result.questionArray;
															$( TESTINFO ).html( result.testInfo );															
														}
													}
						, dataType				: "json"
						, type					: TYPE
					});	
					
					
			}
			
			, reloadTestInfoResitByNumber	: function( question , moduleUUID ){
				
				
				/* $.testconfig.currentQuestion( question  , moduleUUID );
				window.location = window.location; */
				
				//the below stuff used if resitting by number is done not by page reload and setting cookie
				//call loadTest again but only use for reloading test info (for when resiting by clicking number
				$.TNZCFC.invoke({
						  component 			: COMPONENT
						, method 				: "loadTest"		
						, args					: { moduleUUID : $( MODULEUUIDINPUT ).val(), renderState : 2 }		
						, resultHandler 		: function( result )
													{		
														if( result.status)
														{
														__questions = result.questionArray;
															$( TESTINFO ).html( result.testInfo );															
															// after the testinfo is reloaded, then show the question
															$.frontEndTest.showQuestion( question , moduleUUID );															
														}
													}
						, dataType				: "json"
						, type					: TYPE
					});	
					
			}
			
			, isTestComplete	: function( question , moduleUUID ){
				// this check is test is complete by going to the DB
				$.TNZCFC.invoke({
						  component 			: COMPONENT
						, method 				: "isTestCompleteInDB"		
						, args					: { moduleUUID : $( MODULEUUIDINPUT ).val()}		
						, resultHandler 		: function( result )
													{		
														TESTCOMPLETE  = result;														
													}
						, dataType				: "json"
						, type					: TYPE
					});					
			}
			
			, reloadOnError	: function(){
				//used for when error happens - reloading seems to clear error.  Not the best but works for now
				window.location = window.location;
			}	
				
			/****************************************************
			 * Server Actions
			 ****************************************************/
			,	errorHandler		:  function(xhr,err,e)
				{
					 $.TNZCFC.logit( xhr , err, e );
					 //now load the login
					 $.frontEndTest.displayUserLogin("timeout");
					 loginBoxControl.loadButton();
					 __questions	= [];
					 
				}
			,	keepSessionAlive	: function()
				{
				 	$.TNZCFC.invoke({
				 		component 			: COMPONENT
						, method 				: "getSessionToken"		
						, dataType				: "json"
						, type					: TYPE
						, cache					: false
					 });
					setTimeout( $.frontEndTest.keepSessionAlive , INTERVAL );
				
				}
			,	getQuestionsArray	: function( callback )
				{
					$.TNZCFC.invoke({
							  component 			: COMPONENT
							, method 				: "getQuestionArray"		
							, args					: { moduleUUID : $( MODULEUUIDINPUT ).val() }		
							, resultHandler 		: callback
							, dataType				: "json"
							, type					: TYPE
					});		

				}
			,	login				: function()
				{					
					var elemEmail		= $("#theTest-user-email");
					var elemPassword	= $("#theTest-user-password");
					var email		= elemEmail.val();
					var password	= elemPassword.val();
					var bValid		= true;
	
					elemEmail.css("background","#FFF");
					elemPassword.css("background","#FFF");
					$("#login-form-failed-login").slideUp();
					if( email.length == 0 )
					{
						elemEmail.css("background","#FF0000");
						bValid = false;
					}
					if( password.length == 0 )
					{
						elemPassword.css("background","#FF0000");
						bValid = false;
					}
					
					if( bValid == true)				
					{
						$.TNZCFC.invoke({
							  component 			: COMPONENT
							, method 				: "login"		
							, args					: { email : email , password : password , moduleUUID : $( MODULEUUIDINPUT ).val() }		
							, resultHandler 		: function( result )
														{
															if( result.success )
															{
																$.testconfig.testState("SITTINGTEST");
																$( THETEST ).html( result.theTest );
																$( TESTINFO ).html( result.testInfo );
																__questions	= result.questionArray;
																loginBoxControl.loadButton();//refresh the login buttons at the top, thanks to clever Glenn
																__setQuestionHoverState();//reset the hover state
																$.frontEndTest.fixPngButtonsIE6();
															
																// get the webroot and toggle the background
																var sFullURL = window.location.href;					
																var posRootEnd =  sFullURL.indexOf("travel/trade") + 6;					
																var sRootURL = sFullURL.substr(0,posRootEnd);
																$.frontEndTest.toggleTestBackground('loggedin',sRootURL);
																
															}
															else
															{
																$("#login-form-failed-login").slideDown();
															}
														}
							, dataType				: "json"
							, type					: TYPE
						});							
					}
					
				}
			, 	bindLoginFormKeyPress : function()
				{
					$("#theTest-user-email,#theTest-user-password").keypress(function( e ){
						if (e.keyCode == '13') {
							$.frontEndTest.login();
						}
					});
				}
			, 	toggleTestBackground : function(state, absolute_webroot)
				{				
					if(state == 'loggedout'){						
						var sBackgroundURL = absolute_webroot + '/_tnz/view/site/css/trade/pics/TNZ0684/test-panel-bkgd-loggedout.png';
					}else{						
						var sBackgroundURL = absolute_webroot + '/_tnz/view/site/css/trade/pics/TNZ0684/test-panel-bkgd.png';
					}
					$('#module-test').css("background","url('" + sBackgroundURL + "') no-repeat scroll 0 0 transparent");
				}
			
			,	fixPng : function(png) { 
			
					var blank = new Image();
 					blank.src = '/travel/_tnz/view/site/css/trade/pics/TNZ0684/blank.gif';
			
				   // get src
				   var src = png.src;
				   // set width and height
				   if (!png.style.width) { png.style.width = $(png).width(); }
				   if (!png.style.height) { png.style.height = $(png).height(); }
				   // replace by blank image
				   png.onload = function() { };
				   png.src = blank.src;
				   // set filter (display original image)
				   png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";		
			 }				
				
			,  fixPngButtonsIE6: function(){ // function for fixing IE6 transparent pngs for buttons
					 
				 if( __isIE6() )
					{
										
						 $('#module-test .button').each(function() { 
						   if (!this.complete) {
					         this.onload = function() { $.frontEndTest.fixPng(this) };
					       } else {
					         $.frontEndTest.fixPng(this);
					       }
					     });
					}
			}
			
			
		}
	});
	$( document ).ready(
		function()
		{
			__setQuestionHoverState();
			//load the test
			$.frontEndTest.loadUserTest();
			
			setTimeout( $.frontEndTest.keepSessionAlive , INTERVAL );
		}
	);
})(jQuery);

