/***********
UTILITIES
***********/
function detectBrowser() {
	trace('detectBrowser()');
	if(!window.RegExp) return('Browser does not support regular express.');
	var agent,pairs,indentifier,name,major,minor,tmp;
	agent = navigator.userAgent.toLowerCase();
	if(agent.indexOf('msie')<0) {
		// look for the last instance of BrowserName/version (ie Netscape/7.2)
		pairs = agent.match(/\w+\/[v\d\.]+/g);
		if(!pairs) return('Unable to detect browser.');
		// if the name is 'gecko', use the second to last instance.
		identifier = pairs.pop();
		if(identifier.indexOf('gecko')>=0&&pairs.length>=1) identifier = pairs.pop();
		// split the string and figure out the version
		tmp = identifier.split('/');
		if(!tmp||tmp.length<2) return('Unable to detect browser (2).');
		name = identifier.match(/^\w+/);
		minor = parseFloat(identifier.match(/[\d\.]+/));
		// special case for mozilla browsers
		if(name=='mozilla'&&agent.indexOf('macintosh')>=0) minor = parseFloat(agent.match(/rv:([\d\.]+)/)[1]);
		major = parseInt(minor);
	} else {
		tmp = agent.match(/msie\s([\d\.]+)/);
		name = 'msie';
		identifier = tmp[0];
		minor = parseFloat(tmp[1]);
		major = parseInt(minor);
	}

	window.browser = {};
	window.browser.agent = agent;
	window.browser.tag   = identifier;
	window.browser.name  = name;
	window.browser.major = major;
	window.browser.minor = minor;

	trace('browser agent is '+agent);
	trace('detected '+name+' (name), '+major+' (major), '+minor+' (minor)');
	//alert(agent+"\n\n"+'detected '+name+' (name), '+major+' (major), '+minor+' (minor)');
	return(false);
}

// Add an textarea with id="output" in order to follow the trace messages.
// trace(str);
function trace(s) {
	if(!document.getElementById) return('Unsupported DOM.');
	var o=document.getElementById('output');
	if(o) {
		/*
		var now = new Date();
		var s = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds()+'> "'+s+'"'+"\n";
		*/
		o.value = s+"\n"+o.value;
	}
	return(0);
}
// dumpObject(obj); // will dump the contents of an object (non-recursive)
function dumpObject(o) {
	trace('dumpObject('+o+');');
	var str = '';
	if(typeof(o)=='string') {
		str = o;
	} else if(typeof(o)=='object') {
		str = 'start object dump:'+"\n";
		for (var p in o) {
			str += p + '=>' + o[p] + "<\n";
		}
	} else {
		return('dumpObject. Unknown type ['+typeof(o)+']');
	}
	trace(str);
	return(0);
}
function objP(o) {
	return(typeof(o)=='object');
}
function strP(str) {
	return(typeof(str)=='string');
}
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=/";
}

