// Simple Studies Application javascrip's

// Page init`s
// TODO: PLEASE, ADD COMMENTS, TO THE FOLLOW BLOCK'S: 
$(document).ready(function(){

    //LSF_init( 'lsForm_href' );
//    $('#lsForm').keydown(function(){  });

    /*$('input.grey:checkbox, input.grey:radio').checkbox({
        cls:'jquery-grey-checkbox', empty:'images/spacer.gif'});*/
    
    //$('input.lectureCheck:checkbox').checkbox()

    /*$('input.red:checkbox, input.red:radio').checkbox({
        cls:'jquery-red-checkbox', empty:'images/spacer.gif'});*/

    $(document).pngFix();

    $('#definp1').inline_caption({
        txt: 'type your e-mail', 
        txtStyle: 'color: #999999; font-size: 14px; font-weight: bold;',
        divtop: -20
    });

    $('#definp2').inline_caption({
        img:      'images/google_tm.gif', 
        width: 54,
        height: 24,
        left: 10,
        top: 11,
        imgStyle: '10px 11px',
        divtop: -28
    });

    $('#definp5').inline_caption({
        txt: 'type your e-mail', 
        txtStyle: 'color: #999999; font-size: 14px; font-weight: bold;',
        divtop: -20
    });

    $('.block_red img.lock, .block_green img.lock, .block_lgreen img.lock').attr('src', 'images/lock_w.gif');

    /* for Contact view */

    if ( jQuery("#contactForm").length ) {
        if ( jQuery("#contactForm select").get(0).value == "c" ) {
            jQuery('#ask_quest').show();
        }
        jQuery("#contactForm select").change(function(){
            if (jQuery(this).val() == 'c') jQuery('#ask_quest').show(); else jQuery('#ask_quest').hide();
        });
    }

    jQuery('#timeOnTest_td input').keyup(function() { timeOnQuest(); });
    jQuery('#questionsToTake_td').keyup(function() { timeOnQuest(); });

    if ( jQuery('.tests').length > 0 ) {
        $('.lectureType').each(function(){
            arr=$(this).find('.title font')
            sum=0;
            for (i=0;i<arr.length;i++) {
                sum+=parseInt($(arr.get(i)).html());
            }
            //alert(sum);
            if ( sum > 0 ) {
                $(this).show();
            }
        });
    }

    //if ( jQuery('#chkb_timeLimit').length > 0 ) {


        jQuery('#testAll\\[timeLimit\\]').click(function() {
        	//alert('123');
            if (jQuery(this).attr('checked')) {

                jQuery('#div_time').show();
            } else {

                jQuery('#div_time').hide();
            }
        });
        
        jQuery('#testAll\\[filterBookmark\\]').click(function() {
        	jQuery('#select_tutorials_content').html('<br/><center><font style="font: 13px Arial;">Please wait...</font></center>');
        	jQuery('#testAll\\[questionsToTake\\]').val(0);        	
            if (jQuery(this).attr('checked')) {
            	jQuery('#testAll\\[filter\\]').val(1);
			    $.ajax({
        			'type': 'POST',
			        'url':  'tests/indexbookmarks',
        			'cache':false,
        			'success': function(data) {
        				jQuery('#select_tutorials_content').html(data);
	 					$('.lectureType').each(function(){
    	        			arr=$(this).find('.title font')
        	    			sum=0;
            				for (i=0;i<arr.length;i++) {
                				sum+=parseInt($(arr.get(i)).html());
	            			}
    	        			if ( sum > 0 ) {
        	        			$(this).show();
            				}
        				});   

        				jQuery.listId = new Array();
        				jQuery.cntQuestions = 0;

        				initPageTestAll();
        
        				jQuery("input.lectureCheck").bind("click", function(){ all_bindCheckUncheck( this.id ); });	 								
	 					     	
        			},
        			'fault': function(err) {
        			}
    			});                
            } else {
            	jQuery('#testAll\\[filter\\]').val(0);
            	 $.ajax({
        			'type': 'POST',
			        'url':  'tests/indexnotbookmarks',
        			'cache':false,
        			'success': function(data) {
        				jQuery('#select_tutorials_content').html(data);
	 					$('.lectureType').each(function(){
    	        			arr=$(this).find('.title font')
        	    			sum=0;
            				for (i=0;i<arr.length;i++) {
                				sum+=parseInt($(arr.get(i)).html());
	            			}
    	        			if ( sum > 0 ) {
        	        			$(this).show();
            				}
        				});           	
	 					jQuery.listId = new Array();
        				jQuery.cntQuestions = 0;

        				initPageTestAll();
        
        				jQuery("input.lectureCheck").bind("click", function(){ all_bindCheckUncheck( this.id ); });	
        				
        			},
        			'fault': function(err) {
        			}
    			}); 
            }
        });
        
        if (jQuery('#testAll\\[timeLimit\\]').attr('checked')) {

            jQuery('#div_time').show();
        } else {

            jQuery('#div_time').hide();
        }
    //};
    
			$('.faq_help').each(function(){
            	var link=$(this).one('click', function(){
            		
            		document.getElementById('TB_iframe').src = '';
            		document.getElementById('TB_iframe').src = link.attr('href');
            		document.getElementById('TB_overlay').style.display='block';
            		document.getElementById('TB_popup').style.display='block';
            		
                	link.click(function(){
                    	
            			document.getElementById('TB_iframe').src = '';
            			document.getElementById('TB_iframe').src = link.attr('href');
            			document.getElementById('TB_overlay').style.display='block';
            			document.getElementById('TB_popup').style.display='block';                    	
                    	
                    	return false;
                    });
                    
                    return false;
                });
            });    
            
            $('#see_how').click(function(){
                    	
            			var link=$(this);
            	
            			document.getElementById('TB_iframe').src = '';
            			document.getElementById('TB_iframe').src = link.attr('href');
            			document.getElementById('TB_overlay').style.display='block';
            			document.getElementById('TB_popup').style.display='block';                    	
                    	
                    	return false;
                    });
            
            
});

