var loadingImg = '<img src="/img/loading.gif" />';
var loadingText = 'загрузка...';

$(document).ready(function() {
	$('ul.hover li')
		.hover(
			function() {
				$(this).addClass('active');
			},
			function() {
        		$(this).removeClass('active');
      		}
    	)
    	.click(function() {
    		window.location = $(this).find("a").attr('href');
    	})

	initDialogLinks();

    $('.flyout').flyout({
    	loader: 'flyoutLoader',
    	loadingSrc: '/img/loading.gif',
    	inSpeed: 500,
    	outSpeed: 500,
    	loadingText: 'Загрузка...',
    	closeTip: 'Кликните чтобы закрыть'
	});

	if ($('#catsList').length) {
		$('#catsList').btabs();
		$('#lnk').slideDown();
	}
});

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 userLogin() {
	hideModal();
	$('#userLogin').focus();
}

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

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 */
function imgUploadSubmit(s) {
	if (!s) s = '';   
    $('#img_upload_submit'+s).attr('disabled', 'disabled');
    $('#img_upload_submit'+s).val(loadingText);
    $('#iuf'+s).submit()
    return true;
}

function imgUploadDone(img, id, s) {
	if (!s) s = '';
    $('#img_upload_submit'+s).removeAttr('disabled');
    $('#img_upload_submit'+s).val('загрузить');
    toggleIt('img_upload_form'+s, 'img_upload_toggler'+s);
    $('#img_upload_id'+s).val(id);
    $('#img_upload_img'+s).attr('src', img+'?'+Math.random());
}

function imgUploadError(err, s) {
	if (!s) s = '';
    $('#img_upload_submit'+s).removeAttr('disabled');
    $('#img_upload_submit'+s).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 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 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>');
            }
		}
	})
}

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);

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

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

	if (confirmStr==false || window.confirm(confirmStr)) {
		Boxy.load(url, {
			type: type,
			cache:true,
			modal: true,
			title: title,
			closeText: 'Закрыть',
			data: data,
			unloadOnHide: true,
			fixed: false,
			center: true
		});
	}
}

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

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

function commentsAdd(table, obj_id, no_user) {
    if ($('#commentForm').length) {
    	var data = 'commentForm';

    	if ($('#text').length) {
        	$('#text').val(FCKeditorAPI.GetInstance('text').GetXHTML());
		}
		if ($("textarea[@name='text']").val() == '') {
			alert('Введите комментарий');
			return false;

		}
		
	}
	if (no_user) no_user = '/'+1; else no_user = '';

    return openModal('/comments/add/'+table+'/'+obj_id+no_user, 'Новый комментарий', false, data, 'POST');
}

function commentsLoad(table, id) {
    $.ajax({
    	url: '/comments/load/'+table+'/'+id,
    	success: function(data, status) {
    		$('#comments').append(data);
    	}
	});
}