/**
 * Функции для работы с giflary page
 * @author Alexander Eliseev
 *
 */

//количество форм
var maxNumberOfForms = 5;

//html код ссылки на гифку
var htmlCode;
//html код ссылки на гифку
var bbCode;

/**
 * Добавляет одну форму для загрузки гифки.
 * Максимальное количество форм - 5.
 */
function oneMore()
{
    var oneMoreForm = '<div id="filebox">'+
                    '<div class="filebox">'+
                	'<input type="file" size="36" onchange="changeName(this); checkFileName(this); " class="file" name="gif1"/>'+
                    '<input type="text" readonly="readonly" value="' + js_dictionary.upload_your_picture + '" class="filepath" id="filepath"/>'+
                    '<div class="onemore"><a onclick="oneMore();" href="javascript:void(0);"><img height="14" width="14" title="one more" alt="plus" src="/skin/img/plus.png"/></a></div>'+
                   '</div></div>';
	//количество форм
	var length = $(".filebox").length;

	if ( length == (maxNumberOfForms-1))
	{
        $(".onemore").remove();
	}

	if (length >= maxNumberOfForms)
	{
	    return;
	}

	//добавление одной новой формы
	$("#filebox").append(oneMoreForm);

	//изменение аттрибута name у добавленной формы
	$(".filebox:last input:file").attr('name','gif'+(length+1));

	//удалить кнопки добавления у только, что клонированной формы загрузки
	$(".onemore:first").remove();
}

function uploadPictures(building_giflary_form)
{
	//отображение прогресс-бара только в случае, если корректно выбран хотя бы один файл
	if ($(".fileChosenSuccess").size()) $('#progress_bar').show();
    JsHttpRequest.query(
      	  "/?request_mode=ajax&target_block_name=UploadFormBlock",
      	  {'building_giflary_form':building_giflary_form, 'ajax_action' : 'picture_upload'},
      	  function(result, errors) {
     	  	 if(errors)
		     {
     	  		 	$('.underfilebox .warning').html(js_dictionary.giflary_error_during_uploading);
		     }
     	  	 if(result.success)
     	  	 {
     	  		 $('.loadbox3').html(result.response);
     	  	 }
     	  	 else
     	  	 {
     	  		$('.underfilebox .warning').html(js_dictionary.giflary_error_during_uploading);
     	  	 }

     	  	$('#progress_bar').hide();
      	  },
      	  true
      );
}
/**
 * Проверка имени файла на валидность
 * @param input_file
 * @return void
 */
function checkFileName(input_file)
{
    file_to_upload = input_file.value.toLowerCase();

    match_result = file_to_upload.match(/^.*\.(gif|png|jpg)$/);

    if(match_result == null)
    {
        input_file.parentNode.className = 'filebox fileboxred';

        $('.underfilebox .warning').html(js_dictionary.giflary_wrong_file_error_msg);

        return;
    }
    else
    {
    	$('.underfilebox .warning').html('');
    	input_file.parentNode.className = 'filebox';
    	// флаг успешного выбор файла
    	input_file.className=input_file.className + " fileChosenSuccess";
    }

}

/**
 * Изменение имени файла
 * @param obj this элемента, у которого меняем атрибут value
 * @return void
 */
function changeName(obj)
{
	next = $(obj).next();
	next.val($(obj).val());
	$("#sub_div").attr({'class' : 'submitred'});
	$("#submit_gif_button").removeAttr("disabled");
}

/**
 * Поиск в случае, если строка запроса не равна стандартной
 * @param obj
 * @return
 */
function search()
{
	var qs = $("#search input").eq(0).val();
	if (qs == "forexample, cats" || qs =="cats")
		return;
	$("#search").submit();
}

function postCommentByLoggedUser(comment_text, gif_id)
{
    if (comment_text !='')
    {
        $('#comment_progress_bar').show();
        $('#add_comment').hide();
    }
    JsHttpRequest.query(
      	  "/giflary?request_mode=ajax",
      	  {'comment_text' : comment_text, 'gif_id' : gif_id,'ajax_action' : 'post_comment_from_logged_user'},
      	  function(result, errors) {
     	  	 if(errors)
		     {
		     	if(production_flag)
		     	{
		     	    sendUnexpectedErrorReport(errors)
		     	}
		     	else{
		     	    alert(errors);
		     	}
		     }
     	  	 if(result)
     	  	 {

     	  	     $("#add_comment_form").each( function() {
                                                this.reset();
		     	                                });
                 $('#comments_div').html(result);

                 $('#comment_progress_bar').hide();

                 $('#add_comment').show();
     	  	 }
     	  	 else
     	  	 {
     	  	     $("#add_comment_form").each( function() {
                                                this.reset();
		     	                                });
     	  	     $('#comment_progress_bar').hide();
     	  	     $('#add_comment').show();
     	  	 }
      	  },
      	  true
      );
}

function postCommentNotLogged(comment_text, gif_id, login, password)
{
    if(login == 'e-mail' || login == '')
    {
        $('#comment_error_text').show();
        return;
    }

    if(password == 'password' || password == '')
    {
        $('#comment_error_text').show();
        return;
    }
    $('#comment_error_text').hide();

    JsHttpRequest.query(
    	  "/giflary?request_mode=ajax",
    	  {'login' : login, 'password' : password, 'comment_text' : comment_text, 'gif_id' : gif_id, 'ajax_action' : 'login_from_comment'},
    	  function(result, errors) {

    	  	 if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
  	     	 if(result && result!=2)
		     {
                document.location.reload();
		     }
		     else if (result && result == 2)
		     {
                $('#comment_error_text').hide();
		     }
		     else
		     {
                $('#comment_error_text').show();
		     }
    	  },
    	  true
      );
}

function showHTMLcode()
{
    $('#span_htb').show(); 
    $('#htb').hide();
    
    $('#bbb').show();    
    $('#span_bbb').hide(); 
    
    $('#lnb').show();    
    $('#span_lnb').hide();
    
    $('#html_code').html($('#html_embed_code').val()); 
    $('#html_code').select();    
}

function showBBcode()
{
    $('#span_htb').hide(); 
    $('#htb').show();
    
    $('#bbb').hide();    
    $('#span_bbb').show(); 
    
    $('#lnb').show();    
    $('#span_lnb').hide();
    
    $('#html_code').html($('#bb_embed_code').val()); 
    $('#html_code').select();  
}

function showLINKcode()
{
    $('#htb').show();
    $('#span_htb').hide();     
    
    $('#bbb').show();    
    $('#span_bbb').hide(); 
    
    $('#lnb').hide();    
    $('#span_lnb').show();
    
    $('#html_code').html($('#link_embed_code').val()); 
    $('#html_code').select(); 
}
