var JQ = jQuery.noConflict(),
	Pages = {};


document.observe("dom:loaded", function() {
	if(JQ('#homeMap').size()){
		fixPngVillage();
		homeHover(JQ); 
	}
	
	if(JQ('.catalogueHouseTable').size()){Pages.Catalogue(JQ)}
});



Pages.Catalogue = function($){
	//image easy load
	(function(){
		var timer = 0,
			
			houses = new function(){
				//privat members
				var idList = [],
					wrapList = [];
					
					
				//privileged members
				this.addItem = function(tmpId, jObj){
					idList.push(tmpId);
					wrapList.push(jObj);
				}
				
				this.drawImages = function(){
					if(idList.length > 0){
						$.ajax({
							type: 'POST',
							data: {'action': 'getImages', 'houseList': idList},
							url: '/action.php',             
							dataType : "json",                     
							success: function(data){
								for(var i=0; i<data.length; i++){
									var image = '<img class="hidden" src="'+data[i]+'"/>';
									wrapList[i].html(image).find('img').fadeIn('fast');
								}
								idList = [];
								wrapList = [];
							}
						});
					}
				}
			},
		
			_addViewportSelector = (function(){
				$.belowthefold = function(element) {
					var fold = $(window).height() + $(window).scrollTop();
					return fold <= $(element).offset().top;
				};

				$.abovethetop = function(element) {
					var top = $(window).scrollTop();
					return top >= $(element).offset().top + $(element).height();
				};
				
				$.inviewport = function(element) {
					return !$.belowthefold(element) && !$.abovethetop(element) && !$(element).has('img').size();
				};
				
				$.extend($.expr[':'], {
					"inViewportEmty": function(a){return $.inviewport(a);}
				});
			})(),
			
			_handler = function(){
				var inViewportEmtyList = $('.catalogueHouseTable td.preview a:inViewportEmty');
				inViewportEmtyList.each(function(){
					var id = $(this).parents('tr').attr('id');
					houses.addItem(id, $(this));
				});
				houses.drawImages();
			};
		//var end
		
		
		//preloader
		(function(){
			var preloadImages = $('.catalogueHouseTable td.preview .preloaderImg'),
				_offset = 0;
			setInterval(function(){
				preloadImages.css({backgroundPosition: 'left '+_offset+'px'});
				_offset = _offset - 40;
				if(_offset == -480)
					_offset = 0;
			}, 50);
		})();
			
			
		_handler();
		$(window).scroll(function(){
			if(timer){
				clearTimeout(timer);
				timer = 0;
			}
			timer = setTimeout(_handler, 500);
		});
	})();
}



function homeHover($){
	var villageArr = [];
	
	
	$('.homeHouse').hover(
		function(){
			village = new Village($(this));
			village.showIt();
		}, 
		function(){
			village.hideIt();
			village={};
		}
	);
	
	
	
	Village = function(objJQ){
		var id = objJQ.attr('id'),
			animTime = 200,
			content = objJQ.find('.content');
			
				
		this.showIt = function(){
			objJQ.css({'z-index':'6'});
			content.fadeIn(animTime);
		};
		
		
		this.hideIt = function(){	
			content.fadeOut(animTime, function(){objJQ.css({'z-index':'5'});});
		};
		
		
		if(villageArr.indexOf(id) == -1){
			villageArr.push(id);
			
			
			$.ajax({
				type: 'POST',
				data: {'action': 'getHouses', 'village': id},
				url: '/action.php',             
				dataType : "json",                     
				success: function(data){
					var houseList = "",
						villageName = data[0].name,
						colNum = 0,
						wrapWidth = 0;
					
					
					data.shift();
					
					$(data).each(function(i){
						houseList +='\
							<div class="out" onMouseOver="this.className=\'over\'" onMouseOut="this.className=\'out\'" onClick="document.location = \'/cottages/'+this.id+'/\'">\
								<a href="/cottages/'+this.id+'/">\
									<img src="'+this.preview+'"/>\
								</a>\
								<p>\
									Дом:&#160;'+this.house_area+'&#160;м<sup>2</sup><br/>\
									Участок:&#160;'+this.garden_area+'&#160;сот.<br/>\
									От&#160;МКАД:&#160;'+this.mkad_range+'&#160;км\
								</p>\
								<strong>'+this.price+'&#160;'+this.currency+'</strong>\
							</div>\
						';
					})
					
					
					if(data.length == 1)
						colNum = 1;
					else if(data.length == 2)
						colNum = 2;
					else
						colNum = 3;
					
					wrapWidth = colNum*120;
					
					
					houseList = '\
						<h1><a href="/villages/'+id+'/">'+villageName+'</a></h1>\
						<div class="homeHouseBlock" style="width:'+wrapWidth+'px">\
							'+houseList+'\
						</div>'
					;
					
					content.append(houseList);
				}
			});
		}
	}
	
	
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
	
}



function toogleObj(link, obj_id, on_class, off_class, on_link, off_link)
{
	var obj = $(obj_id);
	obj.className = obj.className == off_class ? on_class : off_class;
	link.className = link.className == off_link ? on_link : off_link;
}



function fixPngVillage()
{
	if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent) && navigator.userAgent.search("Opera") < 0){
		document.getElementById('homeVillageBlock').className = 'pngVillageFix';
	}
}



function showLoad () {
	$('load').style.display = 'block';
}



