/* Global variables */
var GET = getURLparams();


/* jQuery ready functions */
$(function() {

  /* AJAX behavior */
  $.ajaxSetup ({ cache: false });
  
  $("#loading").ajaxStart(function(){ $(this).fadeIn("fast"); });
  
  $("#loading").ajaxComplete(function(){ $(this).fadeOut("fast"); });


  /* Location.hash ajax handler */
  $(window).bind("hashchange", function(){
    
    GET = getURLparams();
    
    var cleanHash = document.location.hash.substring(1);
    loadContent(cleanHash);

  });
  
  $(window).trigger("hashchange");


  /* Load menu */
  loadMenu(GET.gallery);


  /* Keyboard shortcuts */
  $(document).bind("keydown", function(event){

    var sourceElement = event.target || event.srcElement;
    var eventKey = event.keyCode || event.which;

    if( $(sourceElement).is(":not(input)") ){
      
      /* Open administration */
      if( eventKey == 97 || eventKey == 65 ){
        window.location.hash = "#act=admin";
      }
    
      /* Toggle upload box */
      else if( eventKey == 117 || eventKey == 85 ){
        $("#tools > ul.tools > li.upload").trigger("click");
      }
    
      /* Toggle upload box */
      else if( eventKey == 68 || eventKey == 100 ){
        $("#tools > ul.tools > li.cdm").trigger("click");
      }
    
      /* Toggle upload box */
      else if( eventKey == 81 || eventKey == 113 ){
        window.location = "index.php?act=proceed&logout=true";
      }
      
      /* Left arrow image navigation */
      else if( eventKey == 37 && GET.act == 'imgview' ){
        
        var newImage = ( GET.image / 1 ) - 1;
        if( isNaN( newImage ) || newImage < 0 ) newImage = 0;
        window.location.hash = "#act=imgview&gallery="+GET.gallery+"&image="+newImage;
      
      }
      
      /* Right arrow image navigation */
      else if( eventKey == 39 && GET.act == 'imgview' ){
        
        var totalImages = $("#navigation div.title h1").text();
        totalImages = ( totalImages.substr(totalImages.indexOf("/")+1) / 1 ) - 1;
        
        var newImage = ( GET.image / 1 ) + 1;
        if( isNaN( newImage ) || newImage > totalImages ) newImage = totalImages;
        
        window.location.hash = "#act=imgview&gallery="+GET.gallery+"&image="+newImage;
      
      }
      
      
    }
  
  });

  // -----------------------------------------
  //     Eye candies
  // -----------------------------------------

  /* Hover opacity animation */
  $(".opbutton").css({ opacity : 0.6 });
  $(".opbutton").hover( function(){ $(this).stop().animate({ opacity: 1 }, 200); },
                        function(){ $(this).stop().animate({opacity: 0.6}, 200); });
  $(".opbutton").live("mousedown", function(){ $(this).stop().css({ opacity : 0.3 }); });
  $(".opbutton").live("mouseup", function(){ $(this).css({ opacity : 1 }); });


  /* Active menu item */
  $("#menu > div.galleries > a").live("click", function(){
    
    $("#menu > div.galleries > a").removeClass("active");
    $(this).addClass("active");
  
  });


  /* Tweaks */
  $(window).bind( "resize load", function(){
    var windowHeight = $(window).height();
    
    if( windowHeight < $("#menu").height() ) $("#menu").css({ "position" : "absolute" })
    else $("#menu").css({ "position" : "fixed" })
    
  });

  if( $.browser.opera ) $("body").css({ "overflow" : "hidden" });

});


/* Ajax content loading */
function loadContent( getData )
{
    
    if( !getData || getData.length < 2 ) getData = 'act=galleryview';
    
    $.ajax({
    
      type: "GET",
      url: "index.php",
      data: "ajax=true&" + getData,
      cache: false,
      success: function(data){
        
        scroll(0,0);
        
        var menuWidth = $("#menu").width();
        var toolsLeft = menuWidth - 35;

        if( GET.act == 'imgview' ) {
            
            menuLeft = menuWidth - ( menuWidth * 2 );
            
            $("#content").addClass("stretched").html(data);
            $("#menu").animate( { "left" : menuLeft + "px" }, 100, function(){ $("div.image").fadeIn(400); } );
            $("#tools").animate({ "left" : "-35px" }, 100);
            
        }else if( GET.act == 'admin' ){
            
            $("#content").removeClass("stretched").hide().html(data).fadeIn();
            $("#menu").animate( { "left" : "0" }, 100 );
            $("#menu > div.galleries > a").removeClass("active");
            $("#tools").css({ "left" : toolsLeft + "px" }, 100).fadeOut(200);
            
            
            /* Admin configs - it has to be here on bind because of IE :/ */
            $("div.configbox form, #createGallery form").bind("submit", function(){
          
                var formAction = $(this).attr("action");
                var formVariables = '';
          
                $(this).find("[name]").each( function(i,e){
                
                  var name = $(this).attr("name");
                  var value = $(this).val();
                  
                  formVariables += "&" + name + "=" + value;
                
                });
                
                var getData = formAction.substr(formAction.indexOf("?")+1) + formVariables;
                
                if( getData.length > 10 ) {
          
                  $.ajax({
                    type: "POST",
                    url: "index.php",
                    data: getData,
                    cache: false,
                    success: function(data){
                    
                      if( data.length > 0 ) message(data);
                      
                    },
                    error: function(){
                      message('Error while loading server response');
                    }
                  });
          
                } else message('Form action is not correct');
          
                return false;
            
            });

        }else{
            
            $("#content").removeClass("stretched").hide().html(data).fadeIn();
            $("#menu").animate( { "left" : "0" }, 100 );
            $("#tools").fadeIn(200).animate({ "left" : toolsLeft + "px" }, 100);
            
        }
      
      },
      error: function(){
      
        $("#content").html('Error while performing AJAX request has occured');
        
      }
     
    });

}



function loadMenu( activeGalleryID )
{
  if( getURLparams().act == 'admin' ) activeGalleryID = 'clear';
  $("#menu > div.galleries").load("?ajax=true&act=menu&gallery=" + activeGalleryID );
}



function message(message){
    
    var container = $('#message');
    var containerWidth = container.width();
    var leftAttr = ( $(window).width() - containerWidth ) / 2;
    
    container.css({ left : leftAttr });
    
    if( message.length > 1 ) {
    
        container.html(message).bind("click", function(){
          $(this).clearQueue().stop().fadeOut(100);
        }).fadeIn(400, function(){
          $(this).clearQueue().stop().delay(3000).fadeOut();
        });
    
    }

}


function getURLparams( from ){
  
  if( from == 'hash' || from == undefined ) var pairs = window.location.hash.substring(1).split("&");
  else if( from == 'search' ) var pairs = window.location.search.substring(1).split("&");
  else var pairs = from.substring(1).split("&");
  
  var params = [];
  
  for (i = 0; i < pairs.length; i++)
  {
       var pair = pairs[i].split("=");
       params[pair[0]] = pair[1];
  }
  
  return params;
  
}

