var timeout;

//******* DOCUMENT READY *******
$(document).ready(function(){

  // search (for gallery)
  $("#search").mouseover(searchGalleryShow);
  $("#search").mouseout(searchGalleryHide);
  searchGalleryHide();
  
  $('#sidprivate form').submit(function(){
    privateAccess($(this));
    return false;
  });
  
});
//******* END OF DOCUMENT READY *******

/**
 * This function provides access to a private gallery.
 */
function privateAccess(frm){
  $.ajax({
    type  : 'POST',
    url   : $(frm).attr('action'),
    data  : $(frm).serializeArray(),
    success : function(msg){
      var response = msg.documentElement || msg;
      var errors = $(response).find('errors');
      var gallery = $(response).find('gallery');
      
      // errors in form
      if($(errors).length > 0){
        var allErrors = $(errors).find('error');
        var errorContainer = $(frm).find('.accessError');
        $(errorContainer).html('');
        $(allErrors).each(function(){
          $(errorContainer).html($(this).text());
        });
        $(errorContainer).show();
        clearTimeout(timeout);
        timeout = setTimeout(function() { $(errorContainer).hide(); }, 5000);
      }

      // no error
      else {
        var url = $(gallery).attr('url');
        window.location.replace(url);
      }
    }
  });
}

/**
 * @desc This function is used to redirect to an another url
 * @param string url This is url to redirect to 
 */
function ubloRedirect(url){
  window.location.replace(url);
}

//******* FUNCTIONS *******

// Search show / hide (for gallery)
function searchGalleryHide(){
  timeout = setTimeout( function(){
    $("#searchgallery").hide()
  }, 200);
}

function searchGalleryShow(){
  clearTimeout(timeout);
  $("#searchgallery").show();
}
