$(function(){
  
  $('.core').css('zoom',1);
  
  //existence of welcome-scholar message indicates that we should show it in an overlay.
  var welcomeScholar = $('#welcome-scholar');
  if(welcomeScholar.size()){
    welcomeScholar.parent().jqm({toTop:true,overlayClass:'jqm-overlay-white',overlay:80}).jqmShow();
    welcomeScholar.find('.btn').click(function(e){
      welcomeScholar.parent().jqmHide();
      e.preventDefault();
    });
  }
  
  $('.hidetabs').hide();
  
  (function(){
    $('.profile-profile_websites a').click(function(e){
      e.preventDefault();
      window.open(this.href);
    });
  })();
  
  /**
   * encapsulation of groups
   */
  (function(){
    $('.see-all-link').click(function(e){
      e.preventDefault();
      var first = true;
      $('.groups .row').each(function(){
        if(!first){
          $(this).toggleClass('hide');
        }
        first = false;
      });
      if($(this).html() == 'See All &raquo;') {
        $(this).html('See Less &raquo;');
      } else {
        $(this).html('See All &raquo;');
      }
    });
  })();
  
  //add cancel button
  if(/user\/\d+\/edit/.test(location.pathname)){
    $('#edit-submit').after('<a class="btn btn-cancel" href="'+location.pathname.replace('/edit','')+'">Cancel</a>');
  }
  
  //on profile view page, hide "view edit track contact" links tabbar,
  //and copy the contact link to next to the profile name.
  if(/users\/.*/.test(location.pathname)){
    $('.G_2-3 .tabs li').hide().eq(3).children().addClass('profile-contact-link').insertAfter('.core h2');
  }
  
  /**
   * add edit section form creation and handling
   */
  var locationPrefix = location.protocol + '//' + location.host;
  $.getScript('/sites/all/themes/siebelscholars/js/jquery.scrollTo.js?o');
  /*
  function updateHeaderExpl(){
    i = 0;
    $(".profile .core").find(".edit-section-link").each(function(){
      if ($(this).is(':hidden')) {
        i++;
      }
    });
    //alert(i);
    if (i < 1){
      $(".profile .core").find(".profile-form-legend-top").hide();
    }
    else {
      $(".profile .core").find(".profile-form-legend-top").show();
    }    
  };
  */

  $('.edit-section-link').each(function(){
    var editLink = $(this);
    var url = editLink.attr('href') + '?modal=1';
    
    // add form container so that we can switch back and forth between showing the form and the section display
    var formContainer = $('<div class="section-form-container"/>').appendTo(editLink.parent()).hide();
    // the profile attributes = the display of the values which the form collects/modifies
    var profileAttributes = editLink.parent().find('.profile-attributes');
    if(!profileAttributes.size()){
      editLink.parent().append('<div class="profile-attributes"/>');
      profileAttributes = editLink.parent().children('.profile-attributes'); 
    }
    
    // add click handler
    
    editLink.click(function(){
      $(".profile .core").find(".profile-form-legend-top").show();
      editLink.hide();
      // hide the profile attributes display
      profileAttributes.animate({'opacity':0}, 500);
      profileAttributes.parent().addClass('loading');
      formContainer.html('Loading...').load(url, null, function(){
        profileAttributes.hide();
        profileAttributes.parent().removeClass('loading');
        formContainer.fadeIn();
        
        function prepareForm(){
          //add appropriate scripts to the page.
          (function(){
            var scripts = [locationPrefix+"/sites/all/themes/siebelscholars/js/jquery.cluetip.js?o", locationPrefix+"/misc/autocomplete.js?o"];
            //load scripts serially, preserving execution order
            var startTime = new Date().getTime();
            (function loadScript(i){
              if( i < scripts.length ){
                if(i==0 && $.cluetip){
                  //no need to load the cluetip js again, just wire tooltips.
                  $('.tooltip').cluetip();
                } else {
                  $.getScript(scripts[i], function(){loadScript(i+1);});
                }
              } else {
                Drupal.behaviors.autocomplete(formContainer[0]);
              }
            })(0);
            
          })();
          
          //add 'cancel' and 'submit' links. (there is already an INPUT[type=submit] but a link is easier to style.)
          //also add a hidden input for modal=1 (post)
          (function(){
                        
            if(!formContainer.find('.form-submit').size()){
              setTimeout(arguments.callee, 20);
              return;
            }
            formContainer.find('.form-submit').eq(0).hide().wrap('<div class="actions"></div>');
            formContainer.find('.actions').prepend('<a class="btn btn-save" href="#">Save</a> <a class="btn btn-cancel" href="#">Cancel</a>');
            formContainer.find('.actions a.btn-cancel').click(function(){
              
              formContainer.fadeOut();
              editLink.show();
              profileAttributes.show().animate({'opacity':1},500, function(){
                $(window).scrollTo(profileAttributes.parent().is('.education_and_work') ? $('.profile') : profileAttributes.parent(), {duration:500});
              });
              /* updateHeaderExpl();  */
              return false;
            });
            formContainer.find('.actions a.btn-save').click(function(){
              setTimeout(function(){
                formContainer.find('form').trigger('submit');
              }, 10);
              return false;
            });
            formContainer.find('fieldset').append('<input type="hidden" name="modal" value="1"/>');
          })();
          
          formContainer.find('form')
            .unbind('submit')
            .bind('submit', function(){
              
              var queryString = $(this).formSerialize();
              $.post(url, queryString, function(responseText, statusText){ //a better name for this would be "afterSubmit" or "afterReturn"

                if(statusText == 'success' && responseText.indexOf('messages error') < 0){
                  formContainer.fadeOut();
                  editLink.show();
                  if(url.indexOf('edit/Profile?') > -1){
                    $('.profile-essence h2').html(responseText).show().animate({'opacity':1},500);
                  } else {
                    profileAttributes.html(responseText).show().animate({'opacity':1},500, function(){
                      $(window).scrollTo(profileAttributes.parent().is('.education_and_work') ? $('.profile') : profileAttributes.parent(), {duration:500});
                    });
                  }
                } else {
                  //sanitize responseText .. strip down to only what's inside the body tag
                  $(window).scrollTo(profileAttributes.parent().is('.education_and_work') ? $('.profile') : profileAttributes.parent(), {duration:500});
                  formContainer.html( responseText.indexOf('<body') > -1 ? responseText.replace(/.*?(<form.*?id="user-profile-form">.*?<\/form>).*/, '$1') : responseText );
                  prepareForm();
                }
              /* updateHeaderExpl();  */ 
              });
              
              return false;
            });
        };
        prepareForm();
      });
      return false;
    });
  });
  
  

  $('#edit-documents-link').click(function(e){
    e.preventDefault();
    var editLink = $(this);
    var uid = editLink.attr('href').substring(6, 9);
    var userfiles = $('.userfiles');
    var editForm = $('.userfiles-edit');
    var viewLink = $('<a href="#" class="edit-documents-link">View Files &raquo;</a>').appendTo(editLink.parent()).click(function(e){
      e.preventDefault();
      $(this).hide();
      editForm.find('.messages').remove();
      editForm.animate({'opacity':0}, 500).hide();
      userfiles.load("/user/"+uid+"/userfiles?modal=1", null, function(){
        $(this).show().animate({'opacity':1}, 500);
      });
      editLink.show();
    });
    editLink.hide();
    userfiles.animate({'opacity':0}, 500).hide();
    editForm.css('opacity', 0).show().animate({'opacity':1}, 500);
    return false;
  });

});


