/*mainInitFunction = function(){
	$('a[rel=fancy]').fancybox({frameWidth:500, frameHeight:500});
}
$(document).ready(mainInitFunction);*/

function defPosition(event) {
	var x = y = 0;
    if (document.attachEvent != null) { // Internet Explorer & Opera
        x = window.event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
        y = window.event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    } else if (!document.attachEvent && document.addEventListener) { // Gecko
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    } else {
        // Do nothing
    }
    return {x:x, y:y};
}
var myMouseCoord = {x:0,y:0};/*
document.onmousemove = function(event) {
    var event = event || window.event;
    myMouseCoord = defPosition(event);
    $('#ajaxLoader').css ( 'left', myMouseCoord.x+10 );
	$('#ajaxLoader').css ( 'top', myMouseCoord.y+10 );
}*/

function ajaxLoadModule ( form, container ) {
	var options = {
		action: form.action,
		method: 'post',
		beforeSubmit: function(formArray, jqForm) {
			formArray[formArray.length] = { name: 'ts_mode', value: 'public' };
			return true;
		},
		success: function(data) {
			$('#'+container).html(data);
		}
	};
	$(form).ajaxSubmit(options);
	return false;
}

function inflectWord(cnt, data){
	if(data.length<1) return "";
	if (data.length < 2) data[1] = data[0];
	if (data.length < 3) data[2] = data[1];
	var ret = data[1];
	if (cnt<1 || (cnt>=10 && cnt<=20) || cnt%10==0 || (cnt%10>4 && cnt%10<=9)){
		ret = data[2];
	}else{
		if (cnt%10 == 1){ret = data[0];}
	}
	return ret;
	
}

var symbolWords=new Array('', 'а', 'ов')
function changeTextAreaCounterCounter(cnt, tc){
	var l = 1000-(cnt.length)/1;
	var lw = inflectWord(l, symbolWords);
	var t = (l > 0) ? 'Осталось '+l+' символ'+lw : 'Описание больше допустимого размера';
	$('#'+tc).html(t);
}
function initTextAreaCounter(ta, tc){
	changeTextAreaCounterCounter($('#'+ta).val(), tc)
	$('#'+ta).change(function(){changeTextAreaCounterCounter($(this).val(), tc)});
	$('#'+ta).keyup(function(){changeTextAreaCounterCounter($(this).val(), tc)});
	$('#gameForm').submit(function(){
		if ($('#'+ta).val().length/1 > 1000){
			alert("Описание больше допустимого размера!\nМаксимальное количество - 1000 символов.");
			$('#'+ta).focus();
			return false;
		}
		return true;
	})
}


/*msgSnd*/
var msgModalData={uid:0,un:"",a:""};
var msgModalFormOptions = {
	beforeSubmit: function(){
		if($.trim($("#basicModalContent_message").val()) == ""){
			alert("Введите текст сообщения!");
			$("#basicModalContent_message").focus();
			return false;
		}
		var h = $("#basicModalContent_form").height();
		$("#basicModalContent_form2").height(h).css("marginTop", "-"+h+"px").html("Отправка сообщения").show();
		$("#basicModalContent_form").css("visibility","hidden");
	},
    success: function(responseText) {
		var t=$(responseText).find(".error p:eq(0)");
		var c=t.css("color");
		
		if (c=="#ff0000" || c=="ff0000" || c=="red") {
			$(".error", $("#basicModalContent")).html(t.parent().html()).show();
		}else{
			$("#basicModalContent_form").html("<p>Ваше сообщение отправлено успешно</p>");
			var dlt = $("#modalContainer").css("marginLeft").replace("px","")/1+105+"px";
			$("#modalContainer").css("marginLeft", dlt).width(250);
		}
		$("#basicModalContent_form2").hide();
		$("#basicModalContent_form").css("visibility","visible");
	}
};

var relModalFormOptions = {
	beforeSubmit: function(){
		if($.trim($("#basicModalContent_rel_message").val()) == ""){
			alert("Введите текст сообщения!");
			$("#basicModalContent_rel_message").focus();
			return false;
		}
		var h = $("#basicModalContent_rel_form").height();
		$("#basicModalContent_rel_form2").height(h).css("marginTop", "-"+h+"px").html("Отправка сообщения").show();
		$("#basicModalContent_rel_form").css("visibility","hidden");
	},
    success: function(responseText) {
		var t=$(responseText).find(".error p:eq(0)");
		var c=t.css("color");
		
		if (c=="#ff0000" || c=="ff0000" || c=="red") {
			$(".error", $("#basicModalContent_rel")).html(t.parent().html()).show();
		}else{
			$("#basicModalContent_rel_form").html("<p>Ваше предложение отправлено успешно</p>");
			var dlt = $("#modalContainer").css("marginLeft").replace("px","")/1+105+"px";
			$("#modalContainer").css("marginLeft", dlt).width(250);
		}
		$("#basicModalContent_rel_form2").hide();
		$("#basicModalContent_rel_form").css("visibility","visible");
	}
};

$(function () {
	$('span.msgModal').css("cursor", "pointer");
	$('a.msgModal, span.msgModal').click(function (e) {
		e.preventDefault();
		msgModalData.uid = $(this).prev().children('span.id:eq(0)').html();
		msgModalData.un = $(this).prev().children('span.login:eq(0)').html();
		msgModalData.a = $(this).attr("href");
		$('#basicModalContent').modal();
	});
	$('span.relModal').css("cursor", "pointer");
	$('a.relModal, span.relModal').click(function (e) {
		e.preventDefault();
		$('#basicModalContent_rel_to').val($(this).prev().children('span.id:eq(0)').html());
		$('#basicModalContent_rel_name').html($(this).prev().children('span.login:eq(0)').html());		
		$('#basicModalContent_rel').modal();
	});
	
	$('a.registerModal').click(function (e) {
        //added - переопределен стандартный id дива на modalContainerRegister,
        //для изменения стиля только окна регистрации
        options = {
     		overlay: 50,
     		overlayId: 'modalOverlay',
     		overlayCss: {},
     		containerId: 'modalContainerRegister',
     		containerCss: {},
     		close: true,
     		closeTitle: 'Close',
     		closeClass: 'modalClose',
     		persist: false,
     		onOpen: null,
     		onShow: null,
     		onClose: null
	    };
        //**************************
        
		$('#registerModalContent')
			.find('#register_form').attr('action','auth/register').end()
			.modal(options);
		$("#register_form img.capchaImg").click();
		return false;
	});
});

/*modal Wins for Actions*/
function showModalActions(el,mode){
	if(mode=='deleteMsg'){
		txt='Вы действительно хотите удалить данное сообщение?';
	}
	else{
		var q_id = parseInt(el.parent().find('.edit_quest_id:eq(0)').text());
		var q_name = el.parent().find('.edit_quest_name:eq(0)').html();
		var txt = 'Вы правда хотите удалить квест “'+q_name+'”?';
		if(mode=='moderate'){txt='Отправить квест “'+q_name+'” на проверку модераторам?';}
		if(mode=='approve'){txt='Подтвердите публикацию квеста “'+q_name+'”?';}
		if(mode=='recomend'){txt='Подтвердите публикацию в виде рекомендованного квеста “'+q_name+'”?';}
		if(mode=='unrecomend'){txt='Подтвердите исключение из рекомендованных квеста “'+q_name+'”?';}
		if(mode=='resolution'){txt='Вернуть квест “'+q_name+'” на доработку?';}
	}
	
	if(mode=='resolution'){$('#actionModalContent .response_txt').show()}
	else{$('#actionModalContent .response_txt').hide()}
	
	$('#actionModalContent h1:eq(0)').html(txt);
	$('#actionModal_form').attr('action', el.attr('href'));
	$('#actionModal_mode').attr('name', mode).val(q_id);
	$('#actionModalContent').modal({close:false});
}
function generateModalActions(){
	$('.my_quests .modalAction_delMsg').click(function(){
		showModalActions($(this),'deleteMsg');
		return false;
	});
	$('.my_quests .modalAction_del').click(function(){
		showModalActions($(this),'delete');
		return false;
	});
	$('.my_quests .modalAction_moder').click(function(){
		showModalActions($(this),'moderate');
		return false;
	});
	$('.my_quests .modalAction_approve').click(function(){
		showModalActions($(this),'approve');
		return false;
	});
	$('.my_quests .modalAction_recomend').click(function(){
		showModalActions($(this),'recomend');
		return false;
	});
	$('.my_quests .modalAction_unrecomend').click(function(){
		showModalActions($(this),'unrecomend');
		return false;
	});
	$('.my_quests .modalAction_resolution').click(function(){
		showModalActions($(this),'resolution');
		return false;
	});
}

