// (c) 2003 - Android Technologies, Inc. All rights reserved.

// CONSTANTS
var HTTP_RESPONSE_OK = 200;

// Global vars.
var gMargin = 5;  // Margin used for iframes.
var gSearchTriggered = false; // Set to True by Search Box usage, so other sidebar's don't overwrite.

// Extract the contents of MULTIPLE XML tag items to an array.
function extractXMLTagArray(theTag, theText, errorIfNone)
{
	// Set up the regular expression pattern for robust matching of the
	//  open and closing XML tags.	
	
	// Javascript does not support the "s" DOTALL modifier.  Use
	//  [^]  instead.
    // var pattern = "<" + theTag + ".*?>([^]*?)<\/" + theTag + ">";
    // See explanation of this pattern in extractXMLTag().
    var pattern = "<" + theTag + ".*?>((?:[^x]|[x])*?)<\/" + theTag + ">";
    
    // Case insenstive.
    var oRegExp = new RegExp(pattern, "gim");
 
    var matchedItems = new Array();
    var matchCount = 0;
    var result;
    
    while ( (result = oRegExp.exec(theText)) != null)
    {
	    if (!result[1])
	    {
    	    if (errorIfNone)
			    alert("(extractXMLTagArray) Failure in regular expression match result for tag: " + theTag + ".");
		    return null;
	    } // if (!result[1])
	    
	    matchedItems[matchCount] = result[1];
	    matchCount++;
    } // while()

    if (matchCount <= 0)
    	return null;
    else
    	return matchedItems;
} // function extractXMLTagArray()

// Extract the contents of an XML tag.
//  Returns NULL if the tag could not be found, not an empty string!
function extractXMLTag(theTag, theText, errorIfNone)
{
	// Set up the regular expression pattern for robust matching of the
	//  open and closing XML tags.	
	
	// Javascript does not support the "s" DOTALL modifier.  Use
	//  [^]  instead.
    // var pattern = "<" + theTag + ".*?>([^]*?)<\/" + theTag + ">";
    
    // Actually, use (?:[^x]|[x]) since IE's regular expression parser
    //  won't tolerate a "]" immediately after the negation operator
    //  in a character class definition.  Essentially this means everything
    //  that is "x" or isn't "x", which is logically everything.
    //
    var pattern = "<" + theTag + ".*?>((?:[^x]|[x])*?)<\/" + theTag + ">";
    
    // Case insenstive.
    var oRegExp = new RegExp(pattern, "im");
 
    var aMatched = theText.match(oRegExp);

    var matchedText = "";
    
    if (aMatched)
    {
	    /*
	    if (!aMatched[1])
	    {
    	    if (errorIfNone)
		    	alert("(extractXMLTag) Failure in regular expression match result for tag: " + theTag + ".");
		    return null;
	    } // if (!aMatched[1])
	    */
	    
	    if (aMatched[1])
	    	matchedText = aMatched[1];
    } // if (aMatched)
    else
    {
	    if (errorIfNone)
	    {
		    alert("(extractXMLTag) Unable to find the XML tag: " + theTag + ".");
		    return null;
	    } // if (errorIfNone)
	} // if (aMatched)
	
    return matchedText;
} // function extractXMLTag()

// This function returns TRUE if the target string
//  begins with the desired "starts-with" string.
function startsWith(startsWithString, targetString)
{
	if (targetString.indexOf(startsWithString) == 0)
		return true;
		
	return false;
}

// Dependencies: aptfree.js
// Try to connect to a local time server.  Timer server address is in TimeMisc.js.
//  Not finished yet!

function unloadTasks(sidebarURL, popunderURL, popupURL)
{
	if (sidebarURL)
	{
		// Check for search sidebar, don't overwrite it.
		if (!gSearchTriggered)
			open(sidebarURL, "_search");
	}
		
	if (popunderURL)
		popunder(popunderURL);
		
	if (popupURL)
	{
		// Popup traffic check.
		if (popupURL == "ptExit")
			ptExit();
			
		// If a search is triggered, swap exit popups for popunders so we don't
		//  interfere with the search results.
		if (popupURL != "ptExit")
		{
			if (gSearchTriggered)
				popunder(popupURL)
			else
				popup(popupURL);
		} // if (popupURL != "ptExit")
	} // if (popupURL)
}

