$(document).ready(
   function() {
		/* версия браузера */
		$.each($.browser, function(i, val){
			if (true === val) {
				browserName = i;
			}
		});

		try{
			$("#categories").covers();
		} catch(e){
		}

		try{
			$("#previews").covers();
		} catch(e){
		}

		/*
		 * • Настройка формы обратной связи
		*/
		try {
			$("#feedback").submit(function() {
				$(this).ajaxSubmit({
					type: "POST",
					dataType:  'json',
					url: "/contacts/",
					beforeSubmit: showRequest,
					success: showResponse,
					notsuccess: errorAjax,
					timeout: 3000
				});
				return false;
			});
		} catch(e) {
		}


		/* «сворачивание» контента внутри класса more */
		if (moreContent = $(".more")) {				
				var firstChild = $(moreContent).children()[0];				
				var content = $(moreContent).wrap('<div></div>').parent();

				$(content).append(firstChild);
				$(content).append(moreContent);

				$(moreContent).toggle();

				$(firstChild).children("a").click(function(){
						$(moreContent).toggle();
						return false;
				});
		}
		
	}
);

$.fn.covers = function(options){
	var container = this;
	var list = $(this).children("li");

	if (0 <= list.length) {

		$(list[0]).addClass("active");
		$("#illustration").attr("src", $(list[0]).children("a").attr("href"));

		list.each(function(){
			$(this).children("a").click(function(){
				resetClassInCollection(list, "active");
				
				$("#illustration").attr("src", $(this).attr("href"));
				$(this).parent().addClass("active");
				return false;
			});
		});
	}
}

function resetClassInCollection(collection, className) {
	if (0 <= collection.length) {
		$(collection).each(function(){
			$(this).removeClass(className);
		});
	}
	return true;
}

/*
 * • Обработка формы обратной связи
*/
function showRequest(formData) {
	$("#feedback #send-button").attr("disabled", "disabled");
	$("#feedback #formsend-icon img").css("visibility", "visible");
    return true;
}

function showResponse(responseText, statusText)  {
	if ("success" == statusText) {
		$("#feedback #send-button").attr("disabled", "");
		$("#feedback #formsend-icon img").css("visibility", "hidden");

		if (responseText.success) {
			$("#feedback").resetForm();
		}
		displayErrors(responseText, "#error_message");
		$("#scode-img").attr("src", "/getimage/contacts/?" + Math.random());
	}
}

function errorAjax(statusText) {
	alert("error = " + statusText);
}

function displayErrors(responseText, container_id) {
	$(container_id).empty();
	$.each(responseText, function(key, item) {
		$(container_id).append("<span class='error'>" + item + "</span>");
		$(container_id).append("<br/>");
	});
}
