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

$(document).ready(function() {
	initDialogLinks();
	$('a.inline').click(function() {
		$('a.inline.group').removeClass('active');
		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
		}
		else {
			$(this).addClass('active');
		}
	});

	if ($('#addBlockLinks').length) {
		$('#addBlockLinks a').each(function() {
			var href = $(this).attr('href');
			$(this).click(function() {
				blockSelect(href+'Block');
			})
		})
	}
});

var flickr_api_key = '1f6f0dae9c98376f1d637b4c4444096a';
var google_api_key = 'ABQIAAAAbwqqYWRG-WDEX5YXoXNMZRT73gIfF5peGXPWTM_ya7ValQkx_BRo9QC-XHiLvVsl5X6XQ3kqpzuolQ';
var cpage = 1;
var per_page = 13;

function blockSelect(block) {
	$('.addBlock').hide();
	$(block).show('fast');
	return false;
}

function searchImage(page) {
	var text = $('#searchText').val();

	if (!page) {
		cpage++;
		page = cpage;
	}
	else {
		cpage = 1;
		page = page;
	}
	var gpage = 8 * (page-1) + 1;

	$('#searchProgress').html(loadingImg);

	$.getJSON('http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q='+text+'&key='+google_api_key+'&start='+gpage+'&rsz=large&alt=json-in-script&callback=?', function(data) {
		$('#searchResult').html('');
		$.each(data.responseData.results, function(i, photo) {
			var image = photo.url;
			var thumb = photo.tbUrl;
			addResultImage(image, thumb);
		});
	});

	$.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.search&page='+page+'&per_page='+per_page+'&format=json&api_key='+flickr_api_key+'&tags='+text+'&tag_mode=any&sort=interestingness-desc&jsoncallback=?', function(data) {
		$.each(data.photos.photo, function(i, photo) {
			var image = 'http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret;
			var thumb = image+'_t.jpg';
			image = image+'.jpg';
			addResultImage(image, thumb);
		});
		$('#searchProgress').html('');
		$('#searchMore').attr('disabled', false);
	});
}
function addResultImage(image, thumb) {
	$('<a class="image" href="javascript:getByUrl(\''+image+'\')"><img src="'+thumb+'" border="0" /></a>').appendTo("#searchResult");
}

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 */
function imgUploadSubmit(s) {
	if (!s) s = '';   
	//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('Загрузить');
    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());
    document.getElementById('iuf'+s).reset();
}

function imgUploadError(err, s) {
	//loadingToggle();
	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 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()">Отмена</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: 'Закрыть',
			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, 'Подписка на комментарии');
}

function commentsUnsubscribe(table, id) {
	return openModal('/comments/unsubscribe/'+table+'/'+id, 'Подписка на комментарии');
}

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, 'Редактирование комментария');
}

function commentsDelete(table, obj_id, comment_id) {
    if (confirm('Удалить комментарий?')) {
        return openModal('/comments/delete/'+table+'/'+obj_id+'/'+comment_id, 'Удаление');
    }
}

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

    	}
	});
}

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

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}