
/*  common/js/user_activity3.js  */
if (!window.UserActivityStream) {
function empty (mixed_var) {
    var key;
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||
        mixed_var === false ||
        typeof mixed_var === 'undefined'
    ){
        return true;
    }
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
    return false;
}

function UserActivityStream(type, load_id, cid, uid, blurbs, limit, lang, width, rtl, upid, show_region, options) {
    var self = this;
    self.options = $.extend({
        animation: false,
        show_country: true
    }, options);
    self.version = 3;
    self.load_id = load_id;
    self.$load_id = $('#' + load_id);
    self.type = type;//ua or fua
    self.key = Math.floor(Math.random() * 9999999);
    self.cid = cid;
    self.uid = uid;
    self.blurbs = blurbs;
    self.limit = limit;
    self.lang = lang;
    self.width = width;
    self.load_type = 'ajax'; // can be 'ajax' = same server and 'script' = debug from other server
	self.load_limit = self.limit * 3;
    self.overload_time = 5000;
    self.additional_time = 5;
    self.ajax_timeout;
    self.shownext_timeout;
    self.use_translate = false;
    self.one_user_time = 0;
    self.QUEUE = [];
    self.data = [];
    self.static_height = false;
    self.loaded_limit = 0;
    self.updater_time_id;
    self.loaded = {};
    self.rtl = rtl;
    self.upid = typeof(upid) == 'number' ? upid : 0;
    self.loggin = false;
    self.entries_cnt = 0;
    self.show_region = show_region || false;
    self.animation = self.options['animation'];

    self.load = function () {
        self.loadActivity();
        self.timeUpdater();
    }
    self.timeUpdater = function() {
        var updatetime = false;
        if(self.updater_time_id) {
            clearTimeout(self.updater_time_id);
            updatetime = true;
        }
        if(0 < self.QUEUE.length &&  true === updatetime) {
            self.updateOldEntry(1);
            self.updateOldEntryHTML();
        }
        self.updater_time_id = setTimeout(self.timeUpdater, 1200);
    }
    /**
    *   Function for remove data from array and update array length;
    *
    **/
    self.remove = function (list, index) {
        for (var i=index+1; i<list.length; ++i)
            list[i-1] = list[i];
        list.length--;
    }
    self.log = function (what, name) {
        if (!self.loggin) {
            return;
        }
        if (name) {
            console.log(' -- ' + name + ' -- ');
        }
        console.log(what);
    }
    /**
    *    function for load new data that came from ajax request
    */
    self.load_data = function() {
        var first_load = false;
        var newEntry;
        if (empty(self.QUEUE)) {
            self.loadDataConteiner();
            self.loadActivityHTML(self.data, true);
            self.showNext();
        } else {
            var newEntry = self.getNewEntry(self.data);
            self.entries_cnt = newEntry.length;
            self.QUEUE = self.setQUEUE(newEntry, self.QUEUE);
            self.loadActivityHTML(newEntry, false);
        }
    }
    /**
    *   Update html for one entry with new time
    *
    **/
    self.updateOneOldEntryHTML = function(user) {
        $('#prettytime_u_'+self.key+'_u_'+user.id, self.$load_id).html(self.prettyDate(user.last_date));
    }
    /**
    *   Update html for entries with new time
    *
    **/
    self.updateOldEntryHTML = function() {
        for(var h in self.QUEUE) {
            self.updateOneOldEntryHTML(self.QUEUE[h]);
        }
    }
    /**
    *   Show list with slideshow effect
    **/
    self.showNext= function() {
        if(self.shownext_timeout) {
            clearTimeout(self.shownext_timeout);
        }
        if (self.loaded_limit >= self.limit && false === self.static_height){
            if (3 < $('#ua_container', self.$load_id).height()) {
                self.static_height = true;
                //$('#ua_container', self.$load_id).css({height:($('#ua_container', self.$load_id).height() + 3) + 'px', overflow:'hidden'});
                $('#ua_container', self.$load_id).height(0);
                $('#ua_container', self.$load_id).css({overflow:'hidden'});
                $('#petition-scroller', self.$load_id).children().each(function(){
                    if ($(this).is(':visible')) {
                        $('#ua_container', self.$load_id).height($('#ua_container', self.$load_id).height() + $(this).height());
                    }
                });
            }

        }
        if(self.QUEUE.length > self.limit) {
            var last = self.QUEUE.length - 1;
            var first = self.QUEUE.length - self.limit -1;
            var lastid = self.QUEUE[last].id;
            var lastidminus1 = self.QUEUE[last - 1].id;
            $('#activity_user_id_'+self.QUEUE[first+1].id, self.$load_id).removeClass('first');
            $('#activity_user_id_'+self.QUEUE[first].id, self.$load_id).addClass('first');
            self.QUEUE[first].last_date = 0;
            self.updateOneOldEntryHTML(self.QUEUE[first]);
            var callback = function () {
                $('#activity_user_id_' + lastid, self.$load_id).remove();
                self.remove(self.QUEUE, last);
                self.shownext_timeout = setTimeout(self.showNext, 1500);
            }
            if ('right' == self.animation) {
                $('#activity_user_id_'+self.QUEUE[first].id, self.$load_id).fadeTo(1000, 1, callback);
            } else {
                $('#activity_user_id_'+self.QUEUE[first].id, self.$load_id).slideDown(1000, callback);
            }

			} else {
            self.shownext_timeout = setTimeout(self.showNext, 1500);
        }

    }
    /**
    *   Update time for old entries
    *
    *   time in seconds
    *
    **/
    self.updateOldEntry = function(time) {
        for(h in self.QUEUE) {
                self.QUEUE[h].last_date = (1 * self.QUEUE[h].last_date) + (1 * (time?time:self.additional_time));
        }
    }
    /**
    *   Get new entry that not loaded
    **/
    self.getNewEntry = function(entries) {
        var newentries = [];
        for(h in entries) {
            var entry = entries[h];
            if (!self.loaded[entry.id])
                newentries.push(entry);
        }
        return newentries;
    }
    /**
    *   Update queue with new entries
    **/
    self.setQUEUE = function (newdata, data) {
        var mdata = [];
        for(var h in newdata) {
            mdata.push(newdata[h]);
        }
        for(var h in data) {
            mdata.push(data[h]);
        }
        return mdata;
    }
    /**
    *   Create html for entries on campaign page
    *
    **/
    self.getActivityHTML = function (data, first_load) {
        var html ='';
        if (true === first_load) {
            for (var h = data.length; h > self.limit; h--) {
                var index = h -1;
                self.loaded[data[index].id] = true;
                self.remove(data, index);
            }
        }
        for(var h in data) {
            //if (self.loaded_limit >= self.limit && true === first_load) break;
            var user = data[h];
            if (self.loaded[user.id]) {
                continue;
            }
            if (true === first_load) {
                self.QUEUE[h] = data[h];
            }
            self.loaded[user.id] = true;
            self.loaded_limit++;
            if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(user.name)) {
                continue;
            }
            html += '<li id="activity_user_id_'+user.id+'"  style="'+(self.loaded_limit > self.limit?'display:none;':'')+'"  class="' + ((1 == (h + 1) && true === first_load)?' first':'')+ '">';
            if ('' == self.rtl) {
                html += '    <div class="time-ago" id="prettytime_u_'+self.key+'_u_'+user.id+'">' +self.prettyDate(user.last_date)+'</div>';
                //html += '    <div class="flag"><img src="/new/images/blue/flags/fr.png" width="29" height="35" alt="fr" style="background-image: url(/images/flags/' + (user.cc+'').toLowerCase() +'.gif); background-position:7px 7px;background-repeat: no-repeat;"/></div>';
                html += '    <div class="flag">';
                html += '       <div class="flag-place">';
                html += '           <span class="flag-' + (user.cc+'').toLowerCase() +' user_activity_flag23x14"><img src="/images/spacer.gif" /></span><span class="ua-flag-overground"><img src="/images/spacer.gif" /></span>';
                html += '       </div>';
                html += '    </div>';
                html += '    <div class="info">';
                html += '        <p class="person"><big>' + (user.name?user.name:'Laila') + '</big>' + (self.options['show_country'] ? ', ' + (user.country?user.country:'Afghanistan') : '') + (!empty(self.show_region) && !empty(user.st)?', ' + user.st:'') + '</p>';
                html += '    </div>';
            } else {
                html += '    <div class="info">';
                html += '        <p class="person"><big>' + (user.name?user.name:'Laila') + '</big>' + (self.options['show_country'] ? ', ' + (user.country?user.country:'Afghanistan') : '') + (!empty(self.show_region) && !empty(user.st)?', ' + user.st:'') + '</p>';
                html += '    </div>';
                //html += '    <div class="flag"><img src="/new/images/blue/flags/fr.png" width="29" height="35" alt="fr" style="background-image: url(/images/flags/' + (user.cc+'').toLowerCase() +'.gif); background-position:7px 7px;background-repeat: no-repeat;"/></div>';
                html += '    <div class="flag">';
                html += '       <div class="flag-place">';
                html += '           <span class="flag-' + (user.cc+'').toLowerCase() +' user_activity_flag23x14"><img src="/images/spacer.gif" /></span><span class="ua-flag-overground"><img src="/images/spacer.gif" /></span>';
                html += '       </div>';
                html += '    </div>';
                html += '    <div class="time-ago" id="prettytime_u_'+self.key+'_u_'+user.id+'">' +self.prettyDate(user.last_date)+'</div>';
            }

            html += '<div style="clear: both;"></div></li>';
            //html += '<li style="'+(self.loaded_limit > self.limit?'display:none;':'')+'" class="Comment ' + ((self.limit == (h + 1) && true === first_load)?' Last':'')+ '" id="activity_user_id_'+user.id+'" ><table celpadding="0" cellspacing="0" width="100%"><tr><td><img src="/images/spacer.gif" style="width:16px; height:11px;background-image: url(/images/flags/all-images.png); background-repeat: no-repeat;" class="'+ 'sprite-' + (user.cc+'').toLowerCase() +'"/>&nbsp;&nbsp;' + (user.name?user.name:'Laila') + ',&nbsp;<span style="font-size:11px; color:#6D6E70;">' + (user.country?user.country:'Afghanistan') + '</span></td><td><div style="text-align:right;"><em style="font-size:11px;" id="prettytime_u_'+self.key+'_u_'+user.id+'">' +self.prettyDate(user.last_date)+'</em></div></td></tr><tr><td colspan="2"><a style="padding-left:24px;" href="/'+(user.lang?user.lang:'en')+'/'+user.cn+'/?fpla">'+(empty(user.ct)?user.cn.toLowerCase():user.ct.toLowerCase())+'</a></td></tr></table></li>';

        }
        return html;
    }
    /**
    *   Create html for entries on front page
    *
    **/
     self.getActivityFUAHTML = function (data, first_load) {
        var html ='';
        if (true === first_load) {
            for (var h = data.length; h > self.limit; h--) {
                var index = h -1;
                self.loaded[data[index].id] = true;
                self.remove(data, index);
            }
        }
        for(h in data) {
            var user = data[h];
            if (self.loaded[user.id]) {
                continue;
            }
            if (true === first_load) {
                self.QUEUE[h] = data[h];
            }
            self.loaded[user.id] = true;
            self.loaded_limit++;
            if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(user.name)) {
                continue;
            }
            html += '<li id="activity_user_id_'+user.id+'"  style="'+(self.loaded_limit > self.limit?'display:none;':'')+'"  class="' + ((1 == (h + 1) && true === first_load)?' first':'')+ '">';
            if ('' == self.rtl) {
                html += '    <div class="time-ago" id="prettytime_u_'+self.key+'_u_'+user.id+'">' +self.prettyDate(user.last_date)+'</div>';
                //html += '    <div class="flag"><img src="/new/images/blue/ua_flag_bg.png" width="27" height="31" alt="fr" style="background-image: url(/images/flags/' + (user.cc+'').toLowerCase() +'.gif); background-position:7px 7px;background-repeat: no-repeat;"/></div>';
                html += '    <div class="flag">';
                html += '       <div class="flag-place">';
                html += '           <span class="flag-' + (user.cc+'').toLowerCase() +' user_activity_flag23x14"><img src="/images/spacer.gif" /></span><span class="ua-flag-overground"><img src="/images/spacer.gif" /></span>';
                html += '       </div>';
                html += '    </div>';
                html += '    <div class="info">';
                html += '        <p class="person"><big>' + (user.name?user.name:'Laila') + '</big>, ' + (user.country?user.country:'Afghanistan') + '</p>';
                html += '        <p class="action"><a href="/'+(user.lang?user.lang:'en')+'/'+user.cn+'/?fpla">'+(empty(user.ct)?user.cn.toLowerCase():user.ct.toLowerCase())+'</a></p>';
                html += '    </div>';
            } else {
                html += '    <div class="info">';
                html += '        <p class="person"><big>' + (user.name?user.name:'Laila') + '</big>, ' + (user.country?user.country:'Afghanistan') + '</p>';
                html += '        <p class="action"><a href="/'+(user.lang?user.lang:'en')+'/'+user.cn+'/?fpla">'+(empty(user.ct)?user.cn.toLowerCase():user.ct.toLowerCase())+'</a></p>';
                html += '    </div>';
                //html += '    <div class="flag"><img src="/new/images/blue/flags/fr.png" width="29" height="35" alt="fr" style="background-image: url(/images/flags/' + (user.cc+'').toLowerCase() +'.gif); background-position:7px 7px;background-repeat: no-repeat;"/></div>';
                html += '    <div class="flag">';
                html += '       <div class="flag-place">';
                html += '           <span class="flag-' + (user.cc+'').toLowerCase() +' user_activity_flag23x14"><img src="/images/spacer.gif" /></span><span class="ua-flag-overground"><img src="/images/spacer.gif" /></span>';
                html += '       </div>';
                html += '    </div>';
                html += '    <div class="time-ago" id="prettytime_u_'+self.key+'_u_'+user.id+'">' +self.prettyDate(user.last_date)+'</div>';

            }

            html += '<div style="clear: both;"></div></li>';
            //html += '<li style="'+(self.loaded_limit > self.limit?'display:none;':'')+'" class="Comment ' + ((self.limit == (h + 1) && true === first_load)?' Last':'')+ '" id="activity_user_id_'+user.id+'" ><table celpadding="0" cellspacing="0" width="100%"><tr><td><img src="/images/spacer.gif" style="width:16px; height:11px;background-image: url(/images/flags/all-images.png); background-repeat: no-repeat;" class="'+ 'sprite-' + (user.cc+'').toLowerCase() +'"/>&nbsp;&nbsp;' + (user.name?user.name:'Laila') + ',&nbsp;<span style="font-size:11px; color:#6D6E70;">' + (user.country?user.country:'Afghanistan') + '</span></td><td><div style="text-align:right;"><em style="font-size:11px;" id="prettytime_u_'+self.key+'_u_'+user.id+'">' +self.prettyDate(user.last_date)+'</em></div></td></tr><tr><td colspan="2"><a style="padding-left:24px;" href="/'+(user.lang?user.lang:'en')+'/'+user.cn+'/?fpla">'+(empty(user.ct)?user.cn.toLowerCase():user.ct.toLowerCase())+'</a></td></tr></table></li>';

        }
        return html;
    }

    /**
    *    Add new entries on the page
    *
    **/

    self.loadActivityHTML = function(data, first_load) {
        var html = '';
        if ('fua' === self.type) {
            html = self.getActivityFUAHTML(data, first_load);
        } else {
            html = self.getActivityHTML(data, first_load);
        }
        if (!empty(html)) {
            $('#ua_scroll_block', self.$load_id).after(html);
        }
    }
    self.loadDataConteiner = function () {
        $('#block-happening-live', self.$load_id).html(self.getDataConteinerHTML());
        $('.title-ribbon, .photo-ribbon', '#block-happening-live', self.$load_id).wrap('<div class="rtlwrap">');
    }
    self.getDataConteinerHTML = function () {
        var html = '';
            html += '<div class="block-inner">';
            html += '   <div class="title-ribbon"><h2 class="title" '+self.rtl+'>'+('ua' === self.type?self.blurbs.RecentPetitionSigners:self.blurbs.HappeningRightNow)+'</h2></div>';
            html += '   <div class="content">';
            html += '       <div class="content-top"></div>';
            html += '       <div class="content-mid" id="ua_container" '+self.rtl+'>';
            html += '           <ul id="petition-scroller">';
            html += '               <li id="ua_scroll_block" style="display:none;"></li>';
            html += '           </ul>';
            html += '       </div>';
            html += '       <div class="content-btm"></div>';
            html += '   </div>';
            html += '</div>';
        return html;
    }
    self.sort_by_date = function (a, b) {
        if (a.last_date == b.last_date){
            return 0;
        }
        return (a.last_date < b.last_date)?-1:1;
    }
    self.ajaxLoad = function () {
        if(self.ajax_timeout) {
            clearTimeout(self.ajax_timeout);
        }
        if (self.QUEUE.length > self.limit) {
            self.ajax_timeout = setTimeout(self.ajaxLoad, self.overload_time);
            return;
        }
        
        $.ajax({
            url:'/act/get_user_activity.php',
            dataType: 'json',
            type: 'GET',
            data: {cid: self.cid, lang: self.lang, uid: self.uid, /*time: self.one_user_time,*/ type: self.type, upid: self.upid},
            success:function(data) {
            self.one_user_time = self.one_user_time + self.additional_time;
            if(data)
                if (data.disabled) {
                    self.showDisableActivity();
                } else {
                    data.sort(self.sort_by_date);
                    self.data = data;
                    self.load_data();
                    self.ajax_timeout = setTimeout(self.ajaxLoad, self.overload_time);
                }
        }});
    }
    self.scriptLoad = function () {
        if(self.ajax_timeout) {
            clearTimeout(self.ajax_timeout);
        }
        if ((self.QUEUE.length) > self.limit) {
            self.ajax_timeout = setTimeout(self.scriptLoad, 1500);
            return;
        }
        $.ajax({
            url:'https://secure.avaaz.org/act/get_user_activity.php',
            dataType: 'jsonp',
            jsonpCallback: 'UserActivityCallback.dataLoader',
            type: 'GET',
            data:{cid: self.cid, lang: self.lang, uid: self.uid, /*time: self.one_user_time,*/ type: self.type}});
    }
    self.dataLoader = function (data) {
            self.one_user_time = self.one_user_time + self.additional_time;
            if (data.disabled) {
                self.showDisableActivity();
            } else {
                data.sort(self.sort_by_date);
                self.data = data;
                self.load_data();
                self.ajax_timeout = setTimeout(self.scriptLoad, (self.entries_cnt > self.limit)?1500:self.overload_time);
            }
            $('script','head').filter(function(){
                if (/act\/get_user_activity.php/.test(this.src)){
                    return true;
                }
                return false;
            }).each(function(){$(this).remove();});
    }
    self.loadActivity = function () {
        switch (self.load_type) {
            case 'ajax':
                self.ajaxLoad();
                break;
            case 'script':
                self.scriptLoad();
                break;
        }
    }
    /**
    * INSERT ELEMT INTO HEADER
    */
    self.insert = function (element) {
        (document.getElementsByTagName('HEAD')[0] || document.body).appendChild(element);
    }

    self.addConteiner = function() {
        if ('' !== self.load_id) {
            self.$load_id.html(self.getConteinerHTML());
        } else {
            document.write(self.getConteinerHTML());
        }

    }

    self.getConteinerHTML = function() {
        var html = '';
        html += '<div id="block-happening-live" class="block row-1 row-first block-blue block-ribbontitle block-scroller"><table width="100%"><tr><td align="center" valign="middle"><img src="/images/ajax-loader.gif"/></td></tr></table></div>';

        return html;
    }
    self.prettyDate = function (time){
    	var date = new Date((time.toString() || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
    		//diff = (((_self.calcTime('0')).getTime() - date.getTime()) / 1000),
            diff = parseInt(time),
    		day_diff = Math.floor(diff / 86400);
    	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
    		return self.blurbs.PrettyTimeMonthAgo;

    	return day_diff == 0 && (
    			diff < 5 && self.blurbs.PrettyTimeJustNow.replace("{time}", '<big>' + diff + '</big>') ||
                diff < 60 && self.blurbs.PrettyTimeSecondsAgo.replace("{time}", '<big>' + diff + '</big>') ||
    			diff < 120 && self.blurbs.PrettyTimeMinuteAgo.replace("{time}", '<big>' + diff + '</big>') ||
    			diff < 3600 && self.blurbs.PrettyTimeMinutesAgo.replace("{time}", '<big>' + Math.floor( diff / 60 )+ '</big>') ||
    			diff < 7200 && self.blurbs.PrettyTimeHourAgo ||
    			diff < 86400 && self.blurbs.PrettyTimeHoursAgo.replace("{time}", '<big>' + Math.floor( diff / 3600 )+ '</big>')) ||
        		day_diff == 1 && self.blurbs.PrettyTimeYesterday ||
        		day_diff < 7 && self.blurbs.PrettyTimeDaysAgo.replace("{time}", '<big>' + day_diff+ '</big>') ||
        		day_diff < 31 && self.blurbs.PrettyTimeWeeksAgo.replace("{time}", '<big>' + Math.ceil( day_diff / 7 )+ '</big>');
    }
    /**************CONSTRUCTOR ACTION***************/
    self.addConteiner();
    window['UserActivityCallback'] = self;
    $(document).ready(function(){self.load();});
    /*********END OF CONSTRUCTOR ACTION*************/
}



}

