/************************************************************
* Filename  quizrunner.js
* Purpose   Dyanamic UI Manipulation for Quiz Runner
* @author   developer@evoknow.com
* version   1.0.0
* copyright © 2008 Evoknow Inc.
************************************************************/


var VALIDATION_MSG               = 'Please answer all questions';
var INTERMEDIATE_WINDOW_LIFETIME = 10000;
var INTERMEDIATE_WINDOW_WIDTH    = 800+'px';
var INTERMEDIATE_WINDOW_HEIGHT   = 600+'px';
var AUTHOR_QUIZ_WINDOW_WIDTH     = '800px';
var AUTHOR_QUIZ_WINDOW_HEIGHT    = '600px' ;
var WINDOW_FLAG                  = false;
var LOGIN_REQUIRED_FOR_TAG       = 'You need to log in to tag this quiz.'
var NO_TAG_ENTERED_WARNING       = 'No tag Entered.';
var ADD_TAG_SUCCESS              = 'Your tag has been added.';
var BIG_IMAGE_PREFIX             = 'img_big_';

/*
*  @name   : init
*  @purpose: To Initialize Lightbox
*  @params : none
*  @return : none
*
*/
function init()
{
   Lightbox.init();
}

/*
*  @name   : changePageTitle
*  @purpose: To change page title
*  @params : none
*  @return : none
*/
function changePageTitle()
{
   if(TOTAL_PAGE_NUM > 1)
   document.title += ' Page '+CURRENT_PAGE_NUM;
}

/*
*  @name   : loadFirstQuestionSet
*  @purpose: load First Question Set
*  @params : none
*  @return : none
*/
function loadFirstQuestionSet()
{
   $('page_'+CURRENT_PAGE_NUM).style.display='block';
   return;
}

/*
*  @name   : renderNavigationBlock
*  @purpose: load Navigation Block
*  @params : none
*  @return : none
*/
function renderNavigationBlock()
{
   $('prev_link').style.display = (CURRENT_PAGE_NUM == 1) ? 'none' : 'block';

   $('next_link').style.display = (CURRENT_PAGE_NUM == TOTAL_PAGE_NUM) ? 'none'
                                                                       : 'block';
   if(document.getElementById('curr_page')!= null)
   {
      $('curr_page').innerHTML = CURRENT_PAGE_NUM;
      $('tot_page').innerHTML  = TOTAL_PAGE_NUM;
   }

   if($('prev_link').style.display == 'none')
   {
      $('pageCounterBlock').className = 'pageNo2';
   }

   return;
}

/*
*  @name   : changePage
*  @purpose: change Page
*  @params : none
*  @return : none
*/
function changePage(page)
{
   if((isRadioAnswerType()) && page == 'next' && !validateOnPageChange())
   {
      alert(VALIDATION_MSG);
      highlightUnansweredQuestions();
      return;
   }

   switch(page)
   {
      case 'previous' : CURRENT_PAGE_NUM--; break;
      case 'next'     : CURRENT_PAGE_NUM++; break;
      default         : return;
   }

   if(OMNITURE == true) createPageView('Quizfarm');

   document.quiz_runner_form.page_no.value = CURRENT_PAGE_NUM;
   document.quiz_runner_form.submit();

}

/*
*  @name   : toggleSubmitButtonDisplay
*  @purpose: Display block or none of Submit Button
*  @params : none
*  @return : none
*/
function toggleSubmitButtonDisplay()
{
   $('submit_quiz').style.display = (CURRENT_PAGE_NUM == TOTAL_PAGE_NUM) ? 'block'
                                                                         : 'none';
   return;
}

/*
*  @name   : submitForm
*  @purpose: submit the Form Data
*  @params : none
*  @return : none
*/
function submitForm()
{
   if(isRadioAnswerType())
   {
      if(!validateOnSubmit())
      {
         alert(VALIDATION_MSG);
         highlightUnansweredQuestions();
         return;
      }
   }

   if(OMNITURE == true) createPageView('Quizfarm');

   document.forms['quiz_runner_form'].action = SITE_URL+'/run.php/QuizRunner';
   $('quiz_runner_form').submit();
}

