/*
* Cache van javascripts.script.js
* Created: 2010-02-24 13:58:07
*/

/*
$Author: sjors $
$LastChangedDate: 2006-10-19 14:05:31 +0200 (do, 19 okt 2006) $
$Id: javascripts.js 28 2006-10-19 12:05:31Z sjors $
$Rev: 28 $
*/

var google = 'UA-4093536-1';
if (google) {
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
}

var pngfix;
var sliders = [];
window.addEvent('load', function() {
	sliders.each(function(slide) {slide.start();});
	window.fireEvent('resize');

	if (google && _gat) {
		var pageTracker = _gat._getTracker(google);
		pageTracker._initData();
		pageTracker._trackPageview();
	}

	document.addEvent('click', function(e) {
  	var e = new Event(e);
  	var el = $(e.target)
  	if (el.tagName.toLowerCase() != 'a') {
  		el = el.getParent('a');
  	}
  	var newwin = false;

		if (el && el.get('href')) {
			newwin = newwin || el.hasClass('newwindow');
			newwin = newwin || el.hasClass('externlink');

			/*if (el.get('href').substring(0, 7) == 'http://' || el.get('href').substring(0, 8) == 'https://') {
				newwin = newwin || el.get('href').indexOf('http://www.axon.tv');
			}*/

			var downloadsurl = '/downloads/';
			newwin = newwin || el.get('href').substring(0, downloadsurl.length) == downloadsurl;
		}
		if (newwin) {
			e.stop();
			window.open(el.href, '_blank');
		}
	});

	if ($('searchfield')) {
		var searchform = $('searchfield').getParent('form');
		searchform.addEvent('submit', function(e) {
			new Event(e).stop();
			var url = searchform.get('action') + '/';
			var subject = 'product';
			searchform.getElements('input[type=radio]').each(function(inpradio) {
				if (inpradio.get('checked')) {
					subject = inpradio.get('value');
				}
			});
			url += subject + '/' + encodeURIComponent($('searchfield').get('value'));
			window.location.href = url;
		});
		$('searchfield').addEvent('keyup', function(e) {
			var subject = 'product';
			searchform.getElements('input[type=radio]').each(function(inpradio) {
				if (inpradio.get('checked')) {
					subject = inpradio.get('value');
				}
			});
			if (subject == 'product') {
				if ($('searchfield').get('value').length > 0) {
					$('searchfield').addClass('loading');
					new Request.HTML({
						'update': $('producthint'),
						'autoCancel': true,
						'onComplete': function() {
							$('searchfield').removeClass('loading');
							$('producthint').setStyle('display', 'block');
						}
					}).post('/products/?name='+encodeURIComponent($('searchfield').get('value')));
					flashview('hidden');
				}
			}
		});
		$('searchfield').addEvent('blur', function(e) {
			$('producthint').setStyle.delay(500, $('producthint'), ['display', 'none']);
			flashview.delay(500, null, 'visible');
		});
		$('searchfield').addEvent('focus', function(e) {
			var subject = 'product';
			searchform.getElements('input[type=radio]').each(function(inpradio) {
				if (inpradio.get('checked')) {
					subject = inpradio.get('value');
				}
			});
			if (subject == 'product') {
				if ($('searchfield').get('value').length > 0) {
					$('producthint').setStyle('display', 'block');
					flashview('hidden');
				}
			}
		});
	}

	$$('.productshortlist a').addEvent('click', function(e) {
		e.stop();
		var target = $(e.target);
		$('productshortlist-results').addClass('loading');
		$('productshortlist-results').setStyle('height', 100);
		$('productshortlist-results').set('html', '');
		new Request.HTML({
			'update': $('productshortlist-results'),
			'autoCancel': true,
			'onComplete': function() {
				$('productshortlist-results').removeClass('loading');
				$('productshortlist-results').setStyle('height', 'auto');
			}
		}).post('/products/?name='+encodeURIComponent(target.get('href').substr(target.get('href').lastIndexOf('/')+1)));
	});

	$$('a.full').each(function(el) {
		var parent = el.getParent('li');
		parent.addEvent('mouseenter', function(e) {
			parent.addClass('hover');
		});
		parent.addEvent('mouseleave', function(e) {
			parent.removeClass('hover');
		});
		parent.addEvent('click', function(e) {
			document.location.href = el.get('href');
		});
	});
});

