/**************************************
 ** AJAX functions.
 *************************************/
 
/**
 * Get a random number to add to the parameter of AJAX
 * to get a unique URL. This solves the problem of 
 * caching in Internet Explorer.
 */
function getUniqueParam() {
  return "&" + Math.round(Math.random() * 1000000);
}

/**
 * Functions which checks wether we were editing the page,
 * and if so, ask the user if he/she really wants to exit without saving the changes.
 */
var pageContentEditorInstance = null;
var boxContentEditorInstance = null;
function checkExitFCKEditor(elementId) {
  if (pageContentEditorInstance && elementId=='content') {
    if (window.confirm('Wanneer u wijzigingen hebt gemaakt in de pagina dan worden deze\nniet opgeslagen als u nu de pagina verlaat.\nWeet u zeker dat u de pagina wilt verlaten?')) {
      autosaveInterval = $clear(autosaveInterval);
      // Unload the CKEditor instances.
      unloadCKEditorInstances();
      pageContentEditorInstance = null;
      boxContentEditorInstance = null;
      return true;
    } else {
      return false;
    }
  }
  return true;
}
 
/**
 * Update an element.
 */ 
function updateElement(elementId, url, params) {
  if (checkExitFCKEditor(elementId)) {
	  new Request.HTML({  
	    url : url + '?' + params + getUniqueParam(),  
	    update : $(elementId)
	  }).get();
	}
}

/**
 * Update an element and perform a function on completion.
 */
function updateElementOnComplete(elementId, url, params, onCompleteFunction) {
  if (checkExitFCKEditor(elementId)) {
	  new Request.HTML({  
	    url : url + '?' + params + getUniqueParam(),
	    update : $(elementId),
	    onComplete : onCompleteFunction
	  }).get();
  }
}

/**
 * General function to update the content.
 */
function updateContentAndSidebar(url, theParams, updateSidebar) {
  // If the component cms_toolbar exists, do the cms on complete.
  if ($('cms_toolbar')) {
    updateContentOnComplete(url, theParams + '&output=content', cmsPageOnComplete, updateSidebar);
  } else {
	  updateElement('content', url, theParams + '&output=content');
	}
  
  // Update the sidebar if it exists.
  if (updateSidebar && $('sidebar')) {
    updateElement('sidebar', url, theParams + '&output=sidebar');
  }
}

function updateContent(url, theParams) {
  updateContentAndSidebar(url, theParams, true);
}

/**
 * Update the content and scroll to the anchor with name=anchorName.
 */
function updateContentAnchor(url, theParams, anchorName) {
  updateContentOnComplete(url, theParams, function() {
    window.open('#' + anchorName, '_self');
  });
}

/**
 * Update the content and perform a function on completion.
 */
function updateContentOnComplete(url, theParams, onCompleteFunction, updateSidebar) {
  // Update the content.
  updateElementOnComplete('content', url, theParams + '&output=content', onCompleteFunction);

  // Update the sidebar if it exists.
  if (updateSidebar && $('sidebar')) {
    updateElement('sidebar', url, theParams + '&output=sidebar');
  }
}

/**
 * Update the content when the question is confirmed.
 */
function confirmUpdateContent(question, url, theParams) {
  if (window.confirm(question)) {
    updateContent(url, theParams);
  }
}

function registerForm(formName, updateElementName) {
  $(formName).addEvent('submit', function(e) {
    /** Prevent the submit event. */
    new Event(e).stop();
    
    /** Perform the AJAX request using the contents of the form element. */
    var url = $(formName).action;
    new Request.HTML({
			url : url + '&output=content' + getUniqueParam(),
			update : $(updateElementName),
			onRequest : function() {
			  if ($(formName).getElement('input[type=submit]')) {
			    $(formName).getElement('input[type=submit]').disabled = true;
			  } else if ($(formName).getElement('button[type=submit]')) {
			    $(formName).getElement('button[type=submit]').disabled = true;
			  }
			},
			onComplete : function() {
			  // Update the sidebar if it exists.
			  if ($('sidebar')) {
			    updateElement('sidebar', url, '&output=sidebar');
			  }
			  if ($('page_toolbar'))
			    cmsPageOnComplete();
			}
    }).post($(formName));
  });
}

