/**
 *
 * @name showMessage
 *
 * @param string text - The message, which will appear in popup
 * @param string type - Specifies popup's style(color, icon). Can take values: notice, warning, error.
 * @param string action - JS action, which will perform after action_btn clicked.
 * @param string action_btn_text - Text on action-button. If it takes empty string, action button will not show. Popup will close by click this button and specified actionwill perform.
 * @param string close_btn_text - Text on close-button. If it takes empty string, action button will not show. Popup will close by click this button.
 *
 * @example  $('#elem_id').click(function(){showMessage ('You can not delete this.', "error", "", "", "Ok");return false}); // add popup with one button "Ok". By click "Ok" popup will close.
 * @example  $('#elem_id').click(function(){showMessage ('Are you sure to delete #1?', "warning", "submitForm(jQuery('#elem_id').get(0),'',{'command':'delete','id':'1'});", "Delete", "Сancel");return false}); // add popup with two buttons: "Delete" and "Cancel". By click "Cancel" popup will close.  By click "Delete" popup will close and JS-code will perform: submitForm(jQuery('#elem_id').get(0),'',{'command':'delete','id':'1'});.
 */
function showMessage (text, type, action, action_btn_text, close_btn_text)
{
    $('#glob_message').remove();
    $('#content_mask').remove();

    if(!type)
        type='notice';
    var action_btn = '';
    var close_btn = '';

    if(action_btn_text)
           action_btn = '<input id="glob_message_action_btn" type="button" value="'+action_btn_text+'">' ;
    if(close_btn_text)
           close_btn = '<input id="glob_message_close_btn" type="button" value="'+close_btn_text+'">';

    var docWidth = $(document).width();
    var docHeight = $(document).height();
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();

    var scrollTop = $(window).scrollTop();
    var scrollLeft = $(window).scrollLeft();

    var maskHeight = docHeight
    var maskWidth = docWidth;
    if(windowWidth>docWidth)
        maskWidth = windowWidth;

    $('body').append('<div id="content_mask"></div>');
    $('#content_mask').css({'width':maskWidth,'height':maskHeight});

    $('body').append('<div id="glob_message" class="glob_message-' + type + '">'+
        '<div id="glob_message_text"><img src="'+baseUrl+'/images/' + type + '.png" align="left">' + text + '</div>'+
        '<div id="glob_message_btns">'+
        action_btn+
        close_btn+
        '</div>'+
        '</div>');
    $('#glob_message').css({'top':windowHeight/2+scrollTop, 'left':windowWidth/2+scrollLeft});

    if(action_btn_text)
    {
        $('#glob_message_action_btn').get(0).onclick = function () {
            $('#glob_message').remove();
            $('#content_mask').remove();
            if(action)
                eval(action);

        };
    }
    if(close_btn_text)
    {
        $('#glob_message_close_btn').click(function() {
            $('#glob_message').remove();
            $('#content_mask').remove();
        });
    }
    return false;
}

function show_loading()
{
	var docWidth = $(document).width();
    var docHeight = $(document).height();
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();

    var scrollTop = $(window).scrollTop();
    var scrollLeft = $(window).scrollLeft();

    var maskHeight = docHeight
    var maskWidth = docWidth;
    if(windowWidth>docWidth)
        maskWidth = windowWidth;
    
    $('body').append('<div id="content_mask"></div>');
    $('#content_mask').css({'width':maskWidth,'height':maskHeight});
    
	$('body').append('<div id="content_loading" style="top:'+(windowHeight/2+scrollTop*1)+'px;left:'+(windowWidth/2+scrollLeft*1)+'px;"></div>');
	
}
function hide_loading()
{
	$('#content_loading').remove();
	$('#content_mask').remove();
}

