/*
#####################################################
# 
# Neil Lerner Kitchens
# Scrapbook JavaScript engine
#
# Hand-crafted by Phenotype (phenotype.net)
#
#####################################################
*/

//some strings
var strCouldNotBeAdded = 'This photo could not be added to a Scrapbook';
var strWasAdded = 'This photo was added to your Scrapbook';
var strAlreadyAdded = 'You already have this photo in your Scrapbook';
var strCouldNotBeSaved = 'Your Scrapbook could not be saved';
var strScrapbookSaved = 'Your Scrapbook was saved';
var strCouldNotBeRetrieved = 'Your Scrapbook could not be retrieved';
var strScrapbookRerieved = 'Your Scrapbook was retrieved';
var strItemCouldNotBeRemoved = 'Item could not be removed from Scrapbook';
var strItemRemoved = 'The item was removed from your Scrapbook';

var strZeroItems = '<p>You have 0 items in your scrapbook.</p>';

//some elements
var elemAddWrapper;
var elemScrapbookMessage;
var elemScrapbookInfo;
var elemScrapbookSaved;
var elemScrapbookCount;
var elemScrapbookEmail;
var elemScrapbookName;

//other global vars
var clicked;
//var img;
var apiUrl;

function initialiseElemVars() {
  elemAddWrapper = jQuery('p.add-scrapbook');
  elemScrapbookMessage = jQuery('#scrapbook-message');
  elemScrapbookInfo = jQuery('#scrapbook-info');
  elemScrapbookSaved = jQuery('#scrapbook-saved');
  elemScrapbookCount = jQuery('#scrapbook-count');
  elemScrapbookEmail = jQuery('#scrapbook-email');
  elemScrapbookName = jQuery('#scrapbook-name');
}

function updateScrapbookMessage(strText) {
  jQuery(elemScrapbookMessage).html(strText);
  jQuery(elemScrapbookMessage).fadeIn('normal');
}

function updateScrapbookInfo(data) {
  jQuery(elemScrapbookSaved).hide();

  if (data.scrapbookCount==0) { data.scrapbookCount = '0'; }

  jQuery(elemScrapbookCount).html(data.scrapbookCount);    
  jQuery(elemScrapbookInfo).fadeIn('normal');

  if (data.scrapbookEmail!='') {
    jQuery(elemScrapbookEmail).html(data.scrapbookEmail);
    jQuery(elemScrapbookName).html(data.scrapbookName); 
    jQuery(elemScrapbookSaved).fadeIn('normal');
  }
}

function ajaxDealWithResponse(data) {
  switch(data.actionCode-0) {
    case 0:  //login to scrapbook
      if (data.actionStatus==0) {
        updateScrapbookMessage(strCouldNotBeRetrieved);
      } else if (data.actionStatus==1) {
        updateScrapbookMessage(strScrapbookRerieved);
        updateScrapbookInfo(data);

        //jQuery('.view-scrapbook a').attr('href', data.scrapbookLink);
        jQuery('.view-scrapbook').fadeIn('normal');
      }
      tb_remove();
      break;

    case 1:  //save scrapbook
      if (data.actionStatus==0) {
        updateScrapbookMessage(strCouldNotBeSaved);
      } else if (data.actionStatus==1) {
        updateScrapbookMessage(strScrapbookSaved);
      }

      tb_remove();

      updateScrapbookInfo(data);

      break;

    case 2: //add to scrapbook
      if (data.actionStatus==0) {
        updateScrapbookMessage(strCouldNotBeAdded);
      } else if (data.actionStatus==1) {
        updateScrapbookMessage(strWasAdded);
      } else if (data.actionStatus==2) {
        updateScrapbookMessage(strAlreadyAdded);
      }

      if (!data.actionStatus==0) {
        updateScrapbookInfo(data);
        //jQuery('.view-scrapbook a').attr('href', data.scrapbookLink);
        jQuery('.view-scrapbook').fadeIn('normal');
      }

      jQuery(elemAddWrapper).removeClass('loading-sml');
      jQuery('.view-scrapbook').fadeIn('normal');

      break;

    case 3: //remove from scrapbook
      if (data.actionStatus==0) {
        updateScrapbookMessage(strItemCouldNotBeRemoved);
      } else if (data.actionStatus==1) {
        updateScrapbookMessage(strItemRemoved);
        jQuery('#item-'+data.resourceId+', .secondary li#'+data.resourceId).fadeOut('normal');
      }

      updateScrapbookInfo(data);

      if (data.scrapbookCount<1) {
        jQuery('#scrapbook').empty().html(strZeroItems);
      }
      break;

    case 4: //get scrapbook info
      jQuery('#retrieve-scrapbook-form').attr('action', apiUrl+'?action=0');
      if (data.actionStatus==1) { //if the fetch worked
        updateScrapbookInfo(data);
        jQuery('form#save-scrapbook-form').attr('action', apiUrl+'?action=1');
        jQuery('input#save-email').attr('value', data.scrapbookEmail);
        jQuery('input#save-name').attr('value', data.scrapbookName);
        //jQuery('.view-scrapbook a').attr('href', data.scrapbookLink);
        jQuery('.view-scrapbook').fadeIn('normal');
      }

      break;

    case 5: //remove scrapbook
      
      break;

    case 6: //flush session and cookie

      break;    

    default:
  }

  return data;
}

