var edit_block;
var edit_elem = null;
var flag_del_block = 0;
var page_old = '';
//var tabs;

function SetMandatoryFields(obj){
	$.ajax({
		type: "POST",
		url: 'admin_builder.php',
  		data: 'sel=SetMandatoryFields&val=' + $(obj).attr('checked'),
		success: function (data) {
			//alert(data);
		}
	});
}

function FastDeleteElement(obj){
    var move_to = $('#tools').find('.'+$(obj).attr('category')).find('ul');
    move_to.append($(obj));
    $(obj).find('.info').removeClass('info').addClass('info_center');
    $(obj).find('.info_center').each(function(){
        Show_ToolTip($(this), $(this).attr('id_elem'));
    });
    var img = $(obj).find('.deleteadd');
    img.unbind('click');
    img.attr('src', '../templates/admin/images/controls/plus.png');
    img.click(function(){ AddElementToPage($(this).parents('li'), -1); });
    $(obj).removeClass('edit_section2');
    $(obj).addClass('edit_section_no_cursor');
    $(obj).find('.control').show();
    $(obj).find('.div_editelem').hide();
}

function DeleteElement(obj, exitblock){ // li
	var ul_obj = $(obj).parents('ul');
	if(ul_obj.find('li').size() == 1){
		$.post(
			'admin_builder.php',
			{
				sel: 'add_empty_field',
				page: $(ul_obj).parent().parent().attr("page_id")
			}
		);
	}
    var move_to = $('#tools').find('.'+$(obj).attr('category')).find('ul');
	if(exitblock == 0){
	    par_get = $(obj).parents('.ui-tabs-panel').attr('id');
		$(obj).fadeOut(250, function() {
        	$(obj).find('.info').removeClass('info').addClass('info_center');
			$(obj).find('.info_center').each(function(){
				Show_ToolTip($(this), $(this).attr('id_elem'));
			});
            if(!$(obj).hasClass('custom') && !$(obj).hasClass('text_del')){
                move_to.append($(obj));
                var img = $(obj).find('.deleteadd');
                img.unbind('click');
                img.attr('src', '../templates/admin/images/controls/plus.png');
                img.click(function(){ AddElementToPage($(this).parents('li'), -1); });
                $(obj).removeClass('edit_section');
                $(obj).addClass('edit_section_no_cursor');
                $(obj).find('.div_editelem').hide();
                $(obj).show(250);
                $.ajax({
                    type: "POST",
                    url: 'admin_builder.php',
                    data: 'sel=del_custom&id='+ $(obj).attr("id_elem")+'&par='+par_get,
                    success: function (data) {
                        //alert(data);
                    }
                });
            }
            else {
                $.ajax({
                    type: "POST",
                    url: 'admin_builder.php',
                    data: 'sel=del_text&id='+ $(obj).attr("id_elem"),
                    success: function (data) {
                        //alert(data);
                    }
                });
                $(obj).remove();
            }
		});
	}
	else{
		$(obj).hide();
		$(obj).find('.info').removeClass('info').addClass('info_center');
		$(obj).find('.info_center').each(function(){
			Show_ToolTip($(this), $(this).attr('id_elem'));
		});
        if(!$(obj).hasClass('custom') && !$(obj).hasClass('text_del')){
            move_to.append($(obj));
            var img = $(obj).find('.deleteadd');
            img.unbind('click');
            img.attr('src', '../templates/admin/images/controls/plus.png');
            img.click(function(){ AddElementToPage($(this).parents('li'), -1); });
            $(obj).removeClass('edit_section');
            $(obj).addClass('edit_section_no_cursor');
            $(obj).find('.div_editelem').hide();
            $(obj).show(250);
        }
        else{
            $.ajax({
                type: "POST",
                url: 'admin_builder.php',
                data: 'sel=del_text&id='+ $(obj).attr("id_elem"),
                success: function (data) {
                    //alert(data);
                }
            });
            $(obj).remove();
        }
	}
}


function DeleteBlock(obj){
    if(!confirm(entity(lang_deletepage)))
        return;

    obj = $(obj).parents('.portlet');
	//obj.effect('explode');
	obj.addClass("clear");
	edit_block = null;

    $(obj).find('li').each(function(){
        FastDeleteElement($(this));
    });
	obj.remove();
	flag_del_block = 0;
	PageNumbers();
    if(tabnum == 0)
        setTimeout("$('.clear').remove();flag_del_block=1;PageNumbers();", 500);
}

function CreateNewBlock(str){
	try{
		var selected = $tabs.tabs('option', 'selected');
	}catch(e) {return;}
	selected++;
	id = "#tabs-"+selected;

	var obj = $(id).find(".empty_block").clone();
    
	obj.removeClass("empty_block");
	$(id).find(".column").append(obj);
	obj.show();

    if(!str){
        tmp = $(obj).offset();
        window.scroll(0,tmp.top-15);
    }

	obj.effect('highlight');

    if(str)
        $(obj).find(".portlet-header").find("div:first").html(str);

    if(tabnum == 0)
        PageNumbers();


	$(obj).find(".portlet-header").find("img").click(function(){
        EditHeader($(this).parents(".portlet"));
	});
}


