﻿function ajaxLoader(obj,url,params) {   
    var obj=$(obj);

if (obj)  {     
   obj.html('<center><img src="'+DIR_STATIC_SKIN+'/images/loader.gif" /></center>');
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/'+url+'.php',
        params,
        function(result, errors) {  
       	if (!result) {
	            obj.html('');
        	}
            if (result.bStateError) {
        	    obj.html('');
            } else {            	
		    obj.html(result.sText);
            }                               
        },
        true
    );

}

}

function ajaxLoadPage(obj,url,params,id) {
    obj=$(obj);

if (obj)  {     
   obj.html('<center><img src="'+DIR_STATIC_SKIN+'/images/loader.gif" /></center>');
    if (url.indexOf('http://') == -1) {
	url = DIR_WEB_ROOT+url;
    }
   
    $.ajax({
        type: "GET",
        url: url,
	data: params,
        cache: false,
        async: true,
        dataType: "html",
        success: function(html) {
            if (id) {
		replaceAtab(id);
	    }
//	    obj.attr('innerHTML', html);
	    obj.html(html);

        }
    });
}

}

var oldatabid = null;
var defatabid = null;

function getAtabId() {
    var atabio = location.hash.indexOf('.');
    var atabio2 = location.hash.indexOf('.', atabio+1)-atabio-1
    if ((atabio > -1)&&(atabio2 > -1)) {
	return location.hash.substr(atabio+1, atabio2);
    } else {
        return false;
    }    
}

function checkAtab() {
    atabid = getAtabId();
    if (!atabid) { atabid = defatabid; if (!oldatabid) { oldatabid = defatabid; } }
    if (atabid && (atabid != oldatabid)) {
        atab = $('#'+atabid);
        if (atab) {
            atab.click();
            oldatabid = atabid;
        }
    }
}

function replaceAtab(newatabid) {
    atabid = getAtabId();
    if (atabid) {
        location.hash = location.hash.replace('.'+atabid+'.', '.'+newatabid+'.');
    } else {
        location.hash += '.'+newatabid+'.';
    }
    if (newatabid != oldatabid) {
        $('#'+oldatabid).removeClass('act');
    }
    oldatabid = newatabid;
}

function ajaxJoinLeaveBlog(obj,idBlog) {   
	obj=$(obj);
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/joinLeaveBlog.php',                       
        { idBlog: idBlog },
        function(result, errors) {  
        	if (!result) {
		show_program_mess('<b>Ошибка</b>:<br /><strong class=\'current_color\'>Повторите попытку чуть позже</strong>');
        	}
            if (result.bStateError) {
		show_program_mess('<b>'+result.sMsgTitle+'</b>:<br /><strong class=\'current_color\'>'+result.sMsg+'</strong>');
            } else {            	
		show_program_mess('<b>'+result.sMsgTitle+'</b>:<br /><strong class=\'current_color\'>'+result.sMsg+'</strong>');
            	if (obj)  {     
            		if (result.bState) {            			
				obj.html('<span>'+result.sLeaveBlog+'</span>');
            		} else {
				obj.html('<span>'+result.sJoinBlog+'</span>');
			}
            		divCount=$('#blog_user_count_'+idBlog);
            		if (divCount) {
            			divCount.text(result.iCountUser);
            		}
            	}
            }                               
        },
        true
    );
}


function ajaxBlogInfo(idBlog) { 	
	$.modal.close();
    $('<center><img src="'+DIR_STATIC_SKIN+'/images/ajax-loader.gif" /></center>').modal({close:false});
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/blogInfo.php',                       
        { idBlog: idBlog },
        function(result, errors) {  
		$.modal.close();
        	if (!result) {
		show_program_mess('<b>Ошибка</b>:<br /><strong class=\'current_color\'>Повторите попытку чуть позже</strong>');
        	}
            if (result.bStateError) {
		show_program_mess('<b>'+result.sMsgTitle+'</b>:<br /><strong class=\'current_color\'>'+result.sMsg+'</strong>');
            } else {            	
            	if ($('#block_blog_info')) {
            		$('#block_blog_info').html(result.sText);            		
            	}
		if ($('#block_blog_rubrics')) {
            		$('#block_blog_rubrics').html(result.sRubrics);
	$('.custom_select a').unbind('click');
	$('.custom_select li').unbind('click');
	customSelectInit();
	CSBfleXcroll('div_rubrics_select');
if (result.cRubrics > 0) {
	$('#span_blog_rubrics').css('display', 'block');
} else {
	$('#span_blog_rubrics').css('display', 'none');
}
		}
            }                               
        },
        true
    );
}