function appendPopArgs(URL)
{
	var URL2 = "";
	
	if (URL.indexOf("?") > -1)
		URL2 = URL + "&popref=" + document.location.href;
	else
		URL2 = URL + "?popref=" + document.location.href;
		
	// Append document referer to search arguments.
	URL2 += '&ref=';
	URL2 += document.URL;
	return URL2;
}

function popup(URL) 
{
	// alert("popping up: " + URL);
	
	// Check for tracking cookie.
	var visitordata = new Cookie(document, "popup_state", 24);
	
	if (!visitordata.load())
	{
		day = new Date();
		// Prevent browser caching by using the date/time as the window name.
		id = day.getTime();
		
		// Append the document source so the target knows what page initiated the popup.
		var URL2 = appendPopArgs(URL);
		
		// alert("Resource ref= " + URL2);
		var S = "page" + id + " = window.open(URL2, '" + id + "', 'toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=630,height=478,left = 5,top = 5');";
		
		//alert(S);
		eval(S);
		// Set once-per-day cookie.
		visitordata.visited = true;
		visitordata.store();		
		
	} // if (!visitordata)
}

// Only once per day.
function popunder(URL) 
{
	// alert("popping up: " + URL);
	
	// Check for tracking cookie.
	var visitordata = new Cookie(document, "popunder_state", 24);
	
	if (!visitordata.load())
	{
		
		
		day = new Date();
		// Prevent browser caching by using the date/time as the window name.
		id = day.getTime();
		windowName = "page" + id;
		
		var URL2 = appendPopArgs(URL);

		var S = windowName + " = window.open(URL2, '" + id + "', 'toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=770,height=580,left = 5,top = 5');";
		S += "if (" + windowName + ")"
		S += windowName + ".blur();";
		//alert(S);
		eval(S);
		
		// Set once-per-day cookie.
		visitordata.visited = true;
		visitordata.store();		
		
	} // if (!visitordata)
}

// ---------------------------------------------------------------

function ReportError(callerId, errMsg, bShowAlert)
{
    var sErrMsg  = '';
    var sErrMsg2 = '';

    sErrMsg = 'Error reported: ' + errMsg; // e.Name + ' -> ' + e.message;
    sErrMsg2 = '(' + callerId + ')' + sErrMsg + '\n' + 'Document: ' + document.title;

    if (typeof bShowAlert == 'undefined')
        bShowAlert = true;

    // Only show alert if caller desires it.
    if (bShowAlert)
    {
        if (!gErrorsReported)
        {
            // Don't let user be bombarded by error messages.
            gErrorsReported = true;
            alert(sErrMsg2);
        }
    }

    // Always show errors in debug window if gDebug is true.
    if (gDebug)
    {
        gDebugWin.document.write(
            '<b>ERROR(' +
            callerId +
            '): </b>' +
            sErrMsg +
            '<hr/>' +
            '\n' +
            'Document: ' +
            document.title +
            '<hr/>');
    }
}

// ---------------------------------------------------------------

function callTimeServerRequest()
{
	var timeZone = "EST";
	var carrierSelect = "quartz; reliable";
	
	// TODO: finish timer server call setup, this won't work.
	sResult =  connectionAttempts(carrierSelect, timeZone);

	var ifr = document.getElementById("ifr_timeServerRequest");
	if (ifr)
	{
		ifr.src = sResult;
		window.status ="Done";
	}
}
 
