/*
 * Accordion 1.3 - jQuery menu widget
 *
 * Copyright (c) 2006 Jï¿½rn Zaefferer, Frank Marcia
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.accordion.js 1524 2007-03-13 20:09:19Z joern $
 *
 */

/**
 * Make the selected elements Accordion widgets.
 *
 * Semantic requirements:
 *
 * If the structure of your container is flat with unique
 * tags for header and content elements, eg. a definition list
 * (dl > dt + dd), you don't have to specify any options at
 * all.
 *
 * If your structure uses the same elements for header and
 * content or uses some kind of nested structure, you have to
 * specify the header elements, eg. via class, see the second example.
 *
 * Use activate(Number) to change the active content programmatically.
 *
 * A change event is triggered everytime the accordion changes. Apart from
 * the event object, all arguments are jQuery objects.
 * Arguments: event, newHeader, oldHeader, newContent, oldContent
 *
 * @example jQuery('#nav').Accordion();
 * @before <dl id="nav">
 *   <dt>Header 1</dt>
 *   <dd>Content 1</dd>
 *   <dt>Header 2</dt>
 *   <dd>Content 2</dd>
 * </dl>
 * @desc Creates an Accordion from the given definition list
 *
 * @example jQuery('#nav').Accordion({
 *   header: 'div.title'
 * });
 * @before <div id="nav">
 *  <div>
 *    <div class="title">Header 1</div>
 *    <div>Content 1</div>
 *  </div>
 *  <div>
 *    <div class="title">Header 2</div>
 *    <div>Content 2</div>
 *  </div>
 * </div>
 * @desc Creates an Accordion from the given div structure
 *
 * @example jQuery('#nav').Accordion({
 *   header: 'a.head'
 * });
 * @before <ul id="nav">
 *   <li>
 *     <a class="head">Header 1</a>
 *     <ul>
 *       <li><a href="#">Link 1</a></li>
 *       <li><a href="#">Link 2></a></li>
 *     </ul>
 *   </li>
 *   <li>
 *     <a class="head">Header 2</a>
 *     <ul>
 *       <li><a href="#">Link 3</a></li>
 *       <li><a href="#">Link 4></a></li>
 *     </ul>
 *   </li>
 * </ul>
 * @desc Creates an Accordion from the given navigation list
 *
 * @example jQuery('#accordion').Accordion().change(function(event, newHeader, oldHeader, newContent, oldContent) {
 *   jQuery('#status').html(newHeader.text());
 * });
 * @desc Updates the element with id status with the text of the selected header every time the accordion changes
 *
 * @param Map options key/value pairs of optional settings.
 * @option String|Element|jQuery|Boolean active Selector for the active element, default is the first child, set to false to display none at start
 * @option String|Element|jQuery header Selector for the header element, eg. div.title, a.head, default is the first child's tagname
 * @option String|Number showSpeed Speed for the slideIn, default is 'slow' (for numbers: smaller = faster)
 * @option String|Number hideSpeed Speed for the slideOut, default is 'fast' (for numbers: smaller = faster)
 * @option String selectedClass Class for active header elements, default is 'selected'
 * @option Boolean alwaysOpen Whether there must be one content element open, default is true.
 * @option Boolean animated Set to false to disable animations. Default: true
 * @option String event The event on which to trigger the accordion, eg. "mouseover". Default: "click"
 *
 * @type jQuery
 * @see activate(Number)
 * @name Accordion
 * @cat Plugins/Accordion
 */

/**
 * Activate a content part of the Accordion programmatically at the given zero-based index.
 *
 * If the index is not specified, it defaults to zero, if it is an invalid index, eg. a string,
 * nothing happens.
 *
 * @example jQuery('#accordion').activate(1);
 * @desc Activate the second content of the Accordion contained in <div id="accordion">.
 *
 * @example jQuery('#nav').activate();
 * @desc Activate the first content of the Accordion contained in <ul id="nav">.
 *
 * @param Number index (optional) An Integer specifying the zero-based index of the content to be
 *				 activated. Default: 0
 *
 * @type jQuery
 * @name activate
 * @cat Plugins/Accordion
 */
 
/**
 * Override the default settings of the Accordion. Affects only following plugin calls.
 *
 * @example jQuery.Accordion.setDefaults({
 * 	showSpeed: 1000,
 * 	hideSpeed: 150
 * });
 *
 * @param Map options key/value pairs of optional settings, see Accordion() for details
 *
 * @type jQuery
 * @name setDefaults
 * @cat Plugins/Accordion
 */

