var cartim = new Image;
cartim.src = '/img/related/cart_added.gif';
var gl_last_pid = '';
var gl_issort = false;
var gl_cartscript = '/tools/add2cart.php?';
var gl_relscript = '/tools/related_books.php?';
var gl_action = '';
var gl_backorder = false;
var gl_wheight = 950;
var gl_addtail = false;
var gl_id = '{$parent_id}';
var gl_cid = '';
var gl_root = '{$parent_id}';
var gl_lastsort = 'name';
var gl_deps_fixed = false;
var gl_class_id = 0;
var gl_lastLoc = '';
var cur_dep = 0;
var chisbn = {};
function showMenu(item, stat) {
    if (stat == 'on') {
        setClass(item+'_2', 'menu_on');
        setImage(item+'_1', './img/subtable_l_u.gif');
        setImage(item+'_3', './img/subtable_r_u.gif');
    }
    if (stat == 'off') {
        setClass(item+'_2', 'menu_off');
        if (item == 'co') setImage(item+'_1', './img/subtable_l_d_first.gif');
            else    setImage(item+'_1', './img/subtable_l_d.gif');
        setImage(item+'_3', './img/subtable_r_d.gif');
    }
}

function setImage(obj, adr) {
    el = document.getElementById(obj);
    if (el) {
        el.src = adr;
    }
}

function setClass(obj, cn) {
	el = document.getElementById(obj);
	if (el) {
		el.className = cn;
	}
}

function closeLayer(nam) {
	enabled = true;
	showWait(false);
	var el = document.getElementById('grelBooks');
	el.innerHTML = '';
}

function doSort(cid, stype) {
	showWait(true);
	gl_action = 'classes';
	gl_lastsort = stype;
	
	send('tool.php?action=classes&id='+cid+'&sort='+stype);
}

function goBackorder(pid) {
	gl_backorder = true;
	goCart(pid);
	gl_backorder = false;
	return false;
}

function goCart(pid, is_rental) {
	showWait(true);
	partner = pid.toString().substring(0, 1);
	if (partner == 'a') {
		pid = pid.substring(1, pid.length);
		partner = '&partner=alibris';
	} else {
		partner = '';
	}
	gl_action = 'cart';
	gl_last_pid = pid;
	rentstr = '';
	
	if (is_rental !== undefined) {
		if (!isNaN(parseFloat(is_rental))) {
			rentstr = '&order_type=rental' + is_rental;
			gl_last_pid += 'r'; // to change rental's button to "added", instead of usual button
		} else if (is_rental === 'mp_rental') {
			var val = document.getElementById('sel'+pid);
			if ((val != "undefined") && (val != null)) {
				rentstr = val.value == 0 ? '' : '&order_type=rental' + val.value;
			}
			gl_last_pid += 'r'; // to change rental's button to "added", instead of usual button
		}
	}
	
	send(gl_cartscript+'id='+pid+partner+rentstr+"&backordered="+gl_backorder.toString());
	return false;
}

function goDep(did) {
	showWait(true);
	gl_action = 'deps';
	gl_id = did;
	gl_cid = 0;
	gl_deps_fixed = false;
	showMenu('bo', 'off');
	showMenu('co', 'off');
	showMenu('pro', 'off');
	send('tool.php?action=deps&id='+did);
}

function goClasses(cid, sort, page) {
	showMenu('course');
	gl_action = 'classes';
	flag = true;
    gl_addtail = cid ? false : true;
	gl_deps_fixed = false;
	
	if ((sort == "undefined") || (sort == "")) sort = 'name';
	gl_lastsort = sort;
	
	if (cid) {
		gl_class_id = cid;
		gl_addtail = true;
		if (sort != '_instructor_') {
			gl_cid = cid;
			showMenu('co', 'on');
			//showPanel('pan_dep');
		} else {
			if (page == '') {
				alert('empty code');
				flag = false;
			}
			showMenu('co', 'off');
		}
		showMenu('bo', 'off');
		showMenu('pro', 'off');
		if (flag) {
			showWait(true);
			send('tool.php?action=classes&id='+cid+'&sort='+sort+'&page='+page);
		}
	} else {
		showMenu('bo', 'off');
		showMenu('co', 'on');
		showMenu('pro', 'off');
		if (gl_cid) cid = gl_cid; else cid = gl_id;
		showWait(true);
		send('tool.php?action=classes&id='+cid+'&sort='+sort+'&page='+page);
	}
}

