
var sidebox_gutter = 0;

var prefetched_pages = new Array();
var prefetched_pages_requested = new Array();
var divs_pending = -1;
var ajax_pending_ids = '';
var ajax_pending_imgs = -1;
var ajax_pending_divs;	// array of div DOM objects
var pending_user_requests = new Array();


//function pageWidth() {return window.innerWidth != null? window.innerWidth: document.body != null? document.body.clientWidth:null;}
//function pageHeight() {return window.innerHeight != null? window.innerHeight: document.body != null? document.body.clientHeight:null;}

function pageWidth() {

  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
	}

	return myWidth;
}

function pageHeight() {

  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
	}

	return myHeight;
}

function stech_process_css(url, element) {

	var cssNode = element.createElement('link');
	cssNode.type = 'text/css';
	cssNode.rel = 'stylesheet';
	cssNode.href = codebase_path + 'get_css.php?src=' + url + '&em_unit=' + (stech_em_unit_base / stech_em_resolution_multiplier);
	cssNode.media = 'screen';
	cssNode.title = 'dynamicLoadedSheet';
	element.getElementsByTagName("head")[0].appendChild(cssNode);
}

function get_unit(str) { 

	return str.replace(/([\d\.]*)(.*)/gi, '$2');
}

function get_number_without_unit(str) {

	return str.replace(/([\d\.]*)(.*)/gi, '$1');
}

function convert_anything_to_px(str) {

	var tmp_unit = get_unit(str);

	if(tmp_unit == 'px')
		return get_number_without_unit(str);

	if(tmp_unit == 'em')
		return em_str2px(str);

	if(tmp_unit == '%')
		alert('ERROR: Unhandled exception: convert_anything_to_px() was asked to convert a percentage value to px');
}

function em2px(em) {

	return em * stech_em_unit;
}

// the assumption below is that we're working with px units from a pre-render source, meaning they do not have the stech_em_resolution_multiplier factored in

function px2em(px) {

	return (px / stech_em_unit_base) * stech_em_resolution_multiplier;
}


function em_str2em(em_str) {

	return parseFloat(em_str.substr(0, em_str.length - 2));
}

function em_str2px(em_str) {

	return em2px(em_str2em(em_str));
}

function em2px_str(em) {

	return px2px_str(em2px(em));
}

function px_str2px(px_str) {

	return parseFloat(px_str.substr(0, px_str.length - 2));
}

function px2px_str(px) {
	
	return px + 'px';
}

function px_str2em_str(px_str) {

	return em2em_str(px2em(px_str2px(px_str)));
}

function px_str2em(px_str) {
	return px2em(px_str2px(px_str));
}

function px2em_str(px) {

	return em2em_str(px2em(px));
}

function em2em_str(em) {

	return em + 'em';
}

function getSS(partial_url) {

	for(var i = 0; i < document.styleSheets.length; i++) {
		if(document.styleSheets[i].href.substr(0 - partial_url.length, partial_url.length) == partial_url)
			return document.styleSheet[i];
	}

	return null;
}

function elasticizeImages(container) {

	imgs = container.getElementsByTagName('img');
	var sizeDetector = new Image();
	for(var i = 0; i < imgs.length; i++) {

		if(imgs[i].stech_em_combined_scale == stech_em_combined_scale)
			continue;

		sizeDetector.src = imgs[i].src;

		if(imgs[i].style.width.search('%') == -1)
			imgs[i].style.width = px2em_str((imgs[i].style.width ? convert_anything_to_px(imgs[i].style.width) : sizeDetector.width) / stech_em_combined_scale);

		if(imgs[i].style.height.search('%') == -1)
	 		imgs[i].style.height = px2em_str((imgs[i].style.height ? convert_anything_to_px(imgs[i].style.height) : sizeDetector.height) / stech_em_combined_scale);
	
		imgs[i].stech_em_combined_scale = stech_em_combined_scale;
	}
}

