// ====================
// = Gloabl Variables =
// ====================
var current_project = null;

// =============
// = Functions =
// =============
function add_track_to_project(attributes){
  $('#select_project input[name=SID]').val(attributes.SID);
  $('#select_project input[name=TID]').val(attributes.TID);
  $('#select_project input[name=tracknum]').val(attributes.trknum);
  $('#select_project input[name=cdnum]').val(attributes.cdnum);
  select_project_overlay.load();
}

function download_project_url(){
  var options = {PID:current_project.id, CID:current_user.id, action:"downloadGSUBTYPE"}
  var url = $.param.querystring("http://musicboxmx.com/serverMP3/pdownload.php", options)
  return url
}

function send_new_project(url, item){
  $.ajax({
    url:url,
    beforeSend:function(){if(item){item.find('.loading').fadeIn()}},
    success:function(xml){
      var error = $(xml).find('error:first');
      switch(error.attr('num')){
        case '0':
          var project = new Project($(xml).find('p:first'));
          current_user.projects.push(project);
          current_project = project;
          load_projects();
          new_project_overlay.close();
          duplicate_project_overlay.close();
          break;
        default:
          alert(error.attr('msg'));
          break;
      }
    },
    error:function(response, status, error){alert(error)},
    complete:function(){if(item){item.find('.loading').fadeOut()}}
  });
}

function load_projects(){
  var options = {action:"ProjectListing", UserLabel:'guest', len:0, userID:get_user_id()};
  var url = $.param.querystring("/import/projects.php", options);
  $.ajax({
    url: url,
    beforeSend: function(){$('#projects ul.projects li ul').append("<li style='border: 0px'><img src='images/loading.png' style='' /> LOADING YOUR PROJECTS...</li>")},
    success: function(data){
      current_user.projects_xml = $(data);
      $('#projects ul.projects li:first ul, #select_project ul').html('');
      $(data).find('p').each(function(){
        var project = new Project($(this));
        current_user.projects.push(project);
        $('#projects ul.projects li:first ul').append(
          "<li class='load_project' id='" + project.id + "_project'>" + project.title + "</li>"
        );
        $('#select_project ul').append(
          "<li><a class='add' id='" + project.id + "_project'>" + project.title + "</a></li>"
        );
      });
    },
    error: function(response, status, error){alert(error)},
    complete: function(){load_project()}
  });
}

function clear_projects(){
  $('#projects ul.projects li:first ul, #select_project ul, #projects ul.current_project, #projects .title').html('');
}

function load_project(id){
  if(!id && !current_project){
    clear_project();
    $('#projects .tracks .title:first').text("SELECT A PROJECT");
    $('#projects .options .description:first').text("SELECT A PROJECT");
    return false;
  }else if(id){
    var pid = id;
  }else if(current_project){
    var pid = current_project.id;
  }else{
    alert('invalid state in load_project');
  }
  current_project = new Project(current_user.projects_xml.find('p[pid=' + pid + ']:first'));
  // project display
  $('#projects .tracks .title:first').text(current_project.title || '');
  $('#projects .options .description:first').text(current_project.description);
  
  // edit form
  $('#edit_project input[name=title]').val(current_project.title);
  $('#edit_project textarea[name=desc]').val(current_project.description);
  
  clear_project();
  $.each(current_project.pTracks, function(){
    add_to_project(this);
  });
  
  // this disables text highliting on double click.
  $('#projects .current_project li .text').disableSelect();
  
  // ==================
  // = Sorting Tracks =
  // ==================
  $('#projects .current_project').sortable({
    stop:function(){
      zebra($(this));
      var options = $.deparam($('#projects .current_project').sortable('serialize'));
      options['userID'] = get_user_id();
      options['action'] = 'sortTracks';
      options['projectID'] = current_project.id;
      var url = $.param.querystring('/import/projects.php', options);
      $.ajax({
        url:url,
        beforeSend:function(){loading_cursor('show')},
        error:function(response, status, error){alert(error)},
        complete:function(){loading_cursor('hide')}
      })
    }
  });
  
  if(current_project && current_project.id == null){current_project = null}
  $.mask.close();
}