function goProfessors(id, sort, page) {
	if (!id) return false;
	showMenu('bo', 'off');
	showMenu('co', 'off');
	showMenu('pro', 'on');
	gl_action = 'instructors';
	showWait(true);
	send('tool.php?action=instructors&id='+id+'&sort='+sort+'&page='+page);
}

function goAdmins(id, sort, page) {
	if (!id) return false;
	showMenu('bo', 'off');
	showMenu('co', 'off');
	showMenu('pro', 'on');
	gl_action = 'admins';
	showWait(true);
	send('tool.php?action=admins&id='+id+'&sort='+sort+'&page='+page);
}

function goBooks(bid, page) {
	gl_action = 'books';
	gl_deps_fixed = false;
	
	if (bid) {
		showMenu('bo', 'off');
		showMenu('co', 'off');
		showMenu('pro', 'off');
		showWait(true);
		send('tool.php?action=books&cid='+bid+'&page='+page);
	} else {
		showWait(true);
		if (gl_cid) di = gl_cid; else di = gl_id;
		send('tool.php?action=books&id='+di+'&page='+page);
		showMenu('bo', 'on');
		showMenu('co', 'off');
		showMenu('pro', 'off');
		//alert('Comming soon. Books  showed only if click on course (for now)');
	}
}

function fixDepsWidth() {
	if (!gl_deps_fixed) {
		var maxw = 200;
		var cldeps = $$('.cldep');
		if (cldeps.length > 3) {
			cldeps.each(function(n){
				var w = n.getWidth();
				if (w > maxw) maxw = w;
			});
		} else maxw = 500;
		
		cldeps.each(function(n){
			if (cldeps.length < 50) {
			str = findChild(n, 'a');
			str = findChild(str, 'strong');
			str.innerHTML = str.innerHTML.replace(/(^\s+)|(\s+$)/g, "");
			strw = $(str).getWidth();
			strt = str.innerHTML;
			}
			
			if (maxw > 340) {
				n.style.width = '98%';
			}
			else {
				n.style.width = maxw+'px';
			}
				
			if (cldeps.length < 50) {
			w = $(n).getWidth() + 1;//chrome req +1
			if (strw > w) {
				sbs = ((strt.length * w / strw) * 0.9).round();
				str.innerHTML = str.innerHTML.substr(0, sbs + 1) + '...';
			}
			}
		});
	}
	gl_deps_fixed = true;
}

