function _progressbar(id_pb, width_p, b_text) {
	$('#'+id_pb+' div').stop(true).animate({width: width_p+'%'}, {
				// пошагово изеняем текст состояния
				step: function(now)
				{
					// если не округлять, то можно увидеть дикую информацию :)
                    $(this).text(Math.round(now) + '%');
                    if(b_text == 1) {
                    	$(document).attr('title', Math.round(now)+'% !');
                    }
				},
				duration: 2000
			});
}
 // Popup
    function _loginPopup(){
        var popWidth = 450;
		var popID = '_login_window';

		$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="/img/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');

		var popMargTop = ($('#' + popID).height() + 80) / 2;
		var popMargLeft = ($('#' + popID).width() + 80) / 2;

		//Apply Margin to Popup
		$('#' + popID).css({
			'margin-top' : -popMargTop,
			'margin-left' : -popMargLeft
		});

		//Fade in Background
		$('body').append('<div id="fade"></div>');
		$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();

		return false;
	};

	$('a.close, #fade').live('click', function() {
	  	$('#fade , .popup_block').fadeOut(function() {
			$('#fade, a.close').remove();
		});
        return false;
	});
    // .Popup

    // Popup
    function _codePopup(){
        var popWidth = 540;
		var popID = '_code_window';

		$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="/img/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');

		var popMargTop = ($('#' + popID).height() + 80) / 2;
		var popMargLeft = ($('#' + popID).width() + 80) / 2;

		//Apply Margin to Popup
		$('#' + popID).css({
			'margin-top' : -popMargTop,
			'margin-left' : -popMargLeft
		});


		//Fade in Background
	    $('body').append('<div id="fade"></div>');
		$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();

		return false;
	};


    // .Popup

$(document).ready(function(){
    // ScrollUp
    $('#footer a.up').click(function(e){
		$.scrollTo(0, 1500);
		e.preventDefault();
        this.blur();
	});
    // .ScrollUp

    // Left Slider
	$('#left_slider').hover(function(){
		$(this).stop().animate({'left':-20, 'opacity': 1},'slow');
	},function(){
		$(this).stop().animate({'left':-220, 'opacity': 1},'slow');
	});
    // .Left Slider



    // Confirm Window
    function _confirmWindow() {
        $.confirm({
			'title'		: 'Подтвердите удаление!',
			'message'	: 'Вы действительно хотите удалить объект?',
			'buttons'	: {
				'Да'	: {
					'class'	: 'blue',
					'action': function(){
                    	alert('yes');
					}
				},
				'Нет'	: {
					'class'	: 'gray',
					'action': function(){
                       //	alert('no');
                    }
				}
			}
		});

	};
    // .Confirm Window
});

function _showError(message) {
	alert(message);
}
function _showMessage(message) {
	//alert(message);
}

function ShowOrHide(id_element) {
	if($("#"+id_element).css("display") == 'none') {
        $("#"+id_element).fadeIn(2000);
    } else {
        $("#"+id_element).fadeOut(1000);
    }
}

function CheckFieldById(id_field) {
 	 error = false;
     item_value = $("#"+id_field).attr("value");
     if(item_value == '') { error = true; }
	 else {$("#"+id_field).removeClass("inputStyleCheckFailed"); return true;}
	 if(error) {
     	$("#"+id_field).addClass("inputStyleCheckFailed"); return false;
     };
}
function CheckFieldValue(id_field, value) {
 	 error = false;
     item_value = $("#"+id_field).attr("value");
     if(item_value == value) { error = true; }
	 else {$("#"+id_field).removeClass("inputStyleCheckFailed"); return true;}
	 if(error) {
     	$("#"+id_field).addClass("inputStyleCheckFailed"); return false;
     };
}
function _getLoader() {
	var loader = '<img src="/img/loading.gif">';
    return loader;
}


/* Register */
$(function(){
	$('#_register_name').blur(function() {
        CheckFieldById("_register_name");
    });

});
$(function(){
	$('#_register_email').blur(function() {
        CheckFieldById("_register_email");
    });

});
$(function(){
	$('#_register_pass').blur(function() {
        CheckFieldById("_register_pass");
    });

});
$(function(){
	$('#_captcha').blur(function() {
        CheckFieldById("_captcha");
    });

});


$(function(){
	$('#_captcha_image').click(function() {
        $(this).attr('src', '/captcha.php?t='+Math.random());
    });
});
$(function(){
	$('#_register_form').submit(function() {
    	if(!CheckFieldById("_register_name") || !CheckFieldById("_register_email") || !CheckFieldById("_register_pass") || !CheckFieldById("_captcha")) {
        	return false;
    	}
    });
});
/* .Register */

