var fourSlides;

var ImageSlides2 = new Class({

  initialize: function( ul, slideTime ){

    this.slideTime    = slideTime;
    this.myFx1        = null;
    this.period       = null;

    this.mainUl       = $( ul );

		if ( !this.mainUl ) {
			return;
		}

    this.listItems    = this.mainUl.getElements( 'li.item' );

    this.slidesCount  = this.listItems.length;
    this.currentSlide = 0;

    this.listItems.forEach( function( el, i ){
      if( i > 0 ) {
        el.setOpacity(0);
        el.setStyle( 'display', 'none' );
      }
    } );
    this.startSliding();
    this.initButtons();
  },

  initButtons: function(){
  	var id = this.currentSlide;
  	if( $( 'slide_prev' ) ){
  		$( 'slide_prev' ).addEvent( 'click' , function( e ){
  			e.stop();
  			// Set right ID
  			id--;
  			if( id < 0 ) id = ( this.slidesCount - 1 );

  			$clear(this.period);
  			this.nextSlide(id);
  			this.period = this.nextSlide.periodical( this.slideTime, this );

  		}.bind( this ) );
  	}
  	if( $( 'slide_next' ) ){
  		$( 'slide_next' ).addEvent( 'click' , function( e ){
  			e.stop();
  			// Set right ID
  			id++;
  			if( id > ( this.slidesCount - 1 ) ) id = 0;

  			$clear(this.period);
  			this.nextSlide(id);
			this.period = this.nextSlide.periodical( this.slideTime, this );

  		}.bind( this ) );
  	}
  },

  startSliding: function()
  {
    $clear(this.period);
    this.period = this.nextSlide.periodical( this.slideTime, this );
  },

  selectSlide: function(id)
  {
    $clear(this.period);
    this.nextSlide(id);
  },

  nextSlide: function(id)
  {
    if(this.listItems[ this.currentSlide ]) {
      this.listItems[ this.currentSlide ].setStyle('z-index', 99);
      var prevSlide = this.currentSlide;
    }

    if( $chk(id) ) { this.currentSlide = id; } else { this.currentSlide++; this.currentSlide; }

    if( this.currentSlide >= this.slidesCount ) this.currentSlide = 0;

    if(this.listItems[ this.currentSlide ]) {

      if( $chk(this.myFx1) ) {
        this.myFx1.cancel();
        this.listItems.forEach( function( el, i ) { if( i.toInt() != prevSlide.toInt() ) { el.setOpacity(0); el.setStyle('z-index', 100); el.setStyle('display', 'none'); } } );
      }

      this.listItems[ this.currentSlide ].setStyle( 'display', '' );
      this.listItems[ this.currentSlide ].setStyle('z-index', 101);

      this.myFx1 = new Fx.Morph(this.listItems[ this.currentSlide ], {
          duration: 500,
          property: 'opacity'
      }).start({ 'opacity' : 1 });
    }
  }

} );

/**
 * Expand the array object with a compare function (using mootools' implement)
 */
Array.implement({
    //compare two arrays to see if they are identical
    compare : function(arr, strict) {
        strict = strict || false;
        if (this.length != arr.length)                  return false;

        for (var i = 0; i < this.length; i++) {
                if ($type(this[i]) == "array") {
                        if (!this[i].compare(arr[i]))   return false;
                }
                if (strict) {
                        if (this[i] !== arr[i])         return false;
                } else {
                        if (this[i] != arr[i])          return false;
                }
        }
        return true;
    }
});




/**
 * Javascript function that emulates php's number_format
 */
function number_format (number, decimals, dec_point, thousands_sep) {

    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}




/**
* Toggles the "add accessory to order" checkbox button on the article detail page
*
* @author Damien Overeem <damien@icit.nl>
*/
function toggleAccessoryCheckbox(labelObject, checkboxId) {

    if ( $(checkboxId) ) {

        var checkBox = $(checkboxId);

        if ( checkBox.checked == true ) {
            labelObject.className = 'orderButton orderAdded'
        } else {
            labelObject.className = 'orderButton orderAdd'
        }
    }

}

/**
 * Smart breadcrumbs
 *
 * @author Damien Overeem <dovereem@icit.nl>
 */
var smartBreadcrumbs = new Class({

    initialize: function(dropdownArray) {

        // Vars
        this.activeDropdown = false

        // Find the smartBreadcrumbs UL.
        if ( !$('smartBreadcrumbs') ) {
            alert("No UL with id 'smartBreadcrumbs' found.")
            return false
        } else {
            this.smartBreadcrumbElement = $('smartBreadcrumbs')
        }

        // Count the number of LI's in the smartbreadcrumbs UL
        var nrOfCrumbs = 0;
        $each( this.smartBreadcrumbElement.getElements("li.crumb"), function(element, index) {
            nrOfCrumbs++;
        })

        // Change the appearance of the breadcrumbs from normal breadcrumbs to "dropdowns"
        elementCounter = 0

        // Loop through all li's in the smartbreadCrumb div.
        $each( this.smartBreadcrumbElement.getElements("li.crumb"), function(element, index) {

            // Remove the delimiter divs
            $each( element.getElements("div.delimiter"), function(element, index) {
                element.style.display = "none"
            })

            // Make the breadcrumb items look like buttons
            buttonEndElement  = new Element('div')
            buttonEndElement.className = "button"

            buttonEndElement.inject(element,'bottom')

            if ( elementCounter < nrOfCrumbs-1 ) {
                buttonEndElement  = new Element('div')
                buttonEndElement.className = "buttonEnd"
            } else {
                buttonEndElement  = new Element('div', {className: 'buttonEndLast'})
                buttonEndElement.className = "buttonEndLast"
            }

            buttonEndElement.inject(element,'bottom')

            // Find the A tag in the element and replace its href by the javascript call and set mouseout
            $each( element.getElements("a"), function(element, index) {
                // Store the element label
                breadcrumbElementLabel = element.innerHTML
                element.setAttribute('href', 'javascript:void(0)' )
                element.setAttribute('onclick', 'javascript:smartBreadcrumb.showDropdown(' + elementCounter + ')')
            })

            // Create the dropdown menu
            dropdownElement = new Element('div', { id: 'dropdown'+elementCounter } )
            dropdownElement.className = "dropdown"
            dropdownElement.style.display = "none"

            dropdownUlElement = new Element('ul')
            dropdownUlElement.inject(dropdownElement)

            dropdownOptionsArray = dropdownArray[elementCounter]

            $each( dropdownOptionsArray, function(option, index) {

                dropdownOptionLabel     = option[0]
                dropdownOptionUrl       = option[1]
                dropdownOptionSelected  = option[2]

                //if ( dropdownOptionSelected ) {
                if ( dropdownOptionLabel == breadcrumbElementLabel ) {
                    optionClass = "selected"
                } else {
                    optionClass = ""
                }

                dropdownOption = new Element('li')
                dropdownOption.className = optionClass
                dropdownOption.inject(dropdownUlElement,'bottom')

                dropdownOptionAnchor = new Element('a')
                dropdownOptionAnchor.className = optionClass
                dropdownOptionAnchor.innerHTML = dropdownOptionLabel
                dropdownOptionAnchor.href      = dropdownOptionUrl
                dropdownOptionAnchor.inject(dropdownOption,'bottom')

            })

            // Insert the dropdown
            dropdownElement.inject(element,'bottom')

            // Add events to the li element
            eval('element.onclick = function () { smartBreadcrumb.showDropdown(' + elementCounter + ' ); };');
            eval('dropdownUlElement.onmouseover = function () { smartBreadcrumb.showDropdown(' + elementCounter + ' ); };');
            eval('dropdownElement.onmouseover = function () { smartBreadcrumb.showDropdown(' + elementCounter + ' ); };');

            dropdownElement.addEvent('mouseleave', function() { smartBreadcrumb.hideDropdown() } )
            dropdownUlElement.addEvent('mouseleave', function() { smartBreadcrumb.hideDropdown() } )


            this.elementCounter++;

        })

        return true

    },

    showDropdown: function(id) {

        dropdownObject = $('dropdown'+id)

        // Close the currently active dropdown if its open
        this.hideDropdown

        // Show the selected dropdown
        dropdownObject.style.display = "block"

        this.activeDropdown = dropdownObject

        return true

    },

    hideDropdown: function() {

      	// Slowdown closing of dropmenu for 1000ms
      	if ( this.activeDropdown ) {
    	   this.activeDropdown.style.display = "none";
      	}

      	return true

    }

})


/**
 * Pagination for accessories on object details
 *
 * @author Damien Overeem <damien@icit.nl>
 */
var AccessoryPagination = new Class({

    initialize: function( objectName ) {

        var tabId = 'accessoryTabContent'

        this.accessoriesPerPage = 3
        this.maxPageLinks       = 4
        this.activePageNr       = 0

        // Store the name of the initialized object for the onclick events
        this.objectName = objectName


        if ( !$('mainAccessoriesContainer') || !$(tabId)) {
            return false;
        } else {
            this.accessoryContainer = $('mainAccessoriesContainer')
            this.tabObject = $(tabId)
        }

        // Get accessory item containers
        this.accessoryItemContainers = this.accessoryContainer.getElements('div.smallArticleContainer')

        // Hide all the current accessoryItem elements
        this.accessoryItemContainers.each( function(element, index) {
                element.style.display = "none"
            }
        )

        // Store the number of available accessories
        this.nrOfAccessories = this.accessoryItemContainers.length

        // Store the number of pages based on this.accessoriesPerPage
        this.pages = ( this.nrOfAccessories / this.accessoriesPerPage )

        // We only need to build pagination if we have more then 1 page
        if ( this.pages <= 1 ) {
            this.showPage(1)
            return true
        }

        // Add the pagination header
        this.injectPaginationOptions()

        // Show the first page
        this.showPage(1)

        return true;

    },

    injectPaginationOptions: function( ) {

        // First create the header div
        var tabHeaderDiv = new Element('div', { 'class' : 'tabHeader' })

        // Create paginationOptions div and inject into headerdiv
        var paginationOptionsDiv = new Element('div', { 'class' : 'paginationOptions' }).inject(tabHeaderDiv)

        // Create totalItems span and inject into paginationOptions
        var totalItemsSpan = new Element('span', { 'class' : 'totalItems' }).inject(paginationOptionsDiv)
        totalItemsSpan.innerHTML = this.nrOfAccessories

        // Add a space
        paginationOptionsDiv.appendText(' ')

        // Create the collection name span
        var collectionNameSpan = new Element('span', { 'class' : 'collectionName' }).inject(paginationOptionsDiv, 'bottom')
        collectionNameSpan.innerHTML = 'Accessoires'


        /**
         * Previous and Next span
         */

        // Create the previousNext span
        var previousNextSpan = new Element('span', { 'class' : 'previousNext' }).inject(paginationOptionsDiv, 'bottom')

        // Add < text item
        previousNextSpan.appendText('< ')

        // Create the 'previous' anchor
        var previousAnchor = new Element('a', { 'href'  : 'javascript:void(0)' }).inject( previousNextSpan, 'bottom')
        previousAnchor.innerHTML = 'vorige'

        // Add event to the 'previous' anchor
        eval( "previousAnchor.addEvent('click', function() { " + this.objectName + ".previousPage()  } ) " )

        // Add pipeline
        previousNextSpan.appendText(' | ')

        var nextAnchor = new Element('a', { 'href'  : 'javascript:void(0)' }).inject( previousNextSpan, 'bottom')
        nextAnchor.innerHTML = 'volgende'

        // Add event to the 'next' anchor
        eval( "nextAnchor.addEvent('click', function() { " + this.objectName + ".nextPage()  } ) " )

        // Add > text item
        previousNextSpan.appendText(' >')

        /**
         * Pages
         */
        // Create the previousNext span
        var pagesSpan = new Element('span', { 'class' : 'pages' }).inject(paginationOptionsDiv, 'bottom')

        // Add page links for each page
        var page
        for ( i=0; i < this.pages; i++ ) {
            pageNumber = i+1
            page = new Element('a', {
                        'href'  : 'javascript:void(0)',
                        'id'    : 'paginationPage_' + pageNumber
                   }).inject( pagesSpan, 'bottom')


            page.className = 'pageNumber'

            page.innerHTML = pageNumber
            eval( "page.addEvent('click', function() { " + this.objectName + ".showPage(" + pageNumber + ")  } ) " )
        }

        // Add the ... span (more) (only when needed)
        if ( this.pages > this.maxPageLinks ) {
            var moreSpan = new Element('span', { 'class' : 'more' }).inject(pagesSpan, 'bottom')
            moreSpan.innerHTML = '...'
        }

        // Inject the tabHeaderDiv as first item into this.tabObject
        tabHeaderDiv.inject( this.tabObject, 'top' )

    },

    showPage: function(pageNumber) {

        if ( pageNumber != this.activePageNr ) {

            // Make the activePageNr pageNumber anchor inactive
            if ( $('paginationPage_' + this.activePageNr) )
                $('paginationPage_' + this.activePageNr).className = 'pageNumber'

            // Set the class for the pageNumber anchor
            if ( $('paginationPage_' + pageNumber) )
                $('paginationPage_' + pageNumber).className = 'pageNumber activePage'


            // Hide all the current accessoryItem elements
            this.accessoryItemContainers.each( function(element, index) {
                    element.style.display = "none"
                }
            )

            /**
             * Determine which items to show based on the pageNumber
             */
            if ( pageNumber == 1 ) {
                var firstItem = 1
            } else {
                var firstItem = ( pageNumber * this.accessoriesPerPage ) - this.accessoriesPerPage  + 1
            }

            var lastItem = ( firstItem + this.accessoriesPerPage ) - 1


            // Show the accessories
            for ( var i = firstItem; i <= lastItem; i++ ) {

                if (  $('accessoiresContainer_' + i) ) {
                    accessoryContainerDiv = $('accessoiresContainer_' + i)
                    accessoryContainerDiv.style.display = "block"
                }

            }

            this.activePageNr = pageNumber

        }

        return true

    },

    previousPage: function() {

        if ( this.activePageNr > 1 ) {
            this.showPage(this.activePageNr-1)
        }
        return true

    },

    nextPage: function() {

        if ( this.activePageNr < this.pages ) {
            this.showPage(this.activePageNr+1)
        }
        return true
    }

})

/**
 * Show shopping cart animation
 *
 * @author Damien Overeem <damien@icit.nl>
 *
 */
function showShoppingCartAnimation( state ) {

    if ( shoppingBasket) {
        if ( state == 1 ) {
            shoppingBasket.GotoFrame(1)
        } else if ( state == 2 ) {
            shoppingBasket.GotoFrame(1)
            shoppingBasket.Play()
        } else if ( state == 3 ) {
            shoppingBasket.GotoFrame(20)
        }
    }

}

/**
 * This function is called by the chat flash element to display a popup with the chat system
 */
function openChatWindow () {

    tmp = window.open ( '/chat/', 'chatWindow', 'resize=no, status=no, width=660, height=600' );
    tmp.moveTo ( ( screen.width / 2 ) - 330, ( screen.height / 2 ) - 300  );

    return true;
}

/**
 * This function catches the post of the "add to mailinglist" form (rightside menu block) and handles
 * the form through javascript
 *
 * @autor Damien Overeem <damien@icit.nl>
 *
 */
function submitToMailingList( formObject, name, email, emailField ) {

    ajaxUrl = "/index.php?a=6&action=addToMailingList&ajax=true"

    emailField = emailField || ''

    if ( email == '' ) {
        email = $(emailField).value;
    }

    if ( !emailField ) {
        emailField = mailingListEmail
    }

    postData = eval("new Object({'mailingListName':name, '" + emailField  + "':   email})");

    var ajaxRequest = new Request({ url:            ajaxUrl,
                                    method:         'post',
                                    evalScripts:    true,
                                    data:           postData
                                 });
    ajaxRequest.send();

}


/**
 * Fetches order details and displays them in a div (My account-> Tab: My account)
 *
 * @autor Damien Overeem <damien@icit.nl>
 *
 */
function fetchOrderDetails(URL) {

      var orderDetailRequest = new Request({
                                                url: URL+'&ajax=true',
                                                method: 'post',
                                                evalScripts: true,
                                                onComplete: function( res ) {
                                                    $( 'orderDetailsContainer' ).innerHTML = res;
                                                    $( 'orderDetailsContainer' ).style.display = "block";
                                                }.bind( this )
                                           });

      orderDetailRequest.send();

}


/**
 * Generates rotating banners from UL lists (right-side vertical bar)
 *
 * @author Damien Overeem <damien@icit.nl>
 *
 */
var ImageSlides = new Class({

  initialize: function( ul, slideTime ) {

    this.myFX         = $H();

    this.slideTime    = slideTime

    this.mainUl       = $( ul );
    this.listItems    = this.mainUl.getElements( 'li.item' );

    this.slidesCount  = this.listItems.length;
    this.currentSlide = 0;

    this.listItems.forEach( function( el, i ){
      if( i > 0 )
        el.setStyle( 'opacity', '0' );

        el.setStyle( 'position', 'absolute')
        el.setStyle( 'top', '0')
        el.setStyle( 'left', '0')
    });

    this.nextSlide.delay( this.slideTime, this );
  },

  nextSlide: function( ) {

      // Stop the slider if we are slidign the headerAmination and Site.stopHeaderAnimation is true.
      if ( this.mainUl.id == 'headerAnimation' && Site.stopHeaderAnimation ) return false;

      if( this.myFX.get( this.listItems[ this.currentSlide ].id ) ) // prevent double animations on 1 element
            this.myFX.get( this.listItems[ this.currentSlide ].id ).stop();

      if(this.listItems[ this.currentSlide ]) {
          this.listItems[ this.currentSlide ].fade(0)
      }
      this.currentSlide++

      if( this.currentSlide >= this.slidesCount )
          this.currentSlide = 0;

      this.listItems[ this.currentSlide ].fade(1)
      this.nextSlide.delay( this.slideTime, this );

  }

} );


/**
 * Toggles the state of the compare article checkbox (category overview)
 *
 * @author Damien Overeem <damien@icit.nl>
 */
function toggleArticleCompareButtonState(hrefObject, checked) {

    var twoRequiredText = "U dient minimaal 2 artikelen te selecteren om te vergelijken."

    if ( checked ) {
        // We need to display the checkbox/image as checked
        hrefObject.className = "actionCompare actionCompareActive"

        // Replace articleCompareDelete with articleCompareAdd in the href
        newHref = hrefObject.href
        newHref = newHref.replace('articleCompareAdd', 'articleCompareDelete')

        // Disable the href
        hrefObject.setAttribute('href', newHref)

        // Clear old events and set onclickt (ajax call)
        hrefObject.setAttribute('onclick', "Site.removeArticleCompare('" + newHref + "'); toggleArticleCompareButtonState(this, false); return false;")

        comparableArticlesCount++;

    } else {
        // We need to display the checkbox/image as unchecked
        hrefObject.className = "actionCompare"

        // Replace articleCompareDelete with articleCompareAdd in the href
        newHref = hrefObject.href
        newHref = newHref.replace('articleCompareDelete', 'articleCompareAdd')

        // Disable the href
        hrefObject.setAttribute('href', newHref)

        // Clear old events and set onclickt (ajax call)
        hrefObject.setAttribute('onclick', "Site.addArticleCompare('" + newHref + "'); toggleArticleCompareButtonState(this, true); return false;")

        comparableArticlesCount--;

    }

    // Enable or disable startcompare, based on the amount of comparableArticlesCount
    if ( $('startCompare') ) {

        if ( comparableArticlesCount >= 2 ) {

            $('startCompare').href = showComparableArticlesHref;
            $('startCompare').setAttribute('onClick', '');

        } else {

            $('startCompare').href = 'javascript:void(0)';
            $('startCompare').setAttribute('onClick', "Site.showMessage('Artikel vergelijken', '" + twoRequiredText + "');");
        }
    }

}

/**
 * If a priceSlider is availailable on the page, this function will set its max value (or initialize it)
 *
 * @author Damien Overeem <damien@icit.nl>
 */
var priceSlider

function setPriceSlider(minAmount, maxAmount, selectedMin, selectedMax, doAjaxSearch) {

    doAjaxSearch = doAjaxSearch || false;

    minAmount = Math.floor(parseInt(minAmount))
    maxAmount = Math.ceil(parseInt(maxAmount))

    if ( !selectedMin )
        var selectedMin = minAmount
    else
        var selectedMin = Math.floor(parseInt(selectedMin))


    if ( !selectedMax )
        var selectedMax = maxAmount
    else
        var selectedMax = Math.ceil(parseInt(selectedMax))


    // Hide the manual filter fields
    if ( $('priceFilterTable') ) { $('priceFilterTable').setStyle('display', 'none') }

    $('priceSlider').setStyle('display','block')

    if ( $('priceSliderBar') && $('priceSliderButtonLeft') && $('priceSliderBackgroundImage') && $('priceSliderButtonRight') ) {


    	priceSlider = new Slider( $('priceSliderBar'), $('priceSliderButtonLeft'),$('priceSliderBackgroundImage'), {
                        		start:    minAmount,
                        		end:      maxAmount,
                        		offset:   9,
                        		snap:     false,
                        		step:     1,
                        		onChange: function(pos){

                                		      $('priceSliderPriceTagLow').set('html', number_format(pos.minpos) )
                                		      $('priceSliderPriceTagHigh').set('html', number_format(pos.maxpos) )

                                		      // If we have an ajaxSearch object, we need to call the setMinPrice and setMaxPrice methods when neccesary
                                		      if ( window.ajaxSearch !== undefined) {
                                		          ajaxSearch.setMinPrice(pos.minpos, doAjaxSearch)
                                		          ajaxSearch.setMaxPrice(pos.maxpos, doAjaxSearch)
                                		      } else {
                                		          // update the (now hidden) value fields
                                                  $('filterMinPrice').set('value', pos.minpos)
                                                  $('filterMaxPrice').set('value', pos.maxpos)
                                		      }
    		                    }
    	                 }, $('priceSliderButtonRight')).setMin(selectedMin).setMax(selectedMax)

    }

}


/**
 * Break out of a frame if we are in one..
 */

function breakFromFrame() {
  if (top.location != location) {
    top.location.href = document.location.href;
  }
}
