// Common javascript functions

var IE = document.all?true:false;
var baseUrl = '';

var gCurrentMode = null;
var gCurrentData = null;
var gRequestedMode = null;
var gRequestedData = null;
var currentContentUrl = null;

var nextToken = 1;
var tokenContainer = new Array();

function checkEscapeKey(evt) {
	var evt=(evt)?evt:((event)?event:null);
	if (evt&&(evt.keyCode==27)) {
		hideobj('popup-div-b');
		hideobj('popup-div-b2');
		hideobj('popup-div-0');
		hideobj('popup-div-2');
		hideobj('popup-div');
	}
}

function getKey(e) {
	var evt = e || window.event;
	return evt.keyCode;
}

function isKey(e, code) {
	var evt = e || window.event;
	return evt.keyCode == code;
}

function reloadToken( base, blocks, data, progress, suffix ) {
	var jst = '';
	for ( var i = 0; i < blocks.length; ++i ) {
		if ( jst.length ) jst += '-';
		var source = 'render';
		var target = 'tblock';
		if ( typeof(blocks[i]) == "string" ) {
			source += blocks[i];
			target += blocks[i];
		} else {
			source += blocks[i][0];
			target += blocks[i][1];
		}
		if ( suffix ) target += suffix;
		if ( !byId(target) ) continue;
		if ( progress ) jst += createToken(base+'?m=x&mode='+source, target, data, target, null, 1);
		else jst += createToken(base+'?m=x&mode='+source, target, data);
	}
	return jst;
}

function createToken( url, target, data, progressTarget, errorTarget, restore, params ) {
	var token = new Array();
	token.url = url;
	token.target = target;
	token.data = data;
	token.progressTarget = progressTarget;
	token.errorTarget = errorTarget;
	token.restore = restore;
	token.params = params;
	token.type = 'ajax';
	var tid = nextToken++;
	tokenContainer[ tid ] = token;
	return tid;
}

function createFuncToken( target, params ) {
	var token = new Array();
	token.target = target;
	token.params = params;
	token.type = 'func';
	var tid = nextToken++;
	tokenContainer[ tid ] = token;
	return tid;
}

function removeToken( id ) {
	delete tokenContainer[ id ];
}

function execToken( id, xml, args, cp, norem ) {
	var pieces = id.split('-');
	for (var i = 0; i < pieces.length; i++)	{
		var token = tokenContainer[ parseInt(pieces[i]) ];
		if ( !token ) continue;
		if ( token.type == 'ajax' ) {
			doAjax(token.url, token.target, token.data, token.progressTarget, token.errorTarget, token.restore, token.params);
		} else if ( token.type == 'func' ) {
			token.target( token.params, xml, args, cp );
		}
		if (!norem) removeToken( parseInt(pieces[i]) );
	}
}

function findPos(obj, noscroll) {
	var anchor = obj;
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft - (noscroll?0:obj.scrollLeft);
		curtop = obj.offsetTop - (noscroll?0:obj.scrollTop);
//		alert('OP1: ' + obj.offsetLeft + ':' + obj.scrollLeft  + ':' +  obj.offsetTop + ':' + obj.scrollTop);
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft - (noscroll?0:obj.scrollLeft);
			curtop += obj.offsetTop - (noscroll?0:obj.scrollTop);
//			alert('OP2: ' + obj.offsetLeft + ':' + obj.scrollLeft  + ':' +  obj.offsetTop + ':' + obj.scrollTop);
		}
	}
//	alert('RET: ' + curleft + ':' + curtop  + ':' +  anchor.offsetWidth  + ':' +  anchor.offsetHeight);
	return [curleft,curtop,anchor.offsetWidth,anchor.offsetHeight];
}

function position(obj, anchor, hz, vt, container) {
	var x = 0; var y = 0;
	var pos = findPos(anchor, IE);
//	alert(pos[0]+' - ' + pos[1]);
	switch( hz )
	{
	case 9: x = pos[0]; obj.style.width = pos[2] + 'px'; break;
	case -2: x = pos[0] - obj.offsetWidth; break;
	case -1: x = pos[0] + pos[2] - obj.offsetWidth; break;
	case 1: x = pos[0] + pos[2]; break;
	default: x = pos[0]; break;
	}
	switch( vt )
	{
	case 9: y = pos[1]; obj.style.height = pos[3] + 'px'; break;
	case -2: y = pos[1] - obj.offsetHeight; break;
	case -1: y = pos[1] + pos[3] - obj.offsetHeight; break;
	case 1: y = pos[1] + pos[3]; break;
	default: y = pos[1]; break;
	}
	if ( container )
	{
		x -= container.scrollLeft;
		y -= container.scrollTop;
	}
	obj.style.left = x + 'px';
	obj.style.top = y + 'px';
} 

function showobj(obj, v, inline, tr) {
	if (typeof(obj) == "string") obj = byId(obj);
	if (obj == null) return false;
	if (v == null) v = 1;
	obj.style.display=v?(inline?'inline':(tr?'table-row':'block')):'none';
	return v;
}
function hideobj(obj) {
	showobj(obj, 0);
}

function visobj(obj, v) {
	if (typeof(obj) == "string") obj = byId(obj);
	if (obj == null) return false;
	if (v == null) v = 1;
	obj.style.visibility=v?'visible':'hidden';
}
function unvisobj(obj) {
	visobj(obj, 0);
}

function alterobj(obj) {
	if (typeof(obj) == "string") obj = byId(obj);
	if (obj == null) return false;
	var visible=obj.style.display=='none'||!obj.style.display;
	showobj(obj,visible);
	return !visible;
}

function altertr(obj, sign) {
	if (typeof(obj) == "string") obj = byId(obj);
	if (obj == null) return false;
	var visible=obj.style.display=='none';
	obj.style.display=visible?'table-row':'none';
	if (sign) byId(sign).src=visible?'/img/icon/sminus.gif':'/img/icon/splus.gif';
	return visible;
}

function byId(sName) {
	return document.getElementById(sName);
}
function byTag(obj,sTag) {
	return obj.getElementsByTagName(sTag);
}

var popupRepos = false;
var popupAnchor = null;
var popupHAlign = 'left';
var popupVAlign = 'over';

function popupConfigure( anchor, halign, valign ) {
	popupAnchor = anchor;
	popupHAlign = halign;
	popupVAlign = valign;
	popupRepos = true;
}

function _popupFromAjax( xml, div, args ) {
	var oDiv = byId(div);
	oDiv.style.visibility = 'hidden';
	if ( typeof(args) == "undefined" || typeof(args.positioning) == "undefined" || args.positioning !== false ) {
		oDiv.style.height = 'auto';
		oDiv.style.width = 'auto';
		oDiv.style.display = 'block';
	}
	oDiv.innerHTML = GetNodeValue(xml, 'data/html', 1);
	if ( typeof(args) == "undefined" || typeof(args.positioning) == "undefined" || args.positioning !== false ) {
		if ( args && args.anchor ) position( oDiv, args.anchor, args.h, args.v, args.container );
		else if ( popupRepos ) showComponent(popupAnchor, oDiv.id, 1, popupVAlign=='under'?1:0, popupHAlign=='right'?1:0); 
	}
	oDiv.style.visibility = 'visible';
	if ( !elementInViewport(oDiv) ) oDiv.scrollIntoView();
	popupRepos = false;

	var firstInput = null;
	var aForms = oDiv.getElementsByTagName('form');
	for ( var f = 0; f < aForms.length; f++ ) {
		for ( var i = 0; i < aForms[f].elements.length; i++ ) {
			var bFocus = aForms[f].elements[i].getAttribute('focus');
			if ( bFocus && bFocus == "1" ) {
				aForms[f].elements[i].focus();
				return;
			} 
			if ( !firstInput && aForms[f].elements[i].type != 'hidden' ) {
				firstInput = aForms[f].elements[i];
			}
		}
	}
	if ( firstInput ) firstInput.focus();
	if ( firstInput ) firstInput.focus();
}

function popupFromAjaxB( xml, args ) {
	_popupFromAjax(xml, 'popup-div-b', args);
}
function popupFromAjaxB2( xml, args ) {
	_popupFromAjax(xml, 'popup-div-b2', args);
}
function popupFromAjax0( xml, args ) {
	_popupFromAjax(xml, 'popup-div-0', args);
}
function popupFromAjax( xml, args ) {
	_popupFromAjax(xml, 'popup-div', args);
}
function popupFromAjax2( xml, args ) {
	_popupFromAjax(xml, 'popup-div-2', args);
}


var mouseX = 0;
var mouseY = 0;
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;

function getMouseXY(e) {
	if (IE) {
		mouseX = event.clientX + document.body.scrollLeft;
		mouseY = event.clientY + document.body.scrollTop;
	} else {
		mouseX = e.pageX;
		mouseY = e.pageY;
	}  
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
	{
		curtop += obj.y;
	}
	return curtop;
}

function centerDiv( obj )
{
	obj.style.display = "block";	
	
	var top = (document.body.clientHeight - obj.offsetHeight) / 2;
	var left = (document.body.clientWidth - obj.offsetWidth) / 2;
          
	obj.style.left = left + document.body.scrollLeft;
	obj.style.top = top + document.body.scrollTop;
}

