/***
 ***
 *** GENERIC TOOLS
 *** 
 ***/
function GenericTools () {

	/**
	 * Convert newlines in a string to something that can be displayed in a browser.
	 */
	this.newlinesToHTML = function(text) {
		var result = text.replace(/\r\n/g,"\n");
		result = result.replace(/\n/g,"<br/>\n");
		return result;
	}

	/**
	 * Convert newlines in a string to something that can be displayed in a browser.
	 */
	this.htmlToNewlines = function(text) {
		var result = text.replace(/<[bB][rR][ ]*\/+>/g,""); // we are betting that a newline was put after the BR anyway
		return result;
	}

	/**
	 * Safe method for determining if a variable is available.
	 */
	this.isDefined = function(object, variable) {
		return (typeof(eval(object)[variable]) != "undefined");
	}
	
	/**
	 * Gets the value of the specified cookie.
	 *
	 * name  Name of the desired cookie.
	 *
	 * Returns a string containing value of specified cookie, or null if cookie does not exist.
	 */
	this.getCookie = function(name) {
		var dc = document.cookie;// this returns/reads all cookies for the domain separated by a semicolon
		var prefix = name + "=";// hd=
		var begin = dc.indexOf("; " + prefix);// returns a -1 or whole number for position of "; hd"
		if (begin == -1){ // "; hd" string does not exist - meaning that hd is the first cookie in the collection of cookies for the domain
			begin = dc.indexOf(prefix); //begin is 0 since prefix ("hd") is at the 0 position
			if (begin != 0) {return null;} //begin should be at index 0 - fail if not
		} else {
			begin += 2; // add 2 to current begin -- not sure why. perhaps this is useful if hd is not the first cookie for the domain
		}
		var end = document.cookie.indexOf(";", begin); // search the cookie collection for ";", start the search at begin
		if (end == -1) { // end does not exist so there is only one cookie for the domain
			end = dc.length; // only one cookie for the domain so the end is the length
		}
		return unescape(dc.substring(begin + prefix.length, end)); // return the values between the end of "hd=" and the end of the cookie
	}

	/**
	 * Gets the value of a specified query parameter.
	 *
	 * name  Name of the value from the query string.
	 *
	 * Returns a string containing value of specified parameter, or null if it does not exist.
	 */
	this.getQueryParameter = function(name) {
		// for now, piggyback on SiteLife's function for this.
		return gSiteLife.GetParameter(name);
	}

	/**
	 *
	 */
	this.mouseX = function(evt) {
		if (evt.pageX) return evt.pageX;
		else if (evt.clientX)
		   return evt.clientX + (document.documentElement.scrollLeft ?
								 document.documentElement.scrollLeft :
								 document.body.scrollLeft);
		else return null;
	}
	
	/**
	 *
	 */
	this.mouseY = function(evt) {
		if (evt.pageY) return evt.pageY;
		else if (evt.clientY)
		   return evt.clientY + (document.documentElement.scrollTop ?
								 document.documentElement.scrollTop :
								 document.body.scrollTop);
		else return null;
	}

	/**
	 *
	 */
	this.hideDiv = function(elementId) {
		var el = document.getElementById(elementId);
		if (el) {
			el.style.display = "none";
		}
	}

	/**
	 *
	 */
	this.showDivAtMouse = function(mouseEvent, elementId) {
		var el = document.getElementById(elementId);
		var posx = mouseX(mouseEvent) - 170;    
		var posy = mouseY(mouseEvent);
		//normalize to make sure we at least appear on the screen
		if (posx < 0) posx = 10;
		if (posy < 0) posy = 10;
	
		el.style.left = posx + "px";
		el.style.top = posy + "px";
		el.style.display = "block";
	}

	this.debug = function(s) {
		if (SITELIFE_DEBUG && this.isDefined(window, "console")) {
			console.log(s);
		}
	}
	this.debugObj = function(o) {
		if (SITELIFE_DEBUG && this.isDefined(window, "console")) {
			console.dir(o);
		}
	}

    this.informUser = function(message) {
        window.alert(message);
    }
}

// Instantiate a tools object for use elsewhere.
var tools = new GenericTools();


/***
 ***
 *** USER SESSION MANAGEMENT
 *** 
 ***/
