/*
  
  &copy; Design Museum 2009.
  
  two main things:
  
  a) if we're on a designer's profile or journal page, we crowbar in 
  the correct LHS menu state and sub-page menu
    
  b) we render the RHS widgets
  
  
*/

String.prototype.startsWith = function (str) {
  return (this.match('^' + str) == str);
};
String.prototype.endsWith = function (str) {
  return (this.match(str + '$') == str);
};
String.prototype.trim = function () {
  return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (obj, fromIndex) {
    if (fromIndex == null) {
        fromIndex = 0;
    } else if (fromIndex < 0) {
        fromIndex = Math.max(0, this.length + fromIndex);
    }
    for (var i = fromIndex, j = this.length; i < j; i++) {
        if (this[i] === obj)
            return i;
    }
    return -1;
  };
}

jQuery(document).ready(
  function () {
    var log = function (str) {
      try {
        console.log(str);
      }
      catch (e) {
        // pass
      }
    };
    
    // render the rss
    jQuery.getFeed({
        url: '/updates/rss.xml',
        'success': function(feed) {
          var target = jQuery('#user-news');
          target.empty();
          var html = '', i, item, l = feed.items.length;
          for (i = 0; i < l && i < 5; i++) {
            item = feed.items[i];
            target.append('<li><a href="' + item.link + '">' + item.title + '</a></li>');
          }
          target.find('li').eq(0).css({
              'border-top': 'none',
              'padding-top': '0em'
          });
        }
    });
    
    // update the search
    var search_input = jQuery('.search-form-pt input');
    var search_form = search_input.parents('form').eq(0);
    if (!search_input.val()) {
      search_input.val('Search');
    } 
    search_input.bind('focus', function () {
        if (search_input.val() == 'Search') {
          search_input.val('');
        } 
    });
    search_input.bind('blur', function () {
        if (!search_input.val()) {
          search_input.val('Search');
        } 
    });
    search_form.bind('submit', function () {
        if (search_input.val() == 'Search') {
          search_input.val('');
        } 
    });
    
    // render the tweets
    jQuery("#user-recent-feeds").tweet({
        'username': ["inresidence"],
        'count': 5,
        'avatar_size': 48,
        'loading_text': ['Loading tweets ...'],
        'query': ['%23inresidence']
      }
    );
    jQuery('#user-recent-feeds li').eq(0).css({
        'border-top': 'none',
        'padding-top': '0em'
    });
    
    // render 12s
    window.handle_12seconds_feed = function (feed) {
      log(feed);
      var target = jQuery('#12second-videos');
      target.empty();
      var i, item, l = feed.value.items.length;
      for (i = 0; i < l && i < 5; i++) {
        item = feed.value.items[i];
        target.append(
          '<li class="user-video"><a href="' + item.link + '">\
              <span class="user-photo"><img src="' + item['media:thumbnail'].url + '" /></span>\
              <span class="user-text"><span>' + item.title + '</span><br />' + item.description + '</span>\
          </a></li>'
        );
      }
      jQuery('#12second-videos li').eq(0).css({
          'border-top': 'none',
          'padding-top': '0em'
      });
    };
    
    var piped_url = 'http://pipes.yahoo.com/pipes/pipe.run?_callback=window.handle_12seconds_feed&_id=9oyONQzA2xGOkM4FqGIyXQ&_render=json&feed=http://12seconds.tv/channel/inresidence/feed';
    jQuery(document.getElementsByTagName('head')[0]).append(
      '<' + 'scr' + 'ipt type="text/javascript" src="' + piped_url + '"' + '><' + '/sc' + 'rip' + 't>'
    );
    
    // are we on a designer's page?
    var designer = '', identifier = '', page_type = '';
    var designers = [
      'Dave Bowker',
      'Marc Owens',
      'Bethan Wood',
      'Asif Khan',
      'Farm'
    ], identifiers = [];
    jQuery.each(designers, function () {
        identifiers.push(this.toLowerCase().replace(' ', '-'));
    });
    log(identifiers);
    var path = window.location.pathname;
    if (path.endsWith('/')) {
      path = path.substring(0, path.length - 1);
    }
    log(path);
    var last_path_part = path.split('/').pop();
    log(last_path_part);
    var index = identifiers.indexOf(last_path_part);
    if (index > -1) {
      log(index);
      // we are on a designers page
      designer = designers[index];
      log(designer);
      identifier = identifiers[index];
      log(identifier);
      if (window.location.pathname.indexOf('/author/') > -1) {
        page_type = 'updates';
      }
      else {
        page_type = 'profile';
      }
      log(page_type);
      // get the LHS elements
      var targets = jQuery('#sidebar1 .section li');
      var target, span, text;
      jQuery.each(targets, function () {
          target = jQuery(this);
          log(target);
          span = target.find('a span');
          text = span.text().trim();
          log(text);
          // if it's not the current designer
          if (text != designer) {
            log('grey it out');
            // grey it out
            target.addClass('greyed-out');
          }
          else {
            log('leave it alone');
          }
      });
      // insert the menu above the first <p/> in #content
      var updates_class = (page_type == 'updates') ? 'selected' : '';
      var profile_class = (page_type == 'profile') ? 'selected' : '';
      var header_content = '<span class="' + profile_class + '"><a href="/' + identifier + '/" title="View ' + designer + '\'s Profile">' + designer + '</a></span><span class="last ' + updates_class + '"><a href="/updates/author/' + identifier + '" title="View ' + designer + '\'s Updates">Updates</a></span>';
      var header = jQuery('#content .header h1').eq(0);
      if (header.length) {
        header.html(header_content);
        header.addClass('dynamic');
      }
      else {
        var p = jQuery('#content p').eq(0);
        p.before(
          '<div class="header"><h1 class="dynamic">' + header_content + '</h1></div>'
        );
      }
      /*jQuery('#content .journal-filter-header').css({'display': 'none'});*/
    }
    else {
      log('last_path_part not in identifiers');
    }
    /*
    if (last_path_part == 'gallery') {
      jQuery('#content .header').before(
        '<div class="header"><h1 class="dynamic"><span><a title="About Designers in Residence" href="/about/">About Designers in Residence</a></span><span class="selected last"><a title="Gallery" href="/updates/tag/gallery/">Gallery</a></span></h1></div>'
      ).remove(); 
    }
    */
  }
);