function showComponent (obj, div, show, under, right)
{
	var x = byId(div);
	x.style.display = (show) ? 'block' : 'none';
	if (show) setLayer (obj, div, under || show == 2, right);
}

function setLayer (obj, lyr, under, right)
{
	var newX = findPosX(obj);
	var newY = findPosY(obj)
	if ( newX == 0 && newY == 0 ) centerDiv( obj );
	else
	{
		var x = byId(lyr);
		if (under) newY += obj.offsetHeight;
		if (right) newX = newX - x.offsetWidth + obj.offsetWidth;
		x.style.top = newY + 'px';
		x.style.left = newX + 'px';
	}
}


function showPopupFromHtml(html, x, y, w, h) {
	var oDiv = byId('popup-div');
	oDiv.innerHTML = html;
	oDiv.style.top = y;
	oDiv.style.left = x;
	oDiv.style.height = h;
	oDiv.style.width = w;
	oDiv.style.display = 'block';
}



function ParseXML (xml) {
	if(window.ActiveXObject) {
		try {
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.loadXML(xml);
		} catch (e) {
			try {
				xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
				xmlDoc.loadXML(xml);
			} catch (e) {
				alert(e);
			}
		}
		return xmlDoc;	
	}
	else if (DOMParser) {
		xmlDoc = (new DOMParser()).parseFromString(xml, "text/xml");
		return xmlDoc;
	}
	throw new Error("Could not instantiate XMLHttpRequest");
}

function GetNode(xml, node)
{
	var curr = xml;
	var pieces = node.split ('/');
	for (var i = 0; i < pieces.length; i++)
	{
		var found = false;
		var n = curr.firstChild;
		while (n)
		{
			if (n.nodeName == pieces[i])
			{
				found = true;
				curr = n;
				break;
			}
			n = n.nextSibling;
		}
		if ( !found ) 
		{
			curr = null;
			break;
		}
	}
	return curr;
}

function GetNodeValue(xml, node, cdata)
{
	var curr = GetNode(xml, node);
	
	if (curr && curr.firstChild)
	{
		if (cdata != null && typeof(curr.textContent) != "undefined") return curr.textContent;
		return curr.firstChild.nodeValue;
	}
	return null;
}

function autoReload(sDiv, tDiv) {
	var oDiv = byId(sDiv);
	if ( !oDiv ) return false;
	doAjax( oDiv.getAttribute('xurl'), tDiv, oDiv.getAttribute('xdata'));
}

function autoUpdate(xml, args) {
	var node = GetNode(xml, 'data/update');
	if ( node )	{
		var n = node.firstChild;
		while (n)
		{
			var e = byId(n.nodeName);
			if ( e ) e.innerHTML = n.textContent;
			n = n.nextSibling;
		}		
	}
	
	var node = GetNode(xml, 'data/bgcolor');
	if ( node )	{
		var n = node.firstChild;
		while (n)
		{
			var e = byId(n.nodeName);
			if ( e ) e.style.backgroundColor = n.textContent;
			n = n.nextSibling;
		}		
	}

	var node = GetNode(xml, 'data/color');
	if ( node )	{
		var n = node.firstChild;
		while (n)
		{
			var e = byId(n.nodeName);
			if ( e ) e.style.color = n.textContent;
			n = n.nextSibling;
		}		
	}

	var node = GetNode(xml, 'data/align');
	if ( node )	{
		var n = node.firstChild;
		while (n)
		{
			var e = byId(n.nodeName);
			if ( e ) e.style.textAlign = n.textContent;
			n = n.nextSibling;
		}		
	}

	var node = GetNode(xml, 'data/id');
	if ( node )	{
		var n = node.firstChild;
		while (n)
		{
			var e = byId(n.nodeName);
			if ( e ) e.id = n.textContent;
			n = n.nextSibling;
		}		
	}
}

function submitForm (name) {
	var form = byId(name);
	if (form) form.submit();
}

function getScrollOffset() {
	var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body
	var dsocleft=document.all? iebody.scrollLeft : pageXOffset
	var dsoctop=document.all? iebody.scrollTop : pageYOffset	
	return [dsocleft, dsoctop];
}

function messagePopup( type, msg, flags ) {
	var oDivW = byId('message-div-wrap');
	var oDiv = byId('message-div');
	oDiv.style.visibility = 'hidden';
	oDivW.style.display = 'block';
	oDiv.innerHTML = msg;
	var offset=getScrollOffset();
	oDiv.style.marginTop= (160 + offset[1]) + 'px';
	oDiv.style.display = 'block';
	oDiv.style.visibility = 'visible';
	var oBtn = byId('efb-close-btn');
	if ( oBtn ) oBtn.focus();
}


function ajaxRequestCompleted (user, status, statusText, responseText, responseXML) {
//	alert (responseText);
	if (responseText == null || responseText.length == 0)
	{
		if (this.ignoreErrors != 1) alert ('Failed to perform the operation!');		
		if (this.progressDiv && this.restoreOnError) {
			this.progressDiv.innerHTML = this.originalContent;		
		}
	}
	else
	{
		var xml = ParseXML(responseText);

		var failed = false;		
		if ( IE ) {
			if ( !xml.documentElement || !xml.documentElement.firstChild ) {
				if (this.ignoreErrors != 1) alert("Parsing Error!\n------------------------------\n" + responseText);
				failed = true;
			}
		} else {
			if ((xml.documentElement.tagName == "parsererror") || 
				(xml.documentElement.namespaceURI == "http://www.mozilla.org/newlayout/xml/parsererror.xml")){
				if (this.ignoreErrors != 1) alert("Parsing Error! " +  xml.documentElement.firstChild.data + "\n------------------------------\n" + responseText);
				failed = true;
			}	
		}
		if ( failed ) {
			if (this.progressDiv && this.restoreOnError) {
				this.progressDiv.innerHTML = this.originalContent;
			}
			return;
		}
		
		var code = GetNodeValue(xml, 'data/result/code');
		var msg = GetNodeValue(xml, 'data/result/msg', 1);
		var msg2 = GetNodeValue(xml, 'data/result/msg2', 1);
		if (code != 0)
		{
			if (this.progressDiv && this.restoreOnError) {
				this.progressDiv.innerHTML = this.originalContent;		
			}
			
			if (this.errorDiv) {
				var oEDiv = byId(this.errorDiv);
				if (oEDiv) {
					oEDiv.innerHTML = msg;
					oEDiv.style.display = 'block';
				} else {
					if ( msg != null && msg.length > 0 ) alert(msg);
				}
			} else if ( this.errorHandler ) {		
				this.errorHandler( xml, this.params );
			} else {
				if ( msg != null && msg.length > 0 ) alert(msg);
				if ( msg2 != null && msg2.length > 0 ) messagePopup('e', msg2, 0);	
//				showPopupFromHtml('testing', '10em', '10em', '10em', '10em');
			}
		}
		else
		{
//			alert(typeof (this.target));
//			alert(this.target);
			if (this.progressDiv && this.restoreOnError == 2) {
				this.progressDiv.innerHTML = this.originalContent;		
			}
			if (this.target == null)
			{
				if ( msg != null && msg.length ) alert(msg);
			}
			else if (typeof (this.target) == "string")
			{
				var oTarget = byId(this.target);
				oTarget.innerHTML = GetNodeValue(xml, 'data/html', 1);
			}
			else if (typeof (this.target) == "object")
			{
				this.target.innerHTML = GetNodeValue (xml, 'data/html', 1);
			}
			else if (typeof (this.target) == "function")
			{
				this.target(xml, this.params);
			}
		}
	}
}

function cb_setobj(xml, params) {
	var target = byId(params.target);
	target.innerHTML = GetNodeValue(xml, 'data/html', 1);
}

function cb_hideobj(xml, params) {
	hideobj(params.hide);
}

function ajax2(url, data, params, oncall, onsuccess, onerror) {
	var ajaxRequest = new Asynchronous();
	ajaxRequest.target = onsuccess;
	ajaxRequest.errorHandler = onerror;
	ajaxRequest.params = params;
	ajaxRequest.complete = ajaxRequestCompleted;
	if ( oncall ) oncall(params);
	ajaxRequest.call( data != null ? "POST" : "GET", url, data );
}

function doAjaxWH(base, url, target, data, progressDiv, errorDiv, restoreOnError, params, ignoreErrors) {
//	hadd(url, [base, target]);
	doAjax(url, target, data, progressDiv, errorDiv, restoreOnError, params, ignoreErrors);
}

function doAjax(url, target, data, progressDiv, errorDiv, restoreOnError, params, ignoreErrors, onerror) {
	var ajaxRequest = new Asynchronous();
	if (errorDiv) {
		if (typeof (errorDiv) == "object") ajaxRequest.errorDiv = errorDiv.id;
		else ajaxRequest.errorDiv = errorDiv;
	}
	if (progressDiv != null) {	
		var ptext = '';
		var pmargin = '3em';
		var sstyle = '';
		var pdiv = progressDiv;
		if ( progressDiv instanceof Array ) {
			ptext = progressDiv[1];
			pmargin = progressDiv[2];
			pdiv = progressDiv[0];
			sstyle = progressDiv[3];
		}
		if (typeof (pdiv) == "object") ajaxRequest.progressDiv = pdiv;
		else ajaxRequest.progressDiv = byId(pdiv);
		ajaxRequest.originalContent = ajaxRequest.progressDiv.innerHTML;
		ajaxRequest.progressDiv.innerHTML = '<div style="text-align:center; margin-top:'+pmargin+';"><span style="'+sstyle+'"><img align="center" valign="middle" class="progress" src="/img/progress.gif"/>'+'&nbsp;&nbsp;'+ptext+'</span></div>';
	}
	ajaxRequest.restoreOnError = restoreOnError;
	ajaxRequest.target = target;
	ajaxRequest.errorHandler = onerror;
	ajaxRequest.params = params;
	ajaxRequest.ignoreErrors = ignoreErrors;
	ajaxRequest.complete = ajaxRequestCompleted;
	ajaxRequest.call("POST", url, data);
}


