$.fn.check = function() {
	return this.each(function() {
		this.checked = true;
	});
};

$.fn.uncheck = function() {
	return this.each(function() {
		this.checked = false;
	});
};


// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}


/**
* EasyDrag 1.4 - Drag & Drop jQuery Plug-in
*
* Thanks for the community that is helping the improvement
* of this little piece of code.
*
* For usage instructions please visit http://fromvega.com
*/

(function($){

	// to track if the mouse button is pressed
	var isMouseDown    = false;

	// to track the current element being dragged
	var currentElement = null;

	// callback holders
	var dropCallbacks = {};
	var dragCallbacks = {};

	// global position records
	var lastMouseX;
	var lastMouseY;
	var lastElemTop;
	var lastElemLeft;

	// returns the mouse (cursor) current position
	$.getMousePosition = function(e){
		var posx = 0;
		var posy = 0;

		if (!e) var e = window.event;

		if (e.pageX || e.pageY) {
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY) {
			posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
		}

		return { 'x': posx, 'y': posy };
	};

	// updates the position of the current element being dragged
	$.updatePosition = function(e) {
		var pos = $.getMousePosition(e);

		var spanX = (pos.x - lastMouseX);
		var spanY = (pos.y - lastMouseY);
		
		$(currentElement).css("top",  (lastElemTop + spanY));
		$(currentElement).css("left", (lastElemLeft + spanX));
	};

	// when the mouse is moved while the mouse button is pressed
	$(document).mousemove(function(e){
		if(isMouseDown){
			// update the position and call the registered function
			$.updatePosition(e);
			if(dragCallbacks[currentElement.id] != undefined){
				//dragCallbacks[currentElement.id](e);
				dragCallbacks[currentElement.id](e, currentElement);
			}

			return false;
		}
	});

	// when the mouse button is released
	$(document).mouseup(function(e){
		if(isMouseDown){
			isMouseDown = false;
			if(dropCallbacks[currentElement.id] != undefined){
				dropCallbacks[currentElement.id](e, currentElement);
			}

			return false;
		}
	});

	// register the function to be called while an element is being dragged
	$.fn.ondrag = function(callback){
		return this.each(function(){
			dragCallbacks[this.id] = callback;
		});
	};

	// register the function to be called when an element is dropped
	$.fn.ondrop = function(callback){
		return this.each(function(){
			dropCallbacks[this.id] = callback;
		});
	};

	// set an element as draggable - allowBubbling enables/disables event bubbling
	$.fn.easydrag = function(allowBubbling){

		return this.each(function(){

			// if no id is defined assign a unique one
			if(undefined == this.id || !this.id.length) this.id = "easydrag"+(new Date().getTime());

			// change the mouse pointer
			//$(this).css("cursor", "move");

			// when an element receives a mouse press
			$(this).find('.dragheader').css("cursor", "move").mousedown(function(e){
				//this = $(this).parents('DIV.popup')[0];
				papa = $(this).parents('DIV')[0];
								
				// set it as absolute positioned
				$(papa).css("position", "absolute");

				// set z-index
				$(papa).css("z-index", "10000");

				// update track variables
				isMouseDown    = true;
				currentElement = papa;

				// retrieve positioning properties
				var pos    = $.getMousePosition(e);
				
				lastMouseX = pos.x;
				lastMouseY = pos.y;

				lastElemTop  = papa.offsetTop;
				lastElemLeft = papa.offsetLeft;
				

				$.updatePosition(e);

				return allowBubbling ? true : false;
			});
		});
	}

})(jQuery);



	var controlsInitialized = false;
	
	
	
	function InitializeControls() {
		if (controlsInitialized) return;
		
		controlsInitialized = true;
	
		$('TABLE.select_block').each(function() {
			if ($(this).attr('inited') != 'yeah') {
				
				var $controlText = $(this).find('DIV.block_123');
				
				$(this).find('IMG.select_opener').add($controlText).click(function() {
					
					var $papa = $(this).parents('TABLE.select_block');
					var $opener = $papa.find('IMG.select_opener'); 
					
					
					$active_p = $papa.find('p[selected_value="1"]');
					$active_p.css('backgroundColor', '#dbdbdb'); 
					
					
					
					$active_p_offset_top = 0;
					$active_p.prevAll().each(function() {
						$active_p_offset_top += 12 + 7; 
					});
					$active_p.parent('div').scrollTo({top:$active_p_offset_top+'px', left:'0px'},200);
					
					
					
					
					if (!$papa.find('DIV.options_list').is(':visible')) {
						$opener.attr('src','/img/select/03_open.gif');
					} else {
						$opener.attr('src','/img/select/03.gif');
					}

					$(this).parents('TABLE.select_block').find('DIV.options_list').toggle();
					
					return false;
					
				}).end().end().find('DIV.options_list DIV').click(function(e) {
								
					var srcEl = e ? e.target : event.srcElement;		
					
				    if (srcEl.getAttribute('value')=='nogo') {
				    	return false;
				    }
					
					
					$('IMG.select_opener').attr('src','/img/select/03.gif');
					
					if (srcEl.tagName == 'P') {
						
						$(srcEl).parents('TABLE.select_block').find('p[selected_value=1]').removeAttr('selected_value').css('backgroundColor', '');
						$(srcEl).attr('selected_value','1');
						
						$(srcEl).parents('TABLE.select_block').
							find('DIV.block_123').html(trim(srcEl.innerHTML)).
							end().find('DIV.options_list').hide().
							end().find('INPUT').each(function() { 
								this.value = srcEl.getAttribute('value'); 
								var $this = $(this);
								$this.change();
							});
						
						return false;
					}		
					
				}).blur(function(e) {
					var srcEl = e ? e.target : event.srcElement;
					$(srcEl).parents('TABLE.select_block').find('DIV.options_list').hide();
					
				}).end().find('INPUT.select_input').each(function() {
					var inputValue = this.value;
					var inputText = $(this).parents('TABLE.select_block').find('DIV.block_123');
															
					$(this).parent().find('P').each(function() {
						if (this.getAttribute('value') == inputValue) {
							inputText.html(trim(this.innerHTML));
						}
					}).hover(function() {
						$(this).css('backgroundColor', '#dbdbdb'); 
					}, function() {
						
						if($(this).attr('selected_value') != '1') {
							$(this).css('backgroundColor', ''); 
						}
					});
				}).end().attr('inited', 'yeah'); 
			}
		});
		
		
		// Теперь чекбоксы
		$('DIV.checkbox').click(function() {
			if ($(this).find('input')[0].checked) {
				this.check(false);		
			} else {
				this.check(true);
			}
		}).each(function() {
			this.check = function(isChecked) {
				$(this).find('input')[0].checked = isChecked;
				$(this).find('img')[0].src = isChecked ? '/img/icons/check_box_1.gif' : '/img/icons/check_box_2.gif';
			}
			
			this.check($(this).find('input')[0].checked); 
		}); 
		
		
		// Таскаемые диалоги
		$('DIV.draggable').easydrag();
	}
	
	
	
	
	
	function collect() {
		var ids = $('#hids').val();
		
		if ((ids) && (ids!='')) {
			var log = $('#hids').val().split(',');
		} else {
			var log = new Array();
		}
		
		
		$('div.checkbox').find('input:checked').each(function() { 
			if (!log.inArray($(this).val())) {
				log.push($(this).val());
			}
		});
			
			
		return log;
	}	
	

	$(document).ready(function() {
		InitializeControls(); 
		
		$(document).click(function(e) {
			if ($(e.target).parents('DIV.select_options').length) return;			
			$('DIV.options_list:visible').each(function() {
				$(this).hide().parents('TABLE.select_block').find('IMG.select_opener').attr('src', '/img/select/03.gif');
			});
		});
		
		$('div.checkbox').click(function(){ 
		
			$('.link_print').each(function(){
				log = collect();	
				this.href='/search/request.phtml'+'?step&request=print&ids='+log.join("|");		
			});
		
		
	
			$('.link_rtf').each(function(){
				log = collect();	
				console.log(log);
				this.href='/rtfexporter.php'+'?mode=rtf&id='+log.join("|");		
			});	
		
		});		
		
	});



	$(document).keydown(function(e) {
	     
	     if (e.keyCode == 27) {	         
	         
			
			$('div.options_list').each(function() {
			 	$(this).hide();			 				
			})
			
	     }
	
	});
