
var PublicPages = {};

// Cache the refresher content
var refresherCache = new Array();

function getQuery()
{
    var re = new RegExp("(http://search.yahoo.com/search.*[?&]p="
                            + "|http://www.google.com/search.*[?&]q="
                            + "|http://www.business.com/search/rslt_default.asp.*[?&]query="
                            + "|http://search.aol.com/aolcom/search.*[?&]query=)([^\\&]+)");

    var ref = CookieUtils.getCookie("spoke_referrer");

    if (!ref || ref == null || ref == '')
        ref = document.referrer;

    if (ref && ref != null)
    {
        var rs = re.exec(ref);
        if (rs != null && rs.length > 2)
        {
            return rs[2];
        }
    }
    return null;
}

function doDelayedBgGet(url, listener)
{
    showWaiting();
    setTimeout(function() { doBgGet(url, listener) }, 1500);
}

function doDelayedBgGet2(url, listener, finallyListener)
{
    showWaiting();
    setTimeout(function() { doBgGet2(url, listener, finallyListener) }, 1500);
}

function checkDoSearch(url)
{
    var q = getQuery();
    if (q != null && q != '')
        doDelayedBgGet(url + '?searchTerm=' + q,
                function(xmlObject) {
                    var sr = document.getElementById('sr');
                    if (sr != null)
                    {
                        sr.innerHTML = xmlObject.responseText;
                        evalScripts(sr);

                        AnimationUtils.slideDown(sr.id, '8px', 100, 200);
                    }
                }
                );
}

function getOffsets(elem)
{
    elem.style.visibility = 'hidden';
    elem.style.display = 'block';

    var dim = {
        width  : elem.offsetWidth,
        height : elem.offsetHeight,
        left   : elem.offsetLeft,
        top    : elem.offsetTop
    };

    elem.style.display = 'none';
    elem.style.visibility = '';

    return dim;
}

function doBgGet(url, listener)
{
    doAjax("GET", url, "", listener, function(){ hideWaiting() });
}

function doBgGet2(url, listener, finallyFunction)
{
    doAjax("GET", url, "", listener, finallyFunction);
}

function doBgPost(url, args, listenerFunction, finallyFunction)
{
    doAjax("POST", url, args, listenerFunction, finallyFunction);
}

function evalScripts(content)
{
    if (content == undefined || content == null)
        return;

    var scripts = content.getElementsByTagName('script');
    if (scripts != null)
    {
        for (var i=0; i < scripts.length; i++)
        {
            eval(scripts[i]);
        }
    }

}

function hideWaiting()
{
    var waitMessage = document.getElementById('waitMessage');
    if (waitMessage)
    {
        waitMessage.style.display = "none";
    }
}

function showWaiting()
{
    var waitMessage = document.getElementById('waitMessage');
    waitMessage.style.display = "block";
}

function getPostString(formObj, noEncodingMap)
{
    var elements = formObj.elements;
    var qryStr = "";

    for (var i = 0; i < elements.length; i ++)
    {
        var elemType = elements[i].type;
        var qryParams = "";

        if (elemType == "hidden" || elemType.indexOf ("text") == 0)
        {
            qryParams = handleEncoding(elements[i].name, elements[i].value, noEncodingMap);
        }
        else if (elemType == "password")
        {
            qryParams = elements[i].name + "=" + elements[i].value;
        }
        else if (elemType == "radio" || elemType == "checkbox")
        {
            if (elements[i].checked)
            {
                qryParams = handleEncoding(elements[i].name, elements[i].value, noEncodingMap);
            }
        }
        else if (elemType == "select-one")
        {
            if (elements[i].selectedIndex > -1)
            {
                qryParams = handleEncoding(elements[i].name, elements[i].options[elements[i].selectedIndex].value, noEncodingMap);
            }
        }
        // if we have a multi-select list we gotta all and the selected options to the qry string
        else if (elemType == "select-multiple")
        {
            var opts = elements[i].options;

            for (var j = 0; j < opts.length; j++)
            {
                if (opts[j].selected)
                {
                    qryParams += handleEncoding(elements[i].name, opts[j].value) + "&";
                }
            }
        }
        else
        {
            continue;
        }

        qryStr += qryParams+ "&";
    }

    return qryStr;
}

function handleEncoding(key, value, noEncodingMap)
{
    var v = value;
    if (!noEncodingMap || !noEncodingMap[key])
        v = encodeURIComponent(value)

    return key + "=" + v;
}

