/**
 * reports a broken link
 * 
 * @param int station
 * @return void
 */
function reportBrokenLink(station, successMsg, link) {
	$.ajax({
		type: 'post',
		url: '/ajax.html',
		dataType: 'json',
		data: {
			action: 'report-broken-link',
			station: station
		},
		success: function (response) {
			if (response.success) {
				$(link).fadeOut(150, function () {
					$(this).replaceWith(
						$('<span class="msg" />').html(successMsg)
					);
				});
			}
		}
	});
}

/**
 * Adds a comment 
 * 
 * @param int station
 * @return void
 */
function addComment(button) {
	var form = $(button).parents('form'),
		params = $(form).serializeArray(),
		errors = [];
	
	// simple validation
	$('.form-row', form).removeClass('error');
	$.each(params, function (i, param) {
		switch (param.name) {
			case 'station':
			case 'title':
			case 'text':
				if ($.trim(param.value).length == 0) {
					errors.push(param);
					$('*[name="' + param.name + '"]', form).parents('.form-row').addClass('error');
				}
				break;
		}
	});
	
	// submit
	if (errors.length === 0) {
		params.push({
			name: 'action',
			value: 'add-comment'
		});
		
		$.ajax({
			type: 'post',
			url: '/ajax.html',
			dataType: 'json',
			data: params,
			success: function (response) {
				$(form).html(response.msg);
			}
		});
	}
}


/**
 * Toggle the add-comment-form
 * 
 * @return void
 */
function displayAddComment() {
	$('#add-comment-wrapper').toggle('fast');
}


/**
 * 
 * 
 * @param int station
 * @return void
 */
function addToFavorites(station, successMsg, link) {
	$.ajax({
		type: 'post',
		url: '/ajax.html',
		dataType: 'json',
		data: {
			action: 'add-to-favorites',
			station: station
		},
		success: function (response) {
			if (response.success) {
				$(link).fadeOut(150, function () {
					$(this).replaceWith(
						$('<span class="msg" />').html(successMsg)
					);
				});
			}
		}
	});
}


/**
 * 
 * 
 * @param int station
 * @return void
 */
function removeFromFavorites(station, successMsg, link) {
	$.ajax({
		type: 'post',
		url: '/ajax.html',
		dataType: 'json',
		data: {
			action: 'remove-from-favorites',
			station: station
		},
		success: function (response) {
			if (response.success) {
				$(link).fadeOut(150, function () {
					$(this).replaceWith(
						$('<span class="msg" />').html(successMsg)
					);
				});
			}
		}
	});
}

/**
 * document.load
 */
$(function () {
  var searchTrie = new Trie, injectPlayer, start, stop;
  
  /**
   * Injects the player
   */
  injectPlayer = function (urls, timeout, error) {
    var url = urls.shift(), fallback;
    
    if (urls.length > 0) {
      fallback = setTimeout(function () {
        injectPlayer(urls, timeout);
      }, timeout);
    }
    else if (typeof error === 'function') {
      fallback = setTimeout(error, timeout);
    }
    
    jwplayer('player').setup({
      flashplayer: '/assets/components/mediaplayer/player.swf',
      file: url,
      height: 1,
      width: 1,
      autostart: true,
      provider: 'sound',
      controlbar: 'none',
      allowscriptaccess: 'allways',
      events: {
        onTime: function (evt) {
          if (fallback) {
            clearTimeout(fallback);
          }
        }
      }
    });
  };
  
  /**
   * start
   */
  start = function () {
    var self = this;
    
    $('a.stream-player').removeClass('playing').removeClass('other-playing');
    $(this).addClass('playing');
    $('a.stream-player').not(this).addClass('other-playing');
    injectPlayer([
      $(this).data('stream-url')
      , $(this).data('stream-url') + '/;'
    ], 2500, function () {
      stop.call(self);
    });
  };
  
  /**
   * stop
   */
  stop = function () {
    $('a.stream-player').removeClass('playing').removeClass('other-playing');
    jwplayer().stop();
  };
  
  
  /**
   * bind onclick handler
   */
  $('a.stream-player').bind('click', function () {
    // stop
    if ($(this).is('.playing')) {
      stop.call(this);
    }
    
    // start playing
    else {
      start.call(this);
    }
  });
  
  // activate placeholder inputs
  $('[data-placeholder]').on({
    focus: function (evt) {
      if ($(this).hasClass('is-placeholder')) {
        $(this).val('');
        $(this).removeClass('is-placeholder');
      }
    },
    blur: function (evt) {
      if ($(this).val() === '') {
        $(this).val($(this).data('placeholder'));
        $(this).addClass('is-placeholder');
      }
      
      $('#suggestions').hide();
    }
  });
  
  // init trie
  $.each(trieElements, function (i, string) {
    searchTrie.add(String(string));
  });
  
  $('#search').on({
    keyup: function () {
      var newVal = $(this).val(), result, max = 10;
      if (newVal.length > 0) {
        $('#suggestions').html('');
  
        result = searchTrie.get(newVal);
        if (result) {
          $.each(result, function (key) {
            $('<a class="suggestion" />').html(
              key.replace(new RegExp('^' + newVal), '<b>' + newVal + '</b>')
            ).appendTo('#suggestions').on({
              mousedown: function () {
                $('#search').val(key);
              }
            });
  
            if (max-- <= 0) {
                return false;
            }
          });
        }
      }
  
      $('#suggestions:hidden').show();
    }
  });
  
  // activate tags
  $('.tag-string').each(function () {
    $(this).html($(this).text().split(',').map(function (val, idx) {
      return '<span>' + $.trim(val) + '</span>';
    }).join(', '));
  });
  
  $('.tag-string').on('click', 'span', function (evt) {
    $('#search').val($(this).text());
    $('#search').closest('form').submit();
  });
});
