/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
var TEMPLATE_COMMENT = '<div id="${comment_id}" class="ceq_rating_box"> \n\
<span id="${rating_id}" style="vertical-align:middle;">\
<span id="RateAL${item_id}" class="widgetlisting" align="right" valign="bottom" style="font-size: smaller; display: none">Lulz</span>\n\
<span class="inline-rating" valign="top">\n\
<ul id="Rate${item_id}" class="ceq_rating small-star" title="0">\n\
<li id="RateC${item_id}" class="curr-rating" style="width:${rating_width}%">Currently ${rating}/5 Stars.</li>\n\
<li id="RateU${item_id}" class="done-rating" style="width:${rating_user_width}%; display: none;">You have rated ${rating_user}/0 Stars.</li>\n\
<li><a href="javascript:void(0);" style="z-index: 4;" rating_val="1" title="Poor" class="one-star">1</a></li>\n\
<li><a href="javascript:void(0);" style="z-index: 3;" rating_val="2" title="Nothing Special" class="two-stars">2</a></li>\n\
<li><a href="javascript:void(0);" style="z-index: 2;" rating_val="3" title="Worth Reading" class="three-stars">3</a></li>\n\
<li><a href="javascript:void(0);" style="z-index: 1;" rating_val="4" title="Pretty Cool" class="four-stars">4</a></li>\n\
<li><a href="javascript:void(0);" style="z-index: 0;" rating_val="5" title="Awesome" class="five-stars">5</a></li>\n\
</ul>\n\
</span>\n\
<span style="vertical-align:top">(<span id="RateX${item_id}"  rating_user="${rating_user}">${rating_count}</span>)</span>\n\
</span>\n\
<span id="span1_${comment_id}">\n\
<img border="0" id="addcomment" src="${WIDGET_RESSOURCE_PATH}/ceq_comment/img/ceq_rating_comment.png" class="ceq_rating_comment" width="14" height="14" align="absbottom">\n\
 <span class="ceq_rating_comment">(${comment_count})</span>\n\
</span> \n\
<span id="span2_${comment_id}">\n\
<img border="0" src="${WIDGET_RESSOURCE_PATH}/ceq_comment/img/ceq_rating_cq.png" class="ceq_rating_ceqinfo" width="14" height="14" align="absbottom" rel="#commenting_overlay" id="openactivities_${comment_id}"> \n\
<span class="ceq_rating_cq">(${equity})</span>\n\
</span> \n\
</div>\n\
<div class="ceq_rating_commentbox" style="position:absolute; display: none; z-index:1000;">\n\
<span class="ceq_rating_post">\n\
<div class="ceq_rating_header">\n\
<span class="ceq_rating_close" id="ceq_comment_close"><img border="0" src="${WIDGET_RESSOURCE_PATH}/ceq_comment/img/ceq_close.gif"/></span>\n\
</div>\n\
<span class="ceq_rating_firstrow">\n\
<img border="0" src="${WIDGET_RESSOURCE_PATH}/ceq_comment/img/ceq_defaultavatar.png" class="ceq_rating_pic">\n\
<textarea name="ceq_rating_input" class="ceq_rating_input" cols="1" rows="1">${comment}</textarea>\n\
</span>\n\
<span class="ceq_rating_secondrow">\n\
<input type="submit" value="Comment" name="ceq_rating_comment" class="ceq_rating_button">\n\
</span>\n\
</span>\n\
</div>\n\
<span id="RateA${item_id}" class="widgetlisting" align="right" valign="bottom" style="font-size: smaller;"></span>\n\
\n\
\n\
</div></div>';/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 * Requires:
 * - jquery.js - 1.2.6 and greater
 * - jquery.template.js
 * - rating_templates.js
 * 
 * TODO: communicate with the user better that the rating is curently being saved
 */

;(function( $ ) {
    function _(str, args) {
        return $.i18n('commenting', str, args);
    }
    
    $.Commenting = function(id){
        this.ID = -1;
        if (id!=null) {
            this.ID = id;
        }

        this.CONTAINER_ID = "comment_" + this.ID;
        this.CS = "#" + this.CONTAINER_ID + " ";
        this.CONTAINER_RATING_ID = "rating_" + this.ID;
        this.RATING_CS = "#" + this.CONTAINER_RATING_ID + " ";
        this.RATING_USER = 0;
        this.RATING_AVG = 0;
        this.RATING_COUNT = 0;
        this.COMMENT_COUNT = 0;
        this.COMMENT = '0';
        this.EQUITY = 0;
        this.PLACEHOLDER = '';

        this.MSGS_ID = '#RateA';
        this.HEIGHT = '120px';
        this.VIEWCOUNT = false;
        this.COUNTVIEWS = 0;
        this.URL;

        this.SHOW_RATING = true;
        this.SHOW_COMMENTING = true;
        this.SHOW_ACTIVITY = true;

        /*
         * params:
         * - rating_width - call getRatingWidth(item.rating)
         * - rating_user_width - call getRatingUserWidth(item.rating_user)
         * - rating_count
         * - item_id - item.id
         */
        this.template_comment = $.template(TEMPLATE_COMMENT);

        this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+"/jersey/InformationParticipationP";
        this.ACTIVITY_WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+ "/jersey/ActivityListingP";

        this.getRequestUrlRating = function(){
            var res = this.WEBSERVICE_URL;
            res += "?output=short&infoid=" + this.ID;
            res += "&viewcount="+this.VIEWCOUNT;
            return res;
        };
        
        this.handleResponse = function(response) {
            //Check for error in response
            if (response.statusCode=='200') {
                this.createItems(response.data);
            } else if (response.statusCode=='403') {
                var link=document.createElement("a") ;
                link.href= response.url + '?goto='+location.href;
                link.appendChild(document.createTextNode(response.message));
                $(this.CS + ' '+this.MSGS_ID + this.ID).append(link);
            } else {
                this.setError("Service not available");
            }
        }

        this.loadRating = function(){
            if (this.ID!=-1) {              
               this.loadRatingFromRemote();                
            }
        };

        this.loadRatingFromRemote = function(){
            //HTTP Status Code in JSON
            var commentingObj = this;
             $.jsonp({
                type: "GET",
                callbackParameter: "callback",
                callback: "callbackFunction",
                url: this.getRequestUrlRating(),
                dataType: "json",
                error: function (d, msg) {
                    commentingObj.setError(document.createTextNode("Service not available"));
                },
                success: function(result){
                    commentingObj.handleResponse(result);
                }
             });
        };


        this.createItems = function(data) {
            var commentingObj = this;
            commentingObj.hideWait();
            if ((data==undefined) || (data==null)){
                commentingObj.setError('Service not available');
                return false;
            }

            if ((data.averageRating==undefined) || (data.averageRating==null)){
                commentingObj.setError('Service not available ');
                return false;
            }
            commentingObj.setRatingAverage(data.averageRating);

           if ((data.countRating==undefined) || (data.countRating==null)){
                commentingObj.setError('Service not available');
                return false;
            }
            commentingObj.setRatingAverage(data.averageRating);
            commentingObj.setRatingUser(data.myRating);
            commentingObj.setRatingCount(data.countRating);
            commentingObj.setCommentCount(data.countComments);
            commentingObj.setComment(data.myComment);
            commentingObj.setEquity(data.informationEquity);
            commentingObj.setCountViews(data.countViews);
            commentingObj.refresh();
        }

        this.showLeft = function(doShowLeft){
            if(doShowLeft) {
                this.MSGS_ID = '#RateAL';
            } else {
                this.MSGS_ID = '#RateA';
            }
        }

        this.showRating = function(bool){
            this.SHOW_RATING = bool;
        }

        this.showCommenting = function(bool){
            this.SHOW_COMMENTING = bool;
        }

        this.showActivity = function(bool){
            this.SHOW_ACTIVITY = bool;
        }

        this.showWait = function(){
            $(this.RATING_CS + ' #Rate' + this.ID).fadeTo("fast", 0.5);
        }
        
        this.hideWait = function(){
            $(this.RATING_CS + ' #Rate' + this.ID).fadeTo("normal", 1.0);
        }

        this.setPlaceholder = function(placeholder) {
            this.PLACEHOLDER = placeholder;
        }

         this.setId = function(id){
            this.ID = id;
            this.CONTAINER_ID = "comment_" + this.ID;
            this.CS = "#" + this.CONTAINER_ID + " ";
            this.CONTAINER_RATING_ID = "rating_" + this.ID;
            this.RATING_CS = "#" + this.CONTAINER_RATING_ID + " ";
        }


        this.setWebserviceURL = function(urlvar) {
            this.WEBSERVICE_URL = urlvar;            
        }


        this.enableViewcount = function() {
            this.VIEWCOUNT = true;
        }

        this.disableViewcount  = function() {
            this.VIEWCOUNT = false;
        }

        this.setRatingUser = function(rating_user){
            this.RATING_USER = rating_user;            
        }
        
        this.setRatingAverage = function(rating_avg){
            this.RATING_AVG = rating_avg;            
        }
        
        this.setRatingCount = function(rating_count){
            this.RATING_COUNT = rating_count;            
        }

        this.setEquity = function(equity){
            this.EQUITY = equity;
        }

         this.setComment = function(comment){
            this.COMMENT = comment;
        }

        this.setCommentCount = function(comment_count){
            this.COMMENT_COUNT = comment_count;
        }
        
        this.setCountViews = function(countviews){
            this.COUNTVIEWS = countviews;
        }

        this.setURL = function(urlstr){
            this.URL = urlstr;
            this.getIDwithURL();
        }

        this.refresh = function(){
            var rc = this.RATING_COUNT;
            $(this.RATING_CS + ' #RateX' + this.ID).html('' + this.RATING_COUNT);
            $(this.RATING_CS + ' #RateC' + this.ID).css("width", (this.RATING_AVG*2*10)+"%" );
            $(this.RATING_CS + ' #RateU' + this.ID).css("width", (this.RATING_USER*2*10)+"%" );
            $(this.RATING_CS + ' #RateX' + this.ID).attr("rating_user", '' + this.RATING_USER);
            $(this.CS + ' .ceq_rating_comment').html('('+this.COMMENT_COUNT+')');
            $(this.CS+' .ceq_rating_input').val(this.COMMENT);
            $(this.CS + ' .ceq_rating_cq').html('('+Math.round(this.EQUITY)+')');
            $(this.CS + ' .ceq_countviews').html(' Views ('+this.COUNTVIEWS+')');
        }
        
        this.setHeight = function(height){
            this.HEIGHT = height;
        }
        
        this.setError = function(message){
            $(this.CS + ' '+this.MSGS_ID + this.ID).html(message);
        }
        
        this.sayThanks = function(){
            $(this.CS + ' '+this.MSGS_ID + this.ID).html('Thanks!');
        }

        this.deploy = function(widgetid){
            this.PLACEHOLDER = widgetid;

            var params = {};
            params.comment_id = this.CONTAINER_ID;
            params.rating_id = this.CONTAINER_RATING_ID;
            params.rating_width = this.getRatingWidth(this.RATING_AVG);
            params.rating_user_width = this.getRatingUserWidth(this.RATING_USER);
            params.rating = this.RATING_AVG;
            params.rating_user = this.RATING_USER;
            params.rating_count = this.RATING_COUNT;
            params.item_id = this.ID;
            params.comment_count = this.COMMENT_COUNT;
            params.comment = this.COMMENT;
            params.equity = this.EQUITY;
            params.countviews = this.COUNTVIEWS;
            params.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;

            $('#'+widgetid).html("<div id='" + this.CONTAINER_ID + "' height='" + this.HEIGHT + "' class='ceq_ratingwidget'></div><div class='overlay' id='commenting_overlay' style='left: 20px; width:545px; height: 290px; '> <div id='commenting_overlay_activitylog' style='width: 500px'> </div></div>");

            $(this.CS).append(this.template_comment, params);

            if (!this.SHOW_RATING) {
                $(this.CS+ ' #rating_'+this.ID).hide();
            }
            if (!this.SHOW_COMMENTING) {
                $(this.CS+ ' #span1_comment_'+this.ID).hide();
            }
            if (!this.SHOW_ACTIVITY) {
                $(this.CS+ ' #span2_comment_'+this.ID).hide();
            }
            var commentingObj = this;
            var viewUserRating = function() {
                $(commentingObj.CS + ' #RateC' + commentingObj.ID).hide();
                $(commentingObj.CS + ' #RateU' + commentingObj.ID).show();
                if ($(commentingObj.CS + ' #RateU' + commentingObj.ID).css("width") == '0%' ) {
                    $(commentingObj.CS + ' '+commentingObj.MSGS_ID + commentingObj.ID).html('Please rate');
                } else {
                    $(commentingObj.CS + ' '+commentingObj.MSGS_ID + commentingObj.ID).html('You\'ve rated ('+commentingObj.RATING_USER+')');
                }
                $(commentingObj.CS + ' '+commentingObj.MSGS_ID + commentingObj.ID).show();
            };
            
            var viewCommunityRating = function(){
                    $(commentingObj.CS + ' #RateU' + commentingObj.ID).hide();
                    $(commentingObj.CS + ' #RateC' + commentingObj.ID).show();
                    $(commentingObj.CS + ' '+commentingObj.MSGS_ID + commentingObj.ID).hide();
                    $(commentingObj.CS + ' '+commentingObj.MSGS_ID + commentingObj.ID).html('You have rated');
            };
                                                
            $(this.RATING_CS).hover(viewUserRating, viewCommunityRating);
            
            
            var vote = function(){
                var Title = $(commentingObj.CS + ' #Rate'+commentingObj.ID).attr('title');
                if(Title != ""){
                    var user_rating = this.innerHTML;
                    commentingObj.showWait();
                     var datastr = commentingObj.WEBSERVICE_URL+"?infoid="+commentingObj.ID+"&rating="+user_rating+"";
                      $.jsonp({
                        type: "GET",
                        callbackParameter: "callback",
                        callback: "callbackFunction",
                        url: datastr,
                        dataType: "json",
                        error: function (d, msg) {
                            commentingObj.setError("Service not available");
                        },
                        success: function(response){
                            commentingObj.setRatingUser(user_rating);
                            commentingObj.handleResponse(response);
                            if (response.statusCode=='200') {
                                commentingObj.sayThanks();
                            }
                        }
                     });

                }
            };

            var comment = function(){
                var text = $(commentingObj.CS+' .ceq_rating_input').val();
                if(text != ''){
                    commentingObj.showWait();

                    var datastr = commentingObj.WEBSERVICE_URL+"?infoid="+commentingObj.ID+"&comment="+text+"";
                      $.jsonp({
                        type: "GET",
                        callbackParameter: "callback",
                        callback: "callbackFunction",
                        url: datastr,
                        dataType: "json",
                        error: function (d, msg) {
                            $(commentingObj.CS +' .ceq_rating_commentbox').toggle('slow');
                            commentingObj.setError("Service not available");
                        },
                        success: function(response){
                            $(commentingObj.CS +' .ceq_rating_commentbox').toggle('slow');
                            commentingObj.handleResponse(response);
                            if (response.statusCode=='200') {
                                commentingObj.sayThanks();
                            }
                        }
                     });                 
                }
            }

            $(this.RATING_CS + ' #Rate' + this.ID + ' a[rating_val]').click(vote);
            $(this.CS + ' .ceq_rating_button').click(comment);
            $(this.CS + ' #addcomment').click(function () {
                  $(commentingObj.CS +' .ceq_rating_commentbox').toggle('slow');
            });

            $(this.CS + ' #ceq_comment_close').click(function () {
                  $(commentingObj.CS + ' .ceq_rating_commentbox').toggle('slow');
            });

            $('#'+ widgetid+' #openactivities_comment_'+ commentingObj.ID).click(function () {
                var activity_log_commenting = new $.ActivityLog(commentingObj.ID);
                activity_log_commenting.setWebserviceURL(commentingObj.ACTIVITY_WEBSERVICE_URL);
                activity_log_commenting.setInfoID(commentingObj.ID);
                activity_log_commenting.deploy('commenting_overlay_activitylog');
            });
            //$('#'+widgetid+' img[rel]').overlay();
            $('#'+ widgetid+' #openactivities_comment_'+ commentingObj.ID).overlay();
            this.loadCSSImages();
            this.refresh();
        };
    
        this.getRatingUserWidth = function(rating_user){
            return rating_user/0.05;
        };
        this.getRatingWidth = function(rating){
            return rating/0.05;
        };

        this.loadCSSImages = function(){
            $('.small-star').css('background-image', 'url('+WIDGET_RESSOURCE_PATH+'/ceq_comment/img/star_small.png)');
            $('.small-star a:hover').css('background-image', 'url('+WIDGET_RESSOURCE_PATH+'/ceq_comment/img/star_small.png)');
            $('.curr-rating').css('background-image', 'url('+WIDGET_RESSOURCE_PATH+'/ceq_comment/img/star_small.png)');
            $('.done-rating').css('background-image', 'url('+WIDGET_RESSOURCE_PATH+'/ceq_comment/img/star_small.png)');
            $('.ceq_rating_commentbox ').css('background-image', 'url('+WIDGET_RESSOURCE_PATH+'/ceq_comment/img/ceq_rating_commentboxbg.gif)');

        };

        this.getIDwithURL = function() {
             var commentingObj = this;
             var datastr = commentingObj.WEBSERVICE_URL.replace('InformationParticipationP','InformationP/ByURL')+'?application=Test+Wiki&url='+this.URL;
             $.jsonp({
                    type: "GET",
                    callbackParameter: "callback",
                    callback: "callbackFunction",
                    url: datastr,
                    dataType: "json",
                    error: function (d, msg) {
                        commentingObj.setError("Service not available");
                    },
                    success: function(response){
                        commentingObj.setId(response.data.infoid);
                        commentingObj.loadRating();
                        commentingObj.deploy(commentingObj.PLACEHOLDER);
                    }
                 });
        };
    }
})(jQuery);/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
/*
 * no params required
 */
var TEMPLATE_ACTIVITY_WIDGET = '<div id="loglisting_header${id}" class="ceq_listing_activity_header"><h3>&nbsp;\n\
<select class="ceq_input" id="ActivityLogFilter${id}" size="1">\n\
	<option value="">Filter by:</option>\n\
	<option value="">All</option>\n\
    <option value="RATE">Rated</option>\n\
	<option value="COMMENT">Commented</option>\n\
	<option value="TAG">Tagged</option>\n\
    <option value="VIEW">Viewed / Downloaded </option>\n\
    <option value="CREATE">Created </option>\n\
    <option value="DELETE">Deleted </option>\n\
<option value="CLONE">Cloned </option>\n\
<option value="UPDATE_CONTENT">Updated content</option>\n\
	<option value="UPDATE_META_DATA">Updated meta data</option>\n\
</select>\n\
</h3></div><div id="loglisting_content${id}">\n\
<div id="loading${id}"><img width="12px" height="12px" src="${WIDGET_RESSOURCE_PATH}/ceq_listing_activity/images/wait.gif"/>&nbsp;Please wait...</div>\n\
</div>\n\
<div class="ceq_listing_footer">\n\
<div class="ceq_listing_divider"></div>\n\
<span id="loglisting_pager${id}" class="ceq_listing_pageroption" style="display: none">\n\
       <a id="loglisting_prev_page${id}" href="javascript:void(0)"><span class="ceq_listing_arrow"> &laquo; </span> Previous</a>\n\
        <span id="loglisting_page_number${id}">&nbsp;</span><span id="loglisting_page_count${id}">&nbsp;</span>\n\
        <a id="loglisting_next_page${id}" href="javascript:void(0)">More <span class="ceq_listing_arrow"> &raquo; </span></a>\n\
</span></div>';

/*
 * params:
 * ${item_id} - id of the item, as received from myshare...
 * 
 *Middle cell:
 * ${item_title}
 * 
 *Second row:
 * ${item_modifier}
 * ${item_modifier_link}
 * ${item_operation}
 * ${time_ago}
 * 
 */


var TEMPLATE_ITEM = '<div class="ceq_listing_activity_item"> \n\
    <img border="0" title="${info_id}" class="ceq_listing_item_icon" src="${WIDGET_RESSOURCE_PATH}/ceq_listing_activity/images/${item_image}"/>\n\
    <span class="ceq_listing_item_title"> ${item_operation} ${item_parameter} \n\
   ${time_ago} by <a href="${item_modifier_link}" title="${item_modifier}">${item_modifier}</a></span></div>';