/* Forgot */
$(function(){
	$('#_button_forgot').click(function() {
        if(!CheckFieldById("_forgot_email")) {return false;}
        _forgotPassword();
    });

});
$(function(){
	$('#_forgot_email').blur(function() {
        CheckFieldById("_forgot_email");
    });

});

function _forgotPassword() {
email = $('#_forgot_email').attr('value');
$('#_button_forgot').hide();
$(_getLoader()).appendTo('#_forgot_progress');
$.getJSON('/index_ajax.php', {task: 'users', sub_task: 'forgot', email: email}, function(obj){
                $('#_forgot_progress').empty();
                if(obj.iSuccess != 1) {
                	_showError(obj.sErrorMessage);
                    $('#_button_forgot').show();
                    return false;
                }
 				$('#_forgot_table').hide();
                $('#_forgot_handler').empty();
                $('<span>Пароль успешно выслан на <b>'+email+'</b>.</span>').appendTo('#_forgot_result');
                $('#_forgot_result').show();
            });
}
/* .Forgot */

/* Login */
$(function(){
	$('#_login_email').blur(function() {
        CheckFieldById("_login_email");
    });
});
$(function(){
	$('#_login_pass').blur(function() {
        CheckFieldById("_login_pass");
    });
});

$(function(){
	$('#_login_form').submit(function() {
    	if(!CheckFieldById("_login_email") || !CheckFieldById("_login_pass")) {
        	return false;
        }
        email = $('#_login_email').attr('value');
        pass = $('#_login_pass').attr('value');
        $('#_button_login').hide();
        $(_getLoader()).appendTo('#_login_progress');
        $.getJSON('/index_ajax.php', {task: 'users', sub_task: 'login', email: email, pass: pass }, function(obj){
                $('#_login_progress').empty();
                if(obj.iSuccess != 1) {
                 	$('#_login_progress').empty();
                	_showError(obj.sErrorMessage);
                    $('#_button_login').show();
                    return false;
                }
 				$('#_login_table').hide();
                $('#_login_handler').empty();
                $('<span>Вход выполнен. Перенаправление в <a href="/cabinet/">личный кабинет</a>.</span>').appendTo('#_login_result');
                setTimeout(function(){window.location='/cabinet/';}, 1000);
                $('#_login_result').show();
            });

        return false;
    });

});
/* .Login */


/* Send Message User*/
function _sendMessageUser(id_user) {
    if(!CheckFieldById("_send_name") || !CheckFieldById("_send_email") || !CheckFieldById("_send_message")) {
        	return false;
    }
    $('#_button_send').hide();

    name = $('#_send_name').attr('value');
    message = $('#_send_message').attr('value');
    email = $('#_send_email').attr('value');
    $(_getLoader()).appendTo('#_message_progress');
     $.getJSON('/index_ajax.php', {task: 'users', sub_task: 'send_message', id_item: id_user, name: name, message: message, email: email}, function(obj){
        if(obj.iSuccess != 1) {
          _showError(obj.sErrorMessage);
          $('#_button_send').show();
          return false;
        }
         $('#_message_progress').empty();
         $('#_message_form').hide();
         $('<span>Сообщение отправлено.</span>').appendTo('#_message_result');
         $('#_message_result').show();
   	});
}
/* .Send Message */


$(function(){
	$('#_add_folder').submit(function() {
        // обработчик отправки формы
		if(!CheckFieldById("_add_name")) {
        	return false;
    	}
    });
});

/* Settings */
$(function(){
	$('#_set_data_form').submit(function() {
    	if(!CheckFieldById("_set_name")) {
        	return false;
    	}
    });
});
$(function(){
	$('#_set_pass_form').submit(function() {
    	if(!CheckFieldById("_old_pass") || !CheckFieldById("_new_pass")) {
        	return false;
    	}
    });
});
/* .Settings */
/* Feedback */
function sendFBMessageHandler() {
   	if(!CheckFieldById("_name") || !CheckFieldById("_email") ||!CheckFieldById("_message")) {
        	return false;
    }
	var name = $('#_name').attr('value');
	var email = $('#_email').attr('value');
	var message = $('#_message').attr('value');
	$('#_submit').hide();
	$(_getLoader()).appendTo('#_loading');
	$.getJSON('/index_ajax.php', {task: 'messages', sub_task: 'feedback', name: name, email: email, message: message}, function(obj){
        $('#_loading').empty();
		if(obj.iSuccess != 1) {
          $('#_submit').hide();
		  _showError(obj.sErrorMessage);
          return false;
        }
		$('<div class="ok_container">Сообщение успешно отправлено.</div>').appendTo('#_result');
   	});
}