/*
*  @name   : validateOnSubmit
*  @purpose: validate before Submit
*  @params : none
*  @return : none
*/
function validateOnSubmit()
{
   for(var i = 1; i <= QUESTION_COUNT; i++)
   {
      if(areNoRadiosSelected('question_'+i)) return false;
   }
   return true;
}

/*
*  @name   : getFirstUnansweredQuestionNumber
*  @purpose: get the first unanswered question no
*  @params : none
*  @return : if success int, otherwise none
*/
function getFirstUnansweredQuestionNumber()
{
   for(var i = 1; i <= QUESTION_COUNT; i++)
   {
      if(getParentDivDisplayProperty($('question_'+i)) == 'block')
      {
         if(areNoRadiosSelected('question_'+i)) return i;
      }
   }
}

/*
*  @name   : getAllUnansweredQuestionNumbers
*  @purpose: get all unanswered question numbers
*  @params : none
*  @return : int
*/
function getAllUnansweredQuestionNumbers()
{
   var unansweredQuestionNumbers = Array();
   for(var i = 1; i <= QUESTION_COUNT; i++)
   {
      if(getParentDivDisplayProperty($('question_'+i)) == 'block')
      {
         if(areNoRadiosSelected('question_'+i)) unansweredQuestionNumbers.push(i);
      }
   }

   return unansweredQuestionNumbers;
}

/*
*  @name   : highlightUnansweredQuestions
*  @purpose: highlighted all unanswered questions
*  @params : none
*  @return : int
*/
function highlightUnansweredQuestions()
{
   questionNumbers = getAllUnansweredQuestionNumbers();
   for(var i=0; i < questionNumbers.length; i++)
   {
      $('question_no_'+questionNumbers[i]).style.color = 'red';
   }

   return;
}

/*
*  @name   : isRadioAnswerType
*  @purpose: To check answer type is radio or not
*  @params : none
*  @return : on success false, otherwise true
*/
function isRadioAnswerType()
{
   for(var i = 0; i < DROPDOWN_ANSWER_TYPES.length; i++)
   {
      if(ANSWER_TYPE == DROPDOWN_ANSWER_TYPES[i]) return false;
   }

   return true;
}

/*
*  @name   : validateOnPageChange
*  @purpose: To check whether the answer type is selected or not
*  @params : none
*  @return : on success false, otherwise true
*/
function validateOnPageChange()
{
   for(var i = 1; i <= QUESTION_COUNT; i++)
   {
      if(getParentDivDisplayProperty($('question_'+i)) == 'block')
      {
         if(areNoRadiosSelected('question_'+i)) return false;
      }
   }

   return true;
}

/*
*  @name   : areNoRadiosSelected
*  @purpose: To check whether the input type is selected or not
*  @params : questionId
*  @return : on success false, otherwise true
*/
function areNoRadiosSelected(questionId)
{
   var radios = $(questionId).getElementsByTagName('input');
   for(var i = 0; i < radios.length; i++)
   {
      if(radios[i].checked == true) return false;
   }
   return true;
}

/*
*  @name   : getParentDivDisplayProperty
*  @purpose: get parent div display property
*  @params : node
*  @return : display property
*/
function getParentDivDisplayProperty(node)
{
   while(node.id.search(/page_[\d]/) == -1 )
   {
      node = node.parentNode;
   }

   return node.style.display;
}

/*
*  @name   : changeColor
*  @purpose: change the color, red to black.
*  @params : questionNumber
*  @return : none
*/
function changeColor(questionNumber)
{
   if($('question_no_'+questionNumber).style.color == 'red')
      $('question_no_'+questionNumber).style.color = '';

   return;
}

