﻿/**
* Today's Parent Toronto - Directory Top Category Widget
* 
* @author Craig Nagy
* @version 1.0
* @requires jQuery The jQuery library
*

EXAMPLE:
<script type="text/javascript" src="/Scripts/com.rogers.Directory.TopCategoryWidget.js"></script>
<script type="text/javascript">
var categoryWidget = new com.rogers.Directory.TopCategoryWidget({ targetID: "directory-popular", count: 5 });
</script>  

*/

/**
* Helper for registering namespaces
*/
function registerNS(ns) {
    var nsParts = ns.split(".");
    var root = window;
    for (var i = 0; i < nsParts.length; i++) {
        if (typeof root[nsParts[i]] == "undefined") {
            root[nsParts[i]] = new Object();
        }
        root = root[nsParts[i]];
    }
}

registerNS("com.rogers.Directory.TopCategoryWidget");

/**
* Constructor
*/
com.rogers.Directory.TopCategoryWidget = function(options) {
    // Configuration properties/options
    this.config = jQuery.extend({

        targetID: "Diretory-TopCategoires",
        serviceUrl: "http://directory.todaysparent.com/Toronto/TopCategories/",
        count: 5,

        // Language
        lang: {
            title: 'Browse by category:',
            moreText: "more"
        },

        // CSS Styles
        styles: {
    },

    debug: true

}, options);

this.$target = {};
var self = this;

$(function() {
    self.log("TopCategoryWidget()");
    if (self.config.targetID != "" && self.init()) {
        self.log("Sending JSON request for category data");
        $.getJSON(self.config.serviceUrl + "?callback=?",
				{ count: self.config.count },
				function(data) { self.display(data); });
    }
});

};

/**
* Checks if the targetID is valid and saves the jquery
* reference to $target
*/
com.rogers.Directory.TopCategoryWidget.prototype.init = function() {
    this.$target = $('#' + this.config.targetID);
    if (this.$target.length != 1) {
        this.log("targetID not found", this.config.targetID);
        return false;
    }
    return true;
};

com.rogers.Directory.TopCategoryWidget.prototype.display = function(data) {

    this.log("display()");
    var html = [
        '<ol class="Directory-TopCategories">'
    ];

    for (var i = 0; i < data.length; i++) {
        html.push(this.item(data[i]));
    }
    html.push('</ul>');

    this.$target.append(html.join(''));

};

/**
*
*/
com.rogers.Directory.TopCategoryWidget.prototype.item = function(category) {
    this.log("item()");
    return ['<li><a href="', category.Url, '">',category.Facet,' - ', category.Name, '</a></li>'].join('');
};


/**
* Firebug based console logging
*/
com.rogers.Directory.TopCategoryWidget.prototype.log = function() {
    if (this.config.debug && window.console && window.console.debug)
        console.debug.apply(console, arguments);
};