var loadingImg = '<img src="/img/loading.gif" />';
var loadingText = lang.loading;

$(document).ready(function() {
	initDialogLinks();
});

function initDialogLinks() {
    $('.dialogLink').click(function() {
    	if ($(this).attr('rel')) {
    		confirmStr = $(this).attr('rel');
		}
		else {
			confirmStr = false;
		}
    	openModal($(this).attr('href'), $(this).attr('title'), confirmStr);
    	return false;
    });
}

function toggleIt(o, t, simple) {
    if (t) {
        if ($(t).is('.iconDown')) {
            $(t).removeClass('iconDown');           
            $(t).addClass('iconUp');
        }
        else {
            $(t).removeClass('iconUp');
            $(t).addClass('iconDown');
        }
    }
    if (simple) $('#'+o).toggle();
        else $('#'+o).slideToggle();
}


/* Аплоад через iframe */
var img_upload_btn_val = false;
function imgUploadSubmit(s) {
	if (!s) s = '';   
	img_upload_btn_val = $('#img_upload_submit'+s).val();
	loadingToggle();
    $('#img_upload_submit'+s).attr('disabled', 'disabled');
    $('#img_upload_submit'+s).val(loadingText);
    $('#iuf'+s).submit()
    return true;
}

function imgUploadDone(img, id, s) {
	loadingToggle();
	if (!s) s = '';
    $('#img_upload_submit'+s).removeAttr('disabled');
    $('#img_upload_submit'+s).val(img_upload_btn_val);
    if (img) toggleIt('img_upload_form'+s, 'img_upload_toggler'+s);
    if (id) $('#img_upload_id'+s).val(id);
    if (img) $('#img_upload_img'+s).attr('src', img+'?'+Math.random());
}

function imgUploadError(err, s) {
	loadingToggle();
	if (!s) s = '';
    $('#img_upload_submit'+s).removeAttr('disabled');
    $('#img_upload_submit'+s).val(img_upload_btn_val);
    alert(err);
}

function imgUploadRemove(link, s) {
	if (!s) s = '';
    $('#img_upload_id'+s).val('0');
    $('#img_upload_img'+s).attr('src', '/img/ava_50.jpg');
    if (link) $(link).hide();
}
/* *** */

function sendForm(form, receiver, submit, indicate, page) {
    if ($('#text').length && $('#text___Config').length) {
        $('#text').val(FCKeditorAPI.GetInstance('text').GetXHTML());
    }
	
	$('#'+submit).attr('disabled', 'disabled');
    var prev = $('#'+submit).val();
    $('#'+submit).val(loadingText);

    if (indicate) {
        $('#'+receiver).html(loadingText);
    }
    if (page) {
    	$('#'+form+' input[name=page]').val(page);
	}

	$.ajax({
		url: $('#'+form).attr('action'), 
		data: $('#'+form).serialize(),
		type: 'POST',
		dataType: 'html',
		success: function(data, status) {
			$('#'+receiver).hide();
	        $('#'+receiver).html(data);
	        $('#'+receiver).slideDown(500, function() {
	        	if (!modalIsOpened() && $('#errMsg').length>0) $('html, body').animate({ scrollTop: $('#errMsg').offset().top }, 500);
	        });
	        $('#'+submit).removeAttr('disabled');
	        $('#'+submit).val(prev);
		}
	});

    return false;
}


function addBookmark(title, url) {
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href', url);
		elem.setAttribute('title', title);
		elem.setAttribute('rel', 'sidebar');
		elem.click();
	} 
	else if(document.all) {
		window.external.AddFavorite(url, title);
	};
}

function inputSymbCount(input, limit) {
	var len = $('#'+input).val().length + '';
	$('#'+input+'SymbCount').html(len);
	if (len>limit) {
		$('#'+input).val($('#'+input).val().substr(0, limit));
	}
}

function transliterate_field(from, to) {
    if ($('#'+from).length) {
        var text = $('#'+from).val();
        text = transliterate(text);
        $('#'+to).val(text);
    }
}

function transliterate(str) {
    var rusChars = new Array('А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У','Ф','Х','Ч','Ц','Ш','Щ','Э','Ю','Я','Ы','Ъ','Ь','а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ч','ц','ш','щ','э','ю','\я','ы','ъ','ь', ' ', ',');
    var transChars = new Array('A','B','V','G','D','E','Jo','Zh','Z','I','J','K','L','M','N','O','P','R','S','T','U','F','H','Ch','C','Sh','Csh','E\'','Ju','Ja','Y','','','a','b','v','g','d','e','jo','zh','z','i','j','k','l','m','n','o','p','r','s','t','u','f','h','ch','c','sh','csh','e\'','ju','ja','y','','', '_', '');
    from = str;
    var to = "";
    var len = from.length;
    var character, isRus;
    for(i=0; i < len; i++)
    {
    //  character = from.substr(i,1);
        character = from.charAt(i,1);
        isRus = false;
        for(j=0; j < rusChars.length; j++)
        {
            if(character == rusChars[j])
            {
                isRus = true;
                break;
            }
        }
        to += (isRus) ? transChars[j] : character;
    }
 	return to;
}

