/**
 * google analytics
 */
var gaJsHost;
var pageTracker;

window.onload = function()
{
	loadGoogleAnalytics();
}

function loadGoogleAnalytics()
{
	gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	var ga = document.createElement('script');
	ga.type = 'text/javascript';
	ga.src = unescape(gaJsHost + 'google-analytics.com/ga.js');
	document.body.appendChild(ga);
	window.setTimeout(initGoogleAnalytics, 500);
}

function initGoogleAnalytics()
{
	try
	{
		pageTracker = _gat._getTracker("UA-7973915-1");
		pageTracker._trackPageview();
		
	} 
	catch(err) {}
}


/**
 * the variable used for the AJax calls
 */
var http = null;
/**
 * the toDo array which will be filled
 * by the dig() function and used by the run() function
 */
var toDo;
/**
 * return the flash movie object
 * needed to communicate with the movie
 */
function thisMovie(movieName) 
{

    if (navigator.appName.indexOf("Microsoft") != -1) 
    {
        return window[movieName];
    }
    else 
    {
        return document[movieName];
    }
} // end thisMovie()


function jump(url)
{
	thisMovie("menuUFO").jumpToPage(url);
}

/**
 * fired from inside the flash menu
 * whenever the SWFAddress changes
 */
function requestPage(link)
{
	try { pageTracker._trackEvent("Ajax", "Page Request", link); } catch(err){}
	/**
	 * some pages may have additional query strings
	 * therefore split the string passed from the flash movie
	 * into the url and attributes part
	 */
	link = link.split("?");
	/**
	 * build the query string for the AJAX call
	 */
	var query = "main.php?do=getAjaxContent&url=" + link[0] + "&attributes=" + link[1];
	/**
	 * the function that is going to be executed
	 * after the server returned the data
	 * in this case to show the content
	 */
	var callBack = "showContent";
	/**
	 * initiate the Ajax call
	 */
	getContent(query, callBack);
}

/**
 * executes the Ajax call,
 * retrieves the data from the server
 * and fires the callback function
 */