// ==================
// = Document Ready =
// ==================
$(function(){
  
  // ==============
  // = Play Track =
  // ==============
  $('#projects .current_project li .text').live('dblclick', function(){
    var attributes = parse_attributes($(this).parents('li:first').attr('rel'));
    var song = new Song(current_project.xml.find('song[id=' + attributes.SID + ']:first'));
    
    jplay_song(song, {track_id:attributes.TID});
  })
  
  // ====================
  // = Download Project =
  // ====================
  $('#projects .download_project').click(function(){
    if(current_project){
      $('#download_project_url').val(download_project_url());
      download_project_overlay.load();
    }else{
      alert('Please select a project.');
    }
  });
  
  // ==================
  // = Delete Project =
  // ==================
  // "http://musicboxmx.com/import/projects.php?SessionId=1273173532368&UserLabel=guest&PID=5562&action=DeleteProject&userID=1109&len=0"
  $('#projects .delete_project').click(function(){
    if(current_project){
      if(confirm("Are you sure you want to delete this project?")){
       options = {PID:current_project.id, action:'DeleteProject', userID:get_user_id()};
       options = standardize_url_options(options);
       var url = $.param.querystring('/import/projects.php', options);
       $.ajax({
         url:url,
         beforeSend:function(){loading_overlay.load()},
         success:function(){
           current_project = null;
           load_projects();
         },
         error:function(response, status, error){alert(error)},
         complete:function(){loading_overlay.close()}
       })
      }
    }else{
      alert("Please select a project.");
    }
  });
  
  // ================
  // = Edit Project =
  // ================
  $('#projects .edit_description').live('click', function(){
    if(current_project){
      edit_project_overlay.load();
    }else{
      alert('Please select a project.');
    }
  });
  
  $('#edit_project form:first').submit(function(){
    // "http://musicboxmx.com/import/projects.php?action=updateProject&PID=5136&userID=1109&SessionId=1273163869055&UserLabel=guest&len=0"
    if(current_project){}else{alert('Please select a project.')}
    var me = $(this);
    var options = $.deparam($(this).serialize());
    options['action'] = 'updateProject';
    options['PID'] = current_project.id;
    options['userID'] = get_user_id();
    options['UserLabel'] = 'guest';
    options['len'] = 0;
    var url = $.param.querystring("/import/projects.php", options);
    $.ajax({
      url:url,
      beforeSend:function(){me.find('.loading').fadeIn()},
      success:function(){edit_project_overlay.close(); load_projects();},
      error:function(response, status, error){alert(error)},
      complete:function(){me.find('.loading').fadeOut()}
    })
    return false;
  });
  
  // ===============
  // = New Project =
  // ===============  
  // http://musicboxmx.com/import/projects.php?SessionId=1273002457065&title=My%20Project%20Now&userID=1109&action=createProject&UserLabel=guest&len=0&desc=
  $('form.new_project').submit(function(){
    var options = $.deparam($(this).serialize());
    options['userID'] = get_user_id();
    options['action'] = 'createProject';
    var url = $.param.querystring("/import/projects.php", options);
    
    send_new_project(url, $(this));
    return false;
  });
  
  // =====================
  // = Duplicate Project =
  // =====================
  $('#projects .duplicate_project').click(function(){
    if(current_project){
      $('#duplicate_project input[name=title]').val(current_project.title + ' copy');
      $('#duplicate_project textarea[name=desc]').val(current_project.description);
      duplicate_project_overlay.load();
    }else{
      alert('Please select a project.');
    }
  });
  
  // "http://musicboxmx.com/import/projects.php?OPID=5136&action=duplicateProject&userID=1109&SessionId=1273169216473&UserLabel=guest&len=0"
  $('#duplicate_project form:first').submit(function(){
    var options = $.deparam($(this).serialize());
    options['userID'] = get_user_id();
    options['action'] = 'duplicateProject';
    options['OPID'] = current_project.id;
    options = standardize_url_options(options);
    var url = $.param.querystring("/import/projects.php", options);
    
    send_new_project(url, $(this));
    return false;
  });
  
  // ========================
  // = Add Track to Project =
  // ========================
  $('#select_project a.add').live('click', function(){
    var options = $.deparam($('#select_project form:first').serialize());
    options['PID'] = parseInt($(this).attr('id'));
    options['action'] = 'assocaiteTrack';
    options['userID'] = get_user_id();
    var url = $.param.querystring("/import/projects.php", options);
    
    $.ajax({
      url: url,
      beforeSend: function(){$('#select_project .loading').fadeIn()},
      success: function(xml){
        if($(xml).find('error:first').attr('num') == '0'){
          select_project_overlay.close();
          load_projects();
        }else{
          alert($(xml).find('error:first').attr('msg'));
        }
      },
      error: function(response, status, error){alert(error)},
      complete: function(){$('#select_project .loading').hide()}
    });
  });
  
  // =============================
  // = Remove Track From Project =
  // =============================
  // "http://musicboxmx.com/import/projects.php?PID=5136&SessionId=1272997469062&len=0&userID=1109&action=disassocaiteTrack&PTID=53701&UserLabel=guest"
  $('.remove_from_project').live('click', function(){
    if(!confirm("Are you sure you want to delete this track?")){
      return null;
    };
    
    var attributes = $(this).attr('rel');
    var options = {userID:get_user_id(), action:'disassocaiteTrack'};
    options['PID'] = attributes.match(/PID=\w+/)[0].replace('PID=', '');
    options['PTID'] = attributes.match(/PTID=\w+/)[0].replace('PTID=', '');
    var url = $.param.querystring("/import/projects.php", options);
    
    $.ajax({
      url: url,
      success: function(xml){load_projects(); set_track_list(new Song)},
      error: function(response, status, error){alert(status + ": " + error)}
    })
  });
  
  $('.add_to_project').live('click', function(){
    if(logged_in()){
      var attributes = parse_attributes($(this).attr('rel'));
      add_track_to_project(attributes)
    }else{
      login_overlay.load();
    }
  });
  
  $('#projects ul.projects li.load_project').live('click', function(){
    reset_nav();
    load_project(parseInt($(this).attr('id')));
  });
  
  
});

// ==========
// = Models =
// ==========
function pTrack(xml){
  this.id = xml.attr('id');
  var tid = xml.attr('tid');
  this.tid = tid;
  this.title = xml.children('title').text().replace(/^\w+: /,'');
  var song = new Song(xml.find('song'));
  this.song = song;
  this.track = new Track(song.xml.find('t[id=' + tid + ']'));
}

function find_project(id){
  return new Project(current_user.projects_xml.find('p[pid=' + id + ']:first'));
}

function Project(xml){
  if(xml){}else{return null}
  var tracks = new Array;
  this.xml = xml;
  this.id = xml.attr('pid');
  this.title = xml.attr('title');
  this.description = xml.find('description').text();
  
  xml.find('pt').each(function(){
    var track = new pTrack($(this));
    trknum = xml.find('song t[id=' + track.id + ']:first').attr('trknum');
    track.trknum = trknum;
    tracks.push(track);
  });
  this.pTracks = tracks;  
}