// Page Type (Graduate or MBA)
var pageType = "MBA";
// Array of all tags
var arrTags = [];
// Array of profile objects
var arrProfiles = []; 
// Search arrays
var arrRegion = [];
var arrEducation = [];
var arrField = [];


// Video profile object
var videoProfile = function()
{
    this.get_html = function()
    { 
        var strImage = (this.img_id && this.img_id != '') ? 'http://www.ubs.com/1/ShowImage/index?contentId=' + this.img_id : 'http://www.ubs.com/2/e/medlib/group/graduates/videos/profiles/profile_missing.gif';
        var txt = '<table border="0" cellpadding="0" cellspacing="0" id="UBSprofile_' + this.id  + '"><tr>' +
                  '<td valign="top"><img src="' + strImage  + '" width="70" alt=""  border="0"/></td>' +
                  '<td width="10">&nbsp;</td>' + '<td valign="top"><b>' + this.name + '</b><br/>' +
                  this.city + ', ' + this.business_group + '<br/>' + this.working_group + '<br/></td></tr></table>';
        return txt;
    }

}

// When DOM is ready..
$(document).ready(function() { 
  // Remove event trapping
  window.onresize = null;
  document.onmousemove = '';

  // Initialize containers
  $("#loadIcon").empty();
  $("#tagCloud").empty().hide();
  $("#tagMatch").empty().hide();

  // Load table
  $.ajax({
    type: "GET",
    url: "http://www.ubs.com/2/e/medlib/group/graduates/videos/profiles/profiles.xml",
    dataType: "xml",
    success: function(xml) {
      $(xml).find('profile').each(function(i)
      {
        // Only show certain profiles
        var tc_tags_arr = [];
        if( $(this).attr('profile') != 'Text' && $(this).attr('title') == pageType)
        {
          // Populate the tag array
          var tagTxt = '';
          var tc_tags_arr = [];
          $(this).find('tag').each(function() {              
            tagTxt = $.trim( $(this).text() );
            tc_tags_arr.push( tagTxt );
            arrTags.push( tagTxt );
          });

          // Populate filters
          arrRegion.push( $(this).attr('region') );
          arrEducation.push( $(this).attr('studied') );
          arrField.push( $(this).attr('working_group') );
        } 

        // Populate profiles
        arrProfiles.length = i;
        arrProfiles[i] = new videoProfile(); 
        arrProfiles[i].id = $(this).attr('id');
        arrProfiles[i].name = $(this).attr('name');
        arrProfiles[i].profile = $(this).attr('profile');
        arrProfiles[i].business_group = $(this).attr('business_group'); // unused
        arrProfiles[i].city = $(this).attr('city');
        arrProfiles[i].region = $(this).attr('region'); // unused
        arrProfiles[i].studied = $(this).attr('studied'); // unused
        arrProfiles[i].working_group = $(this).attr('working_group');
        arrProfiles[i].title = $(this).attr('title');
        arrProfiles[i].url = $(this).attr('url');
        arrProfiles[i].img_id = $(this).attr('img_id');
        arrProfiles[i].tags = tc_tags_arr;
        //arrProfiles[i].related = []; // unused
        //$(this).find('related_id').each(function(j) {
        //    arrProfiles[i].related.push( $(this).text() );
        //}); 

      }); // close each
      
      // Default action: show search
      populateTags('alpha'); 
      // No featured videos for MBA
      if(pageType == "Graduate") {
        showProfilesSearch('Profile', 'Video');
      } else {
        showProfilesSearch('', '');
      }
    },
    error: function(obj, str, exc){
      alert("Error: " + str);
    } 
  }); //close $.ajax 

  // Bind search behaviors
  bindProfileBrowse();
  bindSearchBoxes();  
  // No featured videos for MBA
  if(pageType == "Graduate") {
    bindSearchViewAll();
  } else {
    $("div.viewAll").empty();
  }

});


// Populate the tag cloud
var populateTags = function(sort)
{
  // Count duplicates
  var arrTagsDups = arrTags.duplicates();
  // Get counts of duplicate values
  var arrDups = arrTagsDups.array_flip();
  // Convert to regular array and sort
  var arrDupsSorted = toArrRevSort(arrDups);
  // Remove duplicates
  var arrTagsUniq = arrTags.unique();

  // Build the tag cloud
  if(sort == 'alpha') {
    bindPopularSort();
    removeClick( $("div.sortLinks span.alpha") );
    for(var i in arrTagsUniq) { 
      createTag( arrTagsUniq[i], arrTagsDups[arrTagsUniq[i]] );
    }
  }
  else if(sort == 'pop') {
    bindAlphaSort();
    removeClick( $("div.sortLinks span.popular") );
    for(var i=0; i<arrDupsSorted.length; i++) {
      // Loop through all tags which have 'i' dups
      for(var j in arrTagsDups) {
        if(arrTagsDups[j] == arrDupsSorted[i]) {
          createTag( j, arrTagsDups[j] );
        }
      }
    }
  }

  // Attach event behaviors
  bindTagBehaviors(); 
}


