if(typeof(Prototype)=="undefined"){throw"Control.Rating requires Prototype to be loaded."}if(typeof(Object.Event)=="undefined"){throw"Control.Rating requires Object.Event to be loaded."}Control.Rating=Class.create({initialize:function(a,c){Control.Rating.instances.push(this);this.value=false;this.links=[];this.container=$(a);this.container.update("");this.options={min:1,max:5,rated:false,input:false,reverse:false,capture:true,multiple:false,classNames:{off:"rating_off",half:"rating_half",on:"rating_on",selected:"rating_selected"},updateUrl:false,updateParameterName:"value",updateOptions:{},afterChange:Prototype.emptyFunction};Object.extend(this.options,c||{});if(this.options.value){this.value=this.options.value;delete this.options.value}if(this.options.input){this.options.input=$(this.options.input);this.options.input.observe("change",function(d){this.setValueFromInput(d)}.bind(this,this.options.input));this.setValueFromInput(this.options.input,true)}var b=$R(this.options.min,this.options.max);(this.options.reverse?$A(b).reverse():b).each(function(d){var e=this.buildLink(d);this.container.appendChild(e);this.links.push(e)}.bind(this));this.setValue(this.value||this.options.min-1,false,true)},buildLink:function(a){var b=$(document.createElement("a"));b.value=a;if(this.options.multiple||(!this.options.rated&&!this.options.multiple)){b.href="";b.onmouseover=this.mouseOver.bind(this,b);b.onmouseout=this.mouseOut.bind(this,b);b.onclick=this.click.bindAsEventListener(this,b)}else{b.style.cursor="default";b.observe("click",function(c){Event.stop(c);return false}.bindAsEventListener(this))}b.addClassName(this.options.classNames.off);return b},disable:function(){this.links.each(function(a){a.onmouseover=Prototype.emptyFunction;a.onmouseout=Prototype.emptyFunction;a.onclick=Prototype.emptyFunction;a.observe("click",function(b){Event.stop(b);return false}.bindAsEventListener(this));a.style.cursor="default"}.bind(this))},setValueFromInput:function(a,b){this.setValue($F(a),true,b)},setValue:function(e,c,d){this.value=e;if(this.options.input){if(this.options.input.options){$A(this.options.input.options).each(function(g,a){if(g.value==this.value){this.options.input.options.selectedIndex=a;throw $break}}.bind(this))}else{this.options.input.value=this.value}}this.render(this.value,c);if(!d){if(this.options.updateUrl){var f={},b;f[this.options.updateParameterName]=this.value;b=new Ajax.Request(this.options.updateUrl,Object.extend(this.options.updateOptions,{parameters:f}))}this.notify("afterChange",this.value)}},render:function(b,a){(this.options.reverse?this.links.reverse():this.links).each(function(d,c){if(d.value<=Math.ceil(b)){d.className=this.options.classNames[d.value<=b?"on":"half"];if(this.options.rated||a){d.addClassName(this.options.classNames.selected)}}else{d.className=this.options.classNames.off}}.bind(this))},mouseOver:function(a){if(!this.options.rated){this.render(a.value,true)}},mouseOut:function(a){if(!this.options.rated){this.render(this.value)}},click:function(b,a){if(!this.options.rated){this.options.rated=true;this.setValue((a.value?a.value:a),true);if(!this.options.multiple){this.disable()}}if(this.options.capture){Event.stop(b);return false}}});Object.extend(Control.Rating,{instances:[],findByElementId:function(a){return Control.Rating.instances.find(function(b){return(b.container.id&&b.container.id==a)})}});Object.Event.extend(Control.Rating);
(function(){var a=24*60*60*1000;var e=function(i,j){i=String(i);while(i.length<j){i="0"+i}return i};var h={millisecond:1,second:1000,minute:60*1000,hour:60*60*1000,day:a,week:7*a,month:{add:function(k,i){h.year.add(k,Math[i>0?"floor":"ceil"](i/12));var j=k.getMonth()+(i%12);if(j==12){j=0;k.setYear(k.getFullYear()+1)}else{if(j==-1){j=11;k.setYear(k.getFullYear()-1)}}k.setMonth(j)},diff:function(m,k){var i=m.getFullYear()-k.getFullYear();var j=m.getMonth()-k.getMonth()+(i*12);var l=m.getDate()-k.getDate();return j+(l/30)}},year:{add:function(j,i){j.setYear(j.getFullYear()+Math[i>0?"floor":"ceil"](i))},diff:function(j,i){return h.month.diff(j,i)/12}}};for(var d in h){if(d.substring(d.length-1)!="s"){h[d+"s"]=h[d]}}var g=function(l,k){if(Date.prototype.strftime.formatShortcuts[k]){return l.strftime(Date.prototype.strftime.formatShortcuts[k])}else{var i=(Date.prototype.strftime.formatCodes[k]||"").split(".");var j=l["get"+i[0]]?l["get"+i[0]]():"";if(i[1]){j=e(j,i[1])}return j}};var c={succ:function(i){return this.clone().add(1,i)},add:function(k,j){var i=h[j]||h.day;if(typeof i=="number"){this.setTime(this.getTime()+(i*k))}else{i.add(this,k)}return this},diff:function(j,m,i){j=Date.create(j);if(j===null){return null}var k=h[m]||h.day;if(typeof k=="number"){var l=(this.getTime()-j.getTime())/k}else{var l=k.diff(this,j)}return(i?l:Math[l>0?"floor":"ceil"](l))},strftime:function(j){var l=j||"%Y-%m-%d",i="",k;while(l.length>0){if(k=l.match(Date.prototype.strftime.formatCodes.matcher)){i+=l.slice(0,k.index);i+=(k[1]||"")+g(this,k[2]);l=l.slice(k.index+k[0].length)}else{i+=l,l=""}}return i},getShortYear:function(){return this.getYear()%100},getMonthNumber:function(){return this.getMonth()+1},getMonthName:function(){return Date.MONTHNAMES[this.getMonth()]},getAbbrMonthName:function(){return Date.ABBR_MONTHNAMES[this.getMonth()]},getDayName:function(){return Date.DAYNAMES[this.getDay()]},getAbbrDayName:function(){return Date.ABBR_DAYNAMES[this.getDay()]},getDayOrdinal:function(){return Date.ORDINALNAMES[this.getDate()%10]},getHours12:function(){var i=this.getHours();return i>12?i-12:(i==0?12:i)},getAmPm:function(){return this.getHours()>=12?"PM":"AM"},getUnix:function(){return Math.round(this.getTime()/1000,0)},getGmtOffset:function(){var i=this.getTimezoneOffset()/60;var j=i<0?"+":"-";i=Math.abs(i);return j+e(Math.floor(i),2)+":"+e((i%1)*60,2)},getTimezoneName:function(){var i=/(?:\((.+)\)$| ([A-Z]{3}) )/.exec(this.toString());return i[1]||i[2]||"GMT"+this.getGmtOffset()},toYmdInt:function(){return(this.getFullYear()*10000)+(this.getMonthNumber()*100)+this.getDate()},clone:function(){return new Date(this.getTime())}};for(var b in c){Date.prototype[b]=c[b]}var f={create:function(j){if(j instanceof Date){return j}if(typeof j=="number"){return new Date(j*1000)}var o=String(j).replace(/^\s*(.+)\s*$/,"$1"),k=0,l=Date.create.patterns.length,m;var n=o;while(k<l){ms=Date.parse(n);if(!isNaN(ms)){return new Date(ms)}m=Date.create.patterns[k];if(typeof m=="function"){obj=m(n);if(obj instanceof Date){return obj}}else{n=o.replace(m[0],m[1])}k++}return NaN},MONTHNAMES:"January February March April May June July August September October November December".split(" "),ABBR_MONTHNAMES:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),DAYNAMES:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),ABBR_DAYNAMES:"Sun Mon Tue Wed Thu Fri Sat".split(" "),ORDINALNAMES:"th st nd rd th th th th th th".split(" "),ISO:"%Y-%m-%dT%H:%M:%S.%N%G",SQL:"%Y-%m-%d %H:%M:%S",daysInMonth:function(i,j){if(j==2){return new Date(i,1,29).getDate()==29?29:28}return[undefined,31,undefined,31,30,31,30,31,31,30,31,30,31][j]}};for(var b in f){Date[b]=f[b]}Date.prototype.strftime.formatCodes={matcher:/()%(#?(%|[a-z]))/i,Y:"FullYear",y:"ShortYear.2",m:"MonthNumber.2","#m":"MonthNumber",B:"MonthName",b:"AbbrMonthName",d:"Date.2","#d":"Date",e:"Date",A:"DayName",a:"AbbrDayName",w:"Day",o:"DayOrdinal",H:"Hours.2","#H":"Hours",I:"Hours12.2","#I":"Hours12",p:"AmPm",M:"Minutes.2","#M":"Minutes",S:"Seconds.2","#S":"Seconds",s:"Unix",N:"Milliseconds.3","#N":"Milliseconds",O:"TimezoneOffset",Z:"TimezoneName",G:"GmtOffset"};Date.prototype.strftime.formatShortcuts={F:"%Y-%m-%d",T:"%H:%M:%S",X:"%H:%M:%S",x:"%m/%d/%y",D:"%m/%d/%y","#c":"%a %b %e %H:%M:%S %Y",v:"%e-%b-%Y",R:"%H:%M",r:"%I:%M:%S %p",t:"\t",n:"\n","%":"%"};Date.create.patterns=[[/-/g,"/"],[/st|nd|rd|th/g,""],[/(3[01]|[0-2]\d)\s*\.\s*(1[0-2]|0\d)\s*\.\s*([1-9]\d{3})/,"$2/$1/$3"],[/([1-9]\d{3})\s*-\s*(1[0-2]|0\d)\s*-\s*(3[01]|[0-2]\d)/,"$2/$3/$1"],function(l){var j=l.match(/^(?:(.+)\s+)?([1-9]|1[012])(?:\s*\:\s*(\d\d))?(?:\s*\:\s*(\d\d))?\s*(am|pm)\s*$/i);if(j){if(j[1]){var k=Date.create(j[1]);if(isNaN(k)){return}}else{var k=new Date();k.setMilliseconds(0)}var i=parseFloat(j[2]);i=j[5].toLowerCase()=="am"?(i==12?0:i):(i==12?12:i+12);k.setHours(i,parseFloat(j[3]||0),parseFloat(j[4]||0));return k}}]})();var $D=Date.create;
var APP = (function()
{
    function init(jsDataStore)
    {
        var nodes = {
            flags       : $$('div.red_flag-block'),
            ratings     : $$('div.rating_container'),
            twitter     : $$('div.twits_content')[0]
        };

        $$('div.row3_content_bottom:first-child:not(:has(div))').each(function(node)
        {
            node.up().up().hide();
        });

        nodes.flags.invoke('observe', 'click', function(e)
        {
            var node    = $(this),
                oid     = jsDataStore.oid || 0,
                nid     = parseInt(node.readAttribute('data-nid') || 0, 10);

            if (!node.retrieve('isBusy') && oid > 0 && nid > 0)
            {
                e.stop();
                if (window.confirm('Are you sure?'))
                {
                    node.setStyle({opacity: 0.6}).setStyle({cursor: 'default'}).store('isBusy', 1);

                    new Ajax.Request(jsDataStore.elements.flag.url,
                    {
                        parameters: {
                            oid : oid,
                            nid : nid
                        },
                        onComplete: function(transport)
                        {
                            if (!(transport.status == 200 && (transport.responseJSON || {}).isSuccessfully))
                            {
                                node.setStyle({opacity: 1}).setStyle({cursor: 'pointer'}).store('isBusy', 0);
                            }
                        }
                    });
                }
            }
        });

        nodes.ratings.each(function(node)
        {
            new Control.Rating(node.identify(), {
                value       : node.readAttribute('data-rating'),
                multiple    : true
            }).observe('afterChange', function(node, point)
            {
                var ratingObj = Control.Rating.findByElementId(node.readAttribute('id'));

                if (ratingObj)
                {
                    new Ajax.Request(jsDataStore.elements.rating.url,
                    {
                        parameters: {
                           nid      : node.readAttribute('data-nid'),
                           point    : point
                        },
                        onComplete: function(transport)
                        {
                            var result      = transport.responseJSON || {},
                                hasUpdate   = transport.status == 200 && result.isSuccessfully,
                                value       = hasUpdate ? result.rating : node.readAttribute('data-rating');

                            ratingObj.options.rated = hasUpdate;
                            ratingObj.setValue(value, false, true);
                            if (hasUpdate)
                            {
                                node.fire('rating:hide');
                            }
                        }
                    });
                }
            }.curry(node.observe('rating:hide', function()
            {
                this.up('div.voteform').setStyle({opacity: 0.6});
            })));
        });

        if (Object.isElement(nodes.twitter))
        {
            new Ajax.JSONRequest('http://twitter.com/statuses/user_timeline/RrandomStaff.json',
            {
                parameters: {
                    count: 3
                },
                onComplete: function(transport)
                {
                    var html    = [],
                        result  = transport.responseJSON;

                    if (transport.status == 200 && Object.isArray(result))
                    {
                        var template = new Template('<div class="twits_item"><h5>#{date}<br />by <a href="http://twitter.com/#!/#{user}" target="_blank">#{user}</a></h5><p>#{text}</p></div>');

                        result.each(function(item)
                        {
                            var date = item.created_at.split(' ');
                            
                            html.push(template.evaluate({
                                date: new Date(Date.parse(date[1] + " " + date[2] + ", " + date[5] + " " + date[3] + " UTC")).strftime('%A %B %d at %#I:%M %p'),
                                user: item.user.screen_name,
                                text: item.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url)
                                {
                                    return '<a href="' + url + '">' + url + '</a>';
                                }).replace(/\B@([_a-z0-9]+)/ig, function(reply)
                                {
                                    return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
                                })
                            }));
                        });
                    }
                    else
                    {
                        html.push('<div class="twits_item"><p><strong>Resource temporarily unavailable</strong></p></div>');
                    }

                    nodes.twitter.update(html.join(''));
                }
            });
        }
    }

    return {
        init: init
    }
})();

