/* Basic JavaScript Document - for universal javascript functions and variables */
/* Created by Jonathan Pratchios - Property of QAS */

function getElement(id){
/***************************************************************
Detail 		:	Browser compatible element "getter"
Arguments	:	id = id of element to get 	
***************************************************************/
	if (document.all) return document.all[id];
	if (document.getElementById(id)) return document.getElementById(id);
	return null;
}
/*============================================================*\
ERROR TESTING
\*============================================================*/
/*
var reportStatus = new Array();
function report ( msg ) {
    reportStatus.push ( msg );
}
function showReport ( ) {
    alert ( reportStatus.join ( "\n" ) );
}
window.onerror = function ( err, url, line ) {
    report ( err + " [" + url + " - line " + line + "]" );
    showReport();
}
*/

/*============================================================*\
Initialize Globals
\*============================================================*/
var thisURL = unescape(window.location.pathname);
var titles = new Array();
var activePane = null;



/*============================================================*\
================================================================
                       Global Functions
================================================================
\*============================================================*/

function browserDetect(){
/***************************************************************
Detail 		:	detects the browser and OS version information
***************************************************************/
	var detect = navigator.userAgent.toLowerCase();
	var OS,browser,version,total,thestring;
	
	var checkIt = function (string){
		place = detect.indexOf(string) + 1;
		thestring = string;
		return place;
	}
	
	if (checkIt('konqueror'))
	{
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser = "Safari"
	else if (checkIt('omniweb')) browser = "OmniWeb"
	else if (checkIt('opera')) browser = "Opera"
	else if (checkIt('webtv')) browser = "WebTV";
	else if (checkIt('icab')) browser = "iCab"
	else if (checkIt('msie')) browser = "IE"
	else if (!checkIt('compatible'))
	{
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";
	
	if (!version) version = detect.charAt(place + thestring.length);
	
	if (!OS)
	{
		if (checkIt('linux')) OS = "Linux";
		else if (checkIt('x11')) OS = "Unix";
		else if (checkIt('mac')) OS = "Mac"
		else if (checkIt('win')) OS = "Windows"
		else OS = "an unknown operating system";
	}
	
	this.browser = browser
	this.version = version
	this.OS = OS
}
_clientInfo = new browserDetect();

function speedCheck(){
	var date1 = new Date();
	for (var i=0, j=1; i<100000; i++) j++;
	var date2 = new Date();
	return date2.getTime() - date1.getTime();
	}

if (speedCheck() < 100){
		_clientInfo.cpu = 'fast'; //fast computer
	}else{
		_clientInfo.cpu = 'slow'; //slow computer
	}


function setCookie(name, value, expires, path, domain, secure) {
/***************************************************************
Detail 		:	Sets a Cookie with the given name and value.
Arguments	:	name 		= Name of the cookie
				value 		= Value of the cookie
				[expires] 	= Expiration date of the cookie (default: end of current session)
				[path] 		= Path where the cookie is valid (default: path of calling document)
				[domain] 	= Domain where the cookie is valid (default: domain of calling document)
				[secure] 	= Boolean value indicating if the cookie transmission requires a secure transmission
***************************************************************/
	expDate = new Date()
    document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expDate.setFullYear(takeYear(today)+1) : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "")
}


function getCookie(name) {
/***************************************************************
Detail 		:	Gets the value of the specified cookie or null if cookie does not exist.
Arguments	:	name = Name of the desired cookie
***************************************************************/
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}


function deleteCookie(name, path, domain) {
/***************************************************************
Detail 		:	Deletes the specified cookie.
Arguments	:	name 		= Name of the cookie
				[path] 		= Path where the cookie is valid (default: path of calling document)
				[domain] 	= Domain where the cookie is valid (default: domain of calling document)
***************************************************************/
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}


/*============================================================*\
================================================================
                  Links and Tooltip Handler
================================================================
\*============================================================*/


function externalLinks() {
/***************************************************************
Detail 		:	provides a target="_blank" to all rel="external" links for XHTML strict compatability
***************************************************************/
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");
	for (i=0; i < anchors.length; i++){
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel")
		&& anchor.getAttribute("rel").indexOf("external") >= 0 ){
			anchor.target = "_blank";
		}
	}
}

function accordian() {
/***************************************************************
***************************************************************/
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");
	for (i=0; i < anchors.length; i++){
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel")
		&& anchor.getAttribute("rel").indexOf("accordian") >= 0 ){
			anchor.onclick = function(){
				alert('test');
			}
		}
	}
}