jQuery.fn.extend({
	// nextUntil is necessary, would be nice to have this in jQuery core
	nextUntil: function(expr) {
	    var match = [];
	
	    // We need to figure out which elements to push onto the array
	    this.each(function(){
	        // Traverse through the sibling nodes
	        for( var i = this.nextSibling; i; i = i.nextSibling ) {
	            // Make sure that we're only dealing with elements
	            if ( i.nodeType != 1 ) continue;
	
	            // If we find a match then we need to stop
	            if ( jQuery.filter( expr, [i] ).r.length ) break;
	
	            // Otherwise, add it on to the stack
	            match.push( i );
	        }
	    });
	
	    return this.pushStack( match );
	},
	// the plugin method itself
	Accordion: function(settings) {
		// setup configuration
		settings = jQuery.extend({}, jQuery.Accordion.defaults, {
			// define context defaults
			header: jQuery(':first-child', this)[0].tagName // take first childs tagName as header
		}, settings);

		// calculate active if not specified, using the first header
		var container = this,
			active = settings.active
				? jQuery(settings.active, this)
				: settings.active === false
					? jQuery("<div>")
					: jQuery(settings.header, this).eq(0),
			running = 0;

		container.find(settings.header)
			.not(active || "")
			.nextUntil(settings.header)
			.hide();
		active.addClass(settings.selectedClass);

		function clickHandler(event) {
			// get the click target
			var clicked = jQuery(event.target);
			
			// due to the event delegation model, we have to check if one
			// of the parent elements is our actual header, and find that
			if ( clicked.parents(settings.header).length ) {
				while ( !clicked.is(settings.header) ) {
					clicked = clicked.parent();
				}
			}
			
			var clickedActive = clicked[0] == active[0];
			
			// if animations are still active, or the active header is the target, ignore click
			if(running || (settings.alwaysOpen && clickedActive) || !clicked.is(settings.header))
				return;

			// switch classes
			active.toggleClass(settings.selectedClass);
			if ( !clickedActive ) {
				clicked.addClass(settings.selectedClass);
			}

			// find elements to show and hide
			var toShow = clicked.nextUntil(settings.header),
				toHide = active.nextUntil(settings.header),
				data = [clicked, active, toShow, toHide];
			active = clickedActive ? jQuery([]) : clicked;
			// count elements to animate
			running = toHide.size() + toShow.size();
			var finished = function(cancel) {
				running = cancel ? 0 : --running;
				if ( running )
					return;

				// trigger custom change event
				container.trigger("change", data);
			};
			// TODO if hideSpeed is set to zero, animations are crappy
			// workaround: use hide instead
			// solution: animate should check for speed of 0 and do something about it
			if ( settings.animated ) {
				if ( !settings.alwaysOpen && clickedActive ) {
					toShow.slideToggle(settings.showSpeed);
					finished(true);
				} else {
					toHide.filter(":hidden").each(finished).end().filter(":visible").slideUp(settings.hideSpeed, finished);
					toShow.slideDown(settings.showSpeed, finished);
				}
			} else {
				if ( !settings.alwaysOpen && clickedActive ) {
					toShow.toggle();
				} else {
					toHide.hide();
					toShow.show();
				}
				finished(true);
			}
			//return false;
			return !toShow.length;
		};
		function activateHandlder(event, index) {
			// call clickHandler with custom event
			clickHandler({
				target: jQuery(settings.header, this)[index]
			});
		};

		return container
			.bind(settings.event, clickHandler)
			.bind("activate", activateHandlder);
	},
	// programmatic triggering
	activate: function(index) {
		return this.trigger('activate', [index || 0]);
	}
});

jQuery.Accordion = {};
jQuery.extend(jQuery.Accordion, {
	defaults: {
		selectedClass: "selected",
		showSpeed: 'slow',
		hideSpeed: 'fast',
		alwaysOpen: true,
		animated: true,
		event: "click"
	},
	setDefaults: function(settings) {
		jQuery.extend(jQuery.Accordion.defaults, settings);
	}
});


/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
/**************************MOVED FROM CAROUSEL.JS***************************/
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/