function mycarousel_initCallback(carousel) {
    jQuery('.primary .next a').bind('click', function() {
        //jQuery('.current-photo').next().children('a').click();
        //console.log(jQuery('ul.jcarousel-list li.current-photo').size());
        //carousel.scroll(jQuery('ul.jcarousel-list').index(jQuery('li.current-photo')));
        return false;
    });

    jQuery('.primary .previous a').bind('click', function() {
      //console.log('prev');
      //console.log(jQuery('.current-photo').prev().index());
      //carousel.scroll(jQuery('.current-photo').prev().index());
      return false;
    });
};

function loadNewImage() {
  jQuery('#photostream-main img').remove();

  //create the new image object
  img = jQuery(new Image());

  //assign the load event
  jQuery(img).load(function() {
    jQuery('.primary').removeClass('loading');
    jQuery(this).css('display','none');

    jQuery('#photostream-main a').attr({
      href: jQuery(clicked).attr('rel'),
      title: jQuery(clicked).attr('title')
    }).append(this);

    //fade the image in
    jQuery(this).fadeIn('normal');

    //load the related images
    var strTags = jQuery(clicked).next().next().html();
    //console.log(strTags);
    jQuery('#related').load('related-images-ajax-feed?&docid=' + idDocId + '&doclist_tags='+escape(strTags), function() {
      jQuery('#related').fadeIn('slow');
    });
  }).error(function () {

  }).attr({
    src: jQuery(clicked).attr('href'),
    alt: jQuery(clicked).attr('title'),
    title: jQuery(clicked).attr('title')
  });
}