function tipLinks(e) {
/***************************************************************
Detail 		:	creates tooltip for all links with title atributes
***************************************************************/
	element = YAHOO.util.Event.getTarget(e)
	if(element.tagName.toLowerCase() == 'a' || element.tagName.toLowerCase() == 'area' || element.tagName.toLowerCase() == 'img' && element.title && element.parentNode.tagName.toLowerCase() == 'a'){
		var this_anchor = element;
	}else if(element.parentNode.tagName && element.parentNode.tagName.toLowerCase() == 'a'){
		var this_anchor = element.parentNode;
	}		
	
	if(this_anchor){
		//if(timeout_overlib){window.clearTimeout(timeout_overlib)}
		if (e.type == 'mouseover' && this_anchor.getAttribute("title")){	
			tip_backupTitle = this_anchor.getAttribute("title")	
			overlib(tip_backupTitle, DELAY, 250);
			this_anchor.title = '';
			
			
		}else if(e.type == 'mouseout' && tip_backupTitle || e.type == 'mouseup' && tip_backupTitle){
			this_anchor.title = tip_backupTitle;
			tip_backupTitle = ''
			nd(10); 
		}
	}
}
function formatTip(this_anchor){
/***************************************************************
Detail 		:	Formats caption for all <a> tooltips with defined rel attribute
***************************************************************/
		var tip_caption = getElement('overDiv').getElementsByTagName("span")[0];
		if(this_anchor.getAttribute("rel")){
			tip_rel = this_anchor.getAttribute("rel").split(' ');
			tip_caption.className = getVal(tip_rel[0],'hidden')
			if(tip_rel){tip_caption.innerHTML = tip_caption_ary[tip_rel[0]]}}
		}
	
		var tip_caption_ary = new Array();
		tip_caption_ary['article'] = "Article Summary";
		tip_caption_ary['external'] = "(will open in new window)";
		tip_caption_ary['ad'] = "Trusted Link";
		tip_caption_ary['definition'] = "Definition:";
		var tip_backupTitle = ''
		if (_clientInfo.cpu == 'fast'){
		YAHOO.util.Event.addListener(document, 'mouseover', tipLinks)
		YAHOO.util.Event.addListener(document, 'mouseout', tipLinks)
		YAHOO.util.Event.addListener(document, 'mouseup', tipLinks)
}


/*============================================================*\
================================================================
              Style, Class, and element Handling
================================================================
\*============================================================*/


function assignClass() {
/***************************************************************
Detail 		:	Assigns a class to all dynamically generated anchors (links)
***************************************************************/
	var anchors = document.getElementsByTagName("a");
	var areas = document.getElementsByTagName("area");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		
		switch(anchor.getAttribute("rel")){
			case 'ad external': anchor.className = "ad_external";
			case 'ad internal': anchor.className = "ad_external";
			case 'definition': anchor.className = anchor.getAttribute("rel");
			
			default:
				break;
		}
	}
}


function stripe(id) {
/***************************************************************
Detail 		:	Applies stripes to table called for readability
***************************************************************/

    // the flag we'll use to keep track of 
    // whether the current row is odd or even
    var even = false;
  
    // if arguments are provided to specify the colours
    // of the even & odd rows, then use the them;
    // otherwise use the following defaults:
    var evenColor = arguments[1] ? arguments[1] : "#edf3fe";
    var oddColor = arguments[2] ? arguments[2] : "#fff";
  
    // obtain a reference to the desired table
    // if no such table exists, abort
    var element = document.getElementById(id);
    if (! element) { return; }
		
	if (element.tagName.toLowerCase() == 'div'){
	
	var rows = element.getElementsByTagName("li")
	
		for (var h = 0; h < rows.length; h++) {
			rows[h].className = even ? "alt" : "";
			even =  ! even;
		}
			
	}else{
	
    // by definition, tables can have more than one tbody
    // element, so we'll have to get the list of child
    // <tbody>s 
    var tbodies = element.getElementsByTagName("tbody");

    // and iterate through them...
    for (var h = 0; h < tbodies.length; h++) {
    
     // find all the &lt;tr&gt; elements... 
      var trs = tbodies[h].getElementsByTagName("tr");
      
      // ... and iterate through them
      for (var i = 0; i < trs.length; i++) {

	    // avoid rows that have a class attribute
        // or backgroundColor style
	    if (!hasClass(trs[i]) && ! trs[i].style.backgroundColor) {
 
         // get all the cells in this row...
          var tds = trs[i].getElementsByTagName("td");
        
          // and iterate through them...
          for (var j = 0; j < tds.length; j++) {
        
            var mytd = tds[j];

            // avoid cells that have a class attribute
            // or backgroundColor style
	        if (! hasClass(mytd) && ! mytd.style.backgroundColor) {
        
		      mytd.style.backgroundColor = even ? evenColor : oddColor;
              
            }
          }
        }
        // flip from odd to even, or vice-versa
        even =  ! even;
      }
    }
	}
	}
	function hasClass(obj) {
     var result = false;
     if (obj.getAttributeNode("class") != null) {
         result = obj.getAttributeNode("class").value;
     }
     return result;
}   


