$(document).ready(function () {
  $('#profilePlaylistSearchTerm').watermark('Search');
  
  /*
  $.fn.input = function() {
    return this.focus(function() {
    	if( this.value == this.defaultValue ) {
    		this.value = '';
    	}
    }).blur(function() {
    	if(isEmpty(this.value)) {
    		this.value = this.defaultValue;
    	}
    });
  };*/
  jQuery.fn.input = function () {
    var strType = '';
    
    return this.each(function () {
      if (this.type == 'password') {
        strType = this.type;
        this.type = 'text';
      }
    }).focus(function () {
      if (strType == 'password') {
        this.type = 'password';
      }
      if (this.value == this.defaultValue)
        this.value = '';
    }).blur(function () {
      if (isEmpty(this.value)) {
        if (this.type == 'password') {
          this.type = 'text';
        }
        this.value = this.defaultValue;
      }
    });
  };
  
  //Add song to play list from the player view
  $('#globalPlayerAddToPlayListLink').live('click', function () {
    $('#globalPlayerAddToPlaylist').show();
    
    return false;
  });
  
  //Show the playlists that you can add to from the player view
  $('#globalPlayerShowAddToPlaylists').hover(function () {
    $('#globalPlayerAddToPlaylistArea').show();
    $('#globalPlayerLoadingAddToPlayList').show();
    
    $.ajax({
      type: 'POST',
      dataType: 'json',
      cache: false,
      url: 'ajax/ajax.getPlaylists.php',
      success: function (json) {
        var html = '';
        for(j in json)
          html += '<div class="row globalPlayerAddToPlaylistFromSelect" id="'+json[j].id+'">'+json[j].name+'</div>';
        
        $('#globalPlayerLoadingAddToPlayList').hide();
        $('#globalPlayerAddToPlaylistSelect').html(html);
      }
    });
  }, function () {
    $('#globalPlayerAddToPlaylistArea').hide();
    $('#globalPlayerAddToPlaylistSelect').empty();
  });
  
  //Close add to play list DIV
  $('#globalPlayerCancelAddToPlaylist').live('click', function () {
    $(this).parent().parent().hide();
    $('#globalPlayerNewPlaylistName').val('');
  });
  
  $('.globalPlayerAddToPlaylistFromSelect').live('click', function () {
    var songID = $(':hidden#globalPlayerCurrentSongID').val();
    var playListID = this.id;
    
    if (!isNaN(songID) && !isNaN(playListID)) {
      $.ajax({
          type: 'POST',
          data: 'songID=' +songID+ '&playListID=' +playListID,
          cache: false,
          url: 'ajax/ajax.addToPlaylist.php',
          success: function (html) {
            if (html == 1) {
              $('#globalPlayerAddToPlaylist').hide();
              $('#globalPlayerNewPlaylistName').val('');
            }
          }
        });
    }
    return false;
  });
  
  //Create new play list from player view
  $('#globalPlayerCreateNewPlaylist').live('submit', function () {
    var songID = $(':hidden#globalPlayerCurrentSongID').val();
    var playListName = encodeURIComponent($(this).find('#globalPlayerNewPlaylistName').val());
    var current = $(this);
    
    if (!isEmpty(playListName) && !isNaN(songID)) {
      $.ajax({
        type: 'POST',
        data: 'songID=' +songID+ '&playListName=' +playListName,
        cache: false,
        url: 'ajax/ajax.createPlaylist.php',
        success: function (libraryID) {
          if (libraryID != 0) {
            playListName = decodeURIComponent(playListName);
            $('#globalPlayerPlayListHolder').text(playListName);
            $('#globalPlayerNewPlaylistName').val('');
            $(':hidden#globalPlayerCurrentLibrary').val(libraryID);
            init_player_set_playlist('' +songID+ '');
            current.parent().hide();
          }
        }
      });
    }
    return false;
  });
  
  //Show play list from the player
  $('#player_drop_down_playlist_link').hover(function () {
    $('#player_drop_down_playlist').show();
    $('#globalPlayerLoadingPlayList').show();
    
    $.ajax({
      type: 'POST',
      dataType: 'json',
      cache: false,
      url: 'ajax/ajax.getPlaylists.php',
      success: function (json) {
        var html = '';
        for(j in json)
          html += '<div class="row ajaxGlobalPlaylist" id="'+json[j].id+'">'+json[j].name+'</div>';
        
        $('#globalPlayerLoadingPlayList').hide();
        $('#globalPlayerAjaxAllPlaylists').html(html);
      }
    });
  }, function () {
    $('#player_drop_down_playlist').hide();
    $('#globalPlayerAjaxAllPlaylists').empty();
  });
  
  //Select play list from the global player
  $('.ajaxGlobalPlaylist').live('click', function () {
    var playListID = this.id;
    var playListName = $(this).text();
    
    if (!isNaN(playListID)) {
      $('#globalPlayerPlayListHolder').text(playListName);
      $(':hidden#globalPlayerCurrentLibrary').val(playListID);
      
      $.ajax({
        type: 'POST',
        data: 'playlistID=' +playListID,
        cache: false,
        url: 'ajax/ajax.getPlaylist.php',
        success: function (html) {
          if (html != 0) {
            init_player_set_playlist('' +html+ '');
            //init_player_items('' +html+ '');
            $('#player_drop_down_playlist').hide();
          }
        }
      });
    }
    return false;
  });
  
  //Add song to play list from a page
  $('.ajaxAddToPlayList').live('click', function () {
    var songID = this.id;
    var playListID = $(':hidden#globalPlayerCurrentLibrary').val();
    var addToPlaylistButton = $(this);
    
    
    if (!isNaN(songID) && !isNaN(playListID)) {
      $.ajax({
        type: 'POST',
        data: 'songID=' +songID+ '&playListID=' +playListID,
        cache: false,
        url: 'ajax/ajax.addToPlaylist.php',
        success: function (html) {
          if (html == 1) {
            addToPlaylistButton.unbind('click').removeClass('addToPlayList').addClass('addedToPlayList');
            $('#ajaxAddToPlayListTxt-' +songID).addClass('globalHidden');
            $('#ajaxAddedToPlayListTxt-' +songID).removeClass('globalHidden');
          }
        }
      });
    }
    return false;
  });
  
  //Become a fan
  $('.ajaxBecomeAFan').live('click', function () {
    var celebID = this.id;
    
    if (!isNaN(celebID)) {
      $.ajax({
        type: 'POST',
        data: 'celebID=' +celebID,
        cache: false,
        url: 'ajax/ajax.becomeAFan.php',
        success: function (html) {
          if (html == 1) {
            location.reload(true);
          }
        }
      });
    }
  });
  
  $('#liveFeedOlderPosts').live('click', function () {
    var currentIteration = $(this).parent().attr('id');
    var divParent = $(this).parent();
    
    if (!isNaN(currentIteration)) {
      $.ajax({
        type: 'POST',
        data: 'limit=' +currentIteration,
        cache: false,
        url: 'ajax/ajax.getFeed.php',
        success: function (html) {
          if (!isEmpty(html)) {
            divParent.before(html);
            divParent.attr('id', currentIteration + 50);
          }
          else
            divParent.hide();
        }
      });
    }
    return false;
  });
  
  //Toggle the container to allow the user to create a new playlist
  $('#profileNewPlaylistCreator').live('click', function () {
    $('#profileNewPlaylistCreatorContainer').toggle();
  })
  
  //Handle the event to create a new play list from the profile section
  $('#profilePlaylistCreateNewPlaylist').live('submit', function () {
    var strForm = $(this).serialize();
    var playListName = $(this).find('#profilePlaylistNewPlaylistName');
    
    if (!isEmpty(playListName.val())) {
      $.ajax({
        type: 'POST',
        data: strForm,
        cache: false,
        url: 'ajax/ajax.createEmptyPlaylist.php',
        success: function (html) {
          if (html != 0) {
            $('#profileNewPlaylistCreatorContainer').toggle();
            $('#profileAllPlaylistsNav').append(html);
          }
        }
      });
    }
    return false;
  });
  
  //Delete a play list from the profile - playlist section
  $('.profilePlaylistRemoveButton').live('click', function () {
    var playListID = $(this).attr('id');
    
    if (!isNaN(playListID)) {
      var deleteConfirm = confirm('Are you sure you want to delete this Playlist?');
      
      if (deleteConfirm) {
        $.ajax({
          type: 'POST',
          data: 'playListID=' +playListID,
          cache: false,
          url: 'ajax/ajax.deletePlaylist.php',
          success: function (userID) {
            if (userID !== 0) {
              window.location = 'http://www.newartist.com/profile.php?id='+userID+'&ref=playlists'
            }
          }
        });
      }
    }
    return false;
  });
  
  
  $('#profileMusicDeleteAction').live('click', function () {
    var songID = $(this).find('a').attr('id');
    var parentDIV = $(this).parent().parent().parent();
    
    if (!isNaN(songID)) {
      var deleteConfirm = confirm('Are you sure you want to delete this song?');
      
      if (deleteConfirm) {
        $.ajax({
          type: 'POST',
          data: 'songID=' +songID,
          cache: false,
          url: 'ajax/ajax.deleteSong.php',
          success: function (response) {
            if (response == 1) {
              parentDIV.fadeOut();
            }
          }
        });
      }
    }
    return false;
  });
  
  //Show the container to change out song from the Music area in the profile
  $('#profileMusicEditAction').live('click', function () {
    var parentDIV = $(this).parent().parent();
    var hiddenContainer = parentDIV.find('#jsHiddenSongChangeContainer');
    var currentSongNameContainer = parentDIV.find('#ajaxSongName');
    
    currentSongNameContainer.hide();
    hiddenContainer.removeClass('globalHidden');
    
    return false;
  });
  
  
  $('#ajaxChangeSongName').live('submit', function () {
    var strForm = $(this).serialize();
    var songName = $(this).find('#jsNewSongName');
    var hiddenContainer = $(this).parent().parent().parent().find('#jsHiddenSongChangeContainer');
    var currentSongNameContainer = $(this).parent().parent().find('#ajaxSongName');
    
    if (!isEmpty(songName.val())) {
      hiddenContainer.addClass('globalHidden');
      currentSongNameContainer.val(songName.val());
      currentSongNameContainer.show();
      
      /*
      $.ajax({
        type: 'POST',
        data: strForm,
        cache: false,
        url: 'ajax/ajax.changeSongName.php',
        success: function (response) {
          if (response == 1) {
            parentDIV.fadeOut();
          }
        }
      });
    */
    }
    return false;
  });
  
  //$('.ajaxStarRating .jsStars').starRating();
  $('.ajaxVote').Vote();
  $('.ajaxRemoveVote').RemoveVote();
});

