// shared.js script, version 3, 12-03-2010

// global vars ======================================================
var loc = location.pathname.split('/');
loc.length = loc.length - 1; // removes filename 

var d = location.pathname.replace(/\/[^\/]*/g,'../'); // return one depth too deep, see next line for fix
d = d.substring(0,(d.length-3)); // turns this: ../../ into this ../

function qsGET() {
	// call like so:
	// var GET = qsGET();
	// if (GET.myQSName) {var myQSValue = GET.myQSName;}
	if (location.search != '') {
		var qs = location.search.split('?');
		var nv = qs[1].split('&');
		var GET = new Object();
		for(var n = 0; n < nv.length; n++) {
			var nvSplit = nv[n].split('=');
			GET[nvSplit[0]] = unescape(nvSplit[1]);
			}
		return GET;
		}
	return false;
	}
GET = qsGET();

function vp_width() {// returns viewport width
	var vp_width = document.body.clientWidth;// for IE and iPhone
	if(document.documentElement.clientWidth) {var vp_width = document.documentElement.clientWidth;}
	else if (window.innerWidth) {var vp_width = window.innerWidth;}
	//alert(vp_width);
	return vp_width;
	}

// test for HTML 5 support =====
var autofocus;
if (!("autofocus" in document.createElement("input"))) {autofocus = false;}
// /test for HTML 5 support =====
// /global vars ======================================================

// img preloads =====================================================
/*
hh = new Image(); hh.src = "/pix/hh.gif";
hh_roll = new Image(); hh_roll.src = "/pix/hh_roll.gif";
*/	
// /img preloads =====================================================

window.onload = function() {load_functions()};
window.onorientationchange = function() {update_orientation()};

function popflex(url,winname,W,H,scroll) {
	var popwin = window.open(url, winname,'top=0,left=30,width='+W+',height='+H+',resizable=no,scrollbars='+scroll);
	popwin.focus();
	}	

/* // uncomment if a showhide is needed that does NOT resize the page boxes
function showhide_v3() {
	divid = arguments[0];
	classes = arguments[1];
	onstate = arguments[2];
	force = ''; //stops toggling between on and off and forces either on or off whenever clicked 
	if (typeof arguments[3] != 'undefined') {force = arguments[3];}

	var state = 'none';
	if (document.getElementById(divid).className == classes+' none' || 
	document.getElementById(divid).className == 'none') {
		var state = onstate;
		}
	if (force != '') {state = force;}
	document.getElementById(divid).className = classes+' '+state;
	return divid;
	}
*/
function showhide_v4() {
	divid = arguments[0];
	classes = arguments[1];
	onstate = arguments[2];
	force = ''; //stops toggling between on and off and forces either on or off whenever clicked 
	if (typeof arguments[3] != 'undefined') {force = arguments[3];}

	var pre_height = parseInt(document.getElementById(divid).offsetHeight);//alert(pre_height);
	
	var state = 'none';
	if (document.getElementById(divid).className == classes+' none' || 
	document.getElementById(divid).className == 'none') {
		var state = onstate;
		}
	if (force != '') {state = force;}
	document.getElementById(divid).className = classes+' '+state;
	
	var post_height = parseInt(document.getElementById(divid).offsetHeight);//alert(post_height);
	
	if (vp_width() > 639) {set_height(pre_height,post_height);}// if in smart phone, do NOT resize columns!!!!
	
	return divid;
	}

function rotator(prefix,classtype,n,total,time) {
	/*
	call from html like:
	
	<p class="block" id="blurb_1">This is some text</p>
	<p class="none" id="blurb_2">and here is another line</p>
	<p class="none" id="blurb_3">and another</p>
	<p class="none" id="blurb_4">and finish.</p>
	<script type="text/javascript">rotator('blurb','block',1,4,50000);</script>
	*/
	for (var i = 1; i <= total; i++) {
		var divid = prefix+'_'+i;
		var display = 'none';
		if (i == n) {display = classtype;}
		document.getElementById(divid).className = display;
		}
	n++;
	if (n > total) {n = 1;}
	setTimeout('rotator("'+prefix+'","'+classtype+'",'+n+','+total+','+time+')',time);
	}

