﻿var ajaxLoadContent, tooltip, otk, bAnchor = null, scroll = true, current = 0;
$(function () {
	setInterval("checkAnchor()", 500);

	ajaxLoadContent = function (url, target, callback, searchForChildren) {
		var obj = $(target);
		if ($(target).attr('id') == "content") $('#content > .fixed_top_panel, #content > .sort_top_panel').remove();
		if ((typeof searchForChildren == "undefined") || (searchForChildren != false)) //determine, do we in content or not
			var api = $(obj).find('.content');
		else
			var api = $(obj);
		api = api.jScrollPane({ showArrows: true, verticalGutter: 0, maintainPosition: false }).data('jsp');
		api.scrollToX(0); // !HACK to scroll to the left after catalog
		api.reinitialise({contentWidth: 2});
		var scp = $(obj).find('.jspPane');
		$.ajax({
			url: url,
			success: function (data) {
				$(scp).append(data);
				api.reinitialise();
				callback(api);
			},
			beforeSend: function () {
				$(scp).empty();
				$(obj).show(300, function () { api.reinitialise(); });
				$(scp).append('<div class="loading"></div>');
			},
			complete: function () {
				$(scp).find('.loading').remove();
			}
		});
	}
	
	function _anchor(link,e) {
		e.preventDefault();
		url = $(link).attr('href');
		window.location.hash = "/"+url;
	}
	
	/* Horizontal layout through table with 1 row */
	$("#horizontal").wrapInner("<table cellspacing='0'><tr>");
	$(".cell").wrap("<td>");
	//$('.container').width($('#content').width() + 500); // !HACK: IE 9 cannot resize container width to fit #content width
	
	$('#header .menu a, .ceiling a:not(.admin), .catalog a, .projects a, .filters.top a').live("click", function(e) {
		_anchor($(this), e);
	})
	
	/* Scrolling for 1 column */
	setTimeout("API = $('.column.first').jScrollPane({ showArrows: true, verticalGutter: 0 }).data('jsp')", 500); // !HACK: dont know why we need to wait, otherwise it didnt initialise everytime normally

	/* First column link click handler*/
	$('.column.first a:not(.list, .grid, .table), a.house').live("click", function (e) {
		_anchor($(this), e);
	});
	/* First column link hover handler*/

	tooltip = function() {
		$('.column.first a:not(.list, .grid, .table), .catalog a:not(.list, .grid, .table), .projects li').tooltip({
			delay: 0,
			showURL: false,
			bodyHandler: function () {
				return '<img src="' + $(this).find('img').attr('src').replace('/100/', '/200/') + '"/>';
			}
		});
	}
	
	tooltip();
	
	otk = function() {
		$('#otk1, #otk2').tooltip({
			delay	:	0,
			showURL	:	false,
			fade	:	250,
			bodyHandler: function () {
				return '<img height="500" src="' + $(this).attr('src') + '"/>';
			}
		});
	}
	
	/* 01 02 03 04 folders click */
	$('.files > li > a').live('click', function(e){
		e.preventDefault();
		$(this).siblings('div').toggle();
	});

	//otk();

	/* Triggers to hide columns */
	$('.column .trigger').live("click", function (e) {
		e.preventDefault();
		$(this).parents('.column:not(:animated)').toggleClass('closed', 300);
		/*if ($(this).parents('.column.second').length > 0) { //we have triggered 2 column, toggle top filters
		$('.filters.top').toggle(300);
		}*/
	});

	/* Close button closes object panel, clicking around the panel also closes it */
	$('.close, #fade').live("click", function (e) {
		e.preventDefault();
		$("#object, #fade").fadeOut(500);
	});

	/* Second Column ajax calls */
	$('.mainmenu a').click(function (e) {
		_anchor($(this), e);
	});

	/* Secondmenu ajax calls */
	$('.secondmenu a').live("click", function (e) {
		_anchor($(this), e);
	});
	
	removeEmpty = function(s) { //selector
		$(s).each(function() {
			if ($(this).text().replace(/\s/g, '').length < 6) // if empty or contains <br> only
				$(this).remove();				
		});
	}
	
	/* =============== SORTING ================ */
	sorting = function(v, o){
		$.tinysort.defaults.order = o;
		
		//alphabetically
		if(v == "a"){ 
			if ($('.press').length > 0){ //press list
				$('.press.list h2, .press.list h4, .press.list .interest').remove();
				$('.column.third .content').data('jsp').reinitialise();
				$('.press.list li').tsort('a');
			}
			if ($('.catalog').length > 0) { //catalog
				$('.catalog ul > span').remove();
				$('.catalog li').tsort('span').each(function(i){
					$(this).appendTo('.catalog ul:eq('+ Math.floor(i / 12) +')');
				});
				removeEmpty('.catalog ul');removeEmpty('.catalog td'); //fix container width for correct scrolling
				$('#content').data('jsp').reinitialise({contentWidth: $('.catalog > table').width()});
			}
			if ($('.projects').length > 0) { //projects
				$('.projects li').tsort('span.title').each(function(i){
					$(this).appendTo('.projects ul:eq('+ Math.floor(i / 5) +')');
				});
			}
		}
		
		// by date
		if (v == "d"){
			if ($('.press').length > 0){ //press, news
				if (o == "desc")
					ajaxLoadContent(window.location.hash.substr(2).split("/")[0], $('.column.third'), function(){});
				else {
					$('.press.list h2, .press.list h4, .press.list li.interest').remove();$('.column.third .content').data('jsp').reinitialise();		
					$('.press.list li').tsort({attr: 'class'});
				}	
			}
			if ($('.catalog').length > 0) { //catalog
				$('.catalog ul > span').remove();
				$('.catalog li').tsort('a', {attr: 'class'}).each(function(i){
					$(this).appendTo('.catalog ul:eq('+ Math.floor(i / 12) +')');
				});
				removeEmpty('.catalog ul');removeEmpty('.catalog td'); //fix container width for correct scrolling
				$('#content').data('jsp').reinitialise({contentWidth: $('.catalog > table').width()});
			}
			if ($('.projects').length > 0) { //projects
				$('.projects li').tsort('a', {attr: 'class'}).each(function(i){
					$(this).appendTo('.projects ul:eq('+ Math.floor(i / 5) +')');
				});
			}
		}
		
		//by price in catalog
		if (v == "p"){
			if ($('.catalog').length > 0) { //catalog
				$('.catalog ul > span').remove();
				$('.catalog li').tsort('b').each(function(i){
					$(this).appendTo('.catalog ul:eq('+ Math.floor(i / 12) +')');
				});
				removeEmpty('.catalog ul');removeEmpty('.catalog td'); //fix container width for correct scrolling
				$('#content').data('jsp').reinitialise({contentWidth: $('.catalog > table').width()});
			}
		}
		
		// by square
		if (v == "s") { 
			if ($('.catalog').length > 0) { //catalog
				$('.catalog ul > span').remove();
				$('.catalog li').tsort('i').each(function(i){
					$(this).appendTo('.catalog ul:eq('+ Math.floor(i / 12) +')');
				});
				removeEmpty('.catalog ul');removeEmpty('.catalog td'); //fix container width for correct scrolling
				$('#content').data('jsp').reinitialise({contentWidth: $('.catalog > table').width()});
			}
			if ($('.projects').length > 0) { //projects
				$('.projects li').tsort('b').each(function(i){
					$(this).appendTo('.projects ul:eq('+ Math.floor(i / 5) +')');
				});
			}
		}
		
		//by collection
		if (v == "c"){ 
			if ($('.projects').length > 0) { //projects
				$('.projects li').tsort('span.z').each(function(i){
					$(this).appendTo('.projects ul:eq('+ Math.floor(i / 5) +')');
				});
			}
		}
		
		//by roads and alphabet in catalog
		if (v == "sa"){
			if ($('.catalog').length > 0) { //catalog
				if (o == "desc")
					ajaxLoadContent(window.location.hash.substr(2).split("/")[0], $('#content'), function(){}, false);
				else {
					ajaxLoadContent(window.location.hash.substr(2).split("/")[0]+'/all/desc', $('#content'), function(){}, false);
				}
			}
		}
		
	}
	
	$('.sorting a').live("click", function(e){
		e.preventDefault();
		sorting($(this).attr('href').substring(1), $(this).attr('class'));
		if ($(this).hasClass('asc')){
			$('.sorting a').removeClass('asc').removeClass('desc');
			$(this).addClass('desc');
		} else {
			$('.sorting a').removeClass('asc').removeClass('desc');	
			$(this).addClass('asc');
		}
	});
	/* =============== ^SORTING^ ================ */
	
	/*$('.sort_top_menu .sizes .list').live("click", function () {
		$('.catalog').removeClass('grid').removeClass('table');
		$('.catalog').addClass('list');
	});
	$('.sort_top_menu .sizes .grid').live("click", function () {
		$('.catalog').removeClass('list').removeClass('table');
		$('.catalog').addClass('grid');
	});
	$('.sort_top_menu .sizes .table').live("click", function () {
		$('.catalog').removeClass('list').removeClass('grid');
		$('.catalog').addClass('table');
	});*/

	$('.sizes .list').live("click", function () {
		$(this).parents('.column').removeClass('grid').removeClass('table');
		$(this).parents('.column').addClass('list');
	});
	$('.sizes .grid').live("click", function () {
		$(this).parents('.column').removeClass('list').removeClass('table');
		$(this).parents('.column').addClass('grid');
	});
	$('.sizes .table').live("click", function () {
		$(this).parents('.column').removeClass('list').removeClass('grid');
		$(this).parents('.column').addClass('table');
	});
	

	/* Object's gallery init */
	galleryScroll = function () {
		if (!scroll) return;
		if ((count = $('.gallery td').size()) == 0) {
			current = 0;
			return;
		}
		if (++current >= count) current = 0;
		$('.gallery').scrollTo('td:eq(' + current + ')', 300);
	}

	/* Gallery thumbnails button */
	$(".gallery_thumbnails .button").live("click", function () {
		$('.gallery_thumbnails').toggleClass("closed", 300);
	});

	/* Gallery thumbnails img click */
	$(".gallery_thumbnails img").live("click", function () {
		$('.gallery').scrollTo('td:eq(' + (current = $(this).index()) + ')', 100);
		scroll = false;
	});

	$('.play').live("click", function () { scroll = true });
	$('.pause').live("click", function () { scroll = false });
	setInterval("galleryScroll()", 5000);
	
});

