var charLT='<';
var charGT='>';

function alertObjProp(obj) {
    var result = "";
    for (var i in obj)
        result += i + " = " + obj[i] + "\r";
    alert(result);
}
function showObjProp(obj) {
    var result = "";
    for (var i in obj)
        result += i + " = " + obj[i] + "<br>";
    w=window.showModelessDialog(null,null,"dialogHeight: 400px; dialogWidth: 300px; dialogTop: 50px; dialogLeft: 50px; edge: Raised; center: No; help: No; resizable: Yes; status: No;")
    w.document.write(result);
}

function getOffsetLeft(element, parent)
{
	var result=0;
	var e=element;
	while (e) {
		if (e==parent) break;
		if (parent && parent.offsetParent && parent.offsetParent==e.offsetParent) break;
		if (e.offsetLeft) result+=e.offsetLeft;
		e=e.offsetParent;
	}
	return result;
}
function getAbsoluteLeft(element, parent)
{
	var result=0;
	var e=element;
	while (e) {
		if (e.scrollLeft) result-=e.scrollLeft;
		if (e==parent) break;
		if (parent && parent.offsetParent && parent.offsetParent==e.offsetParent) break;
		if (e.offsetLeft) result+=e.offsetLeft;
		e=e.offsetParent;
	}
	return result;
}

function getOffsetTop(element, parent)
{
	var result=0;
	var e=element;
	while (e) {
		if (e==parent) break;
		if (parent && parent.offsetParent && parent.offsetParent==e.offsetParent) break;
		if (e.offsetTop) result+=e.offsetTop;
		e=e.offsetParent;
	}
	return result;
}
function getAbsoluteTop(element, parent)
{
	var result=0;
	var e=element;
	while (e) {
		if (e.scrollTop) result-=e.scrollTop;
		if (e==parent) break;
		if (parent && parent.offsetParent && parent.offsetParent==e.offsetParent) break;
		if (e.offsetTop) result+=e.offsetTop;
		e=e.offsetParent;
	}
	return result;
}

// Прокрутить список товаров на товар
function scrollToTrade(klstrade)
{//	alert('scrollToTrade('+klstrade+')');
	var result=false;
	if (document.getElementById('scroll_to_klstrade_'+klstrade)) {
		window.setTimeout('document.getElementById("scroll_to_klstrade_'+klstrade+'").scrollIntoView()',100);
		result=true;
	}
	return result;
}

var httpRequest=null;

