$.fn.overlay=function() {
	var el=$(this);
	$('#container').before(
		$('<div class="overlay"></div>').show()
	);
	return this;
};
$.fn.centering=function() {
	var width = this.css('width');
	this.css("position","absolute");
	this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
	this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
	this.css("width", width);

	return this;
};
$.fn.showPopup=function() {
	$('#container').before(
		$(this).centering().overlay().bgIframe().show()
	);
	return this;
};
if ($.fn.bgIframe == undefined) {
	$.fn.bgIframe = function() {return this; };
}
if ($.fn.jqTransform == undefined) {
	$.fn.jqTransform = function() {return this; };
}
if ($.fn.jCarouselLite == undefined) {
	$.fn.jCarouselLite = function() {return this; };
}
function getAbsolutePosition(el) {
	var r = { x: el.offsetLeft, y: el.offsetTop };
	if (el.offsetParent) {
		var tmp = getAbsolutePosition(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}
$(document).ready(function(){
	// Hack for event-calendar-module from UTS
	if( $().jquery == '1.2.6' ) {
		$('form').jqTransform({imgPath:'/i/transform/'});
		return;
	}

	$('.popup .close').click(function(){
		$(this).parents('.popup').hide();
		$('div.overlay:last').remove();
		return false;
	});
	/* input hint */
	if (!$.browser.webkit) {
		$('INPUT[placeholder], TEXTAREA[placeholder]').blur(function(){ 
			if ($(this).val()=='') {
				$(this).val($(this).attr('placeholder'));
				$(this).addClass('m-placeholder');
			}
		}).focus(function(){
			$(this).removeClass('m-placeholder');
			if ($(this).val()==$(this).attr('placeholder'))
				$(this).val('');
		}).each(function(){
			if ( ($(this).val()=='') || ($(this).val()==$(this).attr('placeholder')) ) {
				$(this).val( $(this).attr('placeholder') );
				$(this).addClass('m-placeholder');
			}
			var form = $(this).closest('FORM');
			if (form.length)
				form.submit(function(){
					if ($(this).val()==$(this).attr('placeholder'))
						$(this).val('');
				});
		});
	}
	$('td:first-child,th:first-child').addClass('first');
	$('td:last-child,th:last-child').addClass('last');
	
	$('#header .mainmenu td').hover(
		function(){$(this).addClass('hover');},
		function(){$(this).removeClass('hover');}
	);

	$('form').jqTransform({imgPath:'/i/transform/'});
	
	//predicative search in select list (after jqTransform)
	var pressedKeys = {element: '', keys: new Array()};
	var main = ($.browser.webkit && !$.browser.safari) ? $('body') : $(document); //GC hack
	function predicativeSearch(event, onlySpecials){

		var $ul = $('ul:visible', 'div.jqTransformSelectWrapper');
		if( !$ul || !$ul.html() ) return true;

		event = event || window.event;

		if( event.which == 13 ){ //Enter key
			$('a.selected', $ul).click();
			if( $('#f_pred_search_hint').length ){ $('#f_pred_search_hint').remove(); }
			return false;
		}

		// filtering of pressed keys
		if( onlySpecials ){
			if( event.which != 8 )  //except Backspace key
				return true;
		}
		else{
			if( (event.which < 0x0020 || event.which > 0x007F) &&  //except latin in Unicode
				(event.which < 0x0400 || event.which > 0x04FF) )   //except cyrillic in Unicode
				return true;
		}

		if( pressedKeys.element != $ul.get(0) ){  //other select list
			pressedKeys.element = $ul.get(0);
			pressedKeys.keys = [];
			if( $('#f_pred_search_hint').length ){ $('#f_pred_search_hint').remove(); }
		}

		if( event.which == 8 ){ //Backspace -> remove last key
			pressedKeys.keys.pop();
			if( !pressedKeys.keys.length ){ //buffer is empty -> remove tip, if exist
				if( $('#f_pred_search_hint').length ){
					$('#f_pred_search_hint').remove();
				}
				return false;  //there's nothing to do, exit
			}
		}
		else  //collect pressed keys
			pressedKeys.keys.push( {keyCode: event.which, time: new Date()} );

		var searchText = '';
		for( var i in pressedKeys.keys )
			searchText = searchText + String.fromCharCode(pressedKeys.keys[i].keyCode);

		//show tip, if it not exist, or redraw it
		if( !$('#f_pred_search_hint').length ){
			$('#container').before($('<div id="f_pred_search_hint" class="pred-search-hint"><span id="f_pred_search_hint_text"></span></div>'));

			// Вычисляем ширину текста выбранного элемента (над выпадающим списком)
			//$('#f_pred_search_hint').css('visibility', 'hidden');
			//$('#f_pred_search_hint_text').text( $('span:eq(0)', $ul.parent()).text() );
			//var width = parseInt( $('#f_pred_search_hint_text').css('width') ) + 15;
			//$('#f_pred_search_hint_text').text('');
			//$('#f_pred_search_hint').css('visibility', 'visible');

			var width = $('span:eq(0)', $ul.parent()).text().length * 7 + 15; //зависит от шрифта

			$('#f_pred_search_hint').css('left', $ul.offset().left + width);
			$('#f_pred_search_hint').css('top', $ul.offset().top - 21);

			window.setTimeout(function(){
					pressedKeys.keys = new Array(); //clear buffer
					if( $('#f_pred_search_hint').length ){
						$('#f_pred_search_hint').remove();
					}
				}, 2000 );  //in milliseconds
		}
		$('#f_pred_search_hint_text').text(searchText);
		$('#f_pred_search_hint').css('width', $('#f_pred_search_hint_text').css('width')+20);

		searchText = searchText.toLowerCase();
		var found = false;
		$ul.find('a').each(function(i){ //search text in select list
			if (($(this).text().toLowerCase().indexOf(searchText) == 0)) {
				found = $(this);
				return false; //end of find cycle
			}
		});
		if( !found ) return false; //found = $('a:first',$ul);

		if( $ul.is(':visible') ) {
			$('a.selected', $ul).removeClass('selected');
			found.addClass('selected');

			if( found.offset() ) {  //scroll finded list item to top
				var offSet = $ul.scrollTop() + (found.offset().top - $ul.offset().top);
				$ul.animate({scrollTop: offSet}, 0);
			}
		}
		//else  //search with closed $ul
		//	$('span:eq(0)', $wrapper).html(found.html());
		return false;
	}
	function handleSelectWithKeyArrows(event){

		var $ul = $('ul:visible', 'div.jqTransformSelectWrapper');
		if( !$ul || !$ul.html() ) return true;

		event = event || window.event;

		if( event.which != 38 && // except Up key
			event.which != 40 ){ // except Down key
			return true;
		}

		var $a = $('a.selected', $ul);
		if( !$a || !$a.length ) return true;

		// remove tip and focus selected list element
		if( $('#f_pred_search_hint').length ){
			$('#f_pred_search_hint').remove();
		}
		$a.focus();

		var isMoved = false;
		
		// Up key pressed
		if( event.which == 38 ) {
			// search prev "<li>" element, which contain "<a>"
			var prevA, prevLi = $a.parent().prev();
			while( prevLi.length ) {
				prevA = $('a', prevLi);
				if( prevA.length ) break;
				prevLi = prevLi.prev()
			}
			// move selected class and focus
			if( prevA && prevA.length ) {
				$a.removeClass('selected');
				$a = prevA.addClass('selected').focus();
				isMoved = true;
			}
		}

		// Down key pressed
		if( event.which == 40 ) {
			// search next "<li>" element, which contain "<a>"
			var nextA, nextLi = $a.parent().next();
			while( nextLi.length ) {
				nextA = $('a', nextLi);
				if( nextA.length ) break;
				nextLi = nextLi.next()
			}
			// move selected class and focus
			if( nextA && nextA.length ) {
				$a.removeClass('selected');
				$a = nextA.addClass('selected').focus();
				isMoved = true;
			}
		}

		return false;
		//scroll new selected element to top
		//if( isMoved && $ul.is(':visible') && $a.offset() ) {
		//	var offSet = $ul.scrollTop() + ($a.offset().top - $ul.offset().top);
		//	$ul.animate({scrollTop: offSet}, 0);
		//}
		//
		//return false;
	}
	main.bind('keypress', function(event){
		return predicativeSearch(event, false);
	});
	main.bind('keydown', function(event){
		if( !handleSelectWithKeyArrows(event) ) return false;
		if( !predicativeSearch(event, true) ) return false;
		return true;
	});
	
	$('.fine .menu span').click(function(){
		$(this).siblings().removeClass('active').end().addClass('active');
	});
	$('.order-block .order-info .container-div').hover(
		function(){
			$(this).removeClass('gradient-grey');
			$(this).addClass('gradient-green');
		},
		function(){
			$(this).removeClass('gradient-green');
			$(this).addClass('gradient-grey');
		}
	);
	
	$('.order-user .user').click(function(){
		$('#pp-userinfo').showPopup();
		return false;
	});
	//$('.main-ticker .carousel').jCarouselLite({
	//	visible: 2,
	//	speed: 800,
	//	btnNext: '.main-ticker .next',
	//	btnPrev: '.main-ticker .prev',
	//	circular: true,
	//	vertical: true
	//});
	$('.main-full .full').click(function(){
		$(this).parents('.main-full').eq(0).addClass('main-full-active').find('tr.hidden').show();
		$(this).hide().next().show();
		return false;
	});
	$('.main-full .less').click(function(){
		$(this).parents('.main-full').eq(0).removeClass('main-full-active').find('tr.hidden').hide();
		$(this).hide().prev().show();
		return false;
	});
	$('#header .user .enter').click(function(){
		$('#pp-login').showPopup();
		$('#id_login').focus();
		return false;
	});
	
	$('#id_remind').focus(function(){
		$('#id_pass').focus();
	});
});