// Write a tag into the cloud
function createTag(tagName, numDups)
{
  var style = '';

  if(typeof tagName === 'string')
  { 
    if(numDups == 1) style = "r1";
    if(numDups == 2) style = "r2";
    if(numDups == 3) style = "r3";
    if(numDups == 4) style = "r4";
    if(numDups >= 5) style = "r5";

    // Replace spaces with &nbsp;
    tagName = tagName.replace(/ /g, "&nbsp;"); 

    $('<span class="' + style + '"><a>' + tagName + '</a>&nbsp;(' + numDups + ')</span><span> </span>').appendTo('#tagCloud'); 
  }
}


// Remove click handler from an element
var removeClick = function(o)
{
    o.css({ textDecoration:"none", cursor:"default" });
    o.unbind('click');
}


// Bind tag behaviors when cloud loaded
var bindTagBehaviors = function()
{
  // Add underline when mousing over tags
  $("#tagCloud span a").hover(
    function() {
      $(this).css({ textDecoration:"underline", cursor:"pointer" });
    }, 
    function() {
      $(this).css({ textDecoration:"none", cursor:"default" });
    }
  ); 

  $("#tagCloud span a").click(
    function() {
      // Show the profiles for this tag
      showProfiles( $(this).text() );
    });
}


// Bind profile behavior to play video
var bindProfileBehaviors = function()
{
  // Add underline and change cursor
  $("div.profile table").hover(
    function() {
      $(this).css({ textDecoration:"underline", cursor:"pointer" });
    }, 
    function() {
      $(this).css({ textDecoration:"none", cursor:"default" });
    }
  ); 

  $("div.profile table").click(
    function() {
      // Adjust the browser viewport
      self.scrollTo(0, 230);
      // Play the video
      var pid = $(this).attr('id').replace(/\w+_/, '');
      playID(pid);
    });

}


// Show profiles which match a tag
var showProfiles = function(tag)
{ 
    var pTxt = '';
    var spChar = unescape('%a0');
    while(tag.indexOf( spChar ) != -1) {
        tag = tag.replace(spChar, " ");
    }
    // Hide the tag cloud and sorting links
    $("div.sortLinks").fadeOut("fast");
    $("#tagCloud").fadeOut("fast");
    $("div.brAgain").remove();
    // Show the matching profiles
    $("#tagMatch").empty();
    $("#tagMatch").queue(
      function() { 
        $('<div class="brAgain"><span class="left">' + tag + ':</span>' +
          '<span class="right"><img src="http://www.ubs.com/2/e/medlib/group/graduates/videos/profiles/arrow_double_left.gif" alt=""/>&nbsp;&nbsp;<a>Browse again</a></span></div>'
          ).insertBefore('#tagMatch'); 
        for(var p=0; p<arrProfiles.length; p++)
        {
          for(var t=0; t<arrProfiles[p].tags.length; t++)
          {
            if( $.trim(arrProfiles[p].tags[t]) == tag ) {
              pTxt = arrProfiles[p].get_html();
              $('<div class="profile">' + pTxt + '</div>').appendTo('#tagMatch');
            }
          }
        }
        $('<br style="clear:both; float:none;"/>').appendTo('#tagMatch');
        $("div.brAgain a").click(hideProfiles);
        $(this).dequeue();
      }); 

    // Attach events
    bindProfileBehaviors();
    // Show the results
    $("#tagMatch").fadeIn("fast");
}


// Show profiles which match a search
var showProfilesSearch = function(searchType, searchCrit)
{ 
    var pTxt = '';
    var sField = '';
    // Show the matching profiles
    $("#tagMatch").empty();
    $("#tagMatch").queue(
      function()
      {      
        // Only show headline for initial load
        if(searchType == 'Profile' && searchCrit == 'Video') {
          $('<b>Feature portraits:</b><br/><br/>').appendTo('#tagMatch'); 
        } else {
          $('<br/><br/>').appendTo('#tagMatch'); 
        }
        // Show the profiles
        for(var p=0; p<arrProfiles.length; p++)
        {
          // Only show certain profiles
          if(arrProfiles[p].profile != 'Text' && arrProfiles[p].title == pageType) {
            // Filters
            if(searchType == 'Region') { sField = arrProfiles[p].region; }
            if(searchType == 'Education') { sField = arrProfiles[p].studied; }
            if(searchType == 'Field of Work') { sField = arrProfiles[p].working_group; }
            if(searchType == 'Profile') { sField = arrProfiles[p].profile; }
            if(searchCrit == '' || searchCrit == 'All' || sField == searchCrit ) { 
              pTxt = arrProfiles[p].get_html();
              $('<div class="profile">' + pTxt + '</div>').appendTo('#tagMatch');
            }
          }
        }
        $('<br class="clearfix"/>').appendTo('#tagMatch');
        $(this).dequeue();
      }
    );

    // Attach events
    bindProfileBehaviors();
    // Show the results
    $("#loadIcon").hide();
    $("#tagMatch").fadeIn("fast");
}


