 /**
* DS
* description: javascript functions libraries
*
* author: Monk
* create: 2.10.2007
* update: 15.08.2008
*/

function ds_goto(elm, x, y)
{
	if(elm)
	{
		elm.style.left = parseInt(x);
		elm.style.top = parseInt(y);
	}
}

function $(id)
{
	var elm = document.getElementById(id);
	if(elm)
		return elm;
}

function ds_hide_element(id, display)
{
	var elm = $(id);
	
	if(display == undefined)
		display = 'block';
	
	if(elm)
	{
		if(elm.style.display == 'none')
			elm.style.display = display;
		else
			elm.style.display = 'none';
			
		return elm.style.display;
	}
	
	return display;
}

function dsEcho(str)
{
	document.write(str + '<br />\n');
}

// получение значение в url строке
// возвращает массив значений
function ds_parseurl(url)
{
	var query = new Array();
	
	var i1 = 0, i2 = 0;
	for(var i = 0; i < url.length; i++)
	{
		i1 = url.indexOf('=', i2);
		if(i1 == -1)
			break;
		i1++;
		i2 = url.indexOf('&', i1);
		if(i2 == -1)
			i2 = url.length;
			
		query.push(url.substring(i1, i2));
	}
	
	return query;
}

// создание clip effect'a - постепенное обрезание/появление области элемента
// только для position:absolute
// id - id element
// starty - мин высота с которой начинается создание
//		max - то будет сверху вниз, от большего значение "y" к меньшему
// step - шаг приращения
// time - время в задержке при эффекте
function ds_CreateClipEffect(id, starty, step, time)
{
	var elm = $(id);
	var endy = elm.offsetHeight;// - parseInt(elm.style.top);
	
	if(starty == "max")
	{
		starty = endy;
		endy = 0;
	}
	
	elm.style.clip = "rect(" + starty + "px auto " + starty + "px auto)";
	
	ds_CreateClipEffectEx(id, step, starty, starty, endy, time);
}

function ds_CreateClipEffectEx(id, step, starty, sstarty, endy, time, timeout)
{
	var elm = $(id);
	var isend = false;
	sstarty += step;
	
	if(step >= 0 && sstarty >= endy)
		isend = true;
	else if(step < 0 && sstarty <= endy)
		isend = true;
	
	if(isend)
	{
		sstarty = "auto";
		clearTimeout(timeout);
		elm.removeAttribute('clip');
	}
	else
	{
		timeout = setTimeout('ds_CreateClipEffectEx(\''+id+'\', '+step+', '+starty+', '+sstarty+', '+endy+', '+time+', '+timeout+')', time);
		sstarty = sstarty + 'px';
	}

	if(step >= 0)
		elm.style.clip = "rect(" + starty + "px auto " + sstarty + " auto)";
	else
		elm.style.clip = "rect(" + sstarty + " auto " + starty + "px auto)";
}

/**
* установка для элемента уровня прозрачности
* elm - element
* opacity - level opacity for element
*/
function ds_SetOpacity(elm, opacity)
{
	if(elm)
	{
		elm.style.opacity = (opacity == 1 ? 0.99 : opacity);
		elm.style.MozOpacity = (opacity == 1 ? 0.99 : opacity);
		elm.style.KhtmlOpacity = opacity;
		elm.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + (opacity * 100) + ")";
	}
}

// создание opacity effect'a - постеменное повышение/понижение уровня прозрачности для элемента
// id - id element
// step - шаг приращения прозращности (1 - 99)
// time - время в задержке при эффекте
function ds_CreateOpacityEffect(id, step, time)
{
	var elm = $(id);
	var curr;
	
	step = parseInt(step) / 100;
	
	if(step > 0)
		curr = 0;
	else
		curr = 1;

	ds_SetOpacity(elm, curr);	
	ds_CreateOpacityEffectEx(id, step, curr, time);
}

function ds_CreateOpacityEffectEx(id, step, curr, time, timeout)
{
	var elm = $(id);
	var isend = false;
	
	curr += step;
	if(step > 0 && curr >= 0.99)
	{
		isend = true;
		curr = 1;
	}
	else if(step <= 0 && curr <= 0.01)
	{
		isend = true;
		curr = 0;
	}
	
	if(isend)
	{
		clearTimeout(timeout);
		ds_SetOpacity(elm, 1);
		//elm.style.visibility = 'hidden';
		elm.style.display = 'none';
		return;
	}
	else
	{
		timeout = setTimeout('ds_CreateOpacityEffectEx(\''+id+'\', '+step+', '+curr+', '+time+', '+timeout+')', time);
	}

	ds_SetOpacity(elm, curr);
}