/*
*  @name   : showIntermediateWindow
*  @purpose: show the intermediate window
*  @params : quizId
*  @return : none
*/
function showIntermediateWindow(quizId)
{
   if(isRadioAnswerType())
   {
      if(!validateOnSubmit())
      {
         alert(VALIDATION_MSG);
         highlightUnansweredQuestions();
         return;
      }
   }

   var quizId = $('quiz_id').value;

   var frame = document.createElement("IFRAME");
   frame.frameBorder = 0;
   frame.id        = 'interestitial_frame';
   frame.name      = 'interestitial_frame';
   frame.className = 'interestitial_iframe';
   $('interestitial_window').appendChild(frame);
   frame.src = '/run.php/QuizRunner?cmd=load_interestitial_screen&quiz_id='+quizId;

   Lightbox.showBoxByID('interestitial_window');
   setTimeout('showResult()',INTERMEDIATE_WINDOW_LIFETIME);
}

function startIntermediateResultTimer()
{
   setTimeout('showResult()', INTERMEDIATE_WINDOW_LIFETIME);

   $('interestitial_frame').contentWindow.$('hurry_up').src          = '/view/common/images/btn_hurry_up.png';
   $('interestitial_frame').contentWindow.$('hurry_up').style.cursor = 'pointer';

   $('interestitial_frame').contentWindow.$('hurry_up').setAttribute('onClick', 'JavaScript:parent.showResultHurryUp();');
   $('interestitial_frame').contentWindow.$('subject').setAttribute('onFocus', 'JavaScript:parent.resetTimeOut();');
   $('interestitial_frame').contentWindow.$('message_body').setAttribute('onFocus', 'JavaScript:parent.resetTimeOut();');
}


/*
*  @name   : showResult
*  @purpose: show the result
*  @params : none
*  @return : none
*/
function showResult()
{
   if(WINDOW_FLAG)
   {
      var frameDocument;

      if(Prototype.Browser.Gecko)
      {
         frameDocument = $('interestitial_frame').contentDocument;
      }
      else
      {
         frameDocument = $('interestitial_frame').contentWindow.document
      }

      frameDocument.getElementById('hurry_up').src = SITE_URL+'/view/common/images/btn_see_result.png';
      frameDocument.getElementById('calculate_txt').innerHTML = 'Your result is ready';
      frameDocument.getElementById('img_container').innerHTML = '';

      return;
   }

   document.forms['quiz_runner_form'].action = SITE_URL+'/run.php/QuizRunner';
   document.forms['quiz_runner_form'].setAttribute('action',SITE_URL+'/run.php/QuizRunner');
   document.forms['quiz_runner_form'].submit();
   Lightbox.hideBox();
}

/*
*  @name   : showResultHurryUp
*  @purpose: show result hurry popup box
*  @params : none
*  @return : none
*/
function showResultHurryUp()
{
   if(OMNITURE == true) createPageView('Quizfarm');

   document.forms['quiz_runner_form'].action = SITE_URL+'/run.php/QuizRunner';
   document.forms['quiz_runner_form'].setAttribute('action',SITE_URL+'/run.php/QuizRunner');
   document.forms['quiz_runner_form'].submit();
   Lightbox.hideBox();
}

/*
*  @name   : resetTimeOut
*  @purpose: reset time out flag
*  @params : none
*  @return : none
*/
function resetTimeOut()
{
   WINDOW_FLAG = true;
}

/*
function sendMessage()
{
   var userId = isLoggedIn();

   if($('subject').value == '')
   {
      $('show_message').innerHTML = 'Subject cannot be empty.';
      return;
   }

   if($('body').value == '')
   {
      $('show_message').innerHTML = 'Message body cannot be empty.';
      return;
   }

   $('from_user_id').value = userId;

   var url    = SITE_URL+'/run.php/QuizRunner';
   var params = $('message_frm').serialize();

   new Ajax.Request(url,
   {
      method     : 'post',
      parameters : params ,
      onComplete : function(res)
      {
         $('show_message').innerHTML = 'Your message has been sent.';
         $('subject').value = '';
         $('body').value    = '';
      }
   });
}
*/