// Hide profiles and display the tag cloud again
var hideProfiles = function()
{
  $("div.brAgain").remove();
  $("#tagMatch").fadeOut("fast");
  $("div.sortLinks").fadeIn("fast");
  $("#tagCloud").fadeIn("fast");
}
 

// Activate alpha sort button
var bindAlphaSort = function()
{    
  // Add underline
  $("div.sortLinks span.alpha").css({ textDecoration:"underline", cursor:"pointer" }); 

  // Add click function
  $("div.sortLinks span.alpha").click(
    function() {
      $("#tagCloud").fadeOut("fast");
      $("#tagCloud").queue(
        function() { 
          $(this).empty();
          populateTags('alpha'); 
          $(this).fadeIn("fast");
          $(this).dequeue();
        });
    });
}


// Activate popularity sort button
var bindPopularSort = function()
{
  // Add underline
  $("div.sortLinks span.popular").css({ textDecoration:"underline", cursor:"pointer" }); 

  // Add click function
  $("div.sortLinks span.popular").click(
    function() {
      $("#tagCloud").fadeOut("fast");
      $("#tagCloud").queue(
        function() { 
          $(this).empty();
          populateTags('pop'); 
          $(this).fadeIn("fast");
          $(this).dequeue();
        });
    });
}


// Activate profile search button
var bindProfileSearch = function()
{
  // No featured videos for MBA
  if(pageType == "Graduate") {
    bindSearchViewAll();
  }
  // Add CSS
  $("div.innerButtons a.search").css({ cursor:"pointer" }); 
  // Add click function
  $("div.innerButtons a.search").click(
    function() {
      // Adjust images
      $("div.innerButtons a.search img").attr("src", "http://www.ubs.com/2/e/medlib/group/graduates/videos/profiles/btn_search_portraits_on.gif");
      $("div.innerButtons a.browse img").attr("src", "http://www.ubs.com/2/e/medlib/group/graduates/videos/profiles/btn_browse.gif");
      // Adjust layers
      $("div.brAgain").remove();
      $("div.sortLinks").fadeOut("fast");
      $("#tagCloud").fadeOut("fast");
      $("#searchControls").fadeIn("fast");
      // Show search controls and profiles
      // No featured videos for MBA
      if(pageType == "Graduate") {
        showProfilesSearch('Profile', 'Video');
      } else {
        showProfilesSearch('', '');
      }
      bindProfileBehaviors();
      bindProfileBrowse();
      removeClick( $("div.innerButtons a.search") );
    });
}


// Activate profile browse button
var bindProfileBrowse = function()
{
  // Add CSS
  $("div.innerButtons a.browse").css({ cursor:"pointer" }); 
  // Add click function
  $("div.innerButtons a.browse").click(
    function() {
      // Adjust images
      $("div.innerButtons a.search img").attr("src", "http://www.ubs.com/2/e/medlib/group/graduates/videos/profiles/btn_search_portraits.gif");
      $("div.innerButtons a.browse img").attr("src", "http://www.ubs.com/2/e/medlib/group/graduates/videos/profiles/btn_browse_on.gif");
      // Adjust layers
      $("#searchControls").fadeOut("fast");
      $("#tagMatch").fadeOut("fast");
      $("div.sortLinks").fadeIn("fast");
      $("#tagCloud").fadeIn("fast");
      bindProfileSearch();
      removeClick( $("div.innerButtons a.browse") );
    });
}


// Attach search "view all"
var bindSearchViewAll = function()
{
  $("div.viewAll").empty();
  $("div.viewAll").unbind('click'); 
  $('<span><img alt="" src="http://www.ubs.com/2/e/medlib/group/graduates/videos/profiles/arrow_right_blue_2.gif"/> View all profiles</span>').appendTo("div.viewAll");

  $("div.viewAll").hover(
    function() {
      $(this).css({ cursor:"pointer" });
    }, 
    function() {
      $(this).css({ cursor:"default" });
    }
  ); 

  $("div.viewAll").click(
    function() {
      $("#sel_sort_type").attr("selectedIndex", "0");
      $("#sel_sort_criteria").empty();
      showProfilesSearch('', '');
      bindSearchViewFeatured();
    });
}