function load_functions() {
	/*
	NOTE: this function MUST be called from body onload, ex: <body onload="load_functions();">
	this avoids render timing issues in Safari
	*/

	// functions to be run on every page:
	var test_width = vp_width();
	if (test_width > 639) {set_height();}// if in smart phone, do NOT resize columns!!!!
	if (test_width <= 639) {update_orientation();}// if in smart phone, resize big graphics
	
	auto_width();
	sifr();
	
	// functions run on a per/page basis. loadfunctions is an array declared in /folder/pagescript.js, each array object represents a function declared either in /shared.js or /folder/pagescript.js
	if (typeof loadfunctions !== 'undefined') {
		for (var n=0; n < loadfunctions.length; n++) {
			eval(loadfunctions[n]+'();');
			}
		}
	}

function update_orientation() {
	window.scrollTo(0, 1);// turns off address bar in iPhone
	
	var width = (vp_width()-8);//alert(vp_width());// 3px pad on left and right AND 1px stroke
	
	document.getElementById('shell').style.width = width+'px';//alert(document.getElementById('shell').style.width);
	
	if (typeof in_wordpress != 'undefined' && in_wordpress == true) {img_resize_ajax('img_resize',width);}
	else {img_resize(width);}
	img_resize2(width);
	//if (typeof document.getElementById('divid1') != 'undefined') {div_resize(width,document.getElementById('bgimg'),0);}
	//if (typeof document.getElementById('divid2') != 'undefined') {div_resize(width,document.getElementById('bgimg'),1);}
	
	move_nav();// in /_includes.php/nav.php
	}

var div_resized = new Array();
function	div_resize(width,obj,n) {
	if (obj.style.width != '') {
		var orig_w = parseInt(obj.style.width);//alert(orig_w);
		var orig_h = parseInt(obj.style.height);//alert(orig_h);
		}
	else {
		var orig_w = parseInt(window.getComputedStyle(obj,null).getPropertyValue("width"));//alert(orig_w);
		var orig_h = parseInt(window.getComputedStyle(obj,null).getPropertyValue("height"));//alert(orig_h);
		}
	
	var resize = false;
	for(var k in div_resized) {
		if (div_resized[k] == obj.id) {
			resize = true;
			break;
			}
		}
	if (orig_w > width) {resize = true;}
	if (resize) {
		var x_ratio = (width/orig_w);
		var new_w = width;//alert(new_w);
		var new_h = Math.ceil(x_ratio * orig_h);//alert(new_h);
		
		obj.style.width = new_w+'px';
		obj.style.height = new_h+'px';
		div_resized[n] = obj.id;
		}
	}
var img_resized = new Array();
function img_resize(width) {
	var n = -1;
	for(var k in document.images) {
		var v = document.images[k];
		if (typeof v.width == 'undefined') {continue;}
		n++;
		//alert(v.width);
		resize = false;
		for(var i = 0; i < img_resized.length;i++) {
			if (img_resized[i] == v.src) {
				resize = true;
				break;
				}
			}
		if (parseInt(v.width) > width) {resize = true;}
		if (resize) {
			// calc new height according to width =====
			var orig_w = v.width;
			var orig_h = v.height;
			
			var x_ratio = (width/orig_w);
			var new_w = width;//alert(new_w);
			var new_h = Math.ceil(x_ratio * orig_h);//alert(new_h);
			
			v.width = new_w;
			v.height = new_h;
			img_resized[n] = v.src;
			}// /if (resize) {
		}// /for(var k in document.images) {
	//alert(img_resized);
	}
var img_resized2 = new Array();
function img_resize2(width) {
	//alert(width+' -- '+parseInt((width*0.50)));return;
	var n = -1;
	for(var k in document.images) {
		var v = document.images[k];
		if (typeof v.width == 'undefined') {continue;}
		n++;
		//alert(v.width);
		var resize = false;
		for(var i = 0; i < img_resized2.length;i++) {
			if (img_resized2[i] == v.src) {
				resize = true;
				break;
				}
			}
		if (parseInt(v.width) < width && parseInt(v.width) > parseInt((width*0.50))) {resize = true;}
		if (resize) {
			// calc new height according to width =====
			var orig_w = v.width;
			var orig_h = v.height;
			
			var x_ratio = (parseInt((width*0.50))/orig_w);
			var new_w = parseInt((width*0.50));//alert(new_w);
			var new_h = Math.ceil(x_ratio * orig_h);//alert(new_h);
			
			v.width = new_w;
			v.height = new_h;
			img_resized2[n] = v.src;
			}// /if (resize) {
		}// /for(var k in document.images) {
	//alert(img_resized2);
	}