// Copyright (c) 2006 Sébastien Gruhier (http://xilinus.com, http://itseb.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// VERSION 0.26
var Carousel = Class.create();
Carousel.prototype = {
 // Constructor
 initialize: function(carouselElemID) {
 
  this.carouselElemID = carouselElemID;

  this.options = Object.extend({
    numVisible: 4,
    scrollInc: 3,
    updateurl:    'you must specify this ',
    siteRootPath: 'you must specify this ',  
    animParameters: {},
    buttonStateHandler: null,
    animHandler: null,
    ajaxHandler: null,
    initDoneHandler: null,
    queue: "carousel",
    size: 0,
    prevElementID: "prev-arrow",
    nextElementID: "next-arrow",    
    ajaxParameters: null,
    id_prefix:"",
    start_with:"1",
    goback: '0',
    hasPageGroup: null,
    url: null
  }, arguments[1] || {});



   this.initDone = false;
   this.animRunning = "none";
   this.requestIsRunning = false;

   // add afterFinish options to animParameters (store old function)
   this.animAfterFinish = this.options.animParameters.afterFinish;
   Object.extend(this.options.animParameters, {afterFinish: this._animDone.bind(this), queue: { position:'end', scope: this.options.queue }});

   // Event bindings
   this.prevScroll     = this._prevScroll.bindAsEventListener(this);
   this.nextScroll     = this._nextScroll.bindAsEventListener(this);
   this.onComplete     = this._onComplete.bindAsEventListener(this);
   this.onFailure      = this._onFailure.bindAsEventListener(this);
   
   this.paginateTo     = this._paginateTo.bindAsEventListener(this);
   this.updateCarousel = this._updateCarousel.bindAsEventListener(this);      


   Event.observe(this.options.prevElementID, "click", this.prevScroll);
   Event.observe(this.options.nextElementID, "click", this.nextScroll);

   //added by JCo kudosweb   
   
   Event.observe((this.options.prevElementID + "-pagination"), "click", this.prevScroll);
   Event.observe((this.options.nextElementID + "-pagination"), "click", this.nextScroll);
   
   //added by LA
    $$('.page-groups', '.page-groups-selected').each(function(element){element.observe("click", changePageGroups);},this);

   // Get DOM UL element
   var carouselListClass = this.options.id_prefix + "carousel-list";
   
   this.carouselList = document.getElementsByClassName(carouselListClass, $(carouselElemID))[0]

   this.options.size = $(this.carouselList.getElementsByTagName("li")).length;

   
   this.attatchPaginationEvents();   
    	
   // Init data
   this._init();
   
 },

 // Destructor
 destroy: function() {
 
   Event.stopObserving(this.options.prevElementID, "click", this.prevScroll);
   Event.stopObserving(this.options.nextElementID, "click", this.nextScroll);
  
 },
 
 attatchPaginationEvents: function(){
 
    var paginationFunction = function(event,element){
      element.observe("click", this.paginateTo);
    }


    $$('.' + this.options.id_prefix  + 'page', '.' + this.options.id_prefix  + 'page-selected').each(function(element){element.observe("click", this.paginateTo);},this);
 
 }
 ,
 scrollTo: function(newStart,event) {

   var old_inc = this.options.scrollInc;
   this.ignoreNoMoreImages = true;
    
   if(newStart > this.currentIndex) {

     this.options.scrollInc = newStart - this.currentIndex;
     
     this._nextScroll(this,event);

   } else {

     this.options.scrollInc = this.currentIndex - newStart;
     
     this._prevScroll(this,event);

   }
   this.options.scrollInc = old_inc;
   
   this.stopEvent(event);
 
 },
 
 logTime: function(message){
    //only for debugging (JCO)
    var d = new Date();
    console.log(message + " "  + d.getMinutes() + ":" +  d.getSeconds() + ":" + d.getMilliseconds());
 
 }
 ,
 
 _paginateTo: function(event){

    var element = event.element();
   
    var page_number = element.id;
    //if they are at the begining or the end of the pagination
    if(page_number == (this.options.id_prefix +"next-arrow-pagination") || page_number == (this.options.id_prefix + "prev-arrow-pagination")){

      page_number = 0;

    }else{

      page_number = page_number.substr(this.options.id_prefix.length + 11,page_number.length);

    }    
    
    
    this.scrollTo((page_number) - 1, event); 

    return false;
    
 }
 
 ,
 
 setPaginationHighlight: function(page){

   
   $$('.' + this.options.id_prefix + 'page-selected').each(function(element){
      
     element.writeAttribute("class","page");
   
   });
   
   $(this.options.id_prefix + 'pagination_'+page).writeAttribute("class",this.options.id_prefix + "page-selected");
   $(this.options.id_prefix + 'pagex').update(page);	
 }
 ,

 /* "Private" functions */
 _init: function() {
 
   this.currentIndex = 0;

   // Ajax content
   if (this.options.url && this.options.goback != '1'){
	 
     this._request(this.currentIndex, this.options.numVisible); 
   }
     // Static content

   else {

      this._getLiElementSize();
      //this._updateButtonStateHandler(this.options.prevElementID, false);
      //this._updateButtonStateHandler(this.options.nextElementID, this.options.size > this.options.numVisible);
   }
 },

 _prevScroll: function(event) {

   if (this.animRunning != "none")
   return this.stopEvent(event);

   var inc = this.options.scrollInc;
  
   var newPage = 1;
   
   if (this.currentIndex - inc < 0){
   
     inc = this.currentIndex;     
   }
   
   
   if(this.currentIndex - inc > 0){
   
    newPage = (this.currentIndex - inc) + 1;
   
   }
     
   //LA - if the user is on the very first page and clicks back, inc will == 0, so we will
   //get the total page size, and inc which is the amount of pages to go past
   if (inc == 0)
   {
      newPage = this.options.size;
      inc = -(this.options.size - 1);
   }

   paginationStatePrev(newPage, 20, this.options.size)
  
   this.fillWithData(newPage, true);
   this._scroll(inc)
   return this.stopEvent(event);
 },

 stopEvent: function(event){
  
  try{
  
    if(event != null){ 
      Event.stop(event);
    }
  }catch(e){
  
    //sometimes it has a problem 
    //stopping in certain browsers  
  }

  return false;
 
 }
 ,
 _nextScroll: function(event) {
    
    if (this.animRunning != "none")
    return this.stopEvent(event);

    //added by JCo kudos
    this.nbInCache = this.options.size - (this.currentIndex + this.options.numVisible);

    var page = (this.currentIndex + this.options.numVisible + this.nbInCache) +  (this.options.scrollInc - this.nbInCache);

  //LA - when the user clicks the next link on the very last page, this takes them back to page
  //one, also stops the href event set on the link
  if (page > this.options.size)
  {
    this.fillWithData(1, true);
    this._scroll(this.options.size - 1)
    paginationStateNext(0, 20, this.options.size)
    //paginationState();
    return this.stopEvent(event);
  }
  paginationStateNext(page, 20, this.options.size)
    this.fillWithData(page, true);
    
    // Check if there are enough elements in cache
    if (this.currentIndex + this.options.numVisible + this.options.scrollInc <= this.options.size)    
      
      this._scroll(-this.options.scrollInc);
      
    else {
    
     // Compute how many are in the cache
     
     if (this.options.url && this.noMoreImages == false)

      this._request(this.currentIndex + this.options.numVisible + this.nbInCache, this.options.scrollInc - this.nbInCache);
      

     else {

     if (this.nbInCache > 0)
     
       this._scroll(-this.nbInCache);
       
     }
     
   }
    
   return this.stopEvent(event);
 },

 _request: function(start, nb) {
 
 
 if (this.options.url && ! this.requestIsRunning) {
 
   this.requestIsRunning = true;

   if (this.options.ajaxHandler)
   
     this.options.ajaxHandler(this, "before");

     var params = "start=" + start + "&nb=" + nb;
     
     if (this.options.ajaxParameters != null)
       params += "&" + this.options.ajaxParameters;
 			 
     //JCO set the method to get
     new Ajax.Request(this.options.url, {method: 'get', parameters: params, onComplete: this.onComplete, onFailure: this.onFailure});

 }  
 
 },
 
 fillWithData: function (page,sideFill){

   var asynchronousAjax = sideFill ? false : true;
   
   
   var sideFillParam = sideFill ? "sidefill=0" : "sidefill=1";
   
   var pageGroupURL = '';
   if (this.options.hasPageGroup == true)
   {
   	 var url = $('pagination_' + page).href;
   	 var url_query = url.camelize().toQueryParams();
   	 var pageGroup = url_query.pageGroup;
   	 pageGroupURL = '&page-group=' + pageGroup;
   }
      
   var params = "page=" + page + "&" + sideFillParam + pageGroupURL;

   if(this.containerEmpty(page)){

     this.updatePage = page;
		 
     new Ajax.Request(this.options.updateurl, {method: 'get', asynchronous: asynchronousAjax ,parameters: params, onComplete: this.updateCarousel, onFailure: this.onFailure});

   }

    try{

      this.fadeImageIn(page); //this is for the lookbook only!
    }catch(e){}

    this.clearOldCarouselPages(page,this.options.size);

    this.setPaginationHighlight(page);
  
 
 
 },
 
 fadeImageIn: function (page){
   
	if ($('lookbook-image-' + page))
	{
    	var imgPath = $('lookbook-image-' + page).value;
    	var element = $('lookbook-image');
  
    	element.writeAttribute('src',imgPath);
	}
  
	//Reflection.add($('lookbook-image'), { height: 0.25, opacity: 1 });
 } 
 ,
 
 clearOldCarouselPages: function (page,totalLength){
   
   for(var i = 1; i <= totalLength; i++){
   
     if(i != page && i != (page + 1) && i != (page - 1)){
      
      
      $(this.options.id_prefix + 'carousel_p_' + i).update("");
      
     }

   }
 
 }
 
 , 
 containerEmpty: function(page){
  
   if ($(this.options.id_prefix +'carousel_p_' + page) == null)
   {
    return $(this.options.id_prefix +'carousel_p_' + 1).empty(); 
   }  
   else
   {
    return $(this.options.id_prefix +'carousel_p_' + page).empty(); 
   }

 }
 ,
 _onComplete: function(originalRequest){ 
 
 
     this.requestIsRunning = false;
     this.carouselList.innerHTML = originalRequest.responseText;
     // Compute how many new elements we have
     var size = this.options.size;
     this.options.size = this.carouselList.getElementsByTagName("li").length;
     var inc = this.options.size - size;

     // First run, compute li size
     if (this.initDone == false) {
     this._getLiElementSize()
     this.currentIndex = 0;
     this.initDone = true;
     if (this.options.initDoneHandler)
     this.options.initDoneHandler(this);

     // Update button states
     //this._updateButtonStateHandler(this.options.prevElementID, false);
     //this._updateButtonStateHandler(this.options.nextElementID, this.options.size > 1);
     this.noMoreImages = this.options.size < this.options.numVisible
     }
     // Add images
     else {
     if (!this.ignoreNoMoreImages)
       this.noMoreImages = inc != this.options.scrollInc;
     else
       this.ignoreNoMoreImages = false;
       // Add images
     if (inc > 0) {
       this._scroll(-inc, this.noMoreImages)
     }
     // No more images, disable next button
     else {
     if (this.nbInCache >0)
     
     
     this._scroll(-this.nbInCache, true);

     //this._updateButtonStateHandler(this.options.nextElementID, false);
     }
     }
     if (this.options.ajaxHandler)
     this.options.ajaxHandler(this, "after");

     //added by kudos     
     preparePage();

     if(this.options.start_with > 1){

      this.scrollTo(this.options.start_with - 1,null);

     }else{

       this.fillWithData(1, true);

     }
 },

 _onFailure: function(originalRequest){
 this.requestIsRunning = false;
 },

  _updateCarousel: function (originalRequest){

    var start = (this.currentIndex + this.options.numVisible + this.nbInCache);
    var nb    = (this.options.scrollInc - this.nbInCache);
    
    //var pageNumber = (start -1) + nb;
    
    var pageNumber = this.updatePage;
    
    $(this.options.id_prefix + 'carousel_p_' + pageNumber).update(originalRequest.responseText);
    
    preparePage();
  }

  ,
 _animDone: function(event){

 
 if (this.options.animHandler)
 this.options.animHandler(this.carouselElemID, "after", this.animRunning);

 this.animRunning = "none";
 // Call animAfterFinish if exists
 if (this.animAfterFinish)
  this.animAfterFinish(event);
 },

 _updateButtonStateHandler: function(button, state) {
 if (this.options.buttonStateHandler)
      
   this.options.buttonStateHandler(button, state, this.options.siteRootPath)
 },

 _scroll: function(delta, forceDisableNext) {
 this.animRunning = delta > 0 ? "prev" : "next";

 if (this.options.animHandler)
 this.options.animHandler(this.carouselElemID, "before", this.animRunning);

 new Effect.MoveBy(this.carouselList, 0, delta * this.elementSize, this.options.animParameters);
 this.currentIndex -= delta;
 //this._updateButtonStateHandler(this.options.prevElementID, this.currentIndex != 0);

 /*if (this.options.url && this.noMoreImages == false)
 enable = true;
 else
 enable = (this.currentIndex + this.options.numVisible < this.options.size);
 
     if ($(this.options.id_prefix + 'pagex').innerHTML == this.options.size)
    {
      this._updateButtonStateHandler(this.options.nextElementID, false);
    }
    else
    {
    this._updateButtonStateHandler(this.options.nextElementID, (forceDisableNext ? false : enable));
  }*/
 },

 _getLiElementSize: function() {
 var li = $(this.carouselList.getElementsByTagName("li")[0]);
 this.elementSize = li.getDimensions().width + parseFloat(li.getStyle("margin-left")) + parseFloat(li.getStyle("margin-right"));
 }
}