function isEmpty(str) {
  var strText = String(str).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  
  if (strText == '')
    return true;
  else
    return false;
}

function isEmail(str) {
 var emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
 
 if (emailReg.test(String(str)))
  return true;
 else
  return false; 
}

function showDialog (id) {
  $('#globalShadow').show();
  $('#ajaxLoading').show();
  $('#dialogBox').fadeIn('fast');
  $.ajax({
    type: 'POST',
    url: 'ajax/ajax.Dialog.php',
    data: 'id=' + id,
    cache: false,
    success: function (html) {
      $('#ajaxLoading').fadeOut();
      $('#DOM_Control_dialog').html(html);
    }
  });
}

function closeDialog() {
  $('#dialogBox').fadeOut('fast');
  $('#globalShadow').hide();
}

function addPlayList(songID) {
  $.ajax({
    type: 'POST',
    data: 'songID=' + songID, 
    url: 'ajax/ajax.addFavSong.php', 
    success: function () {
      $('#ajaxAddToPlayList-' + songID).removeAttr('onclick').css({'cursor' : 'default'});
      $('#ajaxAddToPlayList-' + songID).removeClass('artistsAddToPlayList').addClass('artistsAddedToPlayList');
      $('#ajaxAddToPlayListTxt-' + songID).hide();
      $('#ajaxAddedToPlayListTxt-' + songID).removeClass('globalHidden');  
    }
  });
}