// создание move effect'a - перемещение области вниз с последующим обрезанием снизу в месте где в оригинальной позиции заканчивался данный элемент
// только для position:absolute
// id - id element
// starty - мин высота с которой начинается создание
//		max - то будет сверху вниз, от большего значение "y" к меньшему
// step - шаг приращения
// time - время в задержке при эффекте
function ds_CreateMoveEffect(id, starty, step, time)
{
	var elm = $(id);
	var endy = elm.offsetHeight;
	
	if(starty == "max")
	{
		starty = endy;
		endy = 0;
	}
	ds_CreateMoveEffectEx(id, step, starty, starty, endy, time);
}

function ds_CreateMoveEffectEx(id, step, starty, sstarty, endy, time, timeout)
{
	var elm = $(id);
	var isend = false;
	sstarty += step;
	
	if(step >= 0 && sstarty >= endy)
		isend = true;
	else if(step < 0 && sstarty - step <= endy)
		isend = true;
	
	if(isend)
	{
		clearTimeout(timeout);
		elm.removeAttribute('clip');
		//elm.style.visibility = 'hidden';
		elm.style.display = 'none';
		elm.style.clip = "rect(auto auto auto auto)";
		return;
	}
	else
	{
		timeout = setTimeout('ds_CreateMoveEffectEx(\''+id+'\', '+step+', '+starty+', '+sstarty+', '+endy+', '+time+', '+timeout+')', time);
	}

	if(step >= 0)
	{	
		elm.style.clip = "rect(auto auto " + (endy - sstarty) + "px auto)";
		elm.style.top = parseInt(elm.style.top) + Math.abs(step) + 'px';
	}
	else
	{
		elm.style.clip = "rect(auto auto " + sstarty + "px auto)";
		elm.style.bottom = parseInt(elm.style.top) - Math.abs(step) + 'px';
	}
	
}

/**
* получение отступа слева/сверху для элемента путем суммирования смещения относительно предка вплоть до корня (по умолчанию body)
* @elm - текущий элемент
* @dim - left/top
* @roottree - имя корневого тега
*/
function ds_CalcPosElm(elm, dim, roottree)
{
	var pos = 0;
	var tmpelm = elm;
	
	if(dim == "left")
		dim = "Left";
	if(dim == "top")
		dim = "Top";
	
	if(typeof roottree == "undefined")
		roottree = "BODY";
	
	while(tmpelm != null && tmpelm != roottree)
	{
		pos += parseInt(tmpelm['offset' + dim]);
		tmpelm = tmpelm.offsetParent;
	}
	
	return pos;
}

// поиск тега по атрибуту определенного значения
// elm - element
// attr - требуемый атрибут
// value - требуемое значения атрибута
function ds_SearchTag(elm, attr, value)
{
	var t;
	for(var i = 0; i < elm.childNodes.length; i++)
	{
		if(elm.childNodes[i].getAttribute != null)
		{	
			var currval = elm.childNodes[i].getAttribute(attr);
		
			if(currval == value)
				return elm.childNodes[i];
		}
		
		if(elm.childNodes[i].childNodes.length > 0)
		{
			var currelm = ds_SearchTag(elm.childNodes[i], attr, value);
			if(currelm != null)
				return currelm;
		}
	}
	
	return null;
}

/**
* Создание субменю для меню
* id - id submenu
* time - время через которое автоматически гасется меню
* p - parent elm
* step - step opacity
*/
function dsCreateSubmenu(id, time, p, step)
{
	var elm = $(id);
	var timeout;
	if(!elm)
		return false;
	
	if(step == undefined)
		step = 2;

	elm.style.position = "absolute";
	elm.style.top = parseInt(ds_CalcPosElm(p, 'top') + p.offsetHeight / 1.2) + 'px';
	elm.style.left = ds_CalcPosElm(p, 'left') + 'px';

	// capture event
	p.onmouseover = dsSetSubmenu_over;
	p.onmouseout = dsSetSubmenu_out;
	elm.onmouseover = dsSetSubmenu_over;
	elm.onmouseout = dsSetSubmenu_out;
	document.onmouseup = dsSetSubmenu_out;
	
	
	function dsSetSubmenu_out(event)
	{
		if(!event)
			event = window.event;
			
		// если кликаем за подменю, то его сразу закрываем
		if(event.type.indexOf("mouseup") != -1)
			time = 0;
		
		timeout = setTimeout(function()
		{
			//elm.style.display = 'none';
			//elm.style.visibility = 'hidden';
			//ds_CreateMoveEffect(id, 'max', -2, 20);
			ds_CreateOpacityEffect(id, -step, 10);
		}, time);
		elm.timeout = timeout;
	}
	
	function dsSetSubmenu_over()
	{
		elm.style.display = 'block';
		//elm.style.visibility = 'visible';
		//elm.firstChild.style.fontWeight = 'bold';
		
		clearTimeout(elm.timeout);
	}
}