function img_resize_ajax(process,width) {
	for(var k in document.images) {
		var v = document.images[k];
		if (typeof v.width == 'undefined') {continue;}
		img_resize_ajax_async_request(process,document.images[k],width,v.src);
		}
	}
function img_resize_ajax_async_request(process,obj,width,src) {
	var xhr = createXMLHttpRequest();
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4) {// request is finished
			if(xhr.status == 200) {
				if (xhr.responseText != '') {
					//alert(xhr.responseText);// return text
					img_resize_ajax_async_response(obj,xhr.responseText);// CANNOT return value!!!!!
					//alert(xhr.responseXML);// return xml obj, NOTE: on process.php MUST set the header like: ob_start(); print $xml; header("Content-type: application/xhtml+xml"); ob_end_flush();
					//my_ajax_function(xhr.responseXML);// CANNOT return value!!!!!
					}
				}
			else {
				//alert('XMLHttpRequest error: '+xhr.responseText);
				}
			}
		}
	// send with GET =====
	var url = '/_includes.php/process_img_resize.php?process='+process+'&width='+width+'&src='+src;
	xhr.open('GET',url,true);
	xhr.send(null);
	}
function img_resize_ajax_async_response(obj,response) {
	//alert(response);
	eval('var data = '+response+';');//alert(data);
	//for(var k in data) {alert(data[k]);}
	obj.width = data['width'];
	obj.height = data['height'];
	}

function set_height() {
	var pre_height = '';
	var post_height = '';
	if (typeof arguments[0] != 'undefined') {pre_height = arguments[0];}
	if (typeof arguments[1] != 'undefined') {post_height = arguments[1];}
	//alert(pre_height+' '+post_height);
	
	var minheight = 400;
	var total = 20;
	
	function numberorder(a,b) {return a-b;}
	
	// page boxes =======================================================
	//var pagecontainer = document.getElementById('pagecontainer');
	var boxes = [];
	var i = -1;
	for (var n = 0; n < total; n++) {
		var box = document.getElementById('pagebox'+n);
		if (box == null) {continue;}
		i++;
		boxes[i] = parseInt(box.offsetHeight);
		}
	if (document.getElementById('pageboxfull') != null) {
		var box = document.getElementById('pageboxfull');
		boxes[(i+1)] = parseInt(box.offsetHeight);
		}
	
	// find out who's longest =====
	boxes.sort(numberorder);
	var longest = boxes[(boxes.length-1)];//alert(longest);
	if (longest < minheight) {longest = minheight;}
	if (pre_height < post_height) {longest += post_height;}
	if (pre_height > post_height) {longest -= pre_height;}
	// /find out who's longest =====
	
	// reset all containers to the longest value =====
	//pagecontainer.style.height = longest+'px';
	for (var n = 0; n < total; n++) {
		var box = document.getElementById('pagebox'+n);
		if (box == null) {continue;}
		box.style.MozBoxSizing = 'border-box';
		box.style.height = longest+'px';
		}
	if (document.getElementById('pageboxfull') != null) {
		var box = document.getElementById('pageboxfull');
		box.style.MozBoxSizing = 'border-box';
		box.style.height = longest+'px';
		}
	// /page boxes =======================================================
	
	// shell boxes =======================================================
	var shell_boxes = [];
	var i = -1;
	for (var n = 0; n < total; n++) {
		var box = document.getElementById('shellbox'+n);
		if (box == null) {continue;}
		i++;
		shell_boxes[i] = parseInt(box.offsetHeight);
		}
	
	// find out who's longest =====
	shell_boxes.sort(numberorder);
	var longest = shell_boxes[(shell_boxes.length-1)];//alert(longest);
	if (longest < minheight) {longest = minheight;}
	if (pre_height < post_height) {longest += post_height;}
	if (pre_height > post_height) {longest -= pre_height;}
	// /find out who's longest =====
	
	// reset all containers to the longest value =====
	for (var n = 0; n < total; n++) {
		var box = document.getElementById('shellbox'+n);
		if (box == null) {continue;}
		box.style.MozBoxSizing = 'border-box';
		box.style.height = longest+'px';
		}
	// /shell boxes =======================================================
	}

