$(document).ready(function(){
	$('ul#nav_main li:last').addClass('last');
	$('div#tabs ul:first').prev('span').addClass('first').end().find('li:last').addClass('last');
	$('table tr').find('td:last, th:last').css('border-right','none').addClass('last');
	$('table tr').find('td:first, th:first').addClass('first');
	$('table tr').find('td:last').css('border-right','none');
	
    $('table tbody tr').hover(
		function(){
			$(this).find('td').css('background','#f0f0e0')
		},
		function(){
			$(this).find('td').css('background','')
		}
	);

    
    //table width
/* 	$(window).bind('load resize', function(){
		var w = $(this).width()
		if (w <= 1040) {
			$('table').css('margin','15px -54px');
		}
		else {
			$('table').css('margin','15px -22px');
		}
		if (w >=1220) {
			$('div.rc div.thumb').css('width','auto');
		}
		else {
			$('div.rc div.thumb').css('width','30%');
		}
		
	}); */
	if ($('table').length == 1 && $('table').find('tbody').find('tr').length >=4){
		var tbl = $('table').eq(0);
		var thead = tbl.find('thead');
		var theadPos = tbl.offset().top;
		var j = 1;
		$('div#wrapper').append("<div class='thead'><table><thead>"+thead.html()+"</thead></table></div>");
		var fixedThead = $('div.thead');
		//position
		function correct_thead_pos () {
			var x = $('table').offset().left;
			var leftScr = $(window).scrollLeft();
			x = x - leftScr;
			var correctWidth = $('table').outerWidth();
			fixedThead.css({
				'left' : x,
				'width' : correctWidth
			});
			$('table thead tr th').each(function(i){
				fixedThead.find('th').eq(i).width($(this).width());
			});
		};
		correct_thead_pos();
		$(window).bind('load resize', function(){
			correct_thead_pos();
		});
		fixedThead.hide();
		$(window).scroll(function(){
			correct_thead_pos();
			var showCond = $(this).scrollTop() > tbl.offset().top &&  $(this).scrollTop() < tbl.offset().top + tbl.height() && j == 1;
			var hideCond = $(this).scrollTop() > tbl.offset().top + tbl.height() || $(this).scrollTop()<tbl.offset().top;
			if (showCond) {
				fixedThead.show();
				correct_thead_pos();
				j = 0;
			}
			else if (hideCond) {
				fixedThead.hide();
				j=1;
			}
		});
	}
	//TABS
	var tabs = document.getElementById('tabs_content');
	if (!tabs || $('div#tabs ul:first li:last').hasClass('active')) {
		$('div#tabs').parent().css({
			'margin-right' : '0'
		});
		$('div#tabs').css('height','58px').addClass('notabs');
	}
	else if (tabs) {
		if (!$('div#tabs ul:first li:last').hasClass('active')){
			tabContainers = $('div#tabs_content>div');
			tabContainers.hide();
			$('div#tabs ul li a').click(function () {
				if (!$(this).parent('li').hasClass('last')){
					tabContainers.hide().filter(this.hash).show();
					$(this).parents('div.info').prev('div.thumb')
					.find('img').attr('src','/images/'+$(this).attr('img')); /*FIX IMAGES / */
						$(this).parent('li').parent('ul').parent('div').find('li.active, span.active')
						.removeClass('active');
						$(this).parent('li').addClass('active').parent('ul').prev('span').addClass('active');
									
					return false;
				}
			}).parents('ul').find('li.active a').click();
		}
	}
	if ($('div#tabs ul:first li:last').hasClass('active')) {
		$('div#tabs').parent().prev('div.thumb').remove();
	}
	$('div#tabs').find('ul li.active').parent('ul').prev('span').addClass('active');
	
	

	//request
	$('a.request,a#request').click(function(){
		var request = $(this).attr('rel');
        //console.log(request);
        $.post("/ajax/",{req:request,action:'gen_list'},function(r){
            if (r.r) {
                $('div#wrapper').prepend("<div class='overlay_wrap'><div class='overlay'></div><div class='request'><h1>Отправить заявку/ задать вопрос</h1><form><input name='cc' type='hidden' value='59'><input name='sub' type='hidden' value='98'><input name='catalogue' type='hidden' value='1'><input type='hidden' name='posting' value='1'><dl><dt>Имя</dt><dd><input type='text' name='f_Name' /></dd><dt>Телефон</dt><dd><input type='text' name='f_Tel' /></dd><dt>E-mail</dt><dd><input type='text' name='f_Email' /></dd><dt>Заявка/Вопрос <span>(*)</span></dt><dd><textarea rows='4' name='f_Text'>"+r.comment+"</textarea></dd><dt></dt><dd><input type='image' id='send_req' src='/img/send.png' /></dd></dl><p class='result'></p></form></div></div>");
                //$('div#wrapper').prepend("<div class='overlay_wrap'><div class='overlay'></div><div class='request'><h1>Отправить заявку/ задать вопрос</h1><form><dl><dt>Имя</dt><dd><input type='text' /></dd><dt>Телефон</dt><dd><input type='text' /></dd><dt>E-mail</dt><dd><input type='text' /></dd><dt>Заявка/Вопрос</dt><dd><textarea rows='4'></textarea></dd><dt></dt><dd><input type='image' src='img/send.png' /></dd></dl></div></div>");
                $('div.overlay_wrap').fadeIn();
                $('div.overlay').height($('div#wrapper').height());
    			$(window).bind('load resize', function(){
    				$('div.overlay').height($('div#wrapper').height());
    			});
            }
        },'json');
        
       /* $('div#wrapper').prepend("<div class='overlay_wrap'><div class='overlay'></div><div class='request'><h1>Отправить заявку/ задать вопрос</h1><dl><dt>Имя</dt><dd><input type='text' /></dd><dt>Телефон</dt><dd><input type='text' /></dd><dt>E-mail</dt><dd><input type='text' /></dd><dt>Заявка/Вопрос</dt><dd><textarea rows='4'></textarea></dd><dt></dt><dd><input type='image' src='img/send.png' /></dd></dl></div></div>");
		$('div.overlay_wrap').fadeIn();
			$('div.overlay').height($('div#wrapper').height());
			$(window).bind('load resize', function(){
				$('div.overlay').height($('div#wrapper').height());
			});	*/
        
        
		return false;
	});
    
    $("#send_req,#send_req_main").live('click',function(){
        
        $("p.result").attr('class','result');
        
        var pres = $(this).closest('form').find('p.result')
        
        $.post('/netcat/add.php',$(this).closest('form').serialize(),function(r){
               var cl = r.r ? 'ok' : 'err';
               pres.html(r.msg).addClass(cl);
        },'json');
       //console.log($(this).closest('form').serialize()); 
       return false; 
    });
    
    
    
    
	/*$('a#request_flat').click(function(){
		$('div#wrapper').prepend("<div class='overlay_wrap'><div class='overlay'></div><div class='request'><h1>Заявка</h1><dl><dt>Имя</dt><dd><input type='text' /></dd><dt>Телефон</dt><dd><input type='text' /></dd><dt>E-mail</dt><dd><input type='text' /></dd><dt>Комментарий</dt><dd><textarea rows='4' name='f_Text'></textarea></dd><dt></dt><dd><input type='image' src='img/send.png' /></dd></dl></div></div>");
		$('div.overlay_wrap').fadeIn();
        $('div.overlay').height($('div#wrapper').height());
			$(window).bind('load resize', function(){
				$('div.overlay').height($('div#wrapper').height());
			});	

		return false;
	});*/
    
    
	$('div#wrapper div.overlay').live('click',function(){
		$(this).parent().remove();
	});
	
    
    
	//GALLERY

	$('.ad-gallery').adGallery({

	});
	//AUTOCOMPLETE
	$.widget( "ui.combobox", {
			_create: function() {
				var self = this,
					select = this.element.hide(),
					selected = select.children( ":selected" ),
					value = selected.val() ? selected.text() : "";
				var input = this.input = $( "<input>" )
					.insertAfter( select )
					.val( value )
					.autocomplete({
						delay: 0,
						minLength: 0,
						source: function( request, response ) {
							var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
							response( select.children( "option" ).map(function() {
								var text = $( this ).text();
								if ( this.value && ( !request.term || matcher.test(text) ) )
									return {
										label: text.replace(
											new RegExp(
												"(?![^&;]+;)(?!<[^<>]*)(" +
												$.ui.autocomplete.escapeRegex(request.term) +
												")(?![^<>]*>)(?![^&;]+;)", "gi"
											), "<strong>$1</strong>" ),
										value: text,
										option: this
									};
							}) );
						},
						select: function( event, ui ) {
							ui.item.option.selected = true;
							self._trigger( "selected", event, {
								item: ui.item.option
							});
						},
						change: function( event, ui ) {
							if ( !ui.item ) {
								var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
									valid = false;
								select.children( "option" ).each(function() {
									if ( $( this ).text().match( matcher ) ) {
										this.selected = valid = true;
										return false;
									}
								});
								if ( !valid ) {
									// remove invalid value, as it didn't match anything
									$( this ).val( "" );
									select.val( "" );
									input.data( "autocomplete" ).term = "";
									return false;
								}
							}
						}
					})
					.addClass( "ui-widget ui-widget-content ui-corner-left" );

				input.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li></li>" )
						.data( "item.autocomplete", item )
						.append( "<a>" + item.label + "</a>" )
						.appendTo( ul );
				};

				this.button = $( "<button>&nbsp;</button>" )
					.attr( "tabIndex", -1 )
					.attr( "title", "Показать все станции метро" )
					.insertAfter( input )
					.button({
						icons: {
							primary: "ui-icon-triangle-1-s"
						},
						text: false
					})
					.removeClass( "ui-corner-all" )
					.addClass( "ui-corner-right ui-button-icon" )
					.click(function() {
						// close if already visible
						if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
							input.autocomplete( "close" );
							return;
						}

						// pass empty string as value to search for, displaying all results
						input.autocomplete( "search", "" );
						input.focus();
					});
			},

			destroy: function() {
				this.input.remove();
				this.button.remove();
				this.element.show();
				$.Widget.prototype.destroy.call( this );
			}
	});
	
	$('#content_wrap .combo').combobox();
	
    // add metro
    $('div#tabs_content a.add_metro').click(function(){
		if ($(this).parent('div').find('div.combo_holder').length < 3) {
		 
			var tplnum = parseInt($(this).attr('rel'))-1;
            $(this).parent('div').append($('#templates .combo_holder').eq(tplnum).clone());
            
			$('#content_wrap .combo').combobox();
			
			$(this).parent().find('.combo_holder:last').append("<a href='#' class='remove_metro' ></a>");
			return false;
			
		
		}
		return false;
		
	});
	$('div#tabs_content a.remove_metro').live('click',function(){
		$(this).parent().remove();
		return false;
	});
    
	$('.ui-button').click(function(){
		return false;
	});
	$('.ui-button').live('click',function(){
		return false;
	});
    
    
    $(".backlink").click(function(){
       history.back();
       return false; 
    });
    
    
    /* SCROLL TO ANCHOR RESULTS */
    if ( $("#searchr").size()>0) {
        var target_offset = $("#searchr").offset(); 
        var target_top = target_offset.top;
        $('html, body').animate({scrollTop:target_top}, 200);   
    }
    

    
    
	
});