var AnimationUtils = new Object();
AnimationUtils.slideInterval = new Array();
AnimationUtils.slide = function (elemID, maxHeight, dir, increment) {
    var ele = document.getElementById(elemID);
    var stopSliding = false;

    if (dir == 'up') {
        var eHt = parseInt(ele.style.height);
        var maxHt = parseInt(maxHeight);
        if (ele.style.height > 0)
            ele.style.height = ele.style.height - (increment + 'px');
        else
            stopSliding = true;
    } else if (dir == 'down'){
        var eHt = parseInt(ele.style.height);
        var maxHt = parseInt(maxHeight);
        if (eHt < maxHt)
        {
            ele.style.height = (eHt + increment + 'px');
        }
        else
            stopSliding = true;
    }

    if (stopSliding)
    {
        clearInterval(AnimationUtils.slideInterval[elemID]);
    }
}

AnimationUtils.showSliding = function(elemID, maxHt, dir, interval)
{
    document.getElementById(elemID).style.display = 'block';
    AnimationUtils.slideInterval[elemID] = setInterval(function() {
        AnimationUtils.slide(elemID, maxHt, dir, 40);
    }, interval);
}

AnimationUtils.slideDown = function(elemID, minHt, interval, timeout)
{
    if (timeout == undefined || timeout == null || timeout == '')
        timeout = 200;

    if (minHt == undefined || minHt == null || minHt == '')
        minHt = '1px';

    var elem = document.getElementById(elemID);
    var maxHt = getOffsets(elem)['height'];

    elem.style.height = minHt;

    var callback = "AnimationUtils.showSliding('" + elemID + "', '" + maxHt + "', 'down', " + interval + ")"
    window.setTimeout(callback, timeout);
}

AnimationUtils.slideUp = function(elemID, maxHt, interval, timeout)
{
    if (timeout == undefined || timeout == null)
        timeout = 10;

    var callback = "AnimationUtils.showSliding('" + elemID + "', '" + maxHt + "', 'up', " + interval + ")"
    window.setTimeout(callback, timeout);
}

function refreshCompanyPage()
{
    refreshPage({ companyNews : '', companyViewCount : '', companyComments : '' })
}

function refreshPersonPage()
{
    refreshPage({ personComments : '', personTags : '', personViewCount : '' })
}

function refreshPage(params)
{
    var q = buildRefreshQuery(params);
    if (q == '')
    {
        return;
    }


    var url = location.href.substring(0, location.href.lastIndexOf("/")).replace("/info", "/public") + "/panel/fetch.spoke" + q;
    if (refresherCache[url] == undefined)
    {
        doDelayedBgGet2(url,
                function(xmlObject) {
                    var rtn = xmlObject.responseText;
                    var div = document.createElement('div');
                    div.innerHTML = rtn;
                    refresherCache[url] = div;
                    updateSubDivs(div);
                },
                function() {
                    hideWaiting();
                });
    }
    else
    {
        updateSubDivs(refresherCache[url]);
    }
}

function updateSubDivs(div)
{
    var innerDivs = div.getElementsByTagName('div');

    var divProxyIdMap = {
        'profileTagsResults' : 'profileTags',
        'personCommentResults' : 'personComment',
        'personViewCountResults' : 'personViewCount',
        'personRatingResults' : 'personRating',
        'companyRatingResults' : 'companyRating',
        'companyCommentResults' : 'companyComment',
        'companyViewCountResults' : 'companyViewCount',
        'companyNewsResults' : 'companyNews'
    }

    for (var i=0; i < innerDivs.length; i++)
    {
        var divProxyId = divProxyIdMap[innerDivs[i].id];
        if (divProxyId != undefined)
        {
            var divProxy = document.getElementById(divProxyId);
            if (divProxy && innerDivs[i].innerHTML != null && innerDivs[i].innerHTML.length > 0)
            {
                divProxy.innerHTML = innerDivs[i].innerHTML;
            }
        }
    }
}

function buildRefreshQuery(params)
{
    var q = "";
    var first = true;
    for (var p in params)
    {
        if (first)
        {
            q += "?" + p + "=" + params[p];
            first = false;
        }
        else
        {
            q += "&" + p + "=" + params[p];
        }
    }
    return q;
}

