//	$Id: shop.js,v 1.7 2011/10/05 15:25:45 beta Exp $
//	common js for all shop pages


//	///// first some basics

//	nth (subre) or first (subre) or full match
function match (str, re, n) // add to String.prototype? nope
{
	var m = str.match(re);
	return m && (n ? m[n] : 1<m.length ? m[1] : m[0]);
}


function log (str)
{
	try { if (console && console.log) console.log(str); } catch (e) {}
}


var xhrs = 0;
function xhr (url, callback, postdata)
{
	var xhr;
	try { xhr = new XMLHttpRequest();
	} catch(e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(e) { xhr = new ActiveXObject("Msxml2.XMLHTTP");
		}
	}
	var method = postdata ? 'POST' : 'GET';
	log('xhr '+method+' '+url+' BODY '+(postdata || '-'));
	xhr.open(method, url);
	xhr.onreadystatechange = function () {
		if (4 == xhr.readyState) {
			xhrs--;
			callback(200 == xhr.status && xhr.responseText, xhr);
		}
	}
	xhrs++;
	xhr.send(postdata);
}

function I (thid) // thid: object (this or that) or id
{
	return 'string'==typeof thid ? document.getElementById(thid) : thid;
}

function setClass (thid, className)
{
	if (thid = I(thid)) thid.className = className;
}

function show (thid, on)
{
	if (thid = I(thid)) {
		thid.style.display = on || 1==arguments.length ? 'block' : 'none';
		if ('string' == typeof on) thid.innerHTML = on;
	}
	return false; // for links
}

function hide (thid)	// unpop by object or id
{
	show(thid, false);
}


function text (thid, newtext)	// get or set text child
{
	if (!(thid = I(thid))) return;
	var node = thid.firstChild;
	if (!node || '#text' != node.nodeName) {
		if (!newtext) return; // not passed or empty
		node = thid.appendChild(document.createTextNode(newtext));
	} else if (2==arguments.length)
		node.data = newtext;
	return node.data;
}

function trimmed (that) // ECMA 5 has trim
{
	var val = that.value.replace(/^\s+/,'').replace(/\s+$/,'');
	return that.value = val;
}


function setcookie (cname, val, days, minutes)
{
	var exp;
	if (!val) {
		val = '';
		exp = 'Thu, 01 Jan 1970 01:01:01 GMT';
	} else if (days || minutes) {
		var now = (new Date()).getTime();
		minutes = (minutes||0) + days*1440;
		exp = (new Date(now + minutes*60*1000)).toUTCString();
	}
	var newcookie = cname+'='+encodeURIComponent(val)+'; path=/';
	if (exp) newcookie += '; expires='+exp;
	log('setcookie: '+newcookie);
	document.cookie = newcookie;
	if (!val) // also clear domain cookie
		document.cookie = newcookie+'; domain='+location.hostname.replace(/[^.]*/, '');
}


function getcookie (cname)
{
	return match(document.cookie, cname+"=([^;]*)");
}



function shopinit ()
{
	try {
	var args = location.search;
	if (args && /(from|layer)=/.test(args)) {
		if (!args.indexOf('?')) args = args.substr(1);
		var now = (new Date()).getTime();
		setcookie('wt', args+'&time='+(now/1000).toFixed(), 60);
	}
	if (document.referrer && 0>document.referrer.indexOf('//'+location.hostname))
		setcookie('er', document.referrer.substr(0, 70), 1);
	} catch (e) {
		log('exept: '+e);
	}
}

