
/* --------------------------------------------
UrLite
--------------------------------------------- */
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function UrLite() {
    this.login = login;
    this.loadCookies = loadCookies;
    this.writeIdCookie = writeIdCookie;
    this.redirectToUr = redirectToUr;
	this.getLoginPath = getLoginPath;
	this.logout = logout;
	this.getEnvironment = getEnvironment;

    function login(urUser, applicationConfig) {
        var cookies = this.loadCookies();

	
        if (cookies['value']) {
            urUser.vignetteValueCookie.parse(cookies['value']);
        }

        if (cookies['UserLoginCookie']) {
            urUser.valueCookie.parse(cookies['UserLoginCookie']);
        }

        if (urUser.getUserId() == null || urUser.getUserId() < 0) {
            if (applicationConfig.requiresLogin == true) {
                writeIdCookie(cookies, urUser);
                this.redirectToUr(urUser, applicationConfig);
            }
        } else {
			urUser.isLoggedIn = true;
		}

        writeIdCookie(cookies, urUser);

        if (cookies['UserRoleCookie']) {
            urUser.roleCookie.parse(cookies['UserRoleCookie']);
        }

	if (cookies['role']) {
            urUser.vignetteRoleCookie.parse(cookies['role']);
        }

        if (applicationConfig.requiredRoles != null && applicationConfig.requiredRoles.length > 0 && applicationConfig.requiresLogin==true) {
            for (var i = 0; i < applicationConfig.requiredRoles.length; i++) {
		    if (urUser.hasRoleByName(applicationConfig.requiredRoles[i]) == false) {
                    this.redirectToUr(urUser, applicationConfig);
                }
            }
        }
    }

	function logout(urUser, applicationConfig) {
		var domain = getPrimaryDomain();
		deleteLoginCookie("value", "/", domain);
		deleteLoginCookie("role", "/", domain);
		deleteLoginCookie("userLoginCookie", "/", domain);
		deleteLoginCookie("userRoleCookie", "/", domain);
		
		urUser.valueCookie.clear();
		urUser.roleCookie.clear();
		urUser.vignetteValueCookie.clear();
		urUser.vignetteRoleCookie.clear();
		
		urUser.isLoggedIn = false;
	}
	
	function deleteLoginCookie(name, path, domain) {
		document.cookie = name + "=" + "; path=" + path +  "; domain=" + domain + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
	
	function getEnvironment() {
		switch (document.location.hostname) {
			case "localhost":
			case "127.0.0.1":
			case "vdev2.scripps.com":
				return "DEV";
			case "staging.scrippsweb.com":
				return "STAGE";
			default:
				return "PROD";
		}
	}

    function getPrimaryDomain() {
        var theUrl = document.domain;
        var urlLength = theUrl.length;
        var firstDot = theUrl.lastIndexOf(".");
        var secondDot = theUrl.lastIndexOf(".", firstDot - 1);
        var primaryDomain = theUrl.substr(secondDot);
        return primaryDomain;
    }
	

    function redirectToUr(urUser, applicationConfig) {
		window.location = getLoginPath(applicationConfig);
    }
	
	function getLoginPath(applicationConfig) {
		var loginPath;
        if (applicationConfig.urVersion() == "1") {
            loginPath = applicationConfig.loginServer[getEnvironment()] + applicationConfig.applicationPath + '?a=fflogin&url=' + escape(applicationConfig.applicationEntryPage) + '&an=' + escape(applicationConfig.applicationName) + '&ac=' + escape(applicationConfig.applicationCode);
        } else {
            loginPath = applicationConfig.loginServer[getEnvironment()] + applicationConfig.applicationPath + 'urValidation.html?applicationId='+applicationConfig.applicationCode;
        }
		
		return loginPath
	}

    function loadCookies() {
        var cookies = new Array();
        if (document.cookie != '') {
            var cookieArray = document.cookie.split(';');
            for (var i = 0; i < cookieArray.length; i++) {
                var cookiesValues = cookieArray[i].split('=');
                cookies[cookiesValues[0].trim()] = cookiesValues[1];
            }
        }
        return cookies;
    }


    function writeIdCookie(cookies, user) {
        var id = new IdCookie();
        id.createCookie(cookies, user);
    }
	
}

/* --------------------------------------------
IdCookie Global variables - for backward compatibility
--------------------------------------------- */
var userIdCookieUserId;
var userIdEmail;
var userIdCookieCreateDt;
var userIdCookieVersion;

/* --------------------------------------------
IdCookie
--------------------------------------------- */
function IdCookie() {
    this.id = "";
    this.email = "";
    this.createDate = new Date();
    this.version = "2.0";
    this.createCookie = createCookie;
    this.writeCookie = writeCookie;
    this.domain = getPrimaryDomain();
    this.secure = "";
    this.path = "/";
    this.cookieName = 'userIdCookie';
    this.expirationDate = new Date(new Date().getTime() + (10000 * 1000 * 60 * 60 * 24));
	
	function setGlobalValues() {
		// Store in global vars for compatibility
		userIdCookieUserId = this.id;
		userIdEmail = this.email;
		userIdCookieCreateDt = this.createDate;
		userIdCookieVersion = this.version;
	}
	
	function createCookie(cookies, user) {
		var updtCookie = false;
		
		if (cookies['userIdCookie'] != undefined) {
			// Load the current id cookie values
			this.id = getCookieKeyValue(cookies['userIdCookie'], 'userId', 'ZZ');
			this.email = getCookieKeyValue(cookies['userIdCookie'], 'email', 'ZZ');
			this.createDate = getCookieKeyValue(cookies['userIdCookie'], 'createDate', 'ZZ');
			this.version = getCookieKeyValue(cookies['userIdCookie'], 'cookieVersion', 'ZZ');
		}
		
		if (user.isLoggedIn) {
			// Compare the id cookie with UR values
			if (this.id != user.getUserId()) {
				this.id = user.getUserId();
				updtCookie = true;
			}
			if (this.email != user.getEmail()) {
				this.email = user.getEmail();
				updtCookie = true;
			}
		}
		
		if (this.id == "") {
			// Initialize id cookie
			this.id = getRandNumber(10);
			updtCookie = true;
		}
		
		setGlobalValues();
		
		if (updtCookie) {
			// Save updated id cookie
			this.writeCookie();
		}
	}


    function writeCookie() {
        var cookieValue = 'userIdZZ' + this.id + 'ZZemailZZ' + this.email + 'ZZcreateDateZZ' + this.createDate + 'ZZcookieVersionZZ' + this.version + 'ZZ';
        document.cookie = this.cookieName + "=" + escape(cookieValue) +
                          ( ( this.expirationDate ) ? ";expires=" + this.expirationDate.toGMTString() : "" ) +
                          ( ( this.path ) ? ";path=" + this.path : "" ) +
                          ( ( this.domain ) ? ";domain=" + this.domain : "" ) +
                          ( ( this.secure ) ? ";secure=" : "" );
    }

    function getRandNumber(numDigits) {
        var randNum = "";
        var thisDigit = "";
        for (var i = 0; i < numDigits; i++) {
            thisDigit = Math.floor(Math.random() * 10);
            randNum = randNum + thisDigit;
        }
        return randNum;
    }

    function getPrimaryDomain() {
        var theUrl = document.domain;
        var urlLength = theUrl.length;
        var firstDot = theUrl.lastIndexOf(".");
        var secondDot = theUrl.lastIndexOf(".", firstDot - 1);
        var primaryDomain = theUrl.substr(secondDot);
        return primaryDomain;
    }

    function getCookieKeyValue(cookie_value, key, delimeter) {
        if (cookie_value != null) {
            var keystring = key + delimeter;
            var thiscookie_start = cookie_value.indexOf(keystring) + keystring.length;
            var thiscookie_end = cookie_value.indexOf(delimeter, thiscookie_start);
            var keyvalue = cookie_value.substring(thiscookie_start, thiscookie_end);
            return keyvalue;
        } else {
            return null;
        }
    }
}

/* --------------------------------------------
Application Config
--------------------------------------------- */
function ApplicationConfig() {
    this.requiredRoles = new Array();
    this.addRole = addRole;
    this.requiresLogin = false;
    this.loginServer = {"DEV": "", "STAGE": "", "PROD": ""};
    this.applicationName = "";
    this.applicationCode = "";
    this.applicationEntryPage = "";
    this.applicationPath = "";
    this.urVersion = urVersion;

	function getLoginServer(env) {
		if (this.loginServer[env]) {
			return this.loginServer[env];
		} else {
			return null;
		}
	}
	
    function addRole(role) {
        this.requiredRoles.push(role);
    }
    function urVersion() {
        return 1;
    }
}

/* --------------------------------------------
Role
--------------------------------------------- */
function ApplicationRole(name, date) {
    this.name = name;
    this.date = date;
}


/* ---------------------------------------------
	This is the Ur User JavaScript
---------------------------------------------  */


function UrUser(appConfig) {

    this.getEmail = getEmail;
    this.getBirthYear = getBirthYear;
    this.getCity = getCity;
    this.getConfirm = getConfirm;
    this.getFirstName = getFirstName;
    this.getGender = getGender;
    this.getLastName = getLastName;
    this.getParentEmail = getParentEmail;
    this.getPersist = getPersist;
    this.getPhone = getPhone;
    this.getPostalCode = getPostalCode;
    this.getStatus = getStatus;
    this.getTransComplete = getTransComplete;
    this.getUserId = getUserId;
    this.getUserName = getUserName;
	this.getFullName = getFullName;

    // Role Props

    this.getUserType = getUserType;
    this.hasRoleByName = hasRole;
    this.hasRoleById = hasRoleById;

    // cookie objects
    this.valueCookie = new ValueCookie();
    this.roleCookie = new RoleCookie();
    this.vignetteValueCookie = new VignetteValueCookie();
    this.vignetteRoleCookie = new VignetteRoleCookie();

	this.applicationConfig = appConfig;
	this.urLite = new UrLite();
	this.isLoggedIn = false;

	// methods
	this.logout = logout;
	
	// Initialization
	this.urLite.login(this, appConfig);
	
	function logout() {
		if (this.isLoggedIn) {
			this.urLite.logout(this, this.applicationConfig);
		}
	}
	
    // Start Getters
    function getEmail() {
	        if (this.valueCookie.getEmail() != null)
            return this.valueCookie.getEmail();
        if (this.vignetteValueCookie.getEmail() != null)
            return this.vignetteValueCookie.getEmail();
    }

    function getBirthYear() {
	           if (this.valueCookie.getBirthYear() != null)
            return this.valueCookie.getBirthYear();
        if (this.vignetteValueCookie.getBirthYear() != null)
            return this.vignetteValueCookie.getBirthYear();
    }


    function getCity() {
	         if (this.valueCookie.getCity() != null)
            return this.valueCookie.getCity();
        if (this.vignetteValueCookie.getCity() != null)
            return this.vignetteValueCookie.getCity();
    }


    function getConfirm() {
	         if (this.valueCookie.getConfirm() != null)
            return this.valueCookie.getConfirm();
        if (this.vignetteValueCookie.getConfirm() != null)
            return this.vignetteValueCookie.getConfirm();
    }

    function getParentEmail() {
	           if (this.valueCookie.getParentEmail() != null)
            return this.valueCookie.getParentEmail();
        if (this.vignetteValueCookie.getParentEmail() != null)
            return this.vignetteValueCookie.getParentEmail();
    }

    function getPersist() {
	       if (this.valueCookie.getPersist() != null)
            return this.valueCookie.getPersist();
        if (this.vignetteValueCookie.getPersist() != null)
            return this.vignetteValueCookie.getPersist();
    }

    function getPhone() {
	     if (this.valueCookie.getPhone() != null)
            return this.valueCookie.getPhone();
        if (this.vignetteValueCookie.getPhone() != null)
            return this.vignetteValueCookie.getPhone();
    }

    function getPostalCode() {
	    if (this.valueCookie.getPostalCode() != null)
            return this.valueCookie.getPostalCode();
        if (this.vignetteValueCookie.getPostalCode() != null)
            return this.vignetteValueCookie.getPostalCode();
    }

    function getStatus() {
	if (this.valueCookie.getStatus() != null)
            return this.valueCookie.getStatus();
        if (this.vignetteValueCookie.getStatus() != null)
            return this.vignetteValueCookie.getStatus();
    }

    function getTransComplete() {
	if (this.valueCookie.getTransComplete() != null)
            return this.valueCookie.getTransComplete();
        if (this.vignetteValueCookie.getTransComplete() != null)
            return this.vignetteValueCookie.getTransComplete();
    }

    function getUserName() {
	      if (this.valueCookie.getUserName() != null)
            return this.valueCookie.getUserName();
        if (this.vignetteValueCookie.getUserName() != null)
            return this.vignetteValueCookie.getUserName();
    }

    function getFirstName() {
        if (this.valueCookie.getFirstName() != null)
            return this.valueCookie.getFirstName();

        if (this.vignetteValueCookie.getFirstName() != null)
            return this.vignetteValueCookie.getFirstName();
    }


    function getGender() {
        if (this.valueCookie.getGender() != null)
            return this.valueCookie.getGender();

	    if (this.vignetteValueCookie.getGender() != null)
            return this.vignetteValueCookie.getGender();
    }

    function getLastName() {
	if (this.valueCookie.getLastName() != null)
            return this.valueCookie.getLastName();
        if (this.vignetteValueCookie.getLastName() != null)
            return this.vignetteValueCookie.getLastName();
    }
	
	function getFullName() {
		return this.getFirstName() + ' ' + this.getLastName();
	}

    function getUserId() {
        if (this.valueCookie.getUserId() != null)
            return this.valueCookie.getUserId();
        if (this.vignetteValueCookie.getUserId() != null)
            return this.vignetteValueCookie.getUserId();
    }

    function getUserType() {
	if (this.valueCookie.getUserId() != null)
            return this.valueCookie.getUserId();
        if (this.vignetteValueCookie.getUserType() != null)
            return this.vignetteValueCookie.getUserType();
    }

    function hasRoleById(roleId) {
        if (this.vignetteRoleCookie.getRoleById(roleId) != null)
            return true;
        else
            return false;
    }

    function hasRole(role) {
        if (this.roleCookie.getRoleByName(role.name) != null) {
            if(this.roleCookie.getRoleByName(role.name) >= role.date)
                return true;
            else
                return false;
        }

        if (this.vignetteRoleCookie.getRoleByName(role.name) != null)
            return true;
        else
            return false;
    }

}


/* ---------------------------------------------
	VignetteCookie Base Class
---------------------------------------------  */


function VignetteCookie() {

    this.info = new Array();
    this.parse = parseCookie;
    this.parseCookie = parseCookie;
    this.parseSingleValueChip = parseSingleValueChip;
    this.parseMultiValueChip = parseMultiValueChip;
	
	this.cookieName = "";
	this.cookiePath = "/";
	this.cookieDomain = "";
	this.clear = clearInfo;

	function clearInfo() {
		this.info = new Array();
	}

    function stripHeader(string) {
        return string.substring(23);
        // 23 is always the lenght of the header
    }

    function stripTrailer(string) {
        return string.substring(0, string.length - 3);
    }

    function parseCookie(cookie) {
        cookie = stripHeader(cookie);
        cookie = stripTrailer(cookie);
        var cookieArray = cookie.split("ZZ%");
        for (var i = 0; i < cookieArray.length; ++ i) {
            chip = cookieArray[i];
            chip = chip.substring(6);
            if (chip.substring(0, 1) == "s") {
                chip = chip.substring(1);
            } else {
                chip = chip.substring(3);
            }
            if (chip.match("\\+") == '+') {
                this.parseMultiValueChip(chip);
            } else {
                this.parseSingleValueChip(chip);
            }
        }
    }

    function parseSingleValueChip(chip) {
        chip = URLDecode(chip);
        var values = chip.split("ZZ");

        if (values.length < 2) {
            this.info[values[0]] = "";
        } else {
            this.info[values[0]] = values[1];

        }
    }

    function parseMultiValueChip(chip) {
        var multivalue = new Array();
        chip = URLDecode(chip);

        // pull out the name
        var key = chip.split("ZZ")[0];
        chip = chip.substring(key.length);

        // parse the parts
        chip = chip.replace(/ZZZZ/g, "ZZ");
        var chips = chip.split("+");

        for (var i = 0; i < chips.length; ++ i) {
            part = chips[i];
            var parts = part.split("ZZ");
            multivalue[parts[1]] = parts[2];

        }
        this.info[key] = multivalue;
    }

    function URLDecode(encodedString) {
        var output = encodedString;
        var binVal, thisString;
        var myregexp = /(%.{2})/;
        while ((match = myregexp.exec(output)) != null
                && match.length > 1
                && match[1] != '') {
            binVal = parseInt(match[1].substr(1), 16);
            thisString = String.fromCharCode(binVal);
            output = output.replace(match[1], thisString);
        }
        return output;
    }

}

/* ---------------------------------------------
	This is the Ur User JavaScript
---------------------------------------------  */
VignetteValueCookie.prototype = new VignetteCookie();
function VignetteValueCookie() {
    VignetteValueCookie.prototype = new VignetteCookie();
    this.getEmail = getEmail;
    this.getBirthYear = getBirthYear;
    this.getCity = getCity;
    this.getConfirm = getConfirm;
    this.getFirstName = getFirstName;
    this.getGender = getGender;
    this.getLastName = getLastName;
    this.getParentEmail = getParentEmail;
    this.getPersist = getPersist;
    this.getPhone = getPhone;
    this.getPostalCode = getPostalCode;
    this.getStatus = getStatus;
    this.getTransComplete = getTransComplete;
    this.getUserId = getUserId;
    this.getUserName = getUserName;
    this.getUserType = getUserType;

    function getEmail() {
        return this.info['email'];
    }
    function getBirthYear() {
        return this.info['birth_year'];
    }
    function getCity() {
        return this.info['city'];
    }
    function getConfirm() {
        return this.info['confirm'];
    }
    function getFirstName() {
        return this.info['first_name'];
    }
    function getGender() {
        return this.info['gender'];
    }
    function getLastName() {
        return this.info['last_name'];
    }
    function getParentEmail() {
        return this.info['parent_email'];
    }
    function getPersist() {
        return this.info['persist'];
    }
    function getPhone() {
        return this.info['phone'];
    }
    function getPostalCode() {
        return this.info['postal_code'];
    }
    function getStatus() {
        return this.info['status'];
    }
    function getTransComplete() {
        return this.info['transcomplete'];
    }
    function getUserId() {
        return this.info['user_id'];
    }
    function getUserName() {
        return this.info['user_name'];
    }
    function getUserType() {
        return this.info['usertype'];
    }
}

/* ---------------------------------------------
	This is the Ur User JavaScript
---------------------------------------------  */
VignetteRoleCookie.prototype = new VignetteCookie();
function VignetteRoleCookie() {
    VignetteRoleCookie.prototype = new VignetteCookie();
    this.getPersist = getPersist;
    this.getUserId = getUserId;
    this.getRoleByName = getRoleByName;
    this.getRoleById = getRoleById;

    function getPersist() {
        return this.info['persist'];
    }
    function getUserId() {
        return this.info['user_id'];
    }
    function getRoleByName(name) {
        if (this.info['roles'] != undefined) {
            for (var i = 0; i < this.info['roles'].length; i++) {
                if (this.info['roles'][i] != undefined && this.info['roles'][i] == name) {
                    return this.info['roles'][i];
                }
            }
        }

    }
    function getRoleById(id) {
        if (this.info['roles'] != undefined) return this.info['roles'][id];
    }
}


/* ---------------------------------------------
	UrCookie Base ClassS
---------------------------------------------  */


function UrCookie() {

    this.info = new Array();
    this.parse = parseCookie;
    this.parseCookie = parseCookie;
	this.clear = clearInfo;
	
	function clearInfo() {
		this.info = new Array();
	}
	
    function parseCookie(cookie) {


        var cookieArray = cookie.split("|");

        for (var i = 0; i < cookieArray.length; i++) {
            chips = cookieArray[i].split(":");

            this.info[chips[0]] = chips[1];
        }
    }
}

/* ---------------------------------------------
	ValueCookie
---------------------------------------------  */
ValueCookie.prototype = new UrCookie();
function ValueCookie() {
    ValueCookie.prototype = new UrCookie();
    this.getEmail = getEmail;
    this.getBirthYear = getBirthYear;
    this.getCity = getCity;
    this.getConfirm = getConfirm;
    this.getFirstName = getFirstName;
    this.getGender = getGender;
    this.getLastName = getLastName;
    this.getParentEmail = getParentEmail;
    this.getPersist = getPersist;
    this.getPhone = getPhone;
    this.getPostalCode = getPostalCode;
    this.getStatus = getStatus;
    this.getTransComplete = getTransComplete;
    this.getUserId = getUserId;
    this.getUserName = getUserName;
    this.getUserType = getUserType;

    function getEmail() {
        return this.info['email'];
    }
    function getBirthYear() {
        return this.info['birth_year'];
    }
    function getCity() {
        return this.info['city'];
    }
    function getConfirm() {
        return this.info['confirm'];
    }
    function getFirstName() {
        return this.info['first_name'];
    }
    function getGender() {
        return this.info['gender'];
    }
    function getLastName() {
        return this.info['last_name'];
    }
    function getParentEmail() {
        return this.info['parent_email'];
    }
    function getPersist() {
        return this.info['persist'];
    }
    function getPhone() {
        return this.info['phone'];
    }
    function getPostalCode() {
        return this.info['postal_code'];
    }
    function getStatus() {
        return this.info['status'];
    }
    function getTransComplete() {
        return this.info['transcomplete'];
    }
    function getUserId() {
        return this.info['user_id'];
    }
    function getUserName() {
        return this.info['user_name'];
    }
    function getUserType() {
        return this.info['usertype'];
    }
}

/* ---------------------------------------------
	This is the Ur User JavaScript
---------------------------------------------  */
RoleCookie.prototype = new UrCookie();
function RoleCookie() {
    RoleCookie.prototype = new UrCookie();
    this.getRoleByName = getRoleByName;

    function getRoleByName(name) {
	    return this.info[name];
    }
}