//working version, when the user is on the last page of the current pagination view
//the user has to click next to see the rest of the pages.
function paginationStateNext(page, perpage, totalpages)
{
  if (page == 0)
  {
    //first we show the first xx pages per page
    for (i = 1; i <= perpage; i++) 
    {
      if ($('pagenum_' + i))
      {
          $('pagenum_' + i).style.display = '';
      }
    }
    
    //then we hide all the pages after the xx pages per page
    for (i = perpage + 1; i <= (perpage + 1) + perpage; i++) 
    {
      if ($('pagenum_' + i))
      {
          $('pagenum_' + i).style.display = 'none';
      }
    }
    
  }
  else
  {
    if ((page - 1) % perpage == 0)
    {
      var topages = page + perpage;
      for (i = page - 1; i != topages; i++) 
      {
        if ($('pagenum_' + i))
        {
            $('pagenum_' + i).style.display = '';
        }
      }
      
      for (i = page - 1; i != 0; i--) 
      {
        if ($('pagenum_' + i))
        {
            $('pagenum_' + i).style.display = 'none';
        }
      }
    }
  }
}

//working version, when the user is on the first page of the current pagination view
//the user has to click back to see the rest of the pages.
function paginationStatePrev(page, perpage, totalpages)
{
  if (page == totalpages)
  {
    for (i = 1; i <= totalpages; i++) 
    {
      if ($('pagenum_' + i))
      {
          $('pagenum_' + i).style.display = 'none';
      }
    }
    var lastpages = totalpages % perpage;
    var totalpages = (totalpages + 1) - lastpages;
    for (i = totalpages; i <= totalpages + lastpages; i++) 
    {
      if ($('pagenum_' + i))
      {
          $('pagenum_' + i).style.display = '';
        }
    }
    
  }
  else
  { 
    if (page % perpage == 0)
    {
      page = page - perpage + 1;
      var topages = page + perpage;
      for (i = page; i <= topages; i++) 
      {
        if ($('pagenum_' + i))
        {
            $('pagenum_' + i).style.display = '';
        }
      }
      
      for (i = topages; i <= totalpages; i++) 
      {
        if ($('pagenum_' + i))
        {
            $('pagenum_' + i).style.display = 'none';
        }
      }
      }
  }
}
//LA - this will take the ID from the element, then use it to show/hide the required set of page groups
function changePageGroups(event)
{
  //hide all the pages first
  $$('.pagenumber').each(function(element){
        
      element.style.display = 'none';
     
  });
    
  var page_id = this.id.replace('pages-', '');
  var pages = page_id.split('-');
  var from = parseInt(pages[0]);
  var to = parseInt(pages[1]);
  
  for (i = from; i <= to; i++) {
	if ( $('pagenum_' + i) ) {
      $('pagenum_' + i).style.display = '';
	}
  }
  
  Event.stop(event);
}