function generateBlockDiv(name, el){
	var fid="blockeDiv_"+name;
	var div=$("#"+fid);
	if(div.attr('class')==undefined){
		div = $("<div class='blockeDiv' id='"+fid+"'></div>");
		var pos=$(el).position();
		
		var top=pos.top;
		var h=$(el).height();
		if (h == 1) //ie6 fix
		{
			var posTmp1=$(el).find("img:first").position();
			var posTmp2=$(el).find("div.clear:last").position();
			h=posTmp2.top-posTmp1.top;
			top=posTmp1.top-10;
		}
		div.css({
			opacity:'0.85',top:top, left:pos.left, width:$(el).width(), height:h,
			marginTop:$(el).css('marginTop')
		});
		$('body').append(div);
		return true;
	}else{
		return false;
	}
}
function hideBlockDiv(name){
	var fid="blockeDiv_"+name;
	$("#"+fid).remove();
}

/* comments */
function commentAdd(form, com_id){
	if (com_id == undefined) com_id = 0;
	var txt = $.trim($(form).find("textarea").val());
	//var item_id = $.trim($(form).find("input[name=item_id]").val());
	if(txt == ""){
		alert("Комментарий не может быть пустым!");
		$(form).find("textarea").val('').focus();
		return false;
	}
	var options = {
		action: $(form).attr('action'),
		method: 'post',
		beforeSubmit: function(formArray, jqForm) {
			//formArray[formArray.length] = { name: 'ts_mode', value: 'public' };
			if (com_id == 0){
				generateBlockDiv('commentEdit0', $("#addQuestComment"));
			}else{
				generateBlockDiv('commentEdit'+com_id, $("#comment_"+com_id));
			}
			return true;
		},
		success: function(data){
			var txt1 = $(data).find('.my_quests:eq(0)').html();
			var txt2 = $(data).find('.comments_head:eq(0)').html();
			var txt3 = $(data).find('ul.pagination:eq(0)').html();
			$('.my_quests:eq(0)').html(txt1);
			$('.comments_head:eq(0)').html(txt2);
			$('ul.pagination:eq(0)').remove();
			if (txt3 != null){
				$('.my_quests:eq(0)').after("<ul class='pagination'>"+txt3+"</ul>");
			}
			hideBlockDiv('commentEdit'+com_id);
		}
	};
	$(form).ajaxSubmit(options);
}
function deleteComment(l,id){
	generateBlockDiv('commentDelete'+id, $("#comment_"+id));
	$.getJSON($(l).attr('link'), function(data){
		if(data && typeof(data) == 'object' && data.error == 0){
			hideBlockDiv('commentDelete'+id);
			$("#comment_"+id).after(data.text).hide();
		}
	});
}
function restoreComment(el, id){
	var url = window.location.pathname+"?action=restore&id="+id;
	$.getJSON(url, function(data){
		if(data && typeof(data) == 'object' && data.error == 0){
			var div = $(el).parent().remove();
			$("#comment_"+id).show();
		}
	});
}
function prepareCT(txt){
	/* fuck it ie */
	$nl = ($.browser.msie) ? "<BR>" : "\n";
	$nl2 = ($.browser.msie) ? String.fromCharCode('13') : "";
	$tab = ($.browser.msie) ? "<SPAN class=hr>hr</SPAN>" : "\t";
	//$tab = String.fromCharCode('9');
	txt = $('<div class="qqqwwweee">'+txt+'</div>');
	var deep = "";
	var deepCnt = Math.min(txt.find('div.reply').length, 6);
	for (var i=0;i<deepCnt;i++){
		rly = txt.find('div.reply:eq(0)')
		com_id = $.trim(rly.attr('class').replace('reply', '')).substr(3);
		rly.before('[reply to="'+com_id+'" author="'+rly.attr('title')+'"]'+$nl+$tab+deep+rly.html()+$nl+deep+'[/reply] '+$nl+deep);
		deep+=$tab;
	}
	txt.find('div').remove();
	txt = $.trim(txt.html());
	txt = txt.replace(/<br>/ig, $nl2);
	txt = txt.replace(/<SPAN class=hr>hr<\/SPAN>/ig, "     ");
	return txt;
}
function editComment(l,id){
	//comment_id
	var url = window.location;
	var tmp = $("#comment_"+id+" div.comment_content:eq(0)");
	var html = '<div class="commentEdit"><form action="'+url+'" onsubmit="commentAdd(this, '+id+');return false" method="POST">'+$("#addQuestComment form div").html()+'</form></div>';
	html = $(html);
	html
		.find("input:eq(3)").val(id).end()
		.find("input:eq(4)").val("Изменить").after('<input class="button6" value="Отмена" type="button" onclick="cancelCommentEdit('+id+')">').end()
		.find("textarea:eq(0)").val(prepareCT(tmp.html()));
	
	tmp.before(html).hide().next().hide().next().hide();
}
function cancelCommentEdit(id){
	$("#comment_"+id+" div.commentEdit:eq(0)").next().show().next().show().next().show().end().end().end().remove();
}
function answerComemnt(id){
	var d=$("#comment_"+id);
	txt = '<div class="reply com'+id+'" title="'+d.find("span.user:eq(0)").text()+'">'+d.find("div.comment_content:eq(0)").html()+'</div>';
	$("#addQuestComment textarea:eq(0)").val(prepareCT(txt)+"\n");
	var t = $("#addQuestComment textarea");t=t[0];
	setSelectionRange(t, t.value.length, t.value.length);
//	t.setSelectionRange(t.value.length, t.value.length);
//	$("#addQuestComment textarea:eq(0)").focus()
}

function setSelectionRange(input, selectionStart, selectionEnd){
	if (input.setSelectionRange) {
		input.setSelectionRange(selectionStart, selectionEnd);
		input.focus();
	}else if (input.createTextRange) {
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	}
}
/**************************************************************************************/
/* 													 								  */
/* 								КОНФИГУРАТОР В HTML 								  */
/* 																					  */
/**************************************************************************************/

/***********	Работа с точкой      **********/
var hastobe_saved = false;
var hastobe_reloaded = false;
//Функция по загрузке формы редактирования элемента
function loadPoint (quest, id) {
	saveQuest(quest, function () {
		getPoint (quest, id);
		hastobe_saved = false;
	});
}

//Функция по загрузке формы редактирования элемента
function getPoint (quest, id) { 
	//1) подгружаем поля
	showPreloader();
	$("div.editor_popup[rel=edit]").load('/game/edit_new/point/'+quest+'?id='+id+'&ts_mode=public',function() { 
		refresh_selects();
		hidePreloader();
		//2) Показываем все
		$("div.editor_popup[rel=edit]").dialog({ modal: true, width: 649, beforeClose: 
				function(event, ui){ 
					if (confirm("Вы не сохранили изменения, Вы уверены что хотите выйти?")) {
						if (hastobe_reloaded) {
							reloadMain(quest);
							hastobe_reloaded = false;
						}
						return true;
					} else {
						return false;
					}
				} 
		});
	});
}

//Сохранение точки
function savePoint(quest) {
	setPoint (quest);
}

