
var tabController = new Class({

    initialize: function(tabBlockID, activeTab) {

        // Get the tabBlock element
        if ( !$(tabBlockID) ) {
            //alert('There is no tabBlock div with ID ' + tabBlockID)
        } else {
            this.tabBlockElement = $(tabBlockID)
        }

        // activeTab will be the only one visible
        this.activeTab = activeTab

        // set the class of the tab to tabActive
        $(activeTab).className = 'tabActive'

        // Find all the tabContent blocks within the "block"
        $each( this.tabBlockElement.getElements("div.tabContent"), function(element, index) {

      if ( element.id != activeTab+"Content" ) {
        if ( element.parentNode.id == tabBlockID ) {
          element.setStyle("display", "none")
        }
      }

        })

    },

    toggleTab: function(tab) {

        if ( !$(tab) ) {
            //alert('There is no tab div with ID ' + tabBlockID)
        } else {

            // Hide current content
            $(this.activeTab + "Content").setStyle("display", "none")
            $(this.activeTab).className = 'tab'

            // Show the new content
            $(tab + "Content").setStyle("display", "block")
            $(tab).className = 'tabActive'

            // Register the new active tab
            this.activeTab = tab

        }

    }

})


// Used for the delivery options on the article detail pages
var DeliveryOptions= new Class({

    initialize: function(type, deliveryOptionsArray) {
        this.type               = type;

        this.deliveryOptions    = new Array();
        this.deliveryOptions    = deliveryOptionsArray;
    },

    toggleSubOptions: function(selectObject) {

        // Get the deliverID from the selectedObject parameter
        deliverIDString = selectObject.value.split("_")
        deliverID = deliverIDString[1]

        // First we check if we have a value or not.
        if ( selectObject.value  ) {

            this.toggleCheckbox(selectObject.id + 'Checkbox', true)

            // Only one of the types 'pickup' or 'delivery' dropdowns can have a value
            if ( this.type == 'pickup') {
                if ( $('deliverySelect').selectedIndex > 0 ) {

                    // There was something selected. Set selected option index to 0 to clear the selection
                    $('deliverySelect').options [0].selected = true;

                    // Disable the checkbox
                    this.toggleCheckbox($('deliverySelect').id + 'Checkbox', false)

                    // Destroy the selectTypeDiv if it exists
                    if ( $('deliveryTypeSelectDiv') ) {
                        var deliveryTypeSelectDiv = $('deliveryTypeSelectDiv')
                        deliveryTypeSelectDiv.parentNode.removeChild(deliveryTypeSelectDiv)
                    }

                }

                if ( $('deliveryPrice') ) {
                    $('deliveryPrice').innerHTML = '0,00'
                }

            } else if ( this.type == 'delivery' ) {
                if ( $('pickupSelect').selectedIndex > 0 ) {

                    // There was something selected. Set selected option index to 0 to clear the selection
                    $('pickupSelect').options [0].selected = true;

                    // Disable the checkbox
                    this.toggleCheckbox($('pickupSelect').id + 'Checkbox', false)

                    // Destroy the selectTypeDiv if it exists
                    if ( $('pickupTypeSelectDiv') ) {
                        var pickupTypeSelectDiv = $('pickupTypeSelectDiv')
                        pickupTypeSelectDiv.parentNode.removeChild(pickupTypeSelectDiv)
                    }

                }

                if ( $('pickupPrice') ) {
                    $('pickupPrice').innerHTML = '0,00'
                }
            }

        } else {
            // No value. Clear the checkbox and remove the deliveryTypeSelect Div
            this.toggleCheckbox(selectObject.id + 'Checkbox', false)
            if ( $( this.type + 'TypeSelectDiv') ) {
                deliveryTypeSelectDiv = $(this.type + 'TypeSelectDiv')
                deliveryTypeSelectDiv.parentNode.removeChild(deliveryTypeSelectDiv)
            }
            if ( $(this.type + 'Price') ) {
                $(this.type + 'Price').innerHTML = '0,00'
            }
            return
        }




        if ( !this.deliveryOptions[deliverID]) {
            return false
        }

        deliveryTypeData = this.deliveryOptions[deliverID];

        //Build deliveryTypeSelectDiv if it doesnt exist
        if ( $(this.type + 'TypeSelectDiv') ) {
            deliveryTypeSelectDivElement = $(this.type + 'TypeSelectDiv')
        } else {
            deliveryTypeSelectDivElement = new Element('div', {
                'class': 'deliveryTypeSelectDiv',
                'id': this.type + 'TypeSelectDiv'
            })
        }

        // Check if allready have a select element for deliveryType. If so, remove it.
        if ( $(this.type + 'TypeSelect') )
            $(this.type + 'TypeSelect').parentNode.removeChild($(this.type + 'TypeSelect'))

        // Remove the description icon aswell
        if ( $(this.type + 'TypeDescriptionIcon') )
            $(this.type + 'TypeDescriptionIcon').parentNode.removeChild($(this.type + 'TypeDescriptionIcon'))



        //Build deliveryTypeSelect and inject into deliveryTypeSelectDivElement
        deliveryTypeSelectElement = new Element('select', {
            'id'    : this.type + 'TypeSelect',
            'name'  : 'delivMethod'
        }).inject(deliveryTypeSelectDivElement, 'bottom')


        var firstOption = true;
        var firstDeliveryTypeId

        // Add options to the select element
        for ( var i in deliveryTypeData ) {

            if ( !isNaN(parseInt(i)) ) {
                index = i
                deliveryType = deliveryTypeData[index]

                // We remember the first deliveryType, so we can set the first description on the description icon
                if ( firstOption == true ) {
                    firstDeliveryTypeId = index
                    firstOption = false
                }

                if ( $type(deliveryType) == 'array'  ) {

                    deliveryTypeSelectOptionElement = new Element('option', {
                        'value'    : index
                    })

                    deliveryTypeSelectOptionElement.innerHTML = deliveryType[0]
                    deliveryTypeSelectOptionElement.inject(deliveryTypeSelectElement,'bottom')
                }
            }
        }

        // Inject the deliveryTypeSelect div element after the deliveryOptions select element
        deliveryTypeSelectDivElement.inject(selectObject, 'after')

        // Add an image with the description of the selected item
        deliveryTypeDescriptionImage = new Element('img', {
            'id'    : this.type + 'TypeDescriptionIcon',
            'class' : 'specsInfo',
            'src'   : '/layout/default/gfx/icon_info.png'
        }).inject(deliveryTypeSelectDivElement, 'bottom')

        // Add an event to the deliveryTypeSelectElement that will set the title on the discription image icon when changed.
        eval("deliveryTypeSelectElement.addEvent('change', function() { " + this.type + "OptionsObject.setDescriptionAndPrice(" + deliverID + ", this.value); }) ")

        // Set the description and price to the first selected item.
        this.setDescriptionAndPrice(deliverID, firstDeliveryTypeId)

        return true

    },

    toggleCheckbox: function(checkboxID, checked) {

        $(checkboxID).disabled = false;
        $(checkboxID).checked = checked;
        $(checkboxID).disabled = true;
    },

    setDescriptionAndPrice: function(deliveryId,deliveryTypeId) {

        var label       = this.deliveryOptions[deliveryId][deliveryTypeId][0]
        var price       = this.deliveryOptions[deliveryId][deliveryTypeId][1]
        var description = this.deliveryOptions[deliveryId][deliveryTypeId][2]

        $(this.type + 'TypeDescriptionIcon').alt    = '';
        $(this.type + 'TypeDescriptionIcon').title  = '';

        if ( $(this.type + 'TypeDescriptionIcon') ) {

        	$(this.type + 'TypeDescriptionIcon').alt    = label
            $(this.type + 'TypeDescriptionIcon').title  = description

            //Clone the old tip and make a new one
            var oldIcon = $(this.type + 'TypeDescriptionIcon');
            var newIcon = new Element('img', {'src': $(this.type + 'TypeDescriptionIcon').src, 'class': $(this.type + 'TypeDescriptionIcon').className, 'id':  $(this.type + 'TypeDescriptionIcon').id }).inject($(this.type + 'TypeDescriptionIcon'), 'before');
        	newIcon.alt    = label
        	newIcon.title  = description

        	oldIcon.dispose();
            // Set a tip on the tip image
            var specsInfo = new Tips($(this.type + 'TypeDescriptionIcon'), {
						                className: 'specsInfo',
						                onShow: function(toolTip) {
						                  new Fx.Tween(toolTip, { property: 'opacity', duration: 500, wait: false}).start(0, 1);
						                },
						                onHide: function(toolTip) {
						                  new Fx.Tween(toolTip, { property: 'opacity', duration: 500, wait: false}).start(1, 0);
						                }
              				 });

        }

        if ( price ) {
            if ( $(this.type + 'Price') ) {
                $(this.type + 'Price').set('html', price)
                // Use the old function to update the total price in the summary
                addSendPrice(deliveryTypeId, price.replace(',','.'))
            }
        }

    }

})

