jQuery.fn.ajaxSelect = function(options){

	var options = jQuery.extend({
		
		url : null,
		action : "error",
		cancelButton : true,
		
		backgroundColor : "#FFFFFF",
		borderColor : "#000000",
		textColor : "#000000",
		callback : function(){}
		
	}, options);
	
	var change = function(select){
		$(select).change(function(){			
			var change_to = $(this).val();
			$(this).parent().find("span.option").attr("title", "");
			var selected_option = $("<span class='option' rel='"+change_to+"' title='selected' style='display: none;'>"+$(this).parent().find("span.option[rel="+change_to+"]").html()+"</span>");
			$(this).parent().find("span.option[rel="+change_to+"]").remove();
			$(selected_option).appendTo($(this).parent());
			$(this).parent().find(".input_select").css("display", "block");
			$(this).parent().find(".input_select").html($(this).parent().find("span.option[rel="+change_to+"]").html());

			send(select);
		});
	};
	
	var send = function(select){
		if (options.url == null) return false;
		
		var container = $(select).parent().parent();
		var value = $(select).val();
		var data = $(select).attr('name');
		var message = new ResultMessage("");
		$.ajax({
		    url: options.url,
		    type : 'post',
		    data : 'action='+options.action+'&data='+data+'&value='+value,
		    beforeSend : function(){
				message.SetText("Сохранение...");
				message.SetBackgroundColor("#FFEAB8");
				message.Display();
		    },
		    success: function (data, textStatus) { 
		    	if (data == 'ok')
		    	{
		    		message.SetText("Сохранено успешно!");
		    		message.SetBackgroundColor("#178400");
		    		message.SetFontColor("#ffffff");
		    		$(container).css('background', '#00aa00');
			    	$(container).fadeTo(1000, 0.3, function () {
			    		$(container).css('background', 'none');
			    		$(container).css('opacity', '1');
              		});
			    	message.Delete();
					$(select).remove();
					options.callback();
		    	}
		    	else
		    	{
		    		message.SetText("Возникла ошибка при сохранении!");
		    		message.SetBackgroundColor("#FF77FF");
		    		$(container).css('background', '#dd0000');
			    	$(container).fadeTo(2000, 0.3, function () {
			    		$(container).css('background', 'none');
			    		$(container).css('opacity', '1');
              		});
			    	message.Delete();
					$(select).remove();
					options.callback();
		    	}
		    }
		});
	};

	return this.each(function() {
		$(this).click(function(){
			$(this).css('display', 'none');
			var data = $(this).attr('name');
			
			var select = $("<select class='select' name='"+data+"' style='border-color: "+options.borderColor+"; color: "+options.textColor+"; background: "+options.backgroundColor+";'></select>").appendTo($(this).parent()).get(0);
			$(this).nextAll("span.option").each(function(){
				var option = $("<option value='"+$(this).attr('rel')+"'>"+$(this).text()+"</option>");
				if ($(this).attr('title') == "selected")
				{
					$(option).get(0).defaultSelected = true;
					$(option).get(0).selected = true;
				}
				select.appendChild($(option).get(0));						
			});
	
			change(select);
		});
	});
};