/**
* аналог функции print_r в php
*/
function dsDebug(elm)
{
	if(!elm)
		return;
		
	for(e in elm)
	{
		dsEcho(e + ' -> ' + elm[e]);
	}
}

/**
* функция которая выводит инфу в блок, если его нет, то делает его
* @text - выводимый текст
*/
function dsDebugToStr(text)
{
   var elm = $('debug');
   
   if(!elm)
   {
	   var div = document.createElement('div');
	   div.style.position = 'fixed';
	   div.style.bottom = '0px';
	   div.style.width = '100%';
	   div.style.border = '1px solid #000';
	   div.style.padding = '2px';
	   div.style.backgroundColor = '#fff';
	   div.style.color = '#000';
	   div.style.height = '150px';
	   div.style.overflow = 'auto';
	   div.id = 'debug';
	   document.body.appendChild(div);
	   
	   elm = $('debug');
   }
   
   elm.innerHTML = text + '<br />' + elm.innerHTML;
}

/**
* убирания пробелов в начале и в конце строки
* @text - обрабатываемый текст
*/
function dsTrim(text)
{
   return (text || "").replace(/^\s+|\s+$/g, "");
}

/* namespacing object */
var net = new Object();

net.READY_STATE_UNINITIALIZED = 0;
net.READY_STATE_LOADING = 1;
net.READY_STATE_LOADED = 2;
net.READY_STATE_INTERACTIVE = 3;
net.READY_STATE_COMPLETE = 4;


/*--- content loader object for cross-browser requests ---*/
net.ContentLoader = function(url, onload, onerror, method, params, contentType)
{
  this.req = null;
  this.onload = onload;
  this.onerror = (onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url, method, params, contentType);
  this.params = params;
}

net.ContentLoader.prototype.loadXMLDoc = function(url,method,params,contentType)
{
	if(!method)
  	{
   	method = "GET";
  	}
  	if(!contentType && method == "POST")
  	{
		contentType = 'application/x-www-form-urlencoded';
  	}
  	if(window.XMLHttpRequest)
  	{
    	this.req = new XMLHttpRequest();
  	}
  	else if (window.ActiveXObject)
  	{
   	this.req = new ActiveXObject("Microsoft.XMLHTTP");
  	}
  	if(this.req)
  	{
   	try
    	{
      	var loader = this;
      	this.req.onreadystatechange = function()
      	{
        		net.ContentLoader.onReadyState.call(loader);
      	}
      	this.req.open(method, url, true);
      	if (contentType)
      	{
        		this.req.setRequestHeader('Content-Type', contentType);
      	}
      	this.req.send(params);
    	}
    	catch (err)
    	{
      	this.onerror.call(this);
    	}
  	}
}


net.ContentLoader.onReadyState = function()
{
  var req = this.req;
  var ready = req.readyState;
  if (ready == net.READY_STATE_COMPLETE)
  {
    var httpStatus = req.status;
    if (httpStatus == 200 || httpStatus == 0)
    {
      this.onload.call(this, this.params);
    }
    else
    {
      this.onerror.call(this);
    }
  }
}

net.ContentLoader.prototype.defaultError = function()
{
  alert("error fetching data!"
    + "\n\nreadyState:" + this.req.readyState
    + "\nstatus: " + this.req.status
    + "\nheaders: " + this.req.getAllResponseHeaders());
}

function setCookie(name, value, expires, path, domain, secure) {
	if (!name || !value) return false;
	var str = name + '=' + encodeURIComponent(value);
	
	if (expires) str += '; expires=' + expires.toGMTString();
	if (path)    str += '; path=' + path;
	if (domain)  str += '; domain=' + domain;
	if (secure)  str += '; secure';
	
	document.cookie = str;
	return true;
}