window.addEvent('resize', function() {
	$('sidebar_right').setStyle('minHeight', Math.max(window.getSize().y - 258 - 70, 356));
});

window.addEvent('domready', function() {

	$$('body').addClass('js');

	if ($('showproductselector')) {
		var psurl = $('showproductselector').get('href');
		new Element('input', {
			'type': 'button',
			'class': 'button button_big',
			'value': $('showproductselector').get('text'),
			'id': 'showproductselector'
		}).replaces($('showproductselector'));
		$('showproductselector').addEvent('click', function(e) {
			e.stop();
			new productselector(psurl);
		});
	}

	$$('.slider').each(function(sliderdiv) {
		var slide = new slider(sliderdiv, sliderdiv.getElements('.slidertab'), sliderdiv.getElements('.element'));
		slide.start.delay(3000, slide);
		sliders.push(slide);
		
		if (sliderdiv.get('id') == 'homeslider') {
			$$('div#homeslider img.map').each(function(img, i) {
				img.setProperties({
					'ismap': 'ismap', 
					'usemap': '#map'+i
				});
				new Element('map', {
					'id': 'map'+i,
					'name': 'map'+i
				}).injectAfter(img);
			});
			$$('div#homeslider img.map').each(function(img, j) {
				$$('div#homeslider img.map').each(function(img2, i) {
					new Element('area', {
						'shape': 'rect',
						'coords': '11,'+(17+i*27)+',305,'+(35+i*27),
						'events': {
							'mouseenter': function(e) {
								slide.slide(e, i);
							},
							'click': function(e) {
								new Event(e).stop();
								document.location.href = img.getParent('a').get('href');
							}
						}
					}).inject('map'+j);
				});
			});
		}
	});

	if ($('headerflash') && !Browser.Engine.trident && !Browser.Platform.linux) {
		new Swiff($('headerflash_loc').get('value'), {
			'width': $('headerflash_alt').get('width'),
			'height': $('headerflash_alt').get('height'),
			'container': $('headerflash').set('html', ''),
			'params': {
				'quality': 'high',
				'wMode': 'opaque'
			}
		});
	}

	$$('div.flashplay a').each(function(button) {
		// Replace image with flash
		button.addEvent('click', function(e) {
			new Event(e).stop();
			var img = this.getElement('img');
			new Swiff(this.get('href'), {
				'width': img.get('width'),
				'height': img.get('height'),
				'container': this.getParent('div').set('html', ''),
				'params': {
					'quality': 'high',
					'wMode': 'opaque'
				}
			});
		});
	});

	var heightValue = Browser.Engine.trident4?'100%':'';
	$$('.catshortlist li ul').each(function(ul) {
		ul.getParent('li').addClass('hassubcats');
		var a = ul.getParent('li').getElement('a');
		a.set('html', '<span>'+a.get('html')+'</span>');
	});
	var deflist1 = -1;
	var deflist2 = -1;
	$$('.catshortlist .current').each(function(el) {
		if (el.getParent('li')) {
			el = el.getParent('li').getElement('a');
			$$('.catshortlist > li > ul > li.hassubcats > a').each(function (el2, i) {
				if (el.get('href') == el2.get('href')) {
					deflist2 = i;
					el.getParent('li').addClass('open');
					el = el2.getParent('li').getParent('li').getElement('a');
				}
			});
			$$('.catshortlist > li.hassubcats > a').each(function (el2, i) {
				if (el.get('href') == el2.get('href')) {
					deflist1 = i;
					el.getParent('li').addClass('open');
				}
			});
		}
	});
	var ac2 = new Accordion($$('.catshortlist > li.hassubcats > a'), $$('.catshortlist > li > ul'), {
		'display': -1,
		'show': deflist1,
		'alwaysHide': true,
		'onActive': function(el) {
			if (deflist1 == -1) {
				$$('.catshortlist li').removeClass('open');
				el.getParent('li').addClass('open');
			}
		}
	});
	deflist1 = -1;
	new Accordion($$('.catshortlist > li > ul > li.hassubcats > a'), $$('.catshortlist > li > ul > li > ul'), {
		'display': -1,
		'show': deflist2,
		'alwaysHide': true,
		'onActive': function(el) {
			$$('.catshortlist li').removeClass('open');
			var element = $(ac2.elements[ac2.previous]);
			el.getParent('li').addClass('open');
			if (el.getParent('li').getParent('li')) {
				el.getParent('li').getParent('li').addClass('open');
			}
			if (element) {
				if (element.getParent('li')) {
					element.getParent('li').addClass('open');
				}				
				if (element.offsetHeight>0) {
					element.setStyle('height', heightValue);
				}
			}
		}
	});
	if ($$('h2.productcatsub')) {
		ac2 = new Accordion($$('h2.productcat'), $$('div.productcatsub'), {
			'show': -1,
			'alwaysHide': true
		});
	}
	
	$$('.catshortlist a').addEvent('click', function(e) {
		if ($(e.target).getParent('li').hasClass('hassubcats')) {
			e.preventDefault();
		}
	});

	if (Browser.Engine.trident) {
		$$('hr').each(function(hr) {
			new Element('div')
				.setStyles(hr.getStyles('background-image', 'background-repeat', 'height', 'margin', 'clear'))
				.replaces(hr);
		});
	}

	var preload = [];
	$$('img.preload').each(function(img) {
		preload.push(img.get('src'));
	});
	new Asset.images(preload);

	// Put label in value
	$$('input.labelinside').each(function(inp) {
		var labelvalue = inp.getPrevious('label').setStyle('display', 'none').get('text');
		inp.addEvent('focus', function(e) {
			if (inp.get('value') == labelvalue) {
				inp.set('value', '');
				inp.removeClass('defaultvalue');
			}
		});
		inp.addEvent('blur', function(e) {
			if (inp.get('value') == '' || inp.get('value') == labelvalue) {
				inp.set('value', labelvalue);
				inp.addClass('defaultvalue');
			}
		});
		inp.fireEvent('blur');
	});

	$$('ul#menu li, .tab').each(function(tab) {
		if (tab.get('html')) {
			var tabright = new Element('div', {
				'class': 'tabright',
				'html': tab.get('html')
			});

			tab.empty();
			var tableft = new Element('div', {
				'class': 'tableft'
			});
			tabright.inject(tableft);
			tableft.inject(tab);
		}
	});

	$$('ul#menu li').addEvent('mouseenter', function() {
		this.addClass('hover');
	});
	$$('ul#menu li').addEvent('mouseleave', function() {
		this.removeClass('hover');
	});
	$$('ul#menu li').addEvent('click', function() {
		//this.addClass('current');
	});

	$$('ul#footermenu li').each(function(li, i) {
		if (i != 0) {
			new Element('li', {
				'html': '|',
				'class': 'separator'
			}).injectBefore(li);
		}
	});
	$$('ul.productshortlist li').each(function(li, i) {
		if (i != 0) {
			new Element('li', {
				'html': '|',
				'class': 'separator'
			}).injectBefore(li);
		}
	});
	$$('.continents li').each(function(li, i) {
		if (i != 0) {
			new Element('li', {
				'html': '|',
				'class': 'separator'
			}).injectBefore(li);
		}
	});
	$$('ul#breadcrumb li').each(function(li, i) {
		if (i != 0) {
			new Element('li', {
				'html': '&rsaquo;',
				'class': 'separator'
			}).injectBefore(li);
		}
	});

	$$('td.notice').each(function(el) {

		var downloadlink = el.getParent('tr').getNext().getElement('a');
		downloadlink.addEvent('click', function(e) {
			new Event(e).stop();
			
			var overlay = createOverlay();
			var windowsize = window.getSize();
			var windowscroll = window.getScroll();

			var messagesize = {x: 300, y: 200};
			var topoffset = 50;

			var noticediv = new Element('div', {
				'styles': {
					'width': messagesize.x,
					'padding': '10px'
				}
			})
				.set('html', el.get('text'))
				.inject(overlay);

			downloadlink.clone()
				.setStyles({
					'display': 'block',
					'margin-top': '10px'
				})
				.inject(noticediv);

			messagesize.y = noticediv.getSize().y;

			overlay.retrieve('fx').start({
				'left': [overlay.getLeft(), windowscroll.x + (windowsize.x - messagesize.x) / 2],
				'width': ['0px', messagesize.x+'px'],
				'padding': [overlay.getStyle('padding').toInt(), 20]
			});
			overlay.retrieve('fx').start.delay(1200, overlay.retrieve('fx'), {
				'top': [overlay.getTop()-topoffset, (windowscroll.y + (windowsize.y - messagesize.y) / 2) - topoffset],
				'height': ['0px', messagesize.y+'px']
			});
		});
		
		el.getParent('tr').dispose();
	});

	if ($('productdiagram')) {
		var ext = Browser.Engine.trident4 && Browser.Platform.win ? 'gif' : 'png';
		new Element('img', {
			'src': '/images/interface/zoom.'+ext,
			'width': '21',
			'height': '18',
			'styles': {
				'position': 'absolute',
				'top': '10px',
				'right': '5px',
				'z-index': 2
			}
		}).inject($('productdiagram').getParent());
		$('productdiagram').getParent().setStyle('position', 'relative');

		$('productdiagram').addEvent('click', function(e) {
			e.stop();
			
			var overlay = createOverlay();
			var windowsize = window.getSize();
			var windowscroll = window.getScroll();

			var images = new Asset.images([$('productdiagram').getParent('a').getProperty('href')], {onComplete: function() {
				var image = images[0];
				image.inject(overlay);
				var imgsize = image.getSize();
				imgsize = {x: imgsize.x, y: imgsize.y};

				overlay.retrieve('fx').start({
					'left': [overlay.getLeft(), windowscroll.x + (windowsize.x - imgsize.x) / 2],
					'width': ['0px', imgsize.x+'px'],
					'padding': [overlay.getStyle('padding').toInt(), 20]
				});
				overlay.retrieve('fx').start.delay(1200, overlay.retrieve('fx'), {
					'top': [overlay.getTop(), windowscroll.y + (windowsize.y - imgsize.y) / 2],
					'height': ['0px', imgsize.y+'px']
				});
			}});
		});
	}

	new mouseOvers();

	$$('.expandinglist').each(function(list) {
		if (list.get('id') != 'distributors') {
			var defopen = -1;
	
			list.getElements('a.toggler').each(function(a, i) {
				a.addEvent('click', function(e) {
					new Event(e).stop();
				});
				if (defopen == -1 && document.location.href.substr(document.location.href.indexOf('#')) == a.get('href')) {
					defopen = i;
				}
			});
			
			var listacc = new Accordion(list.getElements('a.toggler'), list.getElements('div.details'), {
				'display': defopen,
				'show': defopen,
				'alwaysHide': true
			});
	
			list.getElements('a.close').each(function(a, i) {
				a.addEvent('click', function(e) {
					new Event(e).stop();
					listacc.display(i);
				});
			});
		}
	});
	
	if ($('distributors')) {
		var defopen = -1;

		$$('#distributors a.conttoggler').each(function(a, i) {
			a.addEvent('click', function(e) {
				e.stop();
			});
			if (defopen == -1 && document.location.href.substr(document.location.href.indexOf('#')) == a.get('href')) {
				defopen = i;
			}
		});

		$$('div#distributors a.toggler').addEvent('click', function(e) {
			e.stop();
		});

		var distributors = new Accordion($$('#distributors a.toggler'), $$('#distributors div.details'), {
			'display': -1,
			'show': -1,
			'alwaysHide': true,
			onActive: function(toggler){
				toggler.getParent('ul').setStyle('height', 'auto');
				$$('div#distributors a.toggler').removeClass('current');
				toggler.addClass('current');
			},
			onBackground: function(togglers, stretchers){
				stretchers.setStyle('height', stretchers.offsetHeight);
			}
		});

		$$('.continent h2').setStyle('display', 'none');

		var continents = new Accordion($$('#distributors a.conttoggler'), $$('#distributors ul.countries'), {
			'display': defopen,
			'show': defopen,
			'alwaysHide': true,
			onActive: function(toggler) {
				$$('div#distributors a.conttoggler').removeClass('current');
				toggler.addClass('current');
			},
			onBackground: function(togglers, stretchers){
				distributors.display(-1);
			}
		});

		$$('#distributors a.close').each(function(a, i) {
			a.addEvent('click', function(e) {
				e.stop();
				distributors.display(i);
			});
		});

		if ($('worldmap_map')) {
			var defimage = $('worldmap').get('src');
			
			var worldmaps = [];
			$$('#worldmap_map area').each(function(area) {
				worldmaps.push(defimage.replace(/\/([a-z]+)\.([a-z]{3})$/, '/'+area.get('class')+'.$2'));
			});
			new Asset.images(worldmaps);
			
			$$('#worldmap_map area').addEvent('mouseenter', function() {
				pngfix.setSrc($('worldmap'), defimage.replace(/\/([a-z]+)\.([a-z]{3})$/, '/'+this.get('class')+'.$2'));
			});
			$$('#worldmap_map area').addEvent('mouseleave', function() {
				pngfix.setSrc($('worldmap'), defimage);
			});
			$$('#worldmap_map area').addEvent('click', function(e) {
				e.stop();
				var classname = this.get('class');
				$$('#distributors a.conttoggler').each(function(a, i) {
					if (a.get('href').substring(a.get('href').indexOf('#')+1) == classname) {
						continents.display(i);
					}
				});
			});
		}
	}

	pngfix = new pngSupport({transparentImage: '/images/pnghack/transparent.gif'})
	pngfix.replace();

	// Inject "lastrow" and "newrow"
	$$('ul.columns li').each(newRow);
  $$('ul.columns2 li').each(newRow);
  $$('ul.columns3 li').each(newRow);
  $$('ul.columns, ul.columns2, ul.columns3').each(function(ul) {
  	new Element('li', {
  		'class': 'lastrow'
  	}).inject(ul);
  });

  if ($('myaxon_loginform') && $('myaxon_login')) {
  	var myaxon_loginform = $('myaxon_loginform').get('html');
  	$('myaxon_login').addEvent('click', function(e) {
  		new Event(e).stop();
  		
			var overlay = createOverlay();
			var windowsize = window.getSize();
			var windowscroll = window.getScroll();

			if (!$('myaxon_loginform')) {
				new Element('div', {
					'id': 'myaxon_loginform',
					'html': myaxon_loginform
				}).inject(document.body);
			}

			$('myaxon_loginform')
				.setStyle('display', 'block')
				.inject(overlay);

			var imgsize = $('myaxon_loginform').getSize();
			imgsize = {x: imgsize.x, y: imgsize.y};

			overlay.retrieve('fx').start({
				'left': [overlay.getLeft(), windowscroll.x + (windowsize.x - imgsize.x) / 2],
				'width': ['0px', imgsize.x+'px'],
				'padding': [overlay.getStyle('padding').toInt(), 20]
			});
			overlay.retrieve('fx').start.delay(1200, overlay.retrieve('fx'), {
				'top': [overlay.getTop(), windowscroll.y + (windowsize.y - imgsize.y) / 2],
				'height': ['0px', imgsize.y+'px']
			});
		});
  }

	if ($('firmwarenotifications')) {
		new Element('ul', {
			'id': 'firmwarenotifications_subscribed'
		}).injectAfter($('firmwarenotifications_unsubscribed'));

		var ullist = [$('firmwarenotifications_subscribed'), $('firmwarenotifications_unsubscribed')];

		$('firmwarenotifications_unsubscribed').getParent('form').addEvent('submit', function(e) {
			$('firmwarenotifications_subscribed').getElements('input').set('checked', 'checked');
			$('firmwarenotifications_unsubscribed').getElements('input').set('checked', '');
		});

		$('firmwarenotifications').getElements('li').each(function(label) {
			if (label.getElement('input').get('checked')) {
				label.inject($('firmwarenotifications_subscribed'));
			}
		});
		
		ullist.each(function(ul) {
			ul.getElements('li').removeClass('dark');
			var li = ul.getFirst('li');
			while (li) {
				li.addClass('dark');
				li = li.getNext('li')?li.getNext('li').getNext('li'):null;
			}
		});

		if ($('fn_searchfield')) {
			$('fn_searchfield').addEvent('keyup', function(e) {
				$('firmwarenotifications_unsubscribed').getElements('li').addClass('hidden');
				var value = this.get('value').toUpperCase();
				var vlength = value.length;
				if (vlength == 0) {
					$('firmwarenotifications_unsubscribed').getElements('li').removeClass('hidden');
				} else {
					$('firmwarenotifications_unsubscribed').getElements('label').each(function(lbl) {
						if (lbl.get('text').substring(1, vlength+1).toUpperCase() == value) {
							lbl.getParent('li').removeClass('hidden');
						}
					});
				}
			});
		}
		
		new SortablesExt(ullist, {
			constrain: false,
			ghost: true,
			clone: true,
			onStart: function() {
				var yesno = 'yes';
				if (this.element.getParent('ul').get('id') == 'firmwarenotifications_subscribed') {
					yesno = 'no';
				}

				$('firmwarenotif_wrapper').setStyle('background-image', 'url(/images/interface/subscribearrow_'+yesno+'.png)');
			},
			onComplete: function() {
				// Inject alfa sorted
				var element = this.element;
				var childs = element.getParent('ul').getElements('li');
				var numchilds = childs.length;
				for (var i=0; i<numchilds; i++) {
					if (childs[i].get('text') > element.get('text')) {
						element.inject(childs[i], 'before');
						i = numchilds;
					}
				}

				ullist.each(function(ul) {
					ul.getElements('li').removeClass('dark');
					var li = ul.getFirst('li');
					while (li) {
						li.addClass('dark');
						li = li.getNext('li')?li.getNext('li').getNext('li'):null;
					}
				});
			}
		});
	}

});