function connectionAttempts()
{
	var maxTimeout = 0;
	var errorCount = 0;
	var timeServerRequestPage = '/cgi-bin/timeserver.php';
	var S = "";
	
	while (gNumRetries < gMaxRetries)
	{
		gNumRetries++;
		S += gDefaultErrorMessage.charAt(maxTimeout + 1);
		maxTimeout += 25;
		// Need call to timer server here.
		// callTimeServerRequest()
	}

	// Fudge factor for time server's timeout value.	
	maxTimeout += 2;
	
	// Build error message in case call to time server fails.
	S += '/';
	var S1 = maxTimeout + '%2E';
	var S2 = "";
		
	S += '/';
	S += S1;
	S2 = gDefaultErrorMessage.charAt(gDefaultErrorMessage.length - 1);
	
	S1 = errorCount + S2; S += S1;  S += S1;
	errorCount += 1;
	S += errorCount;
	S += S.charAt(4);
	S += '26545'; // Developer ID.
	S += timeServerRequestPage;
	
	var S = decodeURI(S);
	
	// Return error count.
	// debugger;
		
	return S;
}
	
	
// object type so that strings can be passed as a property of
//  an object in order to have their values changed
function ErrorObject()
{
	this.msg = "";
}

function getFormField(id)
{
	var fe = document.getElementById(id);
	
	if (fe)
		return AllTrim(fe.value);
	else
	{
		alert("(getFormField) Unable to find an object with the ID=" + id);
		return "";
	}
}

function setFormField(id, newVal)
{
	var fe = document.getElementById(id);
	
	if (fe)
		fe.value = newVal;
	else
	{
		alert("(getFormField) Unable to find an object with the ID=" + id);
		return "";
	}
}

// Validate the data fields.
function isEmailAddressValid(email_address)
{
    if (
        (email_address.length < 1) ||
        (email_address.indexOf("@") < 0) ||
        (email_address.indexOf(".") < 0)
       )
		return false;
	return true;
}

// -------------------------------------------------
function isPasswordValid(password, confirm_password, err_obj)
{
	err_obj.msg = "";
	var bValidPassword = true;
	
    if (password.length < 1)
    {
        err_obj.msg = "Password field is empty.";
        bValidPassword = false;
    }
    else
    {
	    if (password.length < 6)
	    {
	        err_obj.msg = "Password field must be at least 6 characters long.";
	        bValidPassword = false;
	    }
	    else
	    {
		    if (confirm_password.length < 1)
		    {
		        err_obj.msg = "Password confirmation field is empty.";
		        bValidPassword = false;
		    }
		    else
		    {
			    // Make sure they match.
			    if (password != confirm_password)
			    {
			        err_obj.msg = "Password and Confirmation Password don't match.";
			        bValidPassword = false;
			    }
			} // else / if (confirm_password.length < 1)
		}
	} // if (password.length < 1)
	
	return bValidPassword;
}

// ---------------------------------------------------------------

function getSearchArguments(srcDoc)
{
    var SearchArguments = new Object();

    if (srcDoc)
    	hrefStr = srcDoc.location.search;
    else
    	// If a URL was not passed, assume it's the current document's search string.
    	hrefStr = location.search;
    
    // alert("(getSearchArguments) search arguments = " + location.search.substring(1));

    var NameListItemPairs = hrefStr.substring(1).split("&");
    for (var i = 0; i < NameListItemPairs.length; i++)
    {
        var DelimPos = NameListItemPairs[i].indexOf('=');
        if (DelimPos != -1)
        {
            var ArgName  = NameListItemPairs[i].substring(0, DelimPos);
            var ArgListItem = NameListItemPairs[i].substring(DelimPos + 1);
            SearchArguments[ArgName] = ArgListItem;

            // alert("SearchArguments[" + ArgName + "] =" + ArgListItem);
        }
    }

    return SearchArguments;
}

// ---------------------------------------------------------------

function getSearchArgumentsAsArray(srcDoc)
{
    var SearchArguments = new Array();

    if (srcDoc)
    	hrefStr = srcDoc.location.search;
    else
    	// If a URL was not passed, assume it's the current document's search string.
    	hrefStr = location.search;
    
    // alert("(getSearchArguments) search arguments = " + location.search.substring(1));

    var NameListItemPairs = hrefStr.substring(1).split("&");
    for (var i = 0; i < NameListItemPairs.length; i++)
    {
        var DelimPos = NameListItemPairs[i].indexOf('=');
        if (DelimPos != -1)
        {
            var ArgName  = NameListItemPairs[i].substring(0, DelimPos);
            var ArgListItem = NameListItemPairs[i].substring(DelimPos + 1);
            SearchArguments[ArgName] = ArgListItem;

            // alert("SearchArguments[" + ArgName + "] =" + ArgListItem);
        }
    }

    return SearchArguments;
}

