/**
 * Common utility functions.
 */
(function (context, $) {

  "use strict";

  context.JK = context.JK || {};
  var profileUtils = {};
  context.JK.ProfileUtils = profileUtils;

  // genre types
  var PROFILE_GENRE_TYPE = 'profile';
  var VIRTUAL_BAND_GENRE_TYPE = 'virtual_band';
  var TRADITIONAL_BAND_GENRE_TYPE = 'traditional_band';
  var PAID_SESSION_GENRE_TYPE = 'paid_sessions';
  var FREE_SESSION_GENRE_TYPE = 'free_sessions';
  var COWRITING_GENRE_TYPE = 'cowriting';

  var NOT_SPECIFIED_TEXT = 'Not specified';

  profileUtils.NOT_SPECIFIED_TEXT = NOT_SPECIFIED_TEXT

  var proficiencyDescriptionMap = {
    "1": "BEGINNER",
    "2": "INTERMEDIATE",
    "3": "EXPERT"
  };

  var proficiencyCssMap = {
    "1": "proficiency-beginner",
    "2": "proficiency-intermediate",
    "3": "proficiency-expert"
  };


  // performance sample types
  profileUtils.SAMPLE_TYPES = {
    JAMKAZAM: {description: "jamkazam"},
    SOUNDCLOUD: {description: "soundcloud"},
    YOUTUBE: {description: "youtube"}
  };

  // online presence types
  profileUtils.ONLINE_PRESENCE_TYPES = {
    SOUNDCLOUD: {description: "soundcloud"},
    REVERBNATION: {description: "reverbnation"},
    BANDCAMP: {description: "bandcamp"},
    FANDALISM: {description: "fandalism"},
    YOUTUBE: {description: "youtube"},
    FACEBOOK: {description: "facebook"},
    TWITTER: {description: "twitter"}
  };

  var USER_TYPE = 'JamRuby::User';

  profileUtils.skillLevelMap = {
    "1": "Amateur",
    "2": "Professional"
  };

  profileUtils.gigMap = {
    "": "Not specified",
    "0": "0",
    "1": "under 10",
    "2": "10 to 50",
    "3": "50 to 100",
    "4": "over 100"
  };

  profileUtils.studioMap = {
    "" : 'Not specified',
    "0": "0",
    "1": "under 10",
    "2": "10 to 50",
    "3": "50 to 100",
    "4": "over 100"
  };

  profileUtils.cowritingPurposeMap = {
    "1": "just for fun",
    "2": "sell music"
  };

  profileUtils.bandCommitmentMap = {
    "1": "infrequent",
    "2": "once a week",
    "3": "2-3 times a week",
    "4": "4+ times a week"
  }

  function buildGenreList(genres) {
    var list = '';

    for (var i=0; i < genres.length; i++) {
      list = list.concat(genres[i].genre_id);
      if (i !== genres.length - 1) {
        list = list.concat(', ');
      }
    }

    return list;
  }


  profileUtils.getGenreIds = function(genres) {
    var list = []

    for (var i=0; i < genres.length; i++) {
      list.push(genres[i].genre_id);
    }

    return list;
  }

  // the server stores money in cents; display it as such
  profileUtils.normalizeMoneyForDisplay = function(serverValue) {
    if (!serverValue || serverValue==="") {
      // Blank value is valid:
      return ""
    }
    if(serverValue || serverValue == 0) {
      return (new Number(serverValue) / 100).toFixed(2)
    }
    else {
      return 0;
    }
  }

  // the server stores money in cents; normalize it from what user entered
  profileUtils.normalizeMoneyForSubmit = function(clientValue) {
    if (!clientValue || clientValue==="") {
      // Blank value is valid:
      return ""
    }

    clientValue = clientValue.trim()
    // remove leading $ if present
    if (clientValue.indexOf('$') == 0) {
      clientValue = clientValue.substring(1)
    }

    var money = new Number(clientValue);

    if(!context._.isNaN(money)) {
      money = Math.round(money * 100)
    }
    else {
      // restore original value to allow server to reject with validation error
      money = '';
    }
    return money;
  }


  // Initialize standard profile help bubbles (topics stored as attributes on element):
  profileUtils.initializeHelpBubbles = function(parentElement) {
    $(".help", parentElement).each(function( index ) {
      context.JK.helpBubble($(this), $(this).attr("help-topic"), {}, {})
    })
  }

  // profile genres
  profileUtils.profileGenres = function(genres) {
    var matches = $.grep(genres, function(g) {
      return g.player_type === USER_TYPE && g.genre_type === PROFILE_GENRE_TYPE;
    });

    return matches;
  }

  profileUtils.profileGenreList = function(genres) {
    var matches = profileUtils.profileGenres(genres);
    return buildGenreList(matches);
  }

  // virtual band genres
  profileUtils.virtualBandGenres = function(genres) {
    var matches = [];
    if (genres) {
      matches = $.grep(genres, function(g) {
        return g.player_type === USER_TYPE && g.genre_type === VIRTUAL_BAND_GENRE_TYPE;
      });
    }

    return matches;
  }

  profileUtils.virtualBandGenreList = function(genres) {
    var matches = profileUtils.virtualBandGenres(genres);
    return buildGenreList(matches);
  }

  // traditional band genres
  profileUtils.traditionalBandGenres = function(genres) {
    var matches = [];
    if (genres) {
      matches = $.grep(genres, function(g) {
        return g.player_type === USER_TYPE && g.genre_type === TRADITIONAL_BAND_GENRE_TYPE;
      });
    }

    return matches;
  }

  profileUtils.traditionalBandGenreList = function(genres) {
    var matches = profileUtils.traditionalBandGenres(genres);
    return buildGenreList(matches);
  }

  // paid session genres
  profileUtils.paidSessionGenres = function(genres) {
    var matches = [];
    if (genres) {
      matches = $.grep(genres, function(g) {
        return g.player_type === USER_TYPE && g.genre_type === PAID_SESSION_GENRE_TYPE;
      });
    }

    return matches;
  }

  profileUtils.paidSessionGenreList = function(genres) {
    var matches = profileUtils.paidSessionGenres(genres);
    return buildGenreList(matches);
  }

  // free session genres
  profileUtils.freeSessionGenres = function(genres) {
    var matches = [];
    if (genres) {
      matches = $.grep(genres, function(g) {
        return g.player_type === USER_TYPE && g.genre_type === FREE_SESSION_GENRE_TYPE;
      });
    }

    return matches;
  }

  profileUtils.freeSessionGenreList = function(genres) {
    var matches = profileUtils.freeSessionGenres(genres);
    return buildGenreList(matches);
  }

  // cowriting genres
  profileUtils.cowritingGenres = function(genres) {
    var matches = [];
    if (genres) {
      matches = $.grep(genres, function(g) {
        return g.player_type === USER_TYPE && g.genre_type === COWRITING_GENRE_TYPE;
      });
    }

    return matches;
  }

  profileUtils.cowritingGenreList = function(genres) {
    var matches = profileUtils.cowritingGenres(genres);
    return buildGenreList(matches);
  }

  profileUtils.jamkazamSamples = function(samples) {
    var matches = $.grep(samples, function(s) {
      return s.service_type === profileUtils.SAMPLE_TYPES.JAMKAZAM.description;
    });

    return matches;
  }

  profileUtils.soundCloudSamples = function(samples) {
    var matches = $.grep(samples, function(s) {
      return s.service_type === profileUtils.SAMPLE_TYPES.SOUNDCLOUD.description;
    });

    return matches;
  }

  profileUtils.youTubeSamples = function(samples) {
    var matches = $.grep(samples, function(s) {
      return s.service_type === profileUtils.SAMPLE_TYPES.YOUTUBE.description;
    });

    return matches;
  }

  profileUtils.soundCloudPresences = function(presences) {
    var matches = $.grep(presences, function(p) {
      return p.service_type === profileUtils.ONLINE_PRESENCE_TYPES.SOUNDCLOUD.description;
    });

    return matches;
  }

  profileUtils.reverbNationPresences = function(presences) {
    var matches = $.grep(presences, function(p) {
      return p.service_type === profileUtils.ONLINE_PRESENCE_TYPES.REVERBNATION.description;
    });

    return matches;
  }

  profileUtils.bandCampPresences = function(presences) {
    var matches = $.grep(presences, function(p) {
      return p.service_type === profileUtils.ONLINE_PRESENCE_TYPES.BANDCAMP.description;
    });

    return matches;
  }

  profileUtils.fandalismPresences = function(presences) {
    var matches = $.grep(presences, function(p) {
      return p.service_type === profileUtils.ONLINE_PRESENCE_TYPES.FANDALISM.description;
    });

    return matches;
  }

  profileUtils.youTubePresences = function(presences) {
    var matches = $.grep(presences, function(p) {
      return p.service_type === profileUtils.ONLINE_PRESENCE_TYPES.YOUTUBE.description;
    });

    return matches;
  }

  profileUtils.facebookPresences = function(presences) {
    var matches = $.grep(presences, function(p) {
      return p.service_type === profileUtils.ONLINE_PRESENCE_TYPES.FACEBOOK.description;
    });

    return matches;
  }

  profileUtils.twitterPresences = function(presences) {
    var matches = $.grep(presences, function(p) {
      return p.service_type === profileUtils.ONLINE_PRESENCE_TYPES.TWITTER.description;
    });

    return matches;
  }

  // Render band instruments to a string:
  profileUtils.renderBandInstruments = function (band) {
    var msg = ""
    if (band.instruments) {
      for (var i = 0; i < band.instruments.length; i++) {
        var instrument = band.instruments[i]
        var description = instrument.instrument_id

        if (msg.length > 0) {
          msg += ", "
        }
        msg += instrument
        msg += "(" + proficiencyDescriptionMap[instrument.proficiency_level] + ")"
      }
    }
    if (msg.length==0) {
      msg = "None specified"
    }
    return msg
  }

  function formatTitle(title) {
    return title;
  }

  profileUtils.renderMusicalExperience = function(player, $root, isOwner) {
    var $instruments = $root.find('.instruments-holder');
    var $musicianStatus = $root.find('#musician-status');
    var $genres = $root.find('#genres');
    var $concertCount = $root.find('#concert-count');
    var $studioCount = $root.find('#studio-count');
    var $btnAddExperiences = $root.find('.add-experiences')

    $instruments.find('.profile-instrument').remove()

    if(isOwner) {
      $btnAddExperiences.show()
    }
    else {
      $btnAddExperiences.hide()
    }
    if (player.instruments) {
      for (var i = 0; i < player.instruments.length; i++) {
        var instrument = player.instruments[i];
        var description = instrument.instrument_id;
        var proficiency = instrument.proficiency_level;
        var instrument_icon_url = context.JK.getInstrumentIcon256(description);

        // add instrument info to layout
        var template = $('#template-profile-instruments').html();
        var instrumentHtml = context.JK.fillTemplate(template, {
          instrument_logo_url: instrument_icon_url,
          instrument_description: description,
          proficiency_level: proficiencyDescriptionMap[proficiency],
          proficiency_level_css: proficiencyCssMap[proficiency]
        });

        $instruments.append(instrumentHtml);
      }
    }

    // status
    var status = player.skill_level;
    $musicianStatus.html(status ? profileUtils.skillLevelMap[status] + ' musician' : NOT_SPECIFIED_TEXT)

    // genres
    $genres.empty();
    var profileGenres = profileUtils.profileGenreList(player.genres);
    $genres.append(profileGenres.length > 0 ? profileGenres : NOT_SPECIFIED_TEXT);

    // concert gigs
    var concertCount = player.concert_count;
    $concertCount.html(concertCount > 0 ? 'Has played ' + profileUtils.gigMap[concertCount] + ' live concert gigs' : 0);

    // studio gigs
    var studioCount = player.studio_session_count;
    $studioCount.html(studioCount > 0 ? 'Has played ' + profileUtils.gigMap[studioCount] + ' studio session gigs' : 0);

  }// function renderMusicalExperience

  profileUtils.renderPerformanceSamples = function(player, $root, isOwner) {
    // performance samples
    var performanceSamples = player.performance_samples;
    var $noSamples = $root.find('.no-samples');
    var $jamkazamSamples = $root.find('.jamkazam-samples');
    var $soundCloudSamples = $root.find('.soundcloud-samples');
    var $youTubeSamples = $root.find('.youtube-samples');
    var $btnAddRecordings = $root.find('.add-recordings');

    $jamkazamSamples.find('.playable').remove()
    $soundCloudSamples.find('.playable').remove()
    $youTubeSamples.find('.playable').remove()

    if (isOwner) {
      $btnAddRecordings.show();
    }
    else {
      $btnAddRecordings.hide();
    }
    if (!performanceSamples || performanceSamples.length === 0) {
      $noSamples.show()
      $jamkazamSamples.hide()
      $soundCloudSamples.hide()
      $youTubeSamples.hide()
    } else {
      $noSamples.hide();

      // show samples section
      var jamkazamSamples = profileUtils.jamkazamSamples(player.performance_samples);
      if (!jamkazamSamples || jamkazamSamples.length === 0) {
        $jamkazamSamples.hide()
      } else {
        $jamkazamSamples.show()
      }

      var soundCloudSamples = profileUtils.soundCloudSamples(player.performance_samples);
      if (!soundCloudSamples || soundCloudSamples.length === 0) {
        $soundCloudSamples.hide()
      } else {
        $soundCloudSamples.show()
      }

      var youTubeSamples = profileUtils.youTubeSamples(player.performance_samples);
      if (!youTubeSamples || youTubeSamples.length === 0) {
        $youTubeSamples.hide()
      } else {
        $youTubeSamples.show()
      }

      $.each(jamkazamSamples, function(index, sample) {
        $jamkazamSamples.append("<a class='jamkazam-playable playable' href='/recordings/" + sample.claimed_recording.id + "' rel='external'>" + formatTitle(sample.claimed_recording.name) + "</a>");
      });

      $.each(soundCloudSamples, function(index, sample) {
        $soundCloudSamples.append("<a class='sound-cloud-playable playable' href='' soundcloud_url='" + sample.url + "'>" + formatTitle(sample.description) + "</a>");
      });

      $.each(youTubeSamples, function(index, sample) {
        $youTubeSamples.append("<a class='youtube-playable playable' href='" + sample.url + "' rel='external'>" + formatTitle(sample.description) + "</a>");
      });
    }
  }// function renderPerformanceSamples

  profileUtils.renderOnlinePresence = function(player, $root, isOwner) {
    var $noOnlinePresence = $root.find('.no-online-presence');
    var $userWebsite = $root.find('.user-website');
    var $soundCloudPresence = $root.find('.soundcloud-presence');
    var $reverbNationPresence = $root.find('.reverbnation-presence');
    var $bandCampPresence = $root.find('.bandcamp-presence');
    var $fandalismPresence = $root.find('.fandalism-presence');
    var $youTubePresence = $root.find('.youtube-presence');
    var $facebookPresence = $root.find('.facebook-presence');
    var $twitterPresence = $root.find('.twitter-presence');
    var $btnAddSites = $root.find('.add-presences');


    if (isOwner) {
      $btnAddSites.show();
    } else {
      $btnAddSites.hide();
    }
    // online presences
    var onlinePresences = player.online_presences;
    if (onlinePresences.length == 0 && !player.website) {
      $noOnlinePresence.show()
      $userWebsite.hide()
      $soundCloudPresence.hide()
      $reverbNationPresence.hide()
      $bandCampPresence.hide()
      $fandalismPresence.hide()
      $youTubePresence.hide()
      $facebookPresence.hide()
      $twitterPresence.hide()
    } else {
      $noOnlinePresence.hide();

      if (player.website) {
        // make sure website is rooted
        var website = player.website;
        if(website.indexOf('http') == -1) {
          website = 'http://' + website;
        }
        $userWebsite.removeClass('hidden').show().find('a').attr('href', website)
      }
      else {
        $userWebsite.addClass('hidden').hide().find('a').attr('href', '')
      }

      var soundCloudPresences = profileUtils.soundCloudPresences(onlinePresences);
      if (soundCloudPresences && soundCloudPresences.length > 0) {
        $soundCloudPresence.find('a').attr('href', 'http://www.soundcloud.com/' + soundCloudPresences[0].username);
        $soundCloudPresence.show();
      } else {
        $soundCloudPresence.hide();
      }

      var reverbNationPresences = profileUtils.reverbNationPresences(onlinePresences);
      if (reverbNationPresences && reverbNationPresences.length > 0) {
        $reverbNationPresence.find('a').attr('href', 'http://www.reverbnation.com/' + reverbNationPresences[0].username);
        $reverbNationPresence.show();
      } else {
        $reverbNationPresence.hide();
      }

      var bandCampPresences = profileUtils.bandCampPresences(onlinePresences);
      if (bandCampPresences && bandCampPresences.length > 0) {
        $bandCampPresence.find('a').attr('href', 'http://' + bandCampPresences[0].username + '.bandcamp.com/');
        $bandCampPresence.show();
      } else {
        $bandCampPresence.hide();
      }

      var fandalismPresences = profileUtils.fandalismPresences(onlinePresences);
      if (fandalismPresences && fandalismPresences.length > 0) {
        $fandalismPresence.find('a').attr('href', 'http://www.fandalism.com/' + fandalismPresences[0].username);
        $fandalismPresence.show();
      } else {
        $fandalismPresence.hide();
      }

      var youTubePresences = profileUtils.youTubePresences(onlinePresences);
      if (youTubePresences && youTubePresences.length > 0) {
        $youTubePresence.find('a').attr('href', 'http://www.youtube.com/' + youTubePresences[0].username);
        $youTubePresence.show();
      } else {
        $youTubePresence.hide();
      }

      var facebookPresences = profileUtils.facebookPresences(onlinePresences);
      if (facebookPresences && facebookPresences.length > 0) {
        $facebookPresence.find('a').attr('href', 'http://www.facebook.com/' + facebookPresences[0].username);
        $facebookPresence.show();
      } else {
        $facebookPresence.hide();
      }

      var twitterPresences = profileUtils.twitterPresences(onlinePresences);
      if (twitterPresences && twitterPresences.length > 0) {
        $twitterPresence.find('a').attr('href', 'http://www.twitter.com/' + twitterPresences[0].username);
        $twitterPresence.show();
      } else {
        $twitterPresence.hide();
      }
    }
  }// function renderOnlinePresence
})(window, jQuery);