var SortablesExt = new Class({

	Extends: Sortables,

	getClone: function(e){
		var element = $(e.target);
		var pos = element.getPosition(element.getOffsetParent());
		var scroll = this.list.getScroll();
		pos = {x: pos.x - scroll.x, y: pos.y - scroll.y};
		return element.clone(true).setStyles({
			'margin': '0px',
			'position': 'absolute',
			'visibility': 'hidden'
		}).addClass('dragging').inject(this.list).position(pos);
	}
	
});

function newRow(li, i) {
	var ul = li.getParent('ul');
	if ((ul.hasClass('columns3') && i%3 == 2) || (ul.hasClass('columns2') && i%2 == 1)) {
		new Element('li', {
  		'class': 'nextrow'
  	}).injectAfter(li);
	}
}

function createOverlay(classname) {
	if (!classname) classname = '';
	if (!$('bodyoverlay')) {
		var windowscroll = window.getScrollSize();
		if (!$('bodyoverlay')) {
			new Element('div', {
				'id': 'bodyoverlay',
				'styles': {
					'opacity': 0,
					'width': windowscroll.x+'px',
					'height': windowscroll.y+'px'
				}
			})
				.inject(document.body)
				.store('fx', new Fx.Tween($('bodyoverlay'), {property: 'opacity', duration: 1000}));
		}
	} else {
		$('bodyoverlay').set('html', '');
	}
	if ($('bodyoverlay').getStyle('opacity') != 0.8) {
		$('bodyoverlay').retrieve('fx').start(0.8);
	}

	flashview('hidden');

	new Element('div', {
		'id': 'overlay_content',
		'class': classname,
		'styles': {
			'top': window.getScroll().y + (window.getSize().y / 2),
			'left': window.getScroll().x + (window.getSize().x / 2)
		}
	}).inject(document.body);
	$('overlay_content').store('fx', new Fx.Morph($('overlay_content'), {
		duration: 1000,
		link: 'cancel',
		onComplete: function() {
			if ($('overlay_content').getStyle('height').toInt() < 20) {
				$('close_overlay_content').setStyle('display', 'none');
			} else {
				$('close_overlay_content').setStyle('display', 'block');
			}
		}
	}));

	new Element('a', {
		'id': 'close_overlay_content',
		'class': 'bullet_grey close',
		'html': 'Close'
	})
		.inject($('overlay_content'))
		.addEvent('click', function(e) {
			new Event(e).stop();
			$('bodyoverlay').retrieve('fx').start(0);
			$('close_overlay_content').dispose();
			$('overlay_content').dispose();
			flashview('visible');
		});

	return $('overlay_content');
}