// Attach search "view featured"
var bindSearchViewFeatured = function()
{
  $("div.viewAll").empty();
  $("div.viewAll").unbind('click'); 
  $('<span><img alt="" src="http://www.ubs.com/2/e/medlib/group/graduates/videos/profiles/arrow_right_blue_2.gif"/> View featured profiles</span>').appendTo("div.viewAll");

  $("div.viewAll").hover(
    function() {
      $(this).css({ cursor:"pointer" });
    }, 
    function() {
      $(this).css({ cursor:"default" });
    }
  ); 

  $("div.viewAll").click(
    function() {
      $("#sel_sort_type").attr("selectedIndex", "0");
      $("#sel_sort_criteria").empty();
      showProfilesSearch('Profile', 'Video');
      bindSearchViewAll();
    });
} 


// Attach the relational select box actions
var bindSearchBoxes = function()
{
  $("#sel_sort_type").change(
    function() {
      populateSearchBox2( this.value );
    });
  
  $("#sel_sort_btn").click(
    function() {
      showProfilesSearch( $("#sel_sort_type option:selected").text(), $("#sel_sort_criteria option:selected").text() );
    });
}


// Fill the second select box with values
var populateSearchBox2 = function(sortType)
{
  var arrTmp = [];
  // Clear select box
  $("#sel_sort_criteria").empty();
  if(sortType)
  {
    if(sortType == 'Region') { arrTmp = arrRegion.unique(); }
    if(sortType == 'Education') { arrTmp = arrEducation.unique(); }
    if(sortType == 'Field of Work') { arrTmp = arrField.unique(); }

    // Populate the box
    $('<option value="All">All</option>').appendTo("#sel_sort_criteria"); 
    for(var i in arrTmp) {
      if(typeof arrTmp[i] != 'function') {
        $('<option value="' + arrTmp[i] + '">' + arrTmp[i] + '</option>').appendTo("#sel_sort_criteria"); 
      }
    }
  }
}


// Display a string or simple array in an alert box
function dump_var( v ) {
  if(typeof v === 'string') {
    alert(v);
  } else {
    var txt='';
    for( var i in v ) {
      txt += '[' + i + '] = [' + v[i] + ']\n';
    }
    alert(txt);
  } 
} 


// Eliminate duplicate and blank entries from arrays, results alpha sorted (non destructive)
Array.prototype.unique = function()
{ 
  var mark = [];
  var aTemp = [];

  for(var i in this)
  { 
    //var indx = this[i]; --> if type does not matter 

    // create a unique index if type does matter
    var indx = this[i] + "_" + typeof(this[i]);
    
    // Eliminate duplicates or blanks
    if(mark[indx] || this[i] == "") {
      //delete this[i];
    } else {
      mark[indx] = this[i]; 
      aTemp.push(this[i]);
    }
  }

  aTemp.sort();
  return aTemp;
}


// Count duplicate entries in array, return associative array
Array.prototype.duplicates = function()
{
  var arrResults = [];

  for(var i in this)
  {
    if( this[i] && (typeof(this[i]) != 'function') )
    {
      arrResults.length++;
      if(arrResults[this[i]]) {
        arrResults[this[i]]++;
      } else {
        arrResults[this[i]] = 1;
      }
    }
  } 
  return arrResults;
}


// Convert assoc array to standard array and reverse sort
function toArrRevSort(arr)
{
    var aTmp = [];
    for(var i in arr) {
      aTmp.push(i);
    }
    return aTmp.sort(sortNumber).reverse();
}


// Fix JavaScript number sort
function sortNumber(a,b)
{
  return a - b;
} 


// Flip an associative array
Array.prototype.array_flip = function()
{
  var tmp_ar = {};
  for( var i in this )
    if( this[i] && (typeof(this[i]) != 'function') )
      tmp_ar[this[i]] = i;
  return tmp_ar;
}


// Check a date to see if it's in the past. Returns 1 for valid date, -1 for past date
Date.prototype.compare = function(eDate)
{
  // Date format: 2008-06-20
  var yr = eDate.substr(0,4);
  var mo = eDate.substr(5,2);
  var da = eDate.substr(8,2);

  // Make sure we have all components
  if(!yr || !mo || !da)
      return -1;

  // Compare dates
  if(yr < this.getFullYear() || (yr == this.getFullYear() && mo < this.getMonth()+1) ||
    (yr == this.getFullYear() && mo == this.getMonth()+1 && da < this.getDate()))
    return -1;
  else
    return 1;
}


