﻿$(document).ready(function(){
	//Executes the function when the DOM is ready to be used.
	// Document is ready
	TofslaFormsStart();
	
	// Add click event for voting for a question
	$('a[name^="vote"]').live( 'click' , function() {
		var $t = $(this);
		var fid = $t.attr('name');
		fid = fid.replace("vote_", '');
		
		var vote = $('input[name="question_'+fid+'"]:checked').val();
		if(typeof vote == 'undefined')
		{
			alert("Моля изберете ДА или НЕ.");
			return;
		}
		else
		{
			rateFaq( fid, vote, isDoneVotingArr[fid]);
		}		
	});

	// Add click event for showing and hiding the FAQ answer
	$('.faqItem .toggle').live( 'click' , function()
	{
		if(!$(this).closest('.faqItem').hasClass('opened'))
		{
			var questId = $(this).next('.thebox').find(':radio').attr('name');
			questId = questId.substring(9); //question_<id>
			_ajaxIncreaseCounter(questId);
		}
		
	  $(this).closest('.faqItem').toggleClass('opened');
	  $(this).next('.thebox').toggle();
	  $(this).closest('.faqItem').next('hr').toggle();
	  return false;
	});

});

// Array keeping all faq ids which have been voted for.
var isDoneVotingArr = [];

/**
 * Sets the topic name header to be the name of the selected one.
 **/
function setTopicName(topic_name)
{
	$('div[name="topic_name"] h3').html('<strong>'+topic_name+':</strong>');
	$('div[name="topic_name"]').show();
}

/**
 * Changes the content of the FAQ section according to the selected topic.
 * If the selected topic is one of the main topic list, then it reload also the sub-topics list. 
 **/
function setTopicData(topic_id, topic_name, is_main)
{
	if(is_main == true) {
		// Reload sub-topics list if the selected topic is MAIN
		_ajaxReloadSubTopics(topic_id);
	}
	
	// Update FAQ section according to the selected topic
	_ajaxReloadFaqs(topic_id, topic_name);
}

/**
 * Gets the new sub-topics list via AJAX according to the selected main topic id.
 * Calls the function that fills the sub-topic SELECT Object 
 **/
function _ajaxReloadSubTopics(topic_id)
{
	$.post('/faq/',
            {ajaxaction: 'getsubtopics',
             topic_id: topic_id
             },
            function(response) { 
                if(response.errorCode == 0) {
                	setSubTopics(response.response);
                } else {                    
                }
            },
            'json');
}

/**
 * Fills the sub-topics SELECT element with new options according to the passed parameter.
 **/
function setSubTopics(sub_topics, set_select)
{
	var sub_topics_list = jQuery.parseJSON( sub_topics );
	
	var sub_topics_select_obj = $('select[name="sub_topics"]');
	sub_topics_select_obj.empty();
	
	if (typeof set_select != 'undefined' && set_select == true)
	{
		sub_topics_select_obj.append('<option value="" selected="selected">Изберете...</option>');
	}
	
	for(var i=0; i<sub_topics_list.length; i++) {
		sub_topics_select_obj.append('<option value="'+sub_topics_list[i].topic_id+'">'+sub_topics_list[i].name+'</option>');
	}
}

/**
 * Gets the new FAQs via AJAX according to the selected topic id.
 * Calls the function that is responsible of showing the new data. 
 **/
function _ajaxReloadFaqs(topic_id, topic_name)
{
	$.post('/faq/',
            {ajaxaction: 'getfaqs',
             topic_id: topic_id
             },
            function(response) { 
                if(response.errorCode == 0) {
                
                	var faqs_list = jQuery.parseJSON( response.response );
                	
                	if(faqs_list.length == 0) 
					{
						$('div[name="topic_name"]').hide();
					}
					else
					{
						setTopicName(topic_name);
					}
					
                	setFaqs(faqs_list);
                } else {
                }
            },
            'json');
}