function styling_checkboxes(elem_selector)
{
	$(elem_selector).find(':checkbox').css('display','none').each(function(i){
		span = $('<span class="checkbox"></span>').insertBefore(this);
		if($(this).attr('checked')==false)
			span.css('background','none');
			
		span.click(function(){
			elem = $(this).next();
			if(elem.attr('checked')==true)
			{
				elem.attr('checked',false);
				$(this).css('background','none');
			}
			else
			{
				elem.attr('checked',true);
				$(this).css('background','url("'+baseUrl+'/images/checkbox.png") no-repeat 0px 0px');
			}
		});
		span.mouseover(function(){
			$(this).css('background','url("'+baseUrl+'/images/checkbox.png") no-repeat 0px -14px');
		});
		span.mouseout(function(){
			elem = $(this).next();
			if(elem.attr('checked')==false)
				$(this).css('background','none');
			else
				$(this).css('background','url("'+baseUrl+'/images/checkbox.png") no-repeat 0px 0px');
		});
	});
}

function changeVisitsParams(path)
{
	var href = baseUrl+'/'+path;
	var client_id = $('#client_id').val();
	
	
	var client_id = '/client_id/'+client_id;
	
	var year = '';
	if($('#year').length)
	{
		year = $('#year').val();
		year = '/year/'+year;
	}
	
	var month = '';
	if($('#month').length)
	{
		month = $('#month').val();
		month = '/month/'+month;
	}
	var clients_filter = '';
	if($('[name=clients_filter]').length)
	{
		clients_filter = 0;
		for(i=0;i<$('[name=clients_filter]').length;i++)
		{
			if($('[name=clients_filter]').get(i).checked)
			{
				clients_filter=$('[name=clients_filter]').get(i).value;
				break;
			}
		}
		clients_filter = '/clients_filter/'+clients_filter;
	}
	
	window.location.href = href+client_id+year+month+clients_filter;
}

var timer;
function sendProfilePhoto()
{
	$('#image_upload').hide();
	$("form[name=form_photo]").submit();
	$("#loading_image").show();
	timer = window.setInterval('repeatProfileUploadingCheck()',500);
}

var maxCheckNum = 20;
var checkNum = 0;
function repeatProfileUploadingCheck()
{
        checkNum++;
        var iframeDoc = getIframeDoc();
        var error_div = iframeDoc.getElementById('responce_error');
        if(!error_div && (checkNum==maxCheckNum))
	{
		showMessage ('Произошла ошибка. Не удалось загрузить фотографию.', 'error', '', '', 'Закрыть');
	
		window.clearInterval(timer);
		
		$("#image_upload").show();
		$("#loading_image").hide();
		clearIframe();
		
		$("form[name=form_photo]").get(0).reset();
		return false;
	}
        if(!error_div)
            return false;
    	
	var error = iframeDoc.getElementById('responce_error').innerHTML;
	var success = iframeDoc.getElementById('responce_success').innerHTML;
	var filename = iframeDoc.getElementById('responce_filename').innerHTML;
	
	window.clearInterval(timer);
	
	if((success!='')&&(filename!=''))
	{
		showProfileUploadedImage(filename);
		showMessage (success, 'success', '', '', 'Закрыть')
	}
	else
	{
		showMessage (error, 'error', '', '', 'Закрыть')
	}
	$("#image_upload").show();
	$("#loading_image").hide();
	clearIframe();
	$("form[name=form_photo]").get(0).reset();
	
//	alert(error+'; '+success+'; '+filename);
}

function clearIframe()
{
	var iframeDoc = getIframeDoc();
	var error_div = iframeDoc.getElementById('responce_error');
	if(!error_div)
		return;		
	iframeDoc.body.innerHTML = '';
}
function getIframeDoc()
{
	var iframeElem = document.getElementById('file_form_iframe');
	var iframeDoc = iframeElem.contentWindow || iframeElem.contentDocument;
	if (iframeDoc.document) {
	    iframeDoc = iframeDoc.document;
	}
	return iframeDoc;
}
function showProfileUploadedImage(filename)
{
	$("#profile_photo").attr('src',filename);
	$("#del_profile_photo").show();
}