function cleanURL (url) {
	var cleanUrl = url;
	var pindex = cleanUrl.indexOf ("http");
	if (pindex == 0)
	{
		var sindex = cleanUrl.indexOf ("//");
		var eindex = cleanUrl.indexOf ("/", sindex + 2);
		cleanUrl = cleanUrl.substr (eindex);
	}

	var bindex = cleanUrl.indexOf (baseUrl);
	if (bindex == 0)
	{
		var sindex = baseUrl.length;
		if (cleanUrl.length > baseUrl.length && cleanUrl.charAt(baseUrl.length) == '/') sindex++;
		cleanUrl = cleanUrl.substr (sindex);
	}

	var hindex = cleanUrl.indexOf ('?');
	if (hindex >= 0)
	{
		cleanUrl = cleanUrl.substr (0, hindex);
	}
	return cleanUrl;	
}

function urlAppendParam (surl, param)
{
	if (surl.search(/\?/) == -1) return surl + "?" + param;
	return surl + "&" + param;
}

function loadMain(url, data, func, user, flags) {
	hideobj('popup-div-b');
	hideobj('popup-div-0');
	hideobj('popup-div');
	hideobj('popup-div-2');
	if ( location.pathname != '' && location.pathname != '/' ) 
	{
		byId('reloadclean').action = '/#'+cleanURL(url);
		byId('reloadclean').submit();
//		location='/#'+cleanURL(url);
		return false;
	}
	loadMainPostFunction = func;
	currentContentUrl = url;
    dhtmlHistory.add(cleanURL(url), null);
	var nurl = urlAppendParam (url, 'm=s');
	loadMainSection("POST", nurl, data, user, flags);
	return false;
}

function hadd(url,data) {
	dhtmlHistory.add(cleanURL(url), data);
}

function loadMainFromLink(name, data, func) {
	var link = byId(name);
	return loadMain(link.href, data, func);
}

function loadm(link, data, func, user, flags) {
	var url = null;
	if( typeof(link) == "object" && (link.tagName == "A" || link.tagName == "a") ) url = link.href;
	else if( typeof(link) == "string" )
	{
		if ( link.substr(0,1) == "/" ) url = link;
		else url = byId(link).href;
	}
	return loadMain(url, data, func, user, flags);
}

function loadMainFromLinkObj(link, data, func, user) {
	return loadMain(link.href, data, func, user);
}

function changeAppTab (oLink, noreload) {
	if ( false ) {
		var oNew = null;
		if (oLink != null) {
			if (typeof(oLink) == "string") {
				oNew = byId(oLink);
			} else {
				oNew = oLink.parentNode;
			}
		}
		var oTopMenu = byId('top-menu');
		var oLists = oTopMenu.getElementsByTagName ('ul');
		for (var i = 0; i < oLists.length; i++) {
			var oItems = oLists[i].getElementsByTagName ('li');
			for (var j = 0; j < oItems.length; j++) {
				oItems[j].className = '';
			}
		}	
		if (oNew == null) return false;
	
		oNew.className = 'current';
	}	
	
	if (typeof(noreload) != "undefined" && noreload == true) return false;
	
	return loadMainFromLinkObj(oLink);
}



function GetListItemFromEvenTarget(p_oNode) {
	var oLI;
	if(typeof (p_oNode) == "object" && p_oNode.tagName == "LI") {
    	oLI = p_oNode;
    } else {
		do {
			if(p_oNode.tagName == "LI") {
			    oLI = p_oNode;                            
                break;
            }
        }
        while((p_oNode = p_oNode.parentNode));
    }
    return oLI;
}

function FindElementByAttribute(p_oNode, attrib) {
	if (p_oNode == null) return null;
	var oLI = null;	
	if(p_oNode.getAttribute && typeof(p_oNode.getAttribute(attrib)) != "undefined") {
    	oLI = p_oNode;
    } else {
		do {			
			if(p_oNode.getAttribute && typeof(p_oNode.getAttribute(attrib)) != "undefined") {
			    oLI = p_oNode;                            
                break;
            }
        }
        while((p_oNode = p_oNode.parentNode));
    }
    return oLI;
}


function initialise( st ) {
	dhtmlHistory.initialize();
	dhtmlHistory.addListener (historyChange);
	document.onkeydown = checkEscapeKey;
	if (dhtmlHistory.isFirstLoad()) 
	{
		if (document.location.hash.length > 0)
		{
			var hash = document.location.hash.substr (1);
			loadMainSection("POST", urlAppendParam (baseUrl + '/' + hash, "m=s"));
		}
/*		else if ( document.location.pathname ==  '/' || document.location.pathname == '' )
		{
			loadMainSection("POST", urlAppendParam (baseUrl + '/home', "m=s"));
		}
		else
		{
			var hash = document.location.pathname.substr(1);
			loadMainSection("POST", urlAppendParam (baseUrl + '/' + hash, "m=s"));
		}*/
	}
	var oCMC = byId('_current_main_content_');
	if (oCMC && oCMC.getAttribute('xtype') == 'category') initCategory( oCMC );
	checkReload();
	if ( st == 0 ) setTimeout ("checkUpdates()", 270000);
}

function initCategory( oCMC ) {
	var oCF = byId('categoryfilter');
	var udata = oCMC.getAttribute('xuser');
	var subcat = '';
	if ( udata.match('^s:') ) subcat = udata.substr( 2 );
	if (oCF == null || oCF.getAttribute('categoryid') != oCMC.getAttribute('xid') || (oCF.getAttribute('subcategory') != udata)) {
	    doAjax ("/categoryops/getfilter?m=x&cid=" + oCMC.getAttribute('xid') + '&subcat=' + subcat, postLoadFilter);
	} else {
		initCategoryFilter( oCF, oCMC.getAttribute('xfilter') );
	}
	bResetRbDynamic = false;
}

function processUpdates( xml ) {
}

function checkUpdates() {
	doAjax('/user/getmsgs?m=x', processUpdates, null, null, null, null, null, 1);
	setTimeout ("checkUpdates()", 270000);
}

function historyChange(newLocation, historyData) {
/*	if ( typeof(historyData) == "object" && historyData instanceof Array && historyData.length >= 2 ) 
	{
		alert(location.hash);
		alert(historyData[0]);
		alert('{ doAjax(urlAppendParam(\'' + baseUrl + '/' + newLocation + '\', "m=x"), \'' + historyData[1] + '\'); }');
		if ( location.hash.indexOf( historyData[0] ) != 0 )
		{
			alert('reload main');
			alert(urlAppendParam(baseUrl + historyData[0], "m=s"));
			loadMainSection("POST", urlAppendParam(baseUrl + '/' + historyData[0], "m=s"), null, { noscroll:true } );
			// new Function("xml", '{ doAjax(urlAppendParam(\'' + baseUrl + '/' + newLocation + '\', "m=x"), \'' + historyData[1] + '\'); }')
		}
		else
		{
			alert('direct');
			alert(urlAppendParam(baseUrl + '/' + newLocation, "m=x"));
			alert(historyData[1]);
			doAjax(urlAppendParam(baseUrl + '/' + newLocation, "m=x"), historyData[1]);
		}
	}
	else */
		loadMainSection("POST", urlAppendParam (baseUrl + '/' + newLocation, "m=s"), null, { noscroll:true } );
}

function isVisible(oObj) {
	var oCurr = oObj;
	while (oCurr) {
		if (oCurr.style && oCurr.style.display == 'none') return false;
		oCurr = oCurr.parentNode;
	}
	return true;
}

function getFormControl(obj, eId) {
	var form = byId(obj);
	if (typeof(obj) == 'object') form = obj;
	if (form == null) return null;
	for(var i = 0; i < form.elements.length; i++)
	{
		if ( form.elements[i].id != eId ) continue;
		return form.elements[i];
	}
	return null;
}

function getFormItem(obj, eId) {
	var form = byId(obj);
	if (form == null) return null;
	for(var i = 0; i < form.elements.length; i++)
	{
		if ( form.elements[i].id != eId ) continue;
		return form.elements[i].value;
	}
	return null;
}