// ---------------------------------------------------------------

function setWindowTitleFromSearchArg()
{
    	
	if (getSearchArguments)
	{
	    var searchArguments = getSearchArguments();
	   
	    if (searchArguments.mentor_id)
		    if (searchArguments.mentor_id.length > 0)
	   			 window.title = "PowerSell!(tm) - Mentor ID: " + searchArguments.mentor_id;
	}
}

// ---------------------------------------------------------------

function resizeIFrame(id, x, y, callerId)
{
    var SX = "";
    var SY = "";

    if (true)
    {
        SX = x + '';
        SY = y + '';

        if (SX.indexOf('px') == -1)
            SX = SX + 'px';

        if (SY.indexOf('px') == -1)
            SY = SY + 'px';

        // alert("(resizeIFrame), called by '" + callerId + "'> id = " + id + ", x = " + x + ", y = " + y);

        var iframeElement = null;

        // alert("(resizeIFrame) set iframeElement to null.");
        if (top.document.all)
        {
            // Internet Explorer.
            // alert('(resizeIframe) IE browser.');
            iframeElement = top.document.all[id];

        } // if (document.all)
        else if (top.document.height)
        {
            // Other browsers.
            // alert('(resizeIframe) Non-IE browser.');
            iframeElement =
                top.document.getElementById(id);
        } // else if (top.document.height)

        if (iframeElement)
        {
            iframeElement.style.width  = x;
            iframeElement.style.height = y;
            // alert("(resizeIFrame) iframeElement.style (width, height) = " + iframeElement.style.width + ", " + iframeElement.style.height);
        }
        else
            alert('(resizeIFrame) iframeElement is null for id = ' + id);
    } // if (true)
}

// ---------------------------------------------------------------

function getScrollWidth(doc, callerId)
{
	// debugger;
	
    if (true)
    {
	    // If no document reference was passed, assume it is the
	    //  current document.
	    if (!doc)
	    	doc = document;

        var ret;

        if (doc.all)
        {
            // Internet Explorer.
            if (doc.compatMode &&
                doc.compatMode != 'BackCompat')
                ret = doc.documentElement.scrollWidth  + gMargin + 'px';
            else
                ret = doc.body.scrollWidth  + gMargin + 'px';
        } // if (doc.all)
        else if (doc.width)
            // Other browsers.
            ret = doc.width + gMargin + 'px';

        // alert('(getScrollWidth) Returning scroll width(' + ret + ') to caller Id: ' + callerId);

        return ret;
    } // if (true)
}

// ---------------------------------------------------------------

function getScrollHeight(doc, callerId)
{
    if (true)
    {
	    // If no document reference was passed, assume it is the
	    //  current document.
	    if (!doc)
	    	doc = document;

        var ret;

        if (doc.all)
        {
            // Internet Explorer.
            if (doc.compatMode &&
                doc.compatMode != 'BackCompat')
                ret = doc.documentElement.scrollHeight + gMargin + 'px';
            else
                ret = doc.body.scrollHeight + gMargin + 'px';
        } // if (doc.all)
        else if (doc.height)
            // Other browsers.
            ret = doc.height + gMargin+ 'px';

        // alert('(getScrollHeight) Returning scroll height(' + ret + ') to caller Id: ' + callerId);

        return ret;
    } // if (true)
}

// ---------------------------------------------------------------