(function($) {
	$.topScroll = function() 
	{
		return document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
	}

	$.leftScroll = function() {
		return document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
	}
	
	$.WindowWidth = function()
  {
    if(document.all && !window.opera)
    {
       var iebody = (document.compatMode == 'CSS1Compat') ? document.documentElement : document.body;
       return iebody.clientWidth;
    }
     
    return (window.top.innerWidth)?window.top.innerWidth: ((document.all)?document.body.offsetWidth:null);
  }
    
  $.WindowHeight = function()
  {
      if(document.all && !window.opera)
      {
          var iebody = (document.compatMode == 'CSS1Compat') ? document.documentElement : document.body;
          return iebody.clientHeight;
      }
      
      return (window.top.innerHeight)?window.top.innerHeight: ((document.all)?document.body.offsetHeight:null); 
  }

	$.getClientWidth = function()
	{
	  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
	}

	$.getClientHeight = function()
	{
		if(document.documentElement)
		{
			if(document.documentElement.clientHeight)
			{
				return document.documentElement.clientHeight;
			}
		}
		return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
	}
	
	$.GetKeyCode = function(e)
	{
		var code = 0;
		e = e || window.event;
		//Find Which key is pressed
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		
		return code;
	}

	$.UrlEncode = function(string) 
	{
		string = string.replace(/\r\n/g, "\n"); var utftext = ""; for ( var n = 0; n < string.length; n++) {var c = string.charCodeAt(n);if (c < 128) {utftext += String.fromCharCode(c);} else if ((c > 127) && (c < 2048)) {utftext += String.fromCharCode((c >> 6) | 192);utftext += String.fromCharCode((c & 63) | 128);} else {utftext += String.fromCharCode((c >> 12) | 224);utftext += String.fromCharCode(((c >> 6) & 63) | 128);utftext += String.fromCharCode((c & 63) | 128);}}
		return escape(utftext);
	}

	$.UrlDecode = function(utftext) 
	{
		utftext = unescape(utftext);
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while (i < utftext.length) {	c = utftext.charCodeAt(i);	if (c < 128) {	string += String.fromCharCode(c);	i++;} else if ((c > 191) && (c < 224)) {c2 = utftext.charCodeAt(i + 1);	string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));	i += 2;	} else {c2 = utftext.charCodeAt(i + 1);	c3 = utftext.charCodeAt(i + 2);	string += String.fromCharCode(((c & 15) << 12)	| ((c2 & 63) << 6) | (c3 & 63));i += 3;	}}
		
		return string;
	}
	
	$.DeleteFromArray = function(array, index)
	{
		var return_arr = [];
		var j = 0;
		
		for(var i = 0; i < array.length; i++)
		{
			if (i != index)
			{
				return_arr[j] = array[i];			
				j++;
			}
		}
		
		return return_arr;
	}
	
	$.Random = function(min, max)
	{
		min = parseInt(min); 
		max = parseInt(max);
		return Math.floor( Math.random() * (max - min + 1) ) + min;
	}
	
	$.SetCookie = function(name, value, expires, path, domain, secure)
	{
		var expire_date = new Date();
	    
	    expire_date.setDate(expire_date.getDate() + expires);
	    document.cookie = (name + "=" + escape(value) + ((expires == null) ? "" : ";expires=" + expire_date.toGMTString()));

	    return true;

		//document.cookie = name + "=" + escape(value)+((expires) ? "; expires=" + expires : "")+((path) ? "; path=" + path : "")+((domain) ? "; domain=" + domain : "")+((secure) ? "; secure" : "");
	}
	
	$.GetCookie = function(name)
	{
		var cookie = " " + document.cookie;
		var search = " " + name + "=";
		var setStr = null;
		var offset = 0;
		var end = 0;
		if (cookie.length > 0)
		{
			offset = cookie.indexOf(search);
			if (offset != -1)
			{
				offset += search.length;
				end = cookie.indexOf(";", offset);
				if (end == -1)
				{
					end = cookie.length;
				}
				setStr = unescape(cookie.substring(offset, end));
			}
		}
		return(setStr);
	}
	
	$.HighlightWord = function(word, text, hashcolor)
	{
		//TODO: написать обход яваскриптов, поиск в них подсвечиваемого слова и не подсвечивать его
		//TODO: а лучше еще, переписать и сделать НОРМАЛЬНО!!
		var html = text;
		var pattern = new RegExp(word, "ig"); // регистронезависимый
		var pattern_tag = new RegExp("<[ a-z\\-\\:;0-9\\(,\\)\\\"=\\[\\]\\/#'_]+"+word+"[ a-z\\-\\:;0-9\\(,\\)\\\"=\\[\\]\\/#'_]+>", "ig"); //<[ a-z\-\:;0-9\(,\)"=\[\]\/\'\#]+name[ a-z\-\:;0-9\(,\)"=\[\]\/\'\#]+>
		var pattern_script = new RegExp("<script[ a-z\\-\\:;0-9\\(,\\)\\\"=\\[\\]\\/'#_\\$\\{\\}\\.\\n]+>[ a-z\\-\\:;0-9\\(,\\)\\\"=\\[\\]\\/'#_\\$\\{\\}\\.\\n]+"+word+"[ a-z\\-\\:;0-9\\(,\\)\\\"=\\[\\]\\/'#_\\$\\{\\}\\.\\n]+<\/script>");
		//alert(pattern_script);
		var index = 0;
		var index_tag = 0;
		var index_script = 0;
		var final_text = '';

		while(index != -1)
		{
			index = html.search(pattern);
			index_tag = html.search(pattern_tag);
			index_script = html.search(pattern_script);
			//alert(index_script);
			
			var flag_tag = false;
			if (index_tag != -1)
			{
				var tag = html.substring(index_tag, html.length);
				var word_pos = tag.search(pattern);
				index_tag++; index_tag--;
				word_pos++; word_pos--;
				word_pos = index_tag + word_pos;
			
				if (index == word_pos)
				{
					flag_tag = true;
				}
			}
			
			var flag_script = false;
			/*if (index_script != -1)
			{
				var tag = html.substring(index_script, html.length);
				var word_pos = tag.search(pattern);
				index_tag++; index_tag--;
				word_pos++; word_pos--;
				word_pos = index_tag + word_pos;
				alert('index = '+index+' | word_pos = '+word_pos+' | index_script = '+index_script);
			
				if (index == word_pos)
				{
					flag_script = true;
				}
			}*/
			
			var before = html.substr(0, index);
			var curw = html.substr(index, word.length);
			html = html.substring((index+curw.length), html.length);
			  
			if (index != -1 && !flag_tag && !flag_script)
			{
				final_text = final_text + before + "<span style='background: #"+hashcolor+"; font-style: italic;'>"+curw+"</span>";
			}
			else
			{
				final_text = final_text + before + curw;
			}
		}
		
	    final_text = final_text + html;
	    
	    return final_text;
	}
	
	$.GetTrueDate = function(lang, template)
	{
		var date = new Date();
		var day = date.getDate();
		var year = date.getFullYear();
		var month = date.getMonth();
		var hour = date.getHours();
		var minute = date.getMinutes();
		
		var months = [ "январь", "февраль", "март", "апрель", "май", "июнь", "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь" ];
		
		if (template == null)
		{
			template = "day month year, hour:minute";
		}
			
		template = template.replace("day", day);
		template = template.replace("month", months[month]);
		template = template.replace("year", year);
		template = template.replace("hour", hour);
		template = template.replace("minute", minute);
		
		return template;		
	}
	
	$.SetTableSortName = function(table, names)
	{
		if (names == null) return;
		
		if ($(table).children("tbody") != null)
		{
			var thead = $("<thead></thead>").insertBefore($(table).children('tbody'));
			var panel = $("<tr></tr>").appendTo(thead);
			var buttons = [];
			
			for (var i = 0; i < names.length; i++)
			{
				if (names[i] != null && names[i] != '')
				{
					buttons[i] = $("<td align='center' id='button["+i+"]'>"+names[i]+"</td>").appendTo(panel);
				}
				else
				{
					buttons[i] = $("<td>&nbsp;</td>").appendTo(panel);
				}
			}						
		}
	}
	
	$.SetExampleTextInput = function(object, text)
	{
		var flag = false;
		$(object).css('color', '#777777');
		$(object).html(text);
		
		$(object).focus(function(){
			
			if( flag == false && $(object).html() == text )
			{
				$(object).html('');
				flag = true;
			}
							
		});

		$(object).blur(function(){
			
			if( flag == true && $(object).html() == '' )
			{
				$(object).html(text);
				flag = false;
			}
							
		});
	}
	
	$.ShowHideButton = function(button, object, text_show, text_hide, flag)
	{
		$(button).css('cursor', 'pointer');
		
		$(button).click(function(){
			if ($(object).css('display') == 'block')
			{
				$(object).css('display', 'none');
				$(this).html(text_show);
			}
			else
			{
				$(object).css('display', 'block');
				$(this).html(text_hide);
			}	 
	    });
		
		if (flag)
		{
			$(object).css('display', 'block');
			$(button).html(text_hide);
		}

		//$(button).bind("click", {button: button, object: object}, ShowHide);
    	/*function ShowHide(event)
    	{
    		if ($(event.data.object).css('display') == 'block')
			{
				$(event.data.object).css('display', 'none');
				$(event.data.button).html(text_show);
			}
			else
			{
				$(event.data.object).css('display', 'block');
				$(event.data.button).html(text_hide);
			}	
    	}*/
	}

	$.ShowHint = function(anchor, hint_type, type, show_on_hint)
	{
		//alert(typeof(hint_type)); string
		//alert(typeof($('body:first'))); object
		var hint;
		
		if(typeof(hint_type) == 'string')
		{
			hint = $(anchor).next(hint_type);
		}
		else
		{
			hint = $(hint_type);
		}

		$(anchor).mouseover(function(){

			var position = $(this).offset();
			var height = $(this).height();
			var width = $(this).width();

			$(hint).css('top', position.top-($(hint).height())+3);
			if (type == 'left')
			{
				$(hint).css('left', position.left-$(hint).width()-3);
			}
			else if (type.indexOf('+') != -1)
			{
				var move = type.substr(1, type.length);
				$(hint).css('left', position.left + width - 3);
			}
			else
			{
				$(hint).css('left', position.left + width - 3);
			}
			$(hint).css('display', 'block');
			
		});
		/*
		var text = $(hint).html();
				text = text.replace(" ", "&nbsp;");
				text = text.replace(" ", "&nbsp;");
				$(hint).html(text);
		*/

		$(anchor).mouseout(function(){

			$(hint).css('display', 'none');
			
		});
		
		$(anchor).mousemove(function(e){
			var hint_width = $(hint).width() + 2;
			if ($(document).width() - hint_width - e.pageX - 15 - 16 > 0)
			{
				$(hint).css("top",(e.pageY - 22) + "px");
				$(hint).css("left",(e.pageX + 15) + "px");				
			}
			else
			{
				var text = $(hint).html();
				text = text.replace(" ", "&nbsp;");
				text = text.replace(" ", "&nbsp;");
				$(hint).html(text);
				$(hint).css("top",(e.pageY - 22) + "px");
				$(hint).css("left",(e.pageX - 15 - $(hint).width()) + "px");
			}
		});	
		
		if (show_on_hint)
		{
			$(hint).mouseover(function(){
				//$(hint_type).css('top', position.top-($(hint).height())+3);
				//$(hint_type).css('left', position.left+width-3);
				$(this).css('display', 'block');			
			});
	
			$(hint).mouseout(function(){
				$(this).css('display', 'none');			
			});
		}
	}
})(jQuery);