function SaveHeader(obj){
	var html = $(obj).find("#headername").val();
    html = html.replace(/::/, ':');
    html = html.replace(/;;/, ';');
    $(obj).find(".portlet-header").find("div:first").html(html);

	//send text via ajax
	var page_id = $(obj).attr('page_id');
	$.ajax({
		type: "POST",
		url: 'admin_builder.php',
        data: {'sel':'save_page_header', 'page': page_id, 'text': html},
		success: function (data) {
			//alert(data);
		}
	});

    $(obj).find(".portlet-header").find("img").unbind('click');
	$(obj).find(".portlet-header").find("img").click(function(){
        EditHeader($(this).parents(".portlet"));
	});
}

function EditHeader(obj){
    var str = $(obj).find(".portlet-header").find("div").html();
    str = str.replace(/"/g, "&quot;");
    str = str.replace(/'/g, "&#039;");

	$(obj).find(".portlet-header").find("div:first").html("<input onkeydown='HeaderKey(event, $(this).parents(\".portlet\"));' onblur='SaveHeader($(this).parents(\".portlet\"));' width='300px' id='headername' value='"+str+"'>");
	$("#headername").css('width','250px');
	$("#headername").focus();
    $(obj).find(".portlet-header").find("img").unbind('click');
    $(obj).find(".portlet-header").find("img").click(function(){ SaveHeader($(this).parents(".portlet")); });
}
function HeaderKey(event, obj){
    if(event.keyCode == "13")
        SaveHeader(obj);
}

function ExitEditBlock(obj, send){
	edit_block = null;
	$(obj).find(".draw_area").sortable('destroy');
	$(obj).find(".control").fadeOut('slow');

    $(obj).find("li").each(function(){
        if($(this).parent().is(".draw_area")){
            $(this).removeClass("edit_element");
            $(this).addClass("edit_section2");
            $(this).removeClass("edit_section");
        }
    });
	
	ColumnSortEnable();
	
	$(".edit_block").fadeIn('slow');
	$(".delete_block").fadeIn('slow');
	
	$(obj).find(".edit").unbind('click'); 
	$(obj).find(".edit").removeClass('edit_element');
	
	$('.enter_edit_element').hide();
	$(".before_edit_element").fadeOut(250);

	if(send == 1){
		var page_id = $(obj).attr('page_id');
		var order = 1;
		var orders = "", ids = "";

		$(obj).find('.portlet-content').find('li').each(function(){
            if($(this).parent().is(".draw_area")){
                ids = ids + 'id[]=' + $(this).attr('id_elem') + '&';
            }
		});

		var send4 = ids + orders;
		$.ajax({
			type: "POST",
			url: 'admin_builder.php',
			data: 'sel=save_elements&page='+ page_id + '&' + send4+'tabs='+tabnum,
			success: function (data, textStatus) {
			}
		});
	}
    $('#exit_flag').val('0');
}

function ColumnSortDisable() {
	$('.column').sortable('destroy');
}

function PageNumbers(){
    PageNumbersSimple();
    if(tabnum != 0){
        return;
	}
    var poststr = "";
    var flag_str = "";
    if (flag_del_block == 1) flag_str = "&flag=1";
    flag_del_block=0;
    $('.portlet').each(function(){
        if(!$(this).hasClass('empty_block')){
            if($(this).attr('page_id') != undefined && $(this).attr('page_id') != 0)
            {
                poststr = poststr + $(this).attr('page_id') + ':';
                $(this).find('li').each(function(){
                    if($(this).attr('id_elem') != undefined)
                        poststr = poststr + $(this).attr('id_elem') + ',';
                });
                poststr = poststr + ';';
            }
        }
    });
    if(poststr != ""){
        $.ajax({
            type: "POST",
            cache: true,
            url: 'admin_builder.php',
            data: 'sel=pages&data='+poststr,
            success: function (data) {
				//alert(data);
			}
        });
    }
	var lang = "";
	var flag = 0;
    $('.portlet').each(function(){
        if(!$(this).hasClass('empty_block')){
            page = $(this).attr('page_id');
            lang = lang + page + '::';
            if(page != undefined){
                if(page > 0 && flag == 0){
                    text = $(this).find('.portlet-header').find('div:first').text();
                    text = text.replace(/::/, ':');
                    text = text.replace(/;;/, ';');
                    text = text.replace(/\t/, '');
                    lang = lang + text + ';;'
                }
            } else {
            	flag = 1;
            }
        } else {
        	flag = 1;
        }
    });

   if(lang.length > 0){
        $.ajax({
            type: "POST",
            cache: false,
            url: 'admin_builder.php',
            data: 'sel=pageslang'+flag_str+'&data='+lang+'&data_old='+page_old+'&rand='+Math.random(),
            success: function (data) {
				//alert(data);
			}
        });
    }
}

function PageNumbersSimple(){
	var i=1;
	page_old = '';
	$(".portlet-header").each(function(){
        if(!$(this).parent().hasClass('clear')){
            page_old = page_old + $(this).parent().attr('page_id')+',';
            $(this).find('span').html('Page '+i+':');
            $(this).parent().attr('page_id', i);
            i++;
        }
	});
}

function ColumnSortEnable() {
	$(".column").sortable({
		placeholder: 'ui-state-highlight',
		connectWith: '.column',
		stop: function(event, ui) { PageNumbers(); },
		items: '.portlet:not(.first_page)'
	});

	$(".column").disableSelection();
	$(".column").bind('sortstart', function(event, ui) {
		$(".column").find(".ui-state-highlight").css('width',ui.item.width());
		$(".column").find(".ui-state-highlight").css('height',ui.item.height());
	});	
}

function LocateEditElement(obj){
	var width = $(".before_edit_block").width();

    if(width > 0)
        $(".enter_edit_element").width(width);
	$(".enter_edit_element").fadeIn('slow');

    $(".enter_edit_element").offset({ top: $(obj).offset().top, left: $(obj).offset().left + $(obj).width() + 45});
    $(".enter_edit_element").offset({ top: $(obj).offset().top, left: $(obj).offset().left + $(obj).width() + 45}); //need double set, position bug in IE
}
function ExitEditElem(obj){
	edit_elem = null;
	$(obj).parent().find('.edit_element').addClass('edit_section');
	$(obj).parent().find('.edit_element').removeClass('.edit_element');
}

function span(obj){
    if($(obj).hasClass('name_for_lang')){
        if($(obj).attr('mandatory') == 1){
            if($(obj).find('.mandatory').html() == null){
                if($(obj).find('p').html() != null)
                    $(obj).find('p:last').append(' <span class="mandatory"><font class="error_msg">*</font></span>');
                else
                    $(obj).append(' <span class="mandatory"><font class="error_msg">*</font></span>');
            }
        }
    }
}

function span_small_text(){
	$('td').find('.elem_small_text').each(function(){
		if($(this).attr('mandatory') == '1'){
            if($(this).find('.mandatory').html() == null){
                if($(this).find('p').html() != null)
                    $(this).find('p:last').append(' <span class="mandatory"><font class="error_msg">*</font></span>');
                else
                    $(this).append(' <span class="mandatory"><font class="error_msg">*</font></span>');
            }
		}
	});
}

function LoadParam(tooltip){

    var id_spr = $(tooltip).find('.div_name_for_lang').attr('id_spr');
    var category = $(tooltip).find('.div_name_for_lang').attr('cat');
    var name = $(tooltip).find('.div_name_for_lang').attr('name_for_lang');

    var personal_array = [4,5]; //id_spr

    if(category == 'personal' && (name == 'id_country' || name == 'id_region' || name == 'id_city')){
        $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_countries.php">'+edit_variants+'</a></div>');
    }
    if(category == 'personal' && (name == 'id_relationship')){
        $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_reference.php?ref=14">'+edit_variants+'</a></div>');
    }
    if(category == 'personal' && (name == 'id_relationship')){
        $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_reference.php?ref=14">'+edit_variants+'</a></div>');
    }
    if(category == 'personal' && (name == 'im' || name == 'looking_for')){
        $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_reference.php?ref=23">'+edit_variants+'</a></div>');
    }

    if(category == 'personal' && id_spr != undefined && id_spr > 0){
        for(var i=0; i<personal_array.length; i++){
            if(personal_array[i] == id_spr){
                $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_reference.php?ref='+id_spr+'">'+edit_variants+'</a></div>');
            }
        }
    }
    if(category == 'personality'){
        if(id_spr != undefined && id_spr > 0){
            $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_reference.php?ref=6&id_spr='+id_spr+'">'+edit_variants+'</a></div>');
        }
        
    }
    if(category == 'description' || category == 'partner_criteria'){
        if(id_spr != undefined && id_spr > 0){
            if(name != 'id_weight' && name != 'id_height' && name != 'partner_id_weight' && name != 'partner_id_height'){
                $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_reference.php?ref=1&id_spr='+id_spr+'">'+edit_variants+'</a></div>');
            }
        }
        if(name == 'id_weight' || name == 'partner_id_weight'){
            $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_reference.php?ref=12">'+edit_variants+'</a></div>');
        }
        if(name == 'id_height' || name == 'partner_id_height'){
            $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_reference.php?ref=13">'+edit_variants+'</a></div>');
        }
    }

    if(category == 'portrait'){
        if(id_spr != undefined && id_spr > 0){
            $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_reference.php?ref=8&id_spr='+id_spr+'">'+edit_variants+'</a></div>');
        }
    }
    if(category == 'custom'){
        if(id_spr != undefined && id_spr > 0){
            $('#link_for_edit').html('<div style="padding: 5px;"><a class="builder_newpage" target="_blank" href="admin_reference.php?ref=24&page=1&id='+id_spr+'">'+edit_variants+'</a></div>');
        }
    }

	html = $(tooltip).find('.name_for_lang').html();
	$('#mandatory').attr('checked', false);
    $('#couple_box').attr('checked', false);

	$('#wysiwyg_span').html(html);
	$('#mandatory').attr('disabled', false);
    $('#couple_box').attr('disabled', false);

	if($('#element_tooltip').find('.name_for_lang').attr('mandatory') == 1){
		$('#mandatory').attr('checked', true);
		UpdateTooltipText();
	}
	if($('#element_tooltip').find('.name_for_lang').attr('couple') == 1){
		$('#couple_box').attr('checked', true);
	}
	if($('#element_tooltip').find('.name_for_lang').attr('enable_couple') == 0){
		$('#couple_box').attr('disabled', true);
	}
	if($('#element_tooltip').find('.name_for_lang').attr('enable_mandatory') == 0){
		$('#mandatory').attr('disabled', true);
	}

    var position = 0;
	position = DefPos();

	$('input[name=position][value="'+position+'"]').attr('checked','checked');
	$('#wysiwyg_span').find('.mandatory').remove();
	$('#wysiwyg').unbind('click'); 
	$('#wysiwyg').bind('click', function() { UpdateTooltipText(); } );
    $(oW.document.body).html($('#wysiwyg_span').html());
}

function DefPos(){
	var position = '';
	if($('#element_tooltip').find('#preview_1').hasClass('name_for_lang')){
		if($('#element_tooltip').find('#preview_2').hasClass('element')){
			position = 'left';
		}
		if($('#element_tooltip').find('#preview_3').hasClass('element')){
			position = 'top';
		}
	}
	if($('#element_tooltip').find('#preview_1').hasClass('element')){
		// right bottom
		if($('#element_tooltip').find('#preview_2').hasClass('name_for_lang')){
			position = 'right';
		}
		if($('#element_tooltip').find('#preview_3').hasClass('name_for_lang')){
			position = 'bottom';
		}
	}
	return position;
}

function SetPosition(position){
	var text, elem;
	var oldposition;
	if($('#element_tooltip').find('#preview_1').hasClass('name_for_lang')){
		if($('#element_tooltip').find('#preview_2').hasClass('element')){
			oldposition = 'left';
			text = $('#element_tooltip').find('#preview_1').html();
			elem = $('#element_tooltip').find('#preview_2').html();
		}
		if($('#element_tooltip').find('#preview_3').hasClass('element')){
			text = $('#element_tooltip').find('#preview_1').html();
			elem = $('#element_tooltip').find('#preview_3').html();
			oldposition = 'top';
		}
	}
	if($('#element_tooltip').find('#preview_1').hasClass('element')){
		if($('#element_tooltip').find('#preview_2').hasClass('name_for_lang')){
			text = $('#element_tooltip').find('#preview_2').html();
			elem = $('#element_tooltip').find('#preview_1').html();
			oldposition = 'right';
		}
		if($('#element_tooltip').find('#preview_3').hasClass('name_for_lang')){
			text = $('#element_tooltip').find('#preview_3').html();
			elem = $('#element_tooltip').find('#preview_1').html();
			oldposition = 'bottom';
		}
	}
	if(oldposition == position)
		return;
	
	$('#element_tooltip').find('#preview_1').removeClass('element');
	$('#element_tooltip').find('#preview_1').removeClass('name_for_lang');

	$('#element_tooltip').find('#preview_2').removeClass('element');
	$('#element_tooltip').find('#preview_2').removeClass('name_for_lang');
	
	$('#element_tooltip').find('#preview_3').removeClass('element');
	$('#element_tooltip').find('#preview_3').removeClass('name_for_lang');
	
	$('#element_tooltip').find('#preview_1').html('');
	$('#element_tooltip').find('#preview_2').html('');	
	$('#element_tooltip').find('#preview_3').html('');
	
	if(position == 'left'){
		$('#element_tooltip').find('#preview_1').html(text);
		$('#element_tooltip').find('#preview_2').html(elem);		
		
		$('#element_tooltip').find('#preview_1').addClass('name_for_lang');		
		$('#element_tooltip').find('#preview_2').addClass('element');		
	}
	if(position == 'top'){
		$('#element_tooltip').find('#preview_1').html(text);
		$('#element_tooltip').find('#preview_3').html(elem);		
		$('#element_tooltip').find('#preview_1').addClass('name_for_lang');		
		$('#element_tooltip').find('#preview_3').addClass('element');		
	}
	if(position == 'right'){
		$('#element_tooltip').find('#preview_2').html(text);
		$('#element_tooltip').find('#preview_1').html(elem);		
		$('#element_tooltip').find('#preview_2').addClass('name_for_lang');		
		$('#element_tooltip').find('#preview_1').addClass('element');		
	}
	if(position == 'bottom'){
		$('#element_tooltip').find('#preview_3').html(text);
		$('#element_tooltip').find('#preview_1').html(elem);		
		$('#element_tooltip').find('#preview_3').addClass('name_for_lang');		
		$('#element_tooltip').find('#preview_1').addClass('element');		
	}
}

function UpdateTooltipText(){
	html = $('#wysiwyg_span').html();
    html = html.replace(/<br>/i, "");
	//html = html.replace(/<br><\/p>$/i, '</p>');
	
	$('#element_tooltip').find('.name_for_lang').html(html);
	if($('#mandatory').is(':checked')){
		$('#element_tooltip').find('.name_for_lang').attr('mandatory', '1');
		span($('#element_tooltip').find('.name_for_lang'));
	}
	else
		$('#element_tooltip').find('.name_for_lang').attr('mandatory', '0');
}

function SaveText(){
	//var html = $('#wysiwyg_span').html();
	
	var clone = $('#element_tooltip').find('.name_for_lang').clone();
	$(clone).find('.mandatory').remove();
	var html = $(clone).html();
	$(clone).remove();
	
	var mandatory = $('#element_tooltip').find('.name_for_lang').attr('mandatory');
    var couple = $('#couple_box').attr('checked');
	var position = DefPos();
	var name_for_lang = $('#element_tooltip').find('.div_name_for_lang').attr('name_for_lang');
	$.ajax({
		type: "POST",
		cache: true,
		url: 'admin_builder.php',
        data: {'sel':'elem_text', 'name_for_lang':name_for_lang, 'html': html, 'mandatory':mandatory, 'pos':position, 'couple':couple, 'tabs':tabnum},
		success: function (data) {
                $(edit_elem).find('.elem_small_text').html(data);
                $(edit_elem).find('.elem_small_text').attr('mandatory', mandatory);
                span_small_text();
                CancelEditElem();
			}
	});
}


function EnterEditElem(obj){
    
    $('#link_for_edit').html('');

    if($(obj).attr('id_elem') != 21){
        $('#captcha').hide();
    }
    else{
        $('#captcha').show();
    }
	if($(".before_edit_element").css('display') != 'none'){
		$(".before_edit_element").fadeOut(250);
    }

    LocateEditElement(obj);

    ExitEditElem(obj);

    $(edit_block).find(".draw_area").sortable('destroy');
	
    $(oW.document.body).html('');
	edit_elem  = obj;
	
	$(obj).addClass('edit_element');
	$(obj).removeClass('edit_section');
	
	$('.enter_edit_element').find('.edit_text').show();
	$('.enter_edit_element').find('.edit_input').show();
	
	var tooltip = $('#element_tooltip');
	var id = $(obj).attr('id_elem');
	tooltip.show();
	tooltip.find('.yCalloutBody').html('<div align=center><img src="../templates/admin/css/custom/images/28.gif"></div>');			
	$.ajax({
		type: "POST",
		cache: true,
        url: 'admin_builder.php',
		data: 'sel=tooltip&id='+id+'&tabs='+tabnum,
		success: function (data, textStatus) {
			tooltip.find('.yCalloutBody').html(data);
			LoadParam(tooltip);
		}
	});
    $(edit_block).find('.control').fadeOut(100);
}

//function SetElemProp(clas){
function SetElemProp(obj){
	if($(obj).hasClass('edit_text')){
		html = $(edit_elem).find('.edit_text').html();
		
		if($(edit_elem).find('.mandatory').html() != null){
			$('#mandatory').attr('checked', 'checked');
			var tmp = $(edit_elem).find('.edit_text').clone();
			$(tmp).find('.mandatory').remove();
			html = $(tmp).html();
		}
		
		$('#wysiwyg_span').html(html);
		$(oW.document.body).html(html);
		$('#wysiwyg').unbind('click'); 
		$('#wysiwyg').bind('click', function() { ChangeElemProp('text'); } ); 
	}
	if($(obj).hasClass('edit_input')){
		$('input[name=position]').change(function(){
			ChangeElemProp('input');
		});

		if($(edit_elem).find('.edit_input').attr('width')==''){
			$('input[name=position][value="right"]').attr('checked','checked');
		}
		else if($(edit_elem).find('.edit_text').css('float')=='left'){
			$('input[name=position][value="left"]').attr('checked','checked');
		}
		else if($(edit_elem).find(':first').find(':first').hasClass('edit_input') == true){
			$('input[name=position][value="bottom"]').attr('checked','checked');
		}		
		else
			$('input[name=position][value="top"]').attr('checked','checked');
	}
}

function ChangeElemProp(type){
	if(type == 'text'){
		//var html = $("#wysiwyg").html();
		if ($('#mandatory').is(':checked')){
			$(edit_elem).find('.edit_text').html($("#wysiwyg_span").html());
			
			if($(edit_elem).find('.mandatory').html() == null){
				if($(edit_elem).find('.edit_text').find('p').html() != null){
					$(edit_elem).find('.edit_text').find('p:last').append(' <span class="mandatory"><font class="error_msg">*</font>:</span>');
				}
				else
					$(edit_elem).find('.edit_text').append(' <span class="mandatory"><font class="error_msg">*</font>:</span>');
			}
		}
		else{
			$(edit_elem).find('.edit_text').find('.mandatory').remove();
			$(edit_elem).find('.edit_text').html($("#wysiwyg_span").html());
		}
		
	}
	if(type== 'input'){
		var position = $('input[name=position]:checked').val();
		text = $(edit_elem).find('.edit_text');
		input = $(edit_elem).find('.edit_input');		
		if(position == 'top'){
			$(text).css('float','none');
			$(text).attr('align','');
			
			$(input).attr('align','left');
			$(input).css('float','none');
			$(input).css('width','100%');
			
			$(input.parent()).append(text);
			$(input.parent()).append(input);
		}
		if(position == 'bottom'){
			$(text).css('float','none');
			$(text).attr('align','');
			
			$(input).attr('align','left');
			$(input).css('float','none');
			$(input).css('width','100%');
			
			$(input.parent()).append(input);
			$(input.parent()).append(text);
		}
		if(position == 'left'){
			$(text).css('float','left');
			$(text).attr('align','');
			
			$(input).attr('align','right');
			$(input).css('float','none');
			$(input).css('width','100%');
			
			$(input.parent()).append(text);
			$(input.parent()).append(input);
		}
		if(position == 'right'){
			$(text).css('float','right');
			$(text).attr('align','right');
			
			$(input).attr('align','');
			$(input).css('float','left');
			$(input).css('width','');
			
			$(input.parent()).append(input);
			$(input.parent()).append(text);
		} 		
		
	}
}

var attr_before = new Array();

function EnterEditBlock(obj, save){
    
	LocateEditBlock(obj);

    $('#exit_flag').val('1');

	$(".edit_block").fadeOut('slow');
	$(".delete_block").fadeOut('slow');
	
	edit_block = obj;
    $(obj).find(".draw_area").find("li").each(function(){
        if($(this).parent().is(".draw_area")){
            $(this).addClass("edit_section");
            $(this).removeClass("edit_section2");
        }
    });

    ColumnSortDisable();
	
	$(obj).find(".draw_area").sortable({
        items: 'li:not(.edit_section_disable)',
		placeholder: 'ui-state-highlight',
		connectWith: '.draw_area'
	});	
	$(obj).find(".draw_area").disableSelection();
	
	// ��������� "����" �� ������������� ��������, ��������� �������
	$(obj).find(".draw_area").bind('sortstart', function(event, ui) {
		$(obj).find(".ui-state-highlight").css('width',ui.item.width());
		$(obj).find(".ui-state-highlight").css('height',ui.item.height());
        $(obj).find(".ui-state-highlight").css('margin','5px 0');
        $(obj).find(".ui-state-highlight").css('padding','4px 0');
	});
	$(obj).find(".draw_area").disableSelection();
	
	
	$(".select_block").fadeOut('slow');
	$(".add_element").fadeIn('slow');

	$(obj).find(".control").show();
    if(save == 1){
        attr_before = new Array();
        $(obj).find('li').each(function(){
            attr_before.push($(this).attr('id_elem'));
        });
    }
}	

function Cancel(obj){
	$(obj).find('li').each(function(){
		try{
			if(attr_before.indexOf($(this).attr('id_elem')) == -1){
				DeleteElement($(this), 1);
                //alert($(this).html());
			}
		}catch(e){};
	});

	$('#tools').find('.draw_area').find('li').each(function(){
		try{
			if(attr_before.indexOf($(this).attr('id_elem')) != -1){
				AddElementToPage($(this), attr_before.indexOf($(this).attr('id_elem')));			
			}
		}catch(e){};
	});
	
	var count = 0;
	for(i=0;i<attr_before.length;i++){
		id = attr_before[i];
		$(obj).find('.draw_area').append($(obj).find('li[id_elem='+ id +']'));
	}
	ExitEditBlock(edit_block, 0);
}

function CancelEditElem(){
    $('.enter_edit_element').fadeOut(100);
    $('#element_tooltip').fadeOut(100);

    EnterEditBlock(edit_block, 0);
}


function LocateEditBlock(obj){
	//edit_block = obj;
	var width = $(".before_edit_block").width();

	if ($(".before_edit_element").css('display') != 'none'){
		$(".before_edit_element").animate({top:$(obj).offset().top-329}, 250 );
		return;
	}
    if($(obj).offset().top > 0)
        $(".before_edit_element").css('top',$(obj).offset().top-329);

	$(".before_edit_element").fadeIn('slow');
    if(width > 0)
        $(".before_edit_element").width(width);

}
function randomString() {
    return '' + new Date().getTime();
}

function strip_tags (str, allowed_tags) {
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
    }
    str += '';
    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
        // Save HTML tag
        html = matches[key].toString();
        // Is tag not in allowed list? Remove from str!
        allowed = false;
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
    return str;
}

function AddElementToPage(obj, place){
	if(place == -1){
        if(place == -1){
            if($(obj).hasClass('custom')){
                //var id = $(obj).attr('id_elem') + randomString();

                var clone = $(obj).clone();
                var html = $(clone).find('.elem_small_text').html();

                $.ajax({
                    type: "POST",
                    url: 'admin_builder.php',
                    data: 'sel=newcustom&id=1',
                    success: function (data) {

                        arr = data.split('%%nfl%%');
                        var name_for_lang = arr[1];
                        var id_elem = arr[0];

                        $(clone).attr('id_elem', id_elem);
                        $(clone).removeClass('edit_section_no_cursor');
                		$(clone).addClass('edit_section');
                        var img = $(clone).find('.deleteadd');
                        $(clone).find('.info_center').removeClass('info_center').addClass('info');
                        $(clone).find('.info').each(function(){
                            $(this).attr('id_elem', data);
                            Show_ToolTip_Left($(this), $(this).attr('id_elem'));
                        });

                        $(clone).find('.editelement').click(function(){
                            EnterEditElem($(clone));
                        });
                        
                        img.unbind('click');
                        img.click(function(){ DeleteElement($(this).parents('li'), 0); });

                        img.attr('src','../templates/admin/images/controls/icn_delete.gif');

                        $(edit_block).find('.draw_area').append($(clone));
                        $(clone).find('.div_editelem').show();
                        

                        $.ajax({
                            type: "POST",
                            cache: true,
                            url: 'admin_builder.php',
                            data: 'sel=elem_text&name_for_lang='+name_for_lang+ '&html='+html + '&mandatory=0&pos=left',
                            success: function (data) {
                            }
                        });
                    }
                });
                return;
            }
        }


		$(obj).hide(250, function(){ 
            $(obj).removeClass('edit_section_no_cursor');
			$(obj).addClass('edit_section');
			
			var img = $(obj).find('.deleteadd');

			$(obj).find('.info_center').removeClass('info_center').addClass('info');
			$(obj).find('.info').each(function(){
				Show_ToolTip_Left($(this), $(this).attr('id_elem'));
			});

			img.unbind('click');
            img.click(function(){ DeleteElement($(this).parents('li'), 0); });
            img.attr('src','../templates/admin/images/controls/icn_delete.gif');
			$(edit_block).find('.draw_area').append($(obj));
            $(obj).find('.div_editelem').show();
			$(obj).show(250);
		});
	}
	else{
	        $(obj).removeClass('edit_section_no_cursor');
		$(obj).addClass('edit_section');
			
		var img = $(obj).find('.deleteadd');
		$(obj).find('.info_center').removeClass('info_center').addClass('info');
		$(obj).find('.info').each(function(){
			Show_ToolTip_Left($(this), $(this).attr('id_elem'));
		});

		img.unbind('click');
                img.click(function(){ DeleteElement($(this).parents('li'), 0); });
        img.attr('src','../templates/admin/images/controls/icn_delete.gif');
		if(place == 0)
			$(obj).insertBefore($(edit_block).find('.draw_area').find('li:eq('+place+')'));
		else{
            if($(edit_block).find('.draw_area').find('li:eq('+place+')').html() == null){
                place--;
            }
			$(obj).insertAfter($(edit_block).find('.draw_area').find('li:eq('+place+')'));
        }
		$(obj).show(250);
	}

}

$(function() {
    $tabs = $('#tabs').tabs({ selected: tabnum });
    //if($('#tools-9').html())
        $tabs_tools = $('#tools').tabs({ selected: 6 });
    //else
    //    $tabs_tools = $('#tools').tabs({ selected: 3 });

    $('#tabs').bind( "tabsselect", function(event, ui) {
        if($(ui.panel).parent().parent().hasClass('before_edit_element'))
            return;

        if($('#exit_flag').val() == '1'){
            if(!confirm(exit_page)){
                return false;
            }
            $('#exit_flag').val('0');
        }
        $('#tabs-1').html(pls_wait);
        $('#tabs-2').html(pls_wait);
        $('#tabs-3').html(pls_wait);
        $('#tabs-4').html(pls_wait);
        document.location.href='admin_builder.php?tabs='+ui.index;
    });
	if(tabnum == 0){
		$(".column").sortable({
			placeholder: 'ui-state-highlight',
			connectWith: '.column',
			stop: function(event, ui) { PageNumbers(); },
			//cancel: 'div:not(.first_page)'
			items: '.portlet:not(.first_page)'
		});
        $(".column").bind('sortstart', function(event, ui) {
            $(".column").find(".ui-state-highlight").css('width',ui.item.width());
            $(".column").find(".ui-state-highlight").css('height',ui.item.height());
        });
    }
	
	$(".portlet").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
		.find(".portlet-header")
			.addClass("ui-widget-header ui-corner-all")
			.prepend('<span class="ui-icon ui-icon-plusthick"></span>')
			.end()
		.find(".portlet-content");
	$(".portlet-header .ui-icon").click(function() {
		$(this).toggleClass("ui-icon-minusthick");
		$(this).parents(".portlet:first").find(".portlet-content").toggle();
	});

	if(tabnum == 0)
		PageNumbersSimple();

	if(tabnum == 0){
		$(".portlet-header").each(function(){
			$(this).find("img").click(function(){
				EditHeader($(this).parents(".portlet"));
			});
		});
	}

	$('.elements').each(function(){
		$(this).click(function(){
			AddElementToPage(this, -1);
		});
	});

	$('.info').each(function(){
		Show_ToolTip_Left($(this), $(this).attr('id_elem'));
	});
	$('.info_center').each(function(){
		Show_ToolTip($(this), $(this).attr('id_elem'));
	});


	$('.toolbox').find('.deleteadd').each(function(){
			$(this).click(function(){
                AddElementToPage($(this).parents('li'), -1);
			});
	});

	$('.portlet-content').find('.deleteadd').each(function(){
		$(this).click(function(){
			//DeleteElement($(this).parent().parent().parent(), 0); 
			//DeleteElement($(this).parentsUntil('.edit_section').parent(), 0);
            DeleteElement($(this).parents('li'), 0);
		});
	});
	$('.portlet-content').find('.editelement').each(function(){
		$(this).click(function(){
            EnterEditElem($(this).parents('li'));
		});	
	});
	$('.toolbox').find('.editelement').each(function(){
		$(this).click(function(){
            EnterEditElem($(this).parents('li'));
		});
	});
	span_small_text();
    if(lang_collapse){
        $(".ui-icon-plusthick").attr("title", lang_collapse);
    }
    $(".ui-icon-plusthick").css("cursor", "pointer");
});
	
	
function SelectUserTypes (section, id_usertypes, destination) {
     str = "sec=" + section + "&sel=usertypes&id_usertypes="+id_usertypes;
	$.ajax({
		url: '../location.php',
		data: str,
		success: function (data, textStatus) {
			$(destination).html(data);
		}
	});
}

function Clear() {
	for ( var i=1; i<=subtype_count;i++) {
    	 if (document.getElementById('id_looking_user_subtypes['+i+']')) {
                 document.getElementById('id_looking_user_subtypes['+i+']').checked = false;
            }
    }
}
	
function Show_ToolTip(element, id){
	var tooltip = $('#help_tooltip');
	tooltip.hide();
	$(element).unbind('mouseover');
	$(element).unbind('mouseout');

	$(element).mouseover(function(){
		if(tooltip.css('display') == 'none')
		{
			tooltip.find('.yCalloutBody').html('<div align=center><img src="../templates/admin/css/custom/images/28.gif"></div>');
			$.ajax({
				type: "POST",
                url: 'admin_builder.php',
				data: 'sel=tooltip&id='+id+'&tabs='+tabnum,
				success: function (data) {
					tooltip.find('.yCalloutBody').html(data);
					span($(tooltip).find('.name_for_lang'));
				}
			});

			var position = $(element).offset();
			tooltip.css({left:position.left-284, top:position.top+20});
			tooltip.show();
		}
	}).mouseout(function(){
		if(tooltip.css('display') != 'none')
		{
			tooltip.hide();
		}
	});
}


function Show_ToolTip_Left(element, id){
	var tooltip = $('#help_tooltip_left');
	tooltip.hide();
	$(element).unbind('mouseover');
	$(element).unbind('mouseout');
	$(element).mouseover(function(){
		if(tooltip.css('display') == 'none')
		{
			tooltip.find('.yCalloutBody').html('<div align=center><img src="../templates/admin/css/custom/images/28.gif"></div>');			
			$.ajax({
				type: "POST",
				cache: true,
				url: 'admin_builder.php',
				data: 'sel=tooltip&id='+id+'&tabs='+tabnum,
				success: function (data, textStatus) {
					tooltip.find('.yCalloutBody').html(data);
					span($(tooltip).find('.name_for_lang'));
				}
			});

			var position = $(element).offset();
			//tooltip.css({left:position.left-31, top:position.top+20});
            tooltip.css({left:position.left-34, top:position.top+16});
            //alert(position.left-284);
			tooltip.show();
		}
	}).mouseout(function(){
		if(tooltip.css('display') != 'none')
		{
			tooltip.hide();
		}
	});


}

function entity(s) {
    s = s.replace(/&gt;/g, '>');
    s = s.replace(/&lt;/g, '<');
    s = s.replace(/&#039;/g, "'");
    return s;
}

function SaveCaptcha(){
    $('#captcha_ok').html(captcha_saving);
	ShowAjaxError(captcha_saving, '', 'info');
    var type = $('input[name=captcha]:checked').val();
    var public_key = $('#captcha_public_key').val();
    var private_key = $('#captcha_private_key').val();

    $.ajax({
        type: "POST",
        cache: false,
        url: 'admin_builder.php',
        data: 'sel=captcha&type='+type+'&public='+public_key+'&private='+private_key,
        success: function (data) {
			ShowAjaxError(data, '', 'info');
            $('#captcha_ok').html(data);

            tooltip = $('#element_tooltip');
            tooltip.find('.yCalloutBody').html('<div align=center><img src="../templates/admin/css/custom/images/28.gif"></div>');
            $.ajax({
                type: "POST",
                cache: false,
                url: 'admin_builder.php',
                data: 'sel=tooltip&id=21&tabs=0',
                success: function (data) {
					tooltip.find('.yCalloutBody').html(data);
					LoadParam(tooltip);
				}
            });
        }
    });
}