function processCells(txt) {
	txt = str_remove("\t", txt);
	showWait(false);
	var is_merch = txt.search('is_merchandise');
	var is_overlimit = txt.search('totals_overlimit');
        if (is_overlimit != -1) {
            window.location = '/sc/?overlimit=1';
            return;
        }
	if (gl_action == 'instructors' || gl_action == 'admins') {
        var its = txt.split('-split-for-js-');
        setDiv('head', its[0]);
        dep = document.getElementById("parent_name").value;
        setDiv('dep_path', ' '+dep);
        setDiv('body', its[1]);
		showObj('body');
	}
	if (gl_action == 'related') {
		setDiv('grelBooks', txt);
	}
	if (gl_action == 'deps') {
		var its = txt.split('-split-for-js-');
		setDiv('head', its[0]);
        dep = document.getElementById("parent_name").value;
        setDiv('dep_path', ' '+dep);
        //setDiv('class_name', dep);
		document.getElementById('class_name').value = dep;
		setDiv('body', '');
		showObj('head');
		
		fixDepsWidth();
	}
	if (gl_action == 'classes') {
		var its = txt.split('-split-for-js-');
		setDiv('head', its[0]);
		dep = document.getElementById("parent_name").value;
		setDiv('dep_path', ' '+dep);
		setDiv('body', its[1]);
		tail = document.getElementById("class_name").value;     
		//setDiv('class_name', tail);
		document.getElementById('class_name').value = tail;
		if (gl_addtail) {
			setDiv('path_tail', tail);
		}
        
		showObj('body');
		//hideObj('head');

		var sorttypes = ['name', 'code', 'instructor'];
		for (var i = 0; i < sorttypes.length; i++) {
			var cs = $('sort-by-'+sorttypes[i]);
			
			if (cs) {
			if (sorttypes[i] == gl_lastsort) {
				cs.addClassName('cursort');
				cs.href = cs.href.split(sorttypes[i]).join(sorttypes[i]+"desc");
			} else if (sorttypes[i]+"desc" == gl_lastsort) {
				cs.addClassName('cursort-desc');
				cs.href = cs.href.split(sorttypes[i]+"desc").join(sorttypes[i]);
			} else {
				cs.removeClassName('cursort');
				cs.removeClassName('cursort-desc');
				cs.href = cs.href.split(sorttypes[i]+"desc").join(sorttypes[i]);
			}
		}
		}

		fixDepsWidth();

		// fix deps highlight
		var cid = gl_class_id;
		var cldeps = $$('.cldep');
		cldeps.each(function(n){
			if (n.id != 'dep'+cid) {
				n.style.display = 'none';
				n.removeClassName('inline-block');
			} else {				
				n.setStyle({
					'float': 'none',
					'display': ''
				});
				n.addClassName('currentdep');
				if(navigator.appVersion.indexOf("MSIE 9.0") > -1) {
				    n.addClassName('inline-block-ie9');
				} else {
				    n.addClassName('inline-block');
				}
				
			}
		});
		
		var cd = $('currentdep');
		if (cd) {
			cd.removeClassName('currentdep');
			$('currentdeplink').onclick = function () {
				return true;
			}
		}


	}
    if (gl_action == 'books') {
        var its = txt.split('-split-for-js-');
        if(its.length == 2) {
            setDiv('head', its[0]);
            setDiv('body', its[1]);
        } else {
            setDiv('head', '');
            setDiv('body', its[0]);
        }
        tail = document.getElementById("class_name").value;       
        //setDiv('class_name', tail); // doesn't work in IE6
		document.getElementById('class_name').value = tail;
        setDiv('path_tail', tail);
		showObj('body');
        //hideObj('head');

		fixDepsWidth();
		inp = document.getElementById('body').getElementsByTagName('input')[0];
		if (inp != undefined) inp.focus();
	}
    if (gl_action == 'cart') {
        var ars = new Array();
        ars = txt.split('|');
        if (ars[0] == 'ok' && ars[1] > 0) {
            sl = gl_backorder ? window.opener.document.getElementById('item-count') : document.getElementById('item-count');
            if (sl) sl.innerHTML = ars[1]+' item'+(ars[1].toString() == '1' ? '':'s');
            le = document.getElementById('pid_'+gl_last_pid);
            if (le) {
				setButtonInCart(le);
				hideConditions(le);
			}
            if (gl_backorder) {
                le = window.opener.document.getElementById('pid_'+gl_last_pid);
                if (le.src) le.src = backordered.src;
            }
            el = gl_backorder ? window.opener.document.getElementById('checkout_span') : document.getElementById('checkout_span');
            el.style.display = 'block';
            //alert('Book successfully added to shopping cart.');
        } else alert('Error while adding book to shopping cart. Please try again.');
		is_merch = (ars[3] == 'merchandise' ? 0: -1);
	}
	
	if (gl_action == 'einfo') {
		einfo = document.getElementById('einfodiv');
		//document.body.appendChild(einfo);
		//einfo.style.top = (document.getElementsByTagName('body')[0].scrollTop+20).toString()+'px';
		etxt = document.getElementById('eitxt');
		etxt.innerHTML = txt;

		document.getElementById('einfofade').style.display = 'block';
		einfo.style.top = '25%';//(document.body.scrollTop + (document.body.clientHeight - 400)/2).toString()+'px';
		einfo.style.left = (document.body.scrollLeft + (document.body.clientWidth - 600)/2).toString()+'px';
		einfo.style.display = 'block';

		return true;
	}

}
function setButtonInCart(obj) {
	button = findParent(obj, 'button cart');
	if (!button) return false;
	button.className = 'button incart';
	
    obj.innerHTML = 'In Cart';
	return true;
}

function showWait(flag) {
	sl = document.getElementById('lWait');
	win = getWindowSize();
	sl.style.top = ((win.height - 100) / 2) + 'px';
	sl.style.left = ((win.width - 200) / 2) + 'px';
	if (flag) {
		sl.innerHTML = "<table width=300 height=40 bgcolor=#316293 border=0 class=medium style='color:white; font-weight:bold; border:solid 0px #ffffff;  padding:0px; margin:4px'><tr><td valign=middle align=center>Please Wait <img src='img/dot.gif' width=15 height=3></td></tr></table>";
	} else {
		sl.innerHTML = '';
		if ( (gl_action == 'classes' || gl_action == 'books' ) && document.body.scrollTop > 320) 
		window.scrollTo(0,320);
	}
	if ((gl_id != gl_root) || (gl_action != '') )
		document.getElementById('featured').style.display = 'none';
	else
		document.getElementById('featured').style.display = '';
	if ((gl_action == 'deps') && (gl_id == gl_root))
		document.getElementById('featured').style.display = '';
}

