﻿/************************************************************
 *     Модуль манипуляции свойствами объекта
 *
 *     Автор:                     Агроник А.Ю.
 *     Дата создания:             08.06.2007
 *
 ************************************************************/
 
 var $global = {
    ShowText:"Подробнее",
    HideText:"Скрыть",
    Mouse:{
        X:"0",
        Y:"0"
    },
    GetConst:{
        Up:"up",
        First:"first",
        Last:"last"
    },
    GetKeyCode:function(e)
    {
		var e = e ? e : window.event;
		var code = e.keyCode ? e.keyCode : e.which;
		return code;
    },
    CurrentMenu:null,
    SwapClasses:function(class1, class2, obj) // Переключить классы у объекта (1 -> 2, 2 -> 1)
    {
        if(obj)
        {
            obj.className = obj.className == class1 ? class2 : class1;
        }
    },
    SwapAttributeValues:function(value1, value2, obj, attr) // Переключить значения атрибутов ???
    {
        if(obj)
        {
            var attribute = obj.getAttributeNode(attr);
            if(attribute)
				attribute.value = attribute.value == value1 ? value2 : value1;
        }
    },
    SwapText:function(obj, Text1, Text2) // Переключить текст
    {
        if(obj)
        {
            var tmp = this.GetText(obj);
            this.SetText(obj, (tmp == Text1 ? Text2 : Text1));
        }
    },
    SwapVisibility:function(obj) // Переключить выдимость элемента
    {
        this.Display.Swap(obj, "none", "block");
    },
    Cookie:
    {
		Set:function(name, value, days, path, domain, secure) // установить заничение Cookie 
		{
			var expire = new Date();
			if(days)
				expire.setTime(expire.getTime() + (days*24*60*60*1000));
			document.cookie = name + "=" + escape(value) +
					((days) ? "; expires=" + expire.toGMTString() : "") +
					((path) ? "; path=" + path : "") +
					((domain) ? "; domain=" + domain : "") +
					((secure) ? "; secure" : "");
		},
		Get:function(name) // получить значение Cookie по имени
		{
			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);
		}
    },
    Display:{
        Swap:function(obj, value1, value2) // Переключить значение стиля display
        {
            if(obj)
            {
                obj.style.display = obj.style.display == value1 ? value2 : value1;
            }
        },
        Clear:function(obj)	// очистить значение стиля display
        {
            if(obj)
            {
                obj.style.display = "";
            }
        },
        Block:function(obj)	// установить значение display в block
        {
            if(obj)
            {
                obj.style.display = "block";
            }
        },
        Inline:function(obj) // установить значение display в inline
        {
            if(obj)
            {
                obj.style.display = "inline";
            }
        },
        Hide:function(obj)	// установить значение display в none
        {
            if(obj)
            {
                obj.style.display = "none";
            }
        }
    },
    GetParent:function(obj, depth) // получит родительский нод вверх на depth элементов
    {
        var res = null;
        if(obj)
        {        
            res = obj;
            var i = 1;
            while(depth >= i)
            {
                res = res.parentNode != null ? res.parentNode : res;
                i++;
            }
        }
        return res;
    },
    GetText:function(obj) //???
    {
        var result = "";
        if(obj)
            result = (obj.innerText) ? obj.innerText : ((obj.textContent) ? obj.textContent : "");
        return result;
    },
    SetText:function(obj, text)	// Безполезно, Использовать: obj.innerHTML = text; ???
    {
        if(obj)
        {
            if(obj.firstChild)
            {
                obj.removeChild(obj.firstChild);
            }
            
            obj.appendChild(document.createTextNode(text));
        }
    },
    SetError:function(obj)   // частная задача для проекта Tezey - ??? 
    {
        if(obj)
            obj.className = "Error";
    },
    ClearError:function(obj)   // частная задача для проекта Tezey - ??? 
    {
        if(obj)
            obj.className = "";
    },
    StepToNumber:function(str) // преобразует строку вида xkym к виду x000y000000
    {
        var res = str;
        while(res.indexOf("k") != -1)
        {
           res = res.replace("k", "000");
        }
        while(res.indexOf("m") != -1)
        {
           res = res.replace("m", "000000");
        }
        return res;
    },
    NormalizeToNumber:function(obj)	// частная задача для проекта Tezey - ???
    {
        if(obj)
        {
            obj.value = Validator.NormalizeToNumber(obj.value);
            $global.ClearError(obj);
        }
    },    
    NormalizeToUpper:function(obj, border)  // частная задача для проекта Tezey - ???
    {
        if(obj)
        {
            obj.value = Validator.NormalizeToUpper(obj.value, border);
            $global.ClearError(obj);
        }
    },
    NormalizeToBottom:function(obj, border)  // частная задача для проекта Tezey - ???
    {
        if(obj)
        {
            obj.value = Validator.NormalizeToBottom(obj.value, border);
            $global.ClearError(obj);
        }
    },
    NormalizeByInterval:function(obj, up, down)  // частная задача для проекта Tezey - ???
    {
        if(obj)
        {
            obj.value = Validator.NormalizeByInterval(obj.value, up, down);
            $global.ClearError(obj);
        }
    },
    FindPosition:function(obj) 
    {
	    var curleft = curtop = 0;
	    if (obj.offsetParent) {
		    curleft = obj.offsetLeft
		    curtop = obj.offsetTop
		    while (obj = obj.offsetParent) {
			    curleft += obj.offsetLeft
			    curtop += obj.offsetTop
		    }
	    }
	    return [curleft,curtop];
    },
    /* Следующий блок заменить на что-нибудь типа:
     Align.AtCursor(), Align.ScreenCenter(), Align.Under(), Align.On(), Align.LeftOf(), Align.RightOf() */
    ShowAtPosition:function(obj)
    {
        if(obj)
        {
            obj.style.position = "absolute";
            obj.style.display = "block";
            obj.style.top = "0px";
            obj.style.left = "0px";
            var pos = $global.FindPosition(obj);
            obj.style.top = Number($global.Mouse.Y-pos[1])+"px";
            obj.style.left = Number($global.Mouse.X-pos[0])+"px";
        }
    },
    ShowInPageCenterByBounds:function(obj, w, h)
    {
        if(obj)
	    {
	        obj.style.position = "absolute";
		    var _deltaX = (w/2);
		    var _deltaY = (h/2);
		    var _centerW = (this.Window.Width()/2)+$global.Window.Scroll.Left();
		    var _centerH = (this.Window.Height()/2)+$global.Window.Scroll.Top();
		    obj.style.top = ((_centerH-_deltaY )> 0) ? (Math.floor(_centerH-_deltaY )+"px") : "0px";
		    obj.style.left = ((_centerW-_deltaX )> 0) ? (Math.floor(_centerW-_deltaX )+"px") : "0px";
		    this.Display.Block(obj);		
	    }
    },
    ShowInPageCenter:function(obj)
    {
        if(obj)
	    {
			var w = obj.offsetWidth;
			var h = obj.offsetHeight;
			w = w == 0 ? this.GetStyle(obj, "width", true) : w;
			h = h == 0 ? this.GetStyle(obj, "height", true) : h;
			w += this.GetStyle(obj, "borderLeftWidth", true) + this.GetStyle(obj, "borderRightWidth", true);
			h += this.GetStyle(obj, "borderTopWidth", true) + this.GetStyle(obj, "borderBottomWidth", true);
			this.ShowInPageCenterByBounds(obj, w, h);
	    }
    },
    ShowUnderObject:function(obj, target)
    {
        if(obj && target)
        {
            obj.style.top = "0px";
            obj.style.left = "0px";                
            var oldPos = $global.FindPosition(obj);
            var h = target.offsetHeight;
            var position = $global.FindPosition(target);
            obj.style.position = "absolute";
            obj.style.top = Number(position[1]+h+oldPos[1])+"px";
            obj.style.left = Number(position[0]+oldPos[0])+"px";
            obj.style.display = "block";
        }
    },
    /* --- конец блока --- */
    TrackMousePosition: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;
	    }
	    $global.Mouse.X = posx;
	    $global.Mouse.Y = posy;
	},
	InitEvents:function(e)
	{
	    document.onmousemove = $global.TrackMousePosition;	    
	},
	SwitchToggleGroupByClass:function(obj, class1, class2, formal) // Частная задача для Tezey - ?
	{
	    if(obj)
	    {
	        var objs = obj.parentNode.getElementsByTagName("div");
	        for(var i = 0;i<objs.length;i++)
	            if(objs[i] != obj)
	                if(objs[i].className.indexOf(formal) != -1)
	                    objs[i].className = class1[i];	               
	        obj.className = class2;
	    }
	},
	SwitchDivGroupClass:function(obj, toggleClass) // Частная задача для Tezey - ?
	{
	    if(obj)
	    {
	        var divGroup = obj.parentNode.getElementsByTagName("div");
	        for(var i = 0; i < divGroup.length; i++)
	            if(divGroup[i] != obj)
	                if(divGroup[i].getAttribute('defaultClass') != null)
	                    divGroup[i].className = divGroup[i].getAttribute('defaultClass');	               
	        obj.className = toggleClass;
	    }
	},
	Next:function(obj, num)
	{
	    var result = null;
	    if(obj)
	    {
	        if(num == null)
	        {
	            result = obj.nextSibling;
	            if(result != null)	            
	                if(result.nodeType == 3)
	                    result = this.Next(result);
	        }
	        else
	        {
	            result = this.Next(obj);
	            for(var i=1;i<num;i++)
	                result = this.Next(result);
	        }
	    }
	    return result;
	},
	Previous:function(obj, num)
	{
	    var result = null;
	    if(obj)
	    {
	        if(num == null)
	        {
	            result = obj.previousSibling;
	            if(result != null)	            
	                if(result.nodeType == 3)
	                    result = this.Previous(result);
	         }
	         else
	         {
	            result = this.Previous(obj);
	            for(var i=1;i<num;i++)
	                result = this.Previous(result);
	         }
	    }
	    return result;
	},
	GetAttribute:function(obj, attr)
	{
	    var result = "";
	    if(obj)
	    {
	        var a = obj.getAttribute(attr);
	        a = a ? a : obj[attr];
	        result = this.isString(a) ? a : "";
	    }
	    return result;
	},
	ValueInArray:function(array, value)
	{
	    var result = false;
	    if(array)
	    {
	        if(value)
	        {
	            for(var i=0;i<array.length;i++)
	            {
	                result = result || (array[i] == value);
	            }
	        }
	    }
	    return result;
	},
	NormCssStr:function(cssPropStr) // Приводит строку к виду для JS, например  margin-left > marginLeft
    {
        var i, c, a = cssPropStr.split('-');
        var s = a[0];
        for (i=1; i<a.length; ++i) 
        {
            c = a[i].charAt(0);
            s += a[i].replace(c, c.toUpperCase());
        }
        return s;
    },
    ShrinkStr:function(str, chars, last, empty)
    {
		return str.length > chars ? str.substring(0, chars) + last : str.length == 0 ? empty : str;
    },
	GetStyle:function(obj, css, i) // Получает значение стиля, если если i == true возвращает int
	{
        var s, v = 'undefined', dv = document.defaultView;
        if(dv && dv.getComputedStyle)
        {            
            s = dv.getComputedStyle(obj,'');
            if (s) v = s.getPropertyValue(css);
        }
        else if(obj.currentStyle) 
            v = obj.currentStyle[this.NormCssStr(css)];
        else return null;
        return i ? (parseInt(v) || 0) : v;
	},
	SetStyle:function(sProp, sVal) // Устанавливает значение стиля для нескольких объектов (через запятую после sVal)
    {
        var i, e;
        for (i = 2; i < arguments.length; ++i) 
        {
            e = arguments[i];
            if (e.style) 
            {
                try { e.style[sProp] = sVal; }
                catch (err) { e.style[sProp] = ''; } // ???
            }
        }
    },
    isString:function(value) // Проверяет, является ли переменная строкой ??
    {
        return typeof(value) == 'string';
    },
    HTML:
    {
        Encode:function(str)
        {
            return str.replace("<", "&lt;").replace(">", "&gt;");
        },
        Decode:function(str)
        {
            return str.replace("&lt;", "<").replace("&gt;", ">");
        },
        GetDomain:function(str)
        {
			var domain = str ? str.replace("http://", "") : "";
			domain = domain.replace("www.", "");
			return domain.indexOf("/") != -1 ? domain.substring(0, domain.indexOf("/")) : domain;
        },
        Unicode:function(lit)
        {
			var el = $global.Tag("div", null, null, lit);
			return el.innerHTML;
        }
    },
    SetOpacity:function(obj, val) // Устанавливает значение непрозрачности для разных браузеров
    {
		this.Opacity.Set(obj, val);                
    },
    ClearOpacity:function(obj)
    {
		this.Opacity.Clear(obj);
    },
    Opacity:
    {
		Set:function(obj, val)
		{
			if(obj)
			{
				if ($global.isString(obj.style.opacity)) 
					obj.style.opacity = val + '';
				else if ($global.isString(obj.style.filter)) 
					obj.style.filter = 'alpha(opacity=' + (100 * val) + ')';
				else if ($global.isString(obj.style.MozOpacity)) 
					obj.style.MozOpacity = val + '';
				else if ($global.isString(obj.style.KhtmlOpacity)) 
					obj.style.KhtmlOpacity = val + '';
			}
		},
		Clear:function(obj)
		{
			if(obj)
			{
				if ($global.isString(obj.style.opacity)) 
					obj.style.opacity = '';
				else if ($global.isString(obj.style.filter)) 
					obj.style.filter = '';
				else if ($global.isString(obj.style.MozOpacity)) 
					obj.style.MozOpacity = '';
				else if ($global.isString(obj.style.KhtmlOpacity)) 
					obj.style.KhtmlOpacity = '';
			}	
		}
    },
	GetElementsByAttribute:function(attribute, value)
	{
	    //TODO: Поиск элементов по значению атрибута
	},
	GetClear:function()
	{
	    var clear = document.createElement("div");
	    clear.className = "clear";
	    return clear;
	},
	Window:
	{
	    Size:function(axis)
        {
            var x,y;	
            if (self.innerHeight) 
            {
                 x = self.innerWidth;	    
                 y = self.innerHeight;	
            } 
            else if (document.documentElement && document.documentElement.clientHeight)
            {	
                 x = document.documentElement.clientWidth;	    
                 y = document.documentElement.clientHeight;	
            } 
            else if (document.body) 
            {
                 x = document.body.clientWidth;	    
                 y = document.body.clientHeight;	
            }
            return (axis == "x") ? x : (axis == "y") ? y : 0;
        },
	    Width:function()
	    {
	        return Validator.NormalizeToNumber(this.Size("x"));
	    },
	    Height:function()
	    {
	        return Validator.NormalizeToNumber(this.Size("y"));
	    },
	    Scroll:
	    {
			Left:function()
			{
				if(document.documentElement)
					return document.documentElement.scrollLeft;
				else
					return document.body.scrollLeft;
			},
			Top:function()
			{
				if(document.documentElement)
					return document.documentElement.scrollTop;
				else
					return document.body.scrollTop;
			}
	    }
	},
	ToolTip:
	{
	    Tip:null,
	    AlignType:
	    {
	        Center:"0",
	        Cursor:"1"
	    },
	    Align:"1",
	    Center:function()
	    {
	        this.Align = this.AlignType.Center;
	        return $global.ToolTip;
	    },
	    Cursor:function()
	    {
	        this.Align = this.AlignType.Cursor;
	        return $global.ToolTip;
	    },
	    Create:function()
	    {
	        if(this.Tip == null)
	        {
	            var items = $global.GetElementsByClass(document.body, "Global_ToolTip");
	            if(items.length == 0)
	            {
	                this.Tip = document.createElement("div");
	                this.Tip.className = "Global_ToolTip";
	                document.body.appendChild(this.Tip);
	                this.Tip.onclick = this.Close;
	            }
	            else
	                this.Tip = items[0];
	       }
	       return this.Tip;
	    },
	    Text:function(text, width)
	    {
	        var tip = this.Create();
	        if(tip)
	        {
	            tip.innerHTML = text;
	            if(width)
	            {
	                tip.style.width = width;
	            }
	            if(this.Align == this.AlignType.Cursor)
	                $global.ShowAtPosition(tip);
	            else if(this.Align == this.AlignType.Center)
	                $global.ShowInPageCenter(tip);
	        }
	    },
	    Object:function(obj, width)
	    {
	        var tip = this.Create();
	        if(tip)
	        {
	            tip.innerHTML = "";
	            if(obj)
	            {
	                tip.appendChild(obj);
	                if(width)
	                {
	                    tip.style.width = width;
	                }
	                if(this.Align == this.AlignType.Cursor)
	                    $global.ShowAtPosition(tip);
	                else if(this.Align == this.AlignType.Center)
	                    $global.ShowInPageCenter(tip);
	            }
	        }
	    },
	    Close:function()
	    {
	        var items = $global.GetElementsByClass(document.body, "Global_ToolTip");
	        if(items.length > 0)
	        {
	            items[0].style.width = "auto";
	            $global.Display.Hide(items[0]);
	        }
	    }
	},
	Number:
	{
		is2N:function(value)
		{
			return value/2 == Math.round(value/2);
		}
	},
	Tag:function(tag, css, id, inner)
	{
		var element = document.createElement(tag);
		if(element)
		{
			if(css)
				element.className = css;
			if(id)
				element.id = id;
			if(inner)
				element.innerHTML = inner;
		}
		return element;
	},
	Get:
	{
		ById:function(id)
		{
			return document.getElementById(id);
		},
		ByTag:function(obj, tag)
		{
			return $global.GetElementsByTagName(obj, tag);
		},
		ByClass:function(obj, css)
		{
			return $global.GetElementsByClass(obj, css);
		}
	},
	GetElementsByTagName:function(obj, tag)
	{
	    var result = new Array();
	    if(obj)
	        if(tag)
	        {
	            var tmp = this.RemoveEmptyNodes(obj.childNodes);
	            if(tmp != null)
	                for(var i = 0;i<tmp.length;i++)
						if(tmp[i].tagName != null)
							if(tmp[i].tagName.toLowerCase() == tag)
								result.push(tmp[i]);
	        }
	    return result;
	},
	RemoveEmptyNodes:function(array)
	{
	    var tmp = new Array();
	        for(var i=0;i<array.length;i++)
	            if(array[i].nodeType != 3)
	                tmp.push(array[i]);
	    return tmp;
	},
	GetElementByTagName:function(obj, tag, index)
	{
	    var result = null;
	    var array = $global.GetElementsByTagName(obj, tag);
	    if(array.length > 0)
	    {
	        var tmp = this.RemoveEmptyNodes(array);
	        if(index != null)
	        {
	            var ind = index == $global.GetConst.First ? 0 : index == $global.GetConst.Last ? (tmp.length-1) : Number(index);
	            if(ind < tmp.length)
	            {
	                result = tmp[ind];
	            } else { result = tmp[0]; }
	        } else { result = tmp[0]; }
	    }
	    return result;
	},
	GetElementsByClass:function(obj, className)
	{
	    var result = new Array();
	    if(obj)
	    {
	        if(obj.childNodes != null)
	        {
	            for(var i = 0;i<obj.childNodes.length;i++)
	            {
	                if(obj.childNodes[i] != null)	                
	                    if(obj.childNodes[i].className != null)
	                        if(obj.childNodes[i].className == className)
	                            result.push(obj.childNodes[i]);
	            }
	        }
	    }
	    return result;
	},
	GET:function(obj, path) // Получает элемент по строке вида "<param>:<value>,<param>:<value>" например "up:3,div:0"
	{
	    var result = obj;
	    var str = new String();
	    str = path;
	    if(obj)
	    {
	        var strArray = str.split(',');
	        for(var i = 0;i<strArray.length;i++)
	        {
	            var pair = strArray[i].split(':');
	            if(pair[0] == $global.GetConst.Up)
	                result = $global.GetParent(result, Number(pair[1]));
	            else
	                result = $global.GetElementByTagName(result, pair[0], pair[1]);
	        }
	    }
	    return result;
	}
 }
 var $G = $global;//Алиас для $global
 var _old = window.onload;
 window.onload = function(){ if(_old)_old(); $global.InitEvents(); };