//Сохранение точки
function setPoint(quest) {
	$("div.editor_popup[rel=edit]").dialog('option','beforeClose',function(){});
	$("div.editor_popup[rel=edit]").dialog('close');
	showPresaver();
	$.ajax({
	  type: 'POST',
	  url: '/game/edit_new/point/'+quest,
	  data: {POINT: $("#edit_form").serialize()},
	  success: function(data) {
		$("div.editor_popup[rel=saving]").hide();
		hidePresaver();
		reloadMain(quest);
	  }
	});
}

//Добавление точки
function addPoint(type,quest,x,y) {
	saveQuest(quest, function() {
		showPresaver();
		$.ajax({
		  type: 'POST',
		  url: '/game/edit_new/point/'+quest,
		  data: {POINT_NEW: type, x: x, y: y},
		  success: function(data) {
			$("div.editor_popup[rel=saving]").hide();
			hidePresaver();
			reloadMain(quest);
		  }
		});
	});
}

//Новая точка
function newPoint(type,quest) {
	$('#editor_popup_choose').dialog('close');	
	showPresaver();	
	$.ajax({
	  type: 'POST',
	  url: '/game/edit_new/point/'+quest,
	  data: {POINT_NEW: type,parent: $("#edit_form input[name=id]").val()},
	  success: function(data) {
		var obj = data.split(',');
		$('select.link_select option[value=new]').after('<option value="new2">new</option>');
		$('select.link_select option[value=new]').val(obj[0]);
		$('select.link_select option[value='+obj[0]+']').html(obj[1]);
		$('select.link_select option[value=new2]').val('new');
		refresh_selects();
		hidePresaver();
		hastobe_reloaded = true;
	  }
	});
}

//перезагрузка точки
function reloadPoint(id,quest) {
showPreloader();
var attr = $('#autosave').attr('checked');
if (typeof attr !== 'undefined' && attr !== false) attr = 1; else attr = 0;
$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/'+quest,
	  data: {mode: 'editor',ts_mode: 'public', autosave: attr},
	  success: function(data) {
		$("#constructor").html(data);
		loadGraphics();
		//1) подгружаем поля
		$("div.editor_popup[rel=edit]").load('/game/edit_new/point/'+quest+'?id='+id+'&ts_mode=public',function() { refresh_selects();});
		hidePreloader();
		//2) Показываем все
		$("div.editor_popup[rel=edit]").dialog({ modal: true, width: 649, beforeClose: 
			function(event, ui){ 
				if (confirm("Вы не сохранили изменения, Вы уверены что хотите выйти?")) {
					return true;
				} else {
					return false;
				}
			} 
		});
	  }
	});
}

//функция, возвращает очередное условие для точки
function getStepLine(condition, text) {
	var res = '';
	res += '<div class="step_line">';
	res += '<input type="text" class="text" value="'+text+'" name="links[n'+condition+'][name]">';
	res += '<select name="links[n'+condition+'][to]" class="link_select" onchange="update_link_selects(this);">';
	res += $('#to_be_cloned').html();
	res += '</select>';
	res += '<a href="#" onclick="$(this).parent().remove(); return false;"><img src="/skins/default/images/delete_step_line.jpg" width="11" height="11" alt="x"></a>';
	res += '</div>';
	return res;
}

//небольшая такая функция
function removeCondition(condition,el) {	
	$(el).parent().after('<input type="hidden" value="'+condition+'" class="remove_condition" />');
	$(el).parent().remove();
	return true;
}

//Функция по добавлению еще одного условия
function addStepLine() {
	max_condition++;
	$("#add_step_line").before(getStepLine(max_condition,''));
	refresh_selects();
}

//функция по загрузке формы с редактирование области видимости счетчиков
function loadCountersVisibleForm(e, quest) {
	var value = $(e).parent().parent().find('input.cvisible').val();
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/point/cvisible/'+quest,
	  data: {ts_mode: 'public', value: value},
	  success: function(data) {
		$('#counters_visible').html(data);
		$('#counters_visible').dialog({ modal: true, width: 400, beforeClose:
		function(event, ui){
			if ($('#counters_visible input[name=to_be_saved]').val()==1) {
				var val = '';
				$('#counters_visible input').each(function(){
					var attr = $(this).attr('checked');
					if (typeof attr !== 'undefined' && attr !== false) {
						if (val=='') val += $(this).val();
						else 		 val += ","+$(this).val();
					}
				});
				$(e).parent().parent().find('input.cvisible').val(val);
			}
		}
	});
	  }
	});
}

/***********    Работа с условием      **********/   
 var max_ifcond = 0;
//функция по смене типа реакции
function changeStepAction(e,quest,point,action) {
	var val = $(e).val();
	var header = e;
	var i=0;
	while (!$(header).hasClass('step-header') && i<10) {
		header = $(header).parent();
	}
	var name = $(header).find('div.title input').val();
	var visible = $(header).find('input.visible').val();
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/point/action/'+quest,
	  data: {point: point,ts_mode: 'public',action: action, new_type: val, name: name, visible: visible},
	  success: function(data) {
		var el = $(e).parent();
		var limit = 0;
		while (!$(el).hasClass('step') && limit<10) {
			limit++;
			el = $(el).parent();
		}
		$(el).replaceWith(data);		
	  }
	});	
}

//Функция по добавлению условия в точку условия (вот такая тофталогия =))
function loadIfStep(quest, point, cond) {
	max_ifcond++;
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/point/action/'+quest,
	  data: {point: point,ts_mode: 'public',action: cond},
	  success: function(data) {
		$('#insert_action_'+cond).before(data);		
	  }
	});
}

//Функция по добавлению условия в точку условия (вот такая тофталогия =))
function addIfStep(quest, point) {
	max_ifcond++;
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/point/action/'+quest,
	  data: {point: point,ts_mode: 'public',action: 'n'+max_ifcond},
	  success: function(data) {
		$('.form_add_step').before(data);
	  }
	});
}

//функция по смене типа дейсвтия
function changeActionType(e) {
	var val = $(e).val();
	$(e).parent().find('.typeT').hide();
	$(e).parent().find('.typeC').hide();
	$(e).parent().find('.typeM').hide();
	$(e).parent().find('.type'+val).show();
	if ($(e).parent().parent().parent().parent().hasClass('timer-variants')) {
		if (val=='C') {
			$(e).parent().addClass('bg1-block');
			$(e).parent().removeClass('tv-bg1');
			$(e).parent().css('width',221);
		} else {
			$(e).parent().removeClass('bg1-block');
			$(e).parent().addClass('tv-bg1');
			$(e).parent().css('width',240);
		}
	}
}
   
//функция по загрузке окна редактирования сообщения
function loadMessageForm(e) {
	$('#message_text').val($(e).parent().find('textarea').val());
	$("#editor_popup_edit_message").dialog({ modal: true, width: 400, dialogClass: 'modal', beforeClose:
		function(event, ui){			
			$(e).parent().find('textarea').val($('#message_text').val());			
			if($('#message_text').val()=="") $(e).css('background-color','#FF0000');
			else $(e).css('background-color','#10ae00');
		}
	});
	$('.modal .ui-dialog-titlebar').hide();
}

//функция по загрузке формы с редактирование области видимости ссылки
function loadVisibleForm(e, quest) {
	var value = $(e).parent().find('input.visible').val();
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/point/visible/'+quest,
	  data: {ts_mode: 'public',value: value},
	  success: function(data) {
		$('#point_visible').html(data);
		$('#point_visible').dialog({ modal: true, width: 600, beforeClose:
		function(event, ui){
			if ($('#point_visible input[name=to_be_saved]').val()==1) {
				$.ajax({
				  type: 'POST',
				  url: '/game/edit_new/point/visible/'+quest,
				  data: {ts_mode: 'public',data: $('#condition_visible_form').serialize()},
				  success: function(data) {
					$(e).parent().find('input.visible').val(data);
					if (data=='') $(e).css('background-color','#37A3E3');
					else $(e).css('background-color','#ff8a00');
				  }
				});
			}
		}
		});	  
	}
	});
}

