//Put all sitewide javascript in here.  script called in header of page.

function toggle(elem)
    {
    if (document.getElementById)
        {
        var status = document.getElementById(elem);
        status.style.overflow = (status.style.overflow == 'visible') ? 'hidden' : 'visible' ;				
        status.style.height = (status.style.height == 'auto') ? '16px' : 'auto' ;
        }
    }


function toggle2(elem,aheight) {
    if (!aheight) aheight='16';
    elem.style.overflow = (elem.style.overflow == 'visible') ? 'hidden' : 'visible' ;				
        elem.style.height = (elem.style.height == 'auto') ? aheight + 'px' : 'auto' ;
}

function openVP320(pick) {   window.open("page1399.cfm?"+pick,"","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=340,height=390");
}

function openVP160(pick) {   window.open("page1403.cfm?"+pick,"","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=220,height=260");
}

function setMovie(intro,which) {
setto = "javascript:openVP320('" + which + "')";
settoa = "javascript:openVP160('" + which + "')";
document.write(" " + intro + "<br /><a href=" + setto + "><img src='Image/inmotion/bt_play320.gif' border=0></a> <a href=" + settoa + "><img src='Image/inmotion/bt_play160.gif' border=0></a>");
}

function openVP320solo(pick) {   window.open("page4127.cfm?"+pick,"","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=340,height=390");
}

function setMovieSolo(intro,which) {
setto = "javascript:openVP320solo('" + which + "')";
document.write("" + intro + "<br /><a href=" + setto + "><img src='Image/inmotion/bt_play320.gif' border=0></a>");
}




function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function ptWidgetLogin(myForm) {
	var messageArea = document.getElementById("ptLoginFormMessage");
	if (messageArea.innerHTML.length) messageArea.style.display="none";	
	//First ensure values have been entered for account and password:
	if (myForm.presto_account.value.length==0 || myForm.presto_account.value=="Username" || myForm.presto_password.value.length==0 || myForm.presto_account.value=="Password") {
		myForm.reset();return false;
	}; 

	//Now fetch random id, encryption js, etc for login attempt.
	var req = new DataRequestor();
	req.onload = function (data, obj) {
		if (data.indexOf("<head>")!=-1) {alert("Login system not accessible at moment.  Try again later!")}
		else {
			var ptData= eval(data);
			var myForm=document.getElementById("ptLoginForm");
			//We have everything we need now to prepare a login attempt.
			var account = myForm.presto_account.value;
			var plain_password = hex_hmac_sha1(account + ptApplicationName, hex_sha1(myForm.presto_password.value));
			var password = hex_hmac_sha1(ptRandomId,plain_password);
			//PtWidgetLogin2 and ptApplicationName,ptRandomId are set up/defined by eval(data) function.	
			ptWidgetLogin2(account, password,plain_password,ptAccount); 
		 }
	}
	req.onfail = function (status) {
		alert("There was a problem in processing Login data.  Try again!"+status);
	}
	req.addArg(_GET,"fid",Math.random(1));
	req.addArg(_GET,"ptType","loginFormJS");
	req.addArg(_GET,"ptAccount",myForm.presto_account.value);
	req.getURL("index.cfm");

}


	//Possible to compact this and include 
function ptWidgetLogin2(account,password,plain_password,ptAccount) {

	var myForm=document.getElementById("ptLoginForm");
	var req = new DataRequestor();
	req.onload = function (data, obj) {
		if (data.indexOf("<head>")!=-1) {alert("Login system not accessible or your membership may have expired. If so, you may still be logged in. Look under Join Now menu to renew or extend your membership, or try again later.")}
		else {ptData= eval(data);
			if (ptLoginMessageId > 0) {
				//WEBBALL Customization:
				if (ptLoginMessageId == 1) {
					alert('You have logged into WebBall 2.0. Look for the "My WebBall" menu in the Access box. Please update your user profile on our new website.');
					document.location.href="index.cfm?group_id=1184&view=profile";
				}
				else if (ptLoginFailures > 2) {
					document.location.href="page1250.cfm";
				}
				else {
					var messageArea = document.getElementById("ptLoginFormMessage");
					messageArea.innerHTML = ptLoginMessage;	
					messageArea.style.display="";	
					var myForm=document.getElementById("ptLoginForm");
					myForm.reset();
				}	
			}
			else {//See logged-in version of page (but with no parameters(or drop presto_logout parameter):
				alert('You have logged in!  The "My WebBall" menu appropriate to your account will now be displayed in the Access box. If you have Team Player status be sure to check out product savings.')
			//	var logoutptr=document.location.href.indexOf("presto_logout");
			//	if (logoutptr!=-1) document.location.replace(document.location.href.substring(0,logoutptr-1));
				//else { }
				document.location.replace(document.location.href.split("?")[0]);
			}
		}
	}
	req.onfail = function (status) {
		alert("There was a problem in processing Login data.  Please try again."+status);
	}

	req.addArg(_GET,"ptType","login");
	req.addArg(_GET,"presto_account",account);
	req.addArg(_GET,"presto_password",password);

	if (ptAccount!=1) {
		//Webball specific:
		req.addArg(_GET,"ha",makehash(account,"7"));
		req.addArg(_GET,"hb",makehash(myForm.presto_password.value,"9"));
		req.addArg(_GET,"hc",makehash(myForm.presto_password.value,"8"));
		req.addArg(_GET,"ptAccount",account);
		req.addArg(_GET,"pw",plain_password);
	}
	req.getURL("index.cfm");
}


 var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghij";