jQuery(document).ready(function() {
  initialiseElemVars();

  //store the basic scrapbook api url
  if (jQuery('.add-scrapbook').size()>0) { 
    apiUrl = jQuery('.add-scrapbook a').attr('href'); 
  } else if (jQuery('#retrieve-scrapbook-form').size()>0) { 
    apiUrl = jQuery('#retrieve-scrapbook-form').attr('action');
  }

  //primary next button
  jQuery('.primary .next a').click(function() {
    jQuery('.current-photo').next().children('a').click();
    return false;
  });

  //primary previous button click event
  jQuery('.primary .previous a').click(function() {
    jQuery('.current-photo').prev().children('a').click();
    return false;
  });

  //secondary thumb nail click
  jQuery('.secondary ul li a').click(function() {
    //Check we've not just clicked on the already loaded image
    if (jQuery(this).children('img').attr('src')==jQuery(clicked).children('img').attr('src')) {
      return false;
    }

    //take the selected class off the last clicked item
    jQuery(clicked).parent().removeClass('current-photo');
    jQuery('#browse-all .thumbnail-list li.current-photo').removeClass('current-photo');

    //assign whats just been clicked
    clicked = jQuery(this);

    jQuery('#photostream-main img').fadeOut('fast', function () {
      jQuery('.primary').addClass('loading');
      jQuery('#related').fadeOut('fast');
      loadNewImage();
    });

    //assign the selected class
    jQuery(clicked).parent().addClass('current-photo');
    jQuery('#browse-all .thumbnail-list ul li a').eq(jQuery('.secondary ul li a').index(this)).parent().addClass('current-photo');

    //change the title
    jQuery('#canvas-overview h4.item-title').fadeOut('fast', function () {
      jQuery('#canvas-overview h4.item-title').html(jQuery(clicked).attr('title')).fadeIn('normal');
    });

    //fadeout the keywords and back again
    jQuery('p.keywords').fadeOut('fast', function() {
      jQuery('p.keywords span.img-keywords').html(jQuery(clicked).next().html());
    }).fadeIn('normal');

    //set up the add to scrapbook url
    jQuery('.add-scrapbook a').attr('href', apiUrl+'?action=2&resource='+jQuery('.secondary ul li.current-photo').attr('id'));

    return false;
  });

  //view larger image button (stimulates click event on main image)
  jQuery('.view-larger a').click(function() {
    jQuery('#photostream-main a').click();
    return false;
  });

  //view photostream img button
  jQuery('.view-photostream a').click(function() {
    var strLink = jQuery(this).attr('id');
    strLink = strLink.substring(5, strLink.length);
    jQuery('ul#canvas-navigation').tabs('select', 1);
    jQuery('.secondary ul li#'+strLink+' a:first').click();
    return false;
  });


  //browse all thumbnail click
  jQuery('#browse-all .thumbnail-list li a').click(function() {
    jQuery('.secondary ul li a').eq(jQuery('#browse-all .thumbnail-list ul li a').index(this)).click();
    jQuery('ul#canvas-navigation').tabs('select', 0);
    return false;
  });

  //assign the click event to add to scrapbook
  jQuery('.add-scrapbook a').click(function() {
    jQuery(elemAddWrapper).addClass('loading-sml');
    jQuery('#scrapbook-message, #scrapbook-info').fadeOut('fast');
    jQuery.getJSON(jQuery(this).attr('href'), function(data) {
      ajaxDealWithResponse(data);
    });
    return false;
  });

  //assign the click event to remove from scrapbook
  jQuery('.delete-item a').click(function() {
    jQuery.getJSON(apiUrl+'?&action=3&resource='+jQuery(this).attr('href'), function(data) {
      ajaxDealWithResponse(data);
    });
    return false;
  });

  //view more details button
  jQuery('p.more-information a').click(function() {
    jQuery('div.more-information').slideToggle();
    return false;
  });
  
  //assign ajax form submit events
  jQuery("#save-scrapbook-form").validate({ submitHandler: function(form) { jQuery(form).ajaxSubmit({ dataType:  'json', success: function(data) { ajaxDealWithResponse(data); } }); } });
  jQuery('#retrieve-scrapbook-form').validate({ submitHandler: function(form) { jQuery(form).ajaxSubmit({ dataType:  'json', success: function(data) { ajaxDealWithResponse(data); } }); } });

  //fade in and do the random scrapbook layouts
  jQuery('.scrapbook-layout').hide();
  //jQuery('.scrapbook-layout').tsort('',{order:'rand'});
  jQuery('.scrapbook-layout:hidden:eq(0)').fadeIn('normal', function() {
    jQuery(this).next().fadeIn('normal', arguments.callee);		
  });

  //setup the scrapbook info for first use
  //hide all the controls
  jQuery('#scrapbook-message, #scrapbook-saved, #scrapbook-info, .view-scrapbook, div.more-information').hide();

  //Ajax for the scrapbook details
  jQuery.getJSON(apiUrl+'?action=4', function(data) { ajaxDealWithResponse(data); });

  //rock the crousel
  jQuery(".secondary ul").jcarousel({ scroll: 4, initCallback: mycarousel_initCallback });

  //activate the carousel on the scrapbook page (special case)
  jQuery('#scrapbook-page .ui-tabs-nav').bind('tabsshow', function(event, ui) { if (ui.index==1) { jQuery("#scrapbook-page .secondary ul").jcarousel({ scroll: 4 }); } });

  //rock the lightbox
  jQuery('a[@rel*=lightbox]').lightBox();

  //load the first secondary thumb into the main image (by stimulating the click)
  if (idShow!=-1) { jQuery('.secondary ul li#'+idShow+' a:first').click(); } else { jQuery('.secondary ul li a:first').click(); }
});
