/* plugin */
(function($){

    $.fn.hotContent = function(options){
        return this.each(function(){
            new $.hotContent(this, options);
        });
    }

    $.hotContent = function(el, options){

        // defaults
        var defaults = {
            displayMax : 6,
            section : 'all',
            type : 'articles'
        };

        // new options
        this.options = $.extend(defaults, options);

        this.props = {
            element : el
        };

        this.init(el);
    }

    $.hotContent.fn = $.hotContent.prototype = {};

    $.hotContent.fn.extend = $.hotContent.extend = $.extend;

    $.hotContent.fn.extend({
        init : function(el){
            var self = this, props = this.props, options = this.options;

            // Set initialization to true
            props.initialized = true;

            // Setup some more props
            props.section = options.section;
            props.type = options.type;
            props.displayMax = options.displayMax;
            if (options.callback) {
                props.callback = options.callback;
            }
            if (options.event) {
                props.event = options.event;
            }

            // default display types
            if (!options.displayTemplate) {
                if (el.tagName.toLowerCase() == "ol" || el.tagName.toLowerCase() == "ul") {
                    options.displayTemplate = '<li><a href="#{url}">#{linkText}</a></li>';
                } else {
                    options.displayTemplate = '<p><b>#{no}.</b>: <a href="#{url}">#{linkText}</a></p>';
                }
            }

            this.load(props.section, props.type, props);
        },

        getDataUrl : function(section,type,proxy){
            if (proxy) {
                return "/wpost/data/proxy.json?r=http://www.washingtonpost.com/wp-srv/javascript/contentorbiting/hotcontent/"+section+"/"+type+"/index.js&jsonp=?";
            }
            return "http://www.washingtonpost.com/wp-srv/javascript/contentorbiting/hotcontent/"+section+"/"+type+"/index.js";
        },

        getProperties : function(obj) {
            // Go through all the properties of the passed-in object
            var r = new Array();
            for (var i in obj) {
                var o = {};
                o.name = i;
                o.value = obj[i];
                r.push(o);
            }
            return r;
        },

        load : function(section,type,props){
            var self = this;

            // determin type to load
            var dtype = 'json';
            var dataUrl = '';
            if (window.location.href.indexOf("http://www.washingtonpost.com/") > -1) {
                dataUrl = self.getDataUrl(section,type, false);
            } else if (window.location.href.indexOf("http://live.washingtonpost.com/") != -1) {
                dtype = 'jsonp';
                dataUrl = "http://www.washingtonpost.com" + self.getDataUrl(section,type, true);
            } else {
                dtype = 'jsonp';
                dataUrl = self.getDataUrl(section,type, true);
            }
            $.ajax({
                dataType:dtype,
                url:dataUrl,
                dataFilter:function(data,type){
                    return self.toJSON(data);
                },
                success:function(data,msg){
                    $.extend(props,{
                        msg:msg
                    });
                    self.render(data, props);
                }
            });
        },

        render : function(data, props) {
            var self = this;

            var $el = $(props.element);
            var max = props.displayMax - 1; // -1 for index
            var maxHeight = 0;

            $el.html("");

            $(data.content).each(function(i) {
                $el.append(self.sanitizeItem(i+1, this));
                return (i < max);
            });

            if(props.event) $(document).trigger(props.event,self.sanitizeUrls(data));
            if(props.callback) props.callback.call(self,data,props);
        },

        sanitizeItem : function(position, item) {
            var self = this;
            var r = this.options.displayTemplate;
            item.position = position;
            var p = this.getProperties(item);
            for (var i = 0; i < p.length; i++) {
                if (p[i].name == 'url') {
                    p[i].value = self.sanitizeUrl(p[i].value);
                }
                r = r.replace('\#\{' + p[i].name + '\}', p[i].value);
            }
            return r;
        },

        sanitizeUrls : function(data){
            var self = this;
            $(data.content).each(function(i){
                this.url = self.sanitizeUrl( this.url );
            });
            return data;
        },

        sanitizeUrl : function(url){
            return url.replace(/(\?|&)nav=.*?(&|$)/,'');
        },

        toJSON : function(json){
            //alert(!(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test( json.replace(/"(\\.|[^"\\])*"/g, '')))&&eval('('+json+')'));
            json = json.replace(/\n/g,'');
            json = json.replace(/"\s*,\s*/g,'",');
            json = json.replace(/{\s*/g,'{');
            while ( json.match(/([{,])(\w+):/) ) {
                json = json.replace(/[{,]\w+:/,RegExp.$1+'"'+RegExp.$2+'":');
            }
            json = json.replace(/\\'/g,'&#39;');
            json = json.replace(/\\"/g,'&#34;');
            json = json.replace(/\s*;$\s*/g,'');
            //alert(!(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test( json.replace(/"(\\.|[^"\\])*"/g, '')))&&eval('('+json+')'));

            return json;
        }

    });
})(jQuery);