function ajaxRubricsEdit(idBlog, mode) {
	if ($('form#form_rubrics')) {
		var frm = $('form#form_rubrics').serialize();
	} else {
		var frm = '';
	}
	$.modal.close();
    $('<center><img src="'+DIR_STATIC_SKIN+'/images/ajax-loader.gif" /></center>').modal({close:false});
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/rubricsEdit.php',                       
        { mode: mode,
	  idBlog: idBlog,
	  form: frm },
        function(result, errors) {  
		$.modal.close();
        	if (!result) {
		show_program_mess('<b>Ошибка</b>:<br /><strong class=\'current_color\'>Повторите попытку чуть позже</strong>');
        	}
            if (result.bStateError) {
		show_program_mess('<b>'+result.sMsgTitle+'</b>:<br /><strong class=\'current_color\'>'+result.sMsg+'</strong>');
            } else {            	
            	if ($('#rubrics')) {
            		$('#rubrics').replaceWith(result.sText);            		
            	}
            }                               
        },
        true
    );
}

function CommentReply(where, smth)
 {
  var replyform = jQuery('#add-comment');

if (tinyMCE.getInstanceById('comment_text'))
{
    tinyMCE.execCommand('mceFocus', false, 'comment_text');                    
    tinyMCE.execCommand('mceRemoveControl', false, 'comment_text');
}
  replyform.insertAfter(where);
  tinyMCE.execCommand('mceAddControl', false, 'comment_text');
//  tinyInit();

  where.style.display = 'none';

  if (prev_to_show)
   prev_to_show.css('display', 'inline');

  prev_to_show = $(where);

  if (!smth)
   jQuery('#comment_text').focus();

  jQuery('#form_comment_reply').val(where.id);
  jQuery('#work_id').val('');

  return false;
 }

function CommentEdit(where, id) {
  var w = $(where);
  var htm = w.html();
//  htm = htm.replace(/<br>/gi, '');
  w.wrap('<form action="" method="POST" enctype="multipart/form-data">' +
	 '<input type="hidden" name="comment_id" value="' + id + '">' +
         '<div class="textareablock"><div class="indent">' + 
	 '<textarea id="textarea' + id +'" name="comment_text">' + htm + '</textarea></div>' +
         '             <div class="greyblock_lt"><!-- --></div>' +
         '             <div class="greyblock_rt"><!-- --></div>' +
         '             <div class="greyblock_lb"><!-- --></div>' +
         '             <div class="greyblock_rb"><!-- --></div>' +
         '         </div>' +
	 '<input type="submit" name="edit_comment" value="Отправить" class="button" /></form>');

  $('#textarea'+id).focus();
  tinyMCE.execCommand('mceAddControl', false, 'textarea'+id);
  tinyMCE.execCommand('mceFocus', false, 'textarea'+id);

}

function WorkEdit(title, where, cfiles, id) {
  var w = $(where);
  var htm = w.html();
//  htm = htm.replace(/<br>/gi, '');
  var titl = $(title).html();
  var fils = $(cfiles).val();
  w.wrap('<form action="" method="POST" enctype="multipart/form-data">' +
	 '<input type="hidden" name="comment_id" value="' + id + '">' +
	 '<div class="input"><input type="text" name="comment_title" value="' + titl + '" /><br /></div>' +
         '<div class="textareablock"><div class="indent">' + 
	 '<textarea id="textarea' + id +'" name="comment_text">' + htm + '</textarea></div>' +
         '             <div class="greyblock_lt"><!-- --></div>' +
         '             <div class="greyblock_rt"><!-- --></div>' +
         '             <div class="greyblock_lb"><!-- --></div>' +
         '             <div class="greyblock_rb"><!-- --></div>' +
         '         </div>' +
      	 '	<table cellpadding="0" cellspacing="0" border="0" id="work_files' + id + '">' +
	 '	' + fils +
         '      </table>' +
         '      <label>Прикрепить файл:</label>' +
	 '	<input type="file" class="text_input" onchange="addWorkFile(this, ' + "'#work_files" + id + "'" +');" style="width:100%;" /><br /><br />'+
	 '<input type="submit" name="edit_comment" value="Отправить" class="button" /></form>');

  $('#textarea'+id).focus();
  tinyMCE.execCommand('mceAddControl', false, 'textarea'+id);
  tinyMCE.execCommand('mceFocus', false, 'textarea'+id);
}