var max_visible_counters = 0;
/* Функция по добавлению новой строчки для счетчика */
function addCounterVisible(e, quest) {
	max_visible_counters++;
	var res = '';
	res += '<div class="bg1-block">';
	res += '<div class="icon-delete" onclick="$(this).parent().remove(); return false;"></div>';
	res += '<select name="counters[n'+max_visible_counters+'][id]">';
	res += $('#cvisible_counters_to_be_cloned').html();
	res += '</select>';
	res += '<p><a href="javascript: void(0);" onclick="addCounterVisibleLine(this,'+quest+','+"'n"+max_visible_counters+"'"+')">Добавить проверку</a></p>';
	res += '</div>';	
	$(e).parent().before(res);
}

var max_visible_counters_line = 0;
/* Функция по добавлению новой строчки для счетчика */
function addCounterVisibleLine(e, quest, counter) {
	max_visible_counters_line++;
	var res = '';
	res += '<div class="tv-left">';
	res += '<div class="icon-delete" onclick="$(this).parent().remove(); return false;"></div>';
	res += '<select style="width:95px;" name="counters['+counter+'][rules][n'+max_visible_counters_line+'][con]" onchange="if($(this).val()==\'d\') $(this).parent().find(\'.diap\').show(); else $(this).parent().find(\'.diap\').hide();">';
	res += '<option value="=">Равно</option>';
	res += '<option value="<">Меньше</option>';
	res += '<option value=">">Больше</option>';
	res += '<option value="d">Диапазон</option>';
	res += '</select>';
	res += '<input type="text" style="width:50px;" name="counters['+counter+'][rules][n'+max_visible_counters_line+'][value]">';
	res += '<span class="diap" style="display: none;">&mdash;</span><input type="text" style="width:50px;display: none;" name="counters['+counter+'][rules][n'+max_visible_counters_line+'][value2]" class="diap">';
	res += '</div>';	
	$(e).parent().before(res);
}

//функция по загрузке формы с редактирование области видимости ссылки
function loadCountersForm(e, quest) {
	var value = $(e).parent().find('input.counters').eq(0).val();
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/point/ifcounters/'+quest,
	  data: {ts_mode: 'public', value: value},
	  success: function(data) {
		$('#point_counters').html(data);
		$('#point_counters').dialog({ modal: true, width: 400, beforeClose:
		function(event, ui){
			$.ajax({
			  type: 'POST',
			  url: '/game/edit_new/point/ifcounters/'+quest,
			  data: {ts_mode: 'public', value: $('#point_counters form').serialize(), mode: 'save'},
			  success: function(data) {			
				$(e).parent().find('input.counters').val(data);
				if (data=='') $(e).css('background-color','#37A3E3');
				else $(e).css('background-color','#ff8a00');
			  }
			});
		}
	});
	  }
	});
}

var max_counters = 0;
//функция по добавлению учета счетчика
function addActionCountersLine(e) {
	max_counters++;
	var res = '';
	res += '<div class="timers">';	
	res += '<select name="items[n'+max_counters+'][counter]">';
	res += $('#counters_to_be_cloned').html();
	res += '</select>&nbsp;&nbsp;&nbsp;';
	res += '<select name="items[n'+max_counters+'][operation]">';
	res += '<option value="a">Прибавить</option><option value="s">Вычесть</option><option value="e">Присвоить</option></select>&nbsp;&nbsp;&nbsp;';
	res += '<input type="text" class="text" value="" name="items[n'+max_counters+'][value]" style="width: 60px;">';	
	res += '<div class="icon-delete" onclick="$(this).parent().remove(); return false;"></div>';
	res += '</div>';
	$(e).parent().before(res);
}

var max_random = 0;
//функция по добавлению варианта для случайного условия
function addRandomVariant(e,quest,link) {
	max_random++;
	var res='';
	res += '<div class="step-params" style="width: 85%;">';
	res += '<div class="icon-delete" onclick="$(this).parent().remove();"></div>';
	res += '<input type="hidden" name="action['+link+'][n'+max_random+'][id]" value="">';
	res += '<input type="hidden" name="action['+link+'][n'+max_random+'][counters]" value="" class="counters">';
	res += '<div class="step-icon2 typeT" style="background-color:#37A3E3; display: none;" onclick="loadCountersForm(this,'+quest+');"></div>';
	res += '<span class="input-percent"><input type="text" name="action['+link+'][n'+max_random+'][percent]" value=""> %</span>';
	res += '&nbsp;<select name="action['+link+'][n'+max_random+'][type]" class="action_type" onchange="changeActionType(this);">';
	res += '<option value="M">Переход</option>';
	res += '<option value="T">Сообщение</option>';
	res += '</select>&nbsp;';
	res += '<select name="action['+link+'][n'+max_random+'][id_point]"  onchange="createNewPoint(this)" class="typeM point_selector">';
	res += $('#events_to_be_cloned').html();
	res += '</select>';
	res += '<img class="step-icon5 typeT" src="/skins/default/images/constr_icon5.png" style="background-color: #ff0000; display: none;" onclick="loadMessageForm(this);">';
	res += '<textarea name="action['+link+'][n'+max_random+'][message]" style="display: none;"></textarea>';
	res += '<label style="margin-top:8px; display: none;" class="typeT">';
	res += '<input value="1" name="action['+link+'][n'+max_random+'][hide]" type="checkbox"> - после действия скрыть шаг</label>';
	res += '<div class="step-icon2 typeM" style="background-color: #37A3E3;" onclick="loadCountersForm(this,'+quest+');"></div>';
	res += '</div>';
	
	$(e).parent().before(res);
	
	return res;
}

var max_variant = 0;
//функция по добавлению варианта для условия таймера
function addCounterVariant(quest,link) {
	max_variant++;			
	var res='';
	res += '<div class="variant">';	
	res += '<input type="hidden" name="action['+link+'][n'+max_variant+'][id]" value="">';
	res += '<input type="hidden" name="action['+link+'][n'+max_variant+'][counters]" value="" class="counters">';
	res += '<div class="tv-left">';
	res += '<select style="width:95px;" name="action['+link+'][n'+max_variant+'][con]"><option value="=">Равно</option><option value="<">Меньше</option><option value=">">Больше</option></select>';
	res += '&nbsp;<input type="text" style="width:50px;" name="action['+link+'][n'+max_variant+'][value]" value="">';
	res += '</div>';
	res += '<div class="tv-right">';
	res += '<div class="tv-bg1 close">';
	res += '<div class="icon-delete" onclick="$(this).parent().parent().parent().remove();"></div>';
	res += '<div class="step-icon2 typeT" style="background-color:#37A3E3; display: none;" onclick="loadCountersForm(this,'+quest+');"></div>';
	res += '<select name="action['+link+'][n'+max_variant+'][type]" class="action_type" onchange="changeActionType(this);">';
	res += '<option value="M">Переход</option>';
	res += '<option value="T">Сообщение</option>';
	res += '<option value="C">Условия</option>';
	res += '</select>';
	res += '&nbsp;<select name="action['+link+'][n'+max_variant+'][id_point]"  onchange="createNewPoint(this)" class="typeM point_selector">';
	res += $('#events_to_be_cloned').html();
	res += '</select>';
	res += '<img class="step-icon5 typeT" src="/skins/default/images/constr_icon5.png" style="background-color: #ff0000; display: none;" onclick="loadMessageForm(this);">';
	res += '<textarea name="action['+link+'][n'+max_variant+'][message]" style="display: none;"></textarea>';
	res += '<label style="margin-top:8px; display: none;" class="typeT">';
	res += '<input value="1" name="action['+link+'][n'+max_variant+'][hide]" type="checkbox"> - после действия скрыть шаг</label>';
	res += '<div class="inventories typeC" style="display: none;">';
	res += $('#inventories_to_be_cloned').html().replace(/%num%/gi,'n'+max_variant);
	res += '</div>'
	res += '<div class="step-icon2 typeM typeC" style="background-color: #37A3E3;" onclick="loadCountersForm(this,'+quest+');"></div>';
	res += '</div>';
	res += '</div>';
	res += '<div class="clear"></div>';
	res += '</div>';
	
	$('#insert_variant_'+link).before(res);
	
	return res;
}