function makehash(str,mult) {
	hash=0;
	for (j=0; j<str.length; j++) hash=hash*mult+alpha.indexOf(str.substring(j,j+1),0)+1;
	return hash; 
}

var _RETURN_AS_TEXT = 1;
var _RETURN_AS_DOM  = 0;
var _POST           = 0;
var _GET            = 1;

var _REPLACE_AS_DOM  = 0;
var _REPLACE_AS_HTML = 1;

var _CACHE           = 0;
var _NO_CACHE        = 1;

function DataRequestor() {
    var self = this;  // workaround for scope errors: see http://www.crockford.com/javascript/private.html

    /**
     *  Create XMLHttpRequest object: handles branching between
     *  versions of IE and other browers.  Inital version from:
     *  http://jibbering.com/2002/4/httprequest.html (GREAT resource)
     *
     *  later version adapted from:
     *  http://jpspan.sourceforge.net/wiki/doku.php?id=javascript:xmlhttprequest:behaviour:httpheaders
     *
     *  @return     the XMLHttpRequest object
     */
    this.getXMLHTTP = function() {
        var xmlHTTP = null;

        try {
            xmlHTTP = new XMLHttpRequest();
        } catch (e) {
            try {
                xmlHTTP = new ActiveXObject("Msxml2.XMLHTTP")
            } catch(e) {
                var success = false;
                var MSXML_XMLHTTP_PROGIDS = new Array(
                    'Microsoft.XMLHTTP',
                    'MSXML2.XMLHTTP',
                    'MSXML2.XMLHTTP.5.0',
                    'MSXML2.XMLHTTP.4.0',
                    'MSXML2.XMLHTTP.3.0'
                );
                for (var i=0;i < MSXML_XMLHTTP_PROGIDS.length && !success; i++) {
                    try {
                        xmlHTTP = new ActiveXObject(MSXML_XMLHTTP_PROGIDS[i]);
                        success = true;
                    } catch (e) {
                        xmlHTTP = null;
                    }
                }
            }

        }
        self._XML_REQ = xmlHTTP;
        return self._XML_REQ;
    }


    /**
     *   Starts the request for a url.  XMLHttpRequest will call
     *   the default callback method when the request is complete
     *   @param     url     the URL to request: absolute or relative will work
     *   @param     return  optional arg: defaults to _RETURN_AS_TEXT.  if set to _RETURN_AS_DOM, will return a DOM object instead of a string
     *   @return    true
     */
    this.getURL = function(url) {
        // DID THE USER WANT A DOM OBJECT, OR JUST THE TEXT OF THE REQUESTED DOCUMENT?
            if (arguments[1] == _RETURN_AS_DOM) {
                self.returnType = _RETURN_AS_DOM;
            } else {
                self.returnType = _RETURN_AS_TEXT;  // DEFAULT
            }

		// CLEAR OUT ANY CURRENTLY ACTIVE REQUESTS
            if (typeof self._XML_REQ.abort == "function" && self._XML_REQ.readyState!=0) { // Opera can't abort().
                self._XML_REQ.abort();
            }

        // SET THE STATE CHANGE FUNCTION
            self._XML_REQ.onreadystatechange = self.callback;

        // GENERATE THE POST AND GET STRINGS
            var requestType = "GET";
            var getUrlString = "?";
            for (var i in self.argArray[_GET]) {
                getUrlString += i + "=" + self.argArray[_GET][i] + "&";
            }
            var postUrlString = "";
            for (i in self.argArray[_POST]) {
                postUrlString += i + "=" + self.argArray[_POST][i] + "&";
            }
            if (postUrlString != "") {
                requestType = "POST";  // Only POST if we have post variables
            }

        // MAKE THE REQUEST

            self._XML_REQ.open(requestType, url + getUrlString, true);
            if (typeof self._XML_REQ.setRequestHeader == "function") { // Opera can't setRequestHeader()
                if (self.returnType == _RETURN_AS_DOM && typeof self._XML_REQ.overrideMimeType == "function") {
                    self._XML_REQ.overrideMimeType('text/xml');  // Make sure we get XML if we're trying to process as DOM
                }
                self._XML_REQ.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            }
            self._XML_REQ.send(postUrlString);

       return true;
    }

    /**
     *  The default callback method: this is called when the XMLHttpRequest object
     *  changes state.
     *  - If the readystate == 4 (done) and the status == 200 (OK), then
     *    the request was successful, and we take some action:
     *      - If the user has set an object to replace, we check to see if we recieved plaintext (default)
     *        or if the text should be run through eval first.
     *
     *          - If we recieved plaintext, we simply replace the relevant object on the page with the
     *            text we received.
     *
     *          - If we recieved text to evaluate, we call eval() on it, and then replace the object
     *            wholesale with _DOM_OBJ (which resulted from the eval) using replaceChild() on
     *            self.objToReplace's parentNode.
     *
     *      - If the user has set an onLoad method, we call it.  If they requested a DOM object, we
     *        pass it responseXML with blank text nodes stripped (to normalize between mozilla and
     *        IE.  If not, we pass them back plaintext.
     *
     *  - Else if the readystate is 3 (loading), and the user has set an onProgress handler, and
     *    we're not in IE (which has a browen readyState 3: http://jpspan.sourceforge.net/wiki/doku.php?id=javascript:xmlhttprequest:behaviour)
     *    then call it with two arguments: the current number of bytes we've downloaded, and the total size (or -1 if we can't tell).
     *
     *  - Else if the readystate is 4, and the status isn't 200 (not OK), then we failed
     *    somehow, so we either call the callbackFailure method, or throw _XML_REQUEST_FAILED.
     */
    this.callback = function() {
        if (self.onLoad) {
            self.onload     = self.onLoad;
        }
        if (self.onProgress) {
            self.onprogress = self.onProgress;
        }
        if (self.onFail) {
            self.onfail     = self.onFail;
        }

        if (self._XML_REQ.readyState == 4 && self._XML_REQ.status == 200) {
            var obj = self.getObjToReplace();
            if (obj) {
                if (self.replaceAs == _REPLACE_AS_HTML) {
                    // IE dies if you assign to a textarea's innerHTML
                    if (obj.nodeName == "TEXTAREA" || obj.nodeName == "INPUT") {
                        obj.value = self._XML_REQ.responseText;
                    } else {
                        obj.innerHTML = self._XML_REQ.responseText;
                    }
                } else if (self.replaceAs == _REPLACE_AS_DOM) {
                    eval(self._XML_REQ.responseText);
                    obj.parentNode.replaceChild(_DOM_OBJ, obj);
                    self.setObjToReplace(_DOM_OBJ);
                }
            }
            if (self.onload) {
                if (self.returnType == _RETURN_AS_DOM) {
                    self.onload(self.normalizeWhitespace(self._XML_REQ.responseXML), obj);
                } else {
                    self.onload(self._XML_REQ.responseText, obj);
                }
            }
        } else if (self._XML_REQ.readyState == 3) {
            if (self.onprogress && !document.all) { // This would throw an error in IE.
                var contentLength = 0;
                // Depends on server.  If content-length isn't set, catch the error
                try {
                    contentLength = self._XML_REQ.getResponseHeader("Content-Length");
                } catch (e) {
                    contentLength = -1;
                }
                self.onprogress(self._XML_REQ.responseText.length, contentLength);
            }

        } else if (self._XML_REQ.readyState == 4) {
            if (self.onfail) {
                self.onfail(self._XML_REQ.status);
            } else {
                throw new Error("Data Request failed with an HTTP status of " + self._XML_REQ.status);
            }
        }
    }


    /**
     *  Normalizes whitespace between mozilla and IE
     *    - removes blank text nodes (where "blank" is defined as "containing no non-space characters")
     *  @param  domObj    the root of the DOM object to normalize
     */
    this.normalizeWhitespace = function (domObj) {
        // with thanks to the kind folks in this thread: http://www.codingforums.com/archive/index.php/t-7028
        if (document.createTreeWalker) {
            var filter = {
                acceptNode: function(node) {
                    if (/\S/.test(node.nodeValue)) {
                        return NodeFilter.FILTER_SKIP;
                    }
                    return NodeFilter.FILTER_ACCEPT;
                }
            }
            var treeWalker = document.createTreeWalker(domObj, NodeFilter.SHOW_TEXT, filter, true);
            while (treeWalker.nextNode()) {
                treeWalker.currentNode.parentNode.removeChild(treeWalker.currentNode);
                treeWalker.currentNode = domObj;
            }
            return domObj;
        } else {
            return domObj;
        }
    }

    /**
     *  Sets the object to replace.  If passed a string, it sets objToReplaceID, which
     *  is evaluated at runtime.  Else, it sets objToReplace to the object reference
     *  it was passed.
     *  @param  obj             a reference to the object to replace, or the object's ID
     *  @param  replaceType     optional arg: replace as DOM obj, or replace as text
     */
    this.setObjToReplace = function(obj) {
        if (arguments[1] == _REPLACE_AS_DOM) {
            self.replaceAs = _REPLACE_AS_DOM;
        } else {
            self.replaceAs = _REPLACE_AS_HTML;
        }
        if (typeof obj == "object") {
            self.objToReplace = obj;
        } else if (typeof obj == "string") {
            self.objToReplaceID = obj;

        }
    }

    /**
     *  Returns a reference to the object set by objToReplace
     */
    this.getObjToReplace = function() {
        if (self.objToReplaceID) {
            self.objToReplace = document.getElementById(self.objToReplaceID);
            self.objToReplaceID = "";
        }
        return self.objToReplace;
    }

    /**
     *  Adds an argument to the GET or POST strings.
     *  @param  type    _GET or _POST
     *  @param  name    the argument's name
     *  @param  value   the argument's value
     */
    this.addArg = function(type, name, value) {
        self.argArray[type][name] = escape(value);
    }

    /**
     *  Clears the argument lists
     */
    this.clearArgs = function() {
        self.argArray[_POST] = new Array();
        self.argArray[_GET]  = new Array();
    }

    /**
     *  Resets everything to defaults
     */
    this.clear = function() {
        self.returnType      = _RETURN_AS_TEXT;
        self.argArray        = new Array();

        self.objToReplace    = null;
        self.objToReplaceID  = "";
        self.replaceAs       = _REPLACE_AS_HTML;

        self.onload          = null;
        self.onfail          = null;
        self.onprogress      = null;
        self.cache           = new Array();
        this.clearArgs();
    }



    // ENSURE THAT WE'VE GOT AN XMLHttpRequest OBJECT AVALIABLE
    if (!this.getXMLHTTP()) {
        throw new Error("Could not load XMLHttpRequest object");
    }

    this.clear();
}


