var defaultSearchText = 'Search'; // text in search box if blank

function trim(s) {
	// only whitespaces?
	if (s.match('/^\s*$/')) {
		return '';
	}
	
	// first delete all whitespaces in front, then all after the text
	return s.replace(/^\s*(\S.*)$/, '$1').replace('/^(.*\S)\s*$/', '$1');
}

function initSlider(containerName) {
	// slider as described at http://jqueryfordesigners.com/slider-gallery/
	
	var container = jQuery(containerName);
	var ul = jQuery('ul', container);
	
	// apply all label positions
	jQuery('div.labels span.label', container).each(function(){
		var position = jQuery('span.position', this).text();
		jQuery('span.position', this).remove();
		jQuery(this).css('margin-left', position+'px');
	});
	
	// apply all links
	jQuery('ul.items li', container).each(function(){
		var url = jQuery('span.link a', this).attr('href');
        var title =jQuery('span.link a', this).attr('title');
		jQuery('span.link', this).remove();
		jQuery('a', this).attr('href', url);
        jQuery('a', this).attr('title', title);	});
	
	// get width of all elements
	// WARNING: potential race condition; may not get correct item width
	//          if images are still loading and CSS does not assign a fix
	//          width to li
	var totalWidth = 0;
	ul.find('li').each(function(){
		totalWidth += parseInt(jQuery(this).css('width'));
		totalWidth += parseInt(jQuery(this).css('margin-left'));
		totalWidth += parseInt(jQuery(this).css('margin-right'));
	});
	
	var max = totalWidth - parseInt(container.find('div.inner').css('width'));
	
	// disable handle (= don't continue) if not enough content to scroll
	if (totalWidth <= container.innerWidth()) {
		//container.find('.handle').css('visibility', 'hidden');
		container.find('.handle').css('display', 'none');
		return;
	}
	
	var sliderWidth = 702;
	var handleWidth = 146;
	
	var controlChange = container.outerWidth();
	
	var sliderStopMove = function (value) {
	  	ul.animate({'left': value * -1}, 500);
	 		jQuery('.handle').animate({'left': (value / max * sliderWidth) - 32}, 500);
	 };
	
	var slider = jQuery('.slider', container);
	slider.slider({
		'min': 0,
		'max': max,
		'handle': '.handle',
		'stop':   function(e, ui) {
								sliderStopMove(ui.value);
							},
		'slide':  function (e, ui) {
		       	 		ul.css('left', ui.value * -1);
		       	 		jQuery('.handle').css('left', (ui.value / max * sliderWidth) - 32);
		          }
	});
	slider.slider('option', 'animate', true);
	jQuery('.handle').css('left', -32);
	
	var slideControl = function(direction){
		var value = slider.slider('value') + controlChange * direction;
		if (value < 0) {
			value = 0;
		} else if (value > max) {
			value = max;
		}
		slider.slider('value', value);
		sliderStopMove(value);
	};
	
	jQuery('.slidercontainer a.control-left').click(function(){
		slideControl(-1);
		return false;
	});
	
	jQuery('.slidercontainer a.control-right').click(function(){
		slideControl(+1);
		return false;
	});
}

function initSearch() {
	// search box has a default text
	// remove that text on focus...
	jQuery('form#search .term').bind('focusin', function(){
		var jThis = jQuery(this);
		if (jThis.val() == defaultSearchText) {
			jThis.val('');
		}
	});
	// ... and reenter it on unfocus if input has been left blank.
	// Also trims search term.
	jQuery('form#search .term').bind('focusout', function(){
		var jThis = jQuery(this);
		var trimmedValue = trim(jThis.val());
		if (trimmedValue == '') {
			jThis.val(defaultSearchText);
		} else {
			jThis.val(trimmedValue);
		}
	});
}

function initInnerFade() {
	// IE 6 overlaps navigation below
	// IE 7 overlaps news ticker
	// Quick workaround: remove completely
	
	//if ((navigator.appName == 'Microsoft Internet Explorer') && (navigator.appVersion.match(/MSIE [67]\..*/) != null)) {
	//	jQuery('div.innerfade').html('');
	//	return;
	//}
	
	// workaround for strange empty HTML comment as last li
	// (cannot remove that with stdWrap/TypoScript?!)
	jQuery('div.innerfade ul li').each(function(){
		var jThis = jQuery(this);
		if (jThis.html() == '<!-- -->') {
			jThis.remove();
		}
	});
	
	

	// initialize innerfade plugin
	// http://medienfreunde.com/lab/innerfade/
	jQuery('div.innerfade ul').innerfade({
		speed: 1500,
		timeout: 5000,
		type: 'sequence'
	});	
}

function initHighlightBoxes() {
	// show hand as cursor where href is defined
	jQuery('div.highlightbox').each(function(){
		var url = jQuery('.link a', this).attr('href');
		if ((typeof url != 'undefined') && (url != '')) {
			jQuery(this).css('cursor', 'pointer');
		}
	});	
	
	// follow links on whole box
	jQuery('div.highlightbox').bind('click', function(){
		var url = jQuery('.link a', this).attr('href');
		if ((typeof url != 'undefined') && (url != '')) {
			window.location = url;
		}
	});
    
    //Mouseover effect
    jQuery('div.highlightbox').mouseenter(function(){
        var mouseover = jQuery('div.mouseover div', this);
        if (mouseover.length == '0'){
            return;
        }else{
             jQuery('div.inner', this).attr('style','display:none')
        }
    });
    
    jQuery('div.highlightbox').mouseleave(function(){
        var mouseover = jQuery('div.mouseover div', this);
        if (mouseover.length == '0'){
            return;
        }else{
            jQuery('div.inner',this).removeAttr('style')
        }
    });    
}

function initQtip() {
	jQuery('.productslider a[title]').qtip({
        style: {
            //name: 'light', tip: true
            color: '#79908e',
            opacity: 1,
            border : {
            	width: 1,
            	radius: 1,
            	color: '#79908e'
            },
            tip : {
            	color: '#79908e'
            }
        },
        position: {
            corner: {
                target: 'topMiddle',
                tooltip: 'leftMiddle'
            }
        }
         
    });
}

function initMain() {
	// initialize search
	initSearch();
	
	// initialize slider
	initSlider('div.productslider');
	
	// initialize innerfade
	initInnerFade();
	
	// initialize highlightboxes
	initHighlightBoxes();
    
	// don't load Qtips if moblilebrowser
    jQuery(document).ready(function($){
        var deviceAgent = navigator.userAgent.toLowerCase();
        var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
        if (agentID) {
   
        }else{
            // initialize Qtips
            initQtip();
        }
    });
    
	//jQuery('a[title]').qtip({ style: { name: 'cream', tip: true } });

	// initialize language selection box
	/*
	jQuery('#languageselection>a').click(function(){
		jQuery('div#languageselectionupperbox').slideToggle();
		return false;
	});
	*/
}

jQuery(document).ready(initMain);