var slider = new Class({
	Implements: [Options],
	
	options: {
		autotimer: 1000
	},
	
	initialize: function(element, controls, elements, options) {
		this.element = element;
		this.setOptions(options);
		this.nextel = 0;
		this.controls = controls;
		this.elements = elements;
		this.started = false;

		var auto = this.element.get('class').match(/auto_([0-9]+)/);
		if (auto) {
			this.options.autotimer = auto[1];
		} else if (this.element.hasClass('noauto')) {
			this.options.autotimer = 0;
		}

		this.controls.each(function(head, i) {
			head.injectBefore(this.elements[0]);
			head.addEvent('click', this.slide.bindWithEvent(this, i));
			if (head.hasClass('sliderinit')) {
				this.nextel = i;
			}
		}, this);

		var maxheight = 0;
		this.elements.each(function(el) {
			maxheight = maxheight > el.getSize().y ? maxheight : el.getSize().y;
		}, this);
		this.elements.setStyle('height', maxheight);
		this.elements.setStyle('display', 'none');
		
		var me = this;
		this.element.addEvent('mouseleave', function() {
			if (me.options.autotimer > 0) {
				this.autoslide = me.doSlide.periodical(me.options.autotimer, me);
			}
		});
		
		this.element.addEvent('mouseenter', function() {
			$clear(this.autoslide);
		});
	},

	slide: function(e, curel) {
		this.nextel = curel;
		this.doSlide();
		this.element.fireEvent('mouseenter');
	},
	
	doSlide: function() {
		if (this.controls.length == 0 || this.elements.length == 0) {
			return;
		}
		if (!this.controls[this.nextel]) {
			this.nextel = 0;
		}
		
		this.elements.setStyle('display', 'none');
		this.controls.removeClass('active');
		this.elements[this.nextel].setStyle('display', 'block');
		this.controls[this.nextel].addClass('active');
		this.nextel++;
	},

	start: function() {
		if (!this.started) {
			this.started = true;
			this.element.fireEvent('mouseleave');
			this.doSlide();
		}
	}
});