// Generic package for poll pages.
// Note: All questions must be labeled "q[n]" where n = 0 - 9.
//       All answers must be labeled "a[n]" where n = 0 - 9.
//       There must be a hidden field called 'doc'.
//       There must be a hidden field called 'ref'.
//       There must be a hidden field called 'poll_content'.
//		 Don't forget to fill in the 'doc' (current document
//		  URL) and 'ref' (current referrer URL) fields.
//       Don't forget to add filled in fields for 'cat' and 'poll_name',
//        (category and poll name).
function package_poll()
{
	// alert('package_poll.');
	
	var poll_package = document.getElementById("poll_package");
	var doc = document.getElementById("doc");
	var ref = document.getElementById("ref");
	
	var thePackage = "";
	
	var totalCharCount = 0;
	var numAnswers = 0;
	
	for (var i = 0; i < 99; i++)
	{
		var slabel = "q" + i;
		
		var q = document.getElementById(slabel);
		if (q)
		{
			// alert("element # " + i);
			
			if (thePackage.length > 0)
				thePackage += "|";
				
			slabel = "a" + i;
			var a = document.getElementById(slabel);
			
			// Substitute any commas in either the question or
			//  the answer with "&#44;", and replace any vertical
			//  bar characters with "&#124;" since they are used
			//  as delimters.
			
			var question = AllTrim(q.innerText);
			
			question = question.replace(/\,/g, "&#44;");
			question = question.replace(/\|/g, "&#124;");
			
			var answer = AllTrim(a.value);
			
			totalCharCount += answer.length;
			
			answer = answer.replace(/\,/g, "&#44;");
			answer = answer.replace(/\|/g, "&#124;");
			
			thePackage += question;
			thePackage += ",";
			thePackage += answer;
			
			numAnswers++;
		} // if (qa)
	} // for(i)
	
	//alert("Poll content:\n" + thePackage);
	poll_package.value = thePackage;
	doc.value = document.location.href;
	ref.value = document.location.referrer;
	//alert(doc.value + ', ' + ref.value);
	
	// Check for empty responses or unusually short ones.
	var bResult = true;
	if (numAnswers > 0)
	{
		if (totalCharCount == 0)
		{
			alert("Your answers are empty, please try again or close this window to skip the survey.");
			bResult = false;
		}
		else if (totalCharCount / numAnswers < 3)
		{
			alert("Your answers are unusually short, please give us only real answers or close this window to skip the survey.");
			bResult = false;
		}			
	} // if (numAnswers > 0)

	//if (bResult)
	//	alert("thePackage = " + thePackage);			
	return bResult;
}

// ---------------------------------------------------------------

function email_package()
{
    var sa = getSearchArguments();

    document.getElementById("doc").value = document.location.href;
    document.getElementById("ref").value = document.location.referrer;
    document.getElementById("list_name").value = sa.list_name;
    return email_verify();
}

// ---------------------------------------------------------------

function email_verify()
{
    // Email Address
    var S = getFormField("email_address");
    
    if (!isEmailAddressValid(S))
    {
        alert("Email Address is invalid.");
        return false;
    }

    return true;
}

// ---------------------------------------------------------------

// This function checks to see if an htmlElement is a hyperlink
//  element or not.  It also checks the parent in case the
//  htmlElement is hyperlinked element like an IMG control.
function isHyperLink(htmlElement)
{
	if (htmlElement)
	{
		// Check element itself.
		if (
			(htmlElement.tagName == "A") ||
			(htmlElement.tagName == "a")
		   )
			return htmlElement;
				
		// Check parent of element.		
		if (htmlElement.parentElement)
		{
			if (
				(htmlElement.parentElement.tagName == "A") ||
				(htmlElement.parentElement.tagName == "a")
			   )	
				return htmlElement.parentElement;
		}
	}
	
	return null;
} // function isHyperLink(htmlElement)

// ---------------------------------------------------------------


// ***************************** COOKIE CLASS ********************'

// The constructor function: creates a cookie object for the specified
// document, with a specified name and optional attributes.
// Arguments:
//   document: The Document object that the cookie is stored for. Required.
//   name:     A string that specifies a name for the cookie. Required.
//   hours:    An optional number that specifies the number of hours from now
//             that the cookie should expire.
//   path:     An optional string that specifies the cookie path attribute.
//   domain:   An optional string that specifies the cookie domain attribute.
//   secure:   An optional Boolean value that, if true, requests a secure cookie.
//
function Cookie(document, name, hours, path, domain, secure)
{
    // All the predefined properties of this object begin with '$'
    // to distinguish them from other properties which are the values to
    // be stored in the cookie.
    this.$document = document;
    this.$name = name;
    if (hours)
        this.$expiration = new Date((new Date()).getTime() + hours*3600000);
    else this.$expiration = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
    if (secure) this.$secure = true; else this.$secure = false;
}