/**************
DOM Shared
**************/
function getByCSS(arr,parent) {
	trace('getByCSS('+arr+','+parent+');');
	if(!objP(parent)) parent = document;
	if(typeof(arr)=="string") arr = arr.split(/\s{1,}/);
	if(arr.length==0) return('getByCSS - wrong input.');

	var seg,tag,id,cla;
	var o;
	var objs=[],tmp=[];
	var ii;

	seg = arr.shift();
	if(seg[0]=='#') { // #id
		o = document.getElementById(seg.substring(1));
		if(objP(o)) objs.push(o);


	} else if(seg[0]=='.') { // .class
		cla = seg.substring(1);
		for(ii in parent.childNodes) {
			o = parent.childNodes[ii];
			if(checkClass(o,cla)) objs.push(o);
		}

	} else if(seg.indexOf('.')>0) { // tag.class
		tmp = seg.split('.');
		tag = tmp[0];
		cla = tmp[1];
		tmp = parent.getElementsByTagName(tag);
		for(var ii=0; ii<tmp.length; ii++) {
			o = tmp[ii];
			if(checkClass(o,cla)) objs.push(o);
		}

	} else if(seg.length>0) { // tag
		tmp = parent.getElementsByTagName(seg);
		for(var ii=0; ii<tmp.length; ii++) {
			objs.push(tmp[ii]);
		}

	}	
	if(objs.length&&arr.length) { // continue to check for child declarations
		var children = [];
		for(ii in objs) {
			children = children.concat(getByCSS(arr.concat(),objs[ii]));
		}
		return( (children.length) ? children : 0);
	} else {
		return(objs);
	}
}
function getElById(id,parent) {
	if(typeof(id)=='object') return(id);
	if(parent==null) parent = document;
	if(!document.getElementById) return("Unsupported DOM.");
	return(parent.getElementById(id));
}
function toggleClassName(obj,str,setP) {
	trace('toggleClassName('+obj+','+str+','+setP+');');
	if(strP(obj)) obj = getElById(obj);
	if(!objP(obj)) return("Element not found. " + obj);
	if(setP==null) setP = (!checkClass(obj,str));
	if(checkClass(obj,str)) {
		var arr = obj.className.split(str);
		obj.className = arr.join('');
	}
	if(setP) {
		obj.className += obj.className.length ? ' '+str : str;
	}
	return(setP);
}
function checkClass(obj,str) {
	if(!objP(obj)) return(false);
	return(obj.className && obj.className.indexOf(str)!=-1);
}
function focusInput(id) {
	trace('focusInput('+id+');');
	var objs;
	if(typeof(id)=='string'&&id.length) {
		objs = getByCSS('#'+id+' input.focus');
	} else {
		objs = getByCSS('input.focus');
	}

	if(objs.length==0) return('No input elements found.');
	for(var ii in objs) {
		var o = objs[ii];
		o.onfocus = function() { this.select(); };
		if(checkClass(o,'focus')&&o.focus) o.focus();
		o.select();
	}
}
function changeInputShape() {
	trace('changeInputShape();');
	var objs = getByCSS('input');
	for(var ii in objs) {
		var o = objs[ii];
		if(o&&o.getAttribute('type')=='text') o.setAttribute('type','search');
	}
}
/************
DYNAMIC NAVIGATION
************/
function hideNav() {
	trace('hideNav();');
	window.active_link = [];
	if(!document.getElementById) return("Unsupported DOM.");
	// Make the select menu dynamic.
	/*
	var o = getByCSS('#site_nav_select');
	if(o.length&&o[0]) o[0].onchange = function() {
		var uri = document.location.href.split('?')[0];
		document.location.href = uri+'?'+this.options[this.selectedIndex].value;
	}
	o = getByCSS('#site_nav_submit');
	if(o.length&&o[0]) toggleClassName(o[0],'hidden',true);
	*/

	var hrefs = getByCSS('ul.level0 a');
	for(var ii in hrefs) {
		var link = hrefs[ii];
		if(objP(link)) {
			var l = link.href;
			if(!link.onclick) {
				link.onclick = function() { return(navClick(this)); };
				if(l.indexOf('homework/logout')!=-1) link.onclick = null;
				if(l.indexOf('.mov')!=-1) link.onclick = null;

				if(checkClass(link,'contentlink')&&checkClass(link.parentNode,'open')) {
					var hierarchy = link.getAttribute('href');
					if(hierarchy.indexOf('?')) hierarchy = hierarchy.substring(hierarchy.indexOf('?')+1);
					hierarchy = hierarchy.split('/');
					var section = hierarchy[1];
					window.active_link[section] = link.parentNode;
				}
			}
		}
	}
	return(0);
}
function catchPopUps(parent) {
	parent = getElById(parent);
	if(!parent) parent = document;
	var arr = parent.getElementsByTagName('a');
	for(var i=0;i<arr.length;i++) {
		var a = arr[i];
		if(a.getAttribute('target')=='bnspop') a.onclick = function() { return(window.popWin(this.href)); }
	}
}
function popWin(uri) {
	if(window.popup&&!window.popup.closed) {
		window.popup.location.href = uri;
		window.popup.focus();
	} else {
		//var w = 62*12 + 60; // 62 (width in em) * 11 (default em size) + 40 (buffer) // 80*getPixelPerEm() + 40;
		//w = 82*window.getPixelPerEm() + 40;
		//w = Math.max(600,w);
		var w = 1000;
		window.popup = window.open(uri,'bnspop','width='+w+',height=800,location=1,menubar=1,scrollbars=1,resizable=1,status=0,toolbar=1,titlebar=1');
	}
	return(false);
}
function navClick(o) {
	trace('navClick('+o+');');
	o = getElById(o);
	if(!objP(o)) return('navClick(). Unsupported input. '+o);

	var uri = o.getAttribute('href');	// take the link url
	uri = '?' + uri.split('?')[1];		// find the query string
	var hierarchy = uri.split('/');		// create hierarchy
	var section = hierarchy[1];			// get the section name
	if(o.parentNode==this.active_link[section]) return(false);

	if(checkClass(o,'contentlink')) {
		var lielement = o.parentNode;
		var visP = toggleClassName(lielement,'open');
		toggleClassName(o,'open',true);

		var currlink = window.active_link[section];
		if(currlink&&currlink!=o) {
			toggleClassName(currlink,'open',0);
			toggleClassName(currlink.childNodes[0],'open',0);
		}
		window.active_link[section] = visP ? o.parentNode : 0;
		return(AJAXrequest(uri,section+'_viewer'));
	} else if(document.getElementsByTagName&&!checkClass(o,'link0')) {
		var as = getByCSS('ul li a',o.parentNode);
		if(objP(as[0])) return(navClick(as[0]));
	} else if(checkClass(o,'link0')) {
		var lielement = o.parentNode;
		var visP = toggleClassName(lielement,'open');
		toggleClassName(section+'_viewer','hidden',!visP);
		var as = getByCSS('ul li a',o.parentNode);
		if(objP(as[0])) return(navClick(as[0]));
		return(false);
	}
	return('Error');
}