/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/


/*
 *Require:
 *- jquery.js - 1.2.6 and greater
 *- jquery.template.js
 *- time_renderer.js
 *- activity_log_templates.js
 *
 *Usage:
 * var activity_log = new $.ActivityLog();
 * activity_log.set...
 * activity_log.deploy('logwidgetarea');
 */
;(function( $ ) {
    function _(str, args) {
        return $.i18n('activitylog', str, args);
    }

  $.ActivityLog = function(id){
//--------CONSTANTS
    this.ORDER_DATE = "date";
    this.ORDER_ACTION = "action";


//--------MEMBER VARS
        this.ID = 1;
        if (id!=null) {
            this.ID = id;
        }
        this.CONTAINER_ID = "activity_log_" + this.ID;
        this.CS = "#" + this.CONTAINER_ID + " ";
        this.PAGENR = 1;
        this.COUNT = 10;
        this.FILTER = this.FILTER_ALL;
        this.ORDER = this.ORDER_DATE;
        this.REVERSE = false;
        this.TAGS = null;
        this.USERID = '';
        this.INFOID = null;
        this.PAGECOUNT = 0;
        this.ITEM_COUNT = 0;
        this.SHOW_ITEM_COUNT = true;
		this.HAS_MORE_ITEMS = false;
        this.HEIGHT = '320px';
        this.timeRenderer = new TimeRenderer();

        //templates
        this.template_widget = $.template(TEMPLATE_ACTIVITY_WIDGET);
        this.template_item = $.template(TEMPLATE_ITEM);

        this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+"/jersey/ActivityListingP";

        this.CURRENT_USER = false;

        this.getRequestUrl = function(){
            var res = this.WEBSERVICE_URL+"?count=" + this.COUNT
                + "&pagenr=" + this.PAGENR + "&filter="
                + this.FILTER + "&order=" + this.ORDER
                + "&reverse=" + this.REVERSE;
            if (this.INFOID != null) {
                res += "&infoid=" + this.INFOID;
            }
            if (this.TAGS != null){
                res += "&tags=" + this.TAGS;
            }
            if (this.USERID != null){
                res += "&userid=" + this.USERID;
            }
            if (this.CURRENT_USER==true) {
                res += "&currentuser=true";
            }
            return res;
        };
//------------------------------------------------------------------------------
//-------------------- SETTERS -------------------------------------------------
//------------------------------------------------------------------------------

        this.setHeight = function(height){
            this.HEIGHT = height;
        }

        this.setId = function(id){
            this.ID = id;
            this.CONTAINER_ID = "activity_log_" + this.ID;
            this.CS = "#" + this.CONTAINER_ID + " ";
        }

        this.setWebserviceURL = function(urlvar) {
            this.WEBSERVICE_URL = urlvar;        
        }

        this.setCurrentUserFilter = function(bool){
            this.CURRENT_USER = bool;
        };

        this.setCount = function(count){
            this.COUNT = count;
        };

        this.setPageNr = function(pageNr){
            this.PAGENR = pageNr;
        };

        this.setFilter = function(filter){
            this.FILTER = filter;
        };

        this.setOrder = function(order){
            this.ORDER = order;
        };
        this.setReverse = function(reverse){
            this.REVERSE = reverse;
        };
        this.setTags = function(tags){
            this.TAGS = tags;
        };

        this.setUserID = function(userid){
            this.USERID = userid;
        };

        this.setInfoID = function(infoid){
            this.INFOID = infoid;
        };


        this.setShowItemCount = function(show){
            this.SHOW_ITEM_COUNT = show;
        };

//------------------------------------------------------------------------------
//-------------------- CONTENT -------------------------------------------------
//------------------------------------------------------------------------------
        this.hideContent = function(){
            /* - No More Blinking
                $(this.CS + "#loglisting_content .item_div").each(function(index, item){
                    $(item).slideToggle("normal", function(){
                        $(item).remove();
                        if (index == (this.PAGE_SIZE_ACTUAL-1)){
                            this.showWait();
                        }
                    });
                });
            */
        };

        this.showContent = function(){
            var loglisting = this;
            $(this.CS + " #loglisting_content"+this.ID+" .item_div").each(function(index, item){
                $(item).slideToggle("normal", function(){
                    //just making sure the rating gets displayed as well
                    $(loglisting.CS + " #" + item.id + " #item_rating_cell").show();
                });
            });
        };

        this.removeContent = function(){
             $(this.CS + " #loglisting_content"+this.ID).html('');
        };


//------------------------------------------------------------------------------
//-------------------- WAIT ----------------------------------------------------
//------------------------------------------------------------------------------
        this.showWait = function(){
            $(this.CS + "#loglisting_content"+this.ID).html("<div id='listing_loading'><img width='12px' height='12px' src='"+WIDGET_RESSOURCE_PATH+"/ceq_listing_activity/images/wait.gif'/>&nbsp;Please wait...</div>");
        };

        this.showLoginLink = function(loginurl){
            var link=document.createElement("a") ;
            link.href= loginurl+ '?goto='+location.href;
            link.appendChild(document.createTextNode('Please login!'));
            $(this.CS +" #loglisting_content"+this.ID).html('');
            $(this.CS + " #loglisting_content"+this.ID).append(link);
        }


//------------------------------------------------------------------------------
//-------------------- ITEM COUNT ----------------------------------------------
//------------------------------------------------------------------------------
        this.hideItemCount = function(){
            $(this.CS + "#loglisting_item_count"+this.ID).contents().remove();
            $(this.CS + "#loglisting_item_count"+this.ID).hide();
        };

        this.refreshItemCount = function(){
            $(this.CS + "#loglisting_item_count"+this.ID).contents().remove();
            if (this.ITEM_COUNT > 0){
                  var string = "Total " + this.ITEM_COUNT;
                  if (this.VIEW_MODE == this.VIEWMODE_ALL){
                      string = string + " items.";
                  }else if (this.VIEW_MODE == this.VIEWMODE_MYSHARE){
                      string = string + " files.";
                  }else if (this.VIEW_MODE == this.VIEWMODE_WIKI){
                      string = string + " pages.";
                  }
                  $(this.CS + "#loglisting_item_count"+this.ID).append(document.createTextNode(string));
            }else{
                $(this.CS + "#loglisting_content"+this.ID).append(document.createTextNode("Empty list."));
            }

        };

        this.showItemCount = function(){
            if (!this.SHOW_ITEM_COUNT){
                return;
            }
            this.refreshItemCount();
            $(this.CS + "#loglisting_item_count"+this.ID).show();
        };

//------------------------------------------------------------------------------
//-------------------- PAGER ---------------------------------------------------
//------------------------------------------------------------------------------
        this.disablePager = function(){
            $(this.CS + "#loglisting_prev_page"+this.ID).unbind("click");
            $(this.CS + "#loglisting_next_page"+this.ID).unbind("click");
        };

        this.enablePager = function(){
            var loglisting = this;
            //------------------------------------------------------------------
            //----------- PREV -------------------------------------------------
            //------------------------------------------------------------------
            $(this.CS + "#loglisting_prev_page"+this.ID).click(function(){
                if (loglisting.PAGENR == 1){
                    return false;
                }
                loglisting.PAGENR--;
                loglisting.refreshPager();
                loglisting.disablePager();
                loglisting.hideContent();
                loglisting.showWait();
                loglisting.loadItems();
            });

            //------------------------------------------------------------------
            //----------- NEXT -------------------------------------------------
            //------------------------------------------------------------------
            $(this.CS + "#loglisting_next_page"+this.ID).click(function(){
                if (loglisting.PAGENR == loglisting.PAGECOUNT){
                    return false;
                }
                loglisting.PAGENR++;
                loglisting.refreshPager();
                loglisting.disablePager();
                loglisting.hideContent();
                loglisting.showWait();
                loglisting.loadItems();
            });
        }

        this.hidePager = function(){
            $(this.CS + "#loglisting_pager"+this.ID).hide();
        };

        this.showPager = function(){
            $(this.CS + "#loglisting_pager"+this.ID).show();
        };

        this.calculatePageCount = function(){
            //let's compute PAGECOUNT
            var pageCount = this.ITEM_COUNT/this.COUNT;
            var modulo = this.ITEM_COUNT % this.COUNT;
            if (modulo > 0){
                pageCount = pageCount - (modulo/this.COUNT);
                pageCount++;
            }
            this.PAGECOUNT = pageCount;
        }

        this.refreshPager = function(){
            if (this.PAGENR > this.PAGECOUNT){
                this.PAGENR = this.PAGECOUNT;
            }

            $(this.CS + "#loglisting_page_number"+this.ID).contents().remove();
            $(this.CS + "#loglisting_page_number"+this.ID).append(document.createTextNode(""/*this.PAGENR*/));
            $(this.CS + "#loglisting_page_count"+this.ID).contents().remove();
            $(this.CS + "#loglisting_page_count"+this.ID).append(document.createTextNode(""/*this.PAGECOUNT*/));
            if (this.PAGENR>1){
                $(this.CS + "#loglisting_prev_page"+this.ID).show();
            }else{
                $(this.CS + "#loglisting_prev_page"+this.ID).hide();
            }
            if (this.HAS_MORE_ITEMS){
                $(this.CS + "#loglisting_next_page"+this.ID).show();
            }else{
                $(this.CS + "#loglisting_next_page"+this.ID).hide();
            }
        };


         this.handleResponse = function(response) {
            //Check for error in response
            if (response.statusCode=='200') {
                this.createItems(response.data);
            } else if (response.statusCode=='403') {
                this.showLoginLink(response.url);
            } else {
                $(this.CS + "#loglisting_content"+this.ID).append(document.createTextNode("Service not available"));
            }
        }

        this.createItems = function(result) {
            var loglisting = this;
            loglisting.removeContent();
            loglisting.HAS_MORE_ITEMS = eval(result.hasMore);
            loglisting.ITEM_COUNT = (result.hasMore) ? (this.PAGENR*result.count)+result.count+1 : 0;
            loglisting.calculatePageCount();
            var now = new Date();
            if (result.count>0) {
                $.each(result.activities, function(i, item){
                    var itemObj = {};
                    itemObj.container_id = loglisting.CONTAINER_ID;
                    itemObj.item_id = item.id;
                    itemObj.item_title = item.title;
                    itemObj.item_operation = item.action;
                    itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
                    itemObj.item_parameter =  '';
                    if (item.action=='RATE') {
                        var star_active= '<img border="0" src="'+WIDGET_RESSOURCE_PATH+'/ceq_listing_activity/images/ceq_rating_staractive.png"/>';
                        var star_inactive= '<img border="0" src="'+WIDGET_RESSOURCE_PATH+'/ceq_listing_activity/images/ceq_rating_starinactive.png"/>';
                        for (var i = 1; i <= 5; i++) {
                            if (i<=item.parameter) {
                                itemObj.item_parameter = itemObj.item_parameter + star_active;
                            } else {
                                itemObj.item_parameter = itemObj.item_parameter + star_inactive;
                            }
                        }
                    }
                    itemObj.item_modifier = item.personname;
                    itemObj.item_modifier_link = item.personhomepage;

                    var datedif = (now - item.date)/1000;
                    itemObj.time_ago = loglisting.timeRenderer.getTimeAgo(datedif, now);
                    itemObj.item_image = "ceq_page_download.png";
                    itemObj.info_id = item.infoid;
                    if (item.action=='COMMENT') {
                        itemObj.item_operation = 'Comment added ';
                        itemObj.item_image = "ceq_rating_comment.png";
                    } else if (item.action=='DELETE') {
                        itemObj.item_image = "";
                    } else if (item.action=='CLONE') {
                        itemObj.item_operation = 'Cloned ';
                        itemObj.item_image = "ceq_page_copy.png";
                    } else if (item.action=='RATE') {
                       itemObj.item_operation = 'Rated with ';
                        itemObj.item_image = "ceq_rating_staractive.png";
                    } else if (item.action=='UPDATE_CONTENT') {
                        itemObj.item_operation = 'Updated content ';
                        itemObj.item_image = "ceq_page_edit.png";
                    } else if (item.action=='UPDATE_META_DATA') {
                        itemObj.item_operation = 'Updated meta data ';
                        itemObj.item_image = "ceq_pencil.png";
                    } else if (item.action=='TAG') {
                        itemObj.item_operation = 'Tagged ';
                        itemObj.item_image = "ceq_tag_green.png";
                    } else if (item.action=='VIEW') {
                        itemObj.item_operation = 'Viewed ';
                        itemObj.item_image = "ceq_page_view.png";
                    } else if (item.action=='DOWNLOAD') {
                        itemObj.item_image = "ceq_page_download.png";
                    } else if (item.action=='CREATE'){
                        itemObj.item_operation = 'Created ';
                        itemObj.item_image = "ceq_page_added.png";
                    } else if (item.action=='CHANGE_MAIN_AUTHOR'){
                        itemObj.item_operation = 'Author changed ';
                        itemObj.item_image = "ceq_user.png";
                    }


                    $(loglisting.CS + " #loglisting_content"+loglisting.ID).append(loglisting.template_item, itemObj);
                });
            }
            loglisting.showItemCount();
            loglisting.showContent();
            if (loglisting.PAGECOUNT > 1){
                loglisting.refreshPager();
                loglisting.showPager();
                loglisting.enablePager();
            } else{
               loglisting.hidePager();
            }

        };

//------------------------------------------------------------------------------
//-------------------- LOAD ITEMS ----------------------------------------------
//------------------------------------------------------------------------------

         this.loadItems = function(){
             this.loadItemsFromRemote();
        };


        this.loadItemsFromRemote = function(){
            //HTTP Status Code in JSON
            var listing = this;
             $.jsonp({
                type: "GET",
                callbackParameter: "callback",
                callback: "callbackFunction",
                url: this.getRequestUrl(),
                dataType: "json",
                error: function (d, msg) {
                  listing.removeContent();
                  $(listing.CS + "#loglisting_content"+listing.ID).append(document.createTextNode("Error"));
                },
                success: function(result){
                    listing.handleResponse(result);
                }
             });
        };


//------------------------------------------------------------------------------
//-------------------- DEPLOY --------------------------------------------------
//------------------------------------------------------------------------------
        this.deploy = function(widgetid){
          var loglisting = this;
          $('#'+widgetid).html("<div id='" + this.CONTAINER_ID + "' class='ceq_listingwidget' height='" + this.HEIGHT + "'></div>");

          var itemObj = {};
          itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
          itemObj.id=loglisting.ID;
          $(this.CS).append(this.template_widget, itemObj);
          $(this.CS + " #ActivityLogFilter"+this.ID).change(function(){
              loglisting.setPageNr(1);
              loglisting.setFilter(this.value);
              loglisting.showWait();
              loglisting.loadItems();
          });
          this.showWait();
          this.loadItems();
        }
    };

})(jQuery);


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
/**
* This is a timerenderer which should be used in the UI....
**/
function TimeRenderer(){
/**
* @param seconds - seconds which have passed since some event
* @param now - Date object, representing point in time, to which the output of this func should be related...
* @return string like '10 seconds ago' or 'about 2 months ago'
**/
    this.getTimeAgo = function(seconds, now){
        var today_sec = (now.getHours() * 3600) + (now.getMinutes() * 60) + now.getSeconds();
        seconds = Math.floor(seconds);
        if (seconds < 60){
            if (seconds > 1){
                return seconds + " seconds ago";//plural
            }else{
                return seconds + " second ago";//singular
            }
        }
        var minutes = Math.floor(seconds/60);
        if (seconds <= 1500){//minutes <= 25
            if (minutes > 1){
                return minutes + " minutes ago";//plural
            }else{
                return minutes + " minute ago";//singular
            }
        }
        if (seconds < 2100){//minutes >25 and minutes<35 -> half an hour
            return "half an hour ago";
        }
        if (seconds < 3600){//minutes >=35 and minutes < 60
            return minutes + " minutes ago";
        }
                    
        var hours = Math.floor(seconds/3600);
        if (seconds < 43200){//sec < 43200 -> hours //if hours < 12
            if (hours > 1){
                return "about " + hours + " hours ago";
            }else{
                return "about " + hours + " hour ago";
            }
        }
        if (seconds < 86400){ //if hours < 24
            if (seconds <= today_sec){
                return "Today";
            }else{
                return "Yesterday";
            }
        }
        if (seconds - today_sec < 86400){
            return "Yesterday";
        } 
                    
        var days = Math.floor(seconds/86400);
        if (days < 14){
            var res = "";
            var addedHours = (seconds - (days * 86400))/3600
            addedHours = Math.floor(addedHours);
            if (addedHours > 0){
                if (addedHours < 8){
                    if (days > 1){
                        res += "about " + days + " days ago";
                    }else{
                        res += "about " + days + " day ago";
                    }
                }else if (addedHours < 16){
                    if (days > 1){
                         res += days + " days ";
                    }else{
                         res += days + " day "
                    }
                    if (addedHours > 1){
                       res += addedHours + " hours ago";
                    }else{
                        res += addedHours + " hour ago"
                    } 
                }else{
                    res += "about " + (days + 1) + " days ago"
                }
            }else{
                res += "about " + days + " days ago";
            }
                        
            return res;
        }
                    
        var weeks = Math.floor(seconds/604800);                    
        if (weeks < 8){                        
            var res = "";
            if (weeks > 1){
                res += weeks + " weeks";                            
            }else{
                res += weeks + " week";
            }
            var addedDays = (seconds - (weeks * 604800))/86400;
            addedDays = Math.floor(addedDays);
            if (addedDays > 0){                            
                if (addedDays > 1){
                    res+= " " + addedDays + " days ago";
                }else{
                    res+= " " + addedDays + " day ago";
                }
            }else{
                res = "about " + res + " ago";
            }
            return res;
        }
        var months = Math.floor(seconds/2629743.83);
        if (months < 12){
            var res = "";
            if (months > 1){
                res += months + " months";
                //return months + " months (" + seconds + ") ago";
            }
            var addedWeeks = Math.floor((seconds - (months * 2629743.83))/604800);                        
            if (addedWeeks > 0){
                if (addedWeeks > 1){
                    res+=" " + addedWeeks + " weeks ago";
                }else{
                    res+=" " + addedWeeks + " week ago";
                }                            
            }else{
                res = "about " + res + " ago";
            }
            return res;
        }
        var years = Math.floor(seconds/31556926);
        if (years > 1){
            return "More than " + years + " years ago";
        }else{
            return "More than " + years + " year ago";
        }
    };
};


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
/*
 * no params required
 */
var TEMPLATE_ACTIVITY_LISTING_WIDGET = '<div class="overlay" id="listing_overlay${item_id}">\n\
 <div id="listing_overlay_activitylog${item_id}" style="width: 500px"> </div>\n\
</div>';

var TEMPLATE_LISTING_WIDGET = '<div id="listing_header${id}" class="ceq_listing_header">\n\
<span id="listing_item_count${id}" class="ceq_listing_item_total">Total items</span>\n\
<span class="ceq_listing_filteroption">\n\
Show: <span class="ceq_listing_filteroption_on"><a id="ceq_listing_filter_all${id}" href="javascript:void(0)">All</a></span> \n\
| <a id="ceq_listing_filter_files${id}"  href="javascript:void(0)">Files</a> \n\
| <a id="ceq_listing_filter_pages${id}" href="javascript:void(0)">Pages</a>\n\
</div>\n\
<div id="listing_content${id}"><div id="loading${id}"><img width="12px" height="12px" src="${WIDGET_RESSOURCE_PATH}/ceq_listing_information/images/wait.gif"/>&nbsp;Please wait...</div></div>\n\
<div class="ceq_listing_footer">\n\
<span id="listing_pager${id}" class="ceq_listing_pageroption" style="display: none">\n\
       <a id="listing_prev_page${id}" href="javascript:void(0)"><span class="ceq_listing_arrow"> &laquo; </span> Previous</a>\n\
        <span id="listing_page_number${id}">&nbsp;</span>/<span id="listing_page_count${id}">&nbsp;</span>\n\
        <a id="listing_next_page${id}" href="javascript:void(0)">Next <span class="ceq_listing_arrow"> &raquo; </span></a>\n\
</span></div>';