var mouseOvers = new Class({
	initialize: function(elements) {
		elements = elements || $$('img.mouseover');
		elements.each(function(image) {
			if (image.hasClass('specialmo')) {
				image.set('src_mouseover', image.get('class').replace(/.*mouseover=/, ''));
				image.set('src_mouseout',  image.get('src'));
				image.addEvent('mouseenter', this.mouseover);
				image.addEvent('mouseleave', this.mouseout);
				new Asset.image(image.get('src_mouseover'));
			} else {
				var xsrc = image.src;
				if (xsrc.substring(xsrc.length-7, xsrc.length-3) == '_up.')	{
					image.set('src_mouseover', image.get('src').replace(/_up\.([a-z]{3})/, '_ov.$1'));
					image.set('src_mouseout',  image.get('src'));

					image.addEvent('mouseenter', this.mouseover);
					image.addEvent('mouseleave', this.mouseout);

					// Preload
					new Asset.image(image.get('src_mouseover'));
				}
			}
		}, this);
	},
	mouseover: function() {
		this.set('src', this.get('src_mouseover'));
	},
	mouseout: function()	{
		this.set('src', this.get('src_mouseout'));
	}
});

var pngSupport = new Class({

	Implements: [Options],

	options: {
		transparentImage: '/images/pnghack/transparent.gif'
	},

	initialize: function(options) {
		this.setOptions(options);
		this.needed = Browser.Engine.trident4 && Browser.Platform.win;
	},

	replace: function(parentel) {
		if (!this.needed) return;
		if (!parentel) parentel = document;

		parentel.getElements('img').each(function(img) {
			if (img.src.indexOf(this.options.transparentImage) == -1 && img.src.indexOf("png") >= 0) {
				var oldsrc = img.get('src');
				var size = img.getSize();
				img.set('src', this.options.transparentImage);
				img.set('width', size.x);
				img.set('height', size.y);
				this.setSrc(img, oldsrc);
			}
		}, this);
	},

	setSrc: function(img, src) {
		if (this.needed) {
			img.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
		} else {
			img.set('src', src);
		}
	}
});