/* Plugins */

/* Vote Plugin */
jQuery.fn.Vote = function () {
  $(this).live('click', function () {
    var songID = $(this).attr('id');
    var current = $(this).parent();
    
    current.hide();
    
    if (!isNaN(songID)) {
    $.ajax({
      type: 'POST',
      data: 'songID=' +songID, 
      url: 'ajax/ajax.Vote.php', 
      success: function (html) {
        if (html != 0) {
          $('.ajaxVote-'+songID).parent()
                                .show()
                                .html(html)
        }
      }
      });
    }
    return false;
  });
};

/* Remove Vote Plugin */
jQuery.fn.RemoveVote = function () {
  $(this).live('click', function () {
    var songID = $(this).attr('id');
    var current = $(this).parent();
    
    current.hide();
    
    if (!isNaN(songID)) {
    $.ajax({
      type: 'POST',
      data: 'songID=' +songID, 
      url: 'ajax/ajax.removeVote.php', 
      success: function (html) {
        if (html != 0) {
          $('.ajaxVoted-'+songID).parent()
                                 .show()
                                 .html(html)
        }
      }
      });
    }
    return false;
  });
};


jQuery.fn.autoExpand = function () {
  $(this).live('focus blur', function (event) {
    var html = $(this).val().split('\n');
    var self = this;
    var b = 1;
    
    if (event == 'focus') {
      for(x = 0; x < html.length; x++)
        if (html[x].length >= self.cols)
          b += math.floor(html[x].length / self.cols);
      
      b += html.length;
      if (b > self.rows)
        self.rows = b;
    }
    else {
      
    }
    
  });
};