/*
 * params:
 * ${item_id} - id of the item, as received from myshare...
 * 
 *Middle cell:
 * ${item_title}
 * 
 *Second row:
 * ${item_modifier}
 * ${item_modifier_link}
 * ${item_operation}
 * ${time_ago}
 * 
 */ 
var TEMPLATE_LISTING_ITEM_DIV = '<div id="item_div_${item_id}" class="ceq_listing_item">\n\
<div class="ceq_listing_item_firstrow">\n\
<span class="application application${item_application}"></span>\n\
<span class="ceq_listing_item_title">\n\
<a class="item_link" href="${item_href}" title="${item_title}">${item_title}</a>\n\
</span>\n\
<span class="ceq_listing_item_ceqinfo">\n\
<img border="0" src="${WIDGET_RESSOURCE_PATH}/ceq_comment/img/ceq_rating_cq.png" class="ceq_item_ceqlabel" width="14" height="14" align="absbottom" rel="#listing_overlay${item_id}" id="openactivities_${item_id}"> \n\
<span class="ceq_rating_cq">(${equity})</span>\n\
</span>\n\
</div>\n\
<div class="ceq_listing_item_secondrow">\n\
<span class="ceq_listing_item_modified">${item_type} - \n\
${item_operation} ${time_ago} by <a href="${item_modifier_link}" title="${item_modifier}" >${item_modifier}</a>\n\
</span>\n\
</div>\n\
</div>';


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/


/*
 *Require:
 *- jquery.js - 1.2.6 and greater
 *- jquery.template.js
 *- time_renderer.js
 *- listing_templates.js
 *
 *Usage:
 * jQuery.noConflict();
 * jQuery.listing_table = new jQuery.InformationListing("listing_table");
 * jQuery.listing_table.deploy();
 */
;(function( $ ) {

   function _(str, args) {
        return $.i18n('informationlisting', str, args);
   }

  $.InformationListing = function(id){
//--------CONSTANTS
    this.FILTER_ALL      = "all";
    this.FILTER_WIKI     = "wiki";
    this.FILTER_BLOG     = "blog";
    this.FILTER_FORUM     = "forum";
    this.FILTER_FILES     = "files";
    this.FILTER_PAGES     = "pages";

    this.ORDER_LASTCREATED = "lastcreated";
    this.ORDER_LASTCHANGED = "lastupdated";
    this.ORDER_TOPIQ       = "topiq";

    this.OPERATOR_AND      = "AND";
    this.OPERATOR_OR    = "OR";

//--------MEMBER VARS
        this.ID = 1;
        if (id!=null) {
            this.ID = id;
        }
        this.CONTAINER_ID = "listing_table_" + this.ID;
        this.CS = "#" + this.CONTAINER_ID + " ";

        this.PAGENR = 1;
        this.COUNT = 5;
        this.FILTER = this.FILTER_ALL;
        this.ORDER = this.ORDER_LASTCHANGED;
        this.REVERSE = false;
        this.TAGS = null;
        this.AUTHOR = '';
        this.PAGECOUNT = 0;
        this.ITEM_COUNT = 0;
        this.SHOW_HEADER = true;
        this.SHOW_FILTER = true;
        this.SHOW_ITEM_COUNT = true;
        this.HEIGHT = '320px';
        this.OPERATOR = this.OPERATOR_OR;

        this.timeRenderer = new TimeRenderer();

        //templates
        this.template_widget = $.template(TEMPLATE_LISTING_WIDGET);
        this.template_item_div = $.template(TEMPLATE_LISTING_ITEM_DIV);
        this.template_activity_widget = $.template(TEMPLATE_ACTIVITY_LISTING_WIDGET);

        this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+"/jersey/InformationListingP";
        this.RATING_WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+ "/jersey/InformationParticipationP";
        this.ACTIVITY_WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+ "/jersey/ActivityListingP";

        this.CURRENT_USER = false;

        this.getRequestUrl = function(){
            var res = this.WEBSERVICE_URL+"?count=" + this.COUNT
                + "&pagenr=" + this.PAGENR + "&filter="
                + this.FILTER + "&order=" + this.ORDER
                + "&reverse=" + this.REVERSE;
            if (this.TAGS != null){
                res += "&tags=" + this.TAGS;
            }
            if (this.OPERATOR != null){
                res += "&operator=" + this.OPERATOR;
            }
            if (this.AUTHOR != null){
                res += "&authors=" + this.AUTHOR;
            }
            if (this.CURRENT_USER==true) {
                res += "&currentuser=true";
            }
            return res;
        };
//------------------------------------------------------------------------------
//-------------------- SETTERS -------------------------------------------------
//------------------------------------------------------------------------------
        //id used for subscription to tagcloud changes.
        // TODO: interwidget communication
        this.subscribeToTagCloud = function(tagcloudid){
            var listing = this;
            OpenAjax.hub.subscribe("com.ceq.tagcloud." + tagcloudid, function(name, tags){
                listing.setTags(tags);
                listing.setPageNr(1);
//                listing.refreshPager();
//                listing.disablePager();
                listing.disableFilter();
                listing.hideContent();
                listing.showWait();
                listing.loadItems();
            });
        };

        this.setHeight = function(height){
            this.HEIGHT = height;
        }

        this.setId = function(id){
            this.ID = id;
            this.CONTAINER_ID = "listing_table_" + this.ID;
            this.CS = "#" + this.CONTAINER_ID + " ";
        }

        this.setWebserviceURL = function(urlvar) {
            this.WEBSERVICE_URL = urlvar;
        }

        this.setRatingWebserviceURL = function(urlvar) {
            this.RATING_WEBSERVICE_URL = urlvar;
        }

        this.setCurrentUserFilter = function(bool){
            this.CURRENT_USER = bool;
        };


        this.setCount = function(count){
            this.COUNT = count;
        };

        this.setPageNr = function(pageNr){
            this.PAGENR = pageNr;
        };

        this.setFilter = function(filter){
            this.FILTER = filter;
        };

        this.setOrder = function(order){
            this.ORDER = order;
        };

        this.setReverse = function(reverse){
            this.REVERSE = reverse;
        };

        this.setOperator = function(operator){
            this.OPERATOR = operator;
        };

        this.setTags = function(tags){
            this.TAGS = tags;
        };

        this.setAuthor = function(author){
            this.AUTHOR = author;
        };

        this.setShowFilter = function(show){
            this.SHOW_FILTER = show;
        };

        this.setShowItemCount = function(show){
            this.SHOW_ITEM_COUNT = show;
        };

//------------------------------------------------------------------------------
//-------------------- CONTENT -------------------------------------------------
//------------------------------------------------------------------------------
        this.hideContent = function(){
            /* - No More Blinking
                $(this.CS + "#listing_content .item_div").each(function(index, item){
                    $(item).slideToggle("normal", function(){
                        $(item).remove();
                        if (index == (this.PAGE_SIZE_ACTUAL-1)){
                            this.showWait();
                        }
                    });
                });
            */
        };

        this.showContent = function(){
            var listing = this;
            $(this.CS + "#listing_content"+this.ID+" .item_div").each(function(index, item){
                $(item).slideToggle("normal", function(){
                    //just making sure the rating gets displayed as well
                    //$(listing.CS + "#" + item.id + " #item_rating_cell").show();
                });
            });
        };

        this.removeContent = function(){
            $(this.CS + ' a[rating_val]').unbind();
            //$(this.CS + "#listing_header").html('');
            $(this.CS + "#listing_content"+this.ID).html('');
            //$(this.CS + "#listing_footer").html('');

        };


//------------------------------------------------------------------------------
//-------------------- WAIT ----------------------------------------------------
//------------------------------------------------------------------------------
        this.showWait = function(){
            $(this.CS + "#listing_content"+this.ID).html("<div id='listing_loading'><img width='12px' height='12px' src='"+WIDGET_RESSOURCE_PATH+"/ceq_listing_information/images/wait.gif'/>&nbsp;Please wait...</div>");
        };

        this.showLoginLink = function(loginurl){
            var link=document.createElement("a") ;
            link.href= loginurl + '?goto='+location.href;
            link.appendChild(document.createTextNode('Please login!'));
            $(this.CS +" #listing_content"+this.ID).html('');
            $(this.CS + " #listing_content"+this.ID).append(link);
        }

//------------------------------------------------------------------------------
//-------------------- ITEM COUNT ----------------------------------------------
//------------------------------------------------------------------------------
        this.hideItemCount = function(){
            $(this.CS + "#listing_item_count"+this.ID).contents().remove();
            $(this.CS + "#listing_item_count"+this.ID).hide();
        };

        this.refreshItemCount = function(){
            $(this.CS + "#listing_item_count"+this.ID).contents().remove();
            if (this.ITEM_COUNT > 0){
              var string = "Total " + this.ITEM_COUNT;
              if (this.VIEW_MODE == this.VIEWMODE_ALL){
                  string = string + " items.";
              }else if (this.VIEW_MODE == this.VIEWMODE_MYSHARE){
                  string = string + " files.";
              }else if (this.VIEW_MODE == this.VIEWMODE_WIKI){
                  string = string + " pages.";
              }
              $(this.CS + "#listing_item_count"+this.ID).append(document.createTextNode(string));
            }else{
              $(this.CS + "#listing_content"+this.ID).append(document.createTextNode("Empty list."));
            }

        };

        this.showItemCount = function(){
            if (!this.SHOW_ITEM_COUNT){
                return;
            }
            this.refreshItemCount();
            $(this.CS + "#listing_item_count"+this.ID).show();
        };

//------------------------------------------------------------------------------
//-------------------- PAGER ---------------------------------------------------
//------------------------------------------------------------------------------
        this.disablePager = function(){
            $(this.CS + "#listing_prev_page"+this.ID).unbind("click");
            $(this.CS + "#listing_next_page"+this.ID).unbind("click");
        };

        this.enablePager = function(){
            var listing = this;
            //------------------------------------------------------------------
            //----------- PREV -------------------------------------------------
            //------------------------------------------------------------------
            $(this.CS + "#listing_prev_page"+this.ID).click(function(){
                if (listing.PAGENR == 1){
                    return false;
                }
                listing.PAGENR--;
                listing.refreshPager();
                listing.disablePager();
                listing.disableFilter();
                listing.hideContent();
                listing.showWait();
                listing.loadItems();
            });

            //------------------------------------------------------------------
            //----------- NEXT -------------------------------------------------
            //------------------------------------------------------------------
            $(this.CS + "#listing_next_page"+this.ID).click(function(){
                if (listing.PAGENR == listing.PAGECOUNT){
                    return false;
                }
                listing.PAGENR++;
                listing.refreshPager();
                listing.disablePager();
                listing.disableFilter();
                listing.hideContent();
                listing.showWait();
                listing.loadItems();
            });
        }

        this.hidePager = function(){
            $(this.CS + "#listing_pager"+this.ID).hide();
        };

        this.hidePageCount = function(){
            $(this.CS + "#listing_page_number"+this.ID).hide();
            $(this.CS + "#listing_page_count"+this.ID).hide();
        };


        this.showPager = function(){
            $(this.CS + "#listing_pager"+this.ID).show();
        };

        this.calculatePageCount = function(){
            //let's compute PAGECOUNT
            var pageCount = this.ITEM_COUNT/this.COUNT;
            var modulo = this.ITEM_COUNT % this.COUNT;
            if (modulo > 0){
                pageCount = pageCount - (modulo/this.COUNT);
                pageCount++;
            }
            this.PAGECOUNT = pageCount;
        }

        this.refreshPager = function(){
            if (this.PAGENR > this.PAGECOUNT){
                this.PAGENR = this.PAGECOUNT;
            }

            $(this.CS + "#listing_page_number"+this.ID).contents().remove();
            $(this.CS + "#listing_page_number"+this.ID).append(document.createTextNode(this.PAGENR));
            $(this.CS + "#listing_page_count"+this.ID).contents().remove();
            $(this.CS + "#listing_page_count"+this.ID).append(document.createTextNode(this.PAGECOUNT));
            if (this.PAGENR>1){
                $(this.CS + "#listing_prev_page"+this.ID).show();
            }else{
                $(this.CS + "#listing_prev_page"+this.ID).hide();
            }
            if (this.PAGENR < this.PAGECOUNT){
                $(this.CS + "#listing_next_page"+this.ID).show();
            }else{
                $(this.CS + "#listing_next_page"+this.ID).hide();
            }
        };

//------------------------------------------------------------------------------
//-------------------- FILTER --------------------------------------------------
//------------------------------------------------------------------------------
        this.disableFilter = function(){
            $(this.CS + " .ceq_listing_filteroption").hide();
            $(this.CS + "#ceq_listing_filter_all"+this.ID).unbind("click");
            $(this.CS + "#ceq_listing_filter_all"+this.ID).unbind("filterSwitch");
            $(this.CS + "#ceq_listing_filter_files"+this.ID).unbind("click");
            $(this.CS + "#ceq_listing_filter_files"+this.ID).unbind("filterSwitch");
            $(this.CS + "#ceq_listing_filter_pages"+this.ID).unbind("click");
            $(this.CS + "#ceq_listing_filter_pages"+this.ID).unbind("filterSwitch");
        };

        this.refreshFilter = function(){
            var listing = this;
            var sel_filter_all = this.CS + "#ceq_listing_filter_all"+this.ID;
            var sel_filter_files = this.CS + "#ceq_listing_filter_files"+this.ID;
            var sel_filter_pages = this.CS + "#ceq_listing_filter_pages"+this.ID;

            //filterSwtch event handler...
            var filterSwitch = function(e, filterMode){
                listing.setPageNr(1);
                listing.setViewMode(filterMode);
                listing.refreshFilter();
                listing.disableFilter();
                listing.hideContent();
                listing.showWait();
                listing.loadItems();
            };

            var disableFilterOption = function(filterMode){
                var sel = null;
                if (filterMode == listing.VIEWMODE_ALL){
                    sel = sel_filter_all;
                }else if (filterMode == listing.VIEWMODE_MYSHARE){
                    sel = sel_filter_files;
                }else if (filterMode == listing.VIEWMODE_WIKI){
                    sel = sel_filter_pages;
                }
                if (sel != null){
                    $(sel).removeClass("ceq_listing_filteroption_on");
                    $(sel).addClass("ceq_listing_filteroption_off");
                }else{
                    alert("disableFilterOption ERROR - unknown filterMode='" + filterMode + "'");
                }
            };

            var enableFilterOption = function(filterMode){
                var sel = null;
                if (filterMode == listing.VIEWMODE_ALL){
                    sel = sel_filter_all;
                }else if (filterMode == listing.VIEWMODE_MYSHARE){
                    sel = sel_filter_files;
                }else if (filterMode == listing.VIEWMODE_WIKI){
                    sel = sel_filter_pages;
                }
                if (sel != null){
                    $(sel).removeClass("ceq_listing_filteroption_on");
                    $(sel).addClass("ceq_listing_filteroption_off");
                    $(sel).bind("filterSwitch", filterSwitch);
                    $(sel).click(function(){
                        $(sel).trigger("filterSwitch", [filterMode])
                    });
                }else{
                    alert("enableFilterOption ERROR - unknown filterMode='" + filterMode + "'");
                }
            };

            if (this.VIEW_MODE == this.VIEWMODE_ALL){
                disableFilterOption(this.VIEWMODE_ALL);
                enableFilterOption(this.VIEWMODE_MYSHARE);
                enableFilterOption(this.VIEWMODE_WIKI);

            }else if(this.VIEW_MODE == this.VIEWMODE_MYSHARE){
                disableFilterOption(this.VIEWMODE_MYSHARE)
                enableFilterOption(this.VIEWMODE_ALL);
                enableFilterOption(this.VIEWMODE_WIKI);

            }else if(this.VIEW_MODE == this.VIEWMODE_WIKI){
                disableFilterOption(this.VIEWMODE_WIKI);
                enableFilterOption(this.VIEWMODE_MYSHARE);
                enableFilterOption(this.VIEWMODE_ALL);
            }
        };

        this.hideHeader = function(){
            $(this.CS + " .ceq_listing_header").hide();
        };

        this.showHeader = function(){
            $(this.CS + " .ceq_listing_header").show();
        };

        this.hideFilter = function(){
            $(this.CS + "#ceq_listing_filteroption"+this.ID).hide();
        };

        this.showFilter = function(){
            if (!this.SHOW_FILTER){
                return;
            }
            this.refreshFilter();
            $(this.CS + "#ceq_listing_filteroption"+this.ID).show();
        };

         this.handleResponse = function(response) {
            //Check for error in response
            if (response.statusCode=='200') {
                this.createItems(response.data);
            } else if (response.statusCode=='403') {
               this.showLoginLink(response.url);
            } else {
                $(this.CS + "#listing_content"+this.ID).append(document.createTextNode("Service not available"));
            }
        }

        this.createItems = function(result) {
            var listing = this;
            listing.removeContent();
            listing.ITEM_COUNT = result.totalCount;
            listing.calculatePageCount();
            var now = new Date();

            if (listing.ITEM_COUNT>0) {
                $.each(result.informations, function(i, item){
                    var itemObj = {};
                    itemObj.container_id = listing.CONTAINER_ID;
                    itemObj.item_id = item.id;
                    itemObj.item_href =  item.url;
                    itemObj.item_title = item.title;
                    itemObj.item_type = item.type;
                    itemObj.item_application = item.application.replace(/ /g, "");
                    if (item.changedDate != item.createdDate) {
                       itemObj.item_operation = "Updated";
	                   if (item.changedByName != null) {
	                       itemObj.item_modifier = item.changedByName;
	                   } else {
		                   itemObj.item_modifier = item.createdByName;
	                   }
                    } else {
                       itemObj.item_operation = "Created";
                       itemObj.item_modifier = item.createdByName;
                    }
                    itemObj.item_modifier_link = item.createdHomepage;
                    itemObj.equity = Math.round(item.equity);
                    itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;

                    var datedif = (now - item.changedDate)/1000;
                    itemObj.time_ago = listing.timeRenderer.getTimeAgo(datedif, now);
                    itemObj.rating = item.rating;
                    $(listing.CS + " #listing_content"+listing.ID).append(listing.template_item_div, itemObj);

                    if ((item.ratingCount == null) || (item.ratingCount == undefined) || (item.ratingCount == "")){
                        itemObj.ratingCount = 0;
                    }else{
                        itemObj.ratingCount = item.ratingCount;
                    }

					/*
                    var sr = new $.StarRating(item.id);
                    sr.setRatingAverage(item.rating);
                    sr.setRatingCount(item.ratingCount);
                    sr.setRatingUser(item.myRating);
                    sr.setWebserviceURL(listing.RATING_WEBSERVICE_URL);
                    sr.deploy(listing.CS + "#item_div_" + item.id + " #item_rating_cell");
					*/

                    $(listing.CS + ' #openactivities_'+ item.id).click(function () {
                        var activity_log_listing = new $.ActivityLog(item.id);
                        activity_log_listing.setWebserviceURL(listing.ACTIVITY_WEBSERVICE_URL);
                        activity_log_listing.setUserID("");
                        activity_log_listing.setInfoID(item.id);
                        activity_log_listing.deploy('listing_overlay_activitylog'+ item.id);
                    });

                    var itemObj2 = {};
                      itemObj2.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
                      itemObj2.item_id =item.id;
                      $(listing.CS).append(listing.template_activity_widget, itemObj2);

                    $(listing.CS + ' #openactivities_'+ item.id).overlay();


                });
            }
            listing.showItemCount();
            listing.showContent();
            listing.showFilter();

            if (listing.PAGECOUNT > 1){
                listing.refreshPager();
                listing.showPager();
                listing.enablePager();
            }else{
                listing.hidePager();
            }

        }
//------------------------------------------------------------------------------
//-------------------- LOAD ITEMS ----------------------------------------------
//------------------------------------------------------------------------------

         this.loadItems = function(){
            this.loadItemsFromRemote();
        };


        this.loadItemsFromRemote = function(){
            //HTTP Status Code in JSON
            var listing = this;
             $.jsonp({
                type: "GET",
                callbackParameter: "callback",
                callback: "callbackFunction",
                url: this.getRequestUrl(),
                dataType: "json",
                error: function (d, msg) {
                  listing.removeContent();
                  $(listing.CS + "#listing_content"+listing.ID).append(document.createTextNode("Error"));
                },
                success: function(result){
                    listing.handleResponse(result);
                }
             });
        };

//------------------------------------------------------------------------------
//-------------------- DEPLOY --------------------------------------------------
//------------------------------------------------------------------------------
        this.deploy = function(widgetid){
          $('#'+widgetid).html("<div id='" + this.CONTAINER_ID + "' height='" + this.HEIGHT + "' class='ceq_listingwidget'></div>");

          var itemObj = {};
          itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
          itemObj.id = this.ID;
          $(this.CS).append(this.template_widget, itemObj);

          this.showWait();
          this.disableFilter();
          if (!this.SHOW_HEADER) {
              this.hideHeader();
          }
          //this.hidePageCount();
          this.loadItems();

        }
    };

})(jQuery);


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 * Requires:
 * - jquery.js - 1.2.6 and greater
 * - jquery.template.js
 * - rating_templates.js
 * 
 * TODO: communicate with the user better that the rating is curently being saved
 */