function getFormData(obj, ignoreVisibility)
{
	var form = byId(obj);
	if (form == null) return false;
	
	var str = "";	
	for(var i = 0; i < form.elements.length; i++)
	{
		switch(form.elements[i].type)
		{
			case "text": str += form.elements[i].id + "=" + encodeURIComponent (form.elements[i].value) + "&"; break;
			case "textarea": str += form.elements[i].id + "=" + encodeURIComponent (form.elements[i].value) + "&"; break;
			case "checkbox": if (form.elements[i].checked == true) str += form.elements[i].id + "=" + encodeURIComponent (form.elements[i].value) + "&"; break;
			case "hidden": str += form.elements[i].id + "=" + encodeURIComponent (form.elements[i].value) + "&"; break;
			case "password": str += form.elements[i].id + "=" + encodeURIComponent (form.elements[i].value) + "&"; break;
			case "radio": if (form.elements[i].checked == true) str += form.elements[i].id + "=" + encodeURIComponent (form.elements[i].value) + "&"; break;
			case "select-one": str += form.elements[i].id + "=" + encodeURIComponent(form.elements[i].options[form.elements[i].selectedIndex].value) + "&"; break;
			case "select-multiple":
				str += form.elements[i].id + "=";
				for(var k = 0; k < form.elements[i].options.length; k++) {
					if(form.elements[i].options[k].selected == true) {
						str += encodeURIComponent(form.elements[i].options[k].value) + ",";
					}
				}
				str += "&";
				break;
    	}
	}
	
	var oDivs = form.getElementsByTagName('div');
	for (var i = 0; i < oDivs.length; i++) {
		if (oDivs[i].getAttribute('type') == 'tick' && (ignoreVisibility || isVisible(oDivs[i]))) {
			var oValue = tickGetValue(oDivs[i]);
			if ( oValue ) str += oDivs[i].id  + "=" + oValue + "&";
		}
	}
	
	if (str.length) str = str.substr(0,(str.length - 1));
//	alert(str);
	return str;
}

function submitAjaxForm (name) {
	var data = getFormData (name);
	var form = byId(name);
	loadMainSection("POST", form.action, data);
}

function submitAjaxFormToTarget (name, url, target, progressDiv, errorDiv, restoreOnError) {
	var data = getFormData (name);
	doAjax(url, target, data, progressDiv, errorDiv, restoreOnError);
}


function fileUpload(form, idiv, odiv) {
	var parentDoc = window.parent.document;
	var oODiv = parentDoc.getElementById(odiv);
	var oIDiv = parentDoc.getElementById(idiv);
	oIDiv.className = 'hidden';
	
	var oImg = parentDoc.createElement('img');
	oImg.src = '/img/progress.gif';
	oImg.className = 'progress';
	oODiv.appendChild(oImg);

	var oForm = byId(form);
	oForm.submit();
}





var reloadUrl = '';
var reloadData = '';
var performReload = false;
var loadMainPostFunction = null;

var mainLoadAjax = new Asynchronous();	
mainLoadAjax.complete = function (user, status, statusText, responseText, responseXML) {
//	alert (responseText);
	var mainDiv = byId('frame-middle-center');
	mainDiv.style.visibility = 'hidden';
	mainDiv.innerHTML = '';
	if ( !user || user.noscroll != true ) {
		window.scrollTo(0, 0);
	}
	mainDiv.innerHTML = responseText;
	mainDiv.style.visibility = 'visible';
	if (loadMainPostFunction != null) {
		var result = loadMainPostFunction();
		loadMainPostFunction = null;
		if (!result) return;
	}

	var bResetRbDynamic = true;
	var oLvpDiv = byId('lvp-list');
	var oLvpNode = oLvpDiv.firstChild;
	
	var titleSet = false;
	var oCMC = byId('_current_main_content_');
	if (oCMC != null) {
		if (oCMC.getAttribute('xtitle') != null) {
			var title = oCMC.getAttribute('xtitle');
			if ( title && title != '' ){
				if ( title != 'NIVO Interactive Shopping' ) title += ' @ NIVO Interactive Shopping';
				document.title = title;
				titleSet = true;
			}
		}
		if (oCMC.getAttribute('xtype') == 'category') {
			initCategory( oCMC );
			bResetRbDynamic = false;
		}
		else if (oCMC.getAttribute('xtype') == 'product') {
			var newId = 'lvp-' + oCMC.getAttribute('xid');
			var oLN = oLvpDiv.firstChild;
			while( oLN && newId )
			{
				if ( oLN.tagName == 'DIV' && oLN.id == newId ) newId = null;
				oLN = oLN.nextSibling;
			}
			if ( newId )
			{			
				var oPNDiv = byId('xproductdesc_lvp');
				var lvpOriginal = byId('lvp-original');
				var oClone = lvpOriginal.cloneNode(true);
				oClone.id = 'lvp-' + oCMC.getAttribute('xid');
				var oLink = oClone.getElementsByTagName('a');
				oLink[0].href = oCMC.getAttribute('xurl');
				oLink[0].innerHTML = oPNDiv.innerHTML;
				oLvpDiv.insertBefore( oClone, oLvpDiv.firstChild );
				oLvpNode = oLvpDiv.firstChild.nextSubling;
			}
		}
	}		
	if ( titleSet == false ) document.title = 'NIVO Interactive Shopping';
	
	var lvpNodeCount = 0;	
	if (oLvpNode && oLvpNode.tagName == 'DIV') byId('last-viewed-prod').style.display = 'block';
	while( oLvpNode && lvpNodeCount++ < 5)
	{
		if ( oLvpNode.tagName == 'DIV' ) oLvpNode.style.display = 'block';
		oLvpNode = oLvpNode.nextSibling;
	}
	while( oLvpNode ) { var cNode = oLvpNode; oLvpNode = oLvpNode.nextSibling; oLvpDiv.removeChild(cNode); }

	if ( bResetRbDynamic )
	{	
	    var oCF = byId('rb_dynamic'); 
	    oCF.style.display = 'none';
	    oCF.innerHTML = '';
	}
}

function initCategoryFilter(obj, filter) {
	var flist = new Array();
	var items=filter.split('/');
	for (var i=0; i < items.length; ++i) {
		if ( items[i] =='' ) continue;
		var sitems=items[i].split('+');
		for (var j=0; j < sitems.length; ++j) {
			var parts=sitems[j].split('~');
			if ( parts.length == 1 ) {
				flist.push( [ parts[0], '' ] );
			} else {
				for (var k=1; k < parts.length; ++k) {
					var fitems=parts[k].split('-');
					for (var l=0; l < fitems.length; ++l) {
						if ( fitems[l] == 'or' || fitems[l] == 'and' ) continue;
						flist.push( [ parts[0], fitems[l] ] );
					}
				}
			}
		}
	}
	
	var selection = filter.split("-");
	var oFilterDivs = obj.getElementsByTagName('div');
	var count = 0;
	for (var x = 0; x < oFilterDivs.length; x++) {
		var type = oFilterDivs[x].getAttribute('ftype');
		var parent = oFilterDivs[x].getAttribute('fparent');
		var value = oFilterDivs[x].getAttribute('feid');
		if (value) {
			oFilterDivs[x].className = 'ticks-g-off';
			if ( type == 'brand' ) {
				var lid = oFilterDivs[x].id.replace( /bentry/, 'brandlines' );
				hideobj(lid);
			}
			for (var y = 0; y < flist.length; ++y) {
				if ( type == 'brand' && value == flist[y][0] ) {
					oFilterDivs[x].className = 'ticks-g-on';
					var lid = oFilterDivs[x].id.replace( /bentry/, 'brandlines' );
					showobj(lid);
				} else if ( (type == 'line' || type == 'for' || type == 'fand') && parent == flist[y][0] && value == flist[y][1] ) {
					oFilterDivs[x].className = 'ticks-g-on';
					break;
				}
			}
		}
	}
}

function postLoadFilter(xml) {
	var oCF = byId('rb_dynamic'); 
	var html = GetNodeValue (xml, 'data/html', 1); 
	oCF.innerHTML = html;	

	var oCMC = byId('_current_main_content_');
//	var selection = oCMC.getAttribute('xfilter').split("-");
	
	var oCFDiv = byId('categoryfilter');
	if (oCFDiv == null) { oCF.style.display = 'none'; return; }

	initCategoryFilter( oCFDiv, oCMC.getAttribute('xfilter') );
	
	if ( html != 'null' && html != '') oCF.style.display = 'block';
}

var LMS_FLAG_NOPROGRESS = 0x1;

function loadMainSection (method, url, data, user, flags) {
	if ( !(flags & LMS_FLAG_NOPROGRESS) ) {
		var oDiv = byId('frame-middle-center');
		oDiv.innerHTML = '<div style="position:relative; text-align:center; padding:1em;"><img class="progress" src="/img/progress.gif"/></div>';
	}
	mainLoadAjax.call("POST", url, data, user);
}

function checkReload()
{
//	alert ("reload: " + performReload);
	if (performReload) 
	{
		performReload = false;
		loadMain (reloadUrl, reloadData);
	}
	setTimeout ("checkReload()", 1000);
}



function performAuthOperation(url, div, form, progressDiv, errorDiv) {
	var data = form ? getFormData(form) : null;
	return doAjax(url, new Function("xml", 
		'{ var lout=GetNodeValue (xml, "data/op") == "logout"; if ((location.hash == "#user/login") || (location.hash == "#user/syslogin") || lout) { location.href=(lout?"http":"https")+"://"+location.hostname+"/"; } else { var newloc = location.href.replace("http"+(lout?"s":"")+":","http"+(lout?"":"s")+":"); if ( newloc == location.href ) location.reload(); else location.href = newloc; } }'), 
		data, progressDiv, errorDiv, true);
}