function update_timeLimitCounter() {

    count_second--;
    if ( count_second > 0 ) {
            
        var cnt_minutes = parseInt(count_second/60);
        var cnt_second = count_second-60*parseInt(count_second/60);
        if ( cnt_second < 10 ) {
            if ( cnt_minutes == 0 ) {
                
                cnt_second_str = cnt_second+'';
            } else {

                cnt_second_str = '0'+cnt_second+'';
            }
        }
        else {
            cnt_second_str = cnt_second;
        }
    
        var put_html = '';
        if ( cnt_minutes > 0 ) {
    
            put_html = cnt_minutes+' min ';
        }
        put_html += cnt_second_str+' sec';
        jQuery('#timeLimit_counter').html( put_html );
        /*    jQuery('.timeLimit span#counter').html(count_second+' sec'); */
    }
    else {

        jQuery('#timeLimit_counter').html( '0 sec' );
    }

    if (count_second > 1) {

        setTimeout( update_timeLimitCounter, 1000);
    } else {

        setTimeout( update_timeLimitCounter_redirect, 1000);
    }
}

function update_timeLimitCounter_redirect() {

    document.location = redirect_href;
}

function crt_bindCheck( th ) {

    var type_id = th.form[contextName+"[type_id]"].value;
    if ( typeof(jQuery.listId[type_id]) == 'undefined' ) {

        jQuery.listId[type_id] = new Array();
    }

    jQuery.listId[type_id] = addId2List2( jQuery.listId[type_id], th );
    th.form[contextName+"[listId]"].value = makeListFromArray(jQuery.listId[type_id]);

    return;
}

function crt_bindUncheck( th ) {

    var type_id = th.form[contextName+"[type_id]"].value;
    if ( typeof(jQuery.listId[type_id]) == 'undefined' ) {

        jQuery.listId[type_id] = new Array();
    }

    jQuery.listId[type_id] = removeIdFromList2( jQuery.listId[type_id], th );

    th.form[contextName+"[listId]"].value = makeListFromArray(jQuery.listId[type_id]);
    return;
}

function all_bindCheckUncheck( id ) {
	if(jQuery('#'+id).attr('checked')==true) {
		all_bindCheck( id );
	} else {
		all_bindUncheck( id );
	}
}

function all_bindCheck( id ) {
	
	
	
    var val = jQuery('#'+id+'_cntQuestions').html();
    var oldCnt = jQuery.cntQuestions;

    if ( jQuery.listId.length ) {

        var exist_item = false;
        for ( cntItems = 0; jQuery.listId[cntItems]; cntItems++ ) {
            if ( jQuery.listId[cntItems] == id ) { exist_item = true; }
        }
        if ( !exist_item ) {

            jQuery.listId = jQuery.merge( jQuery.listId, [ id ] );
            jQuery.cntQuestions += parseInt(val);
        }
    }
    else {
        jQuery.listId = [ id ];
        jQuery.cntQuestions = parseInt(val);
    }

    if ( oldCnt != jQuery.cntQuestions) {
        jQuery('#cntQuestionsOnSelect').html(jQuery.cntQuestions);
    }
    timeOnQuest( jQuery.cntQuestions );
}