/**
 * Fills the FAQ list with the new data sent in the 'faqs_list' parameter.
 * 
 **/
function setFaqs(faqs_list)
{
	var faqs_list_div = $('div[name="faqs_list"]');
	
	// Empty FAQ list
	faqs_list_div.empty();
	var faq_item = '';
	
	if(faqs_list.length == 0) 
	{
		return;
	}
	
	// Fill the list
	for(var i=0; i<faqs_list.length; i++) {
		
		// User can vote for a particular FAQ only once
		isDoneVotingArr[faqs_list[i].faq_id] = faqs_list[i].is_done_voting;
		
		var disabledClass = '';
		var disabledAttr = '';
		if(faqs_list[i].is_done_voting)
		{
			disabledClass = 'tfDisabled';
			disabledAttr = 'disabled="disabled"';
		}
	
		// Buld the new FAQ item
		faq_item = '<div class="faqItem">'; 
	    faq_item = faq_item + '<a class="toggle isItLink" href="#"><strong>'+faqs_list[i].quest+'</strong>';
	    
	    if (faqs_list[i].is_new)
	    {
	    	faq_item = faq_item + ' <span class="reditalic">ново</span>';
	    }
	    
	    faq_item = faq_item + '</a>'+       
	              '<div class="hideme thebox theboxComplex theboxStandard theboxComment mtm">'+  
	              '<b class="theboxTop"><b class="theboxTl"></b><b class="theboxTr"></b></b>'+           
	                '<div class="theboxInner"><div class="theboxBd"><div class="shortLine">'+ 
	                      faqs_list[i].answer + 
	                    '</div></div> '+
	                  '<div class="theboxFt theboxFtAction detail">'+ 
	                    '<div class="left ptss mll"> '+
	                      '<strong>Беше ли полезен този отговор?</strong> '+
	                      '<strong class="mlm"><input type="radio" name="question_'+faqs_list[i].faq_id+'" value="1" checked="checked" '+disabledAttr+'> Да</strong> '+
	                      '<strong class="mlm"><input type="radio" name="question_'+faqs_list[i].faq_id+'" value="0" '+disabledAttr+'> Не</strong> '+
	                    '</div> '+
	                    '<a class="buttonMtel mlm '+disabledClass+'" name="vote_'+faqs_list[i].faq_id+'"><span>Изпрати</span></a> '+
	                  '</div></div>'+
	                  '<b class="theboxBottom"><b class="theboxBl"></b><b class="theboxBr"></b></b>'+
	                  '</div></div>';
	                  
	    if(i != faqs_list.length-1) {
	    	faq_item += '<hr />';
	    }
	    
		faqs_list_div.append(faq_item);
	}
	
	
	//Executes the function when the DOM is ready to be used.
	// Document is ready
	TofslaFormsStart();
	
	
	
}

function _ajaxIncreaseCounter(faq_id)
{
	$.post('/faq/',
            {ajaxaction: 'increasefaqcounter',
             faq_id: faq_id
             },
            function(response) { 
            },
            'json');
}

/**
 * Checks if it has been already voted for a particular question and if not - calls the function
 * that perfoms the AJAX call for voting.
 **/
function rateFaq( faq_id, vote, isDoneVoting)
{
	if(isDoneVoting) return;
	_ajaxRateFaq(faq_id, vote);
}

/**
 * Perform the AJAX call for voting
 **/
function _ajaxRateFaq(faq_id, vote)
{
	$.post('/public/ratefaq',
            {faq_id: faq_id,
             vote: vote
             },
            function(response) {
                if(response.errorCode == 0) {
                	$('input[name="question_'+faq_id+'"]').attr("disabled","disabled");
                	$('a[name="vote_'+faq_id+'"]').addClass("tfDisabled");
                	TofslaFormsStart();
                	cms_dlg_open(response.response);
                	setTimeout("cms_dlg_close()",3000);
                } else {
                	cms_dlg_open(response.errorMessage);
                }
            },
            'json');
}