function checkAnchor() {
	if (window.location.hash != bAnchor) {
		bAnchor = window.location.hash;
		url = bAnchor.substr(2);

		flag = (typeof part1 == "undefined") ? false : (part1 == url.split("/")[0]);
		
		part1 = url.split("/")[0]
		part2 = url.split("/")[1];
		
		//swap menu in second column with poselok menu
		if (part1 != "dom-v-derevne") { 
			if ($('div.backup').html().length > 4) $('.column.second ul.menu').removeClass('menu').addClass('filters').html($('div.backup').html());	
		}
		
		//hide all sort
		$('.sorting li').hide();$('.sorting a[href=#a]').text('Название'); $('.sorting a[href=#s]').text('Площадь'); 
		
		//make links highlighted
		$('a.active').removeClass('active');
		$('a[href="'+part1+'"], a[href="'+part1+'/"]').addClass('active'); // a[href$="'+part1+'"] - проверка только окончания ссылки
		if (typeof part2 != "undefined") $('a[href*="'+url+'"]').addClass('active');
		
		switch (part1) {
		
		
			case "dom-v-derevne":
				$('#content').addClass('column');
				$('.column.third').hide();
				ajaxLoadContent(url, $('#content'), function () {
					var e = $('.column.second ul.filters');
					$('.column.second').removeClass('closed');
					$('div.backup').html($(e).html());
					$(e).addClass('menu').html($('#menu-poselok').html()).removeClass('filters');
					$('.fixed_top_panel').prependTo('#content');
				}, false);
				break;
				
				
			case "project":
				$('#content').addClass('column').addClass('table');
				
				$('.column.third').hide();
				$('.column.second.closed').removeClass('closed');
				
				ajaxLoadContent(url, $('#content'), function (api) {
					$('.sorting li:gt(0):lt(4)').show(); $('.sorting a[href=#a]').text('Название проекта'); //show sorting list
					$('.sort_top_panel').prependTo('#content'); //show area buttons for scrolling
					
					api.reinitialise({contentWidth: $('.projects > table').width()}); 
					
					//count elems by area
					/*$('.projects li').each(function(){
						var v = $(this).attr('class');
						$('.area > a').each(function(){
							var min = $(this).attr('class').split("-")[0];
							var max = $(this).attr('class').split("-")[1];
							if ((v >= min)&&(v <= max))	{
								var c = $(this).html();
								c++;
								$(this).html(c);
								return false;
							}
						});
					});*/
					
					$(".projects").mousewheel(function(event, delta) {  //horizontal mouse wheel scroll
					     api.scrollByX(-delta * 60);
					     event.preventDefault();
					});
					
					tooltip(); //preview on hover
					
					//filter elems by area
					$('.area a').each(function(){$(this).html($(this).attr('class')).live("click", function(e) {
						e.preventDefault();
						$('.area a.active').removeClass('active');
						$(this).addClass('active');
						var min = $(this).attr('class').split("-")[0];
						var max = $(this).attr('class').split("-")[1];
						$('.projects li').each(function(){
							if (($(this).attr('class') >= min) && ($(this).attr('class') <= max)) {
								api.scrollToElement($(this), true, true);
								return false;
							}
						});
					})});
					
					$('.area a:first').html('До 160');$('.area a:last').html('Более 900');
					
				}, false);
				break;
				
				
			case "frame":
			case "offer":
				$('#content').addClass('column');
				$('.column.third').hide();
				ajaxLoadContent(url, $('#content'), function () {}, false);
				break;
				
				
			case "catalog":
				$('#content').addClass('column').addClass('table');
				
				$('.column.third').hide();
				$('.column.second.closed').removeClass('closed');

				ajaxLoadContent(url, $('#content'), function (api) {
					
					$('.sort_top_panel').prependTo('#content'); //do nothing
					
					$('.sorting li:lt(4), .sorting li:eq(5)').show(); $('.sorting a[href=#s]').text('Площадь дома'); $('.sorting a[href=#a]').text('Населенный пункт'); //show sorting list
					
					api.reinitialise({contentWidth: $('.catalog > table').width()}); 
					
					tooltip(); //show tooltips on hover
					
					$(".catalog").mousewheel(function(event, delta) { //horizontal mousewheel scroll
					     api.scrollByX(-delta * 60);
					     event.preventDefault();
					});
					
				}, false);
				break;
				
				
			case "dom":
				$('.column.second.closed').removeClass('closed');
				$('.column.third').hide();
				if (part2 != "filter") {
					$('#content').addClass('column');
					ajaxLoadContent(url, $('#content'), function (api) {
						$('.fixed_top_panel').prependTo('#content');
						ziga = api;
						setTimeout("ziga.reinitialise()", 2000);
					}, false);
				} else {
					ajaxLoadContent(url, $('#house_list'), function (api) {
						api.destroy(); 
						$('.loading').remove(); 
						API.reinitialise(); 
						tooltip();
					}, false);
					var f = url.split("/")[2];
					if ($('.catalog').length > 0) { //if catalog is loaded in #content
						ajaxLoadContent("catalog/"+f, $('#content'), function (api) {
							var s = {contentWidth: $('.catalog > table').width()};
							api.reinitialise(s); 
							tooltip();
							$(".catalog").mousewheel(function(event, delta) {
							     api.scrollByX(-delta * 60);
							     event.preventDefault();
							});
						}, false);
					}
				}
				break;
				
				
			case "press":
			case "news":
			case "page":
				$('.column.third').show();
				$('.sorting li:gt(1):lt(2)').show();
				if (($('.column.third:hidden').length > 0)||(!flag)) // hidden
					ajaxLoadContent(part1 == "page" ? "press" : part1, $('.column.third'), function (api) {
						$('.column.second').removeClass('closed');
						if (!part2) window.location.hash = "/"+$('.press.list a:first').attr('href');
						}
					);
				if (part2) {
					$('#content').addClass('column');
					ajaxLoadContent(url, $('#content'), function () { $('a[href*="'+url+'"]').addClass('active'); }, false);
				}
				break;
			}
	}
}
