var office_chain = new Array();
var cg_array = new Array();
var sliderCount   = 0;
var sliderCounter = 0;
		
(function($) {
	$(document).ready(function() {
	
		var iterator = 0;
		$('.ajaxGallery a').each(function() {
			$(this).attr('id', iterator++);
		});
		
		sliderCount   = $('#buffer li img').length;
		sliderCounter = 0;
		
		$('#rightArrow').live('click', function() {
			if(sliderCounter < sliderCount-1) {
				$('#mainImg img').attr('src', $('#buffer li img').eq(++sliderCounter).attr('src'));
				//$('#sign').text($('ul#buffer li img').eq(sliderCounter).attr('alt'));
				setPosInGallery();
			}
		});
		
		$('#leftArrow').live('click', function() {
			if(sliderCounter > 0) {
				$('#mainImg img').attr('src', $('#buffer li img').eq(--sliderCounter).attr('src'));
				//$('#sign').text($('ul#buffer li img').eq(sliderCounter).attr('alt'));
				setPosInGallery();
			}
		});
		
		$('.ajaxGallery a').live('click',function() {
			sliderCounter = parseInt($(this).attr('id'));
			var doc = document.documentElement || document.body;
			var elLeft = Math.round(doc.scrollLeft+(doc.clientWidth-710)/2)+'px';
			var elTop  = Math.round(doc.scrollTop+(doc.clientHeight-818)/2)+'px';
			var id = $(this).find('img').attr('alt');
			$('#shadow').show();
			$('#ajaxGalleryBlock').css({'top':elTop,'left':elLeft}).fadeIn();
			$('#ajaxGalleryBlock #mainImg img').attr("src","/application/includes/img/b/"+id+".jpg");
			setPosInGallery();
			//$('#sign').text($('ul#buffer li img').eq(sliderCounter).attr('alt'));
		});
	
		// Select
		
		var flag  = false;
		var index = 8;
		$('div.select').each(function() {
			var select = $('div.select[id='+$(this).attr('id')+']');
			select.css('z-index', index--);
			select.find('div.input').live('click', function() {
				var ul = select.find('ul');
				ul.css('display', ((ul.css('display')=='block')?'none':'block'));
				$(this).blur();
				flag = true;
			});
			select.find('li').live('click', function() {
				select.find('div.input').text($(this).text());
				var input = select.find('input');
				var input_id = input.attr('id');
				if(input.attr('id') == 'change_floor_1') {
					$('#change_floor_1_insert').load('/main/load_room_list/', {'floor_str': $(this).text()});
				}
				if(input.attr('id') == 'change_floor_2') {
					$('#change_floor_2_insert').load('/main/load_room_list_free/', {'floor_str': $(this).text()});
				}
				input.attr('value', $(this).text());
				select.find('ul').toggle();
				select.find('li').removeClass('active');
				$(this).addClass('active').blur();
				flag = true;
			});
		});
		
		$('body').live('click', function() {
			if(!flag) {
				$('div.select ul').hide();
			}
			flag = false;
		});
		
		$('div.select ul li').live('mouseover', function() {
			$(this).addClass('hover');
		});
		
		$('div.select ul li').live('mouseout', function() {
			$(this).removeClass('hover');
		});
		
		$('input[type=text]').focus(function() {
			var value = $(this).attr('value');
			switch(value) {
				case 'ваше имя':
				case 'e-mail':
				case 'компания':
				case 'контактное лицо':
				case 'введите код с картинки':
					$(this).attr('value', '');
					$(this).blur(function() {
						if($(this).attr('value') == '') {
							$(this).attr('value', value);
						}
					});
					break;
			}
		});
		$('textarea').focus(function() {
			var text = $(this).text();
			switch(text) {
				case 'вопрос':
				case 'контактные данные':
				case 'дополнительные комментарии':
					$(this).text('');
					$(this).blur(function() {
						if($(this).text() == '') {
							$(this).text(text);
						}
					});
					break;
			}
		});
	
		// -----------------------------
		
		
		$('#print_price').click(function() {
			var floor = $('.calculate input[name=floor]').attr('value');
			var room  = $('.calculate input[name=room]').attr('value');
			$('#price').load('/main/get_price/', {'floor': floor, 'room': room});
		});
		
		// модуль FLOORS
		
		$('#rooms li').each(function() {
			$(this).find('span').css({'line-height':$(this).css('line-height'),'display':'block'});
		});
		
		$('#rooms li.available').live('mouseover', function() {
			$(this).css('z-index', '95');
			var room  = $(this).attr('id').substring(5);
			if(office_chain[room] !== undefined) {
				var count = office_chain[room].length;
				if(count) {
					for(var i = 0; i < count; i++) {
						if(office_chain[room][i] != room) {
							setStatusRoom('sub_hover', office_chain[room][i]);
						}
					}
				}
			}
			setStatusRoom('hover', room);
		});
		
		$('#rooms li.available').live('mouseout', function() {
			$(this).css('z-index', '90');
			var room  = $(this).attr('id').substring(5);
			if(office_chain[room] !== undefined) {
				var count = office_chain[room].length;
				if(count) {
					for(var i = 0; i < count; i++) {
						if(office_chain[room][i] != room) {
							setStatusRoom('not_sub_hover', office_chain[room][i]);
						}
					}
				}
			}
			setStatusRoom('not_hover', room);
		});
		
		// RENT
		$('.link_to_rent').click(function() {
			var id = $(this).attr('id');
			var floor = id.substring(5,6);
			var room  = id.substring(7);
			$('#select_3 div.input').text('этаж №'+floor);
			$('#select_3 input').attr('value', 'этаж №'+floor);
			$('#change_floor_1_insert').load('/main/load_room_list/', {'floor_str': 'этаж №'+floor});
			$('#select_4 div.input').text('№'+room);
			$('#select_4 input').attr('value', '№'+room);
			showForm();
		});
		
		
		// PHOTO
		$('.show_photo').click(function() {
			var room = $(this).attr('id');
			room = room.substring(3);
			$('#ajaxGalleryBlock').load('/main/load_gallery/'+room);
		});
		
		// -----------------------------
		
		$('.text table tr:even').addClass('even');
		$('.text table tr:odd').addClass('odd');
		
		// -----------------------------
		
		
		$('.to_left').live('click', function() {
			var id    = $(this).attr('id');
			var count = getCGCount(id);
			if(count > 4) {
				$('#window_'+id+' li:last').insertBefore('#window_'+id+' li:first');
			}
		});
		$('.to_right').live('click', function() {
			var id = $(this).attr('id');
			var count = getCGCount(id);
			if(count > 4) {
				$('#window_'+id+' li:first').insertAfter('#window_'+id+' li:last');
			}
		});
		$('.firm_loadinfo').live('click', function() {
			var pid = ($(this).attr('id')).substring(5,6);
			var id  = ($(this).attr('id')).substring(7);
			$('#cg_info_'+pid).load('/firms/load/'+id+'?rand='+Math.random());
		});
		
		// -----------------------------
		
		$('#personal2 tr:nth-child(even)').css('background','#F2F2F2');
		$('#newsList li:nth-child(odd)').css('background','#F2F2F2');
		
		$('.standartForm .button').bind('click',function() {
			validateForm(this);
		});
		
		heightShadow = $('#wrapper').height() + $('#flash').height();
		$('#shadow').css('height',heightShadow+'px');
		
		$('#shadow').live('click',function() {
			$('#ajaxGalleryBlock').fadeOut();
			$('#form').hide();
			$(this).hide();
		});
		
		$('a').each(function() {
			if($(this).attr('href') == '/pages/for_renters/order/') {
				$(this).attr('href','javascript:void(0);');
				$(this).click(function() {
					showForm();
				});
			}
		});
		
		$('img.full').wrap('<div class="wrap_full"></div>');
		
		// INIT BLOCK
		// preload images
		var image_1 = new Image();
		image_1.src = '/application/includes/images/close.jpg';
		
		var j, i = 50;
		// because used margin-left: minus value
		$('#menu ul li').each(function() {
			j = 0;
			$(this).css('z-index', i--);
			$(this).find('ul li').each(function() {
				$(this).css('margin-left','-'+(6*j++)+'px');
			});
		});
		// first <img> has width: 25px (not 15px)
		$('#menu ul li:first ul').css('left', '3px');
		
		// EVENTS BLOCK
		$('#menu > ul li').live('mouseover', function() {
			$(this).addClass('hover').find('img.l').attr('src','/application/includes/images/menu_act_left.gif');
			$(this).find('img#first').attr('src','/application/includes/images/menu_first_hover.jpg');
			$(this).find('img#last').attr('src','/application/includes/images/menu_last_hover.jpg');
		});
		$('#menu > ul li').live('mouseout', function() {
			$(this).removeClass('hover').find('img.l').attr('src','/application/includes/images/menu_def.jpg');
			$(this).find('img#first').attr('src','/application/includes/images/menu_first.jpg');
			$(this).find('img#last').attr('src','/application/includes/images/menu_last.jpg');
		});
		
		
		initGallery();
	});
	
	setStatusRoom = function(status, room) {
		switch(status) {
			case 'hover':
				//var li = $('#room_'+room);
				//li.addClass('hover').addClass('hover_'+room);
				//$('#room_'+room+' .layer').css({'width':li.css('width'),'height':li.css('height')});
				$('#room_'+room).addClass('hover').addClass('hover_'+room);
				break;
			case 'sub_hover':
				$('#room_'+room).addClass('hover_sub').addClass('hover_'+room);
				break;
			case 'not_hover':
				$('#room_'+room).removeClass('hover').removeClass('hover_'+room);
				break;
			case 'not_sub_hover':
				$('#room_'+room).removeClass('hover_sub').removeClass('hover_'+room);
				break;
		}
	}
	
	replaceImg = function(id) {
		var img = new Image();
		img.src = '/application/includes/img/b/'+id+'.jpg';
		$('#mainImg img').attr("src","/application/includes/img/b/"+id+".jpg");
	}

	validateForm = function(object) {
		var error = 0;
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		var form = $(object).parent().parent();
		$('*[required]',form).each(function() {
			if ($(this).val()=='') {
				error ++;
				$(this).addClass('notValid');
			} else if ($(this).attr('name') == 'email' && !reg.test($(this).val())) {
				error++;
				$(this).addClass('notValid');
			} else {
				error--;
				$(this).removeClass('notValid');
			}
		});
		if(error != 0) {
			$('.error',form).remove();
			//$(form).before('<p class="error">Проверьте введеные данные</p>');
			$('#point').html('<p class="error">Проверьте введеные данные</p>');
		} else {
			var data = $(form).serialize();
			var action = $(form).attr('action');
			$.ajax({
				url: action,
				type: 'POST',
				data: data,
				success: function(response) {
					$('#point').html('<div class="msgStandartForm">'+response+'</div>');
					//$(form).before('<div class="msgStandartForm">'+response+'</div>');
				}
			})
		}
	}
	
	showForm = function() {
		var doc   = document.documentElement || document.body;
		var elTop = Math.round(doc.scrollTop+(doc.clientHeight-500)/2)+'px';
	
		$('#shadow').show();
		$('#form').css('top', elTop).show();
	}
	
	sendForm = function(id) {
		$('#form_'+id).submit();
	}
	
	closeGallery = function() {
		$('#ajaxGalleryBlock').fadeOut();
		$('#shadow').hide();
		$('#form').hide();
	}
	
	showGalleryForFloors = function(count) {
		var doc = document.documentElement || document.body;
		var elLeft = Math.round(doc.scrollLeft+(doc.clientWidth-860)/2)+'px';
		var elTop  = Math.round(doc.scrollTop+(doc.clientHeight-712)/2)+'px';
		$('#shadow').show();
		$('#ajaxGalleryBlock').css({'top':elTop,'left':elLeft}).fadeIn();
		initGallery();
	}
	
	getCGCount = function(id) {
		var num = parseInt(id.substring(4));
		if(cg_array[num] == undefined) {
			cg_array[num] = $('#window_'+id+' li').length;
		}
		return cg_array[num];
	}
	
	initGallery = function() {
		sliderCount   = $('#buffer li img').length;
		sliderCounter = 0;
		setPosInGallery();
	}
	
	setPosInGallery = function() {
		$('#pos').text((sliderCounter+1)+' / '+sliderCount);
	}
	
	initOldGallery = function() {
		
		$('#rightArrow').live('click', function() {
			var widthPreview = $('#scroll li img').width();
			if((Math.ceil(($('#scroll ul a').length/6)-1)) == sliderCounter) {
				sliderCounter = 0;
			} else {
				sliderCounter++;
			}
			var newPos = '-'+(3*sliderCounter*widthPreview)+'px';
			alert(newPos);
			$('#scroll ul').animate({
				left : newPos
			}, 400, function() { $(this).css('left', newPos); });
		});
		
		$('#leftArrow').live('click', function() {
			var widthPreview = $('#scroll li img').width();
			if(sliderCounter !== 0) {
				sliderCounter--;
			} else {
				sliderCounter = Math.ceil(($('#scroll ul a').length/6)-1);
			}
			var newPos = '-'+(3*sliderCounter*widthPreview)+'px';
			alert(newPos);
			$('#scroll ul').animate({
				left : newPos
			}, 400, function() { $(this).css('left', newPos); });
		});
		
		$('.ajaxGallery a').live('click',function() {
			var doc = document.documentElement || document.body;
			var elLeft = Math.round(doc.scrollLeft+(doc.clientWidth-710)/2)+'px';
			var elTop  = Math.round(doc.scrollTop+(doc.clientHeight-818)/2)+'px';
			var id = $(this).find('img').attr('alt');
			replaceImg(id);
			$('#shadow').show();
			$('#ajaxGalleryBlock').css({'top':elTop,'left':elLeft}).fadeIn();
		});
	
	}

})(jQuery);