function sendMessageHandler() {
    if(!CheckFieldById("_message")) {
         return false;
    }
    $('#_submit').hide();
	$(_getLoader()).appendTo('#_loading');
	message = $("#_message").attr('value');
	$.getJSON('/index_ajax.php', {task: 'users', sub_task: 'cabinet', module: 'messages', sub_module: 'send', message: message}, function(obj){
        $('#_loading').empty();
		if(obj.iSuccess != 1) {
          $('#_submit').hide();
		  _showError(obj.sErrorMessage);
          return false;
        }
		$('<div class="ok_container">Сообщение успешно отправлено.</div>').appendTo('#_result');
		window.location.reload();
		$('#_submit').show();
   	});
}
/* .Feedback*/
function deleteSite(id_item, site_url) {
var x=window.confirm("Удалить сайт "+site_url+'?');
if (x)
window.location = '/cabinet/sites/delete-'+id_item+'/';
else
window.alert("Ну и ладно :)");
}

//-----------------------------------
function arrayUnique( ar ) {
       var a = [];
       var l = ar.length;
       for(var i = 0; i < l; i++) {
               for(var j = i+1; j < l; j++) {
                       if (ar[i] === ar[j])
                               j = ++i;
               }
               a.push(ar[i]);
       }
       return a;
}

$(function(){
	$('#url_button').click(function() {

		width_prev = $('#_url_width_prev').attr('value');
		width = $('#_url_width').attr('value');

		if(width_prev < 150 || width_prev > 400) {
			alert('Ошибка: Размер превью должен быть не менее 150 и не более 400px');
            return false;
		}

		if(width != '') {
			if(width < 400) {
				alert('Ошибка: Обрезать фото можно максимум до 400px');
				return false;
			}
		}

    	status = 0;
         x = 0;
         if(document.getElementById('url_button').disabled == false) {
			str =  document.getElementById('url_list').value;
            if(str == '') {
            	alert('Ошибка: Вы не указали URL картинок!');
                return false;
            }

			$("#pb1").show();
			$("#report_url").show();
			_current_pb = 0;
			_progressbar("pb1", _current_pb, 1);


            document.getElementById('url_button').disabled = true;
            document.getElementById('url_button').value = "Идет загрузка...";

            document.getElementById('url_list').disabled = true;

            user = 'skolopendre';

            str2 = str.split("\n"); //
            str2 = arrayUnique(str2);

			//image_name = document.getElementById('image_name_url').value;
            //width = document.getElementById('width_image_url').value;
			image_name = $('#_url_name').attr('value');


            status_step = 100 / str2.length;

            $("#url_uploading_result").empty();
            //document.getElementById('progressbar').style.width = "0px";
            //document.getElementById('progressbar').style.display = "block";
            //return false;

            doLoaderUrl(str2, image_name);

         }

    });
});

function doLoaderUrl(str2, image_name) {

		        if(str2 == '') {
                   // if(str2.length == x) {
            			document.getElementById('url_list').value = "";
            			document.getElementById('url_list').disabled = false;
            			document.getElementById('url_button').disabled = false;
            			document.getElementById('url_button').value = "Загрузить";

                   // }
					//alert('yo');
                	return false; // загрузка завершена
                }
				doUploadByUrl(str2[0], image_name);
}


function doUploadByUrl(url, image_name)
{
		id_folder = $('#id_folder').attr('value');
		width_prev = $('#_url_width_prev').attr('value');
		width = $('#_url_width').attr('value');
$.getJSON('/index_ajax.php', {task: 'images', sub_task: 'urlupload', url: escape(url), id_folder: id_folder, image_name: image_name, width_prev: width_prev, width: width}, function(obj){
        $('#_loading').empty();
		if(obj.iSuccess != 1) {
          //$('#_submit').hide();
		  //_showError(obj.sErrorMessage);
          //return false;
		  $("<div><small>Ошибка загрузки "+url+": [<font color=\"red\">"+obj.sErrorMessage+"</font>]</small></div>").appendTo("#report_url");
        } else {
			$("<div><small>Изображение "+url+" успешно загружено.</small></div>").appendTo("#report_url");
		}

		//alert(status_step);
		str2.shift();
		_current_pb = _current_pb + status_step;
        _progressbar("pb1", _current_pb, 1);
		doLoaderUrl(str2, image_name, width);

   	});

}
function toggleAll(work_div) {
    var allCheckboxes = $("#"+work_div+" input:checkbox:enabled");
	var notChecked = allCheckboxes.not(':checked');
    if(!$('#_checker').attr('checked')) {
    	allCheckboxes.removeAttr('checked');
    } else { 
    	notChecked.attr('checked', 'checked');
    }

}
$(function(){
	$('#_delete_form').submit(function() {
	 var allCheckboxes = $("#allimages input:checkbox:enabled:checked");
     if(!allCheckboxes.length) {alert('Выберите изображения для удаления!');return false;}
    	if(!window.confirm("Удалить?")) {return false;}
    });
});