/*
*  @name   : showImagePreview
*  @purpose: preview image
*  @params : answerId int, smallImageEl int
*  @return : none
*/
function showImagePreview(answerId,smallImageEl)
{
   var standardbody = (document.compatMode=="CSS1Compat") ? document.documentElement
                                                          : document.body;
   var scrollY      = (window.scrollY) ? window.scrollY
                                       : document.documentElement.scrollTop;
   var clntHeight   = (window.innerHeight) ? window.innerHeight
                                           : standardbody.clientHeight;

   var smallPos    = Position.cumulativeOffset(smallImageEl);
   var smallRelPos = Position.positionedOffset(smallImageEl);
   var smallDim    = smallImageEl.getDimensions();
   var bigImageEl  = $(BIG_IMAGE_PREFIX+answerId);
   var bigDim      = bigImageEl.getDimensions();

   bigImageEl.style.left = (smallPos[0]+smallDim.width)+'px';

   //$('debug').innerHTML = 'img:'+(smallRelPos[1]+bigDim.height)+'client:'+(scrollY+clntHeight);

   if((smallRelPos[1]+bigDim.height) < (scrollY+clntHeight))
   {
      bigImageEl.style.top  = (smallRelPos[1])+'px';
   }
   else
   {
      bigImageEl.style.top  = ((scrollY+smallRelPos[1])-((smallRelPos[1]+bigDim.height) - clntHeight))+'px';
   }

   bigImageEl.style.position = 'absolute';
   bigImageEl.style.display  = 'block';
}

/*
*  @name   : hideImagePreview
*  @purpose: hide preview image
*  @params : answerId int
*  @return : none
*/
function hideImagePreview(answerId)
{
   var bigImageEl = $(BIG_IMAGE_PREFIX+answerId);
   bigImageEl.style.display = 'none';
}

/*
*  @name   : addUserTag
*  @purpose: adding user tag
*  @params : quizID int
*  @return : none
*/
function addUserTag(quizID)
{
   if($('user_tag').value == '')
   {
      $('tag_save_status').innerHTML = NO_TAG_ENTERED_WARNING;
   }
   else
   {
      var params = 'cmd=tag&tag='+$('user_tag').value+'&quiz_id='+quizID;
      new Ajax.Request(SITE_URL+'/run.php/Tag',
                      {
                         method     : 'post'
                        ,parameters : params
                        ,onSuccess  : function(transport)
                         {
                            $('tag_save_status').innerHTML = transport.responseText;
                            $('user_tag').value = '';
                            $('user_tag').focus();
                         }
                       });
   }
}

/*
*  @name   : isLoggedIn
*  @purpose: to check login or not
*  @params : none
*  @return : on success true, otherwise false
*/
function isLoggedIn()
{
   var status;
   var url = SITE_URL+'/run.php/Login?cmd=is_logged_in';

   new Ajax.Request(url,
       {
          method        : 'post'
         ,asynchronous  : false
         ,onSuccess     : function(transport)
                          {
                             status = (transport.responseText == 1) ? true : false;
                          }
       });

   return status;
}

/*
*  @name   : randomizeQuestions
*  @purpose: to randomize questions
*  @params : none
*  @return : none
*/
function randomizeQuestions()
{
    for(var j = 1; j <= TOTAL_PAGE_NUM; j++)
    {
       var questions = new Array();

       if($('table_'+j)){
          questions = $('table_'+j).childElements();
       }
       else{
          questions = $('page_'+j).childElements();
       }

       questions.shuffle();

       for(var i = 0; i < questions.length; i++)
       {
          if($('table_'+j)){
          $('table_'+j).appendChild(questions[i]);
         }
         else{
           $('page_'+j).appendChild(questions[i]);
         }
       }
    }

    changeQuestionLabel();

    if(ANSWER_TYPE == 'Trivia') randomizeAnswers();

    return;
}