function UserSessionTools () {

    var userKey = null;
    var userDisplayName = null;
    var cookieType = "";

    this.parseCookie = function() {
        this.cookieType = "at";
        var cookie = tools.getCookie("at");
        if (cookie == null) {
            cookie = tools.getCookie("hd");
            this.cookieType = "hd";
        }
        if (this.cookieType == "hd") {
            if (cookie != null && cookie.length > 0) {
                this.userKey = unescape(cookie.split("|")[0]);
                this.userDisplayName = unescape(cookie.split("|")[1]);
            }
        } else if (this.cookieType == "at") {
            if (cookie != null && cookie.length > 0) {
                var cookArray = cookie.split("&");
                var cookMap = new Object();
                for (var u = 0 ; u < cookArray.length ; u++ ) {
                    var keyA = cookArray[u].split("=", 2);
                    cookMap[keyA[0]] = keyA[1];
                }
                this.userKey = cookMap["u"];
                this.userDisplayName = cookMap["a"];
            }
        }
        //window.alert("userKey is " + userKey + " from cookie " + cookie);
        return userKey;
    }

    /**
     * For now, this relies on Pluck's "hd" cookie.  But it is up to Customer to determine who is logged in and how.
     */
    this.getUserKey = function() {
        if (this.cookieType == null) {
            this.parseCookie();
        }
        return this.userKey;
    }
    
    
    /**
     * For now, this relies on Pluck's "hd" cookie.  But it is up to Customer to determine who is logged in and how.
     */
    this.getUserDisplayName = function() {
        if (this.cookieType == null) {
            this.parseCookie();
        }
        return this.userDisplayName;
    }

    /**
     * Is the user logged in?
     */
    this.isLoggedIn = function() {
        var f = this.getUserKey();
        return f != null && f.length > 0;
    }

    /**
     * This writes directly to the page during execution!
     */
    this.addLogInFormWidget = function() {
        document.write("<div id=\"pl__LoginForm\"></div>\n");
    }

    this.displayLogInForm = function() {
        var topDivEl = document.getElementById("pl__LoginForm");
        topDivEl.innerHTML = "<form action=\"" + document.location.href + "\" onsubmit=\"return sessionManager.processLoginForum();\"><input type=\"hidden\" name=\"plckGalleryID\" value=\"" + tools.getQueryParameter("plckGalleryID") +"\">\n      <div style=\"padding:3px; clear:both;\"><div style=\"width:100px; padding:3px; float:left;\"><label for=\"pl__displayName\">Name</label></div><input id=\"pl__displayName\" type=\"text\" name=\"pl__displayName\" /></div>\n      <div style=\"padding:3px; clear:both;\"><div style=\"width:100px; padding:3px; float:left;\"><label for=\"pl__emailAddress\">E-Mail Address</label></div><input id=\"pl__emailAddress\" type=\"text\" name=\"pl__emailAddress\" /></div>\n      <div><input type=\"submit\" name=\"Submit\" value=\"Submit\" class=\"pl__LoginSubmitButton\" /></div>\n    </form>\n";
    }

    this.processLoginForum = function() {
        var d = new Date();
        var secs = parseInt(d.getTime() / 1000);

        var cookieType = "hd";
        var displayName = document.getElementById("pl__displayName").value;
        var emailAddress = document.getElementById("pl__emailAddress").value;

        // validate display name
        if (displayName == null || displayName.length < 1) {
            tools.informUser("You must provide a valid name.");
            return false;
        }
        if (displayName.length > 24) {
            displayName = displayName.substring(0, 24);
        }

        // validate e-mail address
        var validAddressRegEx = /[a-zA-Z0-9_.-]+@[a-zA-Z0-9_.]+\.\w{2,3}/;
        if (emailAddress == null || emailAddress.length < 1
            || ! validAddressRegEx.test(emailAddress)) {
            tools.informUser("You must provide a valid e-mail address.");
            return false;
        }

        // looks like the information is good enough to proceed.
        var uniqUserId = hex_md5(displayName);

        var cookiePart = "" + uniqUserId + "|" + displayName + "|" + secs;
        cookiePart += "|" + emailAddress;

        // write the cookie
        document.cookie = cookieType + "=" + cookiePart + ";path=/;domain=" + document.domain;

        // return true to let the page be reloaded.
        //document.location = document.location;
        return true;
    }
}

// Instantiate the User Session Tools.
var sessionManager = new UserSessionTools();