function resortHome(viewPage){
	var house_area_from = $F('house_area_from');
	var house_area_to = $F('house_area_to');
	var garden_area_from = $F('garden_area_from');
	var garden_area_to = $F('garden_area_to');
	var mkad_range_from = $F('mkad_range_from');
	var mkad_range_to = $F('mkad_range_to');
	var price_from = $F('price_from');
	var price_to = $F('price_to');
	var house_id = $F('house_id');

	var url  = '/action.php';
	var pars = 'action=resort&view='+viewPage+'&house_area_from='+house_area_from+'&house_area_to='+house_area_to+'&garden_area_from='+garden_area_from+'&garden_area_to='+garden_area_to+'&mkad_range_from='+mkad_range_from+'&mkad_range_to='+mkad_range_to+'&price_from='+price_from+'&price_to='+price_to+'&house_id='+house_id+'&nocahe='+Math.random();

	var myAjax = new Ajax.Request(url, {
		method: 'get', parameters: pars,
		onCreate: showLoad(),
		onComplete: function(transport) {

			$('load').style.display = 'none';
			
			var response = transport.responseXML.documentElement;
			//alert(transport.responseText);
			var result = response.getElementsByTagName('village');
			for (var i = 0; i< result.length; i++){
				var vID = result[i].getAttribute('id');
				//var total = result[i].getAttribute('total');

				var houseList = result[i].getElementsByTagName('house');
				var hideList = result[i].getElementsByTagName('hide');
				var total = houseList.length;

				for (var j = 0; j< hideList.length; j++){
					var hideID = hideList[j].getAttribute('id');
					$(hideID).style.display = 'none';
				}

				for (var s = 0; s< houseList.length; s++){
					var showID = houseList[s].getAttribute('id');
					$(showID).style.display = 'block';
				}

				var tmp_village = $(vID);
				if(tmp_village!=null){
					if(total > 0){

						var block_div = $('block_'+vID);

						
						if(total == 1)
							block_div.style.width = '120px';
						if(total == 2)
							block_div.style.width = '240px';							
						if(total > 2)
							block_div.style.width = '360px';	
							
						var count_span = $('count_'+vID);
						count_span.innerHTML = total;
						
						tmp_village.style.display = 'block';
					}else{
						tmp_village.style.display = 'none';
					}
				}

			}
		} 
	});
}


function ShowArenda(){
	
	var url  = '/action.php';
	var pars = 'action=show_arenda&nocahe='+Math.random();

	var myAjax = new Ajax.Request(url, {
		method: 'get', parameters: pars,
		onCreate: showLoad(),
		onComplete: function(transport) {

			$('load').style.display = 'none';
			
			var response = transport.responseXML.documentElement;
			//alert(transport.responseText);
			var result = response.getElementsByTagName('village');
			
			var L = result.length;
			
			for (var i = 0; i<L; i++){
				var vID = result[i].getAttribute('id');
				var vTotal = result[i].getAttribute('total');
								
				var tmp_village = $(vID);
				if(tmp_village!=null){
					if(vTotal != 0){
						var count_span = $('count_'+vID);
						count_span.innerHTML = vTotal;
						tmp_village.style.display = 'block';
					
					}else{
						tmp_village.style.display = 'none';
					}
				}

			}
		} 
	});
}



function resortCatalogue(){
	var house_area_from = $F('house_area_from');
	var house_area_to = $F('house_area_to');
	var garden_area_from = $F('garden_area_from');
	var garden_area_to = $F('garden_area_to');
	var mkad_range_from = $F('mkad_range_from');
	var mkad_range_to = $F('mkad_range_to');
	var price_from = $F('price_from');
	var price_to = $F('price_to');
	var house_id = $F('house_id');

	var url  = '/action.php';
	var pars = 'action=resort&house_area_from='+house_area_from+'&house_area_to='+house_area_to+'&garden_area_from='+garden_area_from+'&garden_area_to='+garden_area_to+'&mkad_range_from='+mkad_range_from+'&mkad_range_to='+mkad_range_to+'&price_from='+price_from+'&price_to='+price_to+'&house_id='+house_id+'&nocahe='+Math.random();

	var myAjax = new Ajax.Request(url, {
		method: 'get', parameters: pars,
		onCreate: showLoad(),
		onComplete: function(transport) {
			$('load').style.display = 'none';
			
			var response = transport.responseXML.documentElement;
			var result = response.getElementsByTagName('village');
			for (var i = 0; i< result.length; i++){
				var vID = result[i].getAttribute('id');

				var houseList = result[i].getElementsByTagName('house');
				var hideList = result[i].getElementsByTagName('hide');
				var total = houseList.length;

				for (var j = 0; j< hideList.length; j++){
					var hideID = hideList[j].getAttribute('id');
					$(hideID).className = 'rowHide';
				}

				for (var s = 0; s< houseList.length; s++){
					var showID = houseList[s].getAttribute('id');
					$(showID).className = 'rowShow';
				}
			}
			lazyImgObj.handler(); //картинки домиков
		} 
	});
}
	
	
/*
document.onload = function(event){
	
}
*/

/*
document.onmousedown = function(event){
	var homeMap = $('homeMap');
	var obj = $('cursorPos');
	if(event.pageX || event.pageY){
		var x = event.pageX;
		var y = event.pageY;
	}else{
		var x = event.clientX;
		var y = event.clientY;
	}
	y -= homeMap.offsetTop;
	
	obj.style.left = x;
	obj.style.top = y;
	x -= 12;
	y -= 37;
	obj.innerHTML = x + ", " + y;
}
*/






















