$(document).ready(function() {
    slider('#js-slider');
    gallery('.gallery');
    introFlash();
    printMap();
    
    houses('.scheme .info'); // map
    house('.house');
});	

$(window).load(function() {
	centerImage('.img img');
});

function house(s) {
	var $house = $(s);
	
	if ( 1 == $house.length ) {
		var num = new Object();
		// all needed numbers
		num.house = parseInt(location.href.charAt(location.href.length-1));
		num.porch = 1; 
		num.floor = 2; 
		
		var data = new Object();
		data.porches = false;
		
		// needed elements
		var $floors = $('.select > .floor .scheme', $house);
		var $aptInfo = $('.apartments-info table', $house);
		var $aptTypes = $('.types table', $house);
		var $porches = $('.select > .porch', $house);
		
		// setting house number on the plan (once at load)
		var $plan = $house.find('.houses-plan');		
		$plan.addClass('loading');

		// preloading plan image
		var tempPlan = new Image();
		$(tempPlan).load(function() {
			if ( 1 == $plan.length ) {
				var $activeHouse = $('li.house-' + num.house, $plan);
			
				$activeHouse.addClass('selected');
				$('a', $activeHouse).click(function(e) { 
					e.preventDefault();
				});	
			}
			
			$plan.removeClass('loading');
		}).attr('src', '/images/map/houses-plan.png');
		
		// setting porches (once at load)
		if ( 1 == $porches.length ) {
			// setting house number
			$porches.find('.house-0').removeClass().addClass('house-' + num.house);
			
			// setting porch numbers
			$porches.find('ul li').each(function(i) {
				var garageLink = 'garazh';

				// adding garage if there's any
				if ( -1 == $('a', $(this)).attr('href').indexOf(garageLink) ) {
					$(this).addClass('porch-' + (i+1) )
				} else {
					$(this).addClass('garage');
					$('ul', $floors).append($(this));
				}
			});
		}
		
		// setting legend
		var flatTypes = getFlatTypes($aptTypes);
		var $legend = $('.select .floor .legend ul.free', $house);
		$('li', $legend).each(function(i) {
			$('p', this).text(flatTypes[i].name);
		});
		
		// click handlers
		$('ul li > a', $porches).each(function(i) {
			$(this).click(function(e) {
				if ( !$(this).parent().hasClass('selected') ) {
					num.porch = i+1;
		
					// setting selected state
					$(this).parent().siblings().removeClass('selected');
					$(this).parent().addClass('selected');
		
					// downloading data
					$.ajax({
						url: $(this).attr('href'),
						success: function(result) {
							data.porches = $(result).find('.floors');
						}, 
						complete: function() {
							// selecting the second floor initially
							$('li.floor-2', $floors).click();
						}
					});
			
					// setting apartments
					var $apts = houseApartments(num.porch, $aptInfo, $aptTypes);
					$('li span', $floors).remove();
					
					$('li', $apts).each(function() {
						$('li.' + this.className, $floors).append($(this).html());
					});
			
					// setting scheme name
					$('h3', $floors).text($(this).text());
					
					// removing porch classes
					$('li', $floors).removeClass('selected');
				}
				
				e.preventDefault();
			});
		});
		
		$('li', $floors).each(function(i) {
			$(this).click(function(e) {
				if ( !$(this).hasClass('selected') ) {
					// if we click with mouse button scroll to the plan
					if ( typeof e.which !== "undefined" ) {
						if ( $('#plans').length ) {
							$.scrollTo('#plans', 200);
						}
					}
				
					// setting class
					$(this).siblings().removeClass('selected');
					$(this).addClass('selected');
				
					// image element
					var $floorImage = $('.plans > .floor-image', $house);
					var tempImg = new Image();
					var imgSrc = false;
					
					// Floors header
					var $floorHeader = $('.plans > h2', $house);

					// other elements
					var $galleryCont = $('.house-photos');
					var $tableAndText = $('.house-group', $house);
					var $garageDesc = $('.garage-desc');

					// preloading class
					$floorImage.addClass('loading');

					// ordinary floors
					if ( !$(this).hasClass('garage') ) {
						// floor number is needed for other functions
						num.floor = i+2;
				
						// showning floor data
						$tableAndText.show();
						
						// hiding garage data
						$floorHeader.show().filter('.garage').hide();
						$garageDesc.hide();
				
						// changing floor plan
						imgSrc = $(data.porches).find('li').eq(i).find('img').attr('src');
						
						$(tempImg).load( function() {
							$('img', $floorImage).attr('src', imgSrc);
							$('a', $floorImage).attr('href', imgSrc)
						
							$floorImage.removeClass('loading');
						}).attr('src', imgSrc);	
					
						// and text
						$('span', $floorHeader).text($(data.porches).find('li').eq(i).find('h2 a').text());
		
						data.gallery = false;
		
						// loading gallery photos
						var galleryUrl = $(data.porches).find('li').eq(i).find('h2 a').attr('href');
						var $itemGallery = false;
					
						$.ajax({
							url: galleryUrl,
							success: function(data) {
								$itemGallery = $('.gallery', $(data)).add($('.urls', $(data)));
							}, 
							complete: function() {
								var $gallery = $('#gallery');
								var $res = makeGallery($itemGallery);
								if ( $res ) {
									$galleryCont.show();
									$('ul', $gallery).replaceWith($res);
									// popups
									gallery($gallery);
								} else {
									$galleryCont.hide();
								}
							}
						});
					
						// displaing part of the info table
						floorTable(num.porch, num.floor, '.house .apartments-info table');
					} else {
						// hiding everything unnecessary
						$galleryCont.hide();
						$tableAndText.hide();
						
						var $text = false;
						var garageName = false;
						
						var garageLink = $('a', $(this)).attr('href');
						$.ajax({
							url: garageLink,
							success: function(data) {
								imgSrc = $('#page .floors li:first img' ,$(data)).attr('src');
								garageName = $('#page .floors li:first h2', $(data)).text();
								$text = $('#page .garage-desc', $(data)).html();
								
								// preloading and changing floor plan 
								$(tempImg).load(function() {
									$('img', $floorImage).attr('src', imgSrc);
									$('a', $floorImage).attr('href', imgSrc)
						
									$floorImage.removeClass('loading');
								}).attr('src', imgSrc);	
								
								// changing texts
								$floorHeader.hide().filter('.garage').text(garageName).show();
								$garageDesc.html($text).show();
							},
							complete: function() {
								
							}
						});
					}
				}
				
				e.preventDefault();
			});
		});
		
		// selecting the first porch
		$('li:first a', $porches).click();
	}
}