function auto_width() {	
	for (var n = 0; n < document.getElementsByTagName('input').length; n++) {
		//alert(document.getElementsByTagName('input')[n].type);
		var obj = document.getElementsByTagName('input')[n];
		if (
		obj.type == 'submit' ||
		obj.type == 'button' ||
		obj.type == 'radio' ||
		obj.type == 'checkbox'
		) {
			obj.style.width = 'auto';
			}
		}
	}

// AJAX functions =============================================================
function createXMLHttpRequest() {
	try{return new ActiveXObject("Msxml2.XMLHTTP");}
	catch (e) {}
	try{return new ActiveXObject("Microsoft.XMLHTTP");}
	catch (e) {}
	try{return new XMLHttpRequest();}
	catch (e) {}
	alert('XMLHttpRequest not supported');
	return null;
	}

function ajax_sync_response_example(table,table_col,table_id) {
	// use this most of the time, stops the js/browser till the server returns the data, kinda like an alert
	// setting the last argument in xhr.open() below to false makes it synchronous
	var xhr = createXMLHttpRequest();
	if (xhr) {
		var url = '/admintools/process.php?process=ajax_validate_row_exists&table='+table+'&table_col='+table_col+'&table_id='+table_id;
		xhr.open('GET',url,false);
		xhr.send(null);
		//alert(xhr.responseText);// return text
		return xhr.responseText;
		//alert(xhr.responseXML);// return xml obj, NOTE: on process.php MUST set the header like: ob_start(); print $xml; header("Content-type: application/xhtml+xml"); ob_end_flush();
		//return xhr.responseXML;
		}
	else {
		alert('An AJAX connection could not be established.');
		}
	}
function ajax_async_response_example(table,table_col,table_id) {
	// do not use this UNLESS the js/browser needs to continue while the server does its task
	// setting the last argument in xhr.open() below to true makes it synchronous, MUST test the response and then  
	var xhr = createXMLHttpRequest();
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4) {// request is finished
			if(xhr.status == 200) {
				if (xhr.responseText != '') {
					//alert(xhr.responseText);// return text
					my_ajax_function(xhr.responseText);// CANNOT return value!!!!!
					//alert(xhr.responseXML);// return xml obj, NOTE: on process.php MUST set the header like: ob_start(); print $xml; header("Content-type: application/xhtml+xml"); ob_end_flush();
					//my_ajax_function(xhr.responseXML);// CANNOT return value!!!!!
					}
				}
			else {alert('XMLHttpRequest error: '+xhr.responseText);}
			}
		}
	// send with GET =====
	var url = '/admintools/process.php?process=ajax_validate_row_exists&table='+table+'&table_col='+table_col+'&table_id='+table_id;
	xhr.open('GET',url,true);
	xhr.send(null);

	// send with POST =====
/*
	var url = '/admintools/process.php';
	var params = 'process=ajax_validate_row_exists&table='+table+'&table_col='+table_col+'&table_id='+table_id;
	xhr.open('POST',url,true);
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr.setRequestHeader("Content-length", params.length);
	xhr.setRequestHeader("Connection", "close");
	xhr.send(params);
*/
	}

function ajax_check_unique(inputid,table,col,rowid,value) {
	//alert(inputid+','+table+','+col+','+rowid+','+value);return false;
	trim(value);
	if (value == '') {return;}
	var xhr = createXMLHttpRequest();
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4) {// request is finished
			if(xhr.status == 200) {
				if (xhr.responseText != '') {
					//alert(xhr.responseText);
					ajax_print_msg(inputid,xhr.responseText);
					}
				}
			else {alert('XMLHttpRequest error: '+xhr.responseText);}
			}
		}
	// send with GET =====
	xhr.open('GET','/admintools/process.php?process=ajax_check_unique&table='+table+'&col='+col+'&id='+rowid+'&value='+value,true);
	xhr.send(null);
	// send with POST =====
/*
	var url = '/admintools/process.php';
	var params = 'process=ajax_check_unique&table='+table+'&col='+col+'&id='+rowid+'&value='+value;
	xhr.open('POST',url,true);
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr.setRequestHeader("Content-length", params.length);
	xhr.setRequestHeader("Connection", "close");
	xhr.send(params);
*/
	}
function ajax_print_msg(inputid,msg) {
	alert(msg);
	document.getElementById(inputid).focus();
	return false;
	}
// /AJAX functions =============================================================