function getVal(requestVal,defaultVal){
/***************************************************************
Detail 		:	returns default value if requsted value is null
Arguments	:	requestVal = requested value 
				defaultVal = default value 	
***************************************************************/
	if (requestVal != null && requestVal != '' && requestVal != 'undefined'){		
		return requestVal;
	}else{
		return defaultVal;
	}
}


function focusElement(e){
/***************************************************************
Detail 		:	Swaps the class of (id) to 'focus' for UI feedback
Arguments	:	e = element to swap 	
***************************************************************/
	if(e.className.indexOf('focus') >= 0){
		this.className=this.className.replace(new RegExp(" hover\\b"), "")
	}else{
		this.className+=" hover";
	}
	return null;
}

function swapClass(e,val){
/***************************************************************
Detail 		:	Assigns the class of (id) to received value
Arguments	:	e = element to assign class	
				val = className to assign
***************************************************************/
	if(!e.id){e = eval("getElement(e)")}
	if(val){
		e.className = val;
		return;
		}
	switch (e.className){
	case 'inactive':
		e.className = 'active'
		break
	case 'active':
		e.className = 'inactive'
		break
	case 'small':
		e.className = 'large'
		break
	case 'large':
		e.className = 'small'
		break
	}
}

function swapMenu(){

	if (getElement('nav-global').className != "active"){
		var anim_1 = new YAHOO.util.Anim('fadeout', { opacity: { from: .995, to: .15 } }, .33, YAHOO.util.Easing.easeIn);
	}else{
		swapClass(getElement('nav-global'));
		var anim_1 = new YAHOO.util.Anim('fadeout', { opacity: { to: .995 }}, .33, YAHOO.util.Easing.easeOut);
	}
	
	var cleanup_1 = function(){
		if(getElement('blockout').className != 'active'){swapClass(getElement('nav-global'));}
		swapClass(getElement('blockout'));
		swapClass(getElement('fadeout'));
		if (_clientInfo.cpu == 'fast'){anim_1.onComplete.unsubscribe()}
	}
	
	if (_clientInfo.cpu == 'fast'){
		anim_1.onComplete.subscribe(cleanup_1);
		anim_1.animate()
	}else{
		cleanup_1()
	};
}


function ajaxLoader(loc){
/***************************************************************
Detail 		:	Loads AJAX component into iFrame
Arguments	:	loc = location of file to be loaded 	
***************************************************************/
	//x = document.location.href
	URIbase = "http://www.ptinr.com/data/" //x.slice(0, x.lastIndexOf('/pages') + 1)
	frames['ajaxFrame'].location.href = URIbase + loc
}

function formVerification(form){
/***************************************************************
Detail 		:	Verifies form to ensure content is entered in correctly
***************************************************************/
	var error = new Object()
	var element_ary = form.getElementsByTagName("label");
	var field_label = function (el){
		for (x in element_ary){ 
			if (element_ary[x].htmlFor == el.name){
				return element_ary[x].getElementsByTagName("span")[0].innerHTML
			}
		}
	}
	for (var i=0; i < form.elements.length; i++){
		field = form.elements[i]
		if (field && field.className != "hidden" && field.type != 'hidden'){
			var label = field_label(field)
			if(field.value == ""){
					error.message = "Please provide " + label.toLowerCase(); error.field = field; error.val = field.value; return error;
			}else{
				if (field.name.indexOf('email') >= 0){		// If an email field
					if (field.value.indexOf("@") < 3 || field.value.lastIndexOf(".") < field.value.length - 5){
						error.message = "Please provide a valid email address"; error.field = field; error.val = field.value; return error;
					}
				}else{
					
				}
			}
		}
	}
	
	return null
}


function keyCapture(){
/***************************************************************
Detail 		:	Captures the last key pressed and responds accordingly
***************************************************************/
	
}

function pageLoad(){
/***************************************************************
Detail 		:	Dummy Function
***************************************************************/
	
}





/*=============================================*\
Auto Excecute the following functions onload:
\*=============================================*/
window.onload = function () { externalLinks(); assignClass();} 






/*=============================================*\
SCRAP CODE FOR BUILDING
\*=============================================*/

	function accordian(target){
		for(i=1; i <= 6; i++){
			id = 'accordian'+i;
			if(target == id){
				getElement(id).className = 'accordian_pane active';
			}else{
				getElement(id).className = 'accordian_pane';
				
			}
		}
	}


/*
function accordian(){
	// handle droppable parent object events even more differently than sortable
	
	
	$$('.accordian_pane').each(function(pane, index){
		pane.addEvent('click', function(event){
				if(event){event = new Event(event).stop()};
				activePane = (activePane)?activePane:$('accordian1');
				activePane.removeClass('active');
				this.addClass('active');
				activePane = $(this.id);
		});
	}); 
	
	
}*/
