IPoint = function ( x, y )
{
	this.x = x;
	this.y = y;
}

IRect = function ( x1, y1, x2, y2, w, h )
{
	var o_this = this;
	this.x1 = x1;
	this.x2 = x2;
	this.y1 = y1;
	this.y2 = y2;
	this.width = w;
	this.height = h;
}

IRectSmart = function ( x1, y1, x2, y2, _dim )
{
	var o_this = this;
	this.x1 = x1;
	this.x2 = x2;
	this.y1 = y1;
	this.y2 = y2;
	this.width = null;
	this.height = null;
	this.dim = _dim;
	
	this.Init = function ()
	{
		// если dim не указан, то считаем x2 и y2 - координаты второй точки
		if ( typeof (o_this.dim) == 'undefined' )
		{
			o_this.width = o_this.x1 - o_this.x2;
			o_this.height = o_this.y1 - o_this.y2;
		
			if ( o_this.width < 0 ) o_this.width = o_this.width * -1;
			if ( o_this.height < 0 ) o_this.height = o_this.height * -1;
		}
		// иначе x2 - относительное смещение по горизонтали (+-ширина) и y2 - относительное смещение по вертикали (+-высота)
		else
		{
			o_this.width = o_this.x2;
			o_this.height = o_this.y2;
			o_this.x2 = o_this.x1 + o_this.width;
			o_this.y2 = o_this.y1  + o_this.height;
		}
	}
	
	this.Init();
}