function getWindowSize() {
  if( typeof( window.innerWidth ) == 'number' ) {
    return {'width':window.innerWidth, 'height':window.innerHeight};
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	  return {'width':document.documentElement.clientWidth, 'height':document.documentElement.clientHeight};
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    return {'width':document.body.clientWidth, 'height':document.body.clientHeight};
  }
}

function processFailure(code) {
	showWait(false);
}

function setDiv(did, txt) {
	if (txt == undefined) return;
	var d = document.getElementById(did);
	if (d) {
		d.innerHTML = txt;
	}
}

function showObj(obj) {
	var el = document.getElementById(obj);
	if (typeof initHoverOptions == 'function') initHoverOptions();
	if(el) {
		if (el.style.display == 'none') {
			switchExchange(obj);
			if (obj == 'body') setDiv('pan_browse', '[hide]');
			if (obj == 'head') setDiv('pan_dep', '[hide]');
			if (obj == 'dsearch') setDiv('pan_search', '[hide]');
		}
	}
}

function hideObj(obj) {
	var el = document.getElementById(obj);
	if(el) {
		if (el.style.display == 'block') {
			switchExchange(obj);
			if (obj == 'body') setDiv('pan_browse', '[show]');
			if (obj == 'head') setDiv('pan_dep', '[show]');
			if (obj == 'dsearch') setDiv('pan_search', '[show]');
		}
	}
}

function switchExchange(obj)
{
	var el = document.getElementById(obj);
	var helper = document.getElementById(obj + '-helper')
	if(el)
	{
		if(el.style.display != "block")
		{
			el.style.display = "block";
			if (helper) {
				helper.style.display = "none";
			}
		}
		else
		{
			el.style.display = "none";
			if (helper) {
				helper.style.display = "block";
			}
		}
		return el.style.display;
	}
	return false;
}


function showPanel(pn) {
	if (pn == 'pan_dep') {
		re = switchExchange('head');
		if (re == 'block') {
			setDiv(pn, '[hide]');
		} else {
			setDiv(pn, '[show]');
		}
	}
	if (pn == 'pan_browse') {
		re = switchExchange('body');
		if (re == 'block') {
			setDiv(pn, '[hide]');
		} else {
			setDiv(pn, '[show]');
		}
	}
	if (pn == 'pan_search') {
		re = switchExchange('dsearch');
		if (re == 'block') {
			setDiv(pn, '[hide]');
		} else {
			setDiv(pn, '[show]');
		}
	}
}

function goSort(isbn, sort) {
	showWait(true);
	gl_issort = true;
	gl_action = 'related';
	send(gl_relscript+'isbn='+isbn+'&sort='+sort, false);
}

function goDetail(isbn) {
	document.location.href='/detail-book-'+isbn+'.html';
}

function switchRelated(obj)
{
	var el = document.getElementById('relBooks' + obj);
	el = false;
	if(el)
	{
		if(el.style.display != "block")
		{
			el.style.display = "block";
		}
		else
		{
			el.style.display = "none";
		}
	}
	gl_curisbn = obj;
	var el = document.getElementById('grelBooks');
	el.style.top = document.body.scrollTop + (document.body.clientHeight - gl_wheight)/2
	el.style.left = 100;
	gl_action = 'related';
	showWait(true);
	gl_issort = false;
	send(gl_relscript+'isbn='+obj, false);
}

function showInstr(link) {
	var helpWin = window.open(link.href, "helpI","toolbar=no,location=no,resizable=no,status=no,scrollbars=yes,menubar=no,width=1000,height=800");
	helpWin.focus();
	return false;
}

function popNotify(upc, domain) {
	var w = window.open('/detail.php?action=notify&upc='+upc+'&type=book&domain='+domain+'&institute=','notify','width=350,height=220');
}

function popEInfo(anc) {
	isbn = (chisbn[anc.id]?chisbn[anc.id]:anc.id.substring(3,16));
	showWait(true);
	gl_action = 'einfo';
	send('/detail.php?action=notify&eInfo=true&detail_isbn='+isbn+'&type=einfo');
}

function closeEinfo() {
	document.getElementById('einfofade').style.display = 'none';
	document.getElementById('einfodiv').style.display = 'none';
}