function add_ajax_links() {

	if(!browser_check(compat_ajax_loader))
		return;

	var hrefs = document.getElementsByTagName('a');

	for(var i = 0; i < hrefs.length; i++) {

		if(linkfilter.test(hrefs[i].href) && !/javascript:ajax_joomla\(\'[\s\S]*\',false\)/i.test(hrefs[i].href)) {
	
			prefetch_page(clean_PHP_url(hrefs[i].href + '&stech_ajax=1'));

			hrefs[i].href = clean_PHP_url('javascript:ajax_joomla(\'' + hrefs[i].href + '&stech_ajax=1' + '\',false)');

			var tmp = hrefs[i].id;
			hrefs[i].id = 'xxxx';
			$('#xxxx').click(function() { this.blur(); });
	
//			var imgs = hrefs[i].getElementsByTagName('img');

			$('#xxxx').click(function() { this.href; });	
			hrefs[i].id = tmp;
		}
	}
}

function get_scaled_jpegs(code) {

	var newcode = code.replace(/(src=.)([a-z0-9%\.\_\/\-]*?\.jpg)(.)/gi, '$1' + codebase_path + 'imgresize.php?src=$2&em_fontsize=' + stech_em_combined_scale + '$3');
	newcode = newcode.replace(/(src=.)([a-z0-9%\.\_\/\-]*?\.png)(.)/gi, '$1' + codebase_path + 'imgresize.php?src=$2&em_fontsize=' + stech_em_combined_scale + '$3');
	newcode = newcode.replace(/(src=.)([a-z0-9%\.\_\/\-]*?\.gif)(.)/gi, '$1' + codebase_path + 'imgresize.php?src=$2&em_fontsize=' + stech_em_combined_scale + '$3');
//	newcode = newcode.replace(/(src=.)([a-z0-9%\.\_\/\-]*?\.bmp)(.)/gi, '$1' + codebase_path + 'imgresize.php?src=$2&em_fontsize=' + stech_em_combined_scale + '$3');

	newcode = newcode.replace(/(background\-image\:\s?url\(\'?)([a-z0-9%\.\_\/\-]*?\.jpg)(\'?\))/gi, '$1' + codebase_path + 'imgresize.php?src=$2&em_fontsize=' + stech_em_combined_scale + '$3');
	newcode = newcode.replace(/(url\()([a-z0-9%\.\_\/\-]*?\.png)(\))/gi, '$1' + codebase_path + 'imgresize.php?src=$2&em_fontsize=' + stech_em_combined_scale + '$3');
	newcode = newcode.replace(/(url\()([a-z0-9%\.\_\/\-]*?\.gif)(\))/gi, '$1' + codebase_path + 'imgresize.php?src=$2&em_fontsize=' + stech_em_combined_scale + '$3');
//	newcode = newcode.replace(/(url\()([a-z0-9%\.\_\/\-]*?\.bmp)(\))/gi, '$1' + codebase_path + 'imgresize.php?src=$2&em_fontsize=' + stech_em_combined_scale + '$3');

	return newcode;
}

function px2em_in_code(code) {

	var matches = code.match(/\D\-?\d+(\.\d+)?px(_to_intpx)?/gi);

	if(matches == null)
		return code;

	for(var i = 0; i < matches.length; i++) {

		if(matches[i].substr(0, 1) == '.')
			continue;

		if(/_to_intpx$/.test(matches[i])) {
			code = code.replace(matches[i], matches[i].substr(0, 1) + em2px(px_str2em(matches[i].substr(1, matches[i].length - 3)).toFixed(0)));
		}
		else
			code = code.replace(matches[i], matches[i].substr(0, 1) + px_str2em_str(matches[i].substr(1, matches[i].length - 1)));	
	}

	return code;
}

function clean_PHP_url(str) {

	return str.replace(/\/&/g, '/?');
}

function prefetch_page(url) {

	if(!prefetched_pages_requested[url]) {

		prefetched_pages_requested[url] = 1;
		$.ajax({
			url: url,
			cache: false,
			success: function(html){
				prefetched_pages[url] = html;
			}
		});
	}
}

function get_prefetched_page(url) {

	return prefetched_pages[url];

//	for(var i = 0; i < prefetched_pages.length; i++) {
//		if(prefetched_pages[url] != null)
//	}

//	return null;
}

  function ajax_joomla(url, queue) {

	if(!browser_check(compat_ajax_loader))
		return;

//	document.body.blur();

	// exit if user is already waiting for a previous page to load
	if(ajax_pending_imgs != -1) {
		if(queue) {
			pending_user_requests.push(url);
		
			return;
		}
		else
			return;
	}

	var page = get_prefetched_page(url);

	if(page == null) {
		if(document.getElementById('pos_left').innerHTML == '' && document.getElementById('pos_component').innerHTML == '') {
			document.getElementById('ajax_message').innerHTML = "<center><font style='font-size:0.65em'>[LOADING...]<\/font><\/center>";
			$('#ajax_message').fadeIn(10);
		}

		prefetch_page(url);

		setTimeout("ajax_joomla('" + url + "', " + queue + ")", 300);
	}
	else {
		ajax_pending_imgs = 0;

		ajax_joomla_process(px2em_in_code(get_scaled_jpegs(page)));
	}
}

// This is done for W3C compliance: not because we care about compliance, but because the W3C validator spits out a zillion
// "no alt tag" errors otherwise and prevents us from easily reading the validation results
function add_img_alt_tags(container) {
	
	var imgs = container.getElementsByTagName('img');

	for(var i = 0; i < imgs.length; i++) {
	
		imgs[i].alt = '';
	}
}

function ajax_joomla_process(html) {

//	document.getElementById('debug_box').value = html;

	stech_event_before_content_load();

//	var predoc = document.getElementById("ajax_preloader");

	var olddiv;
	var newdiv;
	var newdiv_comp;

	var changed_divs = new Array();
	var changed_htmls = new Array();

	var pos_divs = new Array();

	for(var i = 0; i < pos.length; i++) {

		pos_divs[i] = document.getElementById(pos[i]);

		newdiv = html.replace(new RegExp('([\\s\\S]*<div id=.' + pos_divs[i].id + '.[^>]*?>)([\\s\\S]*)(<\/div><!--' + pos_divs[i].id + '-->[\\s\\S]*)', 'mgi'), '$2');

		var ignore = new RegExp('(id="current"\\s)|(active\\s(?=item))|(\\/(?=>))|(http:\\/\\/' + site_url_regex + ')|(\\/joomla\\/)', 'mgi');

		olddiv = document.getElementById(pos_divs[i].id).innerHTML.replace(ignore, '');
		newdiv_comp = newdiv.replace(ignore, '');

		olddiv = olddiv.replace(/\s/mg, '');
		newdiv_comp = newdiv_comp.replace(/\s/mg, '');

		olddiv = olddiv.replace(/&(?!amp)/mg, '&amp;');

		olddiv = olddiv.replace(/(javascript:ajax_joomla\(')([\s\S]*?)('\))/mgi, '$2');


		if(olddiv != newdiv_comp) {

			if(olddiv != '' && is_in_list(pos_divs[i].id, pos_ignore)) {}
			else {
				changed_divs.push(pos_divs[i]);
				changed_htmls.push(newdiv);
			}
		}
	}

	ajax_pending_divs = changed_divs;
	ajax_joomla_refresh_div(changed_divs, changed_htmls);
}

function is_in_list(item, list) {

	for(var i = 0; i < list.length; i++) {
		if(list[i] == item)
			return true;
	}

	return false;
}

function ajax_joomla_refresh_div(divs, htmls) {

//	div.focus();
//	div.blur();

	var ids = '';
	var i = 0;	// external scope is important here!
	for(i = 0; i < divs.length; i++) {
		ids += (ids != '' ? ',' : '') + '#' + divs[i].id;
	}

//	$('#pos_banner').animate({top:'-2.625em'}, 200, function() {
//	$('#pos_banner').animate({top:'-2.625em'}, 300);

	var max = i;

	var total = 0;
	$(ids).fadeOut(350, function() {

//			STECH-DEBUG: Note for the future: the callback functions are called once for each element, in an
//			instance like this where a list of selectors is given. You can reference the specific element
//			that the callback is completed for with a simple "this." statement

		total++;
		if(total < max)
			return;
	
		ajax_pending_ids = ids;
		
		// we create a "fake" image to account for scenarios where a page is being loaded that contains no images
//		ajax_pending_imgs++;		

		for(var i = 0; i < divs.length; i++) {

			divs[i].innerHTML = htmls[i];

			var imgs = divs[i].getElementsByTagName('img');

			ajax_pending_imgs += imgs.length;
var imglist = '';
var imgct = 0;
			for(var j = 0; j < imgs.length; j++) {
				imgct++;
				imglist = imglist + 'preload: ' + imgs[j].src + '\n';
				imgs[j].onload = function() { /*alert('LOADED: ' + this.src);*/ div_image_loaded(); }
			}
//alert('TOTAL: ' + imgct + '\n' + imglist);
//			divs_pending++;
		}
		
//		div_image_loaded();	// we call this function once for our "fake" image
	});
}

function div_image_loaded() {

	if(ajax_pending_imgs < 0) {
		
//	alert(this + '   ' + this.innerHTML);
return;
	}

	if(ajax_pending_imgs > 0)
		ajax_pending_imgs--;

	if(ajax_pending_imgs == 0)
		divs_loaded(ajax_pending_divs);
}

function div_loaded() {
		
//	divs_pending--;

//	if(divs_pending == 0) { }
}

function divs_loaded(divs) {

	$('#ajax_message').fadeOut(30, function() {

		if(document.getElementById('pos_banner').innerHTML != '')

			elasticizeImages(document.getElementById('pos_banner'));

			$('#pos_banner').css({
				top: em2px(-2.625) + 'px',
				display: 'block'
			});

		$('#pos_banner').animate({"top": "+=" + em2px(2.625) + 'px'}, (document.getElementById('pos_banner').innerHTML != '' ? 600 : 1), function() {
			$('#pos_banner').css('position', 'relative');

			var max = ajax_pending_divs.length;
			var total = 0;

			
			// this is a fix for IE6/IE7's bug where empty DIVs take up vertical space. See http://www.tricycle.ie/blog/?p=54 for more.
//			$(ajax_pending_ids).each(function() { if(this.innerHTML == '') this.innerHTML = '<!-- -->'; });

			$(ajax_pending_ids).each(function() { fixpng(this); elasticizeImages(this); }).fadeIn(500, function() {

// this is a temporary hack to fix the IE6/IE7 empty div display bug
if(this.innerHTML == '') this.style.display = 'none';

				total++;
				if(total < max)
					return;

//				trim_sidebox('potter_events');
//				trim_sidebox('potter_latest_news');

					// STECH-DEBUG: Warning: this is not necessarily a safe place to call this, as we don't know what the behavior
					// will be when the div is re-loaded (see: bug listing in splashbox/tmpl/default.php) after sb_reset() begins
//					sb_reset();

//				divs_pending = -1;	// clear user to load a new page
				
//				sb_reset();

				stech_setup_rollovers(document);

				stech_event_post_load();
//alert('debug checkpoint: AJAX_JOOMLA');
				add_ajax_links();
			
				ajax_pending_imgs = -1;

//				add_img_alt_tags(document);
//				stech_menu_corrector();

				if(pending_user_requests.length > 0)
					ajax_joomla(pending_user_requests.pop(), true);
			});
		});
	});
}



function get_subdiv(div, id) {
	var subs = div.getElementsByTagName("div");

	for(var i = 0; i < subs.length; i++) {
		if(subs[i].id == id)
			return subs[i];
	}

	return 'ajax_preloader';
}

function round_down_precise(num, precision) {

	var num_fixed = num.toFixed(precision);

	if(num_fixed > num)
		return num_fixed - parseFloat(Math.pow(10, (-1 * precision)));
	else
		return num_fixed;
}

function round_up_precise(num, precision) {

	var num_fixed = num.toFixed(precision);

	if(num_fixed > num)
		return num_fixed - parseFloat(Math.pow(10, (-1 * precision)));
	else
		return num_fixed;
}

function stech_img_hover(cell, hover, anim_duration) {

//alert($('#' + cell).parent().parent().attr('innerHTML'));

	var parent_cell = $('#' + cell).parent().parent().attr('id');

	if(hover)
		$('#' + cell).fadeIn(anim_duration, function() {
//			$('div.ie_disappearing_bug').not('#' + parent_cell).each(function() { this.innerHTML = this.innerHTML; });
		});
	else
		$('#' + cell).fadeOut(anim_duration, function() {
//			$('div.ie_disappearing_bug').not('#' + parent_cell).each(function() { this.innerHTML = this.innerHTML; });
		});

}

function stech_menu_corrector() {

	var img;

	$('.ie_disappearing_bug').filter('div').each(function() {

		this.style.width = $(this).children().children().get(0).style.width;
		this.style.height = $(this).children().children().get(0).style.height;
	});

	$('.ie_disappearing_bug').filter('td').each(function() {
		$(this).addClass($(this).parent().parent().parent().attr('className'));
		this.style.width = $(this).children().children().get(0).style.width;
		this.style.height = $(this).children().children().get(0).style.height;
		this.background = $(this).children().children().get(0).src;
		this.style.backgroundRepeat = 'no-repeat';
		this.style.backgroundImage = 'url(' + $(this).children().children().get(0).src + ')';
	});

	$('.stech_menu_spacer').filter('td').each(function() {
		$(this).addClass($(this).parent().parent().parent().attr('className') + '_spacer');
	});
	$('.stech_menu_spacer').filter('img').each(function() {
		$(this).addClass($(this).parent().parent().parent().parent().attr('className') + '_spacer');
	});
}

function stech_gcal_date(newdate) {

	var iframes = document.getElementById('pos_component').getElementsByTagName('iframe');

	var newdate_str = 'dates=' + newdate + '%2F20320101';
	var new_url;

	if(/dates=\d\d\d\d\d\d\d\d%2f\d\d\d\d\d\d\d\d/i.test(iframes[0].src))
		new_url = iframes[0].src.replace(/dates=\d\d\d\d\d\d\d\d%2f\d\d\d\d\d\d\d\d/i, newdate_str);
	else
		new_url = iframes[0].src + '&' + newdate_str;

	iframes[0].src = new_url;
	
//	remove_all_css(iframes[0].contentDocument);
}

function remove_all_css(element) {
	element.styleSheets[0].disabled = true;
}

function browser_check(compat_matrix) {

//alert(document.compatMode);
//alert("browser: " + BrowserDetect.browser + ", version: " + BrowserDetect.version);


	if(!compat_enforce)
		return true;

	for(var i = 0; i < compat_matrix.length; i++) {
		if(compat_matrix[i][0] == BrowserDetect.browser)
			if(compat_matrix[i][1] <= BrowserDetect.version)
				return true;
	}

	return false;
	
	
}

function in_array(needle, haystack) {

	for(var i = 0; i < haystack.length; i++) {
		if(haystack[i] == needle)
			return true;
	}

	return false;
}

// I noticed that for some reason clicking on pretty much anything on the page caused the missing menu items to re-appear (this applies only to safemode, as the problem does not occur in normal mode for some reason)
function ie6_fix_stech_menu_bug() {

	if(!browser_check(compat_safemode)) {
		document.body.click();

	
//alert('ie6');
	}
}

function stech_setup_rollovers(node) {

	$('.stech_rollover', node).each(function() {

		var img = this.firstChild.firstChild;

		img.stech_rollover_off = img.src;
		img.stech_rollover_on = this.lastChild.src;

//		img.stech_rollover_on = this.style.backgroundImage.replace(/(url\(\'?)(.*src=)?(\/)?([a-z0-9\-\_\.\/]*\/)([a-z0-9\_\-\.]*\.[a-z][a-z][a-z])(\&em\_fontsize.*)?(\'?\))/i, '$2$3$4hover_$5$6');

//		var preload_img = new Image();
//		preload_img.src = img.stech_rollover_on;
	});
}

function stech_rollover(node, enable) {

	node.firstChild.firstChild.src = (enable ? node.firstChild.firstChild.stech_rollover_on : node.firstChild.firstChild.stech_rollover_off);

}