//функция по добавлению варианта для условия таймера
function addCounterCounterVariant(quest) {
	max_variant++;			
	var res='';
	res += '<div class="variant">';	
	res += '<input type="hidden" name="action[n'+max_variant+'][id]" value="">';
	res += '<input type="hidden" name="action[n'+max_variant+'][counters]" value="" class="counters">';
	res += '<div class="tv-left">';
	res += '<select style="width:95px;" name="action[n'+max_variant+'][con]"><option value="=">Равно</option><option value="<">Меньше</option><option value=">">Больше</option></select>';
	res += '&nbsp;<input type="text" style="width:50px;" name="action[n'+max_variant+'][value]" value="">';
	res += '</div>';
	res += '<div class="tv-right">';
	res += '<div class="tv-bg1 close">';
	res += '<div class="icon-delete" onclick="$(this).parent().parent().parent().remove();"></div>';
	res += '<div class="step-icon2 typeT" style="background-color:#37A3E3; display: none;" onclick="loadCountersForm(this,'+quest+');"></div>';
	res += '<select name="action[n'+max_variant+'][type]" class="action_type" onchange="changeActionType(this);">';
	res += '<option value="M">Переход</option>';
	res += '<option value="T">Сообщение</option>';
	res += '<option value="C">Условия</option>';
	res += '</select>';
	res += '&nbsp;<select name="action[n'+max_variant+'][id_point]" onchange="createNewPoint(this)" class="typeM point_selector">';
	res += $('#events_to_be_cloned').html();
	res += '</select>';
	res += '<img class="step-icon5 typeT" src="/skins/default/images/constr_icon5.png" style="background-color: #ff0000; display: none;" onclick="loadMessageForm(this);">';
	res += '<textarea name="action[n'+max_variant+'][message]" style="display: none;"></textarea>';
	res += '<label style="margin-top:8px; display: none;" class="typeT">';
	res += '<input value="1" name="action[n'+max_variant+'][hide]" type="checkbox"> - после действия скрыть шаг</label>';
	res += '<div class="inventories typeC" style="display: none;">';
	res += $('#inventories_to_be_cloned_counter').html().replace(/%num%/gi,'n'+max_variant);
	res += '</div>'
	res += '<div class="step-icon2 typeM typeC" style="background-color: #37A3E3;" onclick="loadCountersForm(this,'+quest+');"></div>';
	res += '</div>';
	res += '</div>';
	res += '<div class="clear"></div>';
	res += '</div>';
	
	$('#insert_variant').before(res);
	
	return res;
}

//Добавление новой точке
function createNewPoint(e) {
	if ($(e).val()=='new') {
		$('#editor_popup_if_choose').dialog({modal: true, dialogClass: 'modal', width: 125, minHeight: 70});
		$('#editor_popup_if_choose').css('width',125);
		$('.modal .ui-dialog-titlebar').hide();
		var position = $(e).offset();
		$("#editor_popup_if_choose").parent().css('top',position.top);
		$("#editor_popup_if_choose").parent().css('left',position.left);	
	}
}

//Новая точка в условии
function ifNewPoint(type,quest) {
	$('#editor_popup_if_choose').dialog('close');	
	showPresaver();
	var x = $('#dataXML input.x[rel='+$('#edit_form input[name=id]').val()+']').val();
	var y = $('#dataXML input.y[rel='+$('#edit_form input[name=id]').val()+']').val()*1+90;
	x = parseInt(x);
	y = parseInt(y);
	if (x<=0 || isNaN(x)) x = 150;
	if (y<=0 || isNaN(y)) y = 60;	
	$.ajax({
		type: 'POST',
		url: '/game/edit_new/point/'+quest,
		data: {POINT_NEW: type, x: x,y: y},
		success: function(data) {
			var obj = data.split(',');
			$('select.point_selector option[value=new]').after('<option value="new2">new</option>');
			$('select.point_selector option[value=new]').val(obj[0]);
			$('select.point_selector option[value='+obj[0]+']').html(obj[1]);
			$('select.point_selector option[value=new2]').val('new');			
			hidePresaver();
			hastobe_reloaded = true;
		}
	});
}
   
/***********	Работа с галереей      **********/

var has_opened = false;
//Функция по загрузке формы редактирования элемента
function loadGallery (q) {
	showPreloader();
	$("div.editor_popup[rel=gallery]").load('/game/edit_new/images/'+q+'?ts_mode=public',function(){
		$('.user_gallery .images').mouseover(function(){$(this).css('background-color',"#AAAAFF")});
		$('.user_gallery .images').mouseout(function(){$(this).css('background-color',"#EEEEEE")});
		var uploader = new qq.FileUploader({
			element: document.getElementById('file_upload'),
			action: '/include/backends/upload_quest_images_html.php',
			params: {'quest_id': q},
			allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
			sizeLimit: 1024*1024*2,
			template: '<div class="qq-uploader">' + 
                '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
                '<div class="qq-upload-button"><span class="middle">Добавить</span></div>' +
                '<ul class="qq-upload-list"></ul>' + 
             '</div>',
			onSubmit: function(id, fileName){
				if (!has_opened) {
					$('#file_preload').remove();
					$('#file_upload').before('<div class="images"><img src="/skins/default/images/preloader.gif" id="file_preload"></div>');
					has_opened = true;
				}
			},
			onComplete: function(id, fileName, response){
				$('#file_preload').replaceWith('<p style="text-align: right;"><a href="javascript: void();" onclick="remove_image('+q+','+response.id+'); $(this).parent().parent().remove(); return false;"><img src="/skins/default/images/delete_step_line.jpg" width="11" height="11" alt="x" class="close"></a></p><img src="/preview.php?id='+response.id+'&q='+q+'" rel="'+response.id+'" onclick="change_point_image(this);">');
				$('.user_gallery .images img[rel='+response.id+']').parent().mouseover(function(){$(this).css('background-color',"#AAAAFF")});
				$('.user_gallery .images img[rel='+response.id+']').parent().mouseout(function(){$(this).css('background-color',"#EEEEEE")});
				$('#file_preload').remove();
				has_opened = false;
			},
			onCancel: function(id, fileName){
				$('#file_preload').parent().remove();
				has_opened = false;
			}  
		});
		hidePreloader();
		//2) Показываем все
		$("div.editor_popup[rel=gallery]").dialog({ width: 500 , modal: true, height: 400 });
	});
}

//Удаление из базы картинки
function remove_image(q,id) {
	$.ajax({
	  type: 'POST',
	  url: '/game/edit_new/images/'+q+'?mode=del&id='+id
	});
	$('#dataXML input.image[value='+id+']').val('-1');
	if ($('#point_image').val()==id) $('#point_image').val('-1');
}

//изменение картинки точки
function change_point_image(el) {
	$('#point_image').val($(el).attr('rel'));
	$('#point_image_src').remove();
	$('#point_image_del').remove();
	$('#point_image').after('<img src="'+$(el).attr('src')+'" id="point_image_src" width="100" style="float: left;"><a href="javascript:void(0);" onclick="del_point_image();" id="point_image_del"><img src="/skins/default/images/delete_step_line.jpg" width="11" height="11" alt="x"></a>');
	$("div.editor_popup[rel=gallery]").dialog('close');
}
//удаление картинки точки
function del_point_image() {
	$('#point_image').val('-1');
	$('#point_image_src').remove();
	$('#point_image_del').remove();
}


/***********	Функции служебные      **********/