function getTagContents(string, tag) {
	string = string.substr(string.indexOf('<' + tag + '>') + String('<' + tag + '>').length, string.length);
	string = string.substr(0, string.indexOf(String('</' + tag + '>')));
	return string;
}

function inArray(arr, val) {
	for (var i = 0; i <= arr.length - 1; i++) {
		if (arr[i] == val) return true;
	}
	return false;
}

function loadMerchandiseOptions(isbn) {
	//items = document.getElementById('optionsList' + isbn).innerHTML.toLowerCase().split(/<\/item>/i);
	items = document.getElementById('optionsList' + isbn).innerHTML.split(/<\/item>/i);
	if ((items.length > 1) && (items[items.length-1].length < 10)) items = items.slice(0, items.length - 1);

	merc = new Array();
	for (i = 0; i <= items.length - 1; i++) {
		/*
		merc[i] = new Array();
		merc[i]['isbn'] = getTagContents(items[i], 'isbn');
		merc[i]['id'] = getTagContents(items[i], 'id');
		merc[i]['size'] = getTagContents(items[i], 'size');
		merc[i]['color'] = getTagContents(items[i], 'color');
		*/
		merc[i] = {
			isbn: 	items[i].match(/<isbn>(\d+)<\/isbn>/mi)[1],
			id:	items[i].match(/<id>(\d+)<\/id>/mi)[1],
			color: 	items[i].match(/<color>(.+)<\/color>/mi)[1],
			size: 	items[i].match(/<size>(.+)<\/size>/mi)[1],
			img: items[i].match(/<image_small>(.*)<\/image_small>/mi)[1]?items[i].match(/<image_small>(.*)<\/image_small>/mi)[1]:'',
			price: 	items[i].match(/<product_price>(.+)<\/product_price>/mi)[1]
		};
	}
	return merc;
}

function merchandiseChangeSize(isbn) {
	form = document.forms['merchandiseOrder' + isbn];
	colors_list = form.elements['color'];
	size = form.elements['size'].value;
	selected_color = colors_list.value;
	merc = loadMerchandiseOptions(isbn);
	colors = new Array();

	for (var i = 0; i <= merc.length - 1; i++) {
		if (merc[i].size != size || inArray(colors, merc[i].color)) continue;
		colors[colors.length] = merc[i].color;
	}

	colors_list.options.length = 0;
	for (var i = 0; i <= colors.length - 1; i++) {
		if (document.createElement) {
			newListOption = document.createElement("OPTION");
			newListOption.text = colors[i];
			newListOption.value = colors[i];
			(colors_list.options.add) ? colors_list.options.add(newListOption) : colors_list.add(newListOption, null);
		} else {
			colors_list.options[i] = new Option(colors[i], colors[i], false, false);
		}
	}
	replaceParms(isbn, merc);
	return true;
}

function merchandiseOrder(isbn) {
	message		= false;
	size		= false;
	product_id	= false;
	form	= document.forms['merchandiseOrder' + isbn];
	image	= document.getElementById('pid_' + isbn);
	color = form.elements['color'].value;
	if (!color) message = 'Please select color.';

	size = form.elements['size'].value;
	if (!size) message = 'Please select your size.';

	if (message) {
		confirm(message);
		return false;
	}

	merc = loadMerchandiseOptions(isbn);
	for (var i = 0; i <= merc.length - 1; i++) {
		if (merc[i]['size'] == size && merc[i]['color'] == color) {
			product_id = merc[i]['id'];
		}
	}
	if (!product_id) {
		confirm('Please select color.');
	} else {
		goCart(product_id);
	}
	return false;
}

function merchandiseChangeColor(isbn) {
	replaceParms(isbn, loadMerchandiseOptions(isbn))
}

function replaceParms(isbn, merc) {
	form = document.forms['merchandiseOrder' + isbn];
	color = form.elements['color'].value;
	size = form.elements['size'].value;
	for(var i = 0; i < merc.length; i++) {
		if (merc[i]['size'] == size && merc[i]['color'] == color) {
			if (im = document.getElementById('imsmall' + isbn)) {
				if (merc[i]['img'])
					im.src = 'http://img.textbookx.com' + merc[i]['img']
				else im.src = 'http://textbookx.com/img/no_image.gif'
			}
			if (anc = document.getElementById('anc' + isbn))
				chisbn[anc.id] = merc[i]['isbn'];
			if (pprice = document.getElementById('pprice' + isbn))
				pprice.innerHTML = merc[i]['price']
			if (link = document.getElementById('link' + isbn))
				link.href = '/detail-book-'+merc[i]['isbn']+'.html'
			if (link = document.getElementById('link2' + isbn))
				link.href = '/detail-book-'+merc[i]['isbn']+'.html'
		}
	}
}