function swapDivs (divs, div) {
	var cDiv = byId(divs);
	var allDivs = cDiv.getElementsByTagName ('div');
	for (var x = 0; x < allDivs.length; x++)
	{
		if (allDivs[x].id == div) allDivs[x].style.display = "block";
		else if (allDivs[x].parentNode == cDiv) allDivs[x].style.display = "none";
	}
}


function showUploadFileDialog(target) {
	
}


function loadCategoryPage(link, cid, data) {	
	changeAppTab('t_products', true); 
	var curl = link;
	if (typeof(link) == 'object') curl = link.href;
	return loadMain(curl, data);
}

function loadProductPage(link) {
	changeAppTab('t_products', true); 
	return loadMainFromLinkObj(link, null);
}

function roundMoney(value) {
	return Math.round(value*100)/100;
}

function showShippingCostPopup(xml) {
	var pId = GetNodeValue (xml, 'data/pid');
	var oObj = byId('shipping' + pId);
	var html = GetNodeValue (xml, 'data/html', 1);	
	
	showPopupFromHtml(html, (findPosX(oObj) + oObj.offsetWidth - 440) + 'px', (findPosY(oObj) + oObj.offsetHeight + 3) + 'px', '30em', 'auto')	
}

function categoryFilterClick2(oObj, bid) {
	var ns=tickClick( oObj );
	if (bid) showobj('brandlines'+bid, ns=='on'); 
		
	var oCFDiv = byId('categoryfilter');
	var oFilterDivs = oCFDiv.getElementsByTagName('div');
	
	var count = 0;
	var filter = 'filter=';
	for (var x = 0; x < oFilterDivs.length; x++)
	{
		var attrib = oFilterDivs[x].getAttribute('feid');
		if (attrib && oFilterDivs[x].className == 'ticks-g-on') {
			if (count > 0) filter += '-';
			filter += attrib;
			count++;
		}
	}
	
	var oCMC = byId('_current_main_content_');
	if (oCMC != null) {		
		if (oCMC.getAttribute('xtype') == 'category') {
			loadCategoryPage(oCMC.getAttribute('xurl')+'0', oCMC.getAttribute('xid'), filter);
		}
	}
}

function pfind(oArray, prefix) {
	for (var i = 0; i < oArray.length; i++) {
		if ( oArray[i].indexOf(prefix) == 0 ) return i;
	}
	return -1;
}

function cfilter(oObj, bid) {
	var ns=tickClick( oObj );
	if (bid) showobj('brandlines'+bid, ns=='on'); 
		
	var oCFDiv = byId('categoryfilter');
	var oFilterDivs = oCFDiv.getElementsByTagName('div');
	
	var brands = new Array();
	var filters = new Array();
	for (var x = 0; x < oFilterDivs.length; x++)
	{
		if (oFilterDivs[x].className != 'ticks-g-on') continue;
		var type = oFilterDivs[x].getAttribute('ftype');
		var parent = oFilterDivs[x].getAttribute('fparent');
		var value = oFilterDivs[x].getAttribute('feid');
		if (type=='brand') {
			if ( pfind( brands, value ) == -1 ) brands.push( value );
		} else if (type=='line') {
			var ix = pfind(brands, parent);
			if ( ix != -1 ) {
				if ( brands[ ix ] == parent ) brands[ ix ] += '~'+value;
				else brands[ ix ] += '-or-'+value;
			}
		} else if (type=='for') {
			var ix = pfind( filters, parent );
			if ( ix == -1 ) filters.push( parent+'~'+value );
			else filters[ ix ] += '-or-'+value;
		} else if (type=='fand') {
			var ix = pfind( filters, parent );
			if ( ix == -1 ) filters.push( parent+'~'+value );
			else filters[ ix ] += '-and-'+value;
		}
	}

	var filter='';
	for (var i = 0; i < brands.length; i++) {
		if ( filter != '' ) filter += '+';
		filter += brands[i];
	}
	if (brands.length) filter += '/';
	for (var i = 0; i < filters.length; i++) {
		filter += filters[i]+'/';
	}

	var oCMC = byId('_current_main_content_');
	if (oCMC != null) {		
		if (oCMC.getAttribute('xtype') == 'category') {
			var udata = oCMC.getAttribute('xuser');
			var subcat = '';
			if ( udata.match('^s:') ) subcat = '/'+udata.substr( 2 );
			loadm( oCMC.getAttribute('xurlbase')+subcat+'/'+filter+'0' );
		}
	}
}

function tickClick2( aId, aGroupId, on, prefix ) {
	var oInput = byId( aId );
	var oTick = byId( aId + '-tick' );
	var oGroup = byId( aGroupId );

	var classNameParts = oTick.className.split('-');
	var newClassName = classNameParts[0] + '-';
	var newState = '';
	
	if ( on != null ) newState = on ? "on" : "off";
	else newState = classNameParts[1] == "on" ? "off" : "on";
	newClassName += newState;
	
	if ( oInput ) oInput.checked = newClassName == classNameParts[0] + '-on';

	if ( oGroup && newState == "on" ) {
		var oDivs = oGroup.getElementsByTagName('div');
		for (var i = 0; i < oDivs.length; i++) {
			var iid = oDivs[i].getAttribute('id');
			var childClassNameParts = oDivs[i].className.split('-');
			if ( childClassNameParts[1] == 'on' ) {
				if ( prefix && !iid.match( new RegExp(prefix) ) ) continue;	
				oDivs[i].className = classNameParts[0] + '-off';
				var aTickId = oDivs[i].id;
				aTickId = aTickId.replace( /-tick$/, '' );
				oInput = byId( aTickId );
				if ( oInput ) oInput.checked = false;
			}
		}
	}  
	oTick.className = newClassName;
	return newState == 'on';
}

function tickClick(oTick, newState, group, prefix, hsuffix) {
	if (typeof(oTick) == "string") oTick = byId(oTick);
	if (oTick.getAttribute('edit') == "false") return false;	
	var classNameParts = oTick.className.split('-');
	var newClassName = classNameParts[0] + '-' + classNameParts[1] + '-';
	if (newState != null) {
		newState = newState ? "on" : "off";
		newClassName += newState;
	} else {
		newState = classNameParts[2] == "on" ? "off" : "on";
		newClassName += newState;
	}
	if (group) {
		var oGroup = byId(group);			
		var oDivs = oGroup.getElementsByTagName('div');
		for (var i = 0; i < oDivs.length; i++) {
			if (oDivs[i].getAttribute('type') == 'tick' && oDivs[i].id != oTick.id) {
				if ( prefix ) {
					var idParts = oDivs[i].id.split('-');
					if ( idParts[0] != prefix ) continue;
				}
				if ( hsuffix ) {
					var hobj = byId(oDivs[i].id + '-' + hsuffix);
					if ( hobj ) hideobj(hobj);
				}
				var clsName = classNameParts[0] + '-' + classNameParts[1] + '-off';
				oDivs[i].className = clsName;
			}
		}
	}
	oTick.className = newClassName;
	return newState;
}

function tickOps(group, op, callback, prefix) {
	var oGroup = byId(group);
	var oDivs = oGroup.getElementsByTagName('div');
	for (var i = 0; i < oDivs.length; i++) {
		if (oDivs[i].getAttribute('type') == 'tick') {
			if ( prefix ) {
				var idParts = oDivs[i].id.split('-');
				if ( idParts[0] != prefix ) continue;
			}
			var classNameParts = oDivs[i].className.split('-');
			var newClassName = classNameParts[0] + '-' + classNameParts[1] + '-';
			switch( op )
			{
			case 1: newState = 'on'; break;
			case 2: newState = 'off'; break;
			case 3: newState = (classNameParts[2] == "on" ? "off" : "on"); break;
			}
			if ( newState != classNameParts[2] ) {
				oDivs[i].className = classNameParts[0] + '-' + classNameParts[1] + '-' + newState;
				if ( callback ) callback(oDivs[i], newState);
			}
		}
	}
}

function getTicked(group) {
	var oGroup = byId(group);
	var oDivs = oGroup.getElementsByTagName('div');
	for (var i = 0; i < oDivs.length; i++) {
		if (oDivs[i].getAttribute('type') == 'tick') {
			var classNameParts = oDivs[i].className.split('-');
			if ( classNameParts[2] == "on" ) return oDivs[i];
		}
	}
	return null;
}

function tickGetValue(oTick) {
	var classNameParts = oTick.className.split('-');
	return classNameParts[2] == "on";
}

