// JavaScript Document

jQuery (document).ready (function  () {
        jQuery ('#smallNoticePanelID').draggable ({
                handle: 'div', 
                revert: true
        });
        
        jQuery ('.shellDiscussPanels span').bind ({
        	'mouseover': function () {
	        	discussSpanHover (this, true);
	        }, 'mouseout': function () {
	        	discussSpanHover (this, false);
	        }
        });
        
        // Hovera na tbl-tata ...
        jQuery ('.effMarkerF, .effMarkerS').mouseover ( function () {
		jQuery (this).addClass ( 'trActiveTblRow' );
	});
	jQuery ('.effMarkerF, .effMarkerS').mouseout ( function () {
		jQuery (this).removeClass ( 'trActiveTblRow' );
	});
});

function refreshImages() {
    var search="?"+(new Date()).getTime();
    for(var i=0;i<document.images.length;document.images[i++].src+=search);
}

function jqescape(str)
{
    return str.replace(/[#;&,\.\+\*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\$&');
}

function changeUserType(o) {
    sendXMLHttpGetRequest('generate_category_data','/editprofile/userTypeAjax/id/'+o);
}


function changePassPanel() {
    var divId = document.getElementById('passPanel');
    var linkId = document.getElementById('changePassLink');

    divId.style.display = 'block';
    linkId.style.display = 'none';

}

function enterOwnCat() {
    var b = document.getElementById('enter_own_cat_button');
    var p = document.getElementById('enter_own_cat_panel');

    b.style.display = 'none';
    p.style.display = 'block';
}

function userAudienceChoice(mode) {
    var a = document.getElementById('user_audience_panel');
    var t = document.getElementById('talent_category');
    var c = document.getElementById('cancel_talents');

    if (mode == 'on') {
        a.style.display = 'none';
        t.style.display = 'block';
        c.style.display = 'block';
    }
    else if (mode == 'off') {
        a.style.display = 'block';
        t.style.display = 'none';
        c.style.display = 'none';
    }
}

mode = 'down';
function colapseCatPanel(img_path)
{
    var p = document.getElementById('user_cateogory_list');
    var i = document.getElementById('arrow_id');

    tmp = 0;

    if (mode == 'down')
    {
        p.style.display = 'block';
        i.src = img_path+'arrow_up.gif';
        mode = 'up';
        tmp = 1;
    }
    else if (mode == 'up' && tmp == 0)
    {
        p.style.display = 'none';
        i.src = img_path+'arrow_down.gif';
        mode = 'down';
    }


}
cmode = 'minus';
function showParentCatContent(parent_id, link_id)
{
    var p = document.getElementById(parent_id)
    var l = document.getElementById(link_id);

    tmp = 0;

    if (cmode == 'minus')
    {
        p.style.display = 'none';
        l.innerHTML = '+';
        cmode = 'plus';
        tmp = 1;
    }
    else if (cmode == 'plus' && tmp == 0)
    {
        p.style.display = 'block';
        l.innerHTML = '-';
        cmode = 'minus';
    }
}

function colapseOwnCats()
{
    var add = document.getElementById('enter_own_cat_button');
    var own = document.getElementById('enter_own_cat_panel');

    add.style.display = 'none';
    own.style.display = 'block';
}


function showNoticePanel (msg_) {
        jQuery ('#smallNoticePanelID span.noticeContent').html (msg_);
        jQuery ('#smallNoticePanelID').effect ('pulsate');
}
function closeNoticePanel () {
        jQuery ('#smallNoticePanelID').hide ();
        jQuery ('#smallNoticePanelID span.noticeContent').html ('');
}

function confirmNewCategory()
{
    if ($('#new_category').val())
    {
        sendXMLHttpPostRequest('saveProfileId','formEditProfile','/editprofile/addNewCategoryAjax');
    }
}

function showNewCategory(catvalue, catid)
{
    $('#add_new_category').show();
    $('#your_cat_id').attr('value',catid);
    $('#parent_cat_id').attr('value', catvalue);
    $('#new_category').attr('value', '');
}

function hideShowCats()
{
    cat_id = $('#your_cat_id').val();
    $('#add_new_category').hide();
    $('#cat_'+cat_id).show();
}



function uploadAvatar()
{
    if ($('#avatar').val())
    {
        $('#add_avatar').attr('value','1');
        $('#del_avatar').attr('value','0');
        $('#formEditProfile').submit();
        $('#uploader').show();
    }
}

function deleteAvatar()
{
    $('#add_avatar').attr('value','0');
    $('#del_avatar').attr('value','1');
    $('#formEditProfile').submit();
    $('#uploader').show();
}

function checkFocused(){
var f = document.forms;


function setFocusedForm(fe,ff){
 var f1 = document.forms;
 var formID = '';
 for(var k=0; k < f1.length; k++){
  var el1 = document.forms[k].elements;
  for(var l=0; l < el1.length; l++){
   if ((el1[l].name == fe) && (el1[l].form.id == ff)) {
        //focusedForm = document.forms[k].name;
        //submitFocusedForm(document.forms[k].name);
    formID = el1[l].form.id;
   }
  }
 }

 if (formID != '') {
  submitFocusedForm(formID);
 }
}



function KeyCheck(e) {
    var KeyID = (window.event) ? event.keyCode : e.keyCode;
    var focusedElement = this.name;
    var focusedForm = this.form.id;

    switch(KeyID)
    {
      case 13:
       setFocusedForm(focusedElement,focusedForm);
      break;
    }
    }

    for(var j=0; j < f.length; j++){
    var el = document.forms[j].elements;
    for(var i=0; i < el.length; i++){
    if (el[i].type == 'text') {
      el[i].onkeydown = KeyCheck;
    }
    }
    }
}

function submitFocusedForm(formName){
         switch (formName)
         {
//                case "registFormId":
//                        $('#registFormId').sumbit();
//                        break;
//                case "loginFormId":
//                    $('#loginFormId').submit();
//                    break;
         }

}

function closeChangePassword()
{
    $('#curr_pass').attr('value','');
    $('#new_pass').attr('value','');
    $('#confirm_new_pass').attr('value','');
    $('#passPanel').hide();
    $('#change_pass_link').show();
}

function confirmNewCategoryNotice()
{
    if ($('#user_type_notice_name').val())
    {
        sendXMLHttpPostRequest('add_new_category_notice','formEditProfile','/editprofile/saveCategoryNoticeAjax');
    }
}

function cleaner(obj_)
{
    obj_.value = obj_.value.replace(/[^0-9.]/g, '');
}

function cleanerPhone(obj_)
{
    obj_.value = obj_.value.replace(/[^0-9+-./() ]/g, '');
}

function generateUserGatewayCategories(cat, parent)
{
    $('#user_categories_block').show();
    sendXMLHttpGetRequest('save_chosen_cat','/registration/deleteCategoryAjax/cat/'+cat+'/parent/'+parent);
}

function initEditProfileCheckers()
{
	if ($('#user_details_visual_birth_date_profile_checker').is(':checked') == true)
	{
	        $('#user_details_visual_birth_date_profile').attr('value', 1);
	}
	 else
	 {
	        $('#user_details_visual_birth_date_profile').attr('value',0);
	 }
	 
	 if ($('#user_use_message_id').is(':checked') == true)
	{
	        $('#user_use_message_name').attr('value', 1);
	}
	 else
	 {
	        $('#user_use_message_name').attr('value',0);
	 }
}

function showUploadMedia(visual)
{
    if (visual == 1)
    {
        $('#upload_panel').show();
        $('#add_link').hide();
        $('#add_gallery').hide();
    }
    else if (visual == 2)
    {
        $('#media_name').val('');
        $('#media_description').val('');
        $('#media_file').val('');
        $('#media_type').val(0);
        $('#media_gallery_name').val('');
        $('#media_gallery_description').val('');
        $('#upload_panel').hide();
        $('#media_video_row').hide();
        $('#media_file_row').hide();
        $('#upload_photo_gallery').hide();
        $('#add_link').show();
        $('#add_gallery').show();
    }
    else if (visual == 3)
    {
        $('#upload_photo_gallery').show();
        $('#add_link').hide();
        $('#add_gallery').hide();
    }
}

function showMediaVideoField()
{
    if ($('#media_type_options').val() == 1)
    {
        $('#media_video_row').show();
        $('#video_or_file').val(1);
        $('#media_file_row').hide();
    }
    else
    {
        $('#video_or_file').val(2);
        $('#media_video_row').hide();
        $('#media_file_row').show();
    }
}

function uploadMedia()
{
    var msg = '';
    var mtype = 0;
    var mgall = 0;

    if (!$('#media_name').val())
    {
        msg += 'Непопълнено име на медия при опит за добавяне!<br />';
    }

    if (!$('#media_type_options').val())
    {
        msg += 'Избери тип на медия!<br />';
    }
    else
    {
        var tval = $('#media_type_options').val();
       
        if (tval == 2) mtype = 4;
        else if (tval > 2 && tval != 3 && tval <=8)
        {
            mtype = 2;

            var tmp_op = 0;

            for (i=4; i<=8; i++)
            {
                tmp_op++;
                if (tval == i)
                {
                    mgall = tmp_op;
                }
            }

            if (mgall > 0)
                $('#media_gallery_id').val(mgall);
        }
        else mtype = tval;

        $('#media_type').val(mtype);
    }

    if ($('#video_or_file').val() == 1)
    {
        if (!$('#media_video_url').val())
        {
            msg += 'Непопълнено поле на видео линк при опит за добавяне!<br />';
        }
    }

    if ($('#video_or_file').val() == 2)
    {
        if (!$('#media_file').val())
        {
            msg += 'Няма посочен файл при опит за добавяне на медия!<br />';
        }
    }

    if (!msg)
    {
        $('#upload_act').val(1);
        $('#formUploadMediaProfile').submit();
    }
    else
    {
        systemMSG.showError(msg);
    }
}

function selectUnselectMedia()
{
        $("#media_all").click(function()
        {
            var checked_status = this.checked;
            $("input[name=media_ids[]]").each(function()
            {
                this.checked = checked_status;
            });
        });
}

function newPhotoAlbum()
{
    var msg = '';

    if (!$('#media_gallery_name').val())
    {
        msg += 'Непопълнено име на фото албум при опит за добавяне!<br />';
    }

    if (!msg)
    {
        $('#new_photo_album').val(1);
        sendXMLHttpPostRequest('new_photos','formUploadMediaProfile','/upload/saveNewPhotoAlbumAjax');
    }
    else
    {
        systemMSG.showError(msg);
    }
}

function reloadJCarouselContainers(width, page)
{
    var w = parseInt(width);

    $(document).ready(function () {
    	if (page == 'profile') {
	         $('#mycarouselPhoto').width(w);
	         $('#mycarouselVideo').width(w);
	         $('#mycarouselAudio').width(w);
	         $('#mycarouselText').width(w);
    	}
    	else if (page == 'viewandrate') {
    		$('#mycarouselUserMediaType').width(w);
    	}
     });
}

function loadDiscussionPanel(icon_path, msg, source)
{
   var inner_html = '';

    inner_html = "<div style='margin-top:-16px;'><img width='40' height='40' src='"+icon_path+"' /></div><div style='margin-left: 55px; margin-top: -30px;'>"+msg+"</div>";


    $('#curr_loaded_media_name').html(inner_html);
    $('#mediaViewerContainerID').html('<img src="'+source+'" style="height: 368px; border: none;" />');
    $('#init_discussion').val(1);
}

function getMediaName(controller, media_id)
{
    var param_str = '';

    //media name
    $.getJSON('/'+controller+'/jsonMediaNameAjax/id/'+media_id,
     function(data)
     {

       $.each(data, function(key, value)
       {
            param_str += value;
       });

        $('#curr_loaded_media_name').html(param_str);

     });
}

function goToViewAndRateMedia(err_msg)
{
    var media_id = parseInt($('#currMediaId').val());
    var init_discussion = parseInt($('#init_discussion').val());

    if (media_id && init_discussion == 0)
    {
        window.location='/viewandrate/index/id/'+media_id;
    }
    else if (err_msg != null)
    {
        systemMSG.showError(err_msg);
    }
}

function selectMedia(source, type, media_id, controller)
{
    var image_source = '';
    var c = parseInt(controller);
    var controller_name = '';

    if (c)
    {
        switch (c)
        {
            case 1:

                controller_name = 'profile';
                $('#currMediaId').val(parseInt(media_id));

                break;

            case 2:

                controller_name = 'viewandrate';

                break;

            case 3:

                controller_name = 'slideshow';

                break;

        }
    }
if (type != 2) {
	$(".mediaViewerContainer").css('text-align', 'left');
} else {
	$(".mediaViewerContainer").css('text-align', 'center');
}
    $('#media_slideshow').hide();
    $('#mediaViewerContainerID').show();
    $('#init_discussion').val(0);

    if (controller_name != '')
    {
        getMediaName(controller_name, media_id);
    }

    if (type == 1 || type == 4 || type == 5)
    {
        $('#mediaViewerContainerID').html('');

        if (type == 4)
        {
            image_source = '&image=/core/applications/layout/img/category-larger-audio.jpg';
        }
        else if (type == 1)
        {
            image_source = '&image=/core/applications/layout/img/category-larger-video.jpg';
        }
        
        var so = new SWFObject('/core/applications/layout/scripts/flash/player.swf','mpl','612','368','9');
            so.addParam('allowfullscreen','true');
            so.addParam("flashvars","file="+source+"&autostart=false"+image_source);
            so.write('mediaViewerContainerID');
    }
    else if (type == 2)
    {
        $('#mediaViewerContainerID').show();
        $('#mediaViewerContainerID').html('<img src="'+source+'" style="height: 368px; border: none;" />');
    }
    else if (type == 3)
    {
        $('#mediaViewerContainerID').html('');
        sendXMLHttpGetRequest('mediaViewerContainerID','/'+controller_name+'/readTextAjax/id/'+media_id);
    }

    if (c == 1)
    	sendXMLHttpGetRequest('media_visit','/'+controller_name+'/visitAjax/id/'+media_id);
    	
    checkMediaIsVoted();
    
}

function openSlideshowWindow(media_id, controller)
{
    var media = parseInt(media_id);
    var inner_html = '';
    var fd_inner_html = '';
    var controller_name = '';
    var c = parseInt(controller);
    var param_str = '';
     
    $('#mediaViewerContainerID').hide();
    $('#media_slideshow').show();
    $('#media_slideshow').html(' ');

    if (c == 1)
    {
        controller_name = 'profile';
        $('#currMediaId').val(media);
    }
    else if (c == 2)
    {
        controller_name = 'viewandrate';
    }

    $.getJSON('/'+controller_name+'/slideshowAjax/id/'+media,

     function(data)
     {

       $.each(data, function(i,v)
       {
            if (v.source != null)
            {
                inner_html += '<img src="'+v.source+'" alt="'+v.file_descr+'"/>';
            }

            if (v.media_name != null)
            {
                param_str += v.media_name;
            }

       });

        $('#curr_loaded_media_name').html(param_str);
        $('#media_slideshow').html(inner_html);
        $('#media_slideshow').galleria();
        
     });

     if (c == 1)
     	sendXMLHttpGetRequest('media_visit','/'+controller_name+'/visitAjax/id/'+media);
     	
     checkMediaIsVoted();
}

 function setYourVoting (currentVot_, page)
 {
     var vote = parseInt(currentVot_);
     
     if (page == 'viewandrate') {
         var media_id = parseInt($('#currentMediaID').val());
     }
     else if (page == 'profile') {
         var media_id = parseInt($('#currMediaId').val());
     }
     
     
     var user_rating = parseInt($('#ratingID').val());
     var ulog = parseInt($('#ulog').val());
     
    if (currentVot_ == 1)
    {
        if (user_rating == 0 && ulog > 0)
        {
            $('#subVotingTitleID').show();
            $('#subVotingPanelID').show();
            
            if (page == 'profile')
            	$('#subVotingPanelID').html(' ');
          
            for (i=2; i<6; i++)
            	$('.votingPanel a.v-'+i).toggleClass('v-'+i+'d');	
            
          
            
            if (page == 'profile')
            {
            	sendXMLHttpGetRequest('subVotingPanelID','/'+page+'/cratingsAjax');
            }
        }
        else
        {        	
            sendXMLHttpGetRequest('subVotingPanelID','/'+page+'/voteAjax/id/'+vote+'/media/'+media_id);
        }
    }
    else
    {
    	
        $('.votingPanel a.v-1').removeClass ('v-1a');
        $('#subVotingTitleID').hide();
        $('#subVotingPanelID').hide();
        sendXMLHttpGetRequest('subVotingPanelID','/'+page+'/voteAjax/id/'+vote+'/media/'+media_id);
    }
}

function setCensVote(currentVot_,page)
{
    var vote = parseInt(currentVot_);
    var media_id = parseInt($('#currentMediaID').val());

    if ($('.crating_id').attr('checked', true))
    {
         sendXMLHttpGetRequest('subVotingPanelID','/'+page+'/voteAjax/id/'+vote+'/media/'+media_id);
    }
}

function censuredMedia (bool_) {
	if (bool_) {
		jQuery ('#censuredMedia').show ();
		jQuery ('.mediaViewerSkin span').hide ();
	} else {
		jQuery ('#censuredMedia').hide ();
		jQuery ('.mediaViewerSkin span').show ();
	}
}

function showCommentForm(param)
{
    var p = parseInt(param);
    var nc = document.getElementById('noCommentID');

    if (nc)
    {
        if (p == 1)
        {
            $('#noCommentID').hide();
        }
        else if (p == 2)
        {
            $('#noCommentID').show();
        }
    }

    if (p == 1)
    {
        $('#comment').val(' ');
        $('#comment_button').hide();
        $('#commentForm').show();
    }
    else if (p == 2)
    {
        $('#comment_button').show();
        $('#commentForm').hide();
    }
}

function countCommentChar()
{
    if ($("#comment").val().length > 255)
    {
        $("#comment").val($("#comment").val().substring(0, 255));
    }
    else
    {
        $("#comment_char_info").html((255 - $("#comment").val().length) + ' оставащи символа');
    }
}

function discussSpanHover (obj_, bool_) {
	if (bool_) {
		jQuery (obj_).addClass ('discussSpanActive');
	} else {
		jQuery (obj_).removeClass ('discussSpanActive');
	}
}

function showDiscussionComment(media_id) {
	var m = parseInt(media_id);
	
	if (m && $('#media_discussion_set:checked').val()) {
	        $('#comment_panel').show();
	}    
}

function cleanDiscussionComment() {
	$('#comment').html(' ');
	$('#comment_panel').hide();
}

function initDiscussionButton(m) {
    var md = parseInt(m);

    $('#media_discussion_id').val(md);
    $('#comment_panel').show();
    $('#media_discussion_set').attr('disabled','disabled');
}

function lockDiscussionButtons(ratings) {
	if ($.isArray(ratings)) {
	        for (i=0; i<ratings.length; i++) {
	            $('#rating_'+ratings[i]).attr('disabled','disabled');
	        }
	    }
}


function BackToMyWebsite() {
	$(window.location).attr('href', '/profile/index');
	return;
}

function checkMediaIsVoted()
{
    var media = parseInt($('#currMediaId').val());
    var vote = parseInt($('#ratingID').val());
    
    if (media) 
    {
        sendXMLHttpGetRequest('generate_voting','/profile/isMediaVotedAjax/id/'+media);
    }
}

// Setvam v URI-to jump-a na paginga ...
function paging_custom_jump ( obj ) {
	int_page_ = jQuery ( obj ).parent().find ( 'input' ).val ();
	url_ = window.location.toString ();
	
	if (url_.search (/\/p\/\w*/) > -1) {
		url_ = url_.replace (/\/p\/\w*/, ('/p/' + int_page_));
	} else if (url_.search (/\/p$/) > -1) {
		url_ = url_.replace (/\/p$/, ('/p/' + int_page_));
	} else {
		url_ = (url_ + (url_.substr (-1, 1) == '/' ? '' : '/') + 'p/' + int_page_);
	}

	// Komentiraniq kod se otnasq samo ako NE se polzva mod rewrite ...
//	if ( url_.search ( /&p=[1-9]*/ ) > -1 ) {
//		url_ = url_.replace ( /&p=[0-9]*/, '&p=' + int_page_ );
//	} else if (url_.search ( /\?p=[1-9]*/ ) > -1) {
//		url_ = url_.replace ( /\?p=[0-9]*/, '?p=' + int_page_ );
//	} else {
//		url_ = url_ + '&p=' + int_page_;
//	}

	window.location = url_;
}
// Setvam v URI-to perpage-a na paginga ...
function paging_custom_pp ( obj ) {
	pp_ = jQuery ( obj ).val ();
	url_ = window.location.toString ();
      
	
        if (url_.search (/\/pp\/\w*/) > -1) {
                url_ = url_.replace (/\/pp\/\w*/, ('/pp/' + pp_));
        } else if (url_.search (/\/pp$/) > -1) {
                url_ = url_.replace (/\/pp$/, ('/pp/' + pp_));
        } else {
                url_ = (url_ + (url_.substr (-1, 1) == '/' ? '' : '/') + 'pp/' + pp_);
        }
	
	// Komentiraniq kod se otnasq samo ako NE se polzva mod rewrite ...
//	if ( url_.search ( /&pp=[1-9]*/ ) > -1 ) {
//		url_ = url_.replace ( /&pp=[0-9]*/, ( '&pp=' + pp_ ) );
//	} else if ( url_.search ( /\?pp=[1-9]*/ ) > -1) {
//		url_ = url_.replace ( /\?pp=[0-9]*/, ( '?pp=' + pp_ ) );
//	} else {
//		url_ = ( url_ + '?pp=' + pp_ );
//	}

	window.location = url_;
}

function bytesFormat(bytes) {
	var result = 0;
	var type;

	if (bytes > 1048576) { 
		result = (bytes / 1048576);
		type = "MB";
	} else if (bytes > 1024) { 
		result = (bytes / 1024);
		type = "KB";
	} else { 
		result = bytes;
	}

	result = (parseFloat(result)).toFixed(2);
	return result + " " + type;
}


this.tooltip = function(){
		xOffset = 10;
		yOffset = 20;		
	$(".tooltip").hover(function(e){
		this.t = this.title;
		this.title = "";
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.css("z-index", 100)
			.fadeIn("fast")
			.html(this.t);
    },
	function(){
		this.title = this.t;
		$("#tooltip").html('').hide();
    });
	$(".tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};
$(document).ready(function(){
	tooltip();
});

function befan(id) {
	$.ajax({
		url: '/fans/befanAjax/id/' + id,
		success: function(data) {
			$('#fan').html('ti si fan');
		}
	});
}

function admViewMedia(mid, pointer)
{
    var m = parseInt(mid);
    var p = parseInt(pointer);

    switch (p)
    {
        case 1:
            window.location='/viewandrate/index/id/'+m;
            break;
        case 2:
            window.location='/discussion/index/id/'+m;
            break;
    }
}

function admMedia(mid, pointer, page_type)
{
    var m = parseInt(mid);
    var p = parseInt(pointer);
    var pt = parseInt(page_type);
    var controller = '';
    var action = '';
    
    switch (pt)
    {
        case 1:
            controller = 'media';
            action = 'mediaActionRowAjax';
            break;
        case 2:
            controller = 'viewandrate';
            action = 'adminOptionsAjax';
            break;
        case 3:
            controller = 'discussion';
            action = 'adminOptionsAjax';
            break;
    }

    if (m && p && pt)
    {
        if (p == 3)
        {
            $("#dialog-confirm p").show();
		$("#dialog-confirm").dialog({
			resizable: false,
			height:160,
			modal: true,
			buttons: {
				"Не": function() {
					$("#dialog-confirm p").hide();
					$( this ).dialog( "close" );
				},
				"Да": function() {
					$("#dialog-confirm p").hide();
					$( this ).dialog( "close" );
                                         sendXMLHttpGetRequest('media_generate','/'+controller+'/'+action+'/id/'+m+'/p/'+p);
				}
			}
		});
        }
        else
        {
            sendXMLHttpGetRequest('media_generate','/'+controller+'/'+action+'/id/'+m+'/p/'+p);
        }
    }
}

function blockUserMedia(userId)
{
    var user_id = parseInt(userId);

    $("#dialog_user_block_confirm p").show();
        $("#dialog_user_block_confirm").dialog({
                resizable: false,
                height:160,
                modal: true,
                buttons: {
                        "Не": function() {
                                $("#dialog_user_block_confirm p").hide();
                                $( this ).dialog( "close" );
                        },
                        "Да": function() {
                                $("#dialog_user_block_confirm p").hide();
                                $( this ).dialog( "close" );
                                $.ajax({
                                  url: "/media/blockUserAjax/id/"+user_id,
                                  success: function(html){
                                    $('#media_generate').html(html);
                                  }
                                });
                         }
                }
        });
}

function returnToDiscussion(mediaId)
{
    var media_id = parseInt(mediaId);

    if (media_id) {
        $.ajax({
          url: "/media/returnToDiscussionAjax/mid/"+media_id,
          success: function(html){
            $('#media_generate').html(html);
          }
        });
    }
}

function adminCensComments(errMsg)
{
   var n = $("input:checked").length;

   if (n == 0)
   {
       systemMSG.showError (errMsg);
   }
   else
   {
       $('#userCommentFormID').submit();
   }
}

function showCommentsPanel(action)
{
    var act = parseInt(action);
    var ajax_comments = parseInt($('#set_generate_comment').val());

    if (act == 1)
    {
        $('#commentsRows').show();

        if (ajax_comments == 1)
        {
            $('#ajaxComments').show();
        }

        $('#commentsShowLink').hide();
        $('#commentsHideLink').show();
    }
    else if (act == 2)
    {
        $('#commentsRows').hide();
        
        if (ajax_comments == 1)
        {
            $('#ajaxComments').hide();
        }

        $('#commentsShowLink').show();
        $('#commentsHideLink').hide();
    }
}

function addUserTypeNotice(titleWindow, userTypeId)
{
    var type = parseInt(userTypeId);

    $(document).ready(function()
    {
        $('#dialog1').show();
        $('#user_type_id').val(0);
        $('#user_type_notice_name').val('');
        $('#user_type_add_name').html(' ');

        sendXMLHttpGetRequest('generate_category_data','/editprofile/addUserTypeNoticeAjax/id/'+type+'/p/1');
        
        $("#add_new_category_notice").dialog(
        {
                resizable: false,
                title: titleWindow,
                width:450,
                height:180,
                modal: true,
                buttons:
                {
                        "Откажи": function()
                        {
                                $("#dialog1").hide();
                                $( this ).dialog( "close" );
                        },
                        "Потвърди": function() 
                        {
                            if ($('#user_type_notice_name').val())
                            {
                                sendXMLHttpPostRequest('generate_category_data','formUserTypeNotice','/editprofile/saveCategoryNoticeAjax');
                            }
                            $("#dialog1").hide();
                            $( this ).dialog( "close" );
                        }
                }
        });
    });
}

function delUserTypeNotice(windowTitle, url, userTypeId)
{
    var type = parseInt(userTypeId);
    
    $(document).ready(function()
    {
        $('#dialog2').show();
        $('#notice_category_warning').html(' ');
        $('#del_user_type_add_name').html(' ');
        
        sendXMLHttpGetRequest('generate_category_data','/editprofile/addUserTypeNoticeAjax/id/'+type+'/p/2');

        $("#del_category_notice").dialog(
        {
                resizable: false,
                title: windowTitle,
                width:320,
                height:180,
                modal: true,
                buttons:
                {
                        "Откажи": function()
                        {
                                $("#dialog2").hide();
                                $( this ).dialog( "close" );
                        },
                        "Потвърди": function()
                        {
                            $("#dialog2").hide();
                            $( this ).dialog( "close" );
                            sendXMLHttpGetRequest('save_chosen_cat', url);
                        }
                }
        });
    });
}

function delAddedUserType(windowTitle, url, userTypeId, ParentAddTypeId)
{
     var type = parseInt(userTypeId);
     var parent_add_type = parseInt(ParentAddTypeId);

    $(document).ready(function()
    {
        $('#dialog3').show();
        $('#del_user_type_name').html(' ');

        sendXMLHttpGetRequest('generate_category_data','/editprofile/addUserTypeNoticeAjax/id/'+type+'/p/3/add/'+parent_add_type);

        $("#del_category").dialog(
        {
                resizable: false,
                title: windowTitle,
                width:320,
                height:180,
                modal: true,
                buttons:
                {
                        "Откажи": function()
                        {
                                $("#dialog3").hide();
                                $( this ).dialog( "close" );
                        },
                        "Потвърди": function()
                        {
                            $("#dialog3").hide();
                            $( this ).dialog( "close" );
                            sendXMLHttpGetRequest('save_chosen_cat', url);
                        }
                }
        });
    });
}

function delAllCats(windowTitle, url, userTypeId)
{
     var type = parseInt(userTypeId);

    $(document).ready(function()
    {
        $('#dialog4').show();
        $('#del_user_types_name').html(' ');

        sendXMLHttpGetRequest('generate_category_data','/editprofile/addUserTypeNoticeAjax/id/'+type+'/p/4');

        $("#del_all_categories").dialog(
        {
                resizable: false,
                title: windowTitle,
                width:320,
                height:180,
                modal: true,
                buttons:
                {
                        "Откажи": function()
                        {
                                $("#dialog4").hide();
                                $( this ).dialog( "close" );
                        },
                        "Потвърди": function()
                        {
                            $("#dialog4").hide();
                            $( this ).dialog( "close" );
                            sendXMLHttpGetRequest('save_chosen_cat', url);
                        }
                }
        });
    });
}

function additCat(windowTitle, CatID, CatValue)
{
    var catid = parseInt(CatID);
    var catvalue = parseInt(CatValue);

    $(document).ready(function()
    {
        $('#dialog5').show();
        $('#additional_parent_category_name').html(' ');

        sendXMLHttpGetRequest('generate_category_data','/editprofile/addUserTypeNoticeAjax/id/'+catid+'/p/5');

        $('#your_cat_id').attr('value',catvalue);
        $('#parent_cat_id').attr('value', catid);
        $('#new_category').attr('value', '');

        $("#add_new_category").dialog(
        {
                resizable: false,
                title: windowTitle,
                width:480,
                height:170,
                modal: true,
                buttons:
                {
                        "Откажи": function()
                        {
                                $("#dialog5").hide();
                                $( this ).dialog( "close" );

                                $('#add_new_category').hide();
                                $('#cat_'+catvalue).show();
                        },
                        "Потвърди": function()
                        {
                            $("#dialog5").hide();
                            $( this ).dialog( "close" );
                            
                            if ($('#new_category').val())
                            {
                                $('#formEditAddCat').submit();
                            }
                            else
                            {
                                $('#add_new_category').hide();
                                $('#cat_'+catvalue).show();
                            }
                        }
                }
        });
    });
}

function deleteResigrationStepSubCat(windowTitle, url, userTypeID, param)
{
    var type = parseInt(userTypeID);
    var p = parseInt(param);

    $(document).ready(function()
    {
        $('#dialog'+p).show();
        $('#del_user_type_name'+p).html(' ');

        sendXMLHttpGetRequest('divId','/registration/dialogUserTypeAjax/id/'+type+'/p/'+p);

        $("#del_cat"+p).dialog(
        {
                resizable: false,
                title: windowTitle,
                width:320,
                height:180,
                modal: true,
                buttons:
                {
                        "Откажи": function()
                        {
                                $("#dialog"+p).hide();
                                $( this ).dialog( "close" );
                        },
                        "Потвърди": function()
                        {
                            $("#dialog"+p).hide();
                            $( this ).dialog( "close" );

                            $('#user_categories_block').show();
                            sendXMLHttpGetRequest('divId', url);
                        }
                }
        });
    });
}

function capLock(e, msg)
{
    $(document).ready(function(){
        
        var kc = e.keyCode?e.keyCode:e.which;
        var sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);

        if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)) {
            systemMSG.showError(msg);
        }
        
    });
}

function textCounter(field, limit, visualCharLimitBlock) 
{    
    var fieldValue = parseInt(field.value.length);
    var charLimit = parseInt(limit);
    var res = 0;
    
    $(document).ready(function() 
    {
        $('#'+visualCharLimitBlock).text(res);
        if (fieldValue > charLimit) 
        {
            systemMSG.showError($('#err_msg_char_limits').val());
            field.value = field.value.substring(0, charLimit);
        }
        else 
        { 
            res = (limit - fieldValue);
            $('#'+visualCharLimitBlock).text(res);
        }
    });
} 

function getUsersBySelectedGatewayOrUser(gateway, user, mode)
{
    var selectedGateway = parseInt(gateway);
    var selectedUser = parseInt(user);
    var gateMode = parseInt(mode);
    
    $(document).ready(function() { 
           if (selectedGateway > 0) {
               sendXMLHttpGetRequest('usersGatewayContainer','/statistics/gatewayUsersAjax/gid/'+selectedGateway+'/uid/'+selectedUser+'/mode/'+gateMode);
               $('#selected_gateway_id').val(selectedGateway);
           }

           $('.gatewaysRadio').click(function() {
               gid = parseInt($(':checked').val());
               $('#selected_gateway_id').val(gid);

               if (gid > 0) {
                   sendXMLHttpGetRequest('usersGatewayContainer','/statistics/gatewayUsersAjax/gid/'+gid+'/mode/'+gateMode);
               }
           });
    });
}

function getGatewaysChoices(e, errUser, m)
{
    var gid = parseInt($('#selected_gateway_id').val());
    var uid = parseInt($('#gateway_user_id').val());
    var path = '';
    
    if (uid == -1) {
        systemMSG.showError(errUser);
    } else if (gid > 0) { 
        if (m == 1) { 
            path = 'gatewayserrors/gid/'+gid+'/uid/'+uid;
        } else { 
            path = 'gatewayslist/gid/'+gid+'/uid/'+uid; 
        } 
        window.location='/statistics/'+path;

    } else {
        systemMSG.showError(e);
    }
}