/*
*  @name   : shuffle
*  @purpose: shuffle array
*  @params : array
*  @return : array
*/
function shuffle( array )
{
  for(var j, x, i = array.length; i; j = parseInt(Math.random() * i), x = array[--i], array[i] = array[j], array[j] = x);
  return array;
}

/*
*  @name   : changeQuestionLabel
*  @purpose: change the question label
*  @params : none
*  @return : none
*/
function changeQuestionLabel()
{
   var labels = document.getElementsByName('lbl_question');
   for(var i = 0; i < labels.length; i++)
   {
      labels[i].innerHTML = i+1+'. ';
   }
}

Array.prototype.shuffle=function()
{
   for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
   return;
}

/*
*  @name   : randomizeAnswers
*  @purpose: to randomize answers
*  @params : none
*  @return : none
*/
function randomizeAnswers()
{
   for(var i = 1; i <= QUESTION_COUNT; i++)
   {
      var answers = $$('#question_'+i+' .quizActions_text');

      var labels = $A(answers[0].getElementsByTagName('label'));
      labels.shuffle();
      str = '';
      labels.each(function(e){str += '<label>'+e.innerHTML+'</label><br>';});
      answers[0].innerHTML = '';
      answers[0].innerHTML = str;
   }

   return;
};

/*
*  @name   : showFullVideo
*  @purpose: to show full video
*  @params : videoId
*  @return : none
*/
function showFullVideo(videoId)
{
   var videoLink = $('video_src_'+videoId).innerHTML;
   var videoUtilsObj = new VideoUtils(videoLink, FULL_VIDEO_WIDTH, FULL_VIDEO_HEIGHT);
   videoLink = videoUtilsObj.resizeVideoObject();
   newWindow= window.open ("", "Welcome","status=1,width=450,height=400,resizable=1");
   var doc = newWindow.document;
   doc.open("text/html", "replace");
   var contents = "<div style='padding-bottom:5px;' align='left'><input onclick='self.close()' type='button' value='Close'></div>"+videoLink;
   newWindow.document.write(contents);
   doc.close();
}

/*
*  @name   : showFlagPopup
*  @purpose: to show flag popup
*  @params : divId
*  @return : none
*/
function showFlagPopup(divId)
{
   Lightbox.showBoxByID(divId);
   loadFlagTypes();
}

/*
*  @name   : hidePopupBox
*  @purpose: to hide popup box
*  @params : none
*  @return : none
*/
function hidePopupBox()
{
   Lightbox.hideBox();
}

/*
*  @name   : loadFlagTypes
*  @purpose: to load flag types
*  @params : none
*  @return : none
*/
function loadFlagTypes()
{
   var url   = '/run.php/Flag';
   var params = 'cmd=get_flag_types';
   new Ajax.Updater('flag_type_select',url,
   {
          method     : 'get'
         ,parameters : params
         ,onComplete:function(response)
         {
            /* do nothing */
         }
   });
}

/*
*  @name   : flagQuiz
*  @purpose: to show flag quiz
*  @params : none
*  @return : none
*/
function flagQuiz()
{
   var quizId = $('quiz_id').value;

   if($('flag_id').value == 0)
   {
      return false;
   }

   var params = 'cmd=flag&quiz_id='+quizId+'&'+$('flag_reason_form').serialize();
   new Ajax.Request('/run.php/Flag',
                   {
                        method     : 'post'
                       ,parameters : params
                       ,onSuccess  : function(response)
                       {
                          hidePopupBox();
                          $('flag_reason').value = '';
                          $('flag_id').selectedIndex = 0;
                       }
                    });
}