/*  common/js/MCounter.js  */
var counterdata;
function MCounter(options) {
    this['mcounter_' + options.cid] = {};
    var counter = this['mcounter_' + options.cid];
    counter.setCurrency = function () {
        $('.progress-currency' + counter.mckey + ', .progress-currency-no-key').each(function () {
            $(this).html(counter.currency_value);
        });
    };
    counter.setTarget = function () {
        var target = counter.number_format(counter.target, 0, '.', options.thousand_separator),
            h = '',
            k = '';
        $('.progress-target' + counter.mckey).each(function () {
            if (counter.is_target) {
                $(this).html(target);
            } else {
                $(this).html('');
            }
        });
        counter.text = counter.text.replace('{target}', target);
        if (counter.is_target) {
            if ('' !== counter.currency_value) {
                h = ' ';
            } else {
                k = ' ';
            }
            $('.progress-target-additional' + counter.mckey).html(k + counter.number_format(counter.target, 0, '.', options.thousand_separator));
            $('.progress-currency-target' + counter.mckey).html(h + counter.currency_value);
        }
    };
    counter.setText = function () {
        if (counter.in_array(counter.counter_type, ['countries_donate', 'donates'])) {
            counter.setAdditionalCurrency();
        }
        $('.progress-text' + counter.mckey).html(' ' + counter.text);

    };
    counter.setAdditionalCurrency = function () {
        if ('euro_dollar' === counter.currency) {
            $('.progress-additional-currency' + counter.mckey).html('($' + counter.number_format(counterdata.USD) + ')');
        } else if ('dollar_euro' === counter.currency) {
            $('.progress-additional-currency' + counter.mckey).html('(&euro;' + counter.number_format(counterdata.EUR) + ')');
        }
    };
    counter.setCountryCount = function () {
        if ('countries' === counter.counter_type) {
            $('.progress-country' + counter.mckey).html(' ' + counterdata.countries_cnt + ' ' + counter.country_text);
        } else if ('countries_donate' === counter.counter_type) {
            $('.progress-country' + counter.mckey).html(' ' + counterdata.donate_countries_cnt + ' ' + counter.country_text);
        }
    };
    counter.setData = function (num) {
        var togo = counter.target - num;
        if (counter.default_max > counter.target) {
            togo = counter.default_max - num;
        }
        $('.progress-data' + counter.mckey).each(function () {
            $(this).html(counter.number_format(num, 0, '.', options.thousand_separator));
        });

        $('.progress-data-nearby' + counter.mckey).each(function () {
            $(this).html(counter.number_format(counter.max_nearby, 0, '.', options.thousand_separator));
        });

        $('.progress-data-togo' + counter.mckey + ', .progress-data-togo-no-key').each(function () {
            if (0 > togo) {
                togo = 0;
            }
            $(this).html(counter.number_format(togo, 0, '.', options.thousand_separator)).change();
        });
        $('.progress-data-goal' + counter.mckey + ', .progress-data-goal-no-key').each(function () {
            $(this).html(counter.number_format(counter.target, 0, '.', options.thousand_separator)).change();
        });
    };
    counter.showCounter = function () {
        var px,
            iw;
        counter.setData(counter.num);
        if (counter.max > counter.default_max) {
            counter.default_max = parseInt(counter.max, 10);
            counter.proc = counter.progress_bar_width / counter.max;
        }
        px = parseInt(counter.proc * counter.num, 10);
        iw = $('.progress-inline' + counter.mckey).width();
        if (0 !== iw && (iw + 10) > px) {
            px = iw + 10;
        }
        $('.progress-move' + counter.mckey).width(px + 'px');
    };

    counter.showNearbyCounter = function () {
        var px,
            iw;
        counter.setData(counter.num);
        if (counter.nearby_max > counter.default_max) {
            counter.default_max = parseInt(counter.nearby_max, 10);
            counter.proc = counter.progress_bar_width / counter.nearby_max;
        }
        px = parseInt(counter.proc * counter.nearby_max, 10);
        iw = $('.progress-inline' + counter.mckey).width();
        if (0 !== iw && (iw + 10) > px) {
            px = iw + 10;
        }
        $('.progress-move' + counter.mckey).width(px + 'px');
    };

    counter.getSumm = function (nnm, nnm2) {
        var rand, timeout;
        if (nnm2 < 1) {
            rand = nnm + nnm2;
        } else if (nnm2 < 10) {
            rand = nnm + 1;
            timeout = 100;
        } else if (nnm2 < 100) {
            rand = nnm + Math.floor((Math.random() * 9) + 1);
            timeout = 0;
        } else if (nnm2 < 1000) {
            rand = nnm + Math.floor((Math.random() * 91) + 10);
            timeout = 50;
        } else if (nnm2 < 10000) {
            rand = nnm + Math.floor((Math.random() * 901) + 100);
            timeout = 50;
        } else if (nnm2 < 100000) {
            rand = nnm + Math.floor((Math.random() * 2001) + 1000);
            timeout = 50;
        } else if (nnm2 < 1000000) {
            rand = nnm + Math.floor((Math.random() * 20001) + 5000);
            timeout = 50;
        } else if (nnm2 >= 1000000) {
            rand = nnm + Math.floor((Math.random() * nnm2 / 100) + nnm2 / 100);
            timeout = 50;
        } else {
            rand = nnm + counter.plus;
        }
        counter.timeout = timeout;
        return rand;
    };

    counter.startCounter = function () {
        var rand, num2;

        if (counter.franchise_cid && undefined != counter.franchise_cid){
            counter.showNearbyCounter();
        } else {
            counter.showCounter();
        }

        if (counter.timerId) {
            clearTimeout(counter.timerId);
        }
        if (counter.num < counter.max) {
            rand = counter.getSumm(counter.num, counter.max);
            if (rand > counter.max) {
                num2 = counter.max - counter.num;
                counter.num = counter.getSumm(counter.num, num2);
            } else {
                counter.num = rand;
            }
            counter.timerId = setTimeout(counter.startCounter, counter.timeout);
        } else if (true === counter.ajax_data) {
            counter.ajaxCounter();
        }

    };
    counter.addCommas = function (nStr) {
        var rgx, x, x1, x2;
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    };
    counter.ajaxCounter = function () {
        if (counter.ajax_counter_timer) {
            clearTimeout(counter.ajax_counter_timer);
        }
        $.ajax({
            url: '/act/ajax_counter.php?cid=' + counter.cid + '&type=' + counter.template +
                (undefined !== counter.petition_id ? '&petition_id=' + counter.petition_id : '') +
                (counter.franchise_cid && undefined !== counter.franchise_cid ? '&franchise_cid=' + counter.franchise_cid : '') +
                (counter.petition_latitude && undefined !== counter.petition_latitude ? '&petition_latitude=' + counter.petition_latitude : '') +
                (counter.petition_longitude && undefined !== counter.petition_longitude ? '&petition_longitude=' + counter.petition_longitude : '') +
                (counter.petition_distance && undefined !== counter.petition_distance ? '&distance=' + counter.petition_distance : ''),
            dataType: 'json',
            type: 'GET',
            success: function (json) {
                if (json && 0 == json.paused) {
                    switch (counter.counter_type) {
                    case 'countries_donate':
                    case 'donates':
                        if (counter.in_array(counter.currency, ['euro', 'euro_dollar'])) {
                            counter.max = json.EUR;
                        } else if (counter.in_array(counter.currency, ['other'])) {
                            counter.max = json.OTHER;
                        } else {
                            counter.max = json.USD;
                        }
                        counterdata.USD = json.USD;
                        counterdata.EUR = json.EUR;
                        counterdata.OTHER = json.OTHER;
                        counter.setAdditionalCurrency();
                        break;
                    case 'x_number':
                        counter.max = json.donations;
                        break;
                    case 'ct_x_unique_donors':
                        counter.max = json.donors;
                        break;

                    case 'sign':
                        counter.max = json.count;
                        if (undefined !== counter.franchise_cid){
                            counter.max_nearby = json.count_nearby;
                        }
                        break;
                    }
                }
                counter.ajax_data = false;
                counter.startCounter();
                counter.ajax_counter_timer = setTimeout(counter.ajaxCounter, 20000);
            }
        });
    };
    counter.in_array = function (needle, haystack, argStrict) {
        var key = '', strict = !!argStrict;
        if (strict) {
            for (key in haystack) {
                if (haystack[key] === needle) {
                    return true;
                }
            }
        } else {
            for (key in haystack) {
                if (haystack[key] == needle) {
                    return true;
                }
            }
        }
        return false;
    };
    counter.number_format = function (number, decimals, dec_point, thousands_sep) {
        var n = number, prec = decimals, toFixedFix, sep, dec, s, abs, v, i, decPos;

        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return (Math.round(n * k) / k).toString();
        };

        n = !isFinite(+n) ? 0 : +n;
        prec = !isFinite(+prec) ? 0 : Math.abs(prec);
        sep = (undefined === thousands_sep) ? ',' : thousands_sep;
        dec = (undefined === dec_point) ? '.' : dec_point;

        s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

        abs = toFixedFix(Math.abs(n), prec);

        if (abs >= 1000) {
            v = abs.split(/\D/);
            i = v[0].length % 3 || 3;

            v[0] = s.slice(0, i + (n < 0)) +
                v[0].slice(i).replace(/(\d{3})/g, sep + '$1');
            s = v.join(dec);
        } else {
            s = s.replace('.', dec);
        }

        decPos = s.indexOf(dec);
        if (prec >= 1 && decPos !== -1 && (s.length - decPos - 1) < prec) {
            s += new Array(prec - (s.length - decPos - 1)).join(0) + '0';
        } else if (prec >= 1 && decPos === -1) {
            s += dec + new Array(prec).join(0) + '0';
        }
        return s;
    };

    counter.cid = options.cid;
    counter.mckey = options.key;

    if (undefined !== options.petition_id) {
        counter.petition_id = options.petition_id;
    }

    counter.progress_bar_width = options.autodect_width ? $(options.progress_container).width() : options.max_width;
    counter.counter_type = options.subtype;
    counter.currency_value = options.current_currency_value;
    counter.currency = options.current_currency;
    counter.text = options.text;
    counter.country_text = options.country_text;
    counter.is_target = options.is_target;
    counter.franchise_cid = false;
    counter.petition_latitude = false;
    counter.petition_longitude = false;
    counter.petition_distance = false;

    if (options.franchise_cid && 'undefined' !== options.franchise_cid){
        counter.franchise_cid = options.franchise_cid;

        counter.petition_latitude  = options.petition_latitude;
        counter.petition_longitude = options.petition_longitude;
        counter.petition_distance = options.petition_distance;
    }

    counter.is_progress_target = ('undefined' !== typeof options.is_progress_target) ? options.is_progress_target : true;
    counter.template = '';

    if (undefined === window.counterdata) {
        window.counterdata = {target: 0, target_donate: 0, EUR: 0, OTHER: 0, USD: 0, sign: 0, sign_nearby: 0, donations: 0};
    }

    switch (counter.counter_type) {
    case 'donates':
        counter.target = counterdata.target_donate;
        if (counter.in_array(counter.currency, ['euro', 'euro_dollar'])) {
            counter.current_value = counterdata.EUR;
        } else if (counter.in_array(counter.currency, ['dollar', 'dollar_euro'])) {
            counter.current_value = counterdata.USD;
        } else if (counter.in_array(counter.currency, ['other'])) {
            counter.current_value = counterdata.OTHER;
        }
        counter.template = 'donates';
        break;
    case 'countries_donate':
        counter.target = counterdata.target_donate;
        if (counter.in_array(counter.currency, ['euro', 'euro_dollar'])) {
            counter.current_value = counterdata.EUR;
        } else if (counter.in_array(counter.currency, ['dollar', 'dollar_euro'])) {
            counter.current_value = counterdata.USD;
        }
        counter.template = 'donates';
        break;
    case 'sign':
        counter.currency_value = '';
        counter.target = counterdata.target;
        counter.current_value = counterdata.sign;
        if (false !== counter.franchise_cid){
            counter.current_nearby_value = counterdata.sign_nearby;
        }
        counter.template = 'sign';
        break;
    case 'x_number':
        counter.currency_value = '';
        counter.target = counterdata.target;
        counter.current_value = counterdata.donations;
        counter.template = 'donations';
        break;

    case 'ct_x_unique_donors':
        counter.currency_value = '';
        counter.target = counterdata.target;
        counter.current_value = counterdata.donors;
        counter.template = 'donors';
        break;

    case 'countries':
        counter.currency_value = '';
        counter.target = counterdata.target;
        counter.current_value = counterdata.sign;
        counter.template = 'sign';
        break;
    }

    counter.max2 = counter.target;
    counter.max = counter.current_value;
    counter.nearby_max = counter.current_nearby_value;
    counter.default_max = parseInt(counter.max2, 10);
    counter.num = 0;//arguments[5]?arguments[5]:0;
    counter.timerId = null;
    counter.plus = undefined !== options.plus ? options.plus : 1;
    counter.timeout = 0;
    counter.proc = counter.progress_bar_width / counter.max2;
    counter.ajax_counter_timer = null;
    counter.ajax_data = options.ajax;
    counter.aj_counter_flag = false;
    if (counter.max > counter.max2) {
        counter.proc = counter.progress_bar_width / counter.max;
        counter.default_max = parseInt(counter.max, 10);
    }
    counter.setText();
    counter.setCurrency();
    counter.setTarget();
    counter.setCountryCount();
    counter.startCounter();
}

/*  new/common/js/async_done.js  */
function async_load_function() {
    if (typeof(async_load) != 'undefined' && async_load) {
	var func = async_load.pop();
	while (func) {
	    func();
	    func = async_load.pop();
	};
    }
    setTimeout(async_load_function,1000);
};
async_load_function();