// Enable/Disable next/previous buttons
function buttonStateHandler(button, enabled, siteRoot) {

  /*if (button == "prev-arrow") 
    $('prev-arrow').src = enabled ? (siteRoot + "/images/skin/product_carousel_back_active.png")    : (siteRoot + "/images/skin/product_carousel_back_dead.png");
  else 
    $('next-arrow').src = enabled ? (siteRoot + "/images/skin/product_carousel_forwards_active.png") : (siteRoot + "/images/skin/product_carousel_forwards_dead.png");*/
}

// Anim effects before and after scrolling
function animHandler(carouselID, status, direction) {
  var region = $(carouselID).down("." + this.options.id_prefix  + "carousel-clip-region")
  if (status == "before") {
    Effect.Fade(region, {to: 0.3, queue: { position:'end', scope: "carousel" }, duration: 0.2})
  }
  if (status == "after") {
    Effect.Fade(region, {to: 1, queue: { position:'end', scope: "carousel" }, duration: 0.2})
  }
}

// Show/hide "loading" overlay before and after ajax request
function ajaxHandler(carousel, status) {
  var overlay = $('overlay');
  if (status == "before") {
    if (overlay) {
      overlay.setOpacity(0);
      overlay.show();
      Effect.Fade(overlay, {from: 0, to: 0.8, duration: 0.2})
    }
    else
      new Insertion.Top("product-data", "<div id='overlay' >Loading...<br><img src='/images/ajax-loader.gif'></div>");
  }
  else 
    Effect.Fade(overlay, {from: 0.8, to: 0.0, duration: 0.2})
}


/*****
* additions by Kudos
****/
function preparePage(){

  //thnings that need to be done to get the page ready for the user!

  replaceMainLinks(); //NOTICE! this method is located in tht booohoo.js file

  attatchColorRoloverEvent();

  attatchGreyProductFrames();
        
}


/**
* Changes the displayed image when the color options are clicked on
*/
function attatchColorRoloverEvent(){
  
  
  $$('.color-rollover').each(function(productDivElement){
    
     
     productDivElement.observe('click', function(event){
      
    $$('#carousel-product-' + productDivElement.id + ' .color-rollover').each(function(productDivElement){
      productDivElement.style.border = "1px solid #cccccc";     
  });
     
     var inputElements = productDivElement.childElements();
     
     var inputElement       = inputElements[0]; //src should always be the first one
     var linkInputElement = inputElements[1]; //height should always be the second one
     var heightInputElement = inputElements[2]; //height should always be the second one
     
     
     var allParents = productDivElement.ancestors();

     var colorDiv = allParents[0];

     var allSiblings = colorDiv.previousSiblings();
     
     var imageContainer = allSiblings[0];
     
     
     //now collect the <img> tag and change the href attribute
     var linkTag = ((imageContainer.childElements())[0]);
     var imageTag = ((linkTag.childElements())[0]);

	 //alert(imageTag.style.backgroundImage);
		 
     //imageTag.writeAttribute('style',"display:none");
     //imageTag.writeAttribute('src',inputElement.readAttribute("value"));
		 
	 imageTag.style.backgroundImage = 'url(' + inputElement.readAttribute("value") + ')';
	 linkTag.href = "javascript:standardPageRequest('"+linkInputElement.readAttribute('value')+"');";
     
     //too jumpy!
     //imageTag.writeAttribute('style',heightInputElement.readAttribute("value"));

     productDivElement.style.border = "1px solid black";
    });

  });
  

}

/**
* Creates a grey border around a product onMouseover
*/
function attatchGreyProductFrames(){
  //try to do all of the following! 
  //some will fail!
  try{
      attatchGreyProductFramesForClass('.carousel-product');
      attatchGreyProductFramesForClass('.lookbook-top-item-1');
      attatchGreyProductFramesForClass('.lookbook-top-item-0');
      attatchGreyProductFramesForClass('.lookbook-bottom-item-1');
      attatchGreyProductFramesForClass('.lookbook-bottom-item-0');
    }catch(e){
    //no error because we can not always know if it will work!
    }
}

/**
*
*/
function attatchGreyProductFramesForClass(className){

  $$(className).each(function(productDivElement){
      
     productDivElement.className = className.replace('.', '');  
     productDivElement.observe('mouseover', function(event){

       $$(className).each(function(innerElement){
       	 
         innerElement.style.border = "1px solid white";
          
       });
       
       if(! productDivElement.empty()){
        productDivElement.style.border = "1px solid #cccccc";

       }
        
    });
   
    productDivElement.observe('mouseout', function(event){
          productDivElement.style.border = "1px solid white";
    });  
  });

}