// jQuery functions ============================================================
// lightbox =====
//$(function() {
	/*
	// Use this example, or...
	$('a[@rel*=lightbox]').lightBox(); // Select all links that contains lightbox in the attribute rel
	// This, or...
	$('#gallery a').lightBox(); // Select all links in object with gallery ID
	// This, or...
	$('a.lightbox').lightBox(); // Select all links with lightbox class
	// This, or...
	$('a').lightBox(); // Select all links in the page
	// ... The possibility are many. Use your creative or choose one in the examples above
	*/
//	$('.gallery a').lightBox(); // Select all links in object with gallery class
//	$('.gallery_2 a').lightBox(); // Select all links in object with gallery_2 class
//});
// /lightbox =====

// prettyPhoto lightbox =====
$(document).ready(function(){
	$(".gallery:first a[rel^='prettyPhoto']").prettyPhoto({animationSpeed:'slow',theme:'light_square',slideshow:2000, autoplay_slideshow: true});
	$(".gallery:gt(0) a[rel^='prettyPhoto']").prettyPhoto({animationSpeed:'fast',slideshow:10000});
	
	$("#custom_content a[rel^='prettyPhoto']:first").prettyPhoto({
		custom_markup: '<div id="map_canvas" style="width:260px; height:265px"></div>',
		changepicturecallback: function(){ initialize(); }
	});
	$("#custom_content a[rel^='prettyPhoto']:last").prettyPhoto({
		custom_markup: '<div id="bsap_1237859" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6" style="height:260px"></div><div id="bsap_1251710" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6"></div>',
		changepicturecallback: function(){ _bsap.exec(); }
	});
});
// /prettyPhoto lightbox =====
// /jQuery functions ============================================================

// sIFR ========================================================================
function sifr() {
	// Replacement calls. Please see documentation for more information.
	/*
	if(typeof sIFR == "function"){
		sIFR.replaceElement(named({sSelector:"body h1", sFlashSrc:"/sIFR/gillsans.swf", sColor:"#000000", sLinkColor:null, sBgColor:null, sHoverColor:null, nPaddingTop:null, nPaddingBottom:null, sFlashVars:null}));
	};
	*/
	}
// sIFR ========================================================================



// utilities ==================================================================
function cb_to_rad(form,obj) {
/*
make a set of checkboxes behave like a set of radio buttons with the added ability to have no selections

call like so:
<input onclick="cb_to_rad(docuemnt.formname,this);" type="checkbox" name="radname" id="radname_1" value="Yes" />'."\r\n";
<input onclick="cb_to_rad(docuemnt.formname,this);" type="checkbox" name="radname" id="radname_2" value="No" />'."\r\n";
*/
	var cb_array = new Array();
	var i = -1;
	for (var n=0;n<form.elements.length;n++) {
		if (form.elements[n].name == obj.name) {
			i++;
			cb_array[i] = form[n];
			}
		}
	for (var n=0;n<cb_array.length;n++) {
		if (obj.checked && cb_array[n].checked && cb_array[n].id != obj.id) {
			cb_array[n].checked = false;
			}
		}
	}
// /utilities ==================================================================


function validate(obj) {
	for (var k in obj) {
		var v = obj[k];
		if (k == 'first_name') {
			var c = check_blank(document.getElementById(k),v);
			if (!c) {return false;}
			}
		if (k == 'last_name') {
			var c = check_blank(document.getElementById(k),v);
			if (!c) {return false;}
			}
		if (k == 'email') {
			var c = check_blank(document.getElementById(k),v);
			if (!c) {return false;}
			var c = check_email(document.getElementById(k),v);
			if (!c) {return false;}
			}
		if (k == 'comments') {
			var c = check_blank(document.getElementById(k),v);
			if (!c) {return false;}
			}
		}// /for (var k in obj) {
	return true;
	
	function check_blank(obj,label) {
		if (obj.value == '') {
			alert('Please provide fill out the  "'+label+'" field');
			obj.focus();
			return false;
			}
		return true;
		}// /function check_blank(obj,label) {
	function check_email(obj,label) {
		if (
		obj.value.indexOf('@') == -1 || 
		obj.value.search(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/)
		) {
			alert('There is a problem with your email address, please check that there are no typos and try again');
			obj.focus();
			return false;
			}
		return true;
		}// /function check_email(obj,label) {
	}// /function validate(obj) {

