// main logic and events bindings
// by Melnychuk Oleg  [http://my.opera.com/melnichuck]

/******************************************************

	MAP BUSINESS LOGIC
	map manipulations

******************************************************/

$(document).ready(function() {
	// configure default ajax settings
	$.ajaxSetup({
		type: 'POST',
		async: false,
		url: CONFIG.host.name + CONFIG.host.map, // default one, should be overriden when needed
		dataType: 'json',
		success: function(res) { return res; },
		error: function(obj, errString) {
			alert(this.url+ "\n\n" +errString+ " " +obj.status+ ", " +obj.statusText);
 		}
	});
	
	jQuery.validator.setDefaults({
		//debug:true
		errorLabelContainer: $(this).find('.errorMessage'),
		wrapper: "li"
	});
	
	// alter all empty # attributes
	$("a[href=#]").attr({ href: "javascript:void(0);" });

	// creating and configuring the system
	var iface	= new Interface();
	var map		= new Map();

	iface.initialize();
	Interface.setMapImage(map.updateMap());	// get the map image for the current window size
	Interface.setMiniImage(Map.getMini());
	
	
	// activating the selected tool
	$('.tools a').click(function(){ 
		iface.setCurrentTool(this);
		iface.setMapCursor(this);
	});
	
	$('#sidetoolbar li').click(function(){ iface.setActiveItem(this); });

	$('#sidebar .item h2').click(function(){
		iface.setActiveItem($(this).parent());
		iface.setSidebarActiveItemHeight();
		
		switch ($(this).parent().attr("id")){
			case "side-user":
				Interface.fetchContents("#side-user .content", "LOGIN_FORM", true);
				break;
			default:
				break;
		}
	});
	
	// deactivate other radio toolbar buttons
/*	$('.radio li a').click(function(){
		$('.radio li').not(this).removeClass("active");
		iface.setMapCursor($(this).find("a"));
	});
*/
	$(window).resize(function(){
		// updating interface
		iface.update();
		Interface.setMapImage(map.updateMap());
		Interface.setMiniImage(Map.getMini());
	});
	
	$('#header h1').hover(
		function() { $('#header ol').stop().show().fadeTo(0, 1); },
		function() { $('#header ol').stop().fadeOut("slow"); }
	);
	$('#header ol').hover(
		function() { $(this).stop().fadeTo(0, 1); },
		function() { $(this).stop().fadeOut("slow"); }
	);
	
	//**********************************

	$('#map').click(function(evt){
		if (!iface.getClickCoordinates(evt, "main")){
			alert(MSG.error.uns_browser);
		} else {
			// going to check what to do next
			switch (iface._curr_tool){
				case CONFIG.tool.zoom_in:
					Interface.setMapImage(map.zoomIn());
					iface.resetMapOffset();
					Interface.setMiniImage(Map.getMini());
					break;
				case CONFIG.tool.zoom_out:
					Interface.setMapImage(map.zoomOut());
					iface.resetMapOffset();
					Interface.setMiniImage(Map.getMini());
					break;
				case CONFIG.tool.move:
					break;
				case CONFIG.tool.pointer:
					if ($('#sidebar .active').attr("id") != "side-error") {
						// just pick the info about the clicked object
						var foundObjects = map.point(CONFIG.coords.mainX, CONFIG.coords.mainY);
						iface.showFoundObjects(foundObjects);
						iface.resetMapOffset();
						Interface.setMiniImage(Map.getMini());
					} else {
						// fetch error form contents
						bug_type = $("#bugtype").val();
						Interface.fetchContents("#side-error .content", "ERROR_FORM", true, false, bug_type);
					}
					break;
				default:
					break;
			}
		}
	});
	
	$('#map').load(function() {
		$(this).fadeTo("fast", 1.0);
		iface.resetMapOffset();
		iface.setStatus(MSG.Status.okay);
	});
	
	//**********************************
	
	// select the default text on focus
	$('#query').focus(function(){ $(this).select(); });
	$('#query').keydown(function() { $('#results').hide(); });

	// search form validation
	$('#search-form').validate({
		rules: {
			query: {
				required: true,
				minlength: 3
			}
		},
		messages: {
			query: {
				required: "Введите запрос для поиска",
				minlength: "Длина меньше 3х символов"
			}
		},
		submitHandler: function(){
			// searching for query
			var foundObjects = map.findObjects($('#query').val());
			iface.showFoundObjects(foundObjects);
			Interface.setMiniImage(Map.getMini());//map.updateMini());
			iface.fitItemHeight();
		}
	});
	
	// registration form validation
	$('#registerForm').validate({
		rules: {
			reg_email: {
				required: true,
				email: true
			},
			reg_password: {
				required: true,
				minLength: 5
			},
			reg_repassword: {
				required: true,
				minLength: 5,
				equalTo: "#reg_password"
			}
		},
		messages: {
			reg_email: "Введен неправильный e-mail адрес",
			reg_password: {
				required: "Пожалуйста, введите пароль",
				minLength: "Длина пароля меньше 5 символов"
			},
			reg_repassword: {
				required: "Пожалуйста, введите пароль",
				minLength: "Длина пароля меньше 5 символов",
				equalTo: "Пароль и подтверждение не совпадают"
			}
		},
		errorLabelContainer: $('#messageBox'),
		wrapper: "li"
	});
	
});