function createXMLHttpRequest()
{
	if (window.XMLHttpRequest)
	{
		try
		{
            return new XMLHttpRequest();
        }
        catch (e)
        {}
    }
    else if (window.ActiveXObject)
    {
        try
        {
            return new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch (e)
        {}
        try
        {
            return new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch (e)
        {}
    }
    throw (new Error('Ошибка при создании XMLHttpRequest'));
    return null;
}

function getRequest(url)
{
    if (!httpRequest) {
    	httpRequest = createXMLHttpRequest();
    }

	httpRequest.open("GET", url, false);
	httpRequest.send(null);
	var result=httpRequest;
	return result;
}

function getUrlParams()
{
    var result={};
    var s=document.URL;
    if (s!='') {
        var p=s.split('&');
        for (var i=0; i<p.length; i++) {
            var j=p[i].indexOf('=')
            if (j>0) {
                result[p[i].substring(0,j)]=p[i].substring(j+1,100000);
            }
            else {
                result[p[i].substring(1,j-1)]='';
            }
        }
    }
    return result;
}


function getAjaxHtml(url)
{	var sBeg='<!--BegAjax-->';
	var sEnd='<!--EndAjax-->';
	var h=getRequest(url);
	var s=h.responseText;
	var nBeg=s.indexOf(sBeg);
	if (nBeg>=0) {		nBeg=nBeg+sBeg.length;	}
	else {		nBeg=0;	}	var nEnd=s.indexOf(sEnd);
	if (nEnd<0) {
		nEnd=s.length;
	}
	if (nEnd>=nBeg)	{		return s.substr(nBeg, nEnd-nBeg);
	}
	else {		return '';	}
}

var lastWindow=null;

function showWindow(url) {	try {
		if (lastWindow) {			if (lastWindow.close) {				lastWindow.close();			}
			lastWindow=null;		}
	}
	catch(e) {}
	finally {		lastWindow=window.open(url,'_blank','fullscreen=no, toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no, resizable=yes,copyhistory=no, width=800, height=620');
	}
}

function showWindowKorzina(url)
{
//	window.open(url,'korzina','fullscreen=no, toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes, resizable=yes,copyhistory=no, width=800, height=580');
	try	{
		if (lastWindow) {
			if (lastWindow.close) {
				lastWindow.close();
			}
			lastWindow=null;
		}
	}
	catch(e) {}
	finally {
		lastWindow=window.open(url,'_blank','fullscreen=no, toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes, resizable=yes,copyhistory=no, width=800, height=580');
	}
}

/*
Проверка узла по критериям поиска
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
node					- проверяемый узел
params					- вложенная система массивов условий
	params.node     	- узел должен совпадает
	params.tagName		- имя без учета регистра должно совпадать
	params.attributes	- ассоциативный массив атрибутов, должны совпадать
	params.parent		- массив, идентичный params, для node.parentNode
*/
function testNode(node, params)
{
	if (params.node && node!=params.node) return false;
	if (params.tagName && node.tagName.toLowerCase()!=params.tagName.toLowerCase()) return false;
	if (params.attributes) {
		for (var attrName in params.attributes) {
			if (params.attributes[attrName]!=node.getAttribute(attrName)) return false;
		}
	}

	if (params.parent) {
		if (!node.parentNode) return false;
		if (!testNode(node.parentNode, params.parent)) return false;
	}
	return true;
}
/*
Возвращает список подходящих узлов
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
node		- корень поиска
params		- условия
maxLevel    - глубина
isFindFirst - искать до первого подходящего
*/
function findNodes(node, params, maxLevel, isFindFirst)
{
	var result=new Array();
	var nodes=new Array(node);
	var level=0;
	while (nodes.length>0) {
		if (maxLevel && level>=maxLevel) break;
		var allChilds=new Array();
		for (var i=0; i<nodes.length; i++) {
			if (testNode(nodes[i], params)) {
				result[result.length]=nodes[i];
				if (isFindFirst) break;
			}
			for (var k=0; k<nodes[i].childNodes.length; k++) {
				n=nodes[i].childNodes.item(k);
				if (!n.tagName) continue;
				allChilds[allChilds.length]=n;
			}
		}
		if (isFindFirst && result.length>0) break;
        nodes=allChilds;
		level++;
	}
	return result;
}
/*
Возвращает первый подходящий узел
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
node		- корень поиска
params		- условия
maxLevel    - глубина
*/
function findFirstNode(node, params, maxLevel)
{
	var result=null;
	var r=findNodes(node, params, maxLevel, true);
	if (r.length>0) result=r[0];
	return result;
}

/*
function changeCheck(id)
{
	getRequest('http://localhost/korzina/changechk.php?mode=change&klstrade='+id);
	if (httpRequest) {		var isShowMessage=false;		var value=httpRequest.responseText;
		for (var i=0; document.all.item(i); i++) {			var node=document.all.item(i);
			var atrId=null;
			if (node.attributes) atrId=node.attributes.getNamedItem('id');
			if (atrId && atrId.value=='tradebay'+id) {
				var nodeTable=node.firstChild;
				var nodeTableBody=nodeTable.firstChild;
				var nodeTr=nodeTableBody.firstChild;
				var nodeTdPrice=nodeTr.cells.item(0);
				var nodeTdCheck=nodeTr.cells.item(1);
				var nodeTdPriceText=nodeTdPrice.firstChild.firstChild;
				if (value=='1') {					var imgName='ris/chkon.gif';
					if (nodeTdCheck.className=='table_bay_check_white') {						imgName='ris/chkwhiteon.gif';					}
					nodeTdCheck.innerHTML='<img src="'+imgName+'">';
					nodeTdPriceText.innerHTML='в&nbsp;корзине';
					nodeTdPrice.className='table_bay_price_on';
                    isShowMessage=true;
				}
				else {
					var imgName='ris/chkoff.gif';
					if (nodeTdCheck.className=='table_bay_check_white') {
						imgName='ris/chkwhiteoff.gif';
					}
					nodeTdCheck.innerHTML='<img src="'+imgName+'">';
					nodeTdPriceText.innerHTML='купить';
					nodeTdPrice.className='table_bay_price_off';
				}
			}
		}
		if (isShowMessage) {			alert('Товар помещен в корзину. Для оформления заказа нажмите кнопку "Корзина" в правом верхнем углу экрана');
		}
	}
}
*/

function resizeImg(perc)
{	for (var i=0; document.all.item(i); i++) {		var node=document.all.item(i);
		if (node==null) continue;
		if (node.nodeName.toLowerCase()!='img') continue;
		if (	(node.className.toLowerCase()!='img1') &&
				(node.className.toLowerCase()!='img2') &&
				(node.className.toLowerCase()!='img99')
			) continue;

		if ((!node.oldWidth) && (node.height) && (node.width) && (node.height>100)) node.oldWidth=node.width;
		if ((!node.oldWidth) && (node.height) && (node.width) && (node.height==1)) node.oldWidth=node.width;
		if (node.oldWidth)	node.style.width=Math.round(node.oldWidth*perc);
	}
}

/*
Внесение изменений в каскадную таблицу стилей,
работает для Explorer, Opera, Chrome, FireFox
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
function addCssRule(css, element, value)
{	if (css) {		if (css.addRule) {			css.addRule(element, value);
		} else if (css.insertRule) {
			css.insertRule(element+' {'+value+'}', 0);
		}
	}}

/*
Проверка является ли browser мобильной версией Safari
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
function isMobilePlatform()
{
	var s=navigator['appVersion'];
//	return false;
//	return true;
	return (s.indexOf('Mobile')>-1);
}

/*
Расчет динамичиских размеров экранных элементов
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
function getFullFrameWidth()
{
    var maxWidth=1250;
    var minWidth=1000;
    var minDelim=10;
	if (document.body.clientWidth <= (minWidth+2*minDelim)) return minWidth;
	if (
		(document.body.clientWidth >= (minWidth+2*minDelim)) &&
		(document.body.clientWidth <= (maxWidth+2*minDelim))
	) return document.body.clientWidth-2*minDelim;
	return maxWidth;
}
function getFullFrameLeft()
{
	var n=Math.round((document.body.clientWidth-getFullFrameWidth()) / 2);
	if (n<=0) n=0;
	return n;
}
function getScrollHeight()
{
	var n=0;
	if (getFullFrameLeft()<2) n=25;
	return n;
}

function getMenuFrameHeight(titleHeight)
{
	var h=document.body.clientHeight;
	return (h-16-getScrollHeight())-titleHeight-3-100-3-21;
}
function getBodyFrameHeight(titleHeight)
{
	var h=document.body.clientHeight;
	return (h-16-getScrollHeight())-titleHeight-3;
}
function getImgPerc()
{
	var n=1.0;
	if (document.body.clientWidth<(1250-80)) {
		n=0.75;
	}
	return n;
}

