/*document.getElementById('filter').onchange = function() {
	this.parentNode.submit();
};*/
(function($) { 
 $.log = function(msg) {
   if (typeof(console) != 'undefined') {
     console.log(msg);
   }
   else {
     $('#debug').append(msg + '<br />');
   }
 }
 $.rot13 = function(string) {
      var newString = string;
      if (typeof string === 'string') {
        newString = newString.replace(/[a-z0-9]/ig, function(chr) {
            var cc = chr.charCodeAt(0);
            if (cc >= 65 && cc <= 90) cc = 65 + ((cc - 52) % 26);
            else if (cc >= 97 && cc <= 122) cc = 97 + ((cc - 84) % 26);
            else if (cc >= 48 && cc <= 57) cc = 48 + ((cc - 43) % 10); //rot5 for numerals
            return String.fromCharCode(cc);
        });
      }
      return newString;
  }
})(jQuery);

$('body').addClass("js");

$(function() {
	
	// Portfolio search
	var quicksearchBinded = false;
	
	$('#searchbox')
		.bind('keyup', function() {
			var $searchbox = $(this);
			
			if ($searchbox.val().length > 1) {
				$('.company_profile:visible').hide();
				
				if ($('#search').is(':hidden')) {
					$('.portfolio_list:visible').hide();
					$('#search').show();
					$('.filter_nav').find('li.selected').removeClass('selected');
					$('#compTitle').html('Search Results');
				}
				
				if (! quicksearchBinded) {
					quicksearchBinded = true;
					
					$searchbox.quicksearch('div#search ul li', {
						selector : 'a',
						noResults : '#no_results'
					});
				}
			}
		})
		.focus(function() {
			$(this).select();
		});

  $('a.email').each(function(){
    var email = $.rot13($(this).attr('href'));
    $(this).attr('href', email);
    var $span = $(this).children('span.email').eq(0);
    if ($span.length) {
      var text = $.rot13($span.text());
      $span.empty().append(text);
    }
  });

	if ($('#team_data').length) {
		// Define groups that do not sort
		var noSorting = ['advisor', 'platform', 'admin'];
		
		// Cache team list
		var $teamList = $('#team_list');
		
		// Create container to hold individual member info
		// We insert it right after the team list
		var $memberBio = $('<ul class="member_info hide">').insertAfter($teamList);
		
		// Our members data object
		var membersData = {};
		
		// Keep track of the current group
		// Default is the investment group since that's the group shown on page load
		var currentGroup = 'investment';
		
		// Keep track of the current location filter
		var currentSubgroup = '';
		
		$('#team_data li').each(function(i) {
			var $this = $(this),
				name = $this.find('h3').eq(0).text(),
				uid = name.replace(/[^a-z0-9]+/ig, '').toLowerCase(),
				bio = $this.find('div.profile').html();
							
			// Get the group for this member
			var groupId = $this.data('group');
			
			// A group is required
			if (groupId != null && name != '') {
			  				
				// If group does not exist, init it
				if (membersData[groupId] == null) {
					// Init group as an object
					membersData[groupId] = {};
				}
				
				// Member info
				var info = {
					'id' 	: uid,
					'name' 	: name,
					'bio'	: bio
				};
				
				membersData[groupId][uid] = info;
			}
		});
		
		if (window.location.hash) {
			displayMemberBio(window.location.hash);
		}
		else {
			populateMemberList('investment');
		}
        
		// Click event to view an individual team member
		$('a', $teamList).live('click', function(e) {
			e.preventDefault();
			
			var hash = $(this).attr('href');
			
			// For some reason IE 7 is returning the full url
			if (hash.indexOf('http://') >= 0) {
				hash = hash.substring(hash.indexOf('#'));
			}
			
			//window.location = hash;
			
			displayMemberBio(hash);
		});
		
		// Back button, hides the member bio and shows the member list
		$('.btn_back_team').live('click', function(e) {
			e.preventDefault();
			$teamList.show();
			$memberBio.hide();
		});
		
		// This is the click event for filtering members of a group, i.e. Investment, Advisors, etc.
		$('.team_filter_nav a').click(function(e) {
			e.preventDefault();
			
			$(this).parent().addClass('selected').siblings().removeClass('selected');
			
			currentGroup = $(this).attr('href').replace('#', '');
			
			populateMemberList(currentGroup);
			
			// If not one of the sorting, hide the sort dropdown
			if ($.inArray(currentGroup, noSorting) > -1) {
				$('#subgroup_filter').hide();
			}
			else {
				$('#subgroup_filter').show();
				
				// Reset the location filter dropdown
				document.getElementById('filter_form').reset();
			}
		});
		
		// Subgroup filter, i.e. China, India, NA
		$('#subgroup_filter').change(function() {
			// Set the location
			currentSubgroup = $(this).val();
			
			// Filter using the current group
			populateMemberList(currentGroup, currentSubgroup);
		});
		
	} // End if $('#team_data').length 
	
	// Populates and displays the member list for a given group
	function populateMemberList(groupId, subgroup) {
		var html = '';
		var members = [];

		if (subgroup != null && typeof(subgroupData[groupId]) != 'undefined' && typeof(subgroupData[groupId][subgroup]) != 'undefined') {
		  
		  for (var i in subgroupData[groupId][subgroup]) {
		    var uid = subgroupData[groupId][subgroup][i];
		    members.push(membersData[groupId][uid]);
		  }
		}
		else {
		   members = membersData[groupId];
		}
		
		for (var i in members) {
		  html += '<li><a href="#'+ members[i].id +'">' + members[i].name  + '</a></li>';
		}
			
		// Hide the member bio in case it was shown
		$memberBio.hide();
		
		// Add members to the team list container
		$teamList
			.html('<ul>' + html + '</ul>')
			.show();
	}
	
	function displayMemberBio(memberId) {
		var direct = false;
		
		// If there is a hadh, get everything after it
		if (memberId.indexOf('#') >= 0) {
			memberId = memberId.substring(memberId.indexOf('#') + 1);
		}
		
		// Get member from our data
		var member = membersData[currentGroup][memberId];
		
		// If null, lets try to search for it
		if (member == null) {
			for (var gid in membersData) {
				member = membersData[gid][memberId];
				
				// Save the group id
				currentGroup = gid;
				
				// If found, break out
				if (member != null) {
					direct = true;
					break;
				}
			}
		}
		
		// Continue if not null
		if (member != null) {
			var html = '<li> \
					<h3>' + member.name + '</h3> \
					<div class="profile">' + member.bio + '</div>';
			
			if ( ! direct) {
				html += '<a href="#" class="btn_back_team">&laquo; Back to team</a>';
			}
			
			html += '</li>';
			
			// Hide the team list
			$teamList.hide();

			$memberBio
				.html(html)
				.show();
		}
	}
	
	
	if ($('.portfolio_list').length) {
	  function changePortfolioSort(id) {
	    var tid = '#'+ id;
		var filterClass = '';
		if ($('.filter_nav li.selected>a').length > 0) {
			filterClass = $('.filter_nav li.selected>a').attr('href').replace(/#/g, '');
		}
			
			$(tid).siblings().not('#compTitle').css('display', 'none');
			if ($(tid).hasClass('portfolio_list')) {
			  $(tid).siblings('.show').removeClass('show');
			  $('#compTitle').css('display', 'block');
			  $(tid).addClass('show');
			}
			if (!$(tid).hasClass(filterClass)) {
			  $('.filter_nav li.selected').removeClass('selected');
			  var sortReg = new RegExp(/sort_[A-Z0-9a-z_]+/);
			  firstSort = sortReg.exec($(tid).attr('class'))[0];
			  $('.filter_nav li>a[href="#'+ firstSort +'"]').eq(0).parent().addClass('selected');
			}
			$('#compTitle').empty().append($('.filter_nav li.selected a').eq(0).text());
			
			$(tid).css('display', 'block').parent().css('display','block');
		  if ($(tid).hasClass('company_profile')) {
		    $('#compTitle').css('display', 'none');
		    $a = $(tid).find('a.logo').eq(0);
		    if ($a.length) {
  			  var img = new Image();
  			  img.src = $a.attr('href');
  			  $a.replaceWith(img);
  			}
		  }
			
	  }
	  
	  $.address.init(function(event) {
	    $('#compTitle').empty().append($('.filter_nav li.selected a').eq(0).text());
      }).change(function(event) {
        $.log('Address: ' + event.value);
        var url = event.value.replace(/^\//, '');
        if (url != '' && url != '/') {
          $.log(url);
          changePortfolioSort(url.replace('/', ''));
        }
        return false;
    });
    
    
		$(".portfolio_list>li>a").each(function(){
			$(this).bind('click', function () {
			  $.address.value($(this).attr('href').replace(/#/g, ''));
			  return false;
			});
		});
		
		$('a.portfolio_back').bind('click', function(){
      $.address.value($('.portfolio_list').filter('.show').eq(0).attr('id'));
		  return false;
		});
	
		$('.filter_nav a').click(function(e) {
			var hash = $(this).attr('href');
			
			$('.filter_nav li').removeClass('selected');
			$(this).parent().addClass('selected');
			
			$.address.value(hash.replace(/#/g, ''));
			return false;
		});
	
	} // End $('.portfolio_list').length
	
	
	//Videos
	var playerConfig = {
    "canvas" : {
      "backgroundColor": "#000000"
    },
    "playlist" : [{ 
      "url": '',
      "autoPlay": "false", 
      "autoBuffering": "true" 
    }]
  };
  
  
  if ($('a.video').length) {
    $('body').append($('<div id="portfolioVideo"></div>').css('display', 'none').css('width', '640px').css('height', '360px'));
    $.getScript('js/jquery.simplemodal.1.4.1.min.js', function(){ $.getScript('js/flowplayer-3.2.4.min.js', bindVideoLinks)});
  }
  
  function bindVideoLinks() {
     $('a.video').bind('click', function(){
        $('#portfolioVideo').empty();
        var vpath = window.location.href;
        vpath = vpath.split('/');
        vpath.pop();
        $.log('vpath' + vpath);
        playerConfig.playlist[0].url = vpath.join('/') + '/' + $(this).attr('href');
        $.log(playerConfig.playlist[0].url);
        $.modal($('#portfolioVideo'), {
              "overlayCss": {
                "background-color": "#666666",
                 "opacity": .95
              },
              "overlayClose" : true,
              "onOpen": function(dialog) {
                dialog.overlay.css('opacity', 0).css("display", "block").animate({opacity: ".65"}, 500, function () {
                		dialog.container.add(dialog.data).fadeIn('slow', function () {
                		  flowplayer('portfolioVideo', {src: 'js/flowplayer-3.2.5.swf', wmode: 'opaque'}, playerConfig);
                		});
                	});
              },
              "onClose": function(dialog) {
                dialog.overlay.add(dialog.container).fadeOut('slow', function(){
                  $.modal.close();
                });
              }
        });
      return false;
      });
  }
  
});