function all_bindUncheck( id ) {

    var val = jQuery('#'+id+'_cntQuestions').html();
    var oldCnt = jQuery.cntQuestions;

    if ( jQuery.listId.length ) {

        var exist_item = 0;
        var tmp_arr = new Array();
        for ( cntItems = 0; jQuery.listId[cntItems]; cntItems++ ) {
            if ( jQuery.listId[cntItems] == id ) { exist_item = 1; }
            else { tmp_arr[cntItems-exist_item] = jQuery.listId[cntItems]; }
        }
        if ( exist_item ) {

            jQuery.listId = tmp_arr;
            jQuery.cntQuestions -= parseInt(val);
        }
    }
    else {
        jQuery.cntQuestions = 0;
        jQuery.listId = new Array();
    }
    if ( oldCnt != jQuery.cntQuestions) {
        jQuery('#cntQuestionsOnSelect').html(jQuery.cntQuestions);
    }
    timeOnQuest( jQuery.cntQuestions );
}

function initPageTestAll() {

    var checkedLections = jQuery('#listId').val();
    
    if ( jQuery.trim(checkedLections) != "" ) {
    	
    	

        jQuery.listId = makeArrayFromList(checkedLections);
        initPageTestAll_sub( jQuery.listId );
        jQuery( '#listId').val( makeListFromArray(jQuery.listId) );
        jQuery('#cntQuestionsOnSelect').html(jQuery.cntQuestions);
        timeOnQuest( jQuery.cntQuestions );
    }
}

function initPageTestAll_sub() {
    for ( cntItems = 0; jQuery.listId[cntItems]; cntItems++ ) {
        
        if ( jQuery('#'+jQuery.listId[cntItems]+'_cntQuestions').length ) {

            jQuery('#'+jQuery.listId[cntItems]+':checkbox').attr('checked', 'checked');
            jQuery.cntQuestions += parseInt(jQuery('#'+jQuery.listId[cntItems]+'_cntQuestions').html());
        } else {

            jQuery.listId.splice(cntItems, 1);
            initPageTestAll_sub( jQuery.listId );
            return;
        }
    }
}

function diag_bindcheck( th ) {
    jQuery.cntQuestions += parseInt(jQuery(th).parent().find('span#'+th.id+'_cntCuests').html());
    jQuery.listId = addId2List2( jQuery.listId, th );
    jQuery("#form_test_options #listId").val(makeListFromArray(jQuery.listId));
}

function diag_binduncheck( th ) {
    jQuery.cntQuestions -= parseInt(jQuery(th).parent().find('span#'+th.id+'_cntCuests').html());
    jQuery.listId = removeIdFromList2(jQuery.listId, th);
    jQuery("#form_test_options #listId").val(makeListFromArray(jQuery.listId));
}

function bookm_binduncheck_l( th ) {

    if ( jQuery.lectureCheck == 1 ) {

        jQuery(th).parents('.groupPreview').find('input.topicCheck').each(function(){ 

            jQuery(this).attr('checked', ''); 
            jQuery.listId = removeIdFromList2( jQuery.listId, this, true );
        });
        jQuery('#cntQuestionsOnSelect').html(jQuery.cntQuestions);
        timeOnQuest(  jQuery.cntQuestions );
    }
    jQuery.lectureCheck = 1;
}

function bookm_bindcheck_l( th ){

    if ( jQuery.lectureCheck == 1 ) {

        jQuery(th).parents('.groupPreview').find('input.topicCheck').each(function(){ 

            if ( !this.disabled ) {

                jQuery(this).attr('checked', 'checked'); 
                jQuery.listId = addId2List2( jQuery.listId, this, true );
            }
        });
        jQuery('#cntQuestionsOnSelect').html(jQuery.cntQuestions);
        timeOnQuest( jQuery.cntQuestions );
    }
    jQuery.lectureCheck = 1;
}