function makeGallery($photos) {
	var $result = false;
	
	if ( $photos ) {	
		if ( $('li', $photos).length ) {
			$result = $('<ul></ul>');
			var $tpl = $('<li class="img"><div class="i"><img src="" alt="" /></div><a target="_blank" href="">Описание изображения</a></li>');
		
			// urls list
			var urls = $photos.filter('.urls').text();
			urls = urls.replace(/\'/g, '').split(',');
			urls.shift();
		
			$('ul li', $photos).each(function(i) {
				var $n = $tpl.clone();
			
				var img = new Image();	
				$(img).load(function() {
					$('img', $n).attr('src', $(this).attr('src'));
					centerImage($('img', $n));
				}).attr('src', $('img', $(this)).attr('src'));
				$('a', $n).attr('href',urls[i]);

				$result.append($n);
			});
		} else {
			return false;
		}
	}

	return $result;
}

function floorTable(porch, floor, table) {
	var $table = $(table);
	
	if ( $table.length ) {
		$table.show();
		$('tbody', $table).not(':first').hide();
		
		var $floor = $('tbody.section-' + porch, $table);
		$('tr', $floor).show().each(function() {
			var $td = $('td:first', $(this));
			if ( $td.length && floor != $td.text() ) {
				$(this).hide();
			}
		});
		
		$floor.show();
	}
}

function houseApartments(porch, $table, $statuses) {
	var types = getFlatTypes($statuses);
	var offset = [22,42,62,82,102]; // in px
		
	if ( 1 == $table.length ) {
		var $result = $('<ul></ul>');
	
		var $rows = $table.find('tbody.section-' + porch).find('tr');
		$rows.each(function() {
			var $cell = $(this).find('td');
			
			if ( 3 == $cell.length ) {
				var floor = $cell.filter(':first').text();
				var type = $cell.filter(':last').text();
				var price = parsePrice(type);
				
				if ( price ) {
					var $thisFloor = $result.find('.floor-' + floor);

					if ( 0 == $thisFloor.length ) {
						$thisFloor = $('<li class="floor-' + floor + '"></li>');
					}
					
					// price in millions
					price /= 1000000;
					
					// iterating through types
					$.each( types, function(i, type) {
						if ( price >= type.from && price < type.to ) {
							$thisFloor.append('<span class="apt type-' + (i+1) + '"></span>');
						}
					});
					
					// positioning flats
					$('span', $thisFloor).each(function(i) {
						$(this).css('left',offset[i] + 'px');
					});
					
					$thisFloor.appendTo($result);
				}
			}
		});
		
		return $result;
	} else {
		return $();
	}
}

function parsePrice(price) {
	price = price.replace(/[^0-9]/g, '');
	
	if ( price ) {
		return price;
	} else {
		return false;
	}
}

function getFlatTypes($t) {
	var $types = $('tbody > tr', $t);
	
	if ( $types.length ) {
		var result = new Array();
		var n, f, t;
	
		$types.each(function() {
			n = $('td', this).eq(0).text();
			f = parseInt($('td', this).eq(1).text());
			t = parseInt($('td', this).eq(2).text());
			
			if ( !f ) f = 0;
			if ( !t ) t = 100;
			
			result.push({name:n, from:f, to:t});
		});
		
		return result;
	} else {
		// returning default types
		return [
			{name:'до 6 млн. руб.', from:0, to:6},
			{name:'от 6 до 10 млн. руб.', from:6, to:10},
			{name:'свыше 10 млн. руб.', from:10, to:100}
		];
	}
}

function houses(s) {
	var $info = $(s);
	var mapImgPath = '/images/map/map.png';
	
	if ( $info.length ) {
		var $scheme = $info.parents('.scheme');
		var $map = $('#map');
	
		// starting huge map preload 
		var mapImg = new Image();
	
		$(mapImg).load( function() {
			$scheme.addClass('isLoaded');
		}).error( function() {
			$scheme.addClass('errorLoading')
		}).attr('src', mapImgPath );
	
		// gathering info
		var $houses = $map.find('ul.houses > li');
		$info.find('tr.houseInfo').each(function(index) {
			var $tds = $(this).find('td');
		
			var houseName = $tds.eq(0).text();
			var houseState = $tds.eq(1).text();
			var houseApt = new Array();
				houseApt[0] = $tds.eq(2).text();
				houseApt[1] = $tds.eq(3).text(); 
				houseApt[2] = $tds.eq(4).text();
				houseApt[3] = $tds.eq(5).text();
			
			var aptText = new Array();
				aptText[0] = $info.find('th.studio').text();
				aptText[1] = $info.find('th.bedroom').text();
				aptText[2] = $info.find('th.three-room').text();
				aptText[3] = $info.find('th.penthouse').text();
			
			var saleText = $info.find('th.for-sale').text();
			
			var $houseInfo = $('<div class="info"><p class="name"><span></span></p></div>');
			var $onMap = $houses.eq(index);
			
			// house is ready
			if ( houseState == 'Сдан' ) {
				$houseInfo.find('.name span').text(houseName);
				$houseInfo.append('<div class="sale"><p>' + saleText + '</p><ol></ol></div>');
				
				$.each(houseApt, function(i,v) {
					if ( parseInt(v) ) {
						$houseInfo.find('.sale ol').append('<li>' + aptText[i] + ': <strong>' + v + '</strong></li>');
					}
				});
			} else {
				$onMap.addClass('inactive');

				if ( houseState.trim().length ) {
					$houseInfo.find('.name span').html(houseName + '&nbsp;&mdash; ' + houseState);
				} else {
					$houseInfo.find('.name span').html(houseName);
				}
			}

			$onMap.append($houseInfo);
		});
		
		// interactive map
	    map($map);
	}
}

function map(s) {
	var $map = $(s);

	if ( $map.length ){ 
		var $houses = $map.find('ul.houses > li');
		
		var iAvail = '/images/map/houses-available.png';
		var iSel = '/images/map/houses-selected.png';
		var iInactive = '/images/map/houses-inactive.png';
		
		preload(iAvail); preload(iSel); preload(iInactive);
		
		$houses.each(function() {
			var $house = $(this);
			var $image = $(this).find('img');
			var $infos = $houses.find('.info');
			var $info = $(this).find('.info');
			var $area = $house.find('map area');

			if ( $(this).hasClass('inactive') ) {
				$(this).find('img').attr('src',iInactive);
			}
	
			$area.mouseenter(function() { 
				$infos.hide();
				$info.show();

				$houses.not('.inactive').find('img').attr('src',iAvail);
				if ( $house.not('.inactive').length ) {
					$image.attr('src',iSel);
				}

				$houses.removeClass('selected');
				$house.addClass('selected');
			});

			$house.mouseleave(function() {
				if ( $house.not('.inactive').length ) {
					$image.attr('src',iAvail);
				}
			
				$infos.hide();
				$house.removeClass('selected');
			});
			
			$area.click(function(e) {
				if ( $house.hasClass('inactive') ) {
					e.preventDefault();
				}
			});
			
			// checking if map is already preloaded 
			var $scheme = $map.parents('.scheme');
			var checkMap = setInterval(function() {
				if ( $scheme.hasClass('isLoaded') ) {
					$scheme.removeClass('loading');
					clearInterval(checkMap);
				}
			}, 1000);	
		});
	}
}	

function preload(img) {
	i = new Image(); 
	i.src = img;
}

function printMap() { 
	$('#print-map a').click(function(e) {
		$('#map').printArea();
		
		e.preventDefault();
	});	
}

function introFlash(id) {
	if (typeof(AC_FL_RunContent) == 'undefined') return;
	if (AC_FL_RunContent) {
		var flashVer = GetSwfVer();
	
		if (-1 != flashVer) {
			$('#dubrovka #head').append('<div class="intro-flash" id="intro-flash"></div>');
		
			$('#dubrovka').addClass('flash');
			var $flash = AC_FL_RunContent(
				'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
				'width', '1600',
				'height', '702',
				'src', '/templates/Main/flash/h1',
				'quality', 'high',
				'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
				'play', 'true',
				'loop', 'true',
				'scale', 'noborder',
				'wmode', 'opaque',
				'devicefont', 'false',
				'id', 'h1',
				'bgcolor', '#ffffff',
				'name', 'h1',
				'menu', 'false',
				'allowFullScreen', 'false',
				'allowScriptAccess','always',
				'movie', '/templates/Main/flash/h1',
				'salign', '',
				'base', '.'
			);

			$('#intro-flash').append($flash);
		}
	}
}

function slider(s) {
	var $slider = $(s);

	if ( $slider.length ) {
		$slider.jcarousel({
			scroll: 1,
			easing: 'swing',
			animation: 100,
			wrap: 'circular',
			auto: 2, /* 2 seconds */
			buttonNextHTML: '<a class="btn btn-next"></a>',
			buttonPrevHTML: '<a class="btn btn-prev"></a>'
		});
    	$slider.disableSelection();
    }
    
    $slider.hover(function() {
    	$(this).jcarousel('stopAuto');
    }, function() {
    	$(this).jcarousel('startAuto');
    });
}

function gallery(s) {
	var $gal = $(s);
	
	$gal.each( function() {
		var $link = $(this).find('li.img a');
		$link.click( function(e) {
			// Set current
			$gal.find('li.img').removeClass('current');
			$(this).parents('li.img').addClass('current');
			
			// Showing popup with all links
			var urls = prevNext($(this).parents('li.img'));
			showPopup($(this).attr('href'), urls.prev, urls.next);
		
			e.preventDefault();
		});
	});	
}	

function showPopup(current, prev, next) {
	var $overlay = $('#overlay');
	var $popup = $('#popup');
	var $img = $('#js-popup-img');
	var $next = $('#js-popup-next');
	var $prev = $('#js-popup-prev');
	
	$prev.hide();
	$next.hide();
	
	$prev.unbind('click').show();
	$next.unbind('click').show();
	
	if ( prev ) {
		$prev.click(function(e) {
			$('.gallery li.img.current').prev('li.img').find('a').click();
			e.preventDefault();
		});
	} else {
		$prev.hide();
	}
	
	if ( next ) {
		$next.click(function(e) {
			$('.gallery li.img.current').next('li.img').find('a').click()
			e.preventDefault();
		});
	} else {
		$next.hide();
	}	
	
	if ( current ) {
		$overlay.css('height','100%');
		$overlay.show();
		$popup.show();
		
		var $c = $img.parents('.image');
		$c.css('height', $c.height());
		$c.addClass('loading');
			
		$img.hide();
		$('#js-popup-enlarge').hide();
		
		var img = new Image();
		$(img).load( function() {
			$c.css('height', 'auto');
			$c.removeClass('loading');

			$img.replaceWith($(this));
			
			// setting new proportional image size
			var iSize = popupSize();
			var newSize = popupImageSize(this.width, this.height, iSize[0], iSize[1]);			
			
			this.width = newSize[0];
			this.height = newSize[1];
			
			$img.show();
			
			// Click switches to the next photo
			if ( next ) {
				$(this).css('cursor','pointer');
				$(this).click(function() {
					$next.click();
				});
			} else {
				$(this).css('cursor','default');
				$(this).click = "";
			}
			
			// Adding enlarge link
			$('#js-popup-enlarge').attr({
				'href': this.src,
				'target': '_blank'
			}).show();
			
		}).error( function() {
		}).attr({
			src:current,
			id:'js-popup-img'
		});
	}
}

function popupSize() {
	var width = 714; // '.js-popup div.image' rule in style.css
	var height;
	
	var wSize = window.size();
	height = wSize.height;
	
	height = height - 40 - 232;
	
	return [width,height];
}

function popupImageSize(iWidth, iHeight, pWidth, pHeight) {
	// If image is smaller than popup window
	if ( iWidth <= pWidth && iHeight <= pHeight ) {
		return [iWidth,iHeight];
	} else {
	// Else we need to calculate new size
		var w, h;

		if (iWidth >= iHeight) {
			w = pWidth;
			h = iHeight / (iWidth/pWidth);	
			
			if (h > pHeight) {
				w /= (h/pHeight);
				h = pHeight;
			}
		} else {
			h = pHeight;
			w = iWidth / (iHeight/pHeight);
			
			if (w > pWidth) {
				h /= (w/pWidth);
				w = pWidth;
			}
		}
		
		return [w,h];
	}
}

function prevNext($li) {
	if ( 1 == $li.length ) {
		var p = $li.prev('li.img');
		if ( p.length ) {
			p = p.find('a').attr('href');
		} else {
			p = '';
		}
		
		var n = $li.next('li.img');
		if ( n.length ) {
			n = n.find('a').attr('href');
		} else {
			n = '';
		}
		
		return {prev:p, next:n}; 				
	} else {
		return {prev:'', next:''};
	}
}

function centerImage(s) {
	var $image = $(s);
	$image.each(function() {
		var left = $(this).width() / 2;
		var top = $(this).height() / 2;
	
		// Centering image
		$(this).css({
			'position': 'absolute',
			'left': '50%',
			'top': '50%',
			'margin-left': -left,
			'margin-top': -top
		});
	});
}

jQuery.fn.extend({
    disableSelection : function() {
            this.each(function() {
                    this.onselectstart = function() { return false; };
                    this.unselectable = "on";
                    jQuery(this).css('-moz-user-select', 'none');
            });
    },
    enableSelection : function() {
            this.each(function() {
                    this.onselectstart = function() {};
                    this.unselectable = "off";
                    jQuery(this).css('-moz-user-select', 'auto');
            });
    }
});

window.size = function()
{
	var w = 0;
	var h = 0;

	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