function flashview(visibility) {
	if (Browser.Platform.linux && $('headerflash_obj') && $('headerflash_alt')) {
		$('headerflash_obj').setStyle('display', visibility=='visible'?'inline':'none');
		$('headerflash_alt').setStyle('display', visibility=='hidden' ?'inline':'none');
	}
}

var productselector = new Class({

	Implements: [Options],
	
	options: {
		idprefix: 'prodsel_',
		classprefix: 'prodsel_'
	},
	
	initialize: function(url, options) {
		this.setOptions(options);

		var overlay = createOverlay('productselector');
		var windowsize = window.getSize();
		var windowscroll = window.getScroll();

		var winsize = {x: 860, y: 600};
		overlay.retrieve('fx').start({
			'left': [overlay.getLeft(), windowscroll.x + (windowsize.x - winsize.x - 40) / 2],
			'width': ['0px', winsize.x+'px'],
			'padding': [overlay.getStyle('padding').toInt(), 20]
		});
		overlay.retrieve('fx').start.delay(1200, overlay.retrieve('fx'), {
			'top': [overlay.getTop(), (windowscroll.y + 20)],
			'height': ['0px', winsize.y+'px']
		});
		/*overlay.setStyles({
			'height': 'auto',
			'top': (windowscroll.y + 20) +'px'
		});*/

		var me = this;
		new Request({
			'url': url,
			'method': 'get',
			'onSuccess': function(responseText, responseXML) {
				new Element('div')
					.set('html', responseText)
					.inject(overlay);

				$(me.options.idprefix + 'submit').setStyle('display', 'none');
				$(me.options.idprefix + 'reset').addEvent('click', me.resetselection.bindWithEvent(me));
				$$('input.' + me.options.classprefix + 'option').addEvent('click', me.updateselection.bindWithEvent(me));

				new Accordion(
					$$('form#productselector li.featuregroup h2'),
					$$('form#productselector li.featuregroup ul'), {
						alwaysHide: true
					}
				);

				$('productselector').setStyles({
					'height': '495px',
					'overflow-y': 'auto'
				});
				$('productselector_resultsul').setStyles({
					'height': '400px',
					'overflow-y': 'auto'
				});

				me.request = new Request({
					'url': $(me.options.idprefix + 'submit').getParent('form').get('action'),
					'method': 'post',
					'autoCancel': true,
					'onRequest': me.updateselectionRequest,
					'onSuccess': me.updateselectionSuccess,
					'parent': me
				});
			}
		}).send('inpage');
	},
	
	resetselection: function(e) {
		new Event(e).stop();
		$$('input.' + this.options.classprefix + 'option').each(function(el) {
			el.set('checked', '');
		});
		this.updateselection();
	},

	updateselection: function() {
		var postdata = 'ajax=1';
		$$('input.' + this.options.classprefix + 'option').each(function(el) {
			el.set('disabled', 'disabled');
			if (el.get('checked')) {
				postdata += '&' + el.get('name') + '=' + el.get('value');
			}
		});
		this.request.send({'data': postdata});
	},

	updateselectionRequest: function() {
		$(this.options.parent.options.idprefix + 'submit').getParent('form').addClass('loading');
	},

	updateselectionSuccess: function(responseText, responseXML) {
		var idprefix = this.options.parent.options.idprefix;
		var catids = responseXML.getElementsByTagName('keepopen');
		var numresponses = catids.length;

		var cattype = '';
		for (var i=0; i<numresponses; i++) {
			cattype = catids[i].getAttribute('type')?catids[i].getAttribute('type')+'':'cat';
			if ($(idprefix + cattype + '_' + catids[i].getAttribute('id'))) {
				$(idprefix + cattype + '_' + catids[i].getAttribute('id')).set('disabled', '');
			}
		}

		var productids = responseXML.getElementsByTagName('product');
		var numresponses = productids.length;
		var products = '';
		var producturl = $('producturl').get('value');
		for (var i=0; i<numresponses; i++) {
			products += '<li><a href="'+producturl+'/'+productids[i].getAttribute('id')+'" title="'+productids[i].getAttribute('name')+'">'+productids[i].getAttribute('name')+'</a></li>';
		}
		$('productselector_resultsul').set('html', products);

		$(idprefix + 'numresults').set('html', responseXML.getElementsByTagName('numproducts')[0].getAttribute('value'));
		$(this.options.parent.options.idprefix + 'submit').getParent('form').removeClass('loading');
		$(idprefix + 'numresults').getParent().highlight.delay(1000, $(idprefix + 'numresults').getParent(), '#9dc2dc');
	}
});