//показать прелоадер
function showPreloader() {
	$( "#editor_popup_loading" ).dialog({
		modal: true, dialogClass: 'modal'
	});
	$('.modal').css('height',50);
	$('.modal .ui-dialog-titlebar').hide();
}

//скрытие прелоадера
function hidePreloader() {
	$("#editor_popup_loading").dialog('close');
}

//показать прелоадер
function showPresaver() {
	$( "#editor_popup_saving" ).dialog({
		modal: true, dialogClass: 'modal'
	});
	$('.modal').css('height',50);
	$('.modal .ui-dialog-titlebar').hide();
}

//скрытие прелоадера
function hidePresaver() {
	$("#editor_popup_saving").dialog('close');
}

/***********	Функции конструктора в целом      **********/

//перезагрузка окошка
function reloadMain(quest) {
var attr = $('#autosave').attr('checked');
if (typeof attr !== 'undefined' && attr !== false) attr = 1; else attr = 0;
showPreloader();
$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/'+quest,
	  data: {mode: 'editor',ts_mode: 'public', autosave: attr},
	  success: function(data) {
		$("#constructor").html(data);
		loadGraphics();
		hidePreloader();
	  }
	});
}

//сохранение всех данных
function saveData (quest) {
	saveQuest(quest, function () {});
}

//сохранение данных
function saveQuest (quest, func) {
	var attr = $('#autosave').attr('checked');
	if (typeof attr !== 'undefined' && attr !== false) attr = 1; else attr = 0;
	showPresaver();
	$.ajax({
	  type: 'POST',
	  url: '/game/edit_new/'+quest+'?ts_mode=public&mode=editor',
	  data: {questData: $("#dataXML").serialize(), publish: $('input[name=publish]').val(), autosave: attr},
	  success: function(data) {			
		hidePresaver();
		func(data);
	  }
	});
}

//Проверка данных
function testData (quest) {
	saveQuest(quest, function() {
		$( "#editor_popup_testing" ).dialog({
			modal: true, dialogClass: 'modal'
		});
		$('.modal').css('height',50);
		$('.modal .ui-dialog-titlebar').hide();
		$.ajax({
		  type: 'GET',
		  url: '/game/edit_new/test/'+quest+'?ts_mode=public',
		  success: function(data) {
			if (data=='1') {
				$("#editor_popup_errors").html('Квест корректен!');
			} else {
				$("#editor_popup_errors").html(data);
			}
			$( "#editor_popup_testing" ).dialog('close');
			$( "#editor_popup_errors" ).dialog();
		  }
		});
	});
}

//Публикация данных
function publicData (quest) {
	saveQuest(quest, function() {
		$( "#editor_popup_testing" ).dialog({
			modal: true, dialogClass: 'modal'
		});
		$('.modal').css('height',50);
		$('.modal .ui-dialog-titlebar').hide();
		$.ajax({
		  type: 'GET',
		  url: '/game/edit_new/test/'+quest+'?ts_mode=public',
		  success: function(data) {
			if (data=='1') {
				$("#editor_popup_version" ).dialog({
					modal: true, dialogClass: 'modal', width: 400, title: 'Версия', beforeClose: 
					function(event, ui){
						$('input[name=publish]').val('1');
						$('input[name=version_message]').val($('#version_message').val());
						saveQuest(quest,function(data) {
							if(data=='P') {
								document.location = '/profile/quests';
								return true;
							} else
								$("#editor_popup_errors").html(data);
							$( "#editor_popup_testing" ).dialog('close');
							$( "#editor_popup_errors" ).dialog();
						});
					}
				});                
			} else {
				$("#editor_popup_errors").html(data);
				$( "#editor_popup_testing" ).dialog('close');
				$( "#editor_popup_errors" ).dialog();
			}			
		  }
		});
	});
}

function show_tip(tip,e) {
	if (tip!='') {
		var xy = $(e).offset();
		var base = $('#editor_canvas').offset();
		$('#tip_box').html(tip);
		$('#tip_box').css('left',xy.left-base.left+60);
		$('#tip_box').css('top',xy.top-base.top);
		$('#tip_box').show();
	}
}

/***********	Функции по настройке     **********/

//Настройка данных
function gameSettings (quest) {
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/settings/'+quest+'?ts_mode=public',
	  success: function(data) {
		$("div.editor_popup[rel=settings]").html(data);
		$("div.editor_popup[rel=settings]").dialog({ modal: true, width: 460,title: 'Настройки'});
		var uploader = new qq.FileUploader({
			element: document.getElementById('settings_upload'),
			action: '/include/backends/settings_upload_html.php',
			allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
			sizeLimit: 1024*1024*2,
			template: '<div class="qq-uploader">' + 
                '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
                '<div class="qq-upload-button"><span class="middle" class="ajaxLink">Выбрать изображение</span></div>' +
                '<ul class="qq-upload-list"></ul>' + 
             '</div>',
			onComplete: function(id, fileName, response){
				if (response.path != '') {
					$('#settings_image').val(response.path);
					$('#settings_image').show();
					$('#settings_image_preview').attr('src','/images/settings/'+response.path);
					$('#del_settings_image').show();
					$('#settings_image_preview').show();
				}
				has_opened = false;
			}
		});
		
		
		var uploader = new qq.FileUploader({
			element: document.getElementById('settings_fieldupload'),
			action: '/include/backends/settings_upload_html.php',
			allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
			sizeLimit: 1024*1024*2,
			template: '<div class="qq-uploader">' + 
                '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
                '<div class="qq-upload-button"><span class="middle" class="ajaxLink">Выбрать изображение</span></div>' +
                '<ul class="qq-upload-list"></ul>' + 
             '</div>',
			onComplete: function(id, fileName, response){
				if (response.path != '') {
					$('#settings_fieldimage').val(response.path);
					$('#settings_fieldimage').show();
					$('#settings_fieldimage_preview').attr('src','/images/settings/'+response.path);
					$('#del_settings_fieldimage').show();
					$('#settings_fieldimage_preview').show();
				}
				has_opened = false;
			}
		});
		
		initSwitcher();
		$('#quest_settings_form div.color_preview').ColorPicker({
			onSubmit: function(hsb, hex, rgb, el) {
				var input = $(el).parent().find('input.color');
				$(input).val(hex);
				$(el).ColorPickerHide();
				$(el).css('background-color','#'+hex);
			},
			onBeforeShow: function () {
				var input = $(this).parent().find('input.color');
				$(this).ColorPickerSetColor($(input).val());
				$(this).css('background-color','#'+$(input).val());
			}
		});
		
		$('#quest_settings_form div.color_preview').each(function(){
			var input = $(this).parent().find('input.color');			
			$(this).css('background-color','#'+$(input).val());
		});
	  }
	});
}

//Сохранение квеста
function saveSettings(quest) {
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/settings/'+quest+'?ts_mode=public&mode=save&'+$("#quest_settings_form").serialize(),
	  success: function(data) {
		$("div.editor_popup[rel=settings]").dialog('close');
	  }
	});
}


/***********	Функции общих ссылок     **********/

//Список ссылок
function gameLinks (quest) {
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/links/'+quest+'?ts_mode=public',
	  success: function(data) {
		$("#keditor_links").html(data);
		$("#keditor_links").dialog({ width: 160,title: 'Общие ссылки', dialogClass: 'wo_close',minHeight: 30});
		$('.wo_close a.ui-dialog-titlebar-close').hide();
		$('.wo_close span.ui-dialog-title').css('marginRight','0');		
		$("#keditor_links").parent().css('top',357);
		var position = $('#constructor').offset();
		$("#keditor_links").parent().css('left',position.left+740);
	  }
	});
}

