/////////////////////////////
// Popup Functions
/////////////////////////////

var lockedSubmit = true;

$j(document).ready(
   function()
   {
        $j("#dialog").dialog({
                                buttons: 
                                {
                                        "Submit": function() 
                                        {
                                           doSubmit();
                                        },
                                        "Cancel": function() 
                                        {
										   doCancel();
                                        } 
                                },
                                width: 300,
                                height: 'auto',
                                autoOpen: false,
                                modal: true,
                                resizable: false});
                                
        $j('#dialog').width(250);

        // Add event for the confirmation popup
        $j('#dialog').bind('dialogbeforeclose', function(event, ui) {
              unblockUI();
              opener.window.unblockUI();
              return true;
        });

        
        lockedSubmit = false;
       
		// Set the tab in the scorer/quiz window...
        if (typeof $j("#compTabGroupId").val() != 'undefined' && typeof window.document.getElementById("compTabGroupId") != null) 
        {
           showTab(0, $j("#compTabGroupId").val());

           // Add event for the child window
           $j(window).unload( function () { onClose(); } );
        }
    }
);



// ijron - US-678
var CURRENT_QUIZ_ID = 0;

function confirmSubmit(formId)
{
   if (!lockedSubmit) 
   {
       //alert("confirmSubmit");
       
	   blockUI();
	   opener.window.blockUI();

	   CURRENT_QUIZ_ID = formId;

       $j("#dialog").dialog('open');
       $j('#dialog').width(250);
       $j('.ui-dialog-buttonpane').css({'bottom':'0px'});
       $j('.ui-dialog-buttonpane').css({'padding-left':'5px'});
       $j('.ui-dialog-buttonpane').css({'position':'relative'});
       $j('#dialog').css({'height':'60px'});  

   }
}



function doSubmit() 
{
   lockedSubmit = true;
   $j("#dialog").dialog('close');   

   var url    = "/minquizzes/savequiz";
   var params = $j("#" + CURRENT_QUIZ_ID).serialize();

   //goAjax(url, params, afterdoSubmit);
   $j.post(url, params, afterdoSubmit);
}



function afterdoSubmit(jsonedResponse) 
{
   var response = eval( '(' + jsonedResponse + ')' );
   
   // NOTE: These vars exists in the TabHandler.js file
   var tabName = CONTENT_PREFIX + selectedTabGroupId + currentTabIds[selectedTabGroupId];

   // Update the popup window
   $j("#" + tabName).html("");
   $j("#" + tabName).html(response.quizPopupData);
// $j("#" + tabName).html(response.quizPopupData);   
   
   // Update the parent window
   opener.window.refreshPracticeTab(response);
      
   unblockUI();   
   opener.window.unblockUI();   
   
   lockedSubmit = false;
}



function refreshPracticeTab(response) 
{
   // Refresh the practice tab...
   window.document.getElementById("pracTabContent").innerHTML = response.practiceTabData;
   
   // Refresh the tooltips for the practice tab...
   //window.createToolTips(response.toolTipData);
   window.buildPracToolTips(response.toolTipData);

   // Reassing the tabs functions...
   var pracTabGroupId = window.document.getElementById("pracTabGroupId").value;
   var tabId = 0;
   
/*
   while (typeof window.document.getElementById("tab_" + selectedTabGroupId + tabId) != null) 
   {
      $j("#tab_" + selectedTabGroupId + tabId).bind("click", function() { showTab(tabId, pracTabGroupId); });
      tabId++;
   }
*/

   $j("#tab_" + selectedTabGroupId + "0").bind("click", function() { showTab(0, pracTabGroupId); });
   $j("#tab_" + selectedTabGroupId + "1").bind("click", function() { showTab(1, pracTabGroupId); });
   $j("#tab_" + selectedTabGroupId + "2").bind("click", function() { showTab(2, pracTabGroupId); });
   
   if (typeof window.document.getElementById("tab_" + selectedTabGroupId + "3") != null) 
   {
      $j("#tab_" + selectedTabGroupId + "3").bind("click", function() { showTab(3, pracTabGroupId); });   	
   }


}



