google.load('jquery', '1');
google.load('jqueryui', '1');

google.setOnLoadCallback(function() {
  $(document).ready(function() {    
    getGETVar = function(name) {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp(regexS);
      var results = regex.exec(window.location.href);
      if (results == null) {
        return "";
      } else {
        return results[1];
      }
    }
    
    stripTags = function(str) {
      return str.replace(/&lt;\/?[^&gt;]+&gt;/gi, "");
    }

    showCart = function() {
      $('#shopping u')
        .text('Close cart!')
        .unbind('click').click(function() {
          closeCart();
        });
      $('#shopping').stop().animate({height:300}, 'normal', function() { moveCart(); });
    }
    
    closeCart = function() {
      $('#shopping u')
        .text('Show cart!')
        .unbind('click').click(function() {
          showCart();
        });
      $('#shopping').stop().animate({height:22}, 'normal', function() { moveCart(); });
    }
    
    updateCart = function() {
      activated = false;
      if ($('#shopping:visible').length == 0) {
        $('#shopping u').click(function() { showCart(); });
        $('#shopping').fadeIn();
        activated = true;
      }
      $('#shoppingContent span').html('Currently '+$('#shopping ul li').length+' badge'+($('#shopping ul li').length == 1 ? '' : 's')+' in your shopping cart.');
      if ($('#shopping ul li').length == 0) {
        closeCart();
      } else {
        $('#shopping').effect('highlight', {}, 300);
      }
    }

    checkoutCart = function() {
      var cartBox = '';
      $('#shoppingContent ul li').each(function() {
        cartBox += $(this).attr('class')+',';
      });
      if (cartBox.length <= 1) {
        alert('Your cart is still empty.');
        return;
      }
      cartBox = cartBox.substring(0, cartBox.length - 1);
      $('#checkout').unbind('click');
      $.ajax({
        url: 'rpc.php',
        type: 'post',
        data: {
          'cmd': 'makeCart',
          'badgeIds': cartBox
        },
        dataType: 'xml',
        success: function(transport) {
          var targetAvatar = 'http://avatars.imvu.com/Benni?cart=';
          if ($('response cart bag', transport).length == 1) {
            location.href = targetAvatar+$('response cart bag', transport).attr('cart_id');
          }
        }
      });
    }
    
    callStats = function() {
      $.ajax({
        url: 'rpc.php',
        type: 'post',
        data: {
          'cmd': 'getStats'
        },
        dataType: 'xml',
        success: function(transport) {
          if ($('response stats stat', transport).length > 0) {
            $('#stats').html(
              'Shop contains '+$('<strong>').text($('response stats stat', transport).attr('articles')).html()+' badges and gave out a total of: '+$('<strong>').text($('response stats stat', transport).attr('success')).html()
            ).fadeIn();              
          }
        }
      });
    }
    
    moveCart = function() {
      var correct = $('#footer').height() + $('#shopping').height();
      var documentHeight = $(document).height() - correct;
      var scrollPosition = $(window).height() + $(window).scrollTop() - correct;
      if (documentHeight > scrollPosition) {
        var newTopValue = scrollPosition - 590;
        if (newTopValue > 0) {
          $('#cart').stop().animate({marginTop:newTopValue});
        }
      }
    }
    
    loadingBadges = function() {
      $('#articles div').each(function(index) {
        var thisIndex = index;
        $('<img>')
          .attr('src', $(this).attr('src'))
          .ready(function() {
            $('#articles div:eq('+thisIndex+')')
              .css('background-image', 'url('+$('#articles div:eq('+thisIndex+')').attr('src')+')');
          });
        $(this).click(function() {
          openDetails($(this).attr('id'));
        });
      });
    }
    
    closeLightboxSmall = function() {
      $('#lightboxOverlay, #lightboxSmall').fadeOut('slow', function() {
        $('body').css('overflow', 'auto');
        $('#lightboxOverlay, #lightboxSmall').remove();
      });
    }
    
    openDetails = function(badgeId) {
      $('body').animate({scrollTop: 0}, 300, function() {
        $(this).css('overflow', 'hidden');
        $('<div>')
          .css('opacity', 0.0)
          .attr('id', 'lightboxOverlay')
          .appendTo('body')
          .fadeTo('slow', 0.7, function() {
            $('<div>')
              .hide()
              .attr('id', 'lightboxSmall')
              .text('Loading...')
              .appendTo($('body'))
              .fadeIn('slow', function() {
                $('#lightboxOverlay').click(function() {
                  closeLightboxSmall();
                });
                $(this).load('rpc_article.php', {'articleId':badgeId}, function(e) {
                  if ($(this).text().length <= 10) {
                    alert('This badge is probably not available anymore.');
                    closeLightboxSmall();
                  }
                });
              });
          });
      });
    }
    
    reopenDetails = function(badgeId) {
      $('#lightboxSmall')
        .text('Loading...')
        .load('rpc_article.php', {'articleId':badgeId}, function(e){
        if ($(this).text().length <= 10) {
          alert('This badge is probably not available anymore.');
          closeLightboxSmall();
        }
      });    
    }
    
    addToCart = function(item) {
      addArticleToCart(item.attr('id'), item.attr('src'), item.attr('title'));
    }
    
    addArticleToCart = function(id, src, title) {
      if ($('#shopping ul li.'+id).length == 0) {
        var imgBadge = $('<img>')
          .attr('src', src)
          .attr('title', title);
        $('<li>')
          .append(imgBadge)
          .attr('class', id)
          .appendTo($('#shopping ul'))
          .hover(function() {
            $(this).addClass('showOverflow');
          },
          function() {
            $(this).removeClass('showOverflow');          
          })
          .click(function() {
            $(this).fadeOut('normal', function() {
              $('#articles div').each(function() {
                if ($(this).attr('id') == id) {
                  $(this).fadeIn();
                }
              });
              $(this).remove();
              updateCart();
            });
          });    
      }
    }
    
    var searchQueryString = '';    
    var searchRunning = false;
    searchFetch = function() {
      var searchString = $('#searchString').val();
      if (searchQueryString != searchString && !searchRunning && searchString.length > 0) {
        searchQueryString = searchString;
        searchRunning = true;        
      } else {
        return;
      }
      $.ajax({
        url: 'rpc.php',
        type: 'post',
        data: {
          'cmd': 'getArticles',
          'searchString': searchString
        },
        dataType: 'xml',
        complete: function() {
          searchRunning = false;
          $('#resultLoader').hide();
          $('#searchString').width(179);
        },
        success: function(transport) {
          $('#articles div, #articles p').remove();        
          if ($('response articles article', transport).length > 0) {
            $('response articles article', transport).each(function() {
              if ($('#shopping li.'+$(this).attr('id')).length == 0) {
                $('<div>')
                  .attr('title', $(this).text())
                  .attr('id', $(this).attr('article_id'))
                  .attr('src', $(this).attr('src'))
                  .text(' ')
                  .prependTo('#articles');
              }
            });
            $('#articles').prepend($('<p>')
              .addClass('msgSuccess')
              .text('Found '+$('response articles', transport).attr('count')+' badges for: '+stripTags(searchString)+' (max 100 results)'));        
          } else {
            $('#articles div, #articles p').remove();          
            $('#articles').prepend($('<p>')
              .addClass('msgError')
              .text('Nothing found for: '+stripTags(searchString)));
          }
          $('#articles div').draggable({
            opacity: 0.35,
            revert: true,
            revertDuration: 100,
            scroll: true,
            scrollSensitivity: 40,
            scrollSpeed: 40
          });
          loadingBadges();
        }
      });
    }
    
    var searchQueryTimer;
    $('#searchString').click(function() {
      if ($(this).val() == 'Search') {
        $(this).css({color:'#000000'}).val('');
      }
    }).keyup(function() {
      if ($(this).val() != '') {
        searchQueryTimer = window.setTimeout('searchFetch();', 2500);
        $(this).width(155);
        $('#resultLoader').show();
      } else {
        $('#resultLoader').hide();      
        $(this).width(179);        
      }
    }).val('Search');
    
    var loadedLastCategoryId = 0;
    loadCategory = function(categoryId) {
      if (loadedLastCategoryId == categoryId) { return; }
      loadedLastCategoryId = categoryId;
      $('#articles div, #articles p').remove();
      $.ajax({
        url: 'rpc.php',
        type: 'post',
        data: {
          'cmd': 'getArticles',
          'categoryId': categoryId
        },
        dataType: 'xml',
        success: function(transport) {
          if ($('response articles article', transport).length > 0) {
            $('response articles article', transport).each(function() {
              if ($('#shopping li.'+$(this).attr('id')).length == 0) {
                $('<div>')
                  .attr('title', $(this).text())
                  .attr('id', $(this).attr('article_id'))
                  .attr('src', $(this).attr('src'))
                  .text(' ')
                  .prependTo('#articles');
              }
            });
          } else {
            $('#articles').append($('<p>').text('No articles found for this category.'));
          }
          $('#articles div').draggable({
            opacity: 0.35,
            revert: true,
            revertDuration: 100,
            scroll: true,
            scrollSensitivity: 40,
            scrollSpeed: 40
          });
          if ($('#stats').text().length == 0) {
            callStats();
          }
          loadingBadges();
        }
      });
    }
    
    firstCategory = function() {
      var firstCategory = $('#categories ul li:visible').eq(0);
      $(firstCategory).addClass('active');
      loadCategory($(firstCategory).attr('title'));
    }

    getCategories = function() {
      $.ajax({
        url: 'rpc.php',
        type: 'post',
        data: {
          'cmd': 'getCategories'
        },
        dataType: 'xml',
        success: function(transport) {
          if ($('response categories category', transport).length > 0) {
            $('#categories ul li').fadeOut('fast', function() {
              $('response categories category', transport).each(function() {
                $('<li>')
                  .hide()
                  .attr('title', $(this).attr('id'))
                  .attr('class', ($(this).attr('class') ? $(this).attr('class') : ''))
                  .text($(this).text())
                  .append($('<small>').text(($(this).attr('count') > 0 ? ' ('+$(this).attr('count')+')' : '')))
                  .appendTo($('#categories ul'))
                  .hover(
                    function() { $(this).addClass('hover'); },
                    function() { $(this).removeClass('hover'); }
                  ).click(function() {
                    $('#categories ul li').removeClass('active');
                    $(this).addClass('active');
                    loadCategory($(this).attr('title'));
                  }).slideDown();
                loadFirstCategory = window.setTimeout('firstCategory();', 1000);
              });
            });
          } else {
            $('#categories ul li').text('Failed.');
          }
        }
      });
    }
    window.setTimeout('getCategories();', 2000);
    
    openLightbox = function() {
      $('body').animate({scrollTop: 0}, 300, function() {
        $(this).css('overflow', 'hidden');
        $('<div>')
          .css('opacity', 0.0)
          .attr('id', 'lightboxOverlay')
          .appendTo('body')
          .fadeTo('slow', 0.7, function() {
            $('<div>')
              .hide()
              .attr('id', 'lightbox')
              .text('Loading...')
              .appendTo($('body'))
              .fadeIn('slow', function() {
                $(this).load('form.php');
              });
          });
      });
    }
    
    closeLightbox = function() {
      $('#lightboxOverlay, #lightbox').fadeOut('slow', function() {
        $('body').css('overflow', 'auto');
        $('#lightboxOverlay, #lightbox').remove();
      });
    }
    
    $('#footer span').click(function() {
      openLightbox();
    });

    if (getGETVar('panel') == 'show') {
      openLightbox();
    } else if (getGETVar('badge') > 0) {
      openDetails(getGETVar('badge'));
    }
        
    $('#cart').droppable({
      accept: '#articles div',
      hoverClass: 'hover',
      drop: function(event, ui) {
        addToCart(ui.draggable);
        ui.draggable.fadeOut('fast');
        updateCart();
      }
    }).click(function() {
      if ($('#shopping ul li:visible').length > 0) {
        showCart();
        var cartPosition = $('#shopping').offset().top - 8;
        $('body').animate({scrollTop: cartPosition}, 300);
      }
    });

    $('#checkout').click(function() {
      checkoutCart();
    });
    
    $(window)
      .scroll(function() { moveCart(); })
      .resize(function() { moveCart(); });
    
    $('.link_addall').click(function() {
      $(this).fadeOut('fast', function() {
        var i = 0;
        var x = 0;
        $('#articles div:visible').each(function() {
          i++;
          if (i <= 250) { 
            x++;
            addToCart($(this));
            $(this).hide();
          }
        })
        $('.link_addall')
          .text(x+' badges added to cart.')
          .fadeIn('normal');
        updateCart();
      });
    });
  });
});