;(function( $ ) {
    
    $.StarRating = function(itemId){
        this.ID = itemId;
        this.CONTAINER_ID = "rating_" + this.ID;
        this.CS = "#" + this.CONTAINER_ID + " ";
        this.RATING_USER = 0;
        this.RATING_AVG = 0;
        this.RATING_COUNT = 0;
        this.ITEM_ID = itemId;
        this.MSGS_ID = '#RateA';
        this.HEIGHT = '320px';

        this.WEBSERVICE_URL = "/ceq-ws/jersey/InformationParticipationP";
        
        /*
         * params:
         * - rating_width - call getRatingWidth(item.rating)
         * - rating_user_width - call getRatingUserWidth(item.rating_user)
         * - rating_count
         * - item_id - item.id
         */
        this.template_rating = $.template(TEMPLATE_RATING);
        
        this.showLeft = function(doShowLeft){
            if(doShowLeft) {
                this.MSGS_ID = '#RateAL';
            } else {
                this.MSGS_ID = '#RateA';
            }
        }
        
        this.showWait = function(){
            $(this.CS + ' #Rate' + this.ITEM_ID).fadeTo("fast", 0.5);
        }
        
        this.hideWait = function(){
            $(this.CS + ' #Rate' + this.ITEM_ID).fadeTo("normal", 1.0);
        }
        
         this.setId = function(id){
            this.ID = id;
            this.CONTAINER_ID = "rating_" + this.ID;
            this.CS = "#" + this.CONTAINER_ID + " ";
        }

        this.setWebserviceURL = function(urlvar) {
            this.WEBSERVICE_URL = urlvar;
        }

        this.setRatingUser = function(rating_user){
            this.RATING_USER = rating_user;            
        }
        
        this.setRatingAverage = function(rating_avg){
            this.RATING_AVG = rating_avg;            
        }
        
        this.setRatingCount = function(rating_count){
            this.RATING_COUNT = rating_count;            
        }
  
        this.refresh = function(){
            var rc = this.RATING_COUNT;
            $(this.CS + ' #RateX' + this.ITEM_ID).html('' + this.RATING_COUNT);
            $(this.CS + ' #RateC' + this.ITEM_ID).css("width", (this.RATING_AVG*2*10)+"%"  );
            $(this.CS + ' #RateU' + this.ITEM_ID).css("width", (this.RATING_USER*2*10)+"%"  );
            $(this.CS + ' #RateX' + this.ITEM_ID).attr("rating_user", '' + this.RATING_USER);
        }
        
        this.setHeight = function(height){
            this.HEIGHT = height;
        }
        
        this.setError = function(message){
            $(this.CS + ' '+this.MSGS_ID + this.ITEM_ID).html(message);
        }
        
        this.sayThanks = function(){
            $(this.CS + ' '+this.MSGS_ID + this.ITEM_ID).html('Thanks!');
        }
        var ratingObj = this;

        this.handleResponse = function(response){
            ratingObj.hideWait();
            if (response.statusCode=='200') {
                ratingObj.sayThanks();
                ratingObj.setRatingAverage(response.data.averageRating);
                $('#item_div_'+ratingObj.ITEM_ID+' .ceq_rating_cq').html('('+Math.round(response.data.informationEquity)+')')
                ratingObj.setRatingCount(response.data.countRating);
            } else {
                ratingObj.setError('Service not available');
                return false;
            }                       
            ratingObj.refresh();                    
            return true;
        };
            
        this.deploy = function(widgetid){
            var params = {};
            params.rating_id = this.CONTAINER_ID;
            params.rating_width = this.getRatingWidth(this.RATING_AVG);
            params.rating_user_width = this.getRatingUserWidth(this.RATING_USER);
            params.rating = this.RATING_AVG;
            params.rating_user = this.RATING_USER;
            params.rating_count = this.RATING_COUNT;
            params.item_id = this.ITEM_ID;
            params.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
            $(widgetid).append(this.template_rating, params);
            
            var ratingObj = this;
            var viewUserRating = function() {
                $(ratingObj.CS + ' #RateC' + ratingObj.ITEM_ID).hide();
                $(ratingObj.CS + ' #RateU' + ratingObj.ITEM_ID).show();
                if ($(ratingObj.CS + ' #RateU' + ratingObj.ITEM_ID).css("width") == '0%' ) {
                    $(ratingObj.CS + ' '+ratingObj.MSGS_ID + ratingObj.ITEM_ID).html('Please rate');
                } else {
                    $(ratingObj.CS + ' '+ratingObj.MSGS_ID + ratingObj.ITEM_ID).html('You\'ve rated ('+ratingObj.RATING_USER+')');
                }
                $(ratingObj.CS + ' '+ratingObj.MSGS_ID + ratingObj.ITEM_ID).show();
            };
            
            var viewCommunityRating = function(){
                    $(ratingObj.CS + ' #RateU' + ratingObj.ITEM_ID).hide();
                    $(ratingObj.CS + ' #RateC' + ratingObj.ITEM_ID).show();
                    $(ratingObj.CS + ' '+ratingObj.MSGS_ID + ratingObj.ITEM_ID).hide();
                    $(ratingObj.CS + ' '+ratingObj.MSGS_ID + ratingObj.ITEM_ID).html('You have rated');
            };
                                                
            $(this.CS).hover(viewUserRating, viewCommunityRating);
            
            
            var vote = function(){
                var Title = $(ratingObj.CS + ' #Rate'+ratingObj.ITEM_ID).attr('title');

                if(Title != ""){
                    var user_rating = this.innerHTML;
                    ratingObj.showWait();
                     var datastr = ratingObj.WEBSERVICE_URL+"?infoid="+ratingObj.ID+"&rating="+user_rating+"";
                      $.jsonp({
                        type: "GET",
                        callbackParameter: "callback",
                        callback: "callbackFunction",
                        url: datastr,
                        dataType: "json",
                        error: function (d, msg) {
                            ratingObj.setError("Service not available");
                        },
                        success: function(response){
                            if (response.statusCode=='200') {
                                ratingObj.sayThanks();
                                ratingObj.setRatingUser(user_rating);
                            }
                            ratingObj.handleResponse(response);
                            
                        }
                     });

                }
            }
                        
            $(this.CS + ' #Rate' + this.ITEM_ID + ' a[rating_val]').click(vote);
            this.refresh();
        }
    
        this.getRatingUserWidth = function(rating_user){
            return rating_user/0.05;
        };
        this.getRatingWidth = function(rating){
            return rating/0.05;
        };          
    }
})(jQuery);/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
var TEMPLATE_RATING = '<span id="${rating_id}" style="vertical-align:middle;">\
<span id="RateAL${item_id}" class="widgetlisting" align="right" valign="bottom" style="font-size: smaller; display: none">Lulz</span>\n\
<span class="inline-rating" valign="top">\n\
<ul id="Rate${item_id}" class="ceq_rating small-star" title="0">\n\
<li id="RateC${item_id}" class="curr-rating" style="width:${rating_width}%">Currently ${rating}/5 Stars.</li>\n\
<li id="RateU${item_id}" class="done-rating" style="width:${rating_user_width}%; display: none;">You have rated ${rating_user}/0 Stars.</li>\n\
<li><a href="javascript:void(0);" style="z-index: 4;" rating_val="1" title="Poor" class="one-star">1</a></li>\n\
<li><a href="javascript:void(0);" style="z-index: 3;" rating_val="2" title="Nothing Special" class="two-stars">2</a></li>\n\
<li><a href="javascript:void(0);" style="z-index: 2;" rating_val="3" title="Worth Reading" class="three-stars">3</a></li>\n\
<li><a href="javascript:void(0);" style="z-index: 1;" rating_val="4" title="Pretty Cool" class="four-stars">4</a></li>\n\
<li><a href="javascript:void(0);" style="z-index: 0;" rating_val="5" title="Awesome" class="five-stars">5</a></li>\n\
</ul>\n\
</span>\n\
<span style="vertical-align:top">(<span id="RateX${item_id}"  rating_user="${rating_user}">${rating_count}</span>)</span><br/>\n\
<span id="RateA${item_id}" class="widgetlisting" align="right" valign="bottom" style="font-size: smaller;"></span>\n\
</span>';


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
/**
* This is a timerenderer which should be used in the UI....
**/
function TimeRenderer(){
/**
* @param seconds - seconds which have passed since some event
* @param now - Date object, representing point in time, to which the output of this func should be related...
* @return string like '10 seconds ago' or 'about 2 months ago'
**/
    this.getTimeAgo = function(seconds, now){
        var today_sec = (now.getHours() * 3600) + (now.getMinutes() * 60) + now.getSeconds();
        seconds = Math.floor(seconds);
        if (seconds < 60){
            if (seconds > 1){
                return seconds + " seconds ago";//plural
            }else{
                return seconds + " second ago";//singular
            }
        }
        var minutes = Math.floor(seconds/60);
        if (seconds <= 1500){//minutes <= 25
            if (minutes > 1){
                return minutes + " minutes ago";//plural
            }else{
                return minutes + " minute ago";//singular
            }
        }
        if (seconds < 2100){//minutes >25 and minutes<35 -> half an hour
            return "half an hour ago";
        }
        if (seconds < 3600){//minutes >=35 and minutes < 60
            return minutes + " minutes ago";
        }
                    
        var hours = Math.floor(seconds/3600);
        if (seconds < 43200){//sec < 43200 -> hours //if hours < 12
            if (hours > 1){
                return "about " + hours + " hours ago";
            }else{
                return "about " + hours + " hour ago";
            }
        }
        if (seconds < 86400){ //if hours < 24
            if (seconds <= today_sec){
                return "Today";
            }else{
                return "Yesterday";
            }
        }
        if (seconds - today_sec < 86400){
            return "Yesterday";
        } 
                    
        var days = Math.floor(seconds/86400);
        if (days < 14){
            var res = "";
            var addedHours = (seconds - (days * 86400))/3600
            addedHours = Math.floor(addedHours);
            if (addedHours > 0){
                if (addedHours < 8){
                    if (days > 1){
                        res += "about " + days + " days ago";
                    }else{
                        res += "about " + days + " day ago";
                    }
                }else if (addedHours < 16){
                    if (days > 1){
                         res += days + " days ";
                    }else{
                         res += days + " day "
                    }
                    if (addedHours > 1){
                       res += addedHours + " hours ago";
                    }else{
                        res += addedHours + " hour ago"
                    } 
                }else{
                    res += "about " + (days + 1) + " days ago"
                }
            }else{
                res += "about " + days + " days ago";
            }
                        
            return res;
        }
                    
        var weeks = Math.floor(seconds/604800);                    
        if (weeks < 8){                        
            var res = "";
            if (weeks > 1){
                res += weeks + " weeks";                            
            }else{
                res += weeks + " week";
            }
            var addedDays = (seconds - (weeks * 604800))/86400;
            addedDays = Math.floor(addedDays);
            if (addedDays > 0){                            
                if (addedDays > 1){
                    res+= " " + addedDays + " days ago";
                }else{
                    res+= " " + addedDays + " day ago";
                }
            }else{
                res = "about " + res + " ago";
            }
            return res;
        }
        var months = Math.floor(seconds/2629743.83);
        if (months < 12){
            var res = "";
            if (months > 1){
                res += months + " months";
                //return months + " months (" + seconds + ") ago";
            }
            var addedWeeks = Math.floor((seconds - (months * 2629743.83))/604800);                        
            if (addedWeeks > 0){
                if (addedWeeks > 1){
                    res+=" " + addedWeeks + " weeks ago";
                }else{
                    res+=" " + addedWeeks + " week ago";
                }                            
            }else{
                res = "about " + res + " ago";
            }
            return res;
        }
        var years = Math.floor(seconds/31556926);
        if (years > 1){
            return "More than " + years + " years ago";
        }else{
            return "More than " + years + " year ago";
        }
    };
};


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 *Require:
 *- jquery.js - 1.2.6 and greater
 *- jquery.template.js
 *- login_templates.js
 *
 *Usage:
 */



;(function( $ ) {
    function _(str, args) {
        return $.i18n('login', str, args);
    }

  $.Login = function(){
        //--------CONSTANTS


        //--------MEMBER VARS
        this.ID = 1;
        this.CONTAINER_ID = "login_" + this.ID;
        this.CS = "#" + this.CONTAINER_ID + " ";
        this.HEIGHT = '200px';

        //templates
        this.template_widget = $.template(TEMPLATE_LOGIN_WIDGET);
        this.template_item = $.template(TEMPLATE_LOGIN_ITEM);

        this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+"/jersey/UserProfileP";

        this.LOGOUT_URL = "/opensso/UI/Logout";

        this.getRequestUrl = function(){
            var res = this.WEBSERVICE_URL+"?currentuser=true";
            return res;
        }

//------------------------------------------------------------------------------
//-------------------- SETTERS -------------------------------------------------
//------------------------------------------------------------------------------
        this.setLogoutURL = function(urlvar) {
            this.LOGOUT_URL = urlvar;
        }

         this.setWebserviceURL = function(urlvar) {
            this.WEBSERVICE_URL = urlvar;            
        }

        this.setHeight = function(height){
            this.HEIGHT = height;
        }



//------------------------------------------------------------------------------
//-------------------- CONTENT -------------------------------------------------
//------------------------------------------------------------------------------
        this.hideContent = function(){

        };

        this.showContent = function(){

        };

        this.removeContent = function(){
             $("#login_content").html('');
        };

//------------------------------------------------------------------------------
//-------------------- WAIT ----------------------------------------------------
//------------------------------------------------------------------------------

        this.showWait = function(){
            $(this.CS +" #login_content").html("<div id='login_loading'><img width='12px' height='12px' src='"+WIDGET_RESSOURCE_PATH+"/ceq_login/images/wait.gif'/>&nbsp;Please wait...</div>");
        }

        this.showLoginLink = function(loginurl){
            var link=document.createElement("a") ;
            if (!loginurl) {
                link.href='';
            } else if (loginurl.indexOf('?')!=-1) {
                link.href= loginurl + '&goto='+location.href;
            } else {
                link.href= loginurl + '?goto='+location.href;
            }
            link.appendChild(document.createTextNode('Please login!'));
            $(this.CS +" #login_content").html('');
            $(this.CS + " #login_content").append(link);
        }

        this.handleResponse = function(response) {
            //Check for error in response
            if (response.statusCode=='200') {
	            this.setLogoutURL(response.logoutUrl);
                this.createItems(response.data);
            } else if (response.statusCode=='403') {
                this.showLoginLink(response.url);
            } else {
                $(this.CS + "#login_content").append(document.createTextNode("Service not available"));
            }
        }

        this.createItems = function(result) {
            //show items
            thisobj = this;
            thisobj.removeContent();

            var itemObj = {};
            itemObj.LOGOUT_URL = this.LOGOUT_URL;
            itemObj.GIVENNAME = result.givenname;
            itemObj.SURNAME = result.surname;
            itemObj.EMAIL = result.email;
            $(thisobj.CS + " #login_content").append(thisobj.template_item, itemObj);


        }
//------------------------------------------------------------------------------
//-------------------- LOAD ITEMS ----------------------------------------------
//------------------------------------------------------------------------------
        this.loadItems = function(){
             this.loadItemsFromRemote();
            
        };

        this.loadItemsFromRemote = function(){
            //HTTP Status Code in JSON
            var tagcloud = this;
             $.jsonp({
                type: "GET",
                callbackParameter: "callback",
                callback: "callbackFunction",
                url: this.getRequestUrl(),
                dataType: "json",
                error: function (d, msg) {
                  tagcloud.removeContent();
                  $(tagcloud.CS + "#tagcloud_content").append(document.createTextNode("Error"));
                },
                success: function(result){
                    tagcloud.handleResponse(result);
                }
             });
        };


//------------------------------------------------------------------------------
//-------------------- DEPLOY --------------------------------------------------
//------------------------------------------------------------------------------
        this.deploy = function(widgetid){
          $('#'+widgetid).html("<div id='" + this.CONTAINER_ID + "' class='ceq_loginwidget' height='" + this.HEIGHT + "'></div>");
           var itemObj = {};
          itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
          $(this.CS).append(this.template_widget, itemObj);
          this.showWait();
          this.loadItems();
        }
    };

})(jQuery);


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
var TEMPLATE_LOGIN_WIDGET = '<div id="login_content" class="ceq_login_box">\n\
</div>';

var TEMPLATE_LOGIN_ITEM = '${GIVENNAME} ${SURNAME} (${EMAIL}) &nbsp;  <a href="${LOGOUT_URL}">Logout</a>';

/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 *Require:
 *- jquery.js - 1.2.6 and greater
 *- jquery.template.js
 *- login_templates.js
 *
 *Usage:
 */


;
(function($) {

	$.CliqsetConnect = function(manager) {
		//--------MEMBER VARS
		this.ID = 1;
		this.CONTAINER_ID = "cliqsetconnect_" + this.ID;
		this.CS = "#" + this.CONTAINER_ID + " ";
		this.template_cliqset = $.template(TEMPLATE_CLIQSETCONNECT_WIDGET);
		this.manager = manager;

		this.deploy = function(widgetid, manager) {
			var overlay = this;

			$('#'+widgetid).append(this.template_cliqset);

			$("#cliqsetconnect_register").click(function() {
				jQuery("#cliqsetconnect_overlay #messages").empty();
				jQuery("#add_cliqset_feed").attr("disabled", false);
				$("#cliqsetconnect_overlay").overlay({
					top: 100,
					api: true,
					finish: {
						top: 100,
						left: 'center',
						absolute: false
					}
				}).load();
			});

			// register submit button
			$("#add_cliqset_feed").click(function() {
				$("#cliqsetconnect_content #messages").empty();
				var applicationName = "Cliqset";
				var feedType = "activitystream";
				var feedUrl = "http://cliqset.com/feed/atom?uid=" + $("#cliqsetid").val();
				var ownerAlias = $("#cliqsetid").val();
				var defaultTags = '';

				//clear messages and show wait
				jQuery("#cliqsetconnect_overlay #messages").empty().append("Please Wait...<img src=\""+WIDGET_RESSOURCE_PATH+"/ceq_siteconnect/images/wait.gif\">");
				jQuery("#add_cliqset_feed").attr("disabled", true);

				var newFeed = {};
				newFeed.applicationName = applicationName;
				newFeed.feedType = feedType;
				newFeed.feedUrl = feedUrl;
				newFeed.defaultTags = defaultTags;
				newFeed.ownerAlias = ownerAlias;
				newFeed.siteFeed = false;
				jQuery.ajax({
					type: "POST",
					url: "/ceq-ws/jersey/Feeds",
					data: newFeed,
					success: function(response, textStatus) {
						jQuery("#cliqsetconnect_overlay #messages").empty().append("Feed Saved!");
						jQuery("#cliqsetconnect_overlay").overlay({
							api: true
						}).close();
						overlay.manager.updatePersonalFeedRow(response);
					},
					error: function(xhr, textStatus, errorThrown) {
						jQuery("#cliqsetconnect_overlay #messages").empty().append("<font color=\"red\">Error registering feed - " + textStatus + " " + xhr.responseText + "</font><br/>");
						jQuery("#add_cliqset_feed").attr("disabled", false);
					},
					dataType:"json"
				});
			});

		};
	};

})(jQuery);


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 *Require:
 *- jquery.js - 1.2.6 and greater
 *- jquery.template.js
 *- login_templates.js
 *
 *Usage:
 */