function makeEditable(aEditDiv, aSaveDiv, aForm, aOps, aTarget, aBlockDiv, aErrorDiv) {
	var oForm = byId(aForm);
	var oEditDiv = byId(aEditDiv);
	var oSaveDiv = byId(aSaveDiv);
	
	var oForm = byId(aForm);
	var oSpans = oForm.getElementsByTagName('span');
	var oInputs = oForm.getElementsByTagName('div');
	
	if (aOps == 1) {
		oEditDiv.style.display = 'none';
		oSaveDiv.style.display = 'block';
		for (var i = 0; i < oSpans.length; i++) {
			oSpans[i].style.display = 'none';
		}

		var oIndex = 0;
		for (var i = 0; i < oInputs.length; i++) {
			if (oInputs[i].getAttribute('type') == 'ctl') {
				oInputs[i].style.display = 'block';				
				if (oIndex++ == 0) {
					var aChildrens = oInputs[i].getElementsByTagName('input');
					if (aChildrens.length > 0) {
						aChildrens[0].focus();
					}
				}
			} else if (oInputs[i].getAttribute('type') == 'tick') {
				oInputs[i].setAttribute("edit", "true");
			}
		}
	} else if (aOps == 2) {
		oEditDiv.style.display = 'block';
		oSaveDiv.style.display = 'none';
		var temp = new Object();
		for (var i = 0; i < oSpans.length; i++) {
			oSpans[i].style.display = 'block';
			temp[oSpans[i].id] = oSpans[i].innerHTML;
		}
		
		for (var i = 0; i < oInputs.length; i++) {
			if (oInputs[i].getAttribute('type') == 'ctl') {
				oInputs[i].style.display = 'none';
				var aChildrens = oInputs[i].getElementsByTagName('input');
				if (aChildrens.length > 0) {
					if (temp[aChildrens[0].id] != 'n/a') aChildrens[0].value = temp[aChildrens[0].id];
				}
			} else if (oInputs[i].getAttribute('type') == 'tick') {
				tickClick(oInputs[i], oInputs[i].getAttribute("value") == "on" );
				oInputs[i].setAttribute("edit", "false");
			}
		}
	} else if (aOps == 0) {
		var formData = getFormData(aForm);
		doAjax(aTarget, aBlockDiv, formData, aBlockDiv, aErrorDiv, 1)
	}
}

function formatNumber(n,d,c,s) 
{
	if ( n == 0 ) return c+'0.00';
	var x = Math.round(n * Math.pow(10,d));
	var neg=x>=0? '':'-';
	var y = (''+Math.abs(x)).split('');
	var z = y.length - d;
	y.splice(z, 0, '.');
	while (!s && z > 3) { z-=3; y.splice(z,0,','); }
	return (c+neg+y.join(''));
}

function recalcFromQty(sform, pqty, piprice, pitotal, gtotal, func) {
	var total = 0.0;
	var oForm = byId(sform);
	for(var i = 0; i < oForm.elements.length; i++)
	{
		if ( oForm.elements[i].type != 'text' ) continue;
		var pieces = oForm.elements[i].id.split('-');
		if ( pieces.length < 2 || pieces[0] != pqty ) continue;

		var qty = parseInt(oForm.elements[i].value);
		if (isNaN(qty) || qty < 0) qty = 0;
		var price = parseFloat(byId(piprice+'-'+pieces[1]).innerHTML);
		if (isNaN(price) || price < 0) price = 0;
		
		var oITotal = byId(pitotal+'-'+pieces[1]);
		if ( oITotal ) oITotal.innerHTML = formatNumber(qty*price, 2, 'R ');
		
		total += roundMoney(qty*price);
	}
	var oGTotal = byId( gtotal );
	if ( oGTotal ) oGTotal.innerHTML = formatNumber(total, 2, 'R ');
	
	if ( typeof(func) == "function" ) func();
	
	return total;
}

function recalcCart(oQty, oNode) {
	var oPL = byId('prod-list');
	if ( !oPL ) return;
	
	if (oQty) {
		var oSpan = oNode.getElementsByTagName('span');
		if (oSpan.length == 2) {
			var oPrice = oSpan[0];
			var oTotal = oSpan[1];
			
			var price = parseFloat(oPrice.getAttribute('price'));
			var total = price * parseFloat(oQty.value);
			if (isNaN(total) || total < 0) return;
			oTotal.innerHTML = formatNumber(total, 2, 'R ');
		}
	}
	
	var total = 0.0;
	var totalex = 0.0;
	var items = 0;
	for (var i = 0; i < oPL.childNodes.length; i++) {
		if (oPL.childNodes[i].tagName == 'DIV' && oPL.childNodes[i].getAttribute('type') == 'product' && oPL.childNodes[i].style.display != 'none') {
			for (var j = 0; j < oPL.childNodes[i].childNodes.length; j++) {
				if (oPL.childNodes[i].childNodes[j].className == "price") {
					var oSpan = oPL.childNodes[i].childNodes[j].getElementsByTagName('span');
					var oInput = oPL.childNodes[i].childNodes[j].getElementsByTagName('input');
					var price = parseFloat(oSpan[0].getAttribute('price'));
					var priceex = parseFloat(oSpan[0].getAttribute('priceex'));
					var qty = parseInt(oInput[0].value);
					total += price * qty;
					totalex += priceex * qty;
					items++;
				}
			}
		}
	}
	if ( items == 0 ) {
		hideobj('cart-extra-info');
		hideobj('cart-div');
		showobj('cart-empty-div');
		return;
	}
	var shipTotal = parseFloat(byId('shipping-option-cost').value);
	
	byId('total-goods').innerHTML = formatNumber(totalex, 2, 'R ');
	byId('total-goods-vat').innerHTML = formatNumber(total - totalex, 2, 'R ');
	byId('total-goods-inc').innerHTML = formatNumber(total, 2, 'R ');
	byId('cart-total').innerHTML = formatNumber(total, 2, 'R ');
	byId('shipping-total').innerHTML = formatNumber(shipTotal, 2, 'R ');
	byId('grand-total').innerHTML = formatNumber(total+shipTotal, 2, 'R ');
	//byId('total-grand').innerHTML = formatNumber(total, 2, 'R ');
	var oShipping = byId('total-shipping');
	if (oShipping) {
		oShipping.style.display = 'none';
		byId('total-shipping-recalc').style.display = 'block';
	}
}

function removeFromCart(id){
	doAjax('/account/removefromcart?m=x&id='+id, 
		new Function("xml", "{ var oDiv = byId('cartitem"+id+"'); if(oDiv) { oDiv.style.display='none'; recalcCart(); } doAjax('/account/rendercart?m=x', 'cart-content-block'); }")
	);
}

function removeFromWList(id){
	doAjax('/account/removefromwlist?m=x&id='+id, 
		new Function("xml", "{ var oDiv = byId('wlistitem"+id+"').style.display='none'; }")
	);
}

function getCartQuantities(){
	var data = '';
	var oPL = byId('prod-list');	
	for (var i = 0; i < oPL.childNodes.length; i++) {
		if (oPL.childNodes[i].tagName == 'DIV' && oPL.childNodes[i].getAttribute('type') == 'product' && oPL.childNodes[i].style.display != 'none') {
			for (var j = 0; j < oPL.childNodes[i].childNodes.length; j++) {
				if (oPL.childNodes[i].childNodes[j].className == "price") {
					var oInput = oPL.childNodes[i].childNodes[j].getElementsByTagName('input');
					if (oInput.length==0) continue;
					var qty = parseInt(oInput[0].value);
					if (data != '') data += '&';
					data += oInput[0].name + '=' + oInput[0].value;
				}
			}
		}
	}
	return data;
}

function cloneDiv(aParent) {
	var oParent = byId(aParent);
	
	var oClonable = null;
	for (var j = oParent.childNodes.length - 1; j >= 0; j--)
	{
		if (oParent.childNodes[j].getAttribute && oParent.childNodes[j].getAttribute('clonable') == 'yes')
		{
			oClonable = oParent.childNodes[j];
			break;
		}
	}
	
	var oClone = oClonable.cloneNode(true);
	var oInputs = oClone.getElementsByTagName('input');
	
	for (var i = 0; i < oInputs.length; i++)
	{
		if (oInputs[i].type != 'text' ) continue;
		var sindex = oInputs[i].id.indexOf ("-");
		var nextId = parseInt(oInputs[i].id.substr (sindex + 1)) + 1;
		oInputs[i].id = oInputs[i].id.substr (0, sindex) + '-' + nextId;
		oInputs[i].name = oInputs[i].id;
	}
	oParent.appendChild(oClone);
}

function show(element, s) {
	var oObj = element;
	if (typeof (element) == "string") {
		oObj = byId(element);
	} 
	if (typeof(oObj) != "undefined") {
		if (s != null) oObj.style.display = s;
		else oObj.style.display = oObj.style.display == 'none' ? 'block' : 'none';
	}
}


var tableOpsAjaxObj = null;
var tableOpsAjax = new Asynchronous();
tableOpsAjax.complete = function (user, status, statusText, responseText, responseXML) {
//	alert (responseText);
	var xml = ParseXML (responseText);
	if (GetNodeValue (xml, 'data/result/code') == 0)
	{
		if (GetNodeValue (xml, 'data/op') == 'a') {
			tableOpsAjaxObj.innerHTML += GetNodeValue (xml, 'data/html', 1);
			var oDiv = byId( tableOpsAjaxObj.id + '-div' );
			if ( oDiv ) oDiv.style.display = 'block';
		}
		else if (GetNodeValue (xml, 'data/op') == 'd') {
			tableOpsAjaxObj.parentNode.removeChild (tableOpsAjaxObj);
		}
		else {
			tableOpsAjaxObj.innerHTML = GetNodeValue (xml, 'data/html', 1);
		}
	}
	else
	{
		alert (GetNodeValue (xml, 'data/result/msg', 1));
	}
}			

function editTableRowExecute (oForm, sUrl) {
	var data = null;
	if (oForm != null) {
		sUrl = oForm.action;
		data = getFormData (oForm.id);
		showComponent(null, oForm.parentNode.id, 0, 1);
 	}
	tableOpsAjax.call("POST", sUrl, data);
}			