function __getCode(id_image, clear) {
    if(clear == 1) {
		$('#_code1,#_code2,#_code3').attr('value', '');
	}
	var sLink = $('#__code_link_'+id_image).attr('value');
	var sPreviewUrl = $('#__code_preview_'+id_image).attr('value');

	$('#_code1').attr('value', $('#_code1').attr('value') + sLink + "\n");
	$('#_code2').attr('value', $('#_code2').attr('value') + '[URL='+sLink+'][IMG]'+sPreviewUrl+'[/IMG][/URL]' + "\n");
	$('#_code3').attr('value', $('#_code3').attr('value') + '<a href="'+sLink+'" target="_blank"><img src="'+sPreviewUrl+'"></a>' + "\n");

	if(clear == 1) {
		_codePopup();
	}
}

function __getCodes() {
	$('#_code1,#_code2,#_code3').attr('value', '');
	 var allCheckboxes = $("#allimages input:checkbox:enabled:checked");
     if(!allCheckboxes.length) {alert('Выберите изображения!');return false;}
	  var arCheckBoxes = new Array();
     allCheckboxes.each(function(i, n) {
         arCheckBoxes[i] = $(this).val();
		 if($(this).val() != 0) {
			__getCode($(this).val(),0);
		 }
	 });
	 _codePopup();
}

function __deleteFolder(id_folder, name) {
	if(!window.confirm("Удалить папку \""+name+"\"?")) {return false;}
	$.getJSON('/index_ajax.php', {task: 'folders', sub_task: 'delete', id_item: id_folder}, function(obj){
		if(obj.iSuccess != 1) {
		  _showError(obj.sErrorMessage);
          return false;
        }
		$('#_folder_'+id_folder).hide();
   	});
}


$(function(){
	$('.name_img1').click(function() {
	  var image_name = $(this).text();
	  $(this).hide();
	  $('#_edit_'+$(this).attr('idimg')).html('<input type="text" class="edit_input" id="_edit_input_'+$(this).attr('idimg')+'" value="'+image_name+'"> <img src="/img/disk.png" style="cursor:pointer" title="Сохранить" onClick="__saveName('+$(this).attr('idimg')+')">').show();
	  //$('_edit_'+$(this).attr('idimg')).show();
	  //$(this).html('<input type="text" class="edit_input" value="'+image_name+'">');
	});
});

function __saveName(id_image) {
	var new_name = $('#_edit_input_'+id_image).attr('value');
	if(new_name == '') return false;
	$.getJSON('/index_ajax.php', {task: 'images', sub_task: 'update_name', id_item: id_image, image_name: new_name}, function(obj){
		if(obj.iSuccess != 1) {
		  _showError(obj.sErrorMessage);
          return false;
        }
		$('#_edit_'+id_image).hide();
		$('#_name_'+id_image).html(new_name);
		$('#_name_'+id_image).show();
   	});
}
$(function(){
	$('._ya_2000_kote').click(function() {
		$.getJSON('/ajax/'+$(this).attr('idu')+'/'+$(this).attr('idi')+'/', {}, function(obj){
			if(obj.iSuccess != 1) {
			_showError(obj.sErrorMessage);
			return false;
			}
		});
	});
});

function __showImageContent() {
	$('#_loading').hide();
	$('#_content').slideDown(2000);
}

// PK uplod
function __pkUpload() {
	width_prev = $('#_pk_width_prev').attr('value');
	width = $('#_pk_width').attr('value');

	if(width_prev < 150 || width_prev > 400) {
		alert('Ошибка: Размер превью должен быть не менее 150 и не более 400px');
        return false;
	}

	if(width != '') {
		if(width < 400) {
			alert('Ошибка: Обрезать фото можно максимум до 400px');
			return false;
		}
	}
	image_name = $('#_pk_name').attr('value');
	$.getJSON('/index_ajax.php', {task: 'images', sub_task: 'uploadset', image_name: image_name, width_prev: width_prev, width: width}, function(obj){
		if(obj.iSuccess != 1) {
		  _showError(obj.sErrorMessage);
          return false;
        }
		$('#file_upload').uploadifyUpload();
   	});
}