function getContent(query, callBack)
{
	
	if (window.XMLHttpRequest) 
	{
		http = new XMLHttpRequest();
	} 
	else if (window.ActiveXObject) 
	{
		http = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (http != null) 
	{
		/**
		 * send the data to the php script using GET
		 */
		http.open("GET", query, true);
		/**
		 * on every onreadystatechang run this function
		 */
		http.onreadystatechange = eval(callBack);
		
		http.send(null);
	}

} // end getContent()

/**
 * take the content returned by the Ajax getContent call
 * and print it to the page
 */
function showContent()
{
	if (http.readyState == 4)
	{
		/**
		 * store the responseText in this var
		 */
		var txt = http.responseText;
		/**
		 * put the JS code found in exec comments
		 * inside a hidden input field
		 */
		txt = txt.replace(/<!-- exec:(.+?) -->/g, '<input type="hidden" name="exec" value="$1" \/>');
		/**
		 * get the target div that will receive the content
		 */
		var ajaxWrapper = document.getElementById("siteFrameWrapper");
		/**
		 * fill in the html text
		 */
		ajaxWrapper.innerHTML = txt;
		/**
		 * clear the toDo List
		 */
		toDo = new Array();
		/**
		 * dig through the ajaxWrapper
		 * to find code that needs to be executed
		 */
		dig(ajaxWrapper.firstChild);
		/**
		 * process the the toDo list
		 */
		runToDo();
	}
}


function postContent(query, data, callBack)
{

	if (window.XMLHttpRequest) 
	{
		http = new XMLHttpRequest();
	} 
	else if (window.ActiveXObject) 
	{
		http = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (http != null) 
	{
		// send the data to the php script
		http.open("POST", query, true);
		http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		http.send(data);
		http.onreadystatechange = eval(callBack);
	}

} // end postContent()


/**
 * loop through the toDo array
 * and execute each command in a 500ms interval
 */
function runToDo()
{
	for (var i = 0; i < toDo.length; i++)
	{
		//alert("todo: " + toDo[i]);
		window.setTimeout(toDo[i], 500);
	}
}

/**
 * loop through a DOM object
 * find all <input> nodes with an "exec" name attribute
 * and add their code to the toDo array
 */
function dig(elm)
{
	do
	{
		/**
		 * if this node is hidden skip it
		 */
		if (! isHidden(elm))
		{
			/**
			 * if this is an <input> node
			 * and its name attribute is exec
			 * add its code to the toDo array
			 */
			if (elm.nodeName.match(/input/i) && elm.name == "exec")
			{
				toDo.push(elm.value);
			}
			/**
			 * otherwise check if this node has siblings
			 */
			else if (elm.hasChildNodes())
			{
				/**
				 * if there siblings, dig it
				 */
				dig(elm.firstChild);
			}
		} 
		/**
		 * pick the next sibling
		 */
		elm = elm.nextSibling;
	}
	while (elm);
}

/**
 * detect whether a node is hidden
 */
function isHidden(obj)
{
	if (obj.style)
	{
		if (obj.style.display == "none")
		{
			return true;
		}
	}
	return false;
}

function insertProductMovie(id, pW, pH, flv, thumb, backcolor)
{

	backcolor = (backcolor) ? backcolor : "0xffffff";
	var div = document.getElementById("movieWrapper");
	
	var FO = { 	movie:			"flash/mediaplayer.swf", 
				id:				"productMovieUFO_" + id,
				width:			pW + "px", 
				height:			pH + "px",
				bgcolor:		"#ffffff",
				flashvars: 		 "overstretch=none"
								+"&usefullscreen=false"
								+"&width=" + pW 
								+"&height=" + pH 
								+"&file=" + flv
								+"&image=" + thumb
								+"&backcolor=" + backcolor,
				name:			"productMovieUFO_" + id, 
				majorversion:	"8", 
				build:			"0" 
			};
	UFO.create(FO, "movieWrapper_" + id);
}


function insertProductSlide(child_of)
{
	var FO = { 	movie:			"flash/productSlide.swf", 
				id:				"productSlideUFO",
				name:			"productSlideUFO",
				width:			"100%", 
				height:			"100%",
				bgcolor:		"#ffffff",
				flashvars:		 "&child_of=" + child_of
								+"&path=assets/product_slide/",	
				majorversion:	"8", 
				build:			"0" 
			};
	UFO.create(FO, "slideWrapper");

}



function insertProductSlideBig(child_of)
{
	
	var FO = { 	movie:			"flash/productSlideBig.swf", 
				id:				"productSlideBigUFO_" + child_of,
				name:			"productSlideBigUFO_" + child_of,
				width:			"100%", 
				height:			"100%",
				bgcolor:		"#ffffff",
				flashvars:		 "&child_of=" + child_of
								+"&path=assets/product_slide_big/",	
				majorversion:	"8", 
				build:			"0" 
			};
	UFO.create(FO, "slideBigWrapper_" + child_of);
}


function popUp(id)
{
	var galleryHandler	= "popUpGallery.php?id=" + id;
	var popWidth 		= 495;
	var popHeight 		= 297;
	var popX 			= (screen.width / 2)  - (popWidth / 2);
	var popY 			= (screen.height / 2) - (popHeight / 2);
	
	var newwin = window.open(	galleryHandler,
								"popUp", 
								"height=" + popHeight + ", width=" + popWidth 
								+ ", screenX=" + popX + ", screenY=" + popY 
								+ ", location=no, resizeable=no, scrollbars=no, toolbar=no, status=no" );
}


var visibleSlide = null;

function fadeSlideText(id)
{
	var div = document.getElementById("slide_" + id);
	var step = 1;
	var steps = 15;
	
	var fade_int = setInterval(function()
										{
											if (visibleSlide)
											{
												if( step <= steps)
												{
													visibleSlide.style.opacity = 1 - (step/steps);
													var alpha = 100 - ((step/steps) * 100);
													visibleSlide.style.filter = "alpha(opacity = " + alpha + ")";
													step++;
												}
												else
												{
													step=1;
													visibleSlide = null;
												}
											}
											else
											{
												if( step <= steps)
												{
													div.style.opacity = (step/steps);
													var alpha = (step/steps) * 100;
													div.style.filter = "alpha(opacity = " + alpha + ")";
													step++;
												}
												else
												{
													clearInterval(fade_int);
													visibleSlide = div;
												}
											}
										}, 20);
}

/**
 * loop through a group container's child nodes 
 * and hide all except for a specific container
 */
function toggleSub(group, page)
{
	/**
	 * the wrapping group container
	 */
	var group = document.getElementById("group_" + group);
	/**
	 * the sub-page that we want to show
	 */
	var target = document.getElementById("sub_page_" + page);
	/**
	 * parent's first sub-page
	 */
	var childNode = group.firstChild;
	/**
	 * loop through all childNodes
	 */
	while(childNode)
	{
		if (childNode.nodeName == "DIV")
		{
			/**
			 * hide the node
			 */
			childNode.style.display = "none";
		}
		/**
		 * pick the next child
		 */
		childNode = childNode.nextSibling;
	}
	/**
	 * show the target
	 */
	target.style.display = "block";
	/**
	 * clear the toDo list
	 */
	toDo = new Array();
	/**
	 * run the dig() function on the group's firstChild
	 */
	dig(group.firstChild);
	/**
	 * process the toDo list
	 */
	runToDo();

} // end toggleSub()


function detectScroll(id, prefix)
{
	// get the text container
	var div 		= document.getElementById(prefix + id);
	// get the scrollbar container
	var scrollbar 	= document.getElementById(prefix + 'scrollbar');
	
	// if the text container
	// is smaller than its content
	if (div.scrollHeight > div.clientHeight)
	{ 
		// shrink the text container
		// by the width of the scrollbar
		div.style.width = div.clientWidth - scrollbar.clientWidth;
		// show the scroller
		showScroller(id, prefix);
		div.style.opacity = "1";
	}

} // end detectScroll()

var mySlide = null;

function showScroller(id, prefix)
{
	// get the text container
	var div				= document.getElementById(prefix + id);
	var msg				= document.getElementById("step");
	var scrollHeight	= div.scrollHeight;
	var clientHeight	= div.clientHeight;
	var scrollSteps 	= scrollHeight - clientHeight;
	var offset			= Math.min(div.scrollTop, scrollSteps);
	var percent 		= clientHeight / scrollHeight;
	var scrubberHeight 	= Math.max(10, Math.round(clientHeight * percent));
	
	
	document.getElementById(prefix + "scroller").style.display 	= "block";
	document.getElementById(prefix + "scrollbar").style.height 	= clientHeight + "px";
	document.getElementById(prefix + "scrubber").style.height  	= 50 + "px"; 
	document.getElementById(prefix + "scroller").style.left 	= div.clientWidth + "px";
	document.getElementById(prefix + "scroller").style.top 		= div.offsetTop + "px";
	
	

	mySlide = new Slider(	$(prefix + 'scrollbar'), 
								$(prefix + 'scrubber'), 
								{	steps: 		scrollSteps,
									mode:		'vertical',
									onChange: 	function(step) { div.scrollTop = step; }
								}
							).set(offset);	
							
}// end showScroller()

function updateScroller(id, prefix)
{
	var div				= document.getElementById(prefix + id);
	var scrollHeight	= div.scrollHeight;
	var clientHeight	= div.clientHeight;
	var scrollSteps 	= scrollHeight - clientHeight;
	var offset			= Math.min(div.scrollTop, scrollSteps);
	var percent 		= clientHeight / scrollHeight;
	var scrubberHeight 	= Math.max(10, Math.round(clientHeight * percent));
	
	mySlide.options.steps = scrollSteps;
	mySlide.set(offset);

}// end updateScroller()


function newsExpand(id)
{
	// the teaser
	var teaser = document.getElementById("news_archive_teaser_" + id);
	// the full content
	var content = document.getElementById("news_archive_content_" + id);
	// the more link
	var moreLink = document.getElementById("news_archive_moreLink_" + id);
	// detect what to do
	var todo = (teaser.style.display != "none") ? "expand" : "collapse";
	
	switch (todo)
	{
		case "expand":
			// hide the teaser
			teaser.style.display = "none";
			// show the content
			content.style.display = "block";
			// change the more link
			moreLink.innerHTML = "[back]";
			break;
		
		case "collapse":
			// show the teaser
			teaser.style.display = "block";
			// hide the content
			content.style.display = "none";
			// change the more link
			moreLink.innerHTML = "[+more]";
			break;
	
	} // end switch
	
	// update the scrollbar
	var newsWrapper			= teaser.parentNode.parentNode.parentNode.parentNode.parentNode.id;
	var newsWrapperPrefix 	= newsWrapper.replace(/(.*?)[0-9]{1,}$/, '$1');
	var newsWrapperID 		= newsWrapper.replace(/.*?([0-9]{1,})$/, '$1');
	updateScroller(newsWrapperID, newsWrapperPrefix);
	
} // end newsExpand()


function jumpToNews(prefix, newsID)
{
	//alert("jumping");
	//var newsID				= location.search.match(/showNews=([0-9]{1,})/);
	if (newsID)
	{
		var newsItem 			= document.getElementById(prefix + newsID);
		var newsWrapper			= newsItem.parentNode;
		var newsWrapperPrefix 	= newsWrapper.id.replace(/(.*?)[0-9]{1,}$/, '$1');
		var newsWrapperID 		= newsWrapper.id.replace(/.*?([0-9]{1,})$/, '$1');
		
		// expand the news
		newsExpand(newsID);
		// scroll news to top
		newsWrapper.scrollTop = newsItem.offsetTop;
		// update the scroller
		updateScroller(newsWrapperID, newsWrapperPrefix);
	}
}


function clearValue(field)
{
	if (field.value == field.defaultValue) 
	{
		field.value="";
	}
}

function restoreValue(field)
{
	if (field.value.replace(/ /g, "").length < 1)
		field.value = field.defaultValue;
}


////// CONTACT FORM /////////////////////
function initFileUpload()
{

	var FO = { 	movie:"flash/contactAttachUpload.swf", 
				id:"fileUploadUFO",
				width:"100%", 
				height:"100%",
				bgcolor:"#ffffff", 
				wmode:"transparent",
  				name:"fileUploadUFO", 
  				majorversion:"8", 
  				build:"0" 
  			};
  	UFO.create(FO, "msg");
  	
} // end initFileUplaod()

function showFileOpen(type)
{
	showLoader();
	thisMovie("fileUploadUFO").browse(type);
	
} // end showFileOpen()

function showLoader()
{
	var pageSize = getPageSize();
	var div = document.getElementById("msg");
	div.style.width = pageSize[0] + "px";
	div.style.height = pageSize[1] + "px";
	div.style.top = pageSize[2] + "px";
	div.style.left = pageSize[3] + "px";

}// end showLoader()


function hideLoader()
{
	var div = document.getElementById("msg");
	div.style.width = "10px";
	div.style.height = "10px";
	div.style.top = "0px";
	div.style.left = "0px";
	
}// end hideLoader()


function contactForm_picFile()
{
	
	var details = 	{	query:"do=contactAttachment&sid=" + sid,
						select:"singleContact",
						description: "All Files",
						extension: "*.*",
						processingScript:"../main.php",
						callback:"contactForm_uploadComplete"
					};	

		
	showFileOpen(details);
}

function addAttachment(key)
{
	// store the key inside the form
	document.contactForm.fld_isAttached.value = sid + "_" + key;
	// toggle the button
	document.getElementById("addAttachBtn").style.display = "none";
	document.getElementById("removeAttachBtn").style.display = "block";
}

function contactForm_removeFile()
{
	// clear the key
	document.contactForm.fld_isAttached.value = "";
	// toggle the button
	document.getElementById("addAttachBtn").style.display = "block";
	document.getElementById("removeAttachBtn").style.display = "none";
	// destroy the file reference
	thisMovie("fileUploadUFO").removeAttached();
}


function contactForm_uploadComplete()
{
	alert("upload complete");
}


function uploadAttachment(obj)
{
	showLoader();
	thisMovie("fileUploadUFO").uploadAttached(obj);
}


function validateForm()
{
	var check = true;
	var required = new Array(0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0);
	var fieldNames = new Array(
								"salutation",
								"firstName",
								"lastName",
								"company",
								"address",
								"city",
								"state",
								"zip",
								"country",
								"msg",
								"phone",
								"fax",
								"mail",
								"website",
								"interest"
							);
	
	
	// check the required fields
	for (var i = 0; i < required.length; i++)
	{
		if (required[i])
		{
			if(eval("document.contactForm.fld_" + i).value == eval("document.contactForm.fld_" + i).defaultValue 
				|| eval("document.contactForm.fld_" + i).value.replace(/ /g, "").length < 1)
			{
				check = false;
				break;
			}
		}
	}
	
	// if a required field
	// was left blank
	// print a message
	if (! check) 
	{
		var msg = "There was a problem with at least one field.\nPlease check your details again.";
		alert(msg);
	}
	else
	{
		// gather field data
		var formString = "";
		for (var i = 0; i< required.length; i++)
		{
			var id = fieldNames[i];
			formString	+= (eval("document.contactForm.fld_" + i).value != eval("document.contactForm.fld_" + i).defaultValue)
							? "&" + id + "=" + encodeURI(eval("document.contactForm.fld_" + i).value)
							: "&" + id + "=" + "";
		}
		
		// add the isAttached value
		formString += "&isAttached=" + document.contactForm.fld_isAttached.value;
		
		// upload the file
		// let flash call the sendform
		if (document.contactForm.fld_isAttached.value != "")
		{
			// upload the attachment
			var obj = 	{
							callBack: 		"postContent",
							query:	 		"main.php?do=sendForm",
							data: 			formString,
							javaCallBack: 	"showContent"
						}
			uploadAttachment(obj);
		}
		// if there is no attachment
		// send the form right away
		else
		{
			postContent("main.php?do=sendForm", formString, "showContent");
		}
	}
	
}