/**
 * Класс кнопки для CSS sprite
 * @param {Object} place - носитель
 * @param {Object} css_rect	- размер кнопки
 * @param {Object} img_src - источник
 * @param {Object} img_pos - положение текстур по состояниям (массив IPoint)
 */


	var mybutton = function ( _debug )
	{
		var debug = _debug;
		
		var bCSS_Sprite = false;	// флаг, используем CSS Sprite
		var vCSS_Sprite = null;		// текстура кнопок

		var imagestate = new Array ();
		var imagestatecur = 0;
		var place = 0;
		var blankimage = 'blank.gif';
		var disabled = false;
		var downstate = false;
		var downstyle = false;
		var buttonstate = 'up';
		var jsevents = 0;
		var noimages = true;
		var backobj = null;
		var jsevents2 = null;
		this.id = 'testbut';
		
		// состояния по умолчанию для функции setImagesArrayPos2Src
		var deff_Pos2Src = {'up':0, 'down':0, 'over':0, 'disable':0};

		this.setEvents = function ( )
		{
			jsevents = new JsEventListener(place, true);
			jsevents.Init(place);
			jsevents.appendEvent ( 'mouseover', this.eventOnmouseover  );
			jsevents.appendEvent ( 'mouseout',  this.eventOnmouseout   );
			jsevents.appendEvent ( 'mousedown', this.eventOnmousedown  );
			jsevents.appendEvent ( 'mouseup',   this.eventOnmouseup    );
			jsevents.appendEvent ( 'click',     this.eventOnmouseclick );
/*
			if (backobj != null )
			{
				jsevents2 = new JsEventListener(backobj , true);
				jsevents2.Init(backobj );
				jsevents2.appendEvent ( 'mouseover', this.eventOnmouseover  );
				jsevents2.appendEvent ( 'mouseout',  this.eventOnmouseout   );
				jsevents2.appendEvent ( 'mousedown', this.eventOnmousedown  );
				jsevents2.appendEvent ( 'mouseup',   this.eventOnmouseup    );
				jsevents2.appendEvent ( 'click',     this.eventOnmouseclick );
			}
			*/
		}

		this.getImages = function ()
		{
			return imagestate;
		}

		this.setBlankImage = function ( str )
		{
			blankimage = str;
		}
		this.setDisabled = function ( str )
		{
			if ( disabled != str )
			{
				disabled = str;
				jsevents.setDisabled (disabled);
				if ( jsevents2 != null )
					jsevents2.setDisabled (disabled);
				place.drawButton ();
			}
			
		}
		this.setDownStyle = function ( str )
		{
			if (downstyle != str) {
				downstyle = str;
			
				if (downstyle == false) 
					downstate = false;
				place.drawButton();
			}
		}
		this.getDownStyle = function ()
		{
			return downstyle;
		}
		this.getState = function ()
		{
			return downstate;
		}
		this.setState = function (str)
		{
			downstate = str;
			if ( downstyle == false ) 
				downstate = false;

			if ( downstate )
				imagestatecur = imagestate['down'];
			else
				imagestatecur = imagestate['up'];

			place.drawButton ();
		}
		this.getDisabled = function ()
		{
			return disabled;
		}
		this.toggleDisabled = function ()
		{
			this.setDisabled ( !disabled );
			jsevents.setDisabled (!disabled);
			if ( jsevents2 != null )
				jsevents2.setDisabled (!disabled);
		}

		this.getPlace = function ()
		{
//			if ( isIE () == true )
//				return backobj;
//			else
				return place;
		}
		this.getPlaceIE = function ()
		{
			if ( isIE () == true )
				return backobj;
			else
				return place;
		}
		
		
		this.setHint = function (str)
		{
			if ( backobj != null )
				setHintToObj ( backobj, str );
			setHintToObj ( place, str );
		}
		
		this.setPlaceBack = function ()
		{
			if ( isIE () == true )
			{
				backobj = document.createElement ('div');
				$(place).append ( backobj  );
				backobj.button = new Object (this);
			//	$(backobj).attr("bid", place.id);
			}
//			else
//				$(place).attr("bid", place.id);
				 
		}

		this.setPlace = function ( obj )
		{
			place = obj;
			
			this.setPlaceBack();
			
			place.button = new Object (this);

			place.drawButton = function ()
			{
				if ( debug){
				place.style.width = 100;
				place.style.height = 50;}

				if ( noimages ) return false;

//				if ( typeof (imagestate['disable']) == 'undefined') return false;

				// безусловное состояние
				if (disabled == true ) imagestatecur = imagestate['disable'];

				// если не отключена и картинка равна отключеной (т.е. состояние только что изменилось)
				if (disabled == false && imagestatecur == imagestate['disable'] ) 
					imagestatecur = imagestate['up'];

				// новый рендер
				if ( bCSS_Sprite == true )
				{
					setBackImagePos ( place, backobj, vCSS_Sprite, imagestatecur );
				}
				// иначе старый рендер
				else
				{
					if ( typeof ( imagestatecur.src != "undefined" ))
						place.style.backgroundImage = "url('"+imagestatecur.src+"')";
						
					if (imagestatecur.src.match(blankimage))
					{
						place.style.filter = imagestatecur.style.filter;
					}
				}
			};

			this.setEvents();

			imagestatecur = imagestate['up'];
			$(place).css('cursor', 'pointer');			
			place.drawButton ();
		}
		this.setImages = function ( path, str, ext, state )
		{
			if (state['up']) 	imagestate['up'] = 	 this.loadPNG ( path+str +state['up']	 + '.' +ext );
			if (state['down']) 	imagestate['down'] = 	 this.loadPNG ( path+str +state['down']	 + '.' +ext );
			if (state['over']) 	imagestate['over'] = 	 this.loadPNG ( path+str +state['over']	 + '.' +ext );
			if (state['disable']) 	imagestate['disable'] =  this.loadPNG ( path+str +state['disable']+ '.' +ext );
			if (state['down_over'])	imagestate['down_over']= this.loadPNG ( path+str +state['down_over']+ '.' +ext );
			noimages = false;
		}
		this.setImagesArray = function ( arr_args )
		{
			if ( typeof (arr_args) === 'undefined' || typeof (arr_args) === null ) return false;

			if ( typeof (arr_args['up']) != 'undefined' )		imagestate['up'] = arr_args['up'];
			if ( typeof (arr_args['down']) != 'undefined' )		imagestate['down'] = arr_args['down'];
			if ( typeof (arr_args['over']) != 'undefined' )		imagestate['over'] = arr_args['over'];
			if ( typeof (arr_args['disable']) != 'undefined' )	imagestate['disable'] = arr_args['disable'];
			if ( typeof (arr_args['down_over']) != 'undefined' )	imagestate['down_over'] = arr_args['down_over'];
			noimages = false;
		}
		this.setImagesArraySrc = function ( arr_args )
		{
			if ( typeof (arr_args) === 'undefined' || typeof (arr_args) === null ) return false;

			if ( typeof (arr_args['up']) != 'undefined' )		imagestate['up'] = preLoadOne(arr_args['up']);
			if ( typeof (arr_args['down']) != 'undefined' )		imagestate['down'] = preLoadOne(arr_args['down']);
			if ( typeof (arr_args['over']) != 'undefined' )		imagestate['over'] = preLoadOne(arr_args['over']);
			if ( typeof (arr_args['disable']) != 'undefined' )	imagestate['disable'] = preLoadOne(arr_args['disable']);
			if ( typeof (arr_args['down_over']) != 'undefined' )	imagestate['down_over'] = preLoadOne(arr_args['down_over']);
			noimages = false;
		}
		
		/**
		 * Установим текстуры для состояний кнопки
		 * @param {Object} img_src - источник
		 * @param {Object} img_pos - положение на картинке состояний (массив) *-1
		 */
		this.setImagesArrayPosSrc = function ( img_src, img_pos )
		{
			bCSS_Sprite = true;
			vCSS_Sprite = img_src;
			// предзагрузка или восстановление
			preLoadOne ( img_src );
			imagestate = img_pos;
			noimages = false;
		}
		/**
		 * Установим текстуры для состояний кнопки
		 * @param {Object} img_src - источник
		 * @param {Object} img_pos - положение на картинке первого состояния (IRect)
		 * @param {Object} states - состояния кнопки в порядке следования слева направо
		 */
		this.setImagesArrayPos2Src = function ( img_src, img_pos, states )
		{
			if ( typeof(states) == 'undefined' ) states = deff_Pos2Src;
				
			bCSS_Sprite = true;
			vCSS_Sprite = img_src;
			// предзагрузка или восстановление
			preLoadOne ( img_src );
			
			// сгенерим состояния
			imagestate = img_pos;
			var count = 0;
			
			if ( isIE () == true )
			{
				for ( var i in states )
				{
					var w = img_pos.width;
					var h = img_pos.height;
					var x1 = img_pos.x1 + w * count;
					var y1 = img_pos.y1;
					var x2 = x1 + img_pos.width;
					var y2 = y1 + h;
					imagestate[i] = new IRect ( x1, y1, x2, y2, w, h );
					count = count + 1;
				}
			}
			else
			{
				for ( var i in states )
				{
					imagestate[i] = new IPoint ( (img_pos.x1 + img_pos.width * count) * -1, img_pos.y1 * -1 );
					count = count + 1;
				}
			}
			
			noimages = false;
		}
		
		this.loadPNG = function ( str )
		{
			var ret = new Image();
			var arVersion = navigator.appVersion.split("MSIE");
			var version = parseFloat(arVersion[1]);
//			if ((version >= 5.5) && (version < 7.0) && (navigator.appName == "Microsoft Internet Explorer") && (document.body.filters)) 
			if ((version >= 5.5) && (navigator.appName == "Microsoft Internet Explorer") && (document.body.filters)) 
			{
				ret.src='images/blank.gif';
				ret.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader (src=' + str +')';
			}
			else
			{
				ret.src=str;
			}
			return ret;
		}


		this.eventOnmouseover = function ( ev )	
		{
			if ( downstate )
				imagestatecur = imagestate['down_over'];
			else
				imagestatecur = imagestate['over'];

			place.drawButton();
		}
		this.eventOnmouseout  = function ( ev )
		{
			if ( downstate )
				imagestatecur = imagestate['down'];
			else
				imagestatecur = imagestate['up'];

			place.drawButton ();
		}
		this.eventOnmouseclick = function ( ev )
		{
			if ( downstyle ) 
			{
//				alert ('click');
				downstate = !downstate;

				if ( downstate )
					imagestatecur = imagestate['down_over'];
				else
					imagestatecur = imagestate['up'];
			}			

			
			place.drawButton ();
			
			return false;

		}

		this.eventOnmousedown = function ( ev )
		{
			if ( !downstyle )
			{
				imagestatecur = imagestate['down'];
				place.drawButton ();
			}
		}
		this.eventOnmouseup = function ( ev )
		{
			if ( !downstyle )
			{
				imagestatecur = imagestate['over'];
				place.drawButton ();
			}
		}


		this.eventAttach = function ( event, func )
		{
			jsevents.appendEvent (event, func );
			if ( jsevents2 != null )
				jsevents2.appendEvent (event, func );
		}
		this.eventDetach = function ( event, func )
		{
			jsevents.removeEventFunc (event, func );
			if ( jsevents2 != null )
				jsevents2.removeEventFunc (event, func );
		}
		this.eventRemove = function ( event )
		{
			jsevents.removeEvent (event );
			if ( jsevents2 != null )
				jsevents2.removeEvent (event );
		}

		this.list = function ()
		{
			jsevents.listEvent();
			if ( jsevents2 != null )
				jsevents2.listEvent();
		}

	}
