var globalCheckCookieName   = 'checkCookies';
var globalShowBoxCookieName = 'showBoxes';
var pageBoxCookieName       = 'boxPositions';
var boxCookie               = '';
var currentBoxID            = 0;


// Fix for Opera - it supports opacity but jQuery doesn't detect that correctly
if(window.opera) {
      $.support.opacity = true;
}

$(document).ready(function() {
      setTimeout(function() {
            // Cookie independant
            $('A[rel=external]').each(function() {
                  $(this).attr('target', '_blank');
            });
            $("a[rel^='prettyPhoto']").prettyPhoto({
                  animationSpeed:          'normal',
                  padding:                 30,
                  opacity:                 0.35,
                  showTitle:               true,
                  allowresize:             true,
                  counter_separator_label: '/',
                  theme:                   'light_rounded',
                  callback:                function(){}
            });
            
            // Cookie dependant
            var time = new Date().getTime();
            $.cookie(globalCheckCookieName, time, { path: '/', secure: false });
            if(!$.cookie(globalCheckCookieName) || $.cookie(globalCheckCookieName) != time) {
                  return;
            }
            
            if(!$.cookie(pageBoxCookieName) || !$.cookie(pageBoxCookieName).length) {
                  $('div.box').each(function() {
                        $(this).attr('boxID', currentBoxID);
                        $(this).css('z-index', currentBoxID + 5);
                        
                        currentBoxID++;
                        
                        updateBoxCookie(pageBoxCookieName, boxCookie, this);
                  });
            }
            else {
                  $('div.box').each(function() {
                        $(this).attr('boxID', currentBoxID);
                        $(this).css('z-index', currentBoxID + 5);
                        
                        currentBoxID++;
                  });
            }
            
            $('div#menu').show();
            if($.cookie(globalShowBoxCookieName) && $.cookie(globalShowBoxCookieName) == 'no') {
                  $('div#menu div#button').removeClass('active');
                  $('div#boxContainer div.box').hide();
            }
            else {
                  $('div#menu div#button').addClass('active');
                  $('div#boxContainer div.box').show();
            }
            
            $('div#boxContainer').css('left', '539px');
            $('div.box').mousedown(function() {
                  var clickedBox   = this;
                  var clickedBoxID = $(this).attr('boxID');
                  
                  $(clickedBox).css('z-index', currentBoxID + 4);
                  updateBoxCookie(pageBoxCookieName, boxCookie, clickedBox);
                  
                  $('div.box').each(function() {
                        if($(this).attr('boxID') != clickedBoxID && $(this).css('z-index') >= $(clickedBox).css('z-index')) {
                              $(this).css('z-index', $(this).css('z-index') - 1);
                              updateBoxCookie(pageBoxCookieName, boxCookie, this);
                        }
                  });
            });
            $('div.box').draggable({
                  handle:  'div.boxHeader',
                  opacity: 0.5,
                  cursor:  'move',
                  stop:    function(event, ui) {
                        updateBoxCookie(pageBoxCookieName, boxCookie, this);
                  }
            });
            $('div.box div.boxHeader').css('cursor', 'move');
            
            if($.cookie(pageBoxCookieName) && $.cookie(pageBoxCookieName).length) {
                  boxCookie = $.cookie(pageBoxCookieName);
                  
                  $.each(boxCookie.split('/'), function(i, box) {
                        var boxID     = null;
                        var boxZIndex = null;
                        var boxTop    = null;
                        var boxLeft   = null;
                        $.each(box.split(';'), function(i, boxDetails) {
                              var detail = $.trim(boxDetails), name = detail.split('=')[0], value = detail.split('=')[1];
                              switch(name) {
                                    case 'box':
                                          boxID = value;
                                          break;
                                    case 'zindex':
                                          boxZIndex = value;
                                          break;
                                    case 'top':
                                          boxTop = value;
                                          break;
                                    case 'left':
                                          boxLeft = value;
                                          break;
                              }
                        });
                        
                        $('[boxID=' + boxID + ']').css('position', 'absolute');
                        $('[boxID=' + boxID + ']').css('z-index', boxZIndex);
                        $('[boxID=' + boxID + ']').css('top', boxTop + 'px');
                        $('[boxID=' + boxID + ']').css('left', boxLeft + 'px');
                  });
            }
            
            $('div#menu div#button').click(function() {
                  if($('div#menu div#button').hasClass('active')) {
                        $('div#menu div#button').removeClass('active');
                        $('div#boxContainer div.box').fadeOut(500);
                        $.cookie(globalShowBoxCookieName, 'no', { path: '/', secure: false });
                  }
                  else {
                        $('div#menu div#button').addClass('active');
                        $('div#boxContainer div.box').fadeIn(500);
                        $.cookie(globalShowBoxCookieName, 'yes', { path: '/', secure: false });
                  }
            });
      }, 25);
});


function updateBoxCookie(cookieName, cookieValue, box) {
      var boxOffset      = $(box).offset();
      var parentOffset   = $(box).parent().offset();
      var boxID          = $(box).attr('boxID');
      var cookieValue    = cookieValue && cookieValue != null ? cookieValue : '';
      var newCookieValue = '';
      $.each(cookieValue.split('/'), function(i, box) {
            var addBox = false;
            $.each(box.split(';'), function(i, boxDetails) {
                  var detail = $.trim(boxDetails), name = detail.split('=')[0], value = detail.split('=')[1];
                  if(name == 'box' && value != boxID) {
                        addBox = true;
                  }
            });
            
            if(addBox == true) {
                  newCookieValue += (newCookieValue.length ? '/' : '') + box;
            }
      });
      
      newCookieValue += (newCookieValue.length ? '/' : '') + 'box=' + boxID + ';top=' + (boxOffset.top - parentOffset.top) + ';left=' + (boxOffset.left - parentOffset.left) +
                        ';zindex=' + $(box).css('z-index');
      boxCookie       = newCookieValue;
      
      $.cookie(cookieName, newCookieValue, { path: '/', secure: false });
}