function validateForm(form_obj,viewer_id) {
	trace('validateReelRequest('+form_obj+');');
	if(!document.getElementById) return('Unsuported DOM');
	var inputs = form_obj.getElementsByTagName('input');
	for(var i=0; i<inputs.length; i++) {
		var el = inputs[i];
		if(checkClass(el,'email')) {
			if(window.RegExp) {
				if(el.value.length<5||!/\w+@\w{3,}\.\w{2,}/.test(el.value)) {
					showWarning(el,'Please enter a valid email address.');
					el.focus();
					return(false);
				}
			}
		} else if(checkClass(el,'required')) {
			if(el.value.length==0) {
				showWarning(el,'This field is required.');
				el.focus();
				return(false);
			}
		}
	}
	return(submitFormViaAJAX(form_obj,viewer_id));
}
function showWarning(el,warning) {
	if(!objP(el)) return;
	var p = el.previousSibling;
	if(checkClass(p,'warning')) {
		p.innerHTML = warning;
	} else if(document.createElement) {
		p = document.createElement('div');
		p.innerHTML = warning;
		p.className = 'warning';
		el.parentNode.insertBefore(p,el);
	}
}
/*********
COLUMNIZATION
*********/
/*window.onresize = window.adjustWidth;
window.onload = window.checkTextSize;*/
window.onunload = function() {
	clearTimeout(window.text_monitor_id);
}
/*function checkTextSize() {
	var referenceObj = document.getElementById('reference');
	var text_height = Math.floor(referenceObj.offsetHeight/10);
	if(window.last_text_height==null || text_height!=window.last_text_height) {
		window.last_text_height = text_height;
		window.adjustWidth();
	}
	window.text_monitor_id = setTimeout('window.checkTextSize()',1000);
}
function adjustWidth(forceP) {
	// calculate the number of columns
	var window_w = window.getWindowWidth();
	var column_w = document.getElementById('guide').offsetWidth;
	var column_count = Math.max(3, Math.floor(window_w / column_w));
	// change the container width
	var container = document.getElementById('container');
	var width_str = (column_count*column_w)+10+'px';
	trace(width_str);
	container.style.width = width_str;
	// columnize text
	column_count--; // remove nav column
	column_count = Math.floor(column_count/2); // take larger text columns into account
	window.columnizeText(column_count);
	return(false);
}*/
function getWindowWidth() {
	if(window.innerWidth) { // all except Explorer
		return(window.innerWidth);
	} else if(document.documentElement&&document.documentElement.clientHeight) { // Strict Explorer 6
		return(document.documentElement.clientWidth);
	} else if(document.body) { // other Explorers
		return(document.body.clientWidth);
	} else {
		return(0); //'getWindowWidth(). Unable to determin width.')
	}
}
function columnizeText(cols) {
	trace('columnizeText('+cols+')');
	var elements_to_columnize = getByCSS("div.columnize");
	var referenceObj = document.getElementById('reference');
	var line_height = Math.floor(referenceObj.offsetHeight/10);
	var em_factor = Math.round(referenceObj.offsetHeight / referenceObj.offsetWidth * 1000)/1000;
	var agent = navigator.userAgent.toLowerCase();
	
	for(var ii=0; ii<elements_to_columnize.length; ii++) {
		// get the source
		var element = elements_to_columnize[ii];
		var full_height = element.firstChild.offsetHeight;
		var line_count = Math.ceil(full_height / line_height);
		var lines_per_column = Math.max(10, Math.ceil(line_count / cols));
		var container = element.parentNode;
		if(container) {
			// find exisiting
			var existing = new Array();
			for(var jj=0; jj<container.childNodes.length; jj++) {
				var n = container.childNodes[jj];
				if(n.className&&n.className.indexOf('column')>=0) {
					existing.push(n);
				}
			}
			
			// append and remove columns as needed
			if(existing.length<cols) {
				for(jj=existing.length;jj<cols;jj++) {
					var o = container.appendChild(existing[0].cloneNode(true));
					o.className = 'column';
					existing.push(o);
				}
			} else if(existing.length>=cols && container.removeChild) {
				for(jj=cols;jj<existing.length;jj++) {
					container.removeChild(existing[jj]);
				}
			}
			// calculate number of lines
			
			// adjust height and position of columns	
			var px_per_column = lines_per_column * line_height;
			var str = 'line_height      = ' + line_height + "\n";
			str += 'full_height      = ' + full_height + "\n";
			str += 'line_count       = ' + line_count + "\n";
			str += 'cols             = ' + cols + "\n";
			str += 'lines_per_column = ' + lines_per_column + "\n";
			str += 'px_per_column    = ' + px_per_column + "\n";
			str += 'em_factor        = ' + em_factor + "\n";
			trace(str);
			for (jj=0; jj<existing.length; jj++) {
				n = existing[jj];
				if(agent.indexOf('msie')>=0||agent.indexOf('safari')>=0) {
					n.style.height = px_per_column + 'px';
					n.firstChild.style.marginTop = -px_per_column*jj + 'px';
				} else {
					n.style.height = lines_per_column * em_factor + 'em';
					n.firstChild.style.marginTop = -(lines_per_column * em_factor * jj) + 'em';
				}
				if (n.className&&n.className.indexOf('cropped')==-1) n.className += ' cropped';
			}
		}
	}
}
/*********
AJAX
*********/
function AJAXinit() {
	trace('Initializing AJAX.');
	var o;
	if(window.ActiveXObject) {
		o = new ActiveXObject("Microsoft.XMLHTTP");
	} else if(window.XMLHttpRequest) {
		o = new XMLHttpRequest();
	} else {
		return(null); // 'Unable to initilaize AJAX.'
	}
    return o;
}
function AJAXrequest(uri,id) {
	trace('AJAX loading ['+uri+']');
	if(window.AJAXobj==undefined) window.AJAXobj = AJAXinit();
	if(window.AJAXobj==null) return('AJAXrequest(). Unable to initialize AJAX object.');
	writeHTML(id,'<p><img src="img/ajax-loader.gif"></p>');
	window.targetid = id;
    window.AJAXobj.open('post',"ajax.php?id="+id+"&uri="+uri,true);
	
    window.AJAXobj.onreadystatechange = AJAXresponse;
    window.AJAXobj.send(null);
    return(false);
}
function AJAXresponse() {
	trace('AJAX response state ['+AJAXobj.readyState+']');
    if(AJAXobj.readyState == 4 && window.targetid!=null){
   		var response = AJAXobj.responseText;
		writeHTML(window.targetid,response);
		if(/(columnize)/.test(response)) adjustWidth(true);
		if(/(<!--javascript)/i.test(response)) {
			// javascript command
			var command = /(<!--javascript)\s(.*)(-->)/i.exec(response)[2];
			if(command) eval(command);
		}
    }
    return(0);
}
function submitFormViaAJAX(form_obj,viewer_id) {
	trace('submitFormViaAJAX('+form_obj+','+viewer_id+')');
	if(window.browser.name=='opera') return('Unsupported browser (opera).');
	if(!document.getElementById) return('Unsuported DOM');
	form_obj = getElById(form_obj);
	var request = '?';
	// build the url string
	var inputs = form_obj.getElementsByTagName('input');
	for(var i=0; i<inputs.length; i++) {
		request += escape(inputs[i].name)+'='+escape(inputs[i].value)+'&';
	}
	// submit the url via AJAX
	return(AJAXrequest(request,viewer_id));
}
function writeHTML(obj,src) {
	//trace('writeHTML('+obj+','+src+');');
	obj = getElById(obj);
	if(!objP(obj)) return("Unable to find element");
	
	removeChildrenFromNode(obj);

	if(obj.innerHTML!==null) {
		obj.innerHTML = src;
	} else if(document.layers) {
		obj.document.open();
		obj.document.write(src);
		obj.document.close();
	}

	window.catchPopUps(obj.id);
	if(window.browser.name=='safari') changeInputShape();
	window.timer = setTimeout('focusInput("'+obj.id+'")',500);
}
function removeChildrenFromNode(node) {
	var a = 0;
	while (node.hasChildNodes()) { 
		node.removeChild(node.firstChild);
		a++;
	}
}
function play_video() {
	document.getElementById('thumb_project').style.display = "none";
	document.getElementById('video').style.display = "block";
	document.getElementById('boton_video').style.display = "none";
	document.getElementById('boton_thumb').style.display = "block";
}
function view_thumb() {
	document.getElementById('thumb_project').style.display = "";
	document.getElementById('video').style.display = "none";
	document.getElementById('boton_video').style.display = "";
	document.getElementById('boton_thumb').style.display = "none";
}
function big_photo(image) {
	document.getElementById('photography_viewer').style.display = "none";
	document.getElementById('photos').style.display = "block";
	document.getElementById('photos').innerHTML = '<div class="d cell triple"><a href="#photography" onclick="photo_small();return false""><img src="CMS/uploads/big/'+image+'" id="photo_big" alt=""></a></div>';

}
function photo_small() {
	document.getElementById('photography_viewer').style.display = "";
	document.getElementById('photos').style.display = "none";
}