function number_format ( price, i, sep, thousand )
{
  if ( isNaN ( price ) || price < 0 )
    price = 0;

  if ( parseInt ( price ) != price )
  {
    eur = parseInt ( price );
    cent = Math.round ( ( price - eur ) * 100 );

    if ( cent < 10 )
      cent = '0' + cent;

  }
  else
  {
    eur = price;
    cent = '00';
  }

  if ( eur > 0 )
  {
    t = eur + '';

    eur = '';
    while ( t.length > 3 )
    {
      eur = thousand + t.substring ( t.length - 3, t.length ) + eur;
      t = t.substring ( 0, t.length - 3 );
    }
    if ( t > 0 )
      eur = t + eur;
  }
  else
    eur = '0';

  return eur + sep + cent;
}

var deliverPrice = 0.00;
var accesoires = new Hash();
var selectedDeliverID = 0;

function addSendPrice( deliverID, price )
{
  deliverPrice = parseFloat(price);

  selectedDeliverID = deliverID;

  reCalculatePrice();
}

function addAccPrice(srcObj) {

  if(srcObj.checked) {
    accesoires.set(srcObj.value, $(srcObj.id + '_price').value);
  } else {
    accesoires.remove(srcObj.value);
  }

  reCalculatePrice();
}

function reCalculatePrice() {

  var artTotalPrice = parseFloat(deliverPrice) + parseFloat($('totalPrice').value);

  var accesoiresPrice = 0.00;

  accesoires.each(function( el ) {
    accesoiresPrice += parseFloat(el);
  }, this );

  artTotalPrice += accesoiresPrice;

  $('deliverPrice').innerHTML = number_format(deliverPrice, 2, ',', '');
  $('accesoiresPrice').innerHTML = number_format(accesoiresPrice, 2, ',', '');

  $('artTotalPrice').innerHTML = number_format(artTotalPrice, 2, ',', '');
}