function findPos(obj) {
	var curleft = 0, curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function scrollToElement(id) {
    var elem = document.getElementById(id);
    if (elem)
    {
        var pos = findPos(elem);
        var x = pos[0];
        var y = pos[1];
        window.scrollTo(x, y);
    }
}

/** Public Pages Comments code **/
PublicPages.Comments = function()
{
    this.init();
}

PublicPages.Comments.prototype =
{
    divId: null,
    inputId: null,
    loginId: null,
    bottomLoadingId: null,
    submitButtonId: null,
    cancelButtonId: null,
    postButtonId: null,
    footerId: null,
    loginButtonId: null,
    loginErrorMessageId: null,
    messageDivId: null,
    form: null,
    loginForm: null,
    init: function()
            {

            },
    setSubmitButton: function(id)
            {
                var self = this;
                this.submitButtonId = id;
                var button = document.getElementById(this.submitButtonId);
                button.onclick = function() {
                    return self.submitComment();
                };
            },
    setCancelButton: function(id)
            {
                var self = this;
                this.cancelButtonId = id;
                var button = document.getElementById(this.cancelButtonId);
                button.onclick = function () {
                    self.hide(self.inputId);
                    self.show(self.footerId);
                    self.show(self.footerId)
                    self.form.comment.value = "";
                }
            },
    setPostButton: function(id)
            {
                var self = this;
                this.postButtonId = id;
                var button = document.getElementById(this.postButtonId);
                button.onclick = function() {
                    self.checkAuth();
                };
            },
    setLoginButton: function(id)
            {
                var self = this;
                this.loginButtonId = id;
                var button = document.getElementById(this.loginButtonId);
                button.onclick = function() {
                    self.login();
                };
            },
    checkAuth: function()
            {
                var self = this;
                self.hide(self.messageDivId);
                self.show(self.bottomLoadingId);
                var params = "";
                if (self.personId)
                {
                    params = "?personId="+self.personId;
                }
                else if (self.companyId)
                {
                    params = "?companyId="+self.companyId;
                }
                doBgGet2("/public/comments/json/checkAuthentication.spoke"+params, function(xmlObject){self.checkAuthListener(xmlObject);}, function() {self.hide(self.bottomLoadingId);} );
            },
    login: function()
            {
                var self = this;
                var noEncode = { 'username' : true };
                var args = encodeURI(getPostString(this.loginForm, noEncode));
                self.hide(self.loginId);
                self.show(self.bottomLoadingId);
                //self.showLoading( document.getElementById(self.loginId).offsetHeight );
                doBgPost(this.loginForm.action, args, function(xmlObject) {self.loginListener(xmlObject)}, function(){self.hide(self.bottomLoadingId);});
            },
    submitComment: function()
            {
                var self = this;
                var args = getPostString(this.form);
                self.hide(self.inputId);
                self.show(self.bottomLoadingId);
                doBgPost(this.form.action, args, function(xmlObject) {self.submitCommentListener(xmlObject)}, function(){self.hide(self.bottomLoadingId);});
            },
    submitCommentListener: function(xmlObject)
            {
                var response = eval("("+xmlObject.responseText+")");
                if (response.success)
                {
                    //collapse the comments
                    var parent = document.getElementById(this.divId);
                    var firstElem = parent.firstChild;
                    var newComment = this.createComment(response.title, response.comment);
                    parent.insertBefore(newComment, firstElem);
                    //parent.appendChild(newComment);
                    this.showMessage( "Thank you. Your comment has been posted." );
                    this.form.comment.value = "";
                }
                else
                {
                    if (!response.authenticated)
                    {
                        this.hide(this.inputId);
                        this.show(this.loginId);
                    }
                    else if (!response.commentsAllowed)
                    {
                        this.hide(this.inputId);
                        this.showMessage( response.message );
                        this.form.comment.value = "";
                    }
                    else
                    {
                        this.hide(this.inputId);
                        this.showMessage( response.message );
                    }
                }
            },
    checkAuthListener: function(xmlObject)
            {
                var response = eval("("+xmlObject.responseText+")");
                if (response.commentsAllowed)
                {
                    if (response.authenticated)
                    {
                        if (response.firstName)
                        {
                            if (response.firstName != null && response.firstName != "")
                            {
                                var elem = document.getElementById("commentsSalutation");
                                if (elem)
                                {
                                    elem.innerHTML = response.firstName;
                                }
                            }
                        }

                        this.show(this.inputId);
                        this.form.comment.focus();
                    }
                    else
                    {
                        this.show(this.loginId);
                        this.loginForm.username.focus();
                    }
                    this.hide( this.footerId );
                }
                else
                {
                    this.showMessage( response.message );
                }
            },
    loginListener: function (xmlObject)
            {
                this.show(this.loginId);
                var response = eval("("+xmlObject.responseText+")");
                if (response.success)
                {
                    this.hide( this.loginId );
                    this.show( this.inputId );
                    if (response.firstName != null && response.firstName != "")
                    {
                        var elem = document.getElementById("commentsSalutation");
                        if (elem)
                        {
                            elem.innerHTML = response.firstName;
                            updateWelcome();
                        }
                    }
                }
                else
                {
                    var errorElem = document.getElementById( this.loginErrorMessageId );
                    errorElem.innerHTML = response.message;
                    errorElem.style.display = "block";
                }
            },
    createComment: function(title, text)
            {
//    <div class="comment">
//        <div class="commentTitle" style="font-weight: bold">by <%=postedBy%> on <%=when%></div>
//        <div class="commentText" style="padding-left: 10px">
//            <%=note.getText()%>
//        </div>
//    </div>
                var titleDiv =  document.createElement("div");
                //titleDiv.setAttribute("class", "commentTitle");
                titleDiv.className = "commentTitle";
                titleDiv.innerHTML = title;

                var textDiv =  document.createElement("div");
                textDiv.className = "commentText";
                textDiv.innerHTML = text;

                var rateDiv =  document.createElement("div");
                rateDiv.className = "commentRating";
                rateDiv.innerHTML = "<table width=\"100%\"><tr>" +
                "<td valign=\"bottom\" align=\"left\"><b>0 of 0</b> positive ratings</td>" +
                "<td valign=\"bottom\" align=\"right\">" +
                    "<div style=\"text-align: right;\">" +
                        "<b>Thank You</b>" +
                    "</div>" +
                "</td>" +
            "</tr></table>";


                var commentDiv = document.createElement("div");
                commentDiv.className = "comment";
                commentDiv.appendChild(titleDiv);
                commentDiv.appendChild(textDiv);
                commentDiv.appendChild(rateDiv);

                return commentDiv;
            },
    hide: function (id)
            {
                var elem = document.getElementById(id);
                if (elem)
                {
                    elem.style.display = "none";
                }
            },
    show: function (id)
            {
                var elem = document.getElementById(id);
                if (elem)
                {
                    elem.style.display = "block";
                }
            },
    showMessage: function(message)
            {
                var messageDiv = document.getElementById(this.messageDivId);
                while(messageDiv.hasChildNodes())
                {
                    messageDiv.removeChild(messageDiv.firstChild);
                }
                messageDiv.appendChild( document.createTextNode(message) );
                this.show(this.messageDivId);
                this.show(this.footerId);
            },
    showLoading: function(height)
            {
                if (height)
                {
                    document.getElementById(this.bottomLoadingId).style.height = height;
                }
                this.show( this.bottomLoadingId );
            },
    disableRating: function(commentId)
            {
                var pos = document.getElementById("ratePositive"+commentId);
                var neg = document.getElementById("rateNegative"+commentId);
                pos.onclick = function() {return true;};
                neg.onclick = function() {return true;};

                pos.className = "plusImageDisabled";
                neg.className = "minusImageDisabled";
            },
    rateCommentPositive: function(commentId)
            {
                this.rateComment(commentId, "positive");
            },
    rateCommentNegative: function(commentId)
            {
                this.rateComment(commentId, "negative");
            },
    rateComment: function(commentId, rating)
            {
                this.disableRating(commentId);
                var self = this;
                doBgGet("/public/comments/json/rateComment.spoke?commentId="+commentId+"&commentRating="+rating, function(xmlObject) {self.rateCommentListener(xmlObject)}, function(){self.hide(self.bottomLoadingId);});
            },
    rateCommentListener: function(xmlObject)
            {
                var response = eval("("+xmlObject.responseText+")");
                if (response.success)
                {
                    var commentId = response.commentId;
                    var rateElem = document.getElementById("rate"+commentId);
                    if (response.alreadyRated)
                    {
                        rateElem.innerHTML = "<b>Already Rated</b>";
                    }
                    else
                    {
                        rateElem.innerHTML = "<b>Thank You</b>";
                    }

                    if (response.positiveRatings != null)
                    {
                        var pos = document.getElementById("positiveRatings"+commentId);
                        pos.innerHTML = response.positiveRatings;

                    }

                    if (response.totalRatings  != null)
                    {
                        var tot = document.getElementById("totalRatings"+commentId);
                        tot.innerHTML = response.totalRatings;
                    }
                }
            }
}

// Header bar search -- START

function publicPagesToggleSearch(tab)
{
    var jobsTabDisabled = document.getElementById("jobsTabDisabled");
    var jobsTabEnabled = document.getElementById("jobsTabEnabled");
    var companyTabDisabled = document.getElementById("companyTabDisabled");
    var companyTabEnabled = document.getElementById("companyTabEnabled");
    var personTabDisabled = document.getElementById("personTabDisabled");
    var personTabEnabled = document.getElementById("personTabEnabled");

    var frm = document.getElementById('headerSearchForm');
    var jobfrm = document.getElementById('jobSearchForm');

    if (companyTabEnabled.style.display == "none" && tab == "company")
    {
        personTabEnabled.style.display = "none";
        personTabDisabled.style.display = "inline";
        jobsTabEnabled.style.display = "none";
        jobsTabDisabled.style.display = "inline";

        companyTabEnabled.style.display = "inline";
        companyTabDisabled.style.display = "none";

        frm.style.display = '';
        jobfrm.style.display = 'none';

        frm.action = '/info/src';
        var q = document.getElementById('qName');
        if (q)
        {
            q.setAttribute("name", "company");
            var v = q.value != null && q.value.trim ? q.value.trim() : '';
            if (v == '' || q.style.color == 'gray')
            {
                q.style.color = 'gray';
                q.value = 'e.g., Spoke';
            }
        }
    }
    else if (personTabEnabled.style.display == "none" && tab == "person")
    {
        companyTabEnabled.style.display = "none";
        companyTabDisabled.style.display = "inline";
        jobsTabEnabled.style.display = "none";
        jobsTabDisabled.style.display = "inline";

        personTabEnabled.style.display = "inline";
        personTabDisabled.style.display = "none";

        frm.style.display = '';
        jobfrm.style.display = 'none';

        frm.action = '/info/srp';
        frm.target = '';

        var q = document.getElementById('qName');
        var v = q.value != null && q.value.trim ? q.value.trim() : '';
        if (q)
        {
            q.setAttribute("name", "name");
            if (v == '' || q.style.color == 'gray')
            {
                q.style.color = 'gray';
                q.value = 'e.g., Frank Vaculin';
            }
        }
    }
    else if (jobsTabEnabled.style.display == "none" && tab == "jobs")
    {
        companyTabEnabled.style.display = "none";
        companyTabDisabled.style.display = "inline";
        personTabEnabled.style.display = "none";
        personTabDisabled.style.display = "inline";

        jobsTabEnabled.style.display = "inline";
        jobsTabDisabled.style.display = "none";

        frm.style.display = 'none';
        jobfrm.style.display = '';

        var q = document.getElementById('qTitle');
        var v = q.value != null && q.value.trim ? q.value.trim() : '';
        if (q)
        {
            if (v == '' || q.style.color == 'gray')
            {
                q.style.color = 'gray';
                q.value = 'Title';
            }
        }

    }
}

function checkJobSearch(frm)
{
    var searchInput = document.getElementById('qTitle');
    var v = searchInput.value != null && searchInput.value.trim ? searchInput.value.trim() : '';
    if (v == '' || searchInput.style.color == 'gray')
    {
        alert('Please enter a job to search');
        searchInput.style.color = 'gray';
        searchInput.value = 'Title';
        return false;
    }
    else if (searchInput.value.indexOf('title:') != 0 &&
             searchInput.value.indexOf('company:') != 0)
    {
        searchInput.value = 'title:(' + searchInput.value + ')';
    }

    var location = frm.elements['l'];
    if (location.style.color == 'gray')
    {
        location.value = '';
    }
    return true;
}

function checkSearch(frm)
{
    if (frm.action == '')
        frm.action = '/info/srp';

    var searchInput = document.getElementById('qName');
    var v = searchInput.value != null && searchInput.value.trim ? searchInput.value.trim() : '';
    if (v == '' || searchInput.style.color == 'gray')
    {
        var t = frm.action.indexOf('/info/srp') != -1 ? "Please enter a person name to search" : "Please enter a company to search";
        alert(t);
        
        searchInput.style.color = 'gray';
        v = frm.action.indexOf('/info/srp') != -1 ? 'e.g., Frank Vaculin' : 'e.g., Spoke';
        searchInput.value = v;

        return false;
    }
    return true;
}

function clearDefault(ele)
{
    ele.value = '';
    ele.style.color = 'black';
}

// Header bar search -- END

function updateWelcome()
{
    var l = CookieUtils.getCookie("l");
    var name = CookieUtils.getCookie("displayName");
    if (l != null && l.length > 0 && name != null && name.length > 0)
    {
        var c = document.getElementById('welcomeContainer');
        if (c != null)
            c.innerHTML = "<b>Welcome, " + name + " | </b>";

        c = document.getElementById('joinContainer');
        if (c != null)
            c.style.display = 'none';

        var ln = '';
        c = document.getElementById('loginJoin');
        if (c != null)
        {
            c.innerHTML = 'Use Spoke';
            ln = c.href;
        }

        c = document.getElementById('moreInfo');
        if (c != null && ln != '')
            c.onclick = function() {
                    window.location = ln;
            }
    }
}

function updateSRJoinOrView(type, keys)
{
    var name = CookieUtils.getCookie("displayName");
    if (!name || name == null || name.length == 0)
        return;

    var jov = document.getElementsByName('jov');
    if (jov != null && jov.length)
    {
        for (var i=0; i < jov.length; i++)
        {
            var ln = jov[i];
            if (type == 'person')
            {
                ln.href = '/secure/person/personDetail.spoke?key=' + keys[i];
                ln.innerHTML = 'View in Spoke'
            }
            else if (type == 'company')
            {
                ln.href = '/secure/company/companyDossier.spoke?dispatch=view&uid=' + keys[i];
                ln.innerHTML = 'View in Spoke'
            }
        }
    }
    if (document.getElementById('join'))
        document.getElementById('join').style.display = 'none';
    if (document.getElementById('login'))
        document.getElementById('login').getElementsByTagName('span')[0].innerHTML = "Search in Spoke";
}

// Rating stuff

function RaterC(sID)
{
    this.model = null;
    this.view  = null;
    this.serialContainer = sID;
}

RaterC.prototype.changing = function(evt) {
    var self = this;
    var src = self.whichStar(evt);

    var change = src.id.substring(src.id.indexOf('_') + 1);

    if (!self.model.isRatingValid(change))
        return;

    self.model.currentRating = change;
    if (change != 0)
    {
        self.rate(change, false);
    }
}

RaterC.prototype.whichStar = function(evt) {
    evt = evt ? evt : window.event;
    return evt.srcElement || evt.target;
}

RaterC.prototype.cancelChange = function(evt) {
    var self = this;

    if (self.model.dirty)
    {
        self.deserializeM(document.getElementById(self.serialContainer));
        self.model.dirty = false;
    }

    self.rate(self.model.rate, true);
}

RaterC.prototype.commitChange = function(evt) {
    var self = this;

    if (window.confirm("Is this your final choice?"))
    {
        var sContainer = document.getElementById(self.serialContainer)
        self.deserializeM(sContainer);
        self.model.rate = self.model.currentRating;
        self.rate(self.model.rate, true);

        function tallyScore(score) {
            self.model.count += 1;
            self.model.total += self.model.currentRating;
            document.getElementById('votes').innerHTML = self.model.count + (self.model.count == 1 ? " vote" : " votes");

            self.serializeM(sContainer);
            doAjax('GET', location.href.substring(0, location.href.lastIndexOf("/")).replace("/info", "/public") + "/panel/rate.spoke?rating=" + score, null,
                    function(xmlObject)
                    {
                        document.getElementById('voted').innerHTML = xmlObject.responseText;
                        var imgs = document.getElementsByName(self.model.prefix);
                        for (var i=0; i < imgs.length; i++)
                        {
                            var img = imgs[i];
                            img.onmouseover = function(evt) { return false; }
                            img.onclick = function(evt) { return false; }
                        }
                    });
        }
        tallyScore(self.model.rate);
    }
    else
    {
        self.cancelChange(evt);
    }
}

RaterC.prototype.init = function(cnt, readOnly) {
    var self = this;
    var container = document.getElementById(self.view.raterId);

    self.view.createView(cnt, self.model.maxRating, self.model.prefix);
    self.rate(cnt, true);
    self.model.rate = cnt;

    if (readOnly)
        return;

    var imgs = document.getElementsByName(self.model.prefix);
    for (var i=0; i < imgs.length; i++)
    {
        var img = imgs[i];
        img.onmouseover = function(evt) { self.changing(evt) }
        img.onclick = function(evt) { self.commitChange(evt) }
    }
}

RaterC.prototype.rate = function(newRating, isView) {
    var self = this;

    var nr = parseInt(newRating);
    var max = parseInt(self.model.maxRating);

    self.model.currentRating = nr;

    for (var i=1; i <= nr; i++) {
        var content = self.fromRating(i, isView);
        self.view.updateUI(document.getElementById(self.model.prefix + '_' + i), content);
    }

    if (nr < max)
    {
        for (var i=nr+1; i <= max; i++) {
            var content = self.emptyRating(i, isView);
            self.view.updateUI(document.getElementById(self.model.prefix + '_' + i), content);
        }
    }
//    document.getElementById('ratingAsText').innerHTML = nr;
}

RaterC.prototype.fromRating = function(cnt, isView) {
    var self = this;

    return isView ? self.view.star : self.view.editStar;
}

RaterC.prototype.emptyRating = function(cnt, isView) {
    var self = this;

    return isView ? self.view.blankStar : self.view.editBlankStar;
}

RaterC.prototype.serializeM = function(ele) {
    var self = this;
    if (ele)
    {
        ele.innerHTML = "{r:"+self.model.rate+",t:"+self.model.total+",c:"+self.model.count+"}";
    }
}

RaterC.prototype.deserializeM = function(ele) {
    var self = this;

    var txt = ele.innerHTML;
    try {
        var m = eval("(" + txt + ")");
        self.model.rate  = m.r;
        self.model.total = m.t;
        self.model.count = m.c;
    }
    catch (e)
    {

    }
}


function RaterM(maxRating, prefix)
{
    this.rate = 0;
    this.currentRating = 0;
    this.maxRating = maxRating;
    this.prefix = prefix;
    this.count = 0;
    this.total = 0;
    this.dirty = true;
}

RaterM.prototype.isRatingValid = function(rating) {
    var self = this;
    return rating <= self.maxRating && rating >= 0;
}

function RaterV(raterId)
{
    this.raterId = raterId;
    this.star = '';
    this.blankStar = '';
    this.editStar = '';
    this.editBlankStar = '';
}

RaterV.prototype.createView = function(cnt, max, name) {
    var self = this;

    var container = document.getElementById(self.raterId);
    for (var i=1; i <= max; i++) {
        var img = document.createElement('img');
        img.id = name + '_' + i;
        img.name = name;
        if (i <= cnt)
            img.src = self.star;
        else
            img.src = self.blankStar;

        container.appendChild(img);
    }
}

RaterV.prototype.updateUI = function(ele, content) {
    ele.src = content;
}

/**
 * Usage tracking
 * @see cnMap for types of statistics
 */
var tracker = {

    cnMap : {
        '_tvis'   : 3600000*24*365,           // total visits (exp in 1 year)
        '_vis30'  : 3600000*24*30,            // total visits in 30 days (exp in 30 days)
        '_dvis30' : 3600000*24*30,            // the first date of visits in 30 days (in long) (exp in 30 days)
        '_fvis'   : 3600000*24*30*365,        // first visit (in long) (exp in 1 year)
        '_vis'    : -1,                       // visited (session cookie)
        '_lpup'   : 3600000*24*7,             // last nag date (in long) (exp in 7 days)
        '_tpup'   : 3600000*24*365            // total popups seen (exp in 1 year)
        },

    /**
     * Initialize
     * @param dn the domain for creating cookies
     * @param nfnc the nag function
     */
    init : function(dn, nfnc) {
        var self = this;
        self.dn = dn == undefined ? '' : dn;
        self.nfnc = nfnc;
    },

    /**
     * Determines whether we should track
     *   - no if we have the displayName - indicates member
     *   - no if we have visited this session
     * @return boolean
     */
    shouldTrack : function() {
        var n = CookieUtils.getCookie("memberID");
        if (n != null)
            return false;

        n = CookieUtils.getCookie("_vis");
        return n == null;
    },

    /**
     * track the usage
     */
    track : function() {
        var self = this;
        if (self.shouldTrack())
        {
            var rtn = null;
            var now = new Date().getTime();
            self._set('_fvis', now, false);
            rtn = self._set('_vis', 1, false);
            if (rtn == 1)
            {
                self._incr('_tvis');

                if (CookieUtils.getCookie('_lpup') != null)
                    return;

                // We need to set the expiration date for 30 day cookie from first visit
                var exp = self._set('_dvis30', now + self.cnMap['_dvis30'], false);
                if (exp == null)
                {
                    exp = CookieUtils.getCookie('_dvis30');
                }

                if (isNaN(exp))
                    exp = now + self.cnMap['_dvis30'];

                var expDate = new Date();
                expDate.setTime(exp);
                rtn = self._incr('_vis30', expDate);

                if (rtn >= 5)
                {
                    rtn = self._set('_lpup', now, false);
                    if (rtn != null && self.nfnc)
                    {
                        self._incr('_tpup');
                        self._set('_vis30', 0, expDate, true);
                        self.nfnc();
                    }
                }
            }
        }
    },

    /**
     * Fetch and prepare the expiration for the given cookie name
     * @param cn the cookie name
     * @see cnMap
     * @return Date object or null or '' (session)
     */
    _getExp : function(cn) {
        var self = this;
        var amt = self.cnMap[cn];
        if (amt != undefined && amt != null)
        {
            var expDate = '';
            if (amt >= 0)
            {
                var exp = new Date().getTime() + amt;
                expDate = new Date();
                expDate.setTime(exp);
            }
            return expDate;
        }
        return null;
    },

    /**
     * Increments the cookie, create if necessary
     * @param cn the cookie name
     * @param expDate optional expiration date (Date object)
     * @return the val
     */
    _incr : function(cn, expDate) {
        var self = this;
        var c = CookieUtils.getCookie(cn);
        var val = 1;
        if (c != null && !isNaN(c))
        {
            val = Number(c);
            val++;
        }
        self._set(cn, val, true, expDate);
        return val;
    },

    /**
     * Sets the cookie
     * @param cn the cookie name
     * @param cv the cookie value
     * @param overwrite overwrite the value
     * @param expDate optional expiration date (Date object)
     * @return the val if the set was successful (i.e., if overwrite is false and cookie does not exist; or cookie value is not the same as the new value)
     */
    _set : function(cn, cv, overwrite, expDate) {
        var self = this;
        var c = CookieUtils.getCookie(cn);
        if (c != null && !overwrite || c == cv)
        {
            return null;
        }

        var amt = self.cnMap[cn];
        if (amt != null)
        {
            expDate = expDate == undefined ? '' : expDate;
            if (amt >= 0)
            {
                expDate = new Date();
                var exp = new Date().getTime() + amt;
                expDate.setTime(exp);
            }
            CookieUtils.setCookie(cn, cv, expDate, "/", self.dn, false);

//            alert(cn + ':' + CookieUtils.getCookie(cn));
            return cv;
        }
    }
}

YAHOO.namespace("spoke.tracker");

YAHOO.spoke.tracker.dialogInit = function (pageTitle) {

	// Define various event handlers for Dialog
	var handleCancel = function() {
		this.cancel();
	};

	// Instantiate the Dialog
	YAHOO.spoke.tracker.dialog = new YAHOO.widget.Panel("spoke-tracker-dialog", {
							  width: '400px',
                              height: '300px',
							  fixedcenter : true,
							  visible : false,
                              draggable: true,
                              dragOnly: true,
                              //constraintoviewport : true,
                              modal: true,
                              effect: [{
                                effect:YAHOO.widget.ContainerEffect.FADE,duration:0.75
                              }]
                            });
    YAHOO.spoke.tracker.dialog.setHeader('Welcome to Spoke');
    YAHOO.spoke.tracker.dialog.setBody('<iframe \
                    src="http://www.spoke.com/iframe/many_visits_public.html?pageTitle='+escape(pageTitle)+'" \
                    width="400" \
                    height="275" \
                    scrolling="no" \
                    frameborder="0"></iframe>');

    // Render the Dialog
	YAHOO.spoke.tracker.dialog.render();

    return function() {
        if (pageTracker !== undefined)
            pageTracker._trackPageview('/spoke.tracker.dialog.show');
        YAHOO.spoke.tracker.dialog.show();
    }
}        