function bookm_bindcheck_t( th ) {    

    var table_container = jQuery(th).parents('.groupPreview');
    var list_topic_check = table_container.find('input.topicCheck:enabled').length;
    var list_topic_check_checked = table_container.find('input.topicCheck:checked').length;

    var parent_lecture_check = table_container.find('input.lectureCheck');
    if ( list_topic_check == list_topic_check_checked ) {

        jQuery.lectureCheck = 0;
        parent_lecture_check.attr('checked', 'checked');
    } else {

        if (parent_lecture_check.attr('checked')) {

            jQuery.lectureCheck = 0;
            parent_lecture_check.attr('checked', '');
        }
    }
    if ( jQuery(th).attr('checked') == true ) {

        jQuery.listId = addId2List2( jQuery.listId, th, true );
    } else {

        jQuery.listId = removeIdFromList2( jQuery.listId, th, true );
    }
    jQuery('#cntQuestionsOnSelect').html(jQuery.cntQuestions);
    timeOnQuest( jQuery.cntQuestions );
}

function bookm_init() {

    var checkedTopics = jQuery('#listId').val();
    if ( jQuery.trim(checkedTopics) != "" ) {

        jQuery.listId = makeArrayFromList(checkedTopics);
        for ( cntItems = 0; jQuery.listId[cntItems]; cntItems++ ) {

            jQuery('#'+jQuery.listId[cntItems]+':checkbox').attr('checked', 'checked');
            jQuery.cntQuestions += parseInt(jQuery('#'+jQuery.listId[cntItems]+'_cntQuestions').html());
        }
        jQuery('#cntQuestionsOnSelect').html(jQuery.cntQuestions);
        timeOnQuest( jQuery.cntQuestions );

        jQuery('.lectureCheck').each(function(){
            
            var lectureCheck = jQuery(this);
            var table_container = lectureCheck.parents('.groupPreview');
            var cnt_enabled = table_container.find('input.topicCheck:enabled').length;
            var cnt_enabled_checked = table_container.find('input.topicCheck:enabled:checked').length;

            if ( cnt_enabled == cnt_enabled_checked ) {
                jQuery.lectureCheck = 0;
                lectureCheck.attr('checked', 'checked');
            }
        });
    }
}

function makeListFromArray( arr, delim ) {

    if ( typeof(delim) == 'undefined' ) {

        delim='|';
    }
    list='';
    if ( typeof(arr.length) != 'undefined' ) {

        for(cntItems=0; arr[cntItems]; cntItems++) {

            if ( jQuery.trim(arr[cntItems]) != '' ) {
                if (cntItems>0) {

                    list +=delim;
                }
                list += arr[cntItems];
            }
        }
    }
    return list;
}

function makeArrayFromList( list, delim ) {

    if ( typeof(delim) == 'undefined' ) {

        delim='|';
    }

    var arr = list.split(delim);
    return arr;
}

function timeOnQuest( cntQuest ) {
	
	//alert('555');

    var html_ = "0";
/*    if ( typeof(cntQuest) == 'undefined' ) { 

        cntQuest = parseInt(jQuery('#cntQuestionsOnSelect').html());
    } */
    
    html_val_to_take = jQuery('#questionsToTake_td input').val();
    int_html_val_to_take = parseInt(html_val_to_take);
    if ( (int_html_val_to_take+'') != html_val_to_take ) {

        int_html_val_to_take = 0;
    }
    cntQuest = int_html_val_to_take;

    html_val = jQuery('#timeOnTest_td input').val();
    int_html_val = parseInt(html_val);
    if ( (int_html_val+'') != html_val ) {
        tot = 0;
    }
    else {
        tot = int_html_val;
    }
    if (cntQuest != 0) {
        html_ = parseFloat(Math.round(tot*10/cntQuest)/10);
    }
    //alert(html_);
    jQuery( '#timeOnQuest' ).html( html_ );
    jQuery( '#listId').val( makeListFromArray(jQuery.listId) );
}

function addId2List2( arr, obj, calc ) {

    var id=obj.id;
    var val;
    if ( typeof(calc) != 'undefined' ) { val = jQuery('#'+id+'_cntQuestions').html(); }
    if ( arr ) {

        var exist_item = false;
        for ( cntItems = 0; arr[cntItems]; cntItems++ ) {

            if ( arr[cntItems] == id ) { exist_item = true; }
        }
        if ( !exist_item ) {

            arr = jQuery.merge( arr, [ id ] );
            if ( typeof(calc) != 'undefined' ) { jQuery.cntQuestions += parseInt(val); }
        }
    }
    else {

        arr = [ id ];
        if ( typeof(calc) != 'undefined' ) { jQuery.cntQuestions = parseInt(val); }
    }
    return arr;
}

function removeIdFromList2( arr, obj, calc ) {

    var id=obj.id;
    var val;
    if ( typeof(calc) != 'undefined' ) { val = jQuery('#'+id+'_cntQuestions').html(); }
    if ( arr ) {

        var exist_item = false;
        var tmp_arr = [];
        for ( cntItems = 0; arr[cntItems]; cntItems++ ) {
            if ( arr[cntItems] == id ) { exist_item = 1; }
            else { tmp_arr[cntItems-exist_item] = arr[cntItems]; }
        }
        if ( exist_item ) {

            arr = tmp_arr;
            if ( typeof(calc) != 'undefined' ) { jQuery.cntQuestions -= parseInt(val); }
        }
    }
    else {

        if ( typeof(calc) != 'undefined' ) { jQuery.cntQuestions = 0; }
    }
    return arr;
}

function make_string_params() {
    params = '?';
    form_bookmark_add='';
    if ( jQuery.trim( jQuery('#for_bookmarks_add').val() ) != '' ) {

        form_bookmark_add = 'for_bookmarks_add=' + jQuery('#for_bookmarks_add').val();
        params += form_bookmark_add;
    }
    form_bookmark_dl='';
    if ( jQuery.trim( jQuery('#for_bookmarks_dl').val() ) != '' ) {

        if ( form_bookmark_add != '' ) {
            params += '&';
        }
        form_bookmark_dl = 'for_bookmarks_dl=' + jQuery('#for_bookmarks_dl').val();
    }
    params += form_bookmark_dl;
    if ( params != '?' ) {
        return params;
    }
    return '';
}
function SelectAll(id)
{
    document.getElementById(id).focus();
    document.getElementById(id).select();
}    

function multipleChoiceFields(type)
{
	if(type=='multiple')
	{
		jQuery('#block_answer_c').show();
		jQuery('#block_answer_d').show();
	}
	else if(type=='truefalse')
	{
		jQuery('#block_answer_c').hide();
		jQuery('#block_answer_d').hide();		
	}
}

function loadTopicsByLecture(lectureID,category, selectedTopicID, selectedTestsetID)
{
	jQuery.getJSON('questionadmin/fetchtopics/id/'+lectureID+'/cat/'+category, null, function(data){
		var options='';
		var topics=data['topics'];
		for(var key in topics)
		{
			options+="<div class='radio_1'><input type='radio' name='questionEdit[topicID]' value='"+key+"'";
			if(key==selectedTopicID)
				options+=' checked';
			options+="><a target='_blank' href='"+topics[key]['url']+"'>"+topics[key]['title']+"</a></div><div class='clear'></div>";
		}
		
		var testsetOptions='';
		var testsets=data['testsets'];		
		testsetOptions+="<div class='radio_1'><input type='radio' name='questionEdit[testsetID]' value='none' checked /><span>None</span></div><div class='clear'></div>";
		
		var cnt = 0;
		for(var k in data['testsets']) 
			cnt = cnt + 1;
		
		//alert(category+' '+cnt);
		if((category=='exam')&&(cnt>0)) {
			
		} else {
			testsetOptions+="<div class='radio_1'><input type='radio' name='questionEdit[testsetID]' value='new' /><span>";
			if(category=='exam')
				testsetOptions+="New Exam Test Set";
			else
				testsetOptions+="New Practice Test Set";			
			testsetOptions+="</span></div><div class='clear'></div>";
		}
		
		for(var key in testsets)
		{
			testsetOptions+="<div class='radio_1'><input type='radio' name='questionEdit[testsetID]' value='"+key+"'";
			if(key==selectedTestsetID)
				testsetOptions+=' checked';
			testsetOptions+="><span>";
			if(category=='exam')
				testsetOptions+="Exam ";
			else
				testsetOptions+="Practice ";
			testsetOptions+="Test Set "+key+": Questions - "+testsets[key][1]+" ("+testsets[key][0]+")</span></div><div class='clear'></div>";
		}
		
		
		//jQuery('#exam_published', '#block_exam').text(data['exam'][0]);
		//jQuery('#exam_draft', '#block_exam').text(data['exam'][1]);
		jQuery('#topic_id_block').html(options);
		jQuery('#testset_id_block').html(testsetOptions);
	});
}

