if (!window.Siteim)
	Siteim = {};
	
Siteim.W = {
	
	domain:'http://siteim.ru',key:'NnliamtrbHQ0MTAxMDY2Mzk2MDA1NDQzMTQxM3Ria29pOHQ',supportOnline:false,createOwnButton:true,
	
	engine: '',
	version: 0,
	
	invited: false,
	prefix: '',
	hidden: false,
	
	start: function(){
		Siteim.W.hidden = "true" == Siteim.W.getCookie("siteim-hidden");
		if (Siteim.W.createOwnButton) {
			Siteim.W.prefix = Math.round(Math.random()*10000);
			Siteim.W.createButton();
		}
		else
			Siteim.W.hideSuggestion(true);
		Siteim.W.attachToButton();
		Siteim.W.clientId = Siteim.W.getCookie("siteim-id");
		Siteim.W.clientKey = Siteim.W.getCookie("siteim-key");
		Siteim.W.sendRequest();
		window.setInterval(Siteim.W.sendRequest, 3000);
	},
	
	sendRequest: function(){
		var r = Math.random();
		var x = document.createElement("script");
		x.id = "siteim-scr-" + r;
		x.src = Siteim.W.domain + '/ext.js/?mode=upd&s=' + Siteim.W.key + "&id=" + Siteim.W.clientId + "&key=" + Siteim.W.clientKey + "&sid="+r + "&i=" + Siteim.W.invited;
		document.body.appendChild(x);
	},
	
	scriptLoaded: function(id){
		var x = document.getElementById("siteim-scr-" + id);
		x.parentNode.removeChild(x);
	},
	
	setClient: function(id, key){
		var expires = Siteim.W.getExpireDate(1024, 0, 0);
		Siteim.W.clientId = id;
		Siteim.W.clientKey = key;
		Siteim.W.setCookie("siteim-id", id, expires, '/');
		Siteim.W.setCookie("siteim-key", key, expires, '/');
	},
	
	showSuggestion: function(uid, dialogId, text){
		if (Siteim.W.hidden)
			Siteim.W.manipulateButton("", "auto", "»", Siteim.W.hideButton, "false", 190, 1);
		Siteim.W.dialogId = dialogId;
		Siteim.W.supportOnline = true;
		if (!Siteim.W.invited) {
			if (Siteim.W.createOwnButton) {
				var x = document.getElementById("siteim-button" + Siteim.W.prefix);
				var n = x.firstChild;
				n.innerHTML = '<img src="' + Siteim.W.domain + '/user_avatar/?user_id=' + uid + '" style="margin: 10px 0px 0 10px;"/>' +
					'<div style="width: 60px; display: inline-block; margin: 0px 10px; vertical-align: top; line-height: 20px; right: 0px; position: absolute; top:0;">' +
					text +
					'<br/>' +
					'<input type="button" id="siteim-button-ok' +
					Siteim.W.prefix +
					'" value="Ответить"/>' +
					'<input type="button" id="siteim-button-cancel' +
					Siteim.W.prefix +
					'" value="Закрыть"/>' +
					"</div>";
				Siteim.W.removeEvent(x, 'click', Siteim.W.openDialog);
				
				n.style.background = "#e3f1fa";
				n.style.textAlign = 'left';
				
				Siteim.W.animate(n, {
					'backgroundColor': {
						value: '#ffc785',
						handler: null
					},
					width: {
						value: x.clientWidth + 10 * 10,
						handler: function(w){
							x.style.width = w + 'px';
							x.firstChild.style.width = (w - 2) + 'px';
							var txt = x.firstChild.lastChild;
							txt.style.width = (w - 88) + 'px';
							x.childNodes[2].style.width = x.childNodes[1].style.width = (w - 4) + 'px';
						}
					}
				}, 10, 100, function(){
					var h = n.lastChild.clientHeight + 5;
					if (h > 60) {
						Siteim.W.animate(x, {
							height: {
								value: h,
								handler: function(nh){
									x.style.height = nh + 'px';
									x.firstChild.style.height = (nh - 2) + 'px';
									x.childNodes[3].style.height = (nh - 8) + 'px';
								}
							}
						}, 5, 100, Siteim.W.bindSuggestion);
					}
					else 
						Siteim.W.bindSuggestion();
				});
			}
			else {
				Siteim.W.bindSuggestion();
				var t = document.getElementById("siteim-button-text" + Siteim.W.prefix);
				if (t) {
					t.innerHTML = text;
					t.style.display = '';
				}
				var on = document.getElementById("siteim-button-online" + Siteim.W.prefix);
				var off = document.getElementById("siteim-button-offline" + Siteim.W.prefix);
				on.style.display = 'none';
				off.style.display = 'none';
			}
			Siteim.W.invited = true;
		}
	},
	
	bindSuggestion: function(){
		var ok = document.getElementById("siteim-button-ok" + Siteim.W.prefix);
		var c = document.getElementById("siteim-button-cancel" + Siteim.W.prefix);
		if (ok){
			ok.style.display = '';
			window.setTimeout(function(){
				Siteim.W.addEvent(ok, 'click', function(){
					Siteim.W.openDialog();
					Siteim.W.hideSuggestion(true);
				})
			}, 0);
		}
		if (c) {
			c.style.display = '';
			window.setTimeout(function(){
				Siteim.W.addEvent(c, 'click', Siteim.W.hideSuggestion);
			}, 0);
		}
	},
	
	hideSuggestion: function(noRequest){
		if (Siteim.W.createOwnButton) {
			var x = document.getElementById("siteim-button" + Siteim.W.prefix);
			var n = x.firstChild;
			n.style.backgroundColor = "#ffc785";
			n.style.textAlign = 'right';
			n.innerHTML = Siteim.W._getInnerHtml(Siteim.W.supportOnline);
			var hid = Siteim.W.hidden;
			Siteim.W.png(n.firstChild, 'image');
			window.setTimeout(function(){
				Siteim.W.addEvent(x, 'click', Siteim.W.openDialog);
			}, 0);
			Siteim.W.animate(n, {
				'backgroundColor': {
					value: '#e3f1fa',
					handler: null
				},
				width: {
					value: (hid ? 20 : 190),
					handler: function(w){
						x.style.width = w + 'px';
						x.firstChild.style.width = (w - 2) + 'px';
						x.childNodes[2].style.width = x.childNodes[1].style.width = (w - 4) + 'px';
					}
				},
				height: {
					value: 60,
					handler: function(nh){
						x.style.height = nh + 'px';
						x.firstChild.style.height = (nh - 2) + 'px';
						x.childNodes[3].style.height = (nh - 8) + 'px';
					}
				}
			}, 10, 100);
		}
		else {
			var t = document.getElementById("siteim-button-text" + Siteim.W.prefix);
			var ok = document.getElementById("siteim-button-ok" + Siteim.W.prefix);
			var c = document.getElementById("siteim-button-cancel" + Siteim.W.prefix);
			var on = document.getElementById("siteim-button-online" + Siteim.W.prefix);
			var off = document.getElementById("siteim-button-offline" + Siteim.W.prefix);
			if (on)
				on.style.display = Siteim.W.supportOnline ? '' : "none";
			if (off)
				off.style.display = Siteim.W.supportOnline ? 'none' : "";
			if (t) 
				t.style.display = 'none';
			if (ok) 
				ok.style.display = 'none';
			if (c) 
				c.style.display = 'none';
		}
		if (noRequest != true){
			var r = Math.random();
			var xx = document.createElement("script");
			xx.id = "siteim-scr-" + r;
			xx.src = Siteim.W.domain + '/ext.js/?mode=rm&s=' + Siteim.W.key + "&id=" + Siteim.W.clientId + "&key=" + Siteim.W.clientKey + "&sid="+r + "&d=" + Siteim.W.dialogId;
			document.body.appendChild(xx);
		}
	},
	
	animate: function(node, properties, steps, timeDelta, onFinish){
		var p = {};
		for (var n in properties){
			if (n == 'backgroundColor'){
				var v = properties[n].value;
				v = [parseInt('0x' + v.substring(1, 3)), parseInt('0x' + v.substring(3, 5)), parseInt('0x' + v.substring(5, 7))];
				var o = node.style.backgroundColor;
				if (o.indexOf('#') == 0)
					o = [parseInt('0x' + o.substring(1, 3)), parseInt('0x' + o.substring(3, 5)), parseInt('0x' + o.substring(5, 7))];
				else{
					var t0 = o.indexOf('(');
					var t1 = o.indexOf(',');
					var t2 = o.lastIndexOf(',');
					var t3 = o.indexOf(')');
					o = [parseInt(o.substring(t0+1, t1)), parseInt(Siteim.W.trim(o.substring(t1+1, t2))), parseInt(Siteim.W.trim(o.substring(t2+1, t3)))];
				}
				p[n] = { start: o, end: v, handler: properties[n].handler };
			}
			else if (n == 'height')
				p[n] = {end: properties[n].value, start: node.clientHeight, handler: properties[n].handler};
			else if (n == 'width')
				p[n] = {end: properties[n].value, start: node.clientWidth, handler: properties[n].handler};
		}
		var i=1;
		var x = function(){
			if (i == steps){
				for (var n in properties){
					var c = properties[n].value;
					if (n == 'backgroundColor')
						node.style[n] = c;
					else
						node.style[n] = c + 'px';
					if (p[n].handler)
						p[n].handler(c);
					if (onFinish)
						onFinish();
				}
			}
			else{
				for (var n in p){
					var e = p[n].end;
					var s = p[n].start;
					var c;
					if (n == 'backgroundColor') {
						c = [Math.round(s[0] + (e[0] - s[0]) * i / steps), Math.round(s[1] + (e[1] - s[1]) * i / steps), Math.round(s[2] + (e[2] - s[2]) * i / steps)];
						node.style.backgroundColor = '#' + c[0].toString(16) + c[1].toString(16) + c[2].toString(16);
					}
					else
						node.style[n] = (c = (s + (e - s) * i / steps)) + 'px';
					if (p[n].handler)
						p[n].handler(c);
				}
				i++;
				window.setTimeout(x, timeDelta);
			}
		}
		x();
	},
	
	
	attachToButton: function(){
		var z = function(i){
			var b = document.getElementById(i + Siteim.W.prefix);
			if (b)
				Siteim.W.addEvent(b, 'click', Siteim.W.openDialog);
		};
		z('siteim-button');
		z('siteim-button-online');
		z('siteim-button-offline');
	},
	
	openDialog: function(e){
		if (!e)
			e = window.event;
		if (e){
			var x = e.target ? e.target : e.srcElement;
			if (x){
				var b = document.getElementById("siteim-button" + Siteim.W.prefix);
				if (b && b.childNodes.length > 1){
					b = b.childNodes[0];
					if (b && b.childNodes.length > 2){
						b = b.childNodes[2];
						if (b){
							for (; x; x = x.parentNode){
								if (x == b)
									return;
							}
						}
					}
				}
			}
		}
		var url = Siteim.W.domain + '/external/?s=' + Siteim.W.key;
		if (Siteim.W.dialogId)
			url += "&did=" + Siteim.W.dialogId;
		window.open(url, 'siteimmessenger',
			'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=0,height=400,width=650');
	},
	
	addEvent: function(object, event, handler, capture){
	    if(Siteim.W.engine == 'ie')
	        object.attachEvent(event.indexOf('on') == 0 ? event : 'on' + event, handler);
	    else
	        object.addEventListener((event.indexOf('on') == 0) ? (event.replace('on','')) : (event), handler, capture);
	},
	
	removeEvent: function(object, event, handler, capture){
	    if(Siteim.W.engine == 'ie')
	        object.detachEvent(event.indexOf('on') == 0 ? event : 'on' + event, handler);
	    else
	        object.removeEventListener((event.indexOf('on') == 0) ? (event.replace('on','')) : (event),handler,capture);
	},
	
	manipulateButton: function(chldDisplay, mLeft, mText, nextF, cookie, totalWidth, animateSteps){
		var x = document.getElementById("siteim-button" + Siteim.W.prefix);
		x.childNodes[0].childNodes[0].style.display = chldDisplay;
		x.childNodes[0].childNodes[1].style.display = chldDisplay == '' ? 'inline-block' : 'none';
		var n = x.childNodes[0].childNodes[2];
		n.style.left = mLeft;
		n.innerHTML = mText;
		window.setTimeout(function(){
			n.onclick = nextF;
		}, 1);
		Siteim.W.setCookie("siteim-hidden", cookie, Siteim.W.getExpireDate(1, 0, 0), '/');
		Siteim.W.hidden = true;
		Siteim.W.animate(x, {
				width: {
					value: totalWidth,
					handler: function(w){
						x.style.width = w + 'px';
						x.firstChild.style.width = (w - 2) + 'px';
						var txt = x.firstChild.lastChild;
						txt.style.width = 20 + 'px';
						x.childNodes[2].style.width = x.childNodes[1].style.width = (w - 4) + 'px';
					}
				}
			}, animateSteps, 100
		);
	},
	
	hideButton: function(){
		Siteim.W.manipulateButton("none", "-5px", "«", Siteim.W.showButton, "true", 20, 10);
	},
	
	showButton: function(){
		Siteim.W.manipulateButton("", "auto", "»", Siteim.W.hideButton, "false", 190, 10);
	},
	
	createButton: function(){
		var div = document.createElement("div");
		var fixIe6;
		if (Siteim.W.engine == 'ie' && Siteim.W.version <= 6){
			div.style.position = "absolute";
			
			fixIe6 = function(){
				div.style.top = (document.body.parentNode.clientHeight + document.documentElement.scrollTop - 100 - div.clientHeight) + 'px';
			}
		}
		else {
			div.style.position = "fixed";
			div.style.opacity = "0.9";
		}
		
		var width = 190;
		div.style.height = "60px";
		if (Siteim.W.hidden)
			div.style.width = "20px";
		else
			div.style.width = width + "px";
		div.style.bottom = "100px";
		div.style.right = "0px";
		div.style.cursor = 'pointer';
		div.id = 'siteim-button' + Siteim.W.prefix;
		div.style.backgroundColor = 'none';
		div.style.zIndex = 100;
		var hid = Siteim.W.hidden;
		var background;
		if (Siteim.W.supportOnline)
			background = '#e3f1fa';
		else
			background = '#fafab3';
		div.innerHTML =
			'<div style="position: relative; overflow: hidden; background-color: ' + background + '; height: 58px; line-height: 58px; ' +
					'vertical-align: middle; width: ' +
					(hid ? "18" : (width-2)) + 'px; ' +
					'position: absolute; top: 1px; left: 1px; color: #03426A; font-family: Arial,sans-serif; font-size: 16px; ' +
					'font-style: normal; font-weight: 400; text-align: right;">' +
					Siteim.W._getInnerHtml(Siteim.W.supportOnline) +
			'</div>' +
			'<div style="overflow: hidden; position: absolute; background: #AED0EA; height: 1px; left: 4px; width: ' +
					(hid ? "16" : (width-4)) + 'px; position: absolute; top: 0px;"></div>' +
			'<div style="overflow: hidden; position: absolute; background: #AED0EA; height: 1px; left: 4px; width: ' +
					(hid ? "16" : (width-4)) + 'px; position: absolute; bottom: 0px;"></div>' +
			'<div style="overflow: hidden; position: absolute; background: #AED0EA; top: 4px; height: 52px; width: 1px; left: 0px; position: absolute; "></div>' +
			'<div style="overflow: hidden; position: absolute; width: 4px; height: 4px; top: 0px; left: 0px; overflow: hidden;">' +
				'<div style="position: absolute; height: 8px; width: 8px; top: 0px; left: 0px; background: url(' + Siteim.W.domain + '/img/round_corner_blue.png);"></div>' +
			'</div>' +
			'<div style="position: absolute; width: 4px; height: 4px; bottom: 0px; left: 0px; overflow: hidden;">' +
				'<div style="position: absolute; height: 8px; width: 8px; top: -4px; left: 0px; background: url(' + Siteim.W.domain + '/img/round_corner_blue.png);"></div>' +
			'</div>';
		document.body.appendChild(div);
		if (Siteim.W.engine == 'ie' && Siteim.W.version <= 6) {
			Siteim.W.png(div.childNodes[0].firstChild, 'image');
			Siteim.W.png(div.childNodes[4].firstChild, 'image');
			Siteim.W.png(div.childNodes[4].firstChild, 'image');
			var r = window.onresize;
			var s = window.onscroll;
			window.onresize = function(){
				if (r)
					r();
				fixIe6();
			};
			window.onscroll = function(){
				if (s)
					s();
				fixIe6();
			};
		}
	},
	
	_getInnerHtml: function(online){
		var suggestionText;
		var arrow;
		var hid = Siteim.W.hidden;
		if (online){
			suggestionText = '<span style="white-space: nowrap; font-weight: bold;">Задать вопрос</span><br/><span style="white-space: nowrap;">Поддержка online</span>';
			arrow = "blue";
		}
		else{
			suggestionText = '<span style="white-space: nowrap; font-weight: bold;">Задать вопрос</span><br/><span style="white-space: nowrap;">Поддержка offline</span>';
			arrow = "green";
		}
		return '<div style="position: absolute; height: 46px; width: 46px; top: 6px; left: 0px; ' +
				'background: url(' + Siteim.W.domain + '/img/arrow_top_32_' + arrow + '.png) no-repeat center left; z-index: 0;' +
				(hid ? " display: none" : "") + '" ' +
				'title="При нажатии откроется окно диалога" alt="При нажатии откроется окно диалога">' +
			'</div>' +
			'<div style="z-index: 1; margin-top: 9px; display: inline-block; line-height: 20px; height: auto; ' +
				'width: 140px; margin-right: 20px; ' +
				(hid ? " display: none" : "") + '" title="При нажатии откроется окно диалога" ' +
				'alt="При нажатии откроется окно диалога">' + suggestionText + '&#160;</div>' +
			'<div style="z-index: 2; margin-top: 0px; display: inline-block; line-height: 56px; height: 100%; ' +
				'width: 20px; position: absolute; right: 0px; color: #1E77B1; top: 0px; font-size: 20px;' +
				(hid ? "left: -5px;" : "") + '" ' +
				(hid ? ' title="Развернуть" alt="Развернуть"' : '"title="Скрыть" alt="Скрыть"') +
				(hid ? ' onclick="Siteim.W.showButton(); return false;">' : ' onclick="Siteim.W.hideButton(); return false;">') +
				(hid ? "«" : "»") + '</div>';
	},
	
	_getEngine: function(){
		var th = Siteim.W;
    	if (th.engine != '')
        	return th.engine;
	    if ((th.engine == '') && (navigator.userAgent.indexOf('Opera') !=- 1)){
	        th.engine = 'opera';
	        var i = navigator.userAgent.indexOf("Version");
	        if (i < 0)
	        	i = navigator.userAgent.indexOf('Opera')+6;
	        else
	        	i += 8;
	        th.version = parseFloat(navigator.userAgent.substr(i));
	    }
	    if ((th.engine == '') && (navigator.userAgent.indexOf('MSIE') != -1)){
	        th.engine = 'ie';
	        th.version = parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf('MSIE')+5));
	    }
	    if ((th.engine == '') && (navigator.userAgent.indexOf('KHTML') != -1)){
	        th.engine = 'khtml';
	        th.version = parseFloat(navigator.appVersion);
	    }
	    if ((th.engine=='') && (navigator.userAgent.indexOf('Gecko') != -1)){
	        th.engine = 'gecko';
	        th.version = parseFloat(navigator.appVersion);
	    }
	    if (th.engine == '')
	        th.engine = 'other';
	    return th.engine;
	},

	ready: function (f) {
		var ie  = !!(window.attachEvent && !window.opera);
	    var wk  = /webkit\/(\d+)/i.test(navigator.userAgent) && (RegExp.$1 < 525);
	    var fn  = [];
	    var run = function () { for (var i = 0; i < fn.length; i++) fn[i](); };
	    var d   = document;
        if (!ie && !wk && d.addEventListener)
            return d.addEventListener('DOMContentLoaded', f, false);
        if (fn.push(f) > 1) return;
        if (ie)
            (function () {
                var ok = false;
                try { d.documentElement.doScroll('left'); ok = true;}
                catch (err) { setTimeout(arguments.callee, 0); }
                if(ok) run();
            })();
        else if (wk)
            var t = setInterval(function () {
                if (/^(loaded|complete)$/.test(d.readyState))
                    clearInterval(t), run();
            }, 0);
    },
	
	getExpireDate: function(days, hours, minutes) {
	    var expDate = new Date();
	    if (typeof days == "number" && typeof hours == "number" && typeof hours == "number") {
	        expDate.setDate(expDate.getDate() + parseInt(days));
	        expDate.setHours(expDate.getHours() + parseInt(hours));
	        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
	        return expDate.toGMTString();
	    }
	},

	setCookie: function(name, value, expires, path, domain, secure) {
		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);
	},
	
	trim: function(s) {
	    if(!s)
	        return '';
	    return s.replace(/(^\s+)|(^\u00A0+)|(^\u00A0+)|(\s+$)/g, ''); 
	},
	
	png: function(element, resizing_method){
	    // если браузер IE версии 5.5-6
	    if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent)){
	        var src;
	        if(element.tagName=='IMG'){ // если текущий элемент картинка (тэг IMG)
	        	//if (/\.png$/.test(element.src)){ // если файл картинки имеет расширение PNG
	                src = element.src;
	                element.setAttribute('_src', src);
	                element.src= "/img/1.gif"; // заменяем изображение прозрачным gif-ом
	            //}
	        }
	        else{ // иначе, если это не картинка а другой элемент
	        	element.runtimeStyle.backgroundImage="";
	            // если у элемента задана фоновая картинка, то присваеваем значение свойства background-шmage переменной src
	            src=element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
	            if(src){
	                src=src[1]; // берем из значения свойства background-image только адрес картинки
	                element.runtimeStyle.backgroundImage="none"; // убираем фоновое изображение
	            }
	        }
	        // если, src не пуст, то нужно загрузить изображение с помощью фильтра AlphaImageLoader
	        if(src)
	        	element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"',sizingMethod='"+resizing_method+"')";
	        else
	        	element.runtimeStyle.filter = "";
	    }
	    else if (/MSIE.+Win/.test(navigator.userAgent)){
	    	element.runtimeStyle.filter = "";
	    }
	}
};
Siteim.W._getEngine();
Siteim.W.ready(Siteim.W.start);