function ajaxFavouriteToggle(type,id,obj) {   
        typeFavourite = {                
		comment: {
                        url: DIR_WEB_ROOT+'/include/ajax/commentFavourite.php',
                        targetName: 'idComment'
		},
                topic: {
                        url: DIR_WEB_ROOT+'/include/ajax/topicFavourite.php',
                        targetName: 'idTopic'
                }
        };
                if (!typeFavourite[type]) {
                        return false;
                }

	obj = $(obj);

if (obj) {

        var params = new Array();
        params['type']=obj.hasClass('active') ? 0 : 1;
        params[typeFavourite[type].targetName]=id;

	JsHttpRequest.query(
    	typeFavourite[type].url,
	params,
        function(result, errors) {  
        	if (!result) {
		show_program_mess('<b>Ошибка</b>:<br /><strong class=\'current_color\'>Повторите попытку чуть позже</strong>');
        	}
            if (result.bStateError) {
		show_program_mess('<b>'+result.sMsgTitle+'</b>:<br /><strong class=\'current_color\'>'+result.sMsg+'</strong>');
            } else {            	
		show_program_mess('<b>'+result.sMsgTitle+'</b>:<br /><strong class=\'current_color\'>'+result.sMsg+'</strong>');

                obj.removeClass('active');
                if (result.bState) {
                	obj.addClass('active');
                }
            }                               
        },
        true
    );

}
}

function ajaxVote(type,id,value,obj) {

        typeVote = {
                topic_comment: {
                        url: DIR_WEB_ROOT+'/include/ajax/voteComment.php',
                        targetName: 'idComment'
                },
                topic: {
                        url: DIR_WEB_ROOT+'/include/ajax/voteTopic.php',
                        targetName: 'idTopic'
                },
                blog: {
                        url: DIR_WEB_ROOT+'/include/ajax/voteBlog.php',
                        targetName: 'idBlog'
                },
                user: {
                        url: DIR_WEB_ROOT+'/include/ajax/voteUser.php',
                        targetName: 'idUser'
                }
        };
                if (!typeVote[type]) {
                        return false;
                }

	obj = $(obj);

if (obj) {

        var params = new Array();
        params['value']=value;
        params[typeVote[type].targetName]=id;

	JsHttpRequest.query(
    	typeVote[type].url,
	params,
        function(result, errors) {  
        	if (!result) {
		show_program_mess('<b>Ошибка</b>:<br /><strong class=\'current_color\'>Повторите попытку чуть позже</strong>');
        	}
            if (result.bStateError) {
		show_program_mess('<b>'+result.sMsgTitle+'</b>:<br /><strong class=\'current_color\'>'+result.sMsg+'</strong>');
            } else {            	
		show_program_mess('<b>'+result.sMsgTitle+'</b>:<br /><strong class=\'current_color\'>'+result.sMsg+'</strong>');

		var upvote = '#upvote_'+type+id;
		var downvote = '#downvote_'+type+id;
		if ($(upvote)) {
			$(upvote).attr('src', DIR_STATIC_SKIN+'/images/ico/ico-vote-up_gray.png');
			$(upvote).parent().click(function() { return false; });
		}
		if ($(downvote)) {
			$(downvote).attr('src', DIR_STATIC_SKIN+'/images/ico/ico-vote-down_gray.png');
			$(downvote).parent().click(function() { return false; });
		}

                result.iRating=parseFloat(result.iRating);  
                if (result.iRating>0) {                        
                        obj.text('+'+result.iRating);
                }
                if (result.iRating<0) {                        
                        obj.text(result.iRating);
                }
                if (result.iRating==0) {
                        obj.text('0');
                }

            }                               
        },
        true
    );

}

}