function editTableRow (oObj, sOp, sTarget, sFormDiv, sPrefix) {
	if (typeof (oObj) == "string") oObj = byId(oObj);
	tableOpsAjaxObj = oObj;
	var sUrl = urlAppendParam (sTarget, 'm=x&op=' + sOp);
	if ((sOp == 'u' || sOp == 'a') && sFormDiv != null) {
		var oFormDiv = byId(sFormDiv);
		var oForms = oFormDiv.getElementsByTagName ('form');
		var oForm = oForms[0];
	
		if (sOp == 'u') {
			var nId = oObj.getAttribute ('itemid');	
			sUrl = urlAppendParam (sUrl, 'id=' + nId);
		}
		var oCells = oObj.getElementsByTagName ('td');
		for (var i = 0; i < oCells.length; i++) {
			var name = oCells[i].getAttribute ('cname');
			if (typeof(name) != "undefined") {
				var oCtrl = byId(sPrefix + '_' + name);
				if (typeof(oCtrl) != "undefined") {
					oCtrl.value = sOp == 'u' ? oCells[i].innerHTML : '';
				}
			}
		}
		oForm.action = sUrl;	
		showComponent (oObj, sFormDiv, 1, 1);
	} else if (sOp == 'd' || sFormDiv == null) {
		var nId = oObj.getAttribute ('itemid');	
		sUrl = urlAppendParam (sUrl, 'id=' + nId);
		editTableRowExecute (null, sUrl);
	}
}

function changeFont(oObj, nSize) {
	var oDivs = byTag(byId('font-selector'), 'div');
	for (var i = 0; i < oDivs.length; i++) {
		oDivs[i].className='grey-square-6';
	}
	document.body.style.fontSize=nSize+'em'; 
	oObj.className='red-square-6';
	doAjax('/user/fsizechange?m=x&fsize='+nSize);
}