function buildPracToolTips(qrData)
{
   	  showTab(0, $j("#pracTabGroupId").val());

      //var qrData       = null;
      var detailData   = $j("#detTT").html();  //'<div style="color:red;">This is a test over the Tip!!!</div>';        
      var idCell       = 0;
      
      // NOTE: If more quizzes are needed we need to add the new quizz types in these arrays:
      /*
      var quizzesTypes = new Array("<?= QST_EPISODE_QUIZ ?>", 
                                   "<?= QST_DIAGNOSTIC   ?>", 
                                   "<?= QST_FULL_LENGHT1 ?>", 
                                   "<?= QST_FULL_LENGHT2 ?>", 
                                   "<?= QST_MIN_DIAG     ?>" );
      */
      
      var quizzesIndex = new Array("EPISODE_QUIZ", 
                                   "DIAGNOSTIC", 
                                   "FULL_LENGHT1", 
                                   "FULL_LENGHT2", 
                                   "MIN_DIAG" );
      
      
      try
      {   	
         //qrData = <?= Zend_Json::encode($this->detail); ?>;
         var detTT = $j("#detTT").html();
         
         // Each Area
         for( var i in qrData )
         {
            // Each Concept 
            for ( var j in qrData[i] ) 
            {
               //alert($j.dump(qrData[i][j]));
         	   //alert($j.dump(quizzesTypes));
         	   
         	   // Each quiz type
         	   for ( qIndex=0; qIndex<quizzesTypes.length; qIndex++ )
         	   {
                  idCell = "#" + qrData[i][j]['concept_id'] + '_' + quizzesTypes[qIndex];
                  
                  if ($j(idCell).html() != "N/A" && $j(idCell).html() != null) 
                  {
                  	 // Set the detail content
                  	 //alert(detailData);    
                  	  
                  	 detailData = detTT;
                  	 var correct = incorrect = skip = true; 
                     detailData = detailData.replace('display:none', 'display:block');                  	         	 
                  	 
                     if (qrData[i][j][quizzesIndex[qIndex]]['correct'].length < 3)
                        detailData = detailData.replace('CorrectValue', eval(qrData[i][j][quizzesIndex[qIndex]]['correct']));
                     if (qrData[i][j][quizzesIndex[qIndex]]['incorrect'].length < 3)
                        detailData = detailData.replace('IncorrectValue', eval(qrData[i][j][quizzesIndex[qIndex]]['incorrect']));
                     if (qrData[i][j][quizzesIndex[qIndex]]['skip'].length < 3)
                        detailData = detailData.replace('SkipValue', eval(qrData[i][j][quizzesIndex[qIndex]]['skip']));
                     //alert(detailData);
                     //alert(quizzesIndex[qIndex]);
                     //alert($j.dump(qrData[i][j][quizzesIndex[qIndex]]));                     
                     
                     if (qrData[i][j][quizzesIndex[qIndex]]['correct'].length < 3)
                         setTooltip(idCell, detailData);
                  }             
                  
                  //setTooltip(idCell, detailData);
                  //alert(idCell);
                  //break;
         	   }
         	  
         	   //break;
            }            
            
            //break;
         }         
      }
      catch (err)
      {
         qrData = "";
      }
}



function doCancel() 
{
   $j("#dialog").dialog('close');   
   
   unblockUI();
   opener.window.unblockUI();
}    



function onClose() 
{
   // If the parent and child window doesn't finish to refresh (method: afterdoSubmit)
   if (lockedSubmit) 
   {
   	  // Refresh the parent window to try get the latest data
      opener.window.document.getElementById("refreshTabForm").submit();   	
   }
}


/////////////////////////////
// Practice Tab Functions
/////////////////////////////



// ijiron - US-678
var quizPopup = null;

function showUpTest(quizTypeId, quizSubTypeId, userId)
{
    var urlQuiz = "http://" + CURRENT_DOMAIN + "/minquizzes/getquiz/quizTypeId/" + quizTypeId + "/quizSubTypeId/" + quizSubTypeId + "/userId/" + userId;

    quizPopup = window.open(urlQuiz, '_blank', 'width=900,height=640,location=no,titlebar=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes');

	if (window.focus) 
	{
		quizPopup.focus();
    }
}



function blockUI() 
{
   $j.blockUI(
      { 
         css: {
                        border: 'none',
                        padding: '15px',
                        backgroundColor: '#000',
                        '-webkit-border-radius': '10px',
                        '-moz-border-radius': '10px',
                        opacity: .5,
                        color: '#fff'
         } 
      }
   );
}



function unblockUI() 
{
   $j.unblockUI();
}



// ijron - US-679
function setTooltip(id, body)
{
   $j(id).tooltip
        (
            {
                delay: 0,
                showURL: false,
                opacity: 1,
                fade: 250,
                bodyHandler: function()
                {
                    return body;
                }
            }
        );
}





//////////////////////////////////
// Quizzes Functions
//////////////////////////////////


// Original JS File: MinisiteQuiz.js

var setAnswersDefault = new Array("A","B","C","D","E");
var setAnswersACT     = new Array("F","G","H","J","K");