function registerFormUpdateContent(formName) {
  registerForm(formName, 'content');
}

/**************************************
 ** Photobook functions.
 *************************************/

/**
 * Function to update the enlarged photo when clicked on the thumbnail.
 */
function updateLargePhoto(photoId, photoUrl, photoDesc, prevPhotoId, nextPhotoId) {
  currentPhotoId = photoId;
  $('largePhoto').src = photoUrl;
  $('largePhotoDesc').innerHTML = photoDesc;
  if (prevPhotoId == 0) {
    $('largePhotoPrevious').onclick = null;
    $('largePhotoPrevious').style.textDecoration = 'none';
  } else {
    $('largePhotoPrevious').onclick = $('thumb_' + prevPhotoId).onclick;
    $('largePhotoPrevious').style.textDecoration = 'underline';
  }
  if (nextPhotoId == 0) {
    $('largePhotoNext').onclick = null;
    $('largePhotoNext').style.textDecoration = 'none';
  } else {
    $('largePhotoNext').onclick = $('thumb_' + nextPhotoId).onclick;
    $('largePhotoNext').style.textDecoration = 'underline';
  }
}

function performThumbClick(photoId, duration) {
  if ($('thumb_' + photoId)) {
	  currentPhotoId = photoId;
	  // Preload large photo.
	  new Asset.image(largePhotoAddress + photoId + '.jpg');
	  var disolveLargePhoto = new Fx.Tween('largePhoto', {property : 'opacity', duration : duration, onComplete: function() {
			$('thumb_' + photoId).onclick.call();
		  var evolveLargePhoto = new Fx.Tween('largePhoto', {property : 'opacity', duration : duration});
		  evolveLargePhoto.start(0, 100);
	  }});
	  disolveLargePhoto.start(100, 0);
  }
}

function startStopSlideshow() {
  if (slideshowIsRunning) {
    $('largePhotoSlideshow').innerHTML = 'Start slideshow';
    $clear(timer)
    slideshowIsRunning = false;
  } else {
    $('largePhotoSlideshow').innerHTML = 'Stop slideshow';
    slideshowIsRunning = true;
	  var myChain = new Chain();
	  var foundCurrent = 0;
	  var waitAtFirst = false;
	  photo_ids.each( function(photoId) {
		  // If the current photo is the last one, set the current photo to the first one.
	    if (currentPhotoId == photo_ids.getLast()) {
	      $('thumb_' + photoId).onclick.call();
	      waitAtFirst = true;
	    }
      if (foundCurrent == 2) {
        if (photoId == photo_ids.getLast()) {
          // The last function is different, since it needs to stop the timer and reset stuff.
          myChain.chain( function(){ 
            performThumbClick(photoId, 2000); 
			      runChain = $clear(timer);
			      $('largePhotoSlideshow').innerHTML = 'Start slideshow';
			      $clear(timer)
			      slideshowIsRunning = false;
          } );
        } else {
          myChain.chain( function(){ performThumbClick(photoId, 2000); } );
        } 
      // Search for the current photo and begin with the next one.
      } else if (foundCurrent == 1) {
        if (waitAtFirst) {
          myChain.chain( function(){ performThumbClick(photoId, 2000); } );
        } else {
          performThumbClick(photoId, 2000);
	        if (photoId == photo_ids.getLast()) {
		        runChain = $clear(timer);
		        $('largePhotoSlideshow').innerHTML = 'Start slideshow';
		        $clear(timer)
		        slideshowIsRunning = false;
	        }
        }
        foundCurrent = 2;
      } else if (photoId == currentPhotoId) {
        foundCurrent = 1;
      }
	  });
	  var runChain = function() {
	    if ($('largePhotoSlideshow')) {
		    myChain.callChain();
	    } else {
	      $clear(timer);
	      slideshowIsRunning = false;
	    }
	  }
	  timer = runChain.periodical(5000);
  }
}

/**
 * Scripts for the catalog.
 */
function catalog_updateLargePhoto(largePhotoUrl, originalPhotoUrl) {
  $('catalogLargePhoto').src=largePhotoUrl;
  $('catalogLargeLink').href=originalPhotoUrl;
}