function showPermalink(id) {
	obj = document.getElementById(id);
	obj.style.visibility='visible';
	obj.select();
	return false;
}

// OuterHTML fix for FireFox
if(navigator.userAgent.toLowerCase().indexOf("gecko") != -1) {
    if (typeof(HTMLElement) != "undefined") {
    	var _emptyTags = {
    		"IMG": true,
    		"BR": true,
    		"INPUT": true,
    		"META": true,
    		"LINK": true,
    		"PARAM": true,
    		"HR": true
    	};
    	    
    	HTMLElement.prototype.__defineGetter__("outerHTML", function () {
    		var attrs = this.attributes;
    		var str = "<" + this.tagName;
    		for (var i = 0; i < attrs.length; i++)
    			str += " " + attrs[ i ].name + "=\"" + attrs[ i ].value + "\"";
            
    			if (_emptyTags[this.tagName])
    			return str + ">";
            
    			return str + ">" + this.innerHTML + "</" + this.tagName + ">";
    	});
    
    	HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {
    		var r = this.ownerDocument.createRange();
    		r.setStartBefore(this);
    		var df = r.createContextualFragment(sHTML);
    		this.parentNode.replaceChild(df, this);
    	});
    }
}

var closetimer = 0;
var menu_id = '';
	
function ddRollOver(id, event) {
	if ((menu_id != '') && (id != menu_id)) {
		ddCloseMenu(menu_id);
	}
		
	menu_id = id;
		
	window.clearTimeout(closetimer);
	var menu = document.getElementById(id);
	menu.style.visibility = "visible";
}

function ddRollOut(id, event) {
	var target = event.target || event.srcElement;
	if (target && ((target.nodeName == 'LI') || (target.nodeName == 'DIV'))) {
		closetimer = window.setTimeout(function(){ddCloseMenu(id)}, 1);
		//alert('Node: ' + target.nodeName);
	}
}

function ddCloseMenu(id) {
	var menu = document.getElementById(id);
	menu.style.visibility = "hidden";
        
}

//Tooltips js code
var DH = 0;
var an = 0;
var al = 0;
var ai = 0;
if (document.getElementById) {
	ai = 1; DH = 1;
} else {
	if (document.all) {
		al = 1; DH = 1;
	} else {
		browserVersion = parseInt(navigator.appVersion);
		if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {
			an = 1; DH = 1;
		}
	}
}