// ijiron - US453
function inArray(arraySearch, valueSearch) {

   for (i=0; i<= arraySearch.length; i++) 
   {
      if(arraySearch[i]==valueSearch)
      {
         return true;
      }
   }
   return false;
}


// ijiron - US453
function unclickAnswers(arrayAnswers, answerId) {

   var answerOption = "";

   for (i=0; i< arrayAnswers.length; i++) 
   {
      answerOption = "#" + answerId + arrayAnswers[i];
      //alert(answerOption);
      $j(answerOption).attr('src', '/images/answersheet/icon_' + arrayAnswers[i].toLowerCase() + '.png');
   }
}


// ijiron - US453
function setUserAnswer(answerId, userAnswer) {

   //alert("answerId: " + answerId);
   //alert("userAnswer: " + userAnswer);

   if (inArray(setAnswersDefault, userAnswer)) 
   {
      //alert("TypeSAT");
      unclickAnswers(setAnswersDefault,answerId);
   }
   else if (inArray(setAnswersACT, userAnswer)) 
   {
      //alert("TypeACT");
      unclickAnswers(setAnswersACT,answerId);
   }

   
   //alert("ID: " + (answerId));   
   //alert($j("#" + answerId).val());      
   //alert(document.getElementById(answerId).value);
   document.getElementById(answerId).value = userAnswer;
   //$j("#" + answerId).val(userAnswer);     
   //alert($j("#" + answerId).val());   
   //alert(document.getElementById(answerId).value);
   
   
   var answerOption = "#" + answerId + userAnswer;
   $j(answerOption).attr('src', '/images/answersheet/icon_outline_grey_filled_grey_' + userAnswer.toLowerCase() + '.png');
    //alert("result: " +  document.getElementById(answerId).value);
    //alert("answerOption: " +  answerOption);
}


// ijiron - US453
function setUserProducedAnswer(answerId, userAnswer) {

   //alert("answerId: " + answerId);
   //alert("userAnswer: " + userAnswer);

   //validateUserProducedAnswer(userAnswer);

   //if (validateUserProducedAnswer(userAnswer)) {
   //   document.getElementById(answerId).value = calcUserProducedAnswer(userAnswer);
   //}

   var calAnswer = null;

   try 
   {
      calAnswer = eval(userAnswer);
      
      if (calAnswer<9) 
      {
         calAnswer = calAnswer.toFixed(2);
      }
      else 
      {
         calAnswer = calAnswer.toFixed(1);
      }
   } 
   catch (err) 
   {
      alert("Invalid answer");
   }

   if (isNaN(calAnswer)) 
   {
      alert("Invalid answer");
      document.getElementById(answerId).value = "";
   }
   else 
   {
      document.getElementById(answerId).value = calAnswer;
   }

   //alert("result: " +  document.getElementById(answerId).value);
}


// ijiron - US453
function validateUserProducedAnswer(userAnswer) {

   var isValid = false;
   var myRegxp1 = new RegExp("/[0-9]\/[0-9]/");
   var myRegxp2 = new RegExp("/\\.[0-9][0-9]/");
   //var myRegxp3 = new RegExp("/0\\.[0-9][0-9]/");
   var myRegxp3 = new RegExp("0\\.\d{1,2}");

   //- Multiple answers could be correct (example: 1/4 = 2/8 = .25 = 0.25)
   if (userAnswer.length < 5) 
   {
       if (myRegxp1.test(userAnswer)) 
       {
          isValid = true;
          alert("Match Pattern1");
       } 
       else if (myRegxp2.test(userAnswer)) 
       {
          isValid = true;
          alert("Match Pattern2");
       } 
       else if (myRegxp3.test(userAnswer)) 
       {
          isValid = true;
          alert("Match Pattern3");
       } 
       else 
       {
          alert("Invalid Pattern");
       }
   }

   return isValid;
}


// ijiron - US453
function calcUserProducedAnswer(userAnswer) {

   var result   = userAnswer;
   var myRegxp1 = "[0-9]\/[0-9]";
   var myRegxp2 = "\.[0-9][0-9]";
   var myRegxp3 = "0\.[0-9][0-9]";

   //- Multiple answers could be correct (example: 1/4 = 2/8 = .25 = 0.25)
   if (userAnswer.length < 5) 
   {
       if (myRegxp1.test(userAnswer)) 
       {
           result = eval(result);
       } 
       else if (myRegxp2.test(userAnswer)) 
       {
           result = '0'+ result;
       }
    }

    return result;
}

// ...Original JS File: MinisiteQuiz.js