function ajaxQuestionVote(idTopic,idAnswer) {	
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/questionVote.php',
        { idTopic: idTopic, idAnswer: idAnswer },
        function(result, errors) {  
        	if (!result) {
		show_program_mess('<b>Ошибка</b>:<br /><strong class=\'current_color\'>Повторите попытку чуть позже</strong>');
        	}
            if (result.bStateError) {
		show_program_mess('<b>'+result.sMsgTitle+'</b>:<br /><strong class=\'current_color\'>'+result.sMsg+'</strong>');
            } else {            	
		show_program_mess('<b>'+result.sMsgTitle+'</b>:<br /><strong class=\'current_color\'>'+result.sMsg+'</strong>');
            	if ($('#topic_question_area_'+idTopic)) {
       	    		$('#topic_question_area_'+idTopic).html(result.sText);
       		}  
            }                               
        },
        true
    );

}


function addWorkFile(elem, cont) {
	var real = $(elem);

        if (!cont) { cont = '#work_files'; }
	var container = $(cont);
	var cloned = real.clone(true);
	real.hide();
	cloned.insertAfter(real);
	
	real.attr('onchange', '');
	real.attr('name', 'work_file[]');
	real.css('display','none');

	var row = $('<tr><td style="padding: 0 20px 0 0;"><img src="' + DIR_STATIC_SKIN + '/images/ico/ico_results_1.png" width="27" height="19" alt="" style="position: relative;left: 14px;" /> <a style="font-size: 11px">'+elem.value+'</a></td><td style="padding: 0;"><a href="javascript:;" onclick="deleteWorkFile(this);" class="grey result_del">удалить</a><br /></td></tr>');
	real.appendTo(row);
	row.appendTo(container);
	cloned.value = '';

}

function deleteWorkFile(elem) {
	$(elem).parent().parent().remove();
}

function tglSpan(elem1, elem2) {
	$(elem1).slideUp();
	$(elem2).slideDown();
}


// для тестов
function getTestScalesCount() {
	return jQuery('tr.test_scale').length;
}

function getTestQuestionsCount() {
	return jQuery('tr.test_question').length;
}

function getTestAnswersCount(question_id) {
	return jQuery('#'+question_id).find('tr.test_answer').length;
}

function getNumericId(type, tid) {
	return parseInt(tid.replace(type, ''));
}

function getTestItemNextId(type) {
	max = 0;
	jQuery('tr.test_'+type).each(function() {		
		id = getNumericId(type, this.id);
		if (max < id) {
			max = id;
		}
	});
	++max;
	id = type + max.toString();
	return id;
}

function getTestItemByChild(btn) {
        tr = btn;
        while (tr.tagName != 'TR') tr = tr.parentNode;
	return tr;
}

function fixAnswer(newTr, passive_add) {

if (passive_add) {
	newTr.id = getTestItemNextId('answer');
	id = getNumericId('answer', newTr.id).toString();
} else {
	id = getNumericId('answer', newTr.id).toString();
}

		jQuery(newTr).find('input.answer_id').eq(0).val(id);
		tr = getTestItemByChild(jQuery(newTr).parent().get(0));
		q_id = getNumericId('question', tr.id);
		jQuery(newTr).find('input.answer_id').eq(0).attr('name', 'answers['+q_id+'][id][]');
		jQuery(newTr).find('input.answer_title').eq(0).attr('name', 'answers['+q_id+'][title]['+id+']');
		jQuery(newTr).find('input.answer_is_right').eq(0).attr('name', 'answers['+q_id+'][is_right]['+id+']');
		jQuery(newTr).find('textarea.answer_comment').eq(0).attr('name', 'answers['+q_id+'][comment]['+id+']');
		jQuery(newTr).find('input.answer_mark').each(function() {
			jQuery(this).attr('name', 'marks['+id.toString()+']['+jQuery(this).attr('rel')+']');
		});
	
}

