/*
 * This is used to manage the Quiz Setup page
 */

$(document).ready(function(){

    //Quizzes table sorter
    $("#quizzes-sort").tablesorter({sortList:[[0,1]], headers: {4: {sorter: false}}, widgets: ['zebra']});

    //Reviews table sorter
    $("#reviews-sort").tablesorter({sortList:[[0,0]], headers: {3: {sorter: false}}, widgets: ['zebra']});

	/**
	 * To start Quiz
	 */
	$('#take-quiz').livequery('click', function() {
		 var chapterId = $('#quiz-chapter').val();
		 if(chapterId == null || chapterId == 0){
    		 alert('Please select a Quiz');
    		 $("#quiz-chapter").focus();
    		 return false;
    	 }
    	 $('#quiz-id').val($('#quiz-chapter :selected').attr('id'));
    	 var quesNo = $('input:radio[name=no-of-ques]:checked').val();
    	 if(quesNo == null || quesNo <= 0){
    		 alert('Please select number of questions');
    		 return false;
    	 }
    	 var quesType = $('input:radio[name=ques-type]:checked').val();
    	 if(quesType == null){
    		 alert('Please select type of questions');
    		 return false;
    	 }
    	 $('#quiz-setup-form').submit();
    });
	
	//quiz start page is ready
	var totalQues = $("#total-ques").val();
	var quesArray = new Array();
	$('#question-container >div.ques-list').each(function(i){
		var ques = $(this).attr('id');
		ques = ques.split('-');
		ques = ques['2'];
		quesArray[i] = '{"QuestionId":"'+ques+'","Answer":""}';
	});

	/**
	 * On click of NEXT question
	 */
	var currQues = 1;
	$('#next-question').livequery('click', function(){
		var quizId = $('#quiz-id').val();
		//var userAnswers = new Array();
		var userAnswers = '{"Questions":[';
		var quesLength = $('#question-container >div').length;
		currQues = currQues + 1;
		if(currQues > quesLength){
			for(var i = 0; i < quesArray.length; i++){
				userAnswers += quesArray[i]+',';
			}
			userAnswers = rtrim(userAnswers,",");
			userAnswers += ']}';
			$('#data').val(userAnswers);
			$('#question-container, #nav-next').hide();
			$('#loader-container').show();
			
			//submit the quiz form
			$('#user-quiz-form').submit();			
		}
		$('#question-container >div').hide();
		$('#question-container >div:nth-child('+currQues+')').fadeIn('slow');
	});
	
	/**
	 * On click of Option radio button
	 */
	$('ul.qlist li :input').livequery('click', function(){
		
		if($(this).attr('checked')){
			var quesDiv = $(this).parent().parent().parent().attr('id');
			quesDiv = quesDiv.split('-');
			var ques = quesDiv['2'];
			var quesIdx = quesDiv['1'];
			
			var option = $(this).attr('id');
			option = option.split('-');
			answer = option['1'];
			
			if(quesArray[quesIdx-1] == '{"QuestionId":"'+ques+'","Answer":""}'){
				quesArray[quesIdx-1] = '{"QuestionId":"'+ques+'","Answer":"'+answer+'"}';
			} 			
			
			var fback = $(this).parent().find('div.note');
			$('.note').hide();
			fback.fadeIn('slow');
			setTimeout(function(){
				fback.fadeOut('slow');
			},10000);
		}
	});
	
	/**
	 * Review Quizzes page
	 * On click of Add to Flashcard icon
	 */
	$('.add-to-flashcards').livequery('click', function(){
		var chapter = $(this).attr('id');
		chapter = chapter.split('~');
		var chapterTitle = chapter[0];
		var chapterId = chapter[1];
		
		var lowerCaseTitle = chapterTitle.toLowerCase();
		lowerCaseTitle = lowerCaseTitle.replace(/ /g, '-');
		
		$('#chapterId').val(chapterId);
		$('#chapterTitle').val(chapterTitle);
		$('#methodName').val('flash-cards');
		$('#flash-cards-form').attr('action','/account/study/flash-cards/'+lowerCaseTitle).submit();
	});
	
	/**
	 * Review One Quiz page
	 * On click of tag this question icon
	 */
	$('.tag-question-card').livequery('click', function(){
		var ele = $(this);
		$(ele).hide();
		$(ele).next().show();
		var question = $(this).attr('id');
		var temp = question.split('-');

		var cardType = 0;
		var cardId = temp['1'];

		$.ajax({
            type: "POST",
            url: "/account/tag-card",
            data: {cardType:cardType,cardId:cardId},
            success: function(r){
            	if(r != 0){
            		if(r == 'tagged'){
            			$('#'+question).addClass('tagged-question').attr("title", "UnTag this Question");
            		} else {
        				$('#'+question).removeClass('tagged-question').attr("title", "Tag this Question");
            		}
            	} else {
            		alert('Please Try again later');
            	}
        		$(ele).show();
        		$(ele).next().hide();
            }
		});
	});
	
	/**
	 * Modal window for Chapter description
	 */
	$(".view-section").colorbox({width:"700px", height:"500px", title:""});

	$(".view-chapter").livequery(function() {
        var id = $(this).attr("id");
        id = id.split('-');
        $(this).colorbox({width:"70%", height:"450", inline:true, href:"#view-chapter-"+id[1], title:""});
    });

	$(".view-chapter").livequery('click',function() {
        var id = $(this).attr("id");
        id = id.split('-');
        
        $.ajax({
            type: "GET",
            url: "/account/get-sections-of-chapter/"+id[2]+"/"+id[3],
            success: function(data){
        		var cid = "#view-chapter-"+id[1];
            	$(cid).html(data.replace(/\\/g,""));
            }
		});
    });

    $("#ques-feedback >span").colorbox({width:"700px", height:"500px", href: function(){
        return "feedback?qid=" + $(this).html().replace(/\(|\)/g, "");
    }});

	if($("#review-quiz-link").length > 0){
		var url = $("#review-quiz-link").attr("href") + $("#userQuizId").text();
		$("#review-quiz-link").attr("href", url);
	}

    $(".view-quiz-stats").colorbox({width:"700px", height:"500px", title:"", onComplete: function() { drawQuiz(); }});

});


/**
 * Right trims '||' for last object element
 */
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