;
(function($) {
	function _(str, args) {
		return $.i18n('login', str, args);
	}

	$.FbConnect = function() {
		//--------MEMBER VARS
		this.ID = 1;
		this.CONTAINER_ID = "fbconnect_" + this.ID;
		this.CS = "#" + this.CONTAINER_ID + " ";

		//templates
		this.facebook_api_key = "";
		this.template_widget = $.template(TEMPLATE_FBCONNECT_WIDGET);
		this.template_item = $.template(TEMPLATE_FBCONNECT_ITEM);

		this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+"/jersey/Facebook/fbstatus";
		this.AUTH_WEBSERVICE_URL = "ceq-ws/jersey/Facebook/authorize";
		/* TODO: Turn into a jndi configuration parameter */
		this.FACEBOOK_LOGIN_URL = "http://www.facebook.com/login.php";

		String.prototype.bool = function() {
		    return (/^true$/i).test(this);
		};

		//------------------------------------------------------------------------------
		//-------------------- CONTENT -------------------------------------------------
		//------------------------------------------------------------------------------

		this.removeContent = function() {
			$("#fbconnect_content").html('');
		};

		//------------------------------------------------------------------------------
		//-------------------- WAIT ----------------------------------------------------
		//------------------------------------------------------------------------------

		this.showWait = function() {
			$(this.CS + " #fbconnect_content").html("<div id='login_loading'><img width='12px' height='12px' src='" + WIDGET_RESSOURCE_PATH + "/ceq_siteconnect/images/wait.gif'/>&nbsp;Please wait...</div>");
		}

                  this.setWebserviceURL = function(urlvar) {
                        this.WEBSERVICE_URL = urlvar;
                    }

		this.showLoginLink = function(loginurl) {
			var link = document.createElement("a") ;
			if (loginurl.indexOf('?') != -1) {
				link.href = loginurl + '&goto=' + location.href;
			} else {
				link.href = loginurl + '?goto=' + location.href;
			}
			link.appendChild(document.createTextNode('Please login!'));
			$(this.CS + " #fbconnect_content").html('');
			$(this.CS + " #fbconnect_content").append(link);
		}

		this.showFacebookLoginLink = function(fbloginurl) {
			var nextUrl = $.url.setUrl(window.location).attr("base") + this.AUTH_WEBSERVICE_URL;

			var link = document.createElement("a") ;
			link.href = '#';
			var fblink = fbloginurl + '?api_key=' + facebook_api_key +
			             '&fbconnect=true&v=1.0&connect_display=popup&return_session=true' +
			             '&req_perms=read_stream,offline_access&next=' + nextUrl;
			link.onclick = function() {
				window.open(fblink, "popup", "width=640, height=500");
			}
			var img = document.createElement("img");
			img.setAttribute('src', 'http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_light_large_long.gif');
			img.setAttribute('alt', 'Facebook Login');
			img.setAttribute('border', '0');
			link.appendChild(img);
			$(this.CS + " #fbconnect_content").html('');
			$(this.CS + " #fbconnect_content").append(link);
		}

		this.handleResponse = function(response) {
			//Check for error in response
			if (response.statusCode == '200') {
				fbloggedin = false;

				if (response.data.attributes != null) {

					$.each(response.data.attributes.entry, function(i, item) {
						if (item.key.$ == "apiKey") {
							facebook_api_key = item.value.$;
						}
						if (item.key.$ == "isLoggedIn") {
							fbloggedin = item.value.$.bool();
						}
					});
				}
				if (!fbloggedin) {
					if (facebook_api_key == "") {
						$(this.CS +" #fbconnect_content").html('');
						$(this.CS + "#fbconnect_content").append(document.createTextNode("Facebook API Key not configured"));
					} else {
						this.showFacebookLoginLink(this.FACEBOOK_LOGIN_URL);
					}
				} else {
					this.createItems(response.data);
				}
			} else if (response.statusCode == '403') {
				this.showLoginLink(response.url);
			} else {
				$(this.CS + "#fbconnect_content").append(document.createTextNode("Service not available"));
			}
		}

		this.createItems = function(result) {
			//show items
			thisobj = this;
			thisobj.removeContent();

			var itemObj = {};
			itemObj.GIVENNAME = result.givenname;
			itemObj.SURNAME = result.surname;
			itemObj.EMAIL = result.email;
			$(thisobj.CS + " #fbconnect_content").append(thisobj.template_item, itemObj);


		}
		//------------------------------------------------------------------------------
		//-------------------- LOAD ITEMS ----------------------------------------------
		//------------------------------------------------------------------------------


		this.loadItemsFromLocal = function() {
			//HTTP Status Code in Header
			var fbconnectwidget = this;

			$.ajax({
				type: "GET",
				url: this.WEBSERVICE_URL,
				dataType: "json",
				error: function (xhr, textStatus, errorThrown) {
					fbconnectwidget.removeContent();
					if (xhr.status == '403') {
						fbconnectwidget.showLoginLink(xhr.getResponseHeader('X-CeqLoginUrl'));
					} else {
						$(fbconnectwidget.CS + "#tagcloud_content").append(document.createTextNode("Service not available"));
					}
				},
				success: function(result) {
					fbconnectwidget.handleResponse(result);
				}
			});

		};


		//------------------------------------------------------------------------------
		//-------------------- DEPLOY --------------------------------------------------
		//------------------------------------------------------------------------------
		this.deploy = function(widgetid) {
			$('#' + widgetid).html("<div id='" + this.CONTAINER_ID + "' class='ceq_loginwidget' height='" + this.HEIGHT + "'></div>");
			var itemObj = {};
			itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
			$(this.CS).append(this.template_widget, itemObj);
			this.showWait();
			this.loadItemsFromLocal();
		}
	};

})(jQuery);


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 *Require:
 *- jquery.js - 1.2.6 and greater
 *- jquery.template.js
 *- time_renderer.js
 *- listing_templates.js
 *
 *Usage:
 * jQuery.noConflict();
 * jQuery.listing_table = new jQuery.InformationListing("listing_table");
 * jQuery.listing_table.deploy();
 */
;(function( $ ) {
    $.SiteConnect = function(id){
	    this.ID = 1;
	    if (id!=null) {
	        this.ID = id;
	    }

	    this.CONTAINER_ID = "siteconnect_" + this.ID;
	    this.CS = "#" + this.CONTAINER_ID + " ";
	    this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+"/jersey/Feeds/SiteFeeds";
	    this.WEBSERVICE_FEED_URL = WEBSERVICE_RESSOURCE_PATH+"/jersey/Feeds";
	    this.WEBSERVICE_PERSONAL_URL = WEBSERVICE_RESSOURCE_PATH+"/jersey/Feeds/PersonalFeeds";

        this.EMPTY_FEEDS_RESPONSE = "EMPTY";
        this.template_table = $.template(TEMPLATE_SITECONNECT_TABLE);

	    this.template_row = $.template(TEMPLATE_SITECONNECT_ROW);
	    this.template_row_content = $.template(TEMPLATE_SITECONNECT_ROW_CONTENT);
	    this.template_empty_row = $.template(TEMPLATE_SITECONNECT_EMPTY_ROW);

	    this.template_personal_row = $.template(TEMPLATE_SITECONNECT_PERSONAL_ROW);
	    this.template_personal_row_content = $.template(TEMPLATE_SITECONNECT_PERSONAL_ROW_CONTENT);
	    this.template_personal_empty_row = $.template(TEMPLATE_SITECONNECT_PERSONAL_EMPTY_ROW);


	    this.tmp_feeds_response = null;
	    this.tmp_personal_feeds_response = null;

        this.deploy = function(CS){
            var manager = this;
            if (CS){
                this.CS = CS;
            }else{
                throw 'Container Selector not valid!';
            }
            var itemObj = {};
            itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
            $(this.CS).append(this.template_table, itemObj);

	        var fbconnect = new $.FbConnect();
	        fbconnect.deploy('ceq_siteconnect_personal_icons');

	        var cliqset = new $.CliqsetConnect(manager);
	        cliqset.deploy('ceq_siteconnect_personal_icons');

            $.ajax({
                type: "GET",
                url: this.WEBSERVICE_URL + "?format=json",
                success: function(data){
                    manager.handleGetAllFeedsResponse(data);
                },
                error: function(xhr, textStatus, errorThrown){
                        alert("Error getting the list of feeds: " + textStatus + " " + xhr.responseText);
                },
                dataType:"json"
            });


            $.ajax({
                type: "GET",
                url: this.WEBSERVICE_PERSONAL_URL + "?format=json",
                success: function(data){
                    manager.handleGetAllPersonalFeedsResponse(data);
                },
                error: function(xhr, textStatus, errorThrown){
                        alert("Error getting the list of personal feeds: " + textStatus + " " + xhr.responseText);
                },
                dataType:"json"
            });



        };

        this.setWebserviceURL = function(urlvar) {
             this.WEBSERVICE_URL = urlvar;
        }

        this.handleGetAllFeedsResponse = function(data){
            if (data != null){
                this.tmp_feeds_response = data;
            }else{
                this.tmp_feeds_response = this.EMPTY_FEEDS_RESPONSE;
            }
            this.handleGetFeedsResponse();
        };

	    this.handleGetAllPersonalFeedsResponse = function(data){
	        if (data != null){
	            this.tmp_personal_feeds_response = data;
	        }else{
	            this.tmp_personal_feeds_response = this.EMPTY_FEEDS_RESPONSE;
	        }
	        this.handleGetPersonalFeedsResponse();
	    };

        this.handleGetFeedsResponse = function(){
            var manager = this;
            manager.clearContent();
            if (manager.tmp_feeds_response == manager.EMPTY_FEEDS_RESPONSE){
                $("#ceq_siteconnect_table_content").append(manager.template_empty_row);
            }else{//there are some feeds defined already...
                var feeds = manager.tmp_feeds_response.Feeds;
                if (!feeds.applicationName){
                    $.each(feeds, function(i, feed){
                        manager.addFeedRow(feed);
                    });
                }else{//just one result
                    manager.addFeedRow(feeds);
                }
            }

        };

	    this.handleGetPersonalFeedsResponse = function(){
	        var manager = this;
	        manager.clearPersonalContent();
	        if (manager.tmp_personal_feeds_response == manager.EMPTY_FEEDS_RESPONSE){
	            $("#ceq_siteconnect_personal_table_content").append(manager.template_personal_empty_row);
	        }else{//there are some feeds defined already...
	            var feeds = manager.tmp_personal_feeds_response.Feeds;
	            if (!feeds.feedId){
	                $.each(feeds, function(i, feed){
	                    manager.addPersonalFeedRow(feed);
	                });
	            }else{//just one result
	                manager.addPersonalFeedRow(feeds);
	            }
	        }

	    };

        this.updateFeedRow = function(feed){
            this.addFeedRow(feed);
        };

        this.addFeedRow = function(feed){
            var manager = this;
            if ($("#ceq_siteconnect_table_content #ceq_siteconnect_empty_row").length > 0){
                $("#ceq_siteconnect_table_content #ceq_siteconnect_empty_row").remove();
            }

            if ($("[id=ceq_siteconnect_table_row_" + feed.applicationName + "]").length > 0){
                $("[id=ceq_siteconnect_table_row_" + feed.applicationName + "]").empty();
            }else{
                $("#ceq_siteconnect_table_content").append(manager.template_row, feed);
            }
            $("[id=ceq_siteconnect_table_row_" + feed.applicationName + "]").append(manager.template_row_content, feed);

            //assignhandler for the Edit.. button
            $("[id=ceq_siteconnect_button_update_" + feed.applicationName + "]").click(function(){
	            var toEdit = {};
                toEdit.applicationName = feed.applicationName;
	            toEdit.siteNames = feed.userAlias;
                var overlay = new $.UpdateSiteOverlay(manager, toEdit);
                overlay.deploy(manager.CS);
            });
        };

	    this.updatePersonalFeedRow = function(feed){
	        this.addPersonalFeedRow(feed);
	    };

	    this.addPersonalFeedRow = function(feed){
	        var manager = this;
	        if ($("#ceq_siteconnect_personal_table_content #ceq_siteconnect_personal_empty_row").length > 0){
	            $("#ceq_siteconnect_personal_table_content #ceq_siteconnect_personal_empty_row").remove();
	        }

	        if ($("#ceq_siteconnect_personal_table_row_" + feed.feedId).length > 0){
	            $("#ceq_siteconnect_personal_table_row_" + feed.feedId).empty();
	        }else{
	            $("#ceq_siteconnect_personal_table_content").append(manager.template_personal_row, feed);
	        }
	        $("#ceq_siteconnect_personal_table_row_" + feed.feedId).append(manager.template_personal_row_content, feed);

	        //assignhandler for the Delete button
	        $("#ceq_siteconnect_personal_button_delete_" + feed.feedId).click(function(){
		       $.ajax({
                    type: "DELETE",
                    url: manager.WEBSERVICE_FEED_URL + "/" + feed.feedId,
                    success: function(msg){
                        $("#ceq_siteconnect_personal_table_row_" + feed.feedId).remove();
                        if ($("#ceq_siteconnect_personal_table_content tr").length == 0){
                            $("#ceq_siteconnect_personal_table_content").empty().append(manager.template_personal_empty_row);
                        }
                    },
                    error: function(xhr, textStatus, errorThrown){
                        alert("Error deleting personal feed:" + textStatus + " " + xhr.responseText);
                    }
                });
	        });
	    };

	    this.clearContent = function(){
	        $("#ceq_siteconnect_table_content").empty();
	    };
	    this.clearPersonalContent = function(){
	        $("#ceq_siteconnect_personal_table_content").empty();
	    };
    };
})(jQuery);

; (function($){

    $.UpdateSiteOverlay = function(manager, site){
        this.CS = "";
        this.ID = "ceq_siteconnect_overlay_update";
        this.template_overlay_update = $.template(TEMPLATE_SITECONNECT_OVERLAY_UPDATE);

        if (!manager){
            throw "SiteConnect UpdateOverlay Init Error: manager parameter missing";
        }
        this.manager = manager;


        if (!site){
            throw "UpdateOverlay Init Error: site parameter missing";
        }
        this.site = site;

        this.getId = function(){
            return this.ID;
        };

        this.deploy = function(CS){
            var overlay = this;
            if (CS){
                this.CS = CS;
            }else{
                throw 'Container Selector not valid!';
            }

            var params = overlay.site;
            params.overlay_id = overlay.ID;
            $(overlay.CS).append(overlay.template_overlay_update, params);

            $("#" + overlay.ID + " #update_siteconnect_submit").click(function(){
                $("#" + overlay.ID + " #messages").empty();

                var siteNames = $("#" + overlay.ID + " #siteNames").val();
	            var applicationName = $("#" + overlay.ID + " #applicationName").val();

                //validate form values
                if(applicationName == ""){
                    $("#" + overlay.ID + " #messages").append("Application Name Cannot Be Empty!<br/>");
					return;
                }

                //clear messages and show wait
                $("#" + overlay.ID + " #messages").empty().append("Please Wait...<img src=\"" + WIDGET_RESSOURCE_PATH + "/ceq_siteconnect/images/wait.gif\">");
                $("#" + overlay.ID + " button").attr("disabled", true);
                $("#" + overlay.ID + " input").attr("disabled", true);
                $("#" + overlay.ID + " select").attr("disabled", true);

                var newSiteName = {};
	            newSiteName.applicationName = applicationName;
	            newSiteName.siteNames = siteNames;
                $.ajax({
                    type: "PUT",
                    url: overlay.manager.WEBSERVICE_URL,
                    data: newSiteName,
                    success: function(response, textStatus){
                        $("#" + overlay.ID + " #messages").empty().append("Site Names Updated!");
                        overlay.closeOverlay();
                        overlay.manager.updateFeedRow(response);
                    },
                    error: function(xhr, textStatus, errorThrown){
                        $("#" + overlay.ID + " #messages").empty().append("<font color=\"red\">Error Updating Site Names - " + textStatus  + " " + xhr.responseText + "</font><br/>");
                        $("#" + overlay.ID + " button").attr("disabled", false);
                        $("#" + overlay.ID + " input").attr("disabled", false);
                        $("#" + overlay.ID + " select").attr("disabled", false);
                    },
                    dataType:"json"
                });
            });

            $("#" + overlay.ID).overlay({
                top: 100,
                api:true,
                onClose:function(){
                    $("#" + overlay.ID).remove();
                },
                finish: {
                    top: 100,
                    left: 'center',
                    absolute: false
                }
            }).load();

        };

        this.closeOverlay = function(){
            $("#" + this.ID).overlay({
                api:true
            }).close();
        };
    };

})(jQuery);


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
var TEMPLATE_SITECONNECT_TABLE =
'<h3>Connect Your Social Networks</h3>' +
'You can connect to your online social personality by clicking the below icons.  Once connected, '+
'your personal connections will appear in the below <strong>Personal Connections</strong> area.<br><br>' +
'<div id="ceq_siteconnect_personal_icons"/><br>' +
'<h3>Personal Connections</h3>' +
'You have personally connected to the following sites.  Click <b>Delete</b> to disconnect the feed.  Click the icons above to reconnect.<br><br>' +
'<table id="ceq_siteconnect_personal_table">' +
	'<tbody id="ceq_siteconnect_personal_table_content"><tr><td><img src="${WIDGET_RESSOURCE_PATH}/img/wait.gif">Please Wait.</td></tr></tbody>' +
'</table>' +
'<br><h3>Site Feed Names</h3>' +
'The following site-wide feeds are currently active.  If you participate in any of the venues associated with these feeds, '+
'click <strong>Edit...</strong> and specify your identifier for a given venue so that your activities are attributed to you.<br><br>' +
'<table id="ceq_siteconnect_table">' +
	'<tbody id="ceq_siteconnect_table_content"><tr><td><img src="${WIDGET_RESSOURCE_PATH}/img/wait.gif">Please Wait.</td></tr></tbody>' +
'</table>';

var TEMPLATE_SITECONNECT_EMPTY_ROW = '<tr id="ceq_siteconnect_empty_row"><td colspan="3"><em>There are no site-wide feeds defined.</em></td></tr>';

var TEMPLATE_SITECONNECT_PERSONAL_EMPTY_ROW = '<tr id="ceq_siteconnect_personal_empty_row"><td colspan="3"><em>You have not personally connected to any sites.</em></td></tr>';

var TEMPLATE_SITECONNECT_ROW = '<tr id="ceq_siteconnect_table_row_${applicationName}"></tr>';

var TEMPLATE_SITECONNECT_PERSONAL_ROW = '<tr id="ceq_siteconnect_personal_table_row_${feedId}"></tr>';

var TEMPLATE_SITECONNECT_ROW_CONTENT =
'<td align="center"><button id="ceq_siteconnect_button_update_${applicationName}">Edit...</button></td>' +
'<td align="left" id="applicationName_${applicationName}">${applicationName}<input type="hidden" value="${applicationName}"></input></td>' +
'<td align="center" id="siteicon_${applicationName}"><span class="application application${applicationName}"/><input type="hidden" value="${applicationName}"></input></td>' +
'<td align="left" id="userAlias_${applicationName}">${userAlias}<input type="hidden" value="${userAlias}"></input></td>';

var TEMPLATE_SITECONNECT_PERSONAL_ROW_CONTENT =
'<td align="center"><button id="ceq_siteconnect_personal_button_delete_${feedId}">Delete</button></td>' +
'<td align="center" id="siteicon_${feedId}"><span class="application application${applicationName}"/></td>' +
'<td align="left" id="applicationName_${feedId}">${applicationName}</td>';