function addTestItem(type, btn){
editorDestroy();
	tr = getTestItemByChild(btn);
	// Создаем новый объект
        var newTr = tr.parentNode.insertBefore(tr.cloneNode(true),tr.nextSibling);
editorInit();
	newTr.id = getTestItemNextId(type);

	if (type == 'scale') {
		jQuery(newTr).find('input.scale_id').eq(0).val(getNumericId('scale', newTr.id).toString());
		jQuery(newTr).find('input.scale_title').eq(0).attr('name', 'scales[title]['+getNumericId('scale', newTr.id)+']');
		jQuery(newTr).find('textarea.scale_text').eq(0).attr('name', 'scales[text]['+getNumericId('scale', newTr.id)+']');
		drawAllScalesBoxes();
	} else if (type == 'question') {
		jQuery(newTr).find('input.question_id').eq(0).val(getNumericId('question', newTr.id).toString());
		jQuery(newTr).find('input.question_title').eq(0).attr('name', 'questions[title]['+getNumericId('question', newTr.id)+']');
		jQuery(newTr).find('select.question_qty_answers').eq(0).attr('name', 'questions[qty_answers]['+getNumericId('question', newTr.id)+']');
		jQuery(newTr).find('textarea.question_text').eq(0).attr('name', 'questions[text]['+getNumericId('question', newTr.id)+']');

		jQuery(newTr).find('tr.test_answer').each(function() {
			fixAnswer(this, true);
		});

	} else if (type == 'answer') {
		fixAnswer(newTr);
	}
	if (type == 'answer') {
		tr = getTestItemByChild(jQuery(newTr).parent().get(0));
		checkForLast(type, tr.id);
	} else {
	        checkForLast(type);
	}
}
function checkForLast(type, question_id){
	if (type == 'answer') {
		anws = jQuery('#'+question_id).find('tr.test_answer');
		anws.find('input[name=drop_'+type+']').each(function() {
			this.disabled = false;
		});
		if (anws.length<=1) {
			anws.find('input[name=drop_'+type+']').get(0).disabled = true;
		}
		
	} else {
	        btns = document.getElementsByName('drop_'+type);
        	for (i = 0; i < btns.length; i++){
	        	btns[i].disabled = false;            
        	}
	        if (btns.length<=1) {
        		btns[0].disabled = true;
	        }
	}
}

function dropTestItem(type, btn){	
	tr = getTestItemByChild(btn);
	parnt = tr.parentNode;
        parnt.removeChild(tr);

	// Если удалил шкалу, то обновляем шкалы по всем ответам
	if (type == 'scale') {
		drawAllScalesBoxes();
	}

	if (type == 'answer') {
		tr = getTestItemByChild(parnt);
		checkForLast(type, tr.id);
	} else {
	        checkForLast(type);
	}
}

function moveUpTestItem(btn) {
	tr = getTestItemByChild(btn);
	prev = jQuery(tr).prev();
	if (prev) {
		jQuery(tr).insertBefore(prev);
	}
}

function moveDownTestItem(btn) {
	tr = getTestItemByChild(btn);
	next = jQuery(tr).next();
	if (next) {
		jQuery(tr).insertAfter(next);
	}
}

function drawScalesBox(tr) {
	var values = new Array();
	jQuery(tr).find('.test_scalesbox').find('tr').each(function() {
		value = jQuery(this).find('input').get(0).value;
		values[jQuery(this).attr('rel')] = value;
	});

	html = '<table>';
	answer_id = getNumericId('answer', tr.id);
	jQuery('input.scale_title').each(function(index) { 
		scale = getTestItemByChild(this);
		scale_id = getNumericId('scale', scale.id);
		value = values[scale.id] ? values[scale.id] : 0;
		html += '<tr class="test_answer_scale" rel="' + scale.id + '"><td>' + this.value + '</td><td><input class="answer_mark" rel="'+scale_id+'" type="text" name="marks['+answer_id.toString()+']['+scale_id.toString()+']" value="'+value.toString()+'" size="3" /></td></tr>';
	});
	html += '</table>';
	jQuery(tr).find('.test_scalesbox').get(0).innerHTML = html;
}

function drawAllScalesBoxes() {
		jQuery('tr.test_answer').each(function() {
			drawScalesBox(this);
		});
}

