/**
 * Class storing and showing last seen creations
 * It uses browser cookies as storage engine, it will not require to enable sessions
 * on server
 */
function MyCreations(){

  /*
   * max creations to store, it will actually display one less,
   * requires to store current creation
   */
  var maxCreations = 6;
  var creations = {}; //creations array loaded/saved to cookie, never cookie is identified by currCookieCreation
  var currentCreation = {id: 0};
  var currCookieCreation = 0; //id of creation to store at the momen, last inserted creation is thix value - 1
  var lang = {}; //language strings
  var boxCenter = null; //direct container of displayed data
  var box = null; //whole created container

  /**
   *  Loads data from cookie then
   *  Loads data prepared in HTML about current object
   */
  this.getCurrentCreationDetails = function(){
    //if cookie enabled
    if (isCookieEnabled())
      //get data from cookie
      getFromCookie();
      //parse data from HTML
      if ($('#parseData').length){
        var o = {};
        o.id = $('#parseData .id').text();
        o.author = $('#parseData .author').text();
        o.title = $('#parseData .title').text();
        o.description = $('#parseData .description').text();
        o.type = $('#parseData .type').text();
        o.typeName = $('#parseData .typeName').text();
        o.category = $('#parseData .category').text();
        o.link = $('#parseData .link').text();
        o.preview = $('#parseData .preview').text();
        lang.title = $('#parseData .langTitle').text();
        lang.clean = $('#parseData .langClean').text();
        currentCreation = o;
        //add current creation to array
        addCurrentCreation();
        //save data to cookie
        saveToCookie();
      }
  }

  /**
   * Test browser for the cookie capability
   */
  function isCookieEnabled(){
    document.cookie = "CookieTest=Enabled";
    var allcookies = document.cookie;
    var pos = allcookies.indexOf("CookieTest=");
    if (pos != -1) {
      var start = pos + 11;
      var end = allcookies.indexOf(";", start);
      if (end == -1) end = allcookies.length;
      var value = allcookies.substring(start,end);
      value = unescape(value);

      if (value == "Enabled") {
        return true;
      } else {
        return false;
      }
    }
    return false;
  }

  //gets id of last creation id in array
  function getPreviousCookieCreation(){
    if (currCookieCreation > 0)
      return (currCookieCreation - 1);
    else
      return (maxCreations - 1);
  }

  /**
   * Add current creation to array
   */
  function addCurrentCreation(){
    var onList = false; //creation exists already
    var id = getPreviousCookieCreation();
    do{//search if not in array already
      if ((creations[id])&&(creations[id].id == currentCreation.id)){
        onList = true;
      }
      id++;
      if (id >= maxCreations){ id = 0;}
    }while ((id != (getPreviousCookieCreation())) && !onList)

    //if not on list then add to it
    if (!onList){
      creations[currCookieCreation] = currentCreation;
      if (currCookieCreation == (maxCreations-1)){
        currCookieCreation = 0;
      }else{
        currCookieCreation++;
      }
    }
  }

  /**
   * Clean all cookies
   */
  function cleanCookie(){
    $.Jookie.Initialise('myCreations',60*24*30);
    $.Jookie.Unset('myCreations','list');
    $.Jookie.Unset('myCreations','current');
    $.Jookie.Unset('myCreations','lang');
  }

  /**
   * Save data to cookies
   */
  function saveToCookie(){
    cleanCookie(); //without this it didn't worked well
    $.Jookie.Initialise('myCreations',60*24*30);
    $.Jookie.Set('myCreations','list',creations);
    $.Jookie.Set('myCreations','current',currCookieCreation);
    $.Jookie.Set('myCreations','lang',lang);
  }

  /**
   * Read data from cookie
   */
  function getFromCookie(){
    $.Jookie.Initialise('myCreations',60*24*30);
    c = $.Jookie.Get('myCreations','list');
    if (typeof c != 'undefined'){
      creations = c;
    }
    c = $.Jookie.Get('myCreations','current');
    if (typeof c != 'undefined'){
      currCookieCreation = c;
    }
    c = $.Jookie.Get('myCreations','lang');
    if (typeof c != 'undefined'){
      lang = c;
    }
  }

  /**
   * Generates box with cookie data
   */
  this.showData = function(){
    //if anything to display
    if (toShow()){
      var insertIn = false; //contaner to display in
      var drop = false; //should pop in by drop function

      if ($('#minorContent').length){//creation and type list pages
        insertIn = $('#minorContent');
        drop = false;
      }else if($('#topListBox').length){ //main page
        $('#topListBox').wrap($('<div>').attr('id', 'topListContainer').addClass('clearfix')); //create wrapping container
        insertIn = $('<div />').attr('id','minorContent'); //pin it to right top corner
        $('#topListBox').after(insertIn); //insert box after top list
        $('#topListBox .toHide').hide(); //hide extra elements before shrinking list box
        drop = true;
      }
      if(insertIn){//if page to insert box proceed
        drawBox(insertIn);
        drawCreations(drop);
      }
    }
  }

  /**
   * hide data and remove it from cookie
   */
  this.hideData = function(){
    if($('#topListBox').length){//index page
      if ($.browser.msie){//if MSIE do not animate
      }else if ($.browser.safari){//if safari/chrome just switch, animation unsupported
        $('#topListBox').removeClass('mediumBox').addClass('largeBox');
      }else{//extend box
        $('#topListBox').switchClass('mediumBox','largeBox',500);
      }
      //hide old box
      box.hide('drop',{ direction: "right" },400, function(){if (!$.browser.msie) {$('#topListBox .toHide').show()};});
    }else{//other pages
      box.slideUp(300, function() {box.empty()} );
    }
    //remove cookie data
    cleanCookie();
  }

  /**
   * Check if there is any data to display
   */
  function toShow(){
    var id = getPreviousCookieCreation();
    do{
      if ((creations[id])&&(creations[id].id != currentCreation.id)){
        return true;
      }
      id++;
      if (id >= maxCreations){ id = 0;}
    }while ((id != (getPreviousCookieCreation())))
    return false;
  }

  /**
   * Draw creations box
   */
  function drawBox(insertIn){
    box = $('<div>').addClass('contentBox smallBox lastBox').css('display', 'none');
    box.prepend($('<div>').addClass('boxTop'));
    boxCenter = $('<div>').addClass('boxCenter clearfix');
    box.append(boxCenter);
    box.append($('<div>').addClass('boxBottom'));
    boxCenter.prepend(
      $('<h2>').text(lang.title)
    ).append(
      $('<a>').addClass('clean moreHitList imgReplacement')
              .click(function(){myCreations.hideData()})
              .attr({href: 'javascript:void(0)'})
              .text(lang.clean)
              .append('<span>')
    )
    insertIn.prepend(box);
  }


  /**
   * Insert creations into prepared box
   */
  function drawCreations(drop){
    var creationsList = $('<ul>');
    var id = currCookieCreation-1;
    var counter = 0; //counter to limit displayed creations to max-1

    do{//add creations
      if (creations[id] && (creations[id].id != currentCreation.id)){
        addCreation(creationsList, creations[id]);
        counter++;
      }
      id--;
      if (id <0) {id = maxCreations-1}
    }while (id != (currCookieCreation-1) && (counter < 5))

    //add generated data to DOM
    boxCenter.append(creationsList);

    //animate created data
    if (drop){//main page, use drop animation
      if ($.browser.safari){//safari/chrome not suported, just switch
        $('#topListBox').removeClass('largeBox').addClass('mediumBox');
      }else{
        $('#topListBox').switchClass('largeBox','mediumBox',400);
      }

      if ($('#topListBox').height() < box.height()){
        $('#topListContainer').height(box.height());
      }


      box.show('drop',{ direction: "right" },500)
    }else{//other pages
      box.slideDown(300);
    }
  }

  /**
   * Add single creation to given container
   */
  function addCreation(container, creation){
    var creationLi = $('<li>');

    //audio creation
    if ($.inArray(creation.type, new Array('monophony', 'polyphony', 'realtone', 'truetone')) != -1){
      creationLi.append(
        $('<a>').attr({
          href: creation.preview
        }).addClass('jpreview').prepend(
          $('<img>').attr({
            src: '/i/icon_listen_large_plain.gif',
            alt: creation.title
          })
        )
      );
    }else{//graphic creation
      creationLi.append(
        $('<a>').attr('href',creation.link).append(
          $('<img>').attr({
            src: creation.preview,
            alt: creation.title
          }).addClass('previewImage')
        )
      )
    }

    creationLi.append(
      $('<span>').addClass('type').text(creation.typeName)
    )

    var creationH3 = $('<h3>').addClass('title').append(
        $('<a>').attr('href',creation.link).addClass('title').text(creation.title)
      );
    if (creation.author && creation.type != 'truetone'){
      creationH3.append(
        $('<a>').attr('href',creation.link).addClass('author').text(' - ' + creation.author)
      )
    }
    creationLi.append(creationH3);
    container.append(creationLi);
  }

}