var TEMPLATE_SITECONNECT_OVERLAY_UPDATE =
'<div id="${overlay_id}" class="overlay">' +
'<span class="application application${applicationName}"/><h3>Edit Site Feed Names for ${applicationName}</h3><br/>' +
'<div id="messages">' +
'</div>' +
'<div id="update_siteconnect_content">' +
'    <table>' +
'        <tr>' +
'            <td><label for="enabled">Site Names:</label></td><td><input type="text" id="siteNames" name="siteNames" size="40" value="${siteNames}"></input>' +
'        </tr>' +
'        <tr><td colspan="2" align="center"><button type="button" id="update_siteconnect_submit">Update</button></td></tr>' +
'    </table>' +
'<input type="hidden" name="applicationName" id="applicationName" value="${applicationName}"></input>' +
'</div>' +
'</div>';

var TEMPLATE_FBCONNECT_WIDGET = '<div id="fbconnect_content"/>';
var TEMPLATE_FBCONNECT_ITEM = 'You are connected to Facebook [<a href="http://www.facebook.com/editapps.php">Disconnect</a>] &nbsp;';

var TEMPLATE_CLIQSETCONNECT_WIDGET =
'<div id="cliqsetconnect_content">' +
'<img id="cliqsetconnect_register" src="http://cliqset-v3.s3.amazonaws.com/img/header-logo.png" width="120" alt="Register your Cliqset feed"/>' +
'</div>'+
'<div class="overlay" style="width:350px;height:150px;" id="cliqsetconnect_overlay">' +
'	<table>' +
'		<tr>' +
'			<td><label for="cliqsetid">Cliqset Username:</label></td>' +
'			<td><input type="text" id="cliqsetid" name="cliqsetid"' +
'			           size="40"/>' +
'		</tr>' +
'		<tr>' +
'			<td>' +
'				<div id="messages">&nbsp;</div>' +
'			</td>' +
'		</tr>' +
'		<tr>' +
'			<td colspan="2" align="center">' +
'				<button type="button" id="add_cliqset_feed">Connect' +
'				</button>' +
'			</td>' +
'		</tr>' +
'	</table>' +
'</div>'+
'</div>';


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 *Require:
 *- jquery.js - 1.2.6 and greater
 *- jquery.template.js
 *- tagcloud_templates.js
 *
 *Usage:   
 *  var tagcloud = new $.TagCloud();
 *  tagcloud.set...;
 *  tagcloud.deploy('tagcloudwidgetarea');
 */

 function StringBuffer() {
   this.buffer = [];
 }

 StringBuffer.prototype.append = function append(string) {
   this.buffer.push(string);
   return this;
 };

 StringBuffer.prototype.toString = function toString() {
   return this.buffer.join("");
 };


;(function( $ ) {
    function _(str, args) {
        return $.i18n('tagcloud', str, args);
    }

  $.TagCloud = function(id){
        //--------CONSTANTS
        this.FILTER_ALL      = "all";
        this.FILTER_WIKI     = "wiki";
        this.FILTER_BLOG     = "blog";
        this.FILTER_FORUM     = "forum";
        this.FILTER_FILES     = "files";
        this.FILTER_PAGES     = "pages";

        this.OPERATOR_AND      = "AND";
        this.OPERATOR_OR    = "OR";

        this.ORDER_ALPHA = "alpha";
        this.ORDER_USAGE = "usage";
        this.ORDER_EQUITY= "equity";

        //--------MEMBER VARS
        this.ID = 1;
        if (id!=null) {
            this.ID = id;
        }
        this.CONTAINER_ID = "tagcloud_" + this.ID;
        this.CS = "#" + this.CONTAINER_ID + " ";
        this.PAGE_NR = 1;
        this.PAGE_SIZE = 20;
        this.PAGE_SIZE_INITIAL = 20; // we need that for the more or less function
        this.FILTER = this.FILTER_ALL;
        this.ORDER = this.ORDER_ALPHA;
        this.TAGS = null;
        this.TAGS_INITIAL = ''; // we need that for the clear function
        this.AUTHOR = null;
        this.ITEM_COUNT = 0;
        this.HIDETAGS = '';
        this.INFOID = -1;
        this.REVERSE = false;
        this.GROUPS = null;
        this.HEIGHT = '320px';
        this.OPERATOR = this.OPERATOR_OR;
        this.SOURCE = null;

        //templates
        this.template_widget = $.template(TEMPLATE_TAGCLOUD_WIDGET);
        this.template_item_div = $.template(TEMPLATE_TAGCLOUD_ITEM_DIV);

        this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+"/jersey/TagCloudP";

        this.CURRENT_USER = false;
        
        this.getRequestUrl = function(){
            var res = this.WEBSERVICE_URL+"?pagenr=" + this.PAGE_NR + "&filter="
                + this.FILTER + "&order=" + this.ORDER;
            res += "&authors=" + this.AUTHOR;
			if(this.PAGE_SIZE >= 0) {
				res += "&count=" + (this.PAGE_SIZE+1);
			}
            if (this.TAGS != null){
                res += "&tags=" + this.TAGS;
            }
            if (this.OPERATOR != null){
                res += "&operator=" + this.OPERATOR;
            }
            if (this.HIDETAGS != null){
                res += "&hidetags=" + this.HIDETAGS;
            }         
            if (this.INFOID != -1) {
                res += "&infoid=" + this.INFOID;
            }
            if (this.REVERSE == true) {
                res += "&reverse=true";
            }
            if (this.GROUPS != null){
                res += "&groups=" + this.GROUPS;
            }
            if (this.SOURCE != null){
                res += "&source=" + this.SOURCE;
            }
            if (this.CURRENT_USER==true) {
                res += "&currentuser=true";
            }
            return res;
        }

//------------------------------------------------------------------------------
//-------------------- SETTERS -------------------------------------------------
//------------------------------------------------------------------------------        

        this.setId = function(id){
            this.ID = id;
            this.CONTAINER_ID = "tagcloud_" + this.ID;
            this.CS = "#" + this.CONTAINER_ID + " ";
        }

         this.setWebserviceURL = function(urlvar) {
            this.WEBSERVICE_URL = urlvar;          
        }

        this.setCurrentUserFilter = function(bool){
            this.CURRENT_USER = bool;
        };
        
        
        this.setHeight = function(height){
            this.HEIGHT = height;
        }       
        
        this.setPageSizeInitial = function(pageSize){
            this.PAGE_SIZE_INITIAL = pageSize;          
        }
        
        this.setPageSize = function(pageSize){  
            this.PAGE_SIZE = pageSize;            
        }
        
        this.setPageNr = function(pageNr){
            this.PAGE_NR = pageNr;
        }
        
        this.setFilter = function(filter){
            this.FILTER = filter;
        };
        
        this.setOrder = function(order){
            this.ORDER = order;
        }

        this.setOperator = function(operator){
            this.OPERATOR = operator;
        }

         this.setTagsInitial = function(tags){
            this.TAGS_INITIAL = +','+tags+',';
        }
        
        this.setTags = function(tags){
            this.TAGS = tags;
            this.TAGS_INITIAL = ','+tags+',';
        }
        
        this.setHidetags = function(hidetags){
            this.HIDETAGS = hidetags;
        }
        
        this.setAuthor = function(author){
            this.AUTHOR = author;
        }

        this.setGroups = function(groups){
            this.GROUPS = groups;
        }
        this.setSource = function(source){
            this.SOURCE = source;
        }
        this.setInfoID = function(info) {
            this.INFOID = info;
        }
        this.setReverse = function(r) {
            this.REVERSE = r;
        }
        
//------------------------------------------------------------------------------
//-------------------- CONTENT -------------------------------------------------
//------------------------------------------------------------------------------
        this.hideContent = function(){
                
        };

        this.showContent = function(){
            
        };

        this.removeContent = function(){
             $(this.CS + ' .ceq_mlink').unbind();
             $(this.CS + " #tagcloud_content"+this.ID).html('');
             $(this.CS + " #tagcloud_footer"+this.ID).html('');
        };
                
//------------------------------------------------------------------------------
//-------------------- WAIT ----------------------------------------------------
//------------------------------------------------------------------------------                
        
        this.showWait = function(){
            $(this.CS +" #tagcloud_content"+this.ID).html("<div id='tagcloud_loading'><img width='12px' height='12px' src='"+WIDGET_RESSOURCE_PATH+"/ceq_tagcloud/images/wait.gif'/>&nbsp;Please wait...</div>");
            $(this.CS +" #tagcloud_footer"+this.ID).html('');
        }

        this.showLoginLink = function(loginurl){
            var link=document.createElement("a") ;
            link.href= loginurl + '?goto='+location.href;
            link.appendChild(document.createTextNode('Please login!'));
            $(this.CS +" #tagcloud_content"+this.ID).html('');
            $(this.CS + " #tagcloud_content"+this.ID).append(link);
            $(this.CS +" #tagcloud_footer"+this.ID).html('');
        }

        this.handleResponse = function(response) {
            //Check for error in response
            if (response.statusCode=='200') {
                this.createItems(response.data);
            } else if (response.statusCode=='403') {
                this.showLoginLink(response.url);
            } else {
                $(this.CS + "#tagcloud_content"+this.ID).append(document.createTextNode("Service not available"));
            }
        }

        this.createItems = function(result) {
            //show items
			//var startmilli = new Date().getTime();
            var tagcloud = this;
            tagcloud.removeContent();
            tagcloud.ITEM_COUNT = result.count;
            if (result.count==0) {
                    $(tagcloud.CS + "#tagcloud_content"+this.ID).append(document.createTextNode("Empty."));
            } else {
                var tagsfilter = ','+tagcloud.TAGS +',';

                var hasSelectedTags = false;
                $.each(result.tags, function(i, item) {
                    if(tagsfilter.indexOf(','+item.key+',')!=-1) {
                        hasSelectedTags = true;
                        // abort once we know that at least one tag was selected
                        return false;
                    } else {
                        // Continue if no tags found yet
                        return true;
                    }
                });

                if(hasSelectedTags) {
                   $(tagcloud.CS + ' #clearbutton'+tagcloud.ID).click(function () {
                        tagcloud.clearTagsSelection();
                   });
                } else {
                    $(tagcloud.CS + ' #clearbutton'+tagcloud.ID).unbind();
                }

				var theWholeHTML = new StringBuffer();
                $.each(result.tags, function(i, item){
                    if (i>(tagcloud.PAGE_SIZE-1)) {
                        return false;
                    }
                    if ((item!=undefined) && (item.key!=undefined)) {
                            var itemObj = {};
                            itemObj.name = item.name;
                            itemObj.key = item.key;
                            itemObj.id = item.id;
                            itemObj.tagclassouter = "";
                            if(tagsfilter.indexOf(','+item.key+',')!=-1) {
                                if (item.kind=='FOLKSONOMY') {
                                    itemObj.tagclassouter = "ceq_selecteduc";
                                } else {
                                    itemObj.tagclassouter = "ceq_selectedc";
                                }
                            }

                            itemObj.tagclass = item.stylesheet;

                            // RJ: I haven't found a way to use my new StringBuffer class with the templates of jQuery
                            //$(tagcloud.CS + "#tagcloud_content").append(tagcloud.template_item_div, itemObj);
                            var theHTML = ' <a href="javascript:void(0)" id="taglink'+itemObj.id+'" class="'+itemObj.tagclass
					+'" key="'+itemObj.key+'"><span class="'+itemObj.tagclassouter+'">'+itemObj.name+'</span></a>';
                            if (tagcloud.TAGS_INITIAL.indexOf(','+item.name+',')==-1) {
                                theWholeHTML.append(theHTML);
                            }
                    }

                });

				$(tagcloud.CS + "#tagcloud_content"+tagcloud.ID).append(theWholeHTML.toString());

				var i = 0, limit = result.tags.length, busy = false;
				var processor = setInterval(function() {
					if(!busy) {
						busy = true;

						var item = result.tags[i];

						$(tagcloud.CS + '#taglink' + item.id).click(function () {
							tagcloud.updateTagcloud(this.attributes['key'].value);
						});

						var gtip_string = 'Usage: '+item.usage+' TQ: '+Math.round(item.tq);
						$(tagcloud.CS + '#taglink' + item.id).qtip({
							content: gtip_string,
							position: {
								corner: {
	                                target: 'bottomLeft',
									tooltip: 'topLeft'
								}
							}
						});
						
						busy = false;
						if(++i == limit) {
							clearInterval(processor);
						}
					}
				}, 5);

                if ((tagcloud.PAGE_SIZE==1000) && (tagcloud.ITEM_COUNT>tagcloud.PAGE_SIZE)) {
                      $(tagcloud.CS + "#tagcloud_content"+tagcloud.ID).append("&nbsp;&nbsp; ... &nbsp;&nbsp;");
                } else if (tagcloud.ITEM_COUNT>tagcloud.PAGE_SIZE) {
                     $(tagcloud.CS + " .ceq_tagcloud_footer").append("<a href='javascript:void(0)' class='ceq_mlink' id='morebutton'>"+_('more')+"<span class='ceq_arrow'>&raquo;</span> </a>");
                     $(tagcloud.CS + ' #morebutton'+tagcloud.ID).click(function () {
                        tagcloud.updateSimpleTagsShowMore();
                    });
                }
                if (tagcloud.PAGE_SIZE==1000) {
                     $(tagcloud.CS + " .ceq_tagcloud_footer").append("<a href='javascript:void(0)' class='ceq_mlink' id='lessbutton'>"+_('less')+"<span class='ceq_arrow'>&laquo;</span> </a>");
                      $(tagcloud.CS + ' #lessbutton'+tagcloud.ID).click(function () {
                        tagcloud.updateSimpleTagsShowLess();
                    });
                }
            }

			//var endmilli = new Date().getTime();
			//alert((endmilli - startmilli) + "ms");
        }
//------------------------------------------------------------------------------
//-------------------- LOAD ITEMS ----------------------------------------------
//------------------------------------------------------------------------------        
        this.loadItems = function(){
            this.loadItemsFromRemote();
        };

        this.loadItemsFromRemote = function(){
            //HTTP Status Code in JSON
            var tagcloud = this;
             $.jsonp({
                type: "GET",
                callbackParameter: "callback",
                callback: "callbackFunction",
                url: this.getRequestUrl(),
                dataType: "json",
                error: function (d, msg) {
                  tagcloud.removeContent();
                  $(tagcloud.CS + "#tagcloud_content"+tagcloud.ID).append(document.createTextNode("Error"));
                },
                success: function(result){
                    tagcloud.handleResponse(result);
                }
             });
        };


        this.setInformation = function(info) {
            this.INFORMATION_ID = info;
        }

        this.updateSimpleTagsShowMore = function() {
            this.showWait();
            this.setPageSize(1000);
            this.loadItems();
        }

        this.updateSimpleTagsShowLess = function () {
            this.showWait();
            this.setPageSize(this.PAGE_SIZE_INITIAL);
            this.loadItems();
        }

        this.updateTagcloud = function (selectedtag) {
            $('.qtip-wrapper').hide();        
            if (this.TAGS!=null) {
                var tagstemp = ','+this.TAGS+',';
                 if (tagstemp.indexOf(','+selectedtag+',')!=-1) {
                   var pos1 = tagstemp.indexOf(','+selectedtag+',');
                   var taglength = selectedtag.length+1;
                    var pos2 = pos1+taglength;
                    this.TAGS = tagstemp.substr(0,pos1);
                    if (tagstemp.length>(pos1+taglength)) {
                         this.TAGS += tagstemp.substr(pos2, tagstemp.length);
                    }

                } else {
                    this.TAGS +=  ','+selectedtag;
                }
            } else {
                    this.TAGS =  selectedtag;
            }

            this.showWait();
            this.loadItems();
            OpenAjax.hub.publish("com.ceq.tagcloud."+this.ID, this.TAGS);
        }

        this.clearTagsSelection = function () {
            this.TAGS = this.TAGS_INITIAL;
            this.showWait();
            this.loadItems();
			if (this.TAGS==null) {
				OpenAjax.hub.publish("com.ceq.tagcloud."+this.ID, '');
			} else {
				OpenAjax.hub.publish("com.ceq.tagcloud."+this.ID, this.TAGS);
			}
        }


//------------------------------------------------------------------------------
//-------------------- DEPLOY --------------------------------------------------
//------------------------------------------------------------------------------
        this.deploy = function(widgetid){
          $('#'+widgetid).html("<div id='" + this.CONTAINER_ID + "' class='ceq_tagcloudwidget' height='" + this.HEIGHT + "'></div>");
          var itemObj = {};
          itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
          itemObj.id = this.ID;
          $(this.CS).append(this.template_widget, itemObj);
          this.showWait();
          this.loadItems();
        }
    };

})(jQuery);


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
var TEMPLATE_TAGCLOUD_WIDGET = '<div id="tagcloud_header${id}" class="ceq_tagcloud_header">\n\
<h3>&nbsp;<!-- selector link -->\n\
<a class="ceq_mlink" href="javascript:void(0)" id="clearbutton${id}">clear selection<span class="ceq_arrow">&nbsp;&raquo;</span>\n\
</a></h3>\n\
</div><div id="tagcloud_content${id}" class="ceq_tagcloud_box">\n\
<div id="loading${id}"><img width="12px" height="12px" src="${WIDGET_RESSOURCE_PATH}/ceq_tagcloud/images/wait.gif"/>&nbsp;Please wait...</div>\n\
</div>\n\
<div id="tagcloud_footer${id}" class="ceq_tagcloud_footer"></div>';

var TEMPLATE_TAGCLOUD_ITEM_DIV = ' <a href="javascript:void(0)" id="taglink${id}" class="${tagclass}" key="${key}">\n\
<span class="${tagclassouter}">${name}</span></a>';

/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 * Requires:
 * - jquery.js - 1.2.6 and greater
 */