function preloadImg(image) {
	var img = new Image();
	img.src = image;
}

function loadingToggle() {
	if (!$('#loading').length) {
		$('body').append('<div id="loading" style="display:none"></div>');
	}
	$('#loading').html(loadingImg.concat('<br />').concat(loadingText));
	//.concat('<br /><a href="javascript:loadingToggle()">cancel</a>'));

	var h = $(window).height()>$(document).height()?$(window).height():$(document).height();
    $('#loading').css({
        width:  $(document.body).width(),
        height:  h/2,
        opacity: 0.8,
        backgroundColor: '#000',
        textAlign: 'center',
        paddingTop: h/2,
        position: 'absolute',
        top: 0,
        left: 0,
        color: '#fff',
        zIndex: 9999
    });

	if ($('#loading').css('display') == 'none') {
		$('#loading').css({display:'block'});
	}
	else {
		$('#loading').css({display:'none'});
	}
}

function openModal(url, title, confirmStr, form, type, afterOpen) {
	if (!confirmStr) confirmStr = false;
	if (!form) data = ''; else data = $('#'+form).serialize();
	if (!type) type = 'GET';
	if (!afterOpen) afterOpen = function() { loadingToggle(); };

	if (confirmStr==false || window.confirm(confirmStr)) {
		loadingToggle();
		Boxy.load(url, {
			type: type,
			cache:true,
			modal: true,
			title: title,
			closeText: lang.close,
			data: data,
			unloadOnHide: true,
			fixed: false,
			center: true,
			afterShow: afterOpen
		});
	}
}

function hideModal() {
	if (modalIsOpened()) {
		Boxy.get().hide();
	}
}

function modalIsOpened() {
	return Boxy.isModalVisible();
}

/* comments */
function commentsSubscribe(table, id) {
	return openModal('/comments/subscribe/'+table+'/'+id, lang.comments_subscribe);
}

function commentsUnsubscribe(table, id) {
	return openModal('/comments/unsubscribe/'+table+'/'+id, lang.comments_unsubscribe);
}

function commentsShowForm() {
	if ($('#comment_form').css('display') == 'none' || $('#commentFormForm').css('display') == 'none') {
		$('#commentFormForm').show();
		$('#comment_form').slideDown();
	}
	$('#comment_form_div').append($('#comment_form'));
	if ($('#parent_comment_id')) $('#parent_comment_id').val('0');
}

function commentsReply(id, link) {
	$('#comment_form').insertAfter($(link));
	if ($('#parent_comment_id')) $('#parent_comment_id').val(id);
	if ($('#comment_form').css('display') == 'none' || $('#commentFormForm').css('display') == 'none') {
		$('#commentFormForm').show();
		$('#comment_form').slideDown();
	}
}

function commentsEdit(table, id) {
    return openModal('/comments/edit/'+table+'/'+id, lang.comments_edit);
}

function commentsDelete(table, obj_id, comment_id) {
    if (confirm(lang.comments_delete_confirm)) {
        return openModal('/comments/delete/'+table+'/'+obj_id+'/'+comment_id, lang.comments_delete);
    }
}

function commentsLoad(table, id, parent_id, update) {
    $.ajax({
    	url: '/comments/load/'+table+'/'+id,
    	success: function(data, status) {
            if (!update) {
	            if (parent_id!='0') {
            		$('#cr'+parent_id).append(data);
				}
				else {
            		$('#comments').append(data);
				}
			}
			else {
				$('#comment'+id+'c').html(content);
			}

    	}
	});
}
/* /comments */

function setSex(sex) {
    if (!sex && sex != 0) sex = '';
    $('#sex').val(sex);
    if (sex) {
        if (sex == 'male') {
            $('#imgfemale').fadeTo('slow', 0.3)
            $('#imgmale').fadeTo(0.1, 1)
        }
        else {
            $('#imgfemale').fadeTo(0.1, 1)
            $('#imgmale').fadeTo('slow', 0.3)
        }
    }
    else {
        $('#imgfemale').css({opacity:0.3});
        $('#imgmale').css({opacity:0.3});
    }
}

function reloadCaptcha() {
  	$('#captchaImage').html(loadingImg);
  	$('#captchaImage').load('/misc/captcha');
}

function loadSelectList(listID, loader, first, emptyString, selected) {
    $('#'+listID).attr('disabled', 'disabled');
    $('#'+listID).html('<option value="0">Загрузка...</option>');

    if ($('#select_'+listID) && $('#select_'+listID).attr('display')=='none') {
        $('#select_'+listID).show();
    }

	$.ajax({
		url: loader, 
		data: { selected: selected },
		type: 'POST',
		dataType: 'html',
		success: function(data, status) {
            $('#'+listID).removeAttr('disabled');
            if (data) {
            	text = data;
                if (first) {
                    text = '<option value="0">' + first + '</option>' + text;
                }
                $('#'+listID).html(text);
            }
            else {
                $('#'+listID).html('<option value="0">'+emptyString+'</option>');
            }
		}
	})
}