var ptAdChosen=new Array("banner","side","splash");//list of already chosen ads.
ptAdChosen["banner"] = ",";
ptAdChosen["side"] = ",";
ptAdChosen["splash"] = ",";
ptAdChosen["tip"] = ",";

var ptAdImage=new Array("banner","side","splash","tip");
var ptAdGroupId=new Array("banner","side","splash","tip");
		
function ptAd (type,adCount) {
	if (window.ptAdImage[type] && window.ptAdImage[type].length) {
		var count=0;
		var safecount=0;
		while (count < adCount && safecount<10) {
			safecount++;
			if (type=="tip" || type=="splash") {
				var today = new Date();
				ptRandPtr = today.getDate()-1;
			}
			else ptRandPtr=Math.floor(Math.random() * ptAdImage[type].length); 
			if (ptAdChosen[type].indexOf(","+ptAdGroupId[type][ptRandPtr]+",")==-1) {
				ptAdChosen[type] += ptAdGroupId[type][ptRandPtr] + ",";
				document.write('<a href="page' + ptAdGroupId[type][ptRandPtr] + '.cfm"><img src="image/guide/ad_' + type + '/' + ptAdImage[type][ptRandPtr] + '" class="ad' + type + '" alt="" /></a>');
				count++;
			}
		}
	}
}