;(function( $ ) {

  $.MyCEQTxt = function(objPerson){

    this.objPerson         = objPerson;
    this.urlService        =  WEBSERVICE_RESSOURCE_PATH + "/jersey/math/myCEQP";
    this.REMOTE_WEBSERVICE = true;

    this.enableRemoteWebservice = function() {
        this.REMOTE_WEBSERVICE = true;
    }

    this.disableRemoteWebservice = function() {
        this.REMOTE_WEBSERVICE = false;
    }

    this.setWebserviceURL = function(urlvar) {
        this.urlService = urlvar;
    }
    
    this.deploy = function(sWidget){
        var objThis = this;
        var jWidget = $(sWidget);
        jWidget.addClass('ceq_ceqwidget');
        this.getJSON( this.urlService,
                      this.objPerson,
                      function(objMyCEQ){
                          jWidget.empty();
                          $('<div/>').addClass("ceq_myceq_title")
                                     .append( $('<h3/>').append( $('<span/>').html('My Community Equity') )
                                                        .append( $('<span/>').addClass("ceq_myceq_help")
                                                                             .append( $('<img/>').attr('border',0)
                                                                                                 .attr('src',WIDGET_RESSOURCE_PATH + '/ceq_topceq/ceq_mycommunityequity/img/ceq_help.png') ) ) )
                                     .appendTo( jWidget );
                          var jCQChart = $('<img/>').attr('border',0)
                                                    .attr('src',WIDGET_RESSOURCE_PATH + '/ceq_topceq/ceq_mycommunityequity/img/ceq_chart_bar.png')
                                                    .qtip({ content: 'future implementation...',
                                                               show: 'mouseover',
                                                               hide: 'mouseout'
                                                          });
/*
                          var jCQActivity = $('<img/>').attr('border',0)
                                                       .attr('rel',"#win_overlay")
                                                       .attr('src',WIDGET_RESSOURCE_PATH + '/ceq_topceq/ceq_mycommunityequity/img/ceq_rating_cq.png')
                                                       .hover( function(){
                                                                   jCQActivity.attr('src',WIDGET_RESSOURCE_PATH + '/ceq_topceq/ceq_mycommunityequity/img/ceq_rating_cqinvert.png');
                                                               },
                                                               function(){
                                                                   jCQActivity.attr('src',WIDGET_RESSOURCE_PATH + '/ceq_topceq/ceq_mycommunityequity/img/ceq_rating_cq.png');
                                                               })
                                                       .click(function(){
                                                           var objLog = new $.ActivityLog('pq');
                                                           objLog.setUserID( objMyCEQ.personId );
                                                           objLog.deploy('overlay_activitylog');
                                                       });
*/
                          $('<div/>').addClass("ceq_myceq_box")
                                     .append( $('<div/>').addClass("ceq_myceq_firstrow")
                                                         .append( $('<span/>').html('Contribution Equity: ') )
                                                         .append( $('<span/>').addClass("ceq_myceq_cqvalue")
                                                                              .html( ""+Math.round(objMyCEQ.CQ) ))
                                                         .append( $('<span/>').addClass('ceq_myceq_cqstat')
                                                                              .append( jCQChart ) )
                                                         .append( $('<span/>').addClass('ceq_myceq_cqinfo')
                                                                              /*.append( jCQActivity ) */) )
                                     .append( $('<div/>').addClass("ceq_myceq_secondrow")
                                                         .html( 'Novice User: ' + Math.max( Math.round(objMyCEQ.CQmin), 0 ) +
                                                                ' &middot; Average User: &middot; ' + Math.round(objMyCEQ.CQavg) +
                                                                ' Power User: ' + Math.round(objMyCEQ.CQmax) ))
                                     .append( $('<div/>').addClass("ceq_myceq_thirdrow")
                                                         .append( $('<span/>').html('Ranking: ') )
                                                         .append( $('<span/>').addClass("ceq_myceq_cqranking")
                                                                              .html( objMyCEQ.CQrank ))
                                                         .append( $('<span/>').html(' ') )
                                                         .append( $('<span/>').addClass("ceq_myceq_details")
                                                                              .html( 'of ' + objMyCEQ.count + ' active User' ) ))
                                     .append( $('<div/>').addClass('ceq_myceq_divider') )
                                     .appendTo( jWidget );
                          var jPQChart = $('<img/>').attr('border',0)
                                                    .attr('src',WIDGET_RESSOURCE_PATH + '/ceq_topceq/ceq_mycommunityequity/img/ceq_chart_bar.png')
                                                    .qtip({ content: 'future implementation...',
                                                               show: 'mouseover',
                                                               hide: 'mouseout'
                                                          });
/*
                          var jPQActivity = $('<img/>').attr('border',0)
                                                       .attr('rel',"#win_overlay")
                                                       .attr('src',WIDGET_RESSOURCE_PATH + '/ceq_topceq/ceq_mycommunityequity/img/ceq_rating_cq.png')
                                                       .hover( function(){
                                                                   jPQActivity.attr('src',WIDGET_RESSOURCE_PATH + '/ceq_topceq/ceq_mycommunityequity/img/ceq_rating_cqinvert.png');
                                                               },
                                                               function(){
                                                                   jPQActivity.attr('src',WIDGET_RESSOURCE_PATH + '/ceq_topceq/ceq_mycommunityequity/img/ceq_rating_cq.png');
                                                               })
                                                       .click(function(){
                                                           var objLog = new $.ActivityLog('pq');
                                                           objLog.setUserID( objMyCEQ.personId );
                                                           objLog.deploy('overlay_activitylog');
                                                       });
*/
                          $('<div/>').addClass("ceq_myceq_box")
                                     .append( $('<div/>').addClass("ceq_myceq_firstrow")
                                                         .append( $('<span/>').html('Participation Equity: ') )
                                                         .append( $('<span/>').addClass("ceq_myceq_pqvalue")
                                                                              .html( ""+Math.round(objMyCEQ.PQ) ))
                                                         .append( $('<span/>').addClass('ceq_myceq_cqstat')
                                                                              .append( jPQChart ) )
                                                         .append( $('<span/>').addClass('ceq_myceq_cqinfo')
/*                                                                              .append( jPQActivity )*/ ) )
                                     .append( $('<div/>').addClass("ceq_myceq_secondrow")
                                                         .html( 'Novice User: ' + Math.max( Math.round(objMyCEQ.PQmin), 0 ) +
                                                                ' &middot; Average User: &middot; ' + Math.round(objMyCEQ.PQavg) +
                                                                ' Power User: ' + Math.round(objMyCEQ.PQmax) ))
                                     .append( $('<div/>').addClass("ceq_myceq_thirdrow")
                                                         .append( $('<span/>').html('Ranking: ') )
                                                         .append( $('<span/>').addClass("ceq_myceq_pqranking")
                                                                              .html( objMyCEQ.PQrank ))
                                                         .append( $('<span/>').html(' ') )
                                                         .append( $('<span/>').addClass("ceq_myceq_details")
                                                                              .html( 'of ' + objMyCEQ.count + ' active User' ) ) )
                                     .appendTo( jWidget );
                          $('<div/>').addClass('overlay')
                                     .attr( 'id','win_overlay')
                                     .css('left','20px')
                                     .css('width','545px')
                                     .css('height','290px')
                                     .append( $('<div/>').attr( 'id','overlay_activitylog')
                                                         .css('width', '500px') )
                                     .appendTo( jWidget );
//                          jPQActivity.overlay();
//                          jCQActivity.overlay();
                      },
                      function(sMessage){
                          jWidget.html( sMessage );
                      });
    }                      
    
    this.getJSON = function( sURL,
                             objParameters,
                             fSuccess,
                             fError ){
            var objThis = this;
            if (this.REMOTE_WEBSERVICE) {
                $.jsonp({
                    type: "GET",
       callbackParameter: "callback",
                callback: "callbackFunction",
                     url: sURL,
                    data: objParameters,
                dataType: "json",
                   error: function (d, msg) {
                              fError("Service not available");
                          },
                 success: function( jsonResult ){
                              objThis.handleResponse( jsonResult, fSuccess, fError );
                          }
             });
            }else{
                $.ajax({
                    type: "GET",
                     url: sURL,
                    data: objParameters,
                dataType: "json",
                   error: function (xhr, textStatus, errorThrown) {
                              if( xhr.status=='403' ){
                                  objThis.showLoginLink(xhr.getResponseHeader('X-CeqLoginUrl'),fError);
                              }else{
                                  fError("Service not available");
                              }
                          },
                 success: function( jsonResult ){
                              objThis.handleResponse( jsonResult, fSuccess, fError );
                          }
             });
            }
        }
        
        this.handleResponse = function( jsonResult, fSuccess, fError ){
            if( jsonResult.statusCode=='200') {
                fSuccess( jsonResult.data );
            } else if( jsonResult.statusCode=='403') {
                this.showLoginLink( jsonResult.url, fError );
            } else {
                fError( "Service not available" );
            }
        }
        
        this.showLoginLink = function( sLoginURL, fError ){
            fError( 'Access denied' );
        }
}})(jQuery);
/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 * Requires:
 * - jquery.js - 1.2.6 and greater
 */

;(function( $ ) {

    function _(str, args) { 
        return $.i18n('ceq', str, args); 
    }
    
    $.TopCommunities = function(id){
        this.ID = 1;
        if (id!=null) {
            this.ID = id;
        }
        this.CONTAINER_ID = "topcommunities_" + this.ID;
        this.CS = "#" + this.CONTAINER_ID + " ";

        this.HEIGHT = '320px';

        //this.TAGS = '';

        //templates
        this.template_widget = $.template(TEMPLATE_TOPCOMMUNITIES_WIDGET);
        this.template_item_div = $.template(TEMPLATE_TOPCOMMUNITIES_ITEM_DIV);

        this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH + '/jersey/math/statisticsP';
        this.COUNT           = 10;

        this.getRequestUrl = function(){
            var res = this.WEBSERVICE_URL+"?report=topcommunity&count="+this.COUNT;
            return res;
        }


        this.setWebserviceURL = function(urlvar) {
            this.WEBSERVICE_URL = urlvar;
        }

		/*
        this.setTags = function(tags){
            this.TAGS = tags;
        }
		*/

        this.setHeight = function(height){
            this.HEIGHT = height;
        }

        
        this.deploy = function(widgetid){
          $('#'+widgetid).html("<div id='" + this.CONTAINER_ID + "' class='ceq_ceqwidget' height='" + this.HEIGHT + "'></div>");
          var itemObj = {};
          itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
          itemObj.id = this.ID;
          $(this.CS).append(this.template_widget, itemObj);
          this.showWait();
          this.loadItems();
        }

        this.showWait = function(){
            $(this.CS+ " #topcommunities_content"+this.ID).html("<div id='topcommunities_loading'><img width='12px' height='12px' src='"+WIDGET_RESSOURCE_PATH+"/ceq_tagcloud/images/wait.gif'/>&nbsp;Please wait...</div>");
        }

         this.loadItems = function(){
            this.loadItemsFromRemote();
            
        };

        this.loadItemsFromRemote = function(){
            //HTTP Status Code in JSON
            var objThis = this;
            $.jsonp({
                            type: "GET",
               callbackParameter: "callback",
                        callback: "callbackFunction",
                             url: this.getRequestUrl(),
                        dataType: "json",
                           error: function (d, msg) {
                                      $(objThis.CS+ " #topcommunities_content"+objThis.ID).html("Service not available");
                                  },
                         success: function( jsonResult ){
                                      objThis.handleResponse( jsonResult );
                                  }
                     });
        };


        this.handleResponse = function( jsonResult){
            if( jsonResult.statusCode=='200') {
                this.createItems(jsonResult.data);
            } else if( jsonResult.statusCode=='403') {
                this.showLoginLink( jsonResult.url );
            } else {
                $(this.CS+ " #topcommunities_content"+this.ID).html( "Error "+jsonResult.message+" (HTTP Status Code: "+jsonResult.statusCode+")" );
            }
        }

        this.createItems = function(objTopInfo) {
            //show items
           var objThis = this;
           objThis.removeContent();
           if( objTopInfo.communities != undefined ){
               var ranking = 1;
               for( var i in objTopInfo.communities ){
                   var itemObj = {};
                   itemObj.ranking = ranking;
                   itemObj.title = objTopInfo.communities[i].name;
                   $(objThis.CS + "#topcommunities_content"+this.ID).append(objThis.template_item_div, itemObj);
                   ranking++;
               }
           }
       }

        this.removeContent = function(){
             $(this.CS + " #topcommunities_content"+this.ID).html('');
             $(this.CS + " #topcommunities_footer"+this.ID).html('');
        };


        this.showLoginLink = function( sLoginURL){
            $(this.CS+ " #topcommunities_content"+this.ID).html('Please <a href="'+sLoginURL+'?goto='+location.href+'">login</a>!' );
        }

         this.setCount = function(count){
            this.COUNT = count;
        };

   }
})(jQuery);

/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
var TEMPLATE_TOPCOMMUNITIES_WIDGET = 
'<div id="topcommunities_content${id}"> \n\
<div id="loading${id}"><img width="12px" height="12px" src="${WIDGET_RESSOURCE_PATH}/ceq_tagcloud/images/wait.gif"/>&nbsp;Please wait...</div>\n\
</div>\n\
<div id="topcommunities_footer${id}"></div>';

var TEMPLATE_TOPCOMMUNITIES_ITEM_DIV = '<div class="ceq_ceq_item"> \n\
<span class="ceq_ceq_ranking">${ranking}</span>\n\
<span class="ceq_ceq_content">${title}</span></<div>';

/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 * Requires:
 * - jquery.js - 1.2.6 and greater
 */

;(function( $ ) {

    function _(str, args) { 
        return $.i18n('ceq', str, args); 
    }
    
    $.TopCountries = function(id){
        this.ID = 1;
        if (id!=null) {
            this.ID = id;
        }
        this.CONTAINER_ID = "topcountries_" + this.ID;
        this.CS = "#" + this.CONTAINER_ID + " ";

        this.HEIGHT = '320px';

        this.TAGS = '';

        //templates
        this.template_widget = $.template(TEMPLATE_TOPCOUNTRIES_WIDGET);
        this.template_item_div = $.template(TEMPLATE_TOPCOUNTRIES_ITEM_DIV);

        this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH + '/jersey/math/statisticsP';
        this.COUNT           = 10;

        this.getRequestUrl = function(){
            var res = this.WEBSERVICE_URL+"?report=topcountry&count="+this.COUNT;
            res += "&tagKey=" + this.TAGS;
            return res;
        }


        this.setWebserviceURL = function(urlvar) {
            this.WEBSERVICE_URL = urlvar;
        }

        this.setTags = function(tags){
            this.TAGS = tags;
        }

        this.setHeight = function(height){
            this.HEIGHT = height;
        }

        
        this.deploy = function(widgetid){
          $('#'+widgetid).html("<div id='" + this.CONTAINER_ID + "' class='ceq_ceqwidget' height='" + this.HEIGHT + "'></div>");
          var itemObj = {};
          itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
          itemObj.id = this.ID;
          $(this.CS).append(this.template_widget, itemObj);

          this.showWait();
          this.loadItems();
        }

        this.showWait = function(){
            $(this.CS+ " #topcountries_content"+this.ID).html("<div id='topcountries_loading'><img width='12px' height='12px' src='"+WIDGET_RESSOURCE_PATH+"/ceq_tagcloud/images/wait.gif'/>&nbsp;Please wait...</div>");
        }

         this.loadItems = function(){
            this.loadItemsFromRemote();         
        };

        this.loadItemsFromRemote = function(){
            //HTTP Status Code in JSON
            var objThis = this;
            $.jsonp({
                            type: "GET",
               callbackParameter: "callback",
                        callback: "callbackFunction",
                             url: this.getRequestUrl(),
                        dataType: "json",
                           error: function (d, msg) {
                                      $(objThis.CS+ " #topcountries_content"+objThis.ID).html("Service not available");
                                  },
                         success: function( jsonResult ){
                                      objThis.handleResponse( jsonResult );
                                  }
                     });
        };
        
        this.handleResponse = function( jsonResult){
            if( jsonResult.statusCode=='200') {
                this.createItems(jsonResult.data);
            } else if( jsonResult.statusCode=='403') {
                this.showLoginLink( jsonResult.url );
            } else {
                $(this.CS+ " #topcountries_content"+this.ID).html( "Error "+jsonResult.message+" (HTTP Status Code: "+jsonResult.statusCode+")" );
            }
        }

        this.createItems = function(objTopInfo) {
            //show items
           var objThis = this;
           objThis.removeContent();
           if( objTopInfo.countries != undefined ){
               var ranking = 1;
               for( var i in objTopInfo.countries ){
                   var itemObj = {};
                   itemObj.ranking = ranking;
                   itemObj.title = objTopInfo.countries[i].name;
				   if(objTopInfo.countries[i].flag != undefined && objTopInfo.countries[i].flag.length > 0) {
					itemObj.imgtag =
						   '<img border="0" class="ceq_topcountry_flagimg" src="'
						   + WIDGET_RESSOURCE_PATH + "/img/flags/" + objTopInfo.countries[i].flag
						   + '"/>';
					} else {
						itemObj.imgtag = "";
					}
                   $(objThis.CS + "#topcountries_content"+objThis.ID).append(objThis.template_item_div, itemObj);
                   ranking++;
               }
           }
       }

        this.removeContent = function(){
             $(this.CS + " #topcountries_content"+this.ID).html('');
             $(this.CS + " #topcountries_footer"+this.ID).html('');
        };


        this.showLoginLink = function( sLoginURL){
            $(this.CS+ " #topcountries_content"+this.ID).html('Please <a href="'+sLoginURL+'?goto='+location.href+'">login</a>!' );
        }

         this.subscribeToTagCloud = function(tagcloudid){
            var objThis= this;
            OpenAjax.hub.subscribe("com.ceq.tagcloud." + tagcloudid, function(name, tags){
                if (tags.indexOf(',')!=-1) {
                    var lasttag = tags.substring((tags.lastIndexOf(',')+1), tags.length);
                    objThis.setTags(lasttag);
                } else {
                    if (tags == null) {
                        objThis.setTags('');
                    } else {
                        objThis.setTags(tags);
                    }
                }
                objThis.showWait();
                objThis.loadItems();
            });
        };

        this.setCount = function(count){
            this.COUNT = count;
        };
   }
})(jQuery);

/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
var TEMPLATE_TOPCOUNTRIES_WIDGET =
'<div id="topcountries_content${id}" class="ceq_ceqwidget">\n\
<div id="loading${id}"><img width="12px" height="12px" src="${WIDGET_RESSOURCE_PATH}/ceq_tagcloud/images/wait.gif"/>&nbsp;Please wait...</div>\n\
</div>\n\
<div id="topcountries_footer${id}"></div>';

var TEMPLATE_TOPCOUNTRIES_ITEM_DIV = '<div class="ceq_ceq_item"> \n\
<span class="ceq_ceq_ranking">${ranking}</span>\n\
<span class="ceq_topcountry_flag"> \n\
${imgtag} \n\
</span> \n\
<span class="ceq_topcountry_content">${title}</span></<div>';
/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 * Requires:
 * - jquery.js - 1.2.6 and greater
 */

;(function( $ ) {

    function _(str, args) { 
        return $.i18n('ceq', str, args); 
    }
    
    $.TopInformation = function(id){
        this.ID = 1;
        if (id!=null) {
            this.ID = id;
        }
        this.CONTAINER_ID = "topinformation_" + this.ID;
        this.CS = "#" + this.CONTAINER_ID + " ";

        this.HEIGHT = '320px';

        this.TAGS = '';

        //templates
        this.template_widget = $.template(TEMPLATE_TOPINFORMATION_WIDGET);
        this.template_item_div = $.template(TEMPLATE_TOPINFORMATION_ITEM_DIV);

        this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH + '/jersey/math/statisticsP';
        this.COUNT           = 10;

        this.getRequestUrl = function(){
            var res = this.WEBSERVICE_URL+"?report=topinfo&count="+this.COUNT;
            res += "&tagKey=" + this.TAGS;
            return res;
        }

        this.setWebserviceURL = function(urlvar) {
            this.WEBSERVICE_URL = urlvar;
        }

        this.setTags = function(tags){
            this.TAGS = tags;
        }

        this.setHeight = function(height){
            this.HEIGHT = height;
        }

        
        this.deploy = function(widgetid){
          $('#'+widgetid).html("<div id='" + this.CONTAINER_ID + "' class='ceq_ceqwidget' height='" + this.HEIGHT + "'></div>");
          var itemObj = {};
          itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
          itemObj.id = this.ID;
          $(this.CS).append(this.template_widget, itemObj);
          this.showWait();
          this.loadItems();
        }

        this.showWait = function(){
            $(this.CS+ " #topinformation_content"+this.ID).html("<div id='topinformation_loading'><img width='12px' height='12px' src='"+WIDGET_RESSOURCE_PATH+"/ceq_tagcloud/images/wait.gif'/>&nbsp;Please wait...</div>");
        }

         this.loadItems = function(){
            this.loadItemsFromRemote();
        };

        this.loadItemsFromRemote = function(){
            //HTTP Status Code in JSON
            var objThis = this;
            $.jsonp({
                            type: "GET",
               callbackParameter: "callback",
                        callback: "callbackFunction",
                             url: this.getRequestUrl(),
                        dataType: "json",
                           error: function (d, msg) {
                                      $(objThis.CS+ " #topinformation_content"+objThis.ID).html("Service not available");
                                  },
                         success: function( jsonResult ){
                                      objThis.handleResponse( jsonResult );
                                  }
                     });
        };
        
        this.handleResponse = function( jsonResult){
            if( jsonResult.statusCode=='200') {
                this.createItems(jsonResult.data);
            } else if( jsonResult.statusCode=='403') {
                this.showLoginLink( jsonResult.url );
            } else {
                $(this.CS+ " #topinformation_content"+this.ID).html( "Error "+jsonResult.message+" (HTTP Status Code: "+jsonResult.statusCode+")" );
            }
        }

        this.createItems = function(objTopInfo) {
            //show items
           var objThis = this;
           objThis.removeContent();
           if( objTopInfo.informations != undefined ){
               var ranking = 1;
               for( var i in objTopInfo.informations ){
                   var itemObj = {};
                   itemObj.ranking = ranking;
                   itemObj.title = objTopInfo.informations[i].title;
                   itemObj.url = objTopInfo.informations[i].url;
                   $(objThis.CS + "#topinformation_content"+objThis.ID).append(objThis.template_item_div, itemObj);
                   ranking++;
               }
           }
       }

        this.removeContent = function(){
             $(this.CS + " #topinformation_content"+this.ID).html('');
             $(this.CS + " #topinformation_footer"+this.ID).html('');
        };


        this.showLoginLink = function( sLoginURL){
            $(this.CS+ " #topinformation_content"+this.ID).html('Please <a href="'+sLoginURL+'?goto='+location.href+'">login</a>!' );
        }

         this.subscribeToTagCloud = function(tagcloudid){
            var objThis= this;
            OpenAjax.hub.subscribe("com.ceq.tagcloud." + tagcloudid, function(name, tags){
                if (tags.indexOf(',')!=-1) {
                    var lasttag = tags.substring((tags.lastIndexOf(',')+1), tags.length);
                    objThis.setTags(lasttag);
                } else {
                    if (tags == null) {
                        objThis.setTags('');
                    } else {
                        objThis.setTags(tags);
                    }
                }
                objThis.showWait();
                objThis.loadItems();
            });
        };

         this.setCount = function(count){
            this.COUNT = count;
        };
   }
})(jQuery);