function showScratchpad(bShow) {
	var oSp = byId('frame-scratchpad');
	var oCon = byId('frame-middle-center');
	
	oCon.style.styleFloat='left';
	oCon.style.marginRight='15em';
	oSp.style.display='block';
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
			alert(ca[i]);
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function formsubmit(e, obj) {
	var keynum;
	if(window.event){keynum = e.keyCode;}else {if(e.which)keynum = e.which;}
	if (keynum==13) { obj.click();	return false; }
	return true;
}


function getTickSelection( sParent, prefix, separator, input )
{
	if ( separator == null ) separator = ',';
	
	var oParent = byId( sParent );
	if ( oParent == null ) return '';
	
	var str = "";

	var oDivs = oParent.getElementsByTagName('div');
	for (var i = 0; i < oDivs.length; i++) {
		if ( oDivs[i].getAttribute('type') == 'tick' ) {
			var name  = oDivs[i].id;
			if ( name.match(new RegExp("^" + prefix + "")) )
			{
				var oValue = tickGetValue( oDivs[i] );
				if ( oValue ) 
				{
					var sId = name.replace(new RegExp("^" + prefix), "");
					if ( str.length ) str += separator;
					str += sId;
					
					if ( input ) {
						var sInput = name.replace(new RegExp("^" + prefix), prefix+input);
						if ( byId(sInput) ) {
							str += ':' + byId(sInput).value;
						}
					}
				}
			}
		}
	}
	return str;
}

function setRowBgColor( sTable, sColor ) {
	var oTable = byId( sTable );
	for ( var i = 0; i < oTable.rows.length; i++ ) {
			oTable.rows[i].style.backgroundColor = sColor;
	}
}

function showcompare() {
	showobj('frame-scratchpad'); 
	showobj('sp-compare');
}

function getSearchStriing( form, ctrl ) {
	var search = getFormItem( form,  ctrl );
//	search = search.replace(/\//g,"%2F");
//	search = search.replace(/\+/g,"%2B");
	search = search.replace(/[ \n\t]/g,"+");
	return search;
}

function setTableCell( table, row, cell, value ) {
	var oTable=byId(table);
	for(var r=0; r<oTable.rows.length; r++) {
		if(oTable.rows[r].id==row) {
			for(var c=0; c<oTable.rows[r].cells.length; c++) {
				if(oTable.rows[r].cells[c].id==cell) {
					oTable.rows[r].cells[c].innerHTML=value;
					return;
				}
			}
			return;
		}
	}
}

function delTableRow( table, row ) {
	var oTable=byId(table);
	for(var r=0; r<oTable.rows.length; r++) {
		if(oTable.rows[r].id==row) {
			oTable.deleteRow(r);
			return;
		}
	}
}

function makeLinkActive(div, link) {
	var links = byTag(div, 'A');
	for (var i = 0; i < links.length; ++i) {
		links[i].style.fontWeight='normal';
	}
	link.style.fontWeight='bold';
}

function productInfo(link, url, target) {
	var pmenu = byId('product-menu');
	var links = byTag(pmenu, 'A');
	for (var i = 0; i < links.length; ++i) {
		links[i].style.fontWeight='normal';
	}
	link.style.fontWeight='bold';
	swapDivs('product-details', target); 
	if (url!=null) doAjax(url, target, null, target);
}

function showrating(item) {
	for (var i = 0; i < 5; i++ ) {
		var sel = item >= 0 && i <= item;
		var newsrc = sel ? 'diamondo.gif' : 'diamondg.gif';
		byId('selrat'+i).src='/img/icon/'+newsrc;
	}
}

function showrating2(item) {
	for (var i = 0; i < 5; i++ ) {
		var sel = item >= 0 && i <= item;
		var newsrc = sel ? 's_star_o.png' : 's_star_g.png';
		byId('selrat'+i).src='/img/icon/'+newsrc;
	}
}

function reloadm() {
	var x=byId('thispage');
	if (!x) x=byId('_current_main_content_');
	if (x) loadm(x.getAttribute('xmainurl') ? x.getAttribute('xmainurl') : x.getAttribute('xurl'));
	return false;
}

function reloadm_nr() {
	var x=byId('thispage');
	if (!x) x=byId('_current_main_content_');
	if (x) loadm(x.getAttribute('xmainurl') ? x.getAttribute('xmainurl') : x.getAttribute('xurl'), null, null, { noscroll:true }, LMS_FLAG_NOPROGRESS);
	return false;
}

function insertTAC( obj, text ) {
    var tArea = obj;
    var isIE = (document.all)? true : false;
    if(isIE){
        tArea.focus();
        var curSelect = document.selection.createRange();
          curSelect.text = text;
    } else /*if(!isIE && typeof tArea.selectionStart != "undefined")*/{
        var selStart = tArea.value.substr(0, tArea.selectionStart);
        var selEnd = tArea.value.substr(tArea.selectionEnd, tArea.value.length);
        var curSelection = tArea.value.replace(selStart, '').replace(selEnd, '');
          tArea.value = selStart + text + selEnd;
    } //else {
//        tArea.value += (arguments[2])? open + arguments[2] + "]" + end : open + end;
//    }
}

function showload(id,text) {
	if (!text) text = 'loading ...';
	showobj(id);
	byId(id).innerHTML = 'loading ...'; 
}

function findObjects(parent, tag, prefix, attrib, val) {
	var objs = new Array();
	if (parent) {
		var oGroup = byId(parent);			
		var oObjs = oGroup.getElementsByTagName(tag);
		for (var i = 0; i < oObjs.length; i++) {
			if (prefix) if (oObjs[i].id.search(prefix) == 0) objs.push(oObjs[i]);
			else if (oObjs[i].getAttribute(attrib) == val) objs.push(oObjs[i]);
		}
	}
	return objs;
}

function _highlight(obj,bg,tx,bt,br,bb,bl) {
	if (typeof(obj) == 'string') obj = byId(obj);
	if (bg) obj.style.backgroundColor=bg;
	if (tx) obj.style.color=tx;
	if (bt) obj.style.borderTop=bt;
	if (br) obj.style.borderRight=br;
	if (bb) obj.style.borderBottom=bb;
	if (bl) obj.style.borderLeft=bl;
}

function highlight(obj,bg,tx,bt,br,bb,bl) {
	if ( obj instanceof Array ) {
		for (var i = 0; i < obj.length; i++) 
			_highlight(obj[i],bg,tx,bt,br,bb,bl);
	} else {
		_highlight(obj,bg,tx,bt,br,bb,bl);
	}
}

String.prototype.trim = function(w) {
	if (!w) w = '\\s*';
    return this.replace(new RegExp("^"+w), "").replace(new RegExp(w+"$"), "");
}

function refreshCoShipping(showmsg) {
	var code = byId('spostalcode').value; 
	if (code.match('^\\d\\d\\d\\d$')) { 
		var acobj=byId('areacode'); 
		var soobj=byId('shipping-option');
		if (acobj && acobj.value==code) return; 
		hideobj('shipping-block-alter'); 
		showobj('shipping-block2'); 
		doAjax('/account/checkoutops?m=x&mode=refreshcartshipping2', function(x,a) { byId('shipping-block2').innerHTML=GetNodeValue(x,'data/html',1); recalcCheckoutAmounts(); }, 'areacode='+code+'&shipping-option='+(soobj?soobj.value:''), 'shipping-block2'); 
	} else { 
		showobj('shipping-block-alter'); 
		hideobj('shipping-block2'); 
		byId('shipping-block2').innerHTML=''; 
		if (showmsg) alert('Please specify the 4-digit Shipping Address Code, like 0002 or 2196.');
	}
}

function recalcCheckoutAmounts() {
	var soc = byId('shipping-option-cost'); 
	var st = byId('shipping-total'); 
	if (soc && st) setNumber('shipping-total', parseFloat(soc.value));
	var gtotal = calc( 'grand-total', [ 'shipping-option-cost', '+', [ 'cart-total', '+', 'extraitems-total' ] ] );
	var dt = byId('discount-total'); 
	if ( dt ) gtotal -= value( 'discount-total' );
	calc( 'net-total', [ gtotal, '-', [ 'voucher-total', '+', [ 'nbucks-total', '+', 'cashaccount-total' ] ] ] );
}

function value( arg ) {
	if ( typeof(arg) == "number" ) return arg;
	if ( typeof(arg) == "string" ) {
		var oObj = byId( arg );
		if ( !oObj ) { return 0; }
		var val = 0;
		if ( oObj.tagName == 'INPUT' ) { val = parseFloat( oObj.value.replace(/([R ,]|&nbsp;)/g, '') ); }
		else { var attr = oObj.getAttribute('value'); if ( attr ) { val = parseFloat( attr.replace(/([R ,]|&nbsp;)/g, '') ); } else { val = parseFloat( oObj.innerHTML.replace(/([R ,]|&nbsp;)/g, '') ); } }
		return isNaN(val) ? 0 : val;
	}
	if ( typeof(arg) == "object") {
		return _calc( arg[0], arg[1], arg[2] );
	}
	return 0;
}

function _calc( a1, op, a2 ) {

	var a1v = value( a1 );
	var a2v = value( a2 );
	var val = 0;	
	if ( op == '+' ) val = a1v + a2v;
	else if ( op == '-' ) val = a1v - a2v;
	else if ( op == '*' ) val = a1v * a2v;
	else if ( op == '/' ) val = a1v / a2v;
//	alert(val + '=[' + a1v + ']' + op + '[' + a2v + ']' );
	return val;
}

function calc( target, data ) {
	var result = _calc( data[0], data[1], data[2] );
	setNumber( target, result );
	return result;
}

function setNumber( target, value ) { 
	if (isNaN(value) || !isFinite(value)) value = 0;
	if ( target ) {
		var oT = byId(target);
		if ( oT )  {
			if ( oT.tagName == 'INPUT' ) oT.value = formatNumber(value, 2, '', true);
			else oT.innerHTML = formatNumber(value, 2, 'R ');
		}
	}
}

function sum(sdiv, stype, sprefix, starget, scond) {
	var oSource = byId(sdiv);
	var oTarget = byId(starget);
	var aObjs = oSource.getElementsByTagName(stype);
	var total = 0;
	for ( var i = 0; i < aObjs.length; i++ ) {
		if ( aObjs[i].id ) {
			var pieces = aObjs[i].id.split('-');
			if ( pieces[0] != sprefix ) continue;
			if ( scond ) {
				var sel = byId(scond + '-' + pieces[1]);
				if ( sel && !tickGetValue(sel) ) continue;
			}
			if (stype == 'INPUT') total += parseFloat(aObjs[i].value);
			else {
				var attr = aObjs[i].getAttribute('value');
				if ( attr ) total += parseFloat(attr);
				else total += parseFloat(aObjs[i].innerHTML.replace(/([R ,]|&nbsp;)/g, ''));
			}
		}
	}
	setNumber( starget, total );
	return total;
}

function at2el( obj ) {
	for ( var i = 0; i < obj.attributes.length; ++i ) {
		var eobj = byId( obj.attributes.item(i).nodeName );
		if ( eobj ) eobj.value = obj.attributes.item(i).nodeValue;
	}
}

function showbusy(obj, text) {
	if ( !text ) text = 'in progress ...';
	if (typeof(obj) == "string") obj = byId(obj);
	obj.innerHTML='<span style="color:#888888;">' + text + '</span>';
}

function printDiv(oname) {
	var a = window.open('','','');
	a.document.open("text/html");
	a.document.write('<head><link rel="stylesheet" href="/default.css" type="text/css"><link rel="stylesheet" href="/layout.css" type="text/css"></head><body style="font-size:0.85em;">');
	a.document.write(document.getElementById(oname).innerHTML);
	a.document.write('</body>');
	a.document.close();
}

function tickSeqSelect(tick, counter,attr) {
	var state=tickClick(tick); 
	var oSn=byId(tick.id.replace(/sel/, 'seq')); 
	var table=byId(counter); 
	if (state=='on') { 
		oSn.value=table.getAttribute(attr); 
		table.setAttribute(attr, 10+parseInt(oSn.value)); 
	} else oSn.value='';
}

function cloneRow(sTpl, sTarget) {
	var orows=byTag(byId(sTpl), 'tr'); 
	var nrow=orows[0].cloneNode(true); 
	var rows=byTag(byId(sTarget), 'tr'); 
	var cells=byTag(nrow, 'td'); 
	var fcell = null;
	var rl=rows.length;
	for(var i=0;i<cells.length;++i) {
		var inputs=byTag(cells[i],'input'); 
		for(var j=0;j<inputs.length;++j) {
			inputs[j].id+=rl;
			if (!fcell) fcell = inputs[j];
		}
		var tareas=byTag(cells[i],'textarea'); 
		for(var j=0;j<tareas.length;++j) {
			tareas[j].id+=rl;
			if (!fcell) fcell = tareas[j];
		}
		var selects=byTag(cells[i],'select'); 
		for(var j=0;j<selects.length;++j) {
			selects[j].id+=rl;
			if (!fcell) fcell = selects[j];
		}
	}
	byId(sTarget).appendChild(nrow);
	if (fcell) fcell.focus();
	return rl;
}

function getParent(o, level) {
	var p=o.parentNode;
	while(--level > 0) {
		p=p.parentNode;
	}
	return p;
}

function showOnChange(event,o) {
	var key=getKey(event); 
	if (key==8||key==32||key>40) showobj(o);
}

function tickChild(obj) {
	if(obj.firstChild.click) obj.firstChild.click(); 
	else if(obj.firstChild.onclick) obj.firstChild.onclick();
}

function estop(args) {
	if(window.event) window.event.cancelBubble=true; 
	else if(args[0]) args[0].stopPropagation();
}

var borderFlashObject = null;
var borderPreserveOld = null;
var borderFlashCount = 0;

function borderFlash() {
	if ( !borderFlashCount || borderFlashCount % 2 ) borderFlashObject.style.border = borderPreserveOld;
	else borderFlashObject.style.border='1px solid blue';
	if (borderFlashCount--) setTimeout( "borderFlash()", 400 );
}

function scrollAndFlash(obj) {
	if (typeof(obj) == "string") obj = byId(obj);
	borderFlashObject = obj;
	obj.scrollIntoView();
	borderPreserveOld = obj.style.border;
	//obj.style.border='1px solid blue';
	borderFlashCount = 5;
	//setTimeout( "borderFlash()", 400 );
}

function loadProductImage(sTarget, pid, iid, mtop) {
	var pheight=byId('imageload-progress').style.height.replace( /px$/, '' ) / 2 - 10;
	var pdata=['imageload-progress', 'loading ...', pheight+'px', 'display:inline-block; vertical-align:middle; background-color:white; padding:0.3em; font-size:0.8em; border:1px solid #CCCCCC;']; 
	doAjax('/pactions/ops?m=x&mode=getproductimage', sTarget, 'pid='+pid+'&iid='+iid, pdata); 
	var mid=byId(sTarget); 
	byId('pimage-'+mid.getAttribute('ciid')).style.border='1px solid #CCCCCC'; 
	mid.setAttribute('ciid',iid); 
	byId('pimage-'+iid).style.border='2px solid black';
}

function getProductLink(pid,name) {
	return '/buy~p'+pid;
}

function startRefresh( url, target, params, isec, progress, ftoken ) {
	doAjax( url, autoRefresh, params, progress, null, 2, { url: url, target: target, params: params, isec: isec, ftoken: ftoken } ); 
}

function autoRefresh( xml, args ) {
	var cont = GetNodeValue( xml, 'data/continue' );
	byId( args.target ).innerHTML = GetNodeValue( xml, 'data/html', 1 );
	if ( cont != '0' ) doAjax( args.url, autoRefresh, args.params, args.progress, null, 2, { url: args.url, target: args.target, params: args.params, isec: args.isec, ftoken: args.ftoken } ); 
	else if ( args.ftoken ) execToken( args.ftoken, xml, args );
}

function execJS( source ) {
	var scripts = new Array();
    while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
    	var s = source.indexOf("<script");
    	var s_e = source.indexOf(">", s);
    	var e = source.indexOf("</script", s);
    	var e_e = source.indexOf(">", e);
    	scripts.push(source.substring(s_e+1, e));
    	source = source.substring(0, s) + source.substring(e_e+1);
	}
	for(var x=0; x<scripts.length; x++) {
		try {
		    eval(scripts[x]);
		} catch( ex ) {
		}
	}
}

function elementInViewport(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;
  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }
  return (
    top >= window.pageYOffset &&
    left >= window.pageXOffset &&
    (top + height) <= (window.pageYOffset + window.innerHeight) &&
    (left + width) <= (window.pageXOffset + window.innerWidth)
  );
}

