(function() {
	var that = this;
	var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_!";
	var signOutLink = '<a id="link-signout" class="alnol" >Sign out</a>';
	var signInLink = '<a id="link-signin" class="alnol" >Sign in</a>'
	var registerLink = '<a id="link-register" class="alnol" >Register</a>';
	var helpLink = '<a id="link-help" class="alnol" >Help</a>';
	var myAdsLink = '<a id="link-managemyads" class="alnol" >Manage my ads</a>';
	var linkSeparator = '<span class="link-separator"> | </span>';
	var emailreg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

	function setHeaderLinks() {
		var greeting = [];
		if (isLoggedIn()) {
			greeting.push('<span id="hello"><span>Hi <span id="user-name">');
			greeting.push(getUserName());
			greeting.push('</span> </span>');
			greeting.push(linkSeparator);
			greeting.push(signOutLink);
			greeting.push('</span>');
		}
		else {
			greeting.push('<span>');
			greeting.push(registerLink);
			greeting.push(linkSeparator);
			greeting.push(signInLink);
			greeting.push('</span>');
		}
		
		greeting.push(linkSeparator);
		greeting.push(myAdsLink);
		greeting.push(linkSeparator);
		greeting.push(helpLink);
		if (document.getElementById("user-links")) {
			document.getElementById("user-links").innerHTML = greeting.join("");
		}
	}

    function uTF8Decode(input) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while (i < input.length) {
            c = input.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = input.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = input.charCodeAt(i+1);
                c3 = input.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
	
    function base64Decode(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\-\_\!]/g, "");
        while (i < input.length) {
            enc1 = keyString.indexOf(input.charAt(i++));
            enc2 = keyString.indexOf(input.charAt(i++));
            enc3 = keyString.indexOf(input.charAt(i++));
            enc4 = keyString.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = uTF8Decode(output);
        return output;
    }
    
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
    function readCookielet(c, t) {
        var a = readCookie(c);
        if (a) {
        	var ca = a.charAt(0) !== '^' ? a.split('^') : a.slice(1).split('^');
            for(var i=0; i < ca.length - 1; i+=2) {
                if (ca[i] === t) {
                    return ca[i+1];
                }
            }
        }
        return null;
    }
    function _hasAuthCookie() {
        var l = readCookielet('a', 'l');
        return (l && base64Decode(l) == '1')
    }
    function _getUserName() {
        if (_hasAuthCookie()) {
            var userName = readCookielet('a', 'n');
            if ((userName == null)||(userName == '')) {
                userName = readCookielet('a', 'u');
            }
            userName = base64Decode(userName);
            var idx = userName.indexOf("@");
            if (idx > 0) userName = userName.substring(0,idx);
            if (userName.length > 20) {
                userName = userName.substring(0,18) + "...";
            }
            return userName;
        }
        return null;
    }
    function _getEmail() {
        if (_hasAuthCookie()) {
            var email = readCookielet('a', 'u');
            return base64Decode(email);
        }
        return null;
    }
    
    function isLoggedIn() {
    	return that._ac;
    }
    
    function getUserEmail() {
    	return that._ue;
    }
    
    function hasUserName() {
        if (_hasAuthCookie()) {
            var userName = readCookielet('a', 'n');
            if ((userName == null)||(userName == '')) {
                return false;
            }
            else {
            	return true;
            }
        }
        return false; 
    }
    function getUserName() {
    	return that._un;
    }

    function getUserPhoneNumber() {
    	return that._up;
    }
    
    function setUserPhoneNumber(number) {
    	that._up = number;
    }
    
    function getUserPhoneNumberIsVerified() {
    	return that._upv;
    }
    
    function setUserPhoneNumberIsVerified(verified) {
    	that._upv = verified;
    }
    	
    function reinit() {
    	that._ac = _hasAuthCookie();
    	that._un = _getUserName();
    	that._ue = _getEmail();
    }
    
    function clearModal(success) {
    	if (typeof that.modalHideFunc == "function") {
    		that.modalHideFunc.apply();
    	}
    	if (typeof that.modalClearFunc == "function") {
    		that.modalClearFunc.apply();
    	}
        window.document.body.removeChild(that.modalOverlay);
    	window.document.body.removeChild(that.modal);
    	if (success && typeof that.modalSuccessFunc == "function") {
    		if (that.modalSuccessFuncScope) {
    			that.modalSuccessFunc.apply(that.modalSuccessFuncScope);
    		}
    		else {
    			that.modalSuccessFunc.apply();
    		}
    	}
    }

    function initModal(p) {
    	var h = window.document.body.clientHeight;
    	var div = window.document.createElement("div");
    	div.id = p.modalId+"OverLay";
    	div.style.zIndex = 1;
        div.style.height = h+"px";
        that.modalOverlay = div;
        that.modal = window.document.getElementById(p.modalId);
        that.modalInitFunc = p.init;
        that.modalClearFunc = p.clear;
        that.modalShowFunc = p.show;
        that.modalHideFunc = p.hide;
    }
    
	function emailValidator(email) {
		return emailreg.test(email);
	}

    function showModal(sFunc, scope) {
    	window.document.body.appendChild(that.modalOverlay);
    	window.document.body.appendChild(that.modal);
    	that.modal.style.display = "block";
    	if (typeof that.modalInitFunc == "function") {
    		that.modalInitFunc.apply();
    	}
    	if (typeof that.modalShowFunc == "function") {
    		that.modalShowFunc.apply();
    	}
    	if (typeof sFunc == "function") {
    		that.modalSuccessFunc = sFunc;
    		that.modalSuccessFuncScope = scope;
    	}
    	
    }
    function setHeaderLinksFunc(sFunc, scope) {
    	that.headerLinksFunc = sFunc;
    	that.headerLinksFuncScope = scope;
    }
    function updateHeaderLinks() {
    	that.headerLinksFunc.apply(that.headerLinksFuncScope);
    }
    
    function setUserDataCallback(sFunc, scope) {
    	that.userDataCallback = sFunc;
    	that.userDataCallbackScope = scope;
    }
    function processUserData(response) {
    	if (that.userDataCallbackScope) {
    		that.userDataCallback.apply(that.userDataCallbackScope,[response]);
    	}
    	else {
    		that.userDataCallback.apply([response]);
    	}
    }
    function updateSubscriptionList() {
    	that.updateSubscriptionListFunc.apply(that.updateSubscriptionListScope);
    }
    function setUpdateSubscriptionList(sfunc, scope) {
    	that.updateSubscriptionListFunc = sfunc;
    	that.updateSubscriptionListScope = scope;
    }

	that._ac = _hasAuthCookie();
	that._un = _getUserName();
	that._ue = _getEmail();
	that._up = null;
	that._upv = false;
	
    window.polaris = {
        setHeaderLinks: setHeaderLinks,
        reinit: reinit,
        processUserData: processUserData,
        setUserDataCallback: setUserDataCallback,
        isLoggedIn: isLoggedIn,
        getUserEmail: getUserEmail,
        hasUserName: hasUserName,
        getUserName: getUserName,
        getUserPhoneNumber : getUserPhoneNumber,
        setUserPhoneNumber : setUserPhoneNumber,
        getUserPhoneNumberIsVerified : getUserPhoneNumberIsVerified,
        setUserPhoneNumberIsVerified : setUserPhoneNumberIsVerified,
        initModal: initModal,
        showModal: showModal,
        setHeaderLinksFunc: setHeaderLinksFunc,
        updateHeaderLinks: updateHeaderLinks,
        clearModal: clearModal,
        updateSubscriptionList: updateSubscriptionList,
        setUpdateSubscriptionList: setUpdateSubscriptionList,
        emailValidator: emailValidator
    };
})();