/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
var TEMPLATE_TOPINFORMATION_WIDGET =
'<div id="topinformation_content${id}">\n\
<div id="loading${id}"><img width="12px" height="12px" src="${WIDGET_RESSOURCE_PATH}/ceq_tagcloud/images/wait.gif"/>&nbsp;Please wait...</div>\n\
</div>\n\
<div id="topinformation_footer${id}"></div>';

var TEMPLATE_TOPINFORMATION_ITEM_DIV = '<div class="ceq_ceq_item"> \n\
<span class="ceq_ceq_ranking">${ranking}</span>\n\
<span class="ceq_ceq_content"><a class="item_link" href="${url}" title="${title}">${title}</a></span></<div>';

/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 * Requires:
 * - jquery.js - 1.2.6 and greater
 */

;(function( $ ) {

    function _(str, args) {
        return $.i18n('ceq', str, args);
    }

    $.TopPeople = function(id){
        this.ID = 1;
        if (id!=null) {
            this.ID = id;
        }
        this.ORDER_CQ      = "cq";
        this.ORDER_PQ      = "pq";
        this.ORDER_TOTAL     = "total";

        this.CONTAINER_ID = "toppeople_" + this.ID;
        this.CS = "#" + this.CONTAINER_ID + " ";

        this.HEIGHT = '320px';
        this.SHOW_PHOTO = false;
        this.TAGS = '';
        this.ORDER = this.ORDER_CQ;

        //templates
        this.template_widget = $.template(TEMPLATE_TOPPEOPLE_WIDGET);
        this.template_item_div = $.template(TEMPLATE_TOPPEOPLE_ITEM_DIV);
        this.template_item_photo_div = $.template(TEMPLATE_TOPPEOPLE_ITEM_PHOTO_DIV);

        this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH + '/jersey/math/statisticsP';

        this.COUNT           = 10;
        this.nItemMaxSize          = 10000;

        this.getRequestUrl = function(){
            var res = this.WEBSERVICE_URL+"?report=topcontrib&count="+this.COUNT;
            res += "&tagKey=" + this.TAGS+ "&order=" + this.ORDER;
            return res;
        }

         this.setId = function(id){
            this.ID = id;
            this.CONTAINER_ID = "toppeople_" + this.ID;
            this.CS = "#" + this.CONTAINER_ID + " ";
        }

        this.setWebserviceURL = function(urlvar) {
            this.WEBSERVICE_URL = urlvar;
        }

        this.setTags = function(tags){
            this.TAGS = tags;
        }

        this.setHeight = function(height){
            this.HEIGHT = height;
        }


        this.deploy = function(widgetid){
          $('#'+widgetid).html("<div id='" + this.CONTAINER_ID + "' class='ceq_ceqwidget' height='" + this.HEIGHT + "'></div>");
          var itemObj = {};
          itemObj.id = this.ID;
          itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;

          $(this.CS).append(this.template_widget, itemObj);
          this.showWait();
          this.loadItems();
        }

        this.showWait = function(){
            $(this.CS+ " #toppeople_content"+this.ID).html("<div id='toppeople_loading'><img width='12px' height='12px' src='"+WIDGET_RESSOURCE_PATH+"/ceq_tagcloud/images/wait.gif'/>&nbsp;Please wait...</div>");
        }

         this.loadItems = function(){
            this.loadItemsFromRemote();
        };

        this.loadItemsFromRemote = function(){
            //HTTP Status Code in JSON
            var objThis = this;
            $.jsonp({
                            type: "GET",
               callbackParameter: "callback",
                        callback: "callbackFunction",
                             url: this.getRequestUrl(),
                        dataType: "json",
                           error: function (d, msg) {
                                      $(objThis.CS+ " #toppeople_content"+objThis.ID).html("Service not available");
                                  },
                         success: function( jsonResult ){
                                      objThis.handleResponse( jsonResult );
                                  }
                     });
        };

        this.handleResponse = function( jsonResult){
            if( jsonResult.statusCode=='200') {
                this.createItems(jsonResult.data);
            } else if( jsonResult.statusCode=='403') {
                this.showLoginLink( jsonResult.url );
            } else {
                $(this.CS+ " #toppeople_content"+this.ID).html( "Error "+jsonResult.message+" (HTTP Status Code: "+jsonResult.statusCode+")" );
            }
        }

        this.createItems = function(objTopPerson) {
            //show items
           var objThis = this;
           objThis.removeContent();
           if( objTopPerson.persons != undefined ){
               var ranking = 1;
               for( var i in objTopPerson.persons ){
                   var itemObj = {};
                   itemObj.ranking = ranking;
                   itemObj.title = "";
                   if (objTopPerson.persons[i].givenname != undefined) {
                       itemObj.title = objTopPerson.persons[i].givenname + " ";
                   }
                   if (objTopPerson.persons[i].surname != undefined) {
                       itemObj.title = itemObj.title + objTopPerson.persons[i].surname;
                   }
                   if(objTopPerson.persons[i].pictureurl != undefined) {
                        itemObj.pictureurl = objTopPerson.persons[i].pictureurl;
                   } else {
                        itemObj.pictureurl = WIDGET_RESSOURCE_PATH+'/img/ceq_defaultavatar.png';
                   }
                   if( ( objTopPerson.persons[i].homepage != undefined ) && ( objTopPerson.persons[i].homepage != "" ) ) {
                        // TBD: should be moved to the template
                        itemObj.title = '<a class="item_link" href="' + objTopPerson.persons[i].homepage + '" title="' + itemObj.title + '">' + itemObj.title + '</a>';
                   }
                   if (objTopPerson.persons[i].authenticated != undefined) {
                        itemObj.title = '<b>' + itemObj.title + '</b>';
                        if (objTopPerson.persons[i].rank != undefined) {
                            itemObj.ranking = '<b>' + objTopPerson.persons[i].rank+ '</b>';
                        }
                   }
                   if (this.SHOW_PHOTO) {
                        $(objThis.CS + "#toppeople_content"+objThis.ID).append(objThis.template_item_photo_div, itemObj);
                   } else {
                        $(objThis.CS + "#toppeople_content"+objThis.ID).append(objThis.template_item_div, itemObj);
                   }
                   ranking++;
               }
           }
       }

        this.removeContent = function(){
             $(this.CS + " #toppeople_content"+this.ID).html('');
             $(this.CS + " #toppeople_footer"+this.ID).html('');
        };

        this.showPhoto = function(){
            this.SHOW_PHOTO = true;
        };

        this.hidePhoto = function(){
            this.SHOW_PHOTO = false;
        };

        this.showLoginLink = function( sLoginURL){
            $(this.CS+ " #toppeople_content"+this.ID).html('Please <a href="'+sLoginURL+'?goto='+location.href+'">login</a>!' );
        }

         this.subscribeToTagCloud = function(tagcloudid){
            var objThis= this;
            OpenAjax.hub.subscribe("com.ceq.tagcloud." + tagcloudid, function(name, tags){
                if (tags.indexOf(',')!=-1) {
                    var lasttag = tags.substring((tags.lastIndexOf(',')+1), tags.length);
                    objThis.setTags(lasttag);
                } else {
                    if (tags == null) {
                        objThis.setTags('');
                    } else {
                        objThis.setTags(tags);
                    }
                }
                objThis.showWait();
                objThis.loadItems();
            });
        };

        this.setCount = function(count){
            this.COUNT = count;
        };

        this.setOrder = function(order){
            this.ORDER = order;
        };
   }
})(jQuery);


/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
var TEMPLATE_TOPPEOPLE_WIDGET =
'<div id="toppeople_content${id}">\n\
<div id="loading${id}"><img width="12px" height="12px" src="${WIDGET_RESSOURCE_PATH}/ceq_tagcloud/images/wait.gif"/>&nbsp;Please wait...</div>\n\
</div>\n\
<div id="toppeople_footer${id}"></div>';

var TEMPLATE_TOPPEOPLE_ITEM_DIV = '<div class="ceq_ceq_item"> \n\
<span class="ceq_ceq_ranking">${ranking}</span>\n\
<span class="ceq_ceq_content">${title}</span></<div>';

var TEMPLATE_TOPPEOPLE_ITEM_PHOTO_DIV = '<div class="ceq_toppeople_item"> \n\
<span class="ceq_ceq_ranking">${ranking}</span>\n\
<span class="ceq_toppeople_photo"><img border="0" class="ceq_toppeople_img" src="${pictureurl}"></span>\n\
<span class="ceq_toppeople_content">${title}</span></<div>';
/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2009 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 * Requires:
 * - jquery.js - 1.2.6 and greater
 */

;(function( $ ) {

    $.MyCEQ = function(objPerson){
      this.objPerson = objPerson;

      this.REMOTE_WEBSERVICE = false;

      this.nX = 0;
      this.nY = 0;

      this.sViewType      = "all";
      this.sCQText        = "Contribution Equity";
      this.sPQText        = "Participation Equity";
      this.nEquityPosition= 5;
      this.nEquityHeight  = 56;
      this.cEquity        = "black";
      this.fsEquity       = 12;
      this.cMyRanking     = "black";
      this.cMyRankingNum  = "#ff9933";
      this.nMyRankingX    = 14;
      this.nMyRankingY    = 18;
      this.fsMyRanking    = 12;
      this.cScale         = "#4d7896";
      this.nScalePositionX = 30;
      this.nScalePositionY = 32;
      this.nScaleWidth    = 207;
      this.nScaleHeight   = 12;
      this.cAvg           = "#C6D3E0";
      this.nAvgHeight     = 7;
      this.urlCommunity   = WIDGET_RESSOURCE_PATH+"/myCEQ/img/ceq_community.gif";
      this.urlMe          = WIDGET_RESSOURCE_PATH+"/myCEQ/img/ceq_me.gif";
      this.nMeWidth       = 15;
      this.fsPerCent      = 9;
      this.nPerCentSymbolWidth = 5;
      this.bBottomText    = "on";
      this.nBottomTextPos = 20;
      this.cBottomText    = "black";
      this.fsBottomText   = 12;
      this.nBottomCommX   = 60;
      this.nBottomUserX   = 140;
      this.sAvgText       = "Community Average";
      this.sUserText      = "User";
      this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH + '/jersey/math/myCEQ';
      this.sWhatIs        = "What's this?";
      this.urlWhatIs      = "";
      this.nWhatIsX       = 116;
      this.nWhatIsY       = 1;
      this.fsWhatIs       = 11;
      this.cWhatIs        = "black";

    this.enableRemoteWebservice = function() {
        this.REMOTE_WEBSERVICE = true;
    }

    this.disableRemoteWebservice = function() {
        this.REMOTE_WEBSERVICE = false;
    }

    this.setWebserviceURL = function(urlvar) {
        this.WEBSERVICE_URL = urlvar;
    }

    this.getPosition = function( nValue, nScale, nMin, nMax ){
        if( nMax > nMin )
            return ( nValue - nMin ) * nScale / ( nMax - nMin );
        else
            return 0;
    };

    this.drawEquity = function( nY, sName, nPersonal, nRank, nAvg, nMax, nMin, nCount ){

        var nAvgPos  = this.getPosition( nAvg, this.nScaleWidth - 2, nMin, nMax );
        var sAvgStr  = Math.floor(this.getPosition( nAvg, 100, nMin, nMax )) + "%";

        var sHtml =  this.drawString( this.nX + this.nEquityPosition, nY, sName, this.fsEquity, this.cEquity ) +
           this.fillRect( this.nX + this.nScalePositionX, nY + this.nScalePositionY-this.nScaleHeight,
                          1 , this.nScaleHeight, this.cScale ) +
           this.fillRect( this.nX + this.nScalePositionX, nY + this.nScalePositionY,
                          this.nScaleWidth, 1, this.cScale ) +
           this.fillRect( this.nX + this.nScaleWidth + this.nScalePositionX - 1,
                          nY + this.nScalePositionY-this.nScaleHeight,
                          1 , this.nScaleHeight, this.cScale ) +
           this.fillRect( this.nX + this.nScalePositionX + 1,
                          nY + this.nScalePositionY - this.nAvgHeight,
                          nAvgPos , this.nAvgHeight, this.cAvg ) +
           this.drawImage( this.nX + this.nScalePositionX + 3,
                           nY + this.nScalePositionY - this.nAvgHeight + 1, this.urlCommunity ) +
           this.drawString( this.nX + this.nScalePositionX + 1 + nAvgPos - sAvgStr.length * this.nPerCentSymbolWidth,
                            nY + this.nScalePositionY - this.nAvgHeight - this.fsPerCent - 2,
                            sAvgStr, this.fsPerCent, this.cScale ) +
           this.drawString( this.nX + this.nScalePositionX + this.nScaleWidth - this.nPerCentSymbolWidth * 2,
                            nY + this.nScalePositionY - this.nScaleHeight - this.fsPerCent - 2,
                            "100%", this.fsPerCent, this.cScale ) +
           this.drawString( this.nX + this.nWhatIsX, nY + this.nWhatIsY,
                            "<a href='" + this.urlWhatIs + "'>" + this.sWhatIs + "</a>",
                            this.fsWhatIs, this.cWhatIs );

        var sMyRankingStr = "";
        if( nPersonal != undefined ){
            var nPersPos = this.getPosition( nPersonal, this.nScaleWidth - 2, nMin, nMax );
            var sPersStr = Math.floor(this.getPosition( nPersonal, 100, nMin, nMax )) + "%";

            sHtml += this.drawImage( this.nX + this.nScalePositionX + 1 + nPersPos - this.nMeWidth/2 ,
                            nY + this.nScalePositionY - 6, this.urlMe ) +
                     this.drawString( this.nX + this.nScalePositionX + 1 + nPersPos - sPersStr.length * this.nPerCentSymbolWidth /2,
                            nY + this.nScalePositionY + 13, sPersStr, this.fsPerCent, this.cScale );
            sMyRankingStr = ( this.cMyRankingText + "<b>" + nRank + "/" + nCount ) + "<\/b>";
            sMyRankingStr = "<b><font color='"+ this.cMyRankingNum +"'>" + nRank + "</font></b> [Me] of ";
        }

        sMyRankingStr += "<b><font color='" + this.cMyRankingNum + "'>" + nCount + "</font></b> [Community]";

        sHtml += this.drawString( this.nX + this.nScalePositionX + this.nScaleWidth + this.nMyRankingX,
                                  nY + this.nMyRankingY,
                                  sMyRankingStr,
                                  this.fsMyRanking, this.cMyRanking );
        return sHtml;
    };

    this.drawBottom = function( nY ){
        return this.drawImage( this.nX + this.nBottomCommX, nY, this.urlCommunity ) +
               this.drawString( this.nX + this.nBottomCommX + this.nBottomTextPos,
                                nY, this.sAvgText, this.fsBottomText, this.cBottomText ) +
               this.drawImage( this.nX + this.nBottomCommX + this.nBottomUserX,
                                nY, this.urlMe ) +
               this.drawString( this.nX + this.nBottomCommX + this.nBottomTextPos + this.nBottomUserX,
                                nY, this.sUserText,
                                this.fsBottomText, this.cBottomText );
    };

    this.drawImage = function( nX, nY, sURL ){
        return '<div style="position:absolute;left:' + nX + 'px;'+
	           'top:' + nY + 'px;"><img src="'+ sURL + '"><\/div>';
    };

    this.fillRect = function( nX, nY, nW, nH, sColor ){
        return '<div style="position:absolute;left:' + nX + 'px;top:' + nY + 'px;' +
                       'width:' + nW + 'px;height:' + nH + 'px;background-color:' + sColor + '" ><\/div>';
    };

    this.drawString = function( nX, nY, sText, nSize, sColor ){
        return '<div style="position:absolute;white-space:nowrap;left:' + nX + 'px;'+
	        'top:' + nY + 'px;font-size:' + nSize + ';color:' + sColor + '">'+ sText + '<\/div>';
    };
    this.getAbsoluteOffset = function( domElement ){
        var offset = new Object();
        offset.top = 0;
        offset.left = 0;
        while( domElement != null ){
            offset.top += domElement.offsetTop;
            offset.left += domElement.offsetLeft;
            domElement = domElement.offsetParent;
        }
        return offset;
    }

    this.deploy = function(sWidget){
        var objThis = this;
        var offsetsWidget = /*$(sWidget).offset()*/ this.getAbsoluteOffset( $(sWidget)[0] );
        this.nX = offsetsWidget.left;
        this.nY = offsetsWidget.top;
        this.getJSON( this.WEBSERVICE_URL,
                   this.objPerson,
                   function(objMyCEQ){
                       var sHtml = "";
                       var nCurPositionY = objThis.nY + objThis.nEquityPosition;

                       if( ( objThis.sViewType == "cq" ) ||
                           ( objThis.sViewType == "all") ){
                               sHtml = objThis.drawEquity( nCurPositionY,
                                                           objThis.sCQText,
                                                           objMyCEQ.CQ,
                                                           objMyCEQ.CQrank,
                                                           objMyCEQ.CQavg,
                                                           objMyCEQ.CQmax,
                                                           Math.min( objMyCEQ.CQmin, 0 ),
                                                           objMyCEQ.count );
                               nCurPositionY += objThis.nEquityHeight;
                       }

                       if( ( objThis.sViewType == "pq" ) ||
                           ( objThis.sViewType == "all" ) ){
                               sHtml += objThis.drawEquity( nCurPositionY,
                                                            objThis.sCQText,
                                                            objMyCEQ.PQ,
                                                            objMyCEQ.PQrank,
                                                            objMyCEQ.PQavg,
                                                            objMyCEQ.PQmax,
                                                            0,
                                                            objMyCEQ.count );
                               nCurPositionY += objThis.nEquityHeight;
                       }

                       if( objThis.bBottomText == "on" )
                           sHtml += objThis.drawBottom( nCurPositionY );
                       $(sWidget).html( sHtml );

                   },
                   function( sMessage ){
                       $(sWidget).html( sMessage );
                   });
    };
            this.getJSON = function( sURL,
                                 objParameters,
                                 fSuccess,
                                 fError ){
            var objThis = this;
            if (this.REMOTE_WEBSERVICE) {
                $.jsonp({
                    type: "GET",
       callbackParameter: "callback",
                callback: "callbackFunction",
                     url: sURL,
                    data: objParameters,
                dataType: "json",
                   error: function (d, msg) {
                              fError("Error");
                          },
                 success: function( jsonResult ){
                              objThis.handleResponse( jsonResult, fSuccess, fError );
                          }
             });
            }else{
                $.ajax({
                    type: "GET",
                     url: sURL,
                    data: objParameters,
                dataType: "json",
                   error: function (xhr, textStatus, errorThrown) {
                              if( xhr.status=='403' ){
                                  objThis.showLoginLink(xhr.getResponseHeader('X-CeqLoginUrl'),fError);
                              }else{
                                  fError("Error (HTTP Status Code: "+xhr.status+")");
                              }
                          },
                 success: function( jsonResult ){
                              objThis.handleResponse( jsonResult, fSuccess, fError );
                          }
             });
            }
        }
        
        this.handleResponse = function( jsonResult, fSuccess, fError ){
            if( jsonResult.statusCode=='200') {
                fSuccess( jsonResult.data );
            } else if( jsonResult.statusCode=='403') {
                this.showLoginLink( jsonResult.url, fError );
            } else {
                fError( "Error "+jsonResult.message+" (HTTP Status Code: "+jsonResult.statusCode+")" );
            }
        }
        
        this.showLoginLink = function( sLoginURL, fError ){
            fError( 'Please <a href="'+sLoginURL+'?goto='+location.href+'">login</a>!' );
        }
}})(jQuery);