function showArrow(obj, content) {


  // remove all arrows
  $$('table#deliverTable td').setStyle('background-color', '');
  $$('table#deliverTable td').setStyle('background-image', '');

  // set arrows at selected row
  $(obj).getElements('td.radio').setStyle('background-color', '#f5f5f5');
  $(obj).getElements('td.label').setStyle('background-color', '#f5f5f5');
  $(obj).getElements('td.price').setStyle('background-image', 'url(modules/webshop/gfx/delivery_bg_arrow.gif)');

  // add mouseout event
  $(obj).addEvent('mouseout', function (el) {

    $(obj).getElements('td').setStyle('background-color', '');
    $(obj).getElements('td').setStyle('background-image', '');

    // set selected arrow
    if($('delivery_'+selectedDeliverID)) {

      $('delivery_'+selectedDeliverID).getElements('td.radio').setStyle('background-color', '#f5f5f5');
      $('delivery_'+selectedDeliverID).getElements('td.label').setStyle('background-color', '#f5f5f5');
      $('delivery_'+selectedDeliverID).getElements('td.price').setStyle('background-image', 'url(modules/webshop/gfx/delivery_bg_arrow.gif)');

    }

  });


}


function showStockExplain(obj) {


  $('stockExplain').setStyle('left', $(obj).getLeft() + 1);
  $('stockExplain').setStyle('top', $(obj).getTop() + 20);
  $('stockExplain').setStyle('display', 'block');

}
function hideStockExplain() {
  $('stockExplain').setStyle('display', 'none');
}

function switchArticleImage( num , detailImage ){
    $( 'imageContainer' ).setStyle('background-image', 'url("'+detailImage+'")');
}

function acticleFilesHover( num ) {
    $('summaryTabContent').getElements('.thumbnail').removeClass('active');
    $('thumbnail'+num).addClass('active');
}

function viewArticleImage(imageUrl) {
    if(!$chk(imageUrl)) {
        imageUrl = $('imageContainer').getStyle('background-image');
    }
    imageUrl = imageUrl.replace('"', '');
    imageUrl = imageUrl.replace('url(', '');
    imageUrl = imageUrl.replace('"', '');
    imageUrl = imageUrl.replace(')', '');
    imageUrl = imageUrl.replace(/([A-z0-9]+)\.jpg$/, 'detail\.jpg');
    Site.viewImage( imageUrl );
}

var mediaplayer = null;
function viewArticleMedia(mediaID, mediaFileUrl) {
    w = 400;
    h = 300;
    l = ( ( window.getWidth() - w ) / 2 ).toInt();
    t = ( ( window.getHeight() - h ) / 2 ).toInt();

    sTop = 0;
    if ( window.pageYOffset )
      sTop = window.pageYOffset;
    else if ( document.documentElement.scrollTop )
      sTop = document.documentElement.scrollTop;
    else if ( document.body.scrollTop )
      sTop = document.body.scrollTop;

    if( t <= 0 )
      t = 20;
    else if( t >= 150 )
      t = 150;

    t += sTop;

    var media = new Element('div', {
    id: 'mediaFilePlayer-'+mediaID,
    styles:{
        position: 'absolute',
        'z-index': 99999,
        width: w,
        height: h,
        left:l,
        top:t
    }
    });
    media.inject( document.body );

    var so = new SWFObject ( 'modules/webshop/flowplayer-3.2.5.swf', 'mediaFilePlayer', '400', '300', 8 );
    so.addParam ( 'flashvars', "config={'clip':'/" + mediaFileUrl + "'}" );
    so.addParam ( 'allowfullscreen', 'true' );
    so.write ( 'mediaFilePlayer-'+mediaID );
    //mediaplayer = $f('mediaFilePlayer-'+mediaID, 'modules/webshop/flowplayer-3.2.5.swf', '/' + mediaFileUrl);

    new Element('div', {
        html : 'sluiten',
        id: 'mediaPlayerClose',
        events: {
            'click': function() {
                mediaplayerClose('mediaFilePlayer-'+mediaID);
            }
        }
    }).inject('mediaFilePlayer-'+mediaID, 'top');

    if ( !$('tintScreenMedia') ) {
      var tint = new Element('div', {id: 'tintScreenMedia'});
      tint.addEvent('click', function() {
        this.mediaplayerClose('mediaFilePlayer-'+mediaID);
      }.bind(this));
      tint.setStyle('opacity', 0);
      tint.inject(document.body);
    } else {
      var tint = $('tintScreenMedia')
    }
    tint.fade(0.8);

}

function mediaplayerClose(elId) {
    if(navigator.userAgent.toLowerCase().indexOf('msie ') != -1) {
        window.location = window.location;
        return;
    }
    //mediaplayer.stop();
    //mediaplayer.close();
    //mediaplayer.unload();
    //$f()._api().fp_close();
    //$f().unload();
    $(elId).dispose(); // hier gaat ie stoek in IE...
    if ($('tintScreenMedia')) {
      $('tintScreenMedia').fade('out');
    }
}
