/* jslint config */
/*global FAB, jQuery */
/*jslint plusplus: false */

window.FAB = window.FAB || {};

FAB.Widget = function(username, containerId, options){ 

    this.username = username;
    this.containerId = containerId;
    this.options = options;

    this.loadStylesheet(); 
    this.ensurejQuery(); 
};
FAB.Widget.prototype = {

    ROOT: 'http://www.fablistic.com',

    loadStylesheet: function() {
        var c = window.document.createElement("link");
        c.href = this.ROOT +'/media/css/widget.css';
        c.rel = "stylesheet";
        c.type = "text/css";
        window.document.getElementsByTagName("head")[0].appendChild(c);
    },

    ensurejQuery: function() {

        if (typeof(window.jQuery) === 'undefined') {

            var c = window.document.createElement("script"),
                widget = this;
            c.type = "text/javascript";
            c.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js";
            window.document.getElementsByTagName("head")[0].appendChild(c);
            window.setTimeout(function(){widget.waitForjQuery();}, 20);
        }
        else {
            this.main();
        }
    },

    waitForjQuery: function() {
        if ( typeof(window.jQuery) === 'undefined' ) {
            var widget = this;
            window.setTimeout(function(){widget.waitForjQuery();}, 10);
        } 
        else {
            this.main();
        }
    },

    main: function() {
        var widget = this,
            colors, colorStr,
            url;

        this.settings = window.jQuery.extend(true, {
            width: 250,
            numReviews: 5,
            colors: { 
                shellBg: '#6BAFF0', 
                shellText: '#FFF', 
                reviewBg: '#FFF', 
                reviewText: '#444',
                linkText: '#0058A6'
            }
        }, this.options);

        colors = this.settings.colors;
        colorStr = window.escape(
                        colors.shellBg +'|'+ colors.shellText +'|'+ 
                        colors.reviewBg +'|'+ colors.reviewText +'|'+ 
                        colors.linkText);
        url = this.ROOT +'/widget/'+ this.username +
            '/?width='+ this.settings.width +
            '&num='+ this.settings.numReviews +
            '&colors='+ colorStr +
            '&callback=?';
        window.jQuery.getJSON(
            url,
            function(data) {
                window.jQuery('#'+ widget.containerId).html(data.html);
            });
    }

};