function deleteProfilePhoto()
{
	show_loading();

	$.post(baseUrl+'/users/ajdeleteprofilephoto',null,function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');
		
		if(status=='success')
		{
			$("#profile_photo").attr('src',defaultProfilePhoto);
			$("#del_profile_photo").hide();
			hide_loading();
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}




// FRIENDS FUNCTIONS
function addToFriends(user_id)
{
	if(!user_id)
	{
		showMessage ('Не удалось отправить приглашение.', 'error', '', '', 'Закрыть');
		return;
	}
    show_loading();
	$.post(baseUrl+'/friends/ajadd',{id:user_id},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>.*$/,'$1');
                var action = data.replace(/^.*\<action\>(.*)\<\/action\>$/,'$1');

		hide_loading();
		if(status=='success')
		{
                        if(action=='bind')
                        {
                            $('#add_friend_id_'+user_id).unbind().attr('id','del_friend_id_'+user_id).html('Убрать из друзей');
                            $('#del_friend_id_'+user_id).click(function(){
                                    showMessage ("Этот пользователь будет удален из списка ваших друзей. Удалить?", "notice", "deleteFromFriends("+user_id+")", "Да", "Отмена");
                                    return false;
                            });
                        }
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}
function deleteFromFriends(user_id)
{
    if(!user_id)
    {
    	showMessage ('Не удалось удалить из друзей.', 'error', '', '', 'Закрыть');
    	return;
    }
    show_loading();
	$.post(baseUrl+'/friends/ajdelete',{id:user_id},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');

		hide_loading();
		if(status=='success')
		{

			$('#del_friend_id_'+user_id).unbind().attr('id','add_friend_id_'+user_id).html('Добавить в друзья');
			$('#add_friend_id_'+user_id).click(function(){
				showMessage ("Этому пользователю будет отправлено приглашение в друзья. Отправить?", "notice", "addToFriends("+user_id+")", "Да", "Отмена");
				return false;
			});
			
			if($('#tab_content_1').length)
			{
				// delete you from his friends (if you view his friends page)
				if($('#active_user_'+userId).length)
					$('#active_user_'+userId).remove();
				
				if($('#online_user_'+userId).length)
					$('#online_user_'+userId).remove();
				
				// delete he from your friends (if you view your friends page)
				if($('#active_user_'+user_id).length)
					$('#active_user_'+user_id).remove();
				
				if($('#online_user_'+user_id).length)
					$('#online_user_'+user_id).remove();
			}
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}
function acceptFriends(user_id)
{
    if(!user_id)
    {
    	showMessage ('Не удалось добавить в друзья.', 'error', '', '', 'Закрыть');
    	return;
    }
    show_loading();
	$.post(baseUrl+'/friends/ajaccept',{id:user_id},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');

		hide_loading();
		if(status=='success')
		{
			$('#refuse_user_id_'+user_id).remove();
			var div = $('#pending_user_'+user_id).clone().get(0);
			$('#pending_user_'+user_id).remove();
			
			
			$(div).attr('id','active_user_'+user_id);
			$('#tab_content_1').append(div);
			$('#tab_content_1').find('#accept_user_id_'+user_id).html('Убрать').attr('id','del_friend_active_id_'+user_id).unbind().click(function(){
				showMessage ("Этот пользователь будет удален из списка ваших друзей. Удалить?", "notice", "deleteFromFriends("+user_id+")", "Да", "Отмена");
				return false;
			});
			
			if($(div).hasClass('online'))
			{
				div = $('#active_user_'+user_id).clone().get(0);
				$(div).attr('id','online_user_'+user_id);
				$('#tab_content_2').append(div);
				$('#tab_content_2').find('#del_friend_active_id_'+user_id).attr('id','del_friend_online_id_'+user_id).unbind().click(function(){
					showMessage ("Этот пользователь будет удален из списка ваших друзей. Удалить?", "notice", "deleteFromFriends("+user_id+")", "Да", "Отмена");
					return false;
				});
			}
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}
function refuseFriends(user_id)
{
    if(!user_id)
    {
    	showMessage ('Не удалось отказать в дружбе.', 'error', '', '', 'Закрыть');
    	return;
    }
    show_loading();
	$.post(baseUrl+'/friends/ajrefuse',{id:user_id},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');

		hide_loading();
		if(status=='success')
		{
//			var div = $('#pending_user_'+user_id).clone().get(0);
			$('#pending_user_'+user_id).remove();
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}


// FAVORITE USERS FUNCTIONS


function addToFavUsers(user_id)
{
    if(!user_id)
    {
    	showMessage ('Не удалось добавить в избранное.', 'error', '', '', 'Закрыть');
    	return;
    }
    show_loading();
	$.post(baseUrl+'/favoriteusers/ajadd',{id:user_id},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');

		hide_loading();
		if(status=='success')
		{
			$('#add_fav_user_id_'+user_id).attr('id','del_fav_user_id_'+user_id).html('Убрать из избранного');
			$('#del_fav_user_id_'+user_id).click(function(){
				showMessage ("Этот пользователь будет удален из списка ваших избранных фотографов. Удалить?", "notice", "deleteFromFavUsers("+user_id+")", "Да", "Отмена");
				return false;
			});
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}
function deleteFromFavUsers(user_id)
{
    if(!user_id)
    {
    	showMessage ('Не удалось удалить из избранного.', 'error', '', '', 'Закрыть');
    	return;
    }
    show_loading();
	$.post(baseUrl+'/favoriteusers/ajdelete',{id:user_id},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');

		hide_loading();
		if(status=='success')
		{

			if($('#del_fav_user_id_'+user_id).length)
			{
				$('#del_fav_user_id_'+user_id).attr('id','add_fav_user_id_'+user_id).html('Добавить в избранное');
				$('#add_fav_user_id_'+user_id).click(function(){
					showMessage ("Этот пользователь будет добавлен в список ваших избранных фотографов. Добавить?", "notice", "addToFavUsers("+user_id+")", "Да", "Отмена");
					return false;
				});
			}
			if($('#tab_content_1').length)
			{
				if($('#active_user_'+user_id).length)
					$('#active_user_'+user_id).remove();
				
				if($('#online_user_'+user_id).length)
					$('#online_user_'+user_id).remove();
			}
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}


// DELETE PHOTO

function deletePhoto(id)
{
    if(!id)
    {
		showMessage ('Не удалось удалить фотографию.', 'error', '', '', 'Закрыть');
		return;
    }
    show_loading();
	$.post(baseUrl+'/photos/ajdelete',{id:id},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');

		hide_loading();
		if(status=='success')
		{

			if($('#photo_'+id).length)
				$('#photo_'+id).remove();

			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}


// MAKE ALBUM'S COVER FROM PHOTO

function makeCover(id)
{
	if(!id)
    {
		showMessage ('Не удалось разместить фотографию на обложке альбома.', 'error', '', '', 'Закрыть');
		return;
    }
    show_loading();
	$.post(baseUrl+'/albums/ajmakecover',{id:id,album_id:albumId},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');

		hide_loading();
		if(status=='success')
		{
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}


// DELETE ALBUM

function deleteAlbum(id)
{
    if(!id)
    {
		showMessage ('Не удалось удалить альбом.', 'error', '', '', 'Закрыть');
		return;
    }
    show_loading();
	$.post(baseUrl+'/albums/ajdelete',{id:id},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');

		hide_loading();
		if(status=='success')
		{

			if($('#album_'+id).length)
				$('#album_'+id).remove();

			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}




// FAVORITE PHOTOS FUNCTIONS

function addToFavPhotos(photo_id)
{
    if(!photo_id)
    {
    	showMessage ('Не удалось добавить в избранное.', 'error', '', '', 'Закрыть');
    	return;
    }
    show_loading();
	$.post(baseUrl+'/favoritephotos/ajadd',{id:photo_id},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');

		hide_loading();
		if(status=='success')
		{
			$('#add_fav_photo_id_'+photo_id).attr('id','del_fav_photo_id_'+photo_id).html('Убрать из избранного');
			$('#del_fav_photo_id_'+photo_id).click(function(){
				showMessage ("Выбранная фотография будет убрана из избранных фотографий. Убрать?", "notice", "deleteFromFavPhotos("+photo_id+")", "Да", "Отмена");
				return false;
			});
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}
function deleteFromFavPhotos(photo_id)
{
    if(!photo_id)
    {
    	showMessage ('Не удалось удалить из избранного.', 'error', '', '', 'Закрыть');
    	return;
    }
    show_loading();
	$.post(baseUrl+'/favoritephotos/ajdelete',{id:photo_id},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>.*$/,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>$/,'$1');

		hide_loading();
		if(status=='success')
		{

			if($('#del_fav_photo_id_'+photo_id).length)
			{
				$('#del_fav_photo_id_'+photo_id).attr('id','add_fav_photo_id_'+photo_id).html('Добавить в избранное');
				$('#add_fav_photo_id_'+photo_id).click(function(){
					showMessage ("Выбранная фотография будет добавлена в избранное. Добавить?", "notice", "addToFavPhotos("+photo_id+")", "Да", "Отмена");
					return false;
				});
			}
			if($('#content div[id^="photo_"]').length)
			{
				if($('#photo_'+photo_id).length)
					$('#photo_'+photo_id).remove();
			}
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}


// SEND COMMENT FUNCTION
function sendComment()
{
	var text = $('#comment').val();
	var parent_id = $('#parent_comment_id').val();
	var photo_id = $('#photo_id').val();
	
        show_loading();
	$.post(baseUrl+'/photocomments/ajadd',{parent_id:parent_id,photo_id:photo_id,text:text},function(data){
		var status = data.replace(/^\<status\>(.*)\<\/status\>[\s\S]*$/m,'$1');
		var message = data.replace(/^.*\<message\>(.*)\<\/message\>[\s\S]*$/m,'$1');
		var comments = data.replace(/^\<status\>.*\<\/message\>/,'');
                hide_loading();
		if(status=='success')
		{
			unbindReply();
			$('#comments_block').html(comments);
			$('#comment').val('');
			$('#parent_comment_id').val(0);
			bindReply();
			showMessage (message, 'success', '', '', 'Закрыть');
		}
		else
			showMessage (message, 'error', '', '', 'Закрыть');
	});
}

function bindReply()
{
	var photo_id = $('#photo_id').val();
	$('.reply_to').each(function(){
		$(this).click(function(){
			id = this.id.replace('add_comment_','');
			$('#parent_comment_id').val(id);
			
			// place replied comment's info in 'comment_dest'
			$('#comment_dest').html('Ваш ответ на комментарий от '+$('#comment_'+id).find('.comment_date').text()+', автор: '+$('#comment_'+id).find('.user_link').text());
			$('#reset_comment_dest').show();
			
			window.scroll(0,20000);
//			window.location.href = baseUrl+'/photo/'+photo_id+'#add_comment';
			return false;
		});
	});
}
function unbindReply()
{
	$('.reply_to').unbind();
}

function switchTab(elem)
{
    var tabNum = elem.id.replace('tab_','');

    $('.tab').removeClass('active');
    $('#tab_'+tabNum).addClass('active');

    $('.tab_content').hide();
    $('#tab_content_'+tabNum).show();
}

/**
 * Events
 **/
var KEY = {
        LEFT: 37,
        UP: 38,
        RIGHT: 39,
        DOWN: 40,
        DEL: 8,
        TAB: 9,
        RETURN: 13,
        ENTER: 13,
        ESC: 27,
        PAGEUP: 33,
        PAGEDOWN: 34,
        SPACE: 32
};

jQuery(document).ready(function() {
    $(document).keydown(function(event){
        event = event || window.event;
        if (event.keyCode == KEY.ESC) {
            if($('#glob_message').length) {
                $('#glob_message').remove();
                $('#content_mask').remove();
            }
	}
    });
});
