(function(context, $) {
  
  function renderCss(sidebar) {
      var head = document.getElementsByTagName("head")[0];
      var link = document.createElement("link");
      link.setAttribute("rel", "stylesheet");
      link.setAttribute("type", "text/css");
      link.setAttribute("media", "all");
      link.setAttribute("href", sidebar.cssPath + "sidebar." + sidebar.skin + ".css");
      head.appendChild(link);
  }

  function constructItem(sidebar, item) {
    var target,
        markup = itemTemplate.replace(/\{id\}/g, sidebar.id)
      .replace(/\{cp\}/g, sidebar.classPrefix)
      .replace(/\{name\}/g, item.name)
      .replace(/\{iconSrc\}/g, item.iconSrc)
      .replace(/\{link\}/g, item.link)
      .replace(/\{iconTitle\}/g, item.title)
      .replace(/\{onClick\}/g, item.onClick);
    
    if (item.target) {
      target = 'target="' + item.target + '"';
    } else {
      target = "";
    }
    return markup.replace(/\{target\}/g, target);
  }

  function constructContent(sidebar, item, content) {
    return contentTemplate.replace(/\{id\}/g, sidebar.id)
      .replace(/\{cp\}/g, sidebar.classPrefix)
      .replace(/\{name\}/g, content)
      .replace(/\{index\}/g, item.index);
  }

  var index = 0;
  var markupTemplate = [
    // {cp} : classPrefix property.  Allows user to set their own prefix on classes in stylesheets.
    // {id} : id property.  Allows for multiple rotators on one page.
    '<div id="{id}_container" class="{cp}_container">',
    '  <ul id="{id}_items" class="{cp}_items">',
    '  </ul>',
    '  <div id="{id}_content_wrapper" class="{cp}_content_wrapper">',
    '    <div id="{id}_content_carat" class="{cp}_content_carat"><img src="img/sidebar/sidebar-carat.png" /></div>',
    '    <div class="{cp}_content {cp}_round" style="background-color:#232323;">',
	'    <div class="sb_close"><div class="sb_close_button" onClick="me.dismissContent()">x</div></div>',   
    '    <div id="{id}_content" class="""></div></div>',
    '  </div>',
    '</div>'

  ].join('\n');

  var contentTemplate = [

    '  <div id="{id}_carat" class="{cp}_carat carat_{index}">',
    '  </div>',
    '  <div id="{id}_sidebar_content" class="{cp}_sidebar_content {cp}_round"">',
	'    {content}',
    '  </div>'

  ].join('\n');

  var itemTemplate = [
    
    '<li>',
    '  <a href="{link}" id="{id}_{name}_link" {target} onClick="{onClick}" >',
    '    <img src="{iconSrc}" class="{cp}_item_img" alt="{iconTitle}" title="{iconTitle}" />',
    '  </a>',
    '</li>'

  ].join('\n');

  var Sidebar = function(options) {
    options = options || {};
    this.id = options.id || "sidebar" + (++index);
    this.skin = options.skin || "default";
    this.cssPath = options.cssPath || "";
    this.classPrefix = options.classPrefix || "sb";
    this.items = options.items || [];

    this.rendered = false;
  };

  Sidebar.prototype = {

    getMarkupTemplate: function() {
      return markupTemplate.replace(/\{id\}/g, this.id)
        .replace(/\{cp\}/g, this.classPrefix);
    },
    
    render: function(container, cb) {
      var me = this;
    
    me.items = [
      {
        name: "email",
        title: "Our Team",
        index: 0, // index of icon in sidebar, 0 is at top.  Helps with placement of "carat" when hover/click.
        content: "html content or template",
        //link: "mailto:resumesgb@zyquest.com",
        link: "./about.html#about.team",
        iconSrc: "img/sidebar/sidebar-email.png",
        onClick: "return myApp.content.setSectionContent('about', 'team')"
      },
      {
        name: "portal",
        title: "Employee Portal",
        index: 1, // index of icon in sidebar, 0 is at top.  Helps with placement of "carat" when hover/click.
        content: "html content or template",
        link: "http://www.hrconnection.com/",
        target: "_blank",
        iconSrc: "img/sidebar/sidebar-portal.png"
      }/*,
      {
        name: "information",
        title: "Information",
        index: 4, // index of icon in sidebar, 0 is at top.  Helps with placement of "carat" when hover/click.
        content: "Here's some information about ZyQuest",
        link: "#",
        iconSrc: "img/sidebar/sidebar-info.png"
      }*/
    ];
      if (! me.rendered) {
        var el, go = false, i = 0;
        if (typeof container === "string") {
          if (container.charAt(0) === "#") {
            el = $(container);
            //el = document.getElementById(container.substring(1));
            go = true;
          } else {
            cb && cb("Container element specified is not a valid ID.  Consider sending #"+container);
          }
        } else if (typeof container === "object") { // assume it's a dom element
          el = $(container);
          go = true;
        } else {
          cb && cb("Invalid container submitted.  Should be string or object, but was " + (typeof container));
        }

        if (go) {
          
          renderCss(me);
      

          el.append(me.getMarkupTemplate());

          // Render content
          var item, list = $('#'+me.id+'_items');
          var content;
          for (i = 0; i < me.items.length; i++) {
            item = me.items[i];
      
            /* Unknowns: 
             * how to handle contact info.  Likely do something similar to slidePanel
             * 
             */
            // Append the list item
            el = $(constructItem(me, item));
            //set up content

            el.appendTo(list);

            // Ready the display content
            // TODO: Need to figure out how to set up each item's content for display on hover / click.
      
            //$('#'+me.id+'_content_wrapper').empty();  // then append in onclick / hover
            $('body').bind('click', me.dismissContent);

          } // end for each item

          me.rendered = true;

        } // end if go
      } 
    },
  clearGroupContent: function()
  {
    $('.sidebar-content').remove();
  },
  addGroupContent: function(html) {
    var me = this;
    var list = $('#'+me.id+'_items');
    html = '<li class="sidebar-content" style="display: block;">' + html + '</li>';
    $(html).prependTo(list);
  },
  addToContentPanel: function(html) {
    var me = this;
    $('#'+me.id+'_content').empty();
    $(html).appendTo('#'+me.id+'_content');
    $('#'+me.id+'_content_wrapper').toggle();
  },
  setContentPanelDimens: function(options) {
    var me = this;
    
    options = options || {};
    var width = options.width || $('#'+me.id+'_content').css('width');
    var height = options.height || $('#'+me.id+'_content').css('height');

    $('#'+me.id+'_content').css('width', width);
    $('#'+me.id+'_content').css('height', height);
  },

  activateContent: function(event) {
    var me = this;

    // TODO: Implement method to append content and show it.  Then bind this method to items.
  },

  dismissContent: function(event) {
    if (! $.contains($('#'+myApp.sidePanel.id+'_container')[0], $(this)[0])) {
      $('#'+myApp.sidePanel.id+'_content_wrapper').fadeOut(250);
    }
  }

  };

  if (context) context.Sidebar = Sidebar;

})(window, jQuery);