//Редактировать ссылку
function editLink (quest,link) {
	saveQuest(quest, function () {
		$.ajax({
		  type: 'GET',
		  url: '/game/edit_new/links/'+quest+'?ts_mode=public&mode=edit&id='+link,
		  success: function(data) {
			$("div.editor_popup[rel=edit_link]").html(data);
			$("div.editor_popup[rel=edit_link]").dialog({ modal: true, width: 640,title: 'Изменить общую ссылку', beforeClose: 
					function(event, ui){ 
						if (confirm("Вы не сохранили изменения, Вы уверены что хотите выйти?")) {
							if (hastobe_reloaded) {
								reloadMain(quest);
								hastobe_reloaded = false;
							}
							return true;
						} else {
							return false;
						}
					} });
		  }
		});
	});
}

//Функция по добавлению условия в точку условия (вот такая тофталогия =))
function loadLink(quest, link) {
	max_ifcond++;
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/point/action/'+quest,
	  data: {link: link,ts_mode: 'public'},
	  success: function(data) {
		$('#quest_links_form .form_buttons').before(data);
	  }
	});
}

//функция по смене типа реакции
function changeLinkAction(e,quest,point,link) {
	var val = $(e).val();
	var header = e;
	var i=0;
	while (!$(header).hasClass('step-header') && i<10) {
		header = $(header).parent();
	}
	var name = $(header).find('div.title input').val();
	var visible = $(header).find('input.visible').val();
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/point/action/'+quest,
	  data: {link: link,ts_mode: 'public', new_type: val, name: name, visible: visible},
	  success: function(data) {		
		$(e).parent().parent().parent().parent().parent().replaceWith(data);
	  }
	});	
}

//Сохранить ссылку
function saveLink (quest,link) {
	$.ajax({
	  type: 'POST',
	  url: '/game/edit_new/links/'+quest+'?ts_mode=public&mode=save&id='+link+'&'+$("#quest_links_form").serialize(),
	  success: function(data) {
		$("div.editor_popup[rel=edit_link]").dialog('option','beforeClose',function(){});
		if (data.indexOf('quest_links_form')>=0) {
			$("div.editor_popup[rel=edit_link]").dialog('close');
			$("div.editor_popup[rel=edit_link]").html(data);
			$("div.editor_popup[rel=edit_link]").dialog({ modal: true, width: 640,title: 'Изменить общую ссылку'});
		} else {		
			$("div.editor_popup[rel=edit_link]").dialog('close');
			$("#keditor_links").html(data);			
		}
		reloadMain(quest);
	  }
	});
}

//Удаляем ссылку
function delLink (quest,link) {
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/links/'+quest+'?ts_mode=public&mode=del&id='+link,
	  success: function(data) {		
		$("#keditor_links").html(data);		
	  }
	});
}

/***********	Функции инвентаря     **********/

//Список инвентаря
function gameInventory (quest) {
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/inventory/'+quest+'?ts_mode=public',
	  success: function(data) {
		$("#keditor_inventories").html(data);
		$("#keditor_inventories").dialog({ width: 160,title: 'Условия', dialogClass: 'wo_close',minHeight: 30});
		$('.wo_close a.ui-dialog-titlebar-close').hide();
		$('.wo_close span.ui-dialog-title').css('marginRight','0');
		$("#keditor_inventories").parent().css('top',507);
		var position = $('#constructor').offset();		
		$("#keditor_inventories").parent().css('left',position.left+740);
	  }
	});
}

//Редактировать инвентарь
function editInventory (quest,inv) {
	saveQuest(quest, function () {
		$.ajax({
		  type: 'GET',
		  url: '/game/edit_new/inventory/'+quest+'?ts_mode=public&mode=edit&id='+inv,
		  success: function(data) {		
			$("div.editor_popup[rel=edit_inventory]").html(data);
			$("div.editor_popup[rel=edit_inventory]").dialog({ modal: true, width: 460,title: 'Изменить условие', beforeClose: 
					function(event, ui){ 
						if (confirm("Вы не сохранили изменения, Вы уверены что хотите выйти?")) {
							if (hastobe_reloaded) {
								reloadMain(quest);
								hastobe_reloaded = false;
							}
							return true;
						} else {
							return false;
						}
					}});
		  }
		});
	});
}

//Сохранить инвентарь
function saveInventory (quest,inv) {
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/inventory/'+quest+'?ts_mode=public&mode=save&id='+inv+'&'+$("#quest_inventory_form").serialize(),
	  success: function(data) {
		$("div.editor_popup[rel=edit_inventory]").dialog('option','beforeClose',function(){});
		if (data.indexOf('quest_inventory_form')>=0) {
			$("div.editor_popup[rel=edit_inventory]").dialog('close');
			$("div.editor_popup[rel=edit_inventory]").html(data);
			$("div.editor_popup[rel=edit_inventory]").dialog({ modal: true, width: 460,title: 'Изменить условие'});
		} else {		
			$("div.editor_popup[rel=edit_inventory]").dialog('close');
			$("#keditor_inventories").html(data);
		}
		reloadMain(quest);
	  }
	});
}

//Удаляем инвентарь
function delInventory (quest,inv) {
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/inventory/'+quest+'?ts_mode=public&mode=del&id='+inv,
	  success: function(data) {		
		$("#keditor_inventories").html(data);		
	  }
	});
}

/***********	Функции счетчика    **********/

//Список счетчиков
function gameCounters (quest) {
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/counters/'+quest+'?ts_mode=public',
	  success: function(data) {
		$("#keditor_counters").html(data);
		$("#keditor_counters").dialog({ width: 160,title: 'Счетчики', dialogClass: 'wo_close',minHeight: 30});
		$('.wo_close a.ui-dialog-titlebar-close').hide();
		$('.wo_close span.ui-dialog-title').css('marginRight','0');
		$("#keditor_counters").parent().css('top',657);
		var position = $('#constructor').offset();
		$("#keditor_counters").parent().css('left',position.left+740);
	  }
	});
}

//Редактировать инвентарь
function editCounters (quest,val) {
	saveQuest(quest, function () {
		$.ajax({
		  type: 'GET',
		  url: '/game/edit_new/counters/'+quest+'?ts_mode=public&mode=edit&id='+val,
		  success: function(data) {
			$("div.editor_popup[rel=edit_counters]").html(data);
			$("div.editor_popup[rel=edit_counters]").dialog({ modal: true, width: 500,title: 'Изменить счетчик', beforeClose: 
					function(event, ui){ 
						if (confirm("Вы не сохранили изменения, Вы уверены что хотите выйти?")) {
							if (hastobe_reloaded) {
								reloadMain(quest);
								hastobe_reloaded = false;
							}
							return true;
						} else {
							return false;
						}
					}});
		  }
		});
	});
}

//Сохранить инвентарь
function saveCounters (quest,val) {
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/counters/'+quest+'?ts_mode=public&mode=save&id='+val+'&'+$("#quest_counters_form").serialize(),
	  success: function(data) {
		$("div.editor_popup[rel=edit_counters]").dialog('option','beforeClose',function(){});
		if (data.indexOf('quest_counters_form')>=0) {
			$("div.editor_popup[rel=edit_counters]").dialog('close');
			$("div.editor_popup[rel=edit_counters]").html(data);
			$("div.editor_popup[rel=edit_counters]").dialog({ modal: true, width: 500,title: 'Изменить счетчик'});
		} else {		
			$("div.editor_popup[rel=edit_counters]").dialog('close');
			$("#keditor_counters").html(data);
		}
		reloadMain(quest);
	  }
	});
}

//Удаляем инвентарь
function delCounters (quest,val) {
	$.ajax({
	  type: 'GET',
	  url: '/game/edit_new/counters/'+quest+'?ts_mode=public&mode=del&id='+val,
	  success: function(data) {		
		$("#keditor_counters").html(data);
		reloadMain(quest);
	  }
	});
}
/**************************************************************************************/
/* 													 								  */
/* 								КОНЕЦ КОНФИГУРАТОРА 								  */
/* 																					  */
/**************************************************************************************/

function getImgSize(imgSrc) {
	var newImg = new Image();
	newImg.src = imgSrc;
	var height = newImg.height;
	var width = newImg.width;
	alert ('The image size is '+width+'*'+height);
}

$(document).ready(function(){
	initSearchInput();
	initNewFilter();
	initMainBlocks();
})

initSearchInput = function(){
	$("input.text").focus(function(){
		if ($(this).attr("value") == $(this).attr("title")) {
			$(this).attr("value", "");
		}
		
	});
	$("input.text").blur(function(){
		if (($(this).attr("value")) == "") {
			$(this).attr("value", $(this).attr("title"));
		}
	});
}

initNewFilter = function(){
	$("#filter_sort .pseudo_select").click(function(){
		if ($(this).hasClass("opened")) {
			$(this).removeClass("opened");
			$("#filter_sort .pseudo_list").slideUp();
		}else{
			$("#filter_sort .pseudo_select").removeClass("opened");
			$(this).addClass("opened");
			$("#filter_sort .pseudo_list").slideUp();
			$(this).find(".pseudo_list").slideToggle();
		}
	});
	
	$("#filter_sort li.active a").click(function(){return false;});
	
	$("#top_filter").click(function(){
		if ($(this).hasClass("opened")) {
			$(this).removeClass("opened");
			$("#top_filter .pseudo_list").slideUp();
		}else{
			$("#top_filter").removeClass("opened");
			$(this).addClass("opened");
			$("#top_filter .pseudo_list").slideUp();
			$(this).find(".pseudo_list").slideToggle();
		}
	});
};

$(document).ready(function(){
	$('.width_select').click(function(){
		$('.width_select').removeClass('active');
		$(this).addClass('active');
		$('#widget_width').val($(this).attr('rel'));
		return false;		
	});
	$('.height_select').click(function(){
		$('.height_select').removeClass('active');
		$(this).addClass('active');
		$('#widget_height').val($(this).attr('rel'));
		return false;		
	});	
});

function recalc_widget (quest) {
	var width="450";
	var height="450";
	if ($('#widget_width').val()>10) {
		width = $('#widget_width').val();
	}
	if ($('#widget_height').val()>10) {
		height = $('#widget_height').val();
	}
	var s = '<iframe src="http://kvester.ru/game/quest/widget/'+quest+'?height='+height+'" frameBorder="0" id="quest" height="'+height+'" width="'+width+'"></iframe>';
	$('#widget').val(s);
	$('#widget').focus();
	$('#widget').select();	
}

function update_top_filter (e) {
	$('.top_quest').hide(); 
	$('#top_filter .selected').html($(e).html()); 
	$('#top_filter li').removeClass('active');
	$(e).parent().addClass('active');
	$('.top_quest[rel='+$(e).attr('rel')+']').show();
	return false;
}

var on_move = false;

/**  Обновление игры, по аяксу  **/
function update_game (link) {	
	//window.location = link;return'';
	if (on_move) return false;
	on_move = true;	
	var is_top_link = 'margin-left: 21px;';
	if ($(link).parent().parent().hasClass('inlineMenuList')) {
		$(link).parent().css('margin-left',-8);
		$(link).parent().html('<img src="/skins/default/images/action_preloader2.gif" style="height: 16px; margin-bottom: -3px; margin-right: 5px; width: 16px;"/>'+$(link).parent().html());
	} else {
		$(link).parent().css('margin-left',-21);
		$(link).parent().html('<div style="float:left;"><img src="/skins/default/images/action_preloader2.gif" style="height: 16px; margin-bottom: -3px; margin-right: 5px; width: 16px;"/></div><div style="margin-left: 21px;">'+$(link).parent().html()+'</div>');
	}
	$.ajax({
	  type: 'GET',
	  url: $(link).attr('href')+'&ts_mode=public',	  
	  success: function(data) {
		if (data=='W' || data=='L') {
			window.location = $(link).attr('href').substr(0,$(link).attr('href').indexOf( '?',0));
		} else {			
			$('div.main').html(data);
			try{
				ieWandsGenerate();
			}catch(ex){
				
			}
		}
		on_move = false;
	  },
	  error: update_game(link)
	});
}

initMainBlocks = function(){
	function comments_call(carousel) {
		jQuery('.k_block_nav.comment a.bottom').bind('click', function() {
			carousel.next();
			return false;
		});
		jQuery('.k_block_nav.comment a.top').bind('click', function() {
			carousel.prev();
			return false;
		});
	};
	
	function news_call(carousel) {
		jQuery('.k_block_nav.news a.bottom').bind('click', function() {
			carousel.next();
			return false;
		});
		jQuery('.k_block_nav.news a.top').bind('click', function() {
			carousel.prev();
			return false;
		});
	};
	
	if (jQuery('#last_comments_block').size()>0) {
		jQuery('#last_comments_block').jcarousel({
			vertical: true,
			scroll: 6,
			initCallback: comments_call,
			// This tells jCarousel NOT to autobuild prev/next buttons
			buttonNextHTML: null,
			buttonPrevHTML: null,
			itemFallbackDimension: 300,
			buttonNextCallback: function(car,e,flag) {
				if(flag)
					jQuery('.k_block_nav.comment a.bottom').removeClass('disabled');
				else
					jQuery('.k_block_nav.comment a.bottom').addClass('disabled');
			},
			buttonPrevCallback: function(car,e,flag) {
				if(flag)
					jQuery('.k_block_nav.comment a.top').removeClass('disabled');
				else
					jQuery('.k_block_nav.comment a.top').addClass('disabled');
			}
		});
	}
	if (jQuery('#news_block').size()) {
		jQuery('#news_block').jcarousel({
			vertical: true,
			scroll: 6,
			initCallback: news_call,
			itemFallbackDimension: 300,
			// This tells jCarousel NOT to autobuild prev/next buttons
			buttonNextHTML: null,
			buttonPrevHTML: null,
			buttonNextCallback: function(car,e,flag) {
				if(flag)
					jQuery('.k_block_nav.news a.bottom').removeClass('disabled');
				else
					jQuery('.k_block_nav.news a.bottom').addClass('disabled');
			},
			buttonPrevCallback: function(car,e,flag) {
				if(flag)
					jQuery('.k_block_nav.news a.top').removeClass('disabled');
				else
					jQuery('.k_block_nav.news a.top').addClass('disabled');
			}
		});
	}
}

initSwitcher = function(){
	$('#quest_settings_form a.switcher').click(function(){
		$('a.switcher').removeClass('active');
		$(this).addClass('active');
		$('#quest_settings_form div.switch_Tab').hide();
		$('#quest_settings_form div.switch_Tab[rel='+$(this).attr('rel')+']').show();
		return false;
	});		
}

function vote_quest(el,id) {
	var data='';
	$('#'+id+' input').each(function(){
		data += $(this).attr('name')+'='+$(this).val()+'&';
	});
	$.ajax({
	   type: "POST",
	   url: $('#'+id).attr('action'),
	   data: data,
	   success: function(msg){
		 $(el).replaceWith('<span class="like"><span class="icon"></span>'+msg+' - спасибо за голос</span>&nbsp;&nbsp;&nbsp;');
	   }
	 });
}

/**  Обновление игры, по аяксу  **/
function update_game_old (link) {	
	//window.location = link;return'';
	if (on_move) return false;
	on_move = true;
	$(link).parent().css('margin-left',-26);	
	$(link).parent().html('<div style="float:left;"><img src="/skins/default/images/action_preloader.gif" style="height: 16px; margin-bottom: -3px; margin-right: 10px; width: 16px;"/></div><div style="padding-left: 26px;">'+$(link).parent().html()+'</div>');
	$.ajax({
	  type: 'GET',
	  url: $(link).attr('href')+'&ts_mode=public',	  
	  success: function(data) {
		if (data=='W' || data=='L') {
			window.location = $(link).attr('href').substr(0,$(link).attr('href').indexOf( '?',0));
		} else {			
			$('#main_block .game_process').html(data);
		}
		on_move = false;
	  },
	  error: update_game(link)
	});
}