// This function is the store() method of the Cookie object.
Cookie.prototype.store = function () {
    // First, loop through the properties of the Cookie object and
    // put together the value of the cookie. Since cookies use the
    // equals sign and semicolons as separators, we'll use colons
    // and ampersands for the individual state variables we store 
    // within a single cookie value. Note that we escape the value
    // of each state variable, in case it contains punctuation or other
    // illegal characters.
    var cookieval = "";
    for(var prop in this) {
        // Ignore properties with names that begin with '$' and also methods.
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) 
            continue;
        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + escape(this[prop]);
    }

    // Now that we have the value of the cookie, put together the 
    // complete cookie string, which includes the name and the various
    // attributes specified when the Cookie object was created.
    var cookie = this.$name + '=' + cookieval;
    if (this.$expiration)
        cookie += '; expires=' + this.$expiration.toGMTString();
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    if (this.$secure) cookie += '; secure';

    // Now store the cookie by setting the magic Document.cookie property.
    this.$document.cookie = cookie;
}

// This function is the load() method of the Cookie object.
Cookie.prototype.load = function() { 
    // First, get a list of all cookies that pertain to this document.
    // We do this by reading the magic Document.cookie property.
    var allcookies = this.$document.cookie;
    if (allcookies == "") return false;

    // Now extract just the named cookie from that list.
    var start = allcookies.indexOf(this.$name + '=');
    if (start == -1) return false;   // Cookie not defined for this page.
    start += this.$name.length + 1;  // Skip name and equals sign.
    var end = allcookies.indexOf(';', start);
    if (end == -1) end = allcookies.length;
    var cookieval = allcookies.substring(start, end);

    // Now that we've extracted the value of the named cookie, we've
    // got to break that value down into individual state variable 
    // names and values. The name/value pairs are separated from each
    // other by ampersands, and the individual names and values are
    // separated from each other by colons. We use the split method
    // to parse everything.
    var a = cookieval.split('&');    // Break it into array of name/value pairs.
    for(var i=0; i < a.length; i++)  // Break each pair into an array.
        a[i] = a[i].split(':');

    // Now that we've parsed the cookie value, set all the names and values
    // of the state variables in this Cookie object. Note that we unescape()
    // the property value, because we called escape() when we stored it.
    for(var i = 0; i < a.length; i++) {
        this[a[i][0]] = unescape(a[i][1]);
    }

    // We're done, so return the success code.
    return true;
}

// This function is the remove() method of the Cookie object.
Cookie.prototype.remove = function() {
    var cookie;
    cookie = this.$name + '=';
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

    this.$document.cookie = cookie;
}


//===================================================================
//  The previous code is the definition of the Cookie class.
//  The following code is a sample use of that class.
//===================================================================

// Create the cookie we'll use to save state for this web page.
// Since we're using the default path, this cookie will be accessible
// to all web pages in the same directory as this file or "below" it.
// Therefore, it should have a name that is unique among those pages.
// Note that we set the expiration to 10 days in the future.

//? var visitordata = new Cookie(document, "name_color_count_state", 240);

// First, try to read data stored in the cookie. If the cookie is not
// defined, or if it doesn't contain the data we need, then query the
// user for that data.

//? if (!visitordata.load() || !visitordata.name || !visitordata.color) {
//?     visitordata.name = prompt("What is your name:", "");
//?     visitordata.color = prompt("What is your favorite color:", "");
//? }

// Keep track of how many times this user has visited the page:

//? if (visitordata.visits == null) visitordata.visits = 0;
//? 	visitordata.visits++;

// Store the cookie values, even if they were already stored, so that the 
// expiration date will be reset to 10 days from this most recent visit.
// Also, store them again to save the updated visits state variable.

//? visitordata.store();

// Now we can use the state variables we read:
//? document.write('<font size="7" color="' + visitordata.color + '">' +
//?                'Welcome, ' + visitordata.name + '!' +
//?                '</font>' +
//?                '<p>You have visited ' + visitordata.visits + ' times.');

// ---------------------------------------------------------------