function fd(oi, wS) {
	if (ai) return wS ? document.getElementById(oi).style:document.getElementById(oi);
	if (al) return wS ? document.all[oi].style: document.all[oi];
	if (an) return document.layers[oi];
}
function pw() {
	return window.innerWidth != null? window.innerWidth: document.body.clientWidth != null? document.body.clientWidth:null;
}
function mouseX(evt) {
	if (evt.pageX) return evt.pageX;
	else if (evt.clientX) return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft);
	else return null;
}
function mouseY(evt) {
	if (evt.pageY) return evt.pageY - 100;
	else if (evt.clientY)
	return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) - 100;
	else return null;
}
function popUp(evt,oi) {
	if (DH) {
		var wp = pw(); ds = fd(oi,1); dm = fd(oi,0); st = ds.visibility;
		if (dm.offsetWidth) ew = dm.offsetWidth; else if (dm.clip.width) ew = dm.clip.width;
		if (st == "visible" || st == "show") {
			ds.visibility = "hidden";
		} else {
			tv = mouseY(evt) + 10; lv = mouseX(evt) - (ew/4);
			if (lv < 2) lv = 2; else if (lv + ew > wp) lv -= ew/2;
			if (!an) {lv += 'px';tv += 'px';} ds.left = lv; ds.top = tv; ds.visibility = "visible";
		}
	}
}
function expandDesc(elem) {
    var cd = document.getElementById(elem.parentNode.id);
    var fd = document.getElementById(elem.parentNode.id + "full");
    cd.style.display = "none";
    fd.style.display = "block";
    
    return false;
}
function findParent(obj, className) {
	if (!obj.parentNode) return false;
	if (obj.className == className) return obj;
	return findParent(obj.parentNode, className);
}
function findChild(obj, tagName, className) {
	list = obj.getElementsByTagName(tagName);
	if (!className) return list[0];
	for (i = 0; i <= list.length - 1; i++) {
		if (list[i].className == className) return list[i];
	}
	return false;
}
function findNodeList(obj, className) {
	list = obj.getElementsByTagName('ul');
	for (i = 0; i <= list.length - 1; i++) {
		if (list[i].className == className) {
			obj = list[i];
			i = list.length;
		}
	}
	list = obj.childNodes;
	listArr = new Array;
	for (i = 0; i <= list.length - 1; i++) {
		if (list[i].nodeName.toLowerCase() != 'li') continue;
		listArr.push(list[i]);
	}
	return listArr;
}
function showCondition(obj) {
	conditionTab = false;
	book = findParent(obj, 'book');
	if (!book) return false;

	condList = findNodeList(book, 'conditions');
	for (i = 0; i <= condList.length - 1; i++) {
		if (obj.parentNode == condList[i]) conditionTab = true;
		condList[i].removeAttribute("class");
	}
	cond = obj.getAttribute('rel');
	if (conditionTab) {
		obj.parentNode.className = 'bookmark';
	} else {
		condList[0].className = 'bookmark';
	}
	if (obj.nodeName.toLowerCase() == 'input') {
		obj.setAttribute('rel', obj.checked ? '' : 'tbx');
	} else {
		cb = findChild(book, 'div', 'checkboxes');
		cb = findChild(cb, 'input');
		cb.checked = false;
		cb.setAttribute('rel', 'tbx');

	}

	offer = findNodeList(book, 'offer');
	for (i = 0; i <= offer.length - 1; i++) {
		if (offer[i].className == 'header' || !offer[i].className) continue;

		if (offer[i].className.indexOf(cond) >= 0) {
			offer[i].style.display = 'block';
		} else {
			offer[i].style.display = 'none';
		}
	}

	cbs = findChild(book, 'div', 'checkboxes');
	cbs = findChild(cbs, 'div', 'expandbtn');
	cbs = findChild(cbs, 'a');
	cbs.innerHTML = 'Hide All Books';
	cbs.setAttribute('rel', 'hideAllBooks');

	return false;
}
function hideConditions(obj) {
	offer = findParent(obj, 'book');
	if (!offer) return false;

	list = findNodeList(offer, 'offer');
	for (i = 0; i <= list.length - 1; i++) {
		if (list[i].className == 'header' || !list[i].className) continue;
		list[i].style.display = 'none';
	}

	list = offer.getElementsByTagName('a');
	for (i = 0; i <= list.length - 1; i++) {
		if (list[i].className.indexOf('incartBook') < 0) continue;
		list[i].style.display = 'block';
		list[i].focus();
	}

	cbs = findChild(offer, 'div', 'checkboxes');
	cbs = findChild(cbs, 'div', 'expandbtn');
	cbs = findChild(cbs, 'a');
	cbs.innerHTML = 'Book is already in cart. Click to View All Books';
	cbs.setAttribute('rel', '');
}
function expandBookList(obj) {
	cond = obj.getAttribute('rel');
	showCondition(obj);
	obj.setAttribute('rel', cond == '' ? 'hideAllBooks' : '');
	
	if (cond == '') {
		obj.innerHTML = 'Hide All Books';
	} else {
		obj.innerHTML = 'View All Books';
	}
	return false;
}
function str_remove(search, subject) {
	return subject.split(search).join('');
}
function removePlaceholder(obj, rem) {
	obj.value = rem ? '' : obj.getAttribute('rel') || '';
}

var rentalTimer;
function showRentalOptons(id) {
	if (rentalTimer) clearTimeout(rentalTimer);
	obj = document.getElementById('rentalOptions' + id);
	if (!obj) return false;
	position = getElementPosition(obj);
	
	layer = document.getElementById('rentalOptions');
	layer.innerHTML = obj.innerHTML;
	layer.style.top = position.top + 'px';
	layer.style.left = position.left + 'px';
	layer.style.display = 'block';

	layer.onmouseover = function() {
		clearTimeout(rentalTimer);
	}
	layer.onmouseout = function() {
		hideRentalOptons();
	}
}
function hideRentalOptons() {
	layer = document.getElementById('rentalOptions');
	rentalTimer = setTimeout('changeObjDisplay(layer)', 500);
}
function changeObjDisplay(obj) {
	if (!obj) return false;
	if (obj.style.display == 'none') {
		obj.style.display = 'block';
	} else {
		obj.style.display = 'none';
	}	
}
function getElementPosition(obj) {
	var left = 0;
    var top = 0;
    while(obj) {
        left += obj.offsetLeft;
        top += obj.offsetTop;
        obj = obj.offsetParent;
    }
	
    return {'left':left, 'top':top};
}
function popUpCondition(obj) {
	popupWin = window.open(obj.href,'conditionwin','width=400,height=400,scrollbars=yes,toolbar=no,menubar=no');
	popupWin.focus();
	return false;
}


/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~ AJAX NAVIGATION & HISTORY ~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */



window.dhtmlHistory.create({ //Use prototype JSON methods 
	toJSON: function(o) { return Object.toJSON(o); },
	fromJSON: function(s) { return s.evalJSON(); } ,
	debugMode: false
});


//instantiate our history object
function init() {
	is_admin_mode = document.getElementById('formLayer');
	var isall = is_admin_mode ? 'all=1' : '';
	new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "getcourses.php", {minChars: 2, parameters:isall});
	new Ajax.Autocompleter("autocompletei", "autocomplete_choices_i", "getinstructors.php", {minChars: 3, select: null, parameters:isall});
	// quit if this function has already been called
	if (arguments.callee.done) return;
	// flag this function so we don't do the same thing twice
	arguments.callee.done = true;

	dhtmlHistory.initialize();
	dhtmlHistory.addListener(historyChange);
	
    if(document.getElementById('permCourseId')) {
        c = document.getElementById('permCourseId').value;
        uri = window.location.href;
        window.location.replace(uri.replace(/\?.+$/, '#books/' + c + '/'));
    } else {
        if(window.location.href.indexOf('?') != -1) {
            a = document.getElementsByTagName('a');
            for(i=0;i<a.length;i++){
                h = a[i].href;
                a[i].href = h.replace(/\?class=.+#(deps|classes|books)/, '#$1');
            }
        }
        uri = dhtmlHistory.getCurrentLocation();
    }
	//if first submitted uri was without any '#' part, add for it history point
	if(uri == '') {
		parent_id_obj = document.getElementById("parent_id");
		if(parent_id_obj != null){
			var id = parent_id_obj.value;
			dhtmlHistory.add('', "goDep("+id+", 1)");
		}
	} else {
        if (typeof(WEDONTTOLOADTHISSTUFFAGAIN) == 'undefined' || !WEDONTTOLOADTHISSTUFFAGAIN) {
		    getData(uri);
        }
	}
}

/* for Mozilla */
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
	document.write("<script defer src=ie_onload.js><"+"/script>");
/*@end @*/

/* for other browsers */
window.onload = init;

//functions for ajax history handling start
var gl_new_loc;
function historyChange(newLocation, historyData) {
	if (newLocation+' '+historyData == gl_lastLoc) return;
	gl_lastLoc = newLocation+' '+historyData;
	gl_new_loc = newLocation;
	var parts = parseURI(gl_new_loc);
	var gl_action = parts[0];
	//if(parts[0] != 'books') document.getElementById("classes_link").href = "#classes/" + parts[1] + "/";
	historyData ? getData(historyData, 1) : getData(newLocation);
};

function getData(qs, direct_call) {
	if(typeof direct_call !== "undefined") {
		eval(qs);
		gl_data = qs;
	} else {
		qs.indexOf("#") >= 0 ? gl_new_loc = qs.split("#")[1] : gl_new_loc = qs;
		var parts = parseURI(gl_new_loc);
		var gl_action = parts[0];
		var id = parts[1];
		var sort = parts[2] == '' ? 'undefined' : parts[2];
		var gl_lastsort = parts[2] == '' ? 'name' : parts[2];

		var page = parts[3];
        var fname = '';
		switch(gl_action) {
		case 'deps':
			goDep(id);
			fname = 'goDep'; 
			break;
		case 'classes':
			goClasses(id, sort, page);
			fname = 'goClasses';
			break;
		case 'books':
			goBooks(id);
			fname = 'goBooks';
			break;
		case 'instructors':
			goProfessors(id, sort, page);
			fname = 'goProfessors';
			break;
		case 'admins':
			goAdmins(id, sort, page);
			fname = 'goAdmins';
			break;
		}
		var gl_data = fname+'("'+id+'","'+sort+'","'+page+'")';
	}
	dhtmlHistory.add(gl_new_loc, gl_data);
	return true;    
}

function parseURI(s) {
	var arr = s.split("/");
	return arr;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

