window.addEvent('domready',function() {

	$$('a[rel=external]').set('target', '_blank');

	if ($('q')) {
		initSearchForm();
	}
	
	if (location.href.contains('/contact/') && $('formcontact')) {
		initContactForm();
	}
	
	if ($('content')) {
		resizeContent();
	}

    if ($('nieuwsbrief')) {
        $('email').addEvents({
            'focus' : function() {
                if (this.get('value') === 'E-mailadres') {
                    this.set('value', '');
                }
            },
            'blur' : function() {
                if (this.get('value') === '') {
                    this.set('value', 'E-mailadres');
                }
            }
        });

        $('nieuwsbrief').addEvent('submit', function(e) {
            var regExMail = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

            if (!$('email').get('value').match(regExMail)) {
                alert('Vul een geldig e-mailadres in.');
                return false;
            }

            return true;
        });
    }

    Search();
});

window.onload = function() {
    if ($('slideshow')) {
		initSlideShow();
	}
}

var resizeContent = function() {
	if ($('content').getSize().y < 700) {
		$('content').setStyle('height', '700px');
	}
}

var initSearchForm = function() {
	new OverText($('q'));

	$('q').addEvents({
		'focus' : function() {
			this.addClass('active');
		},
		'blur' : function() {
			this.removeClass('active');		
		}
	});
}

var initContactForm = function() {
	$('formcontact').addEvent('submit',function(e) {
		new Event(e).stop();

		var valid = true;

		$$('.reqFld').each(function(field) {
			field.removeClass('reqFldEmpty');
			if(field.get('value') == '') {
			  field.addClass('reqFldEmpty');
			  valid = false;
			}
		});

		if (!valid) {
			alert('De gekleurde velden zijn verplicht');
			return;
		}

		$("formcontact").submit();
	});
}

var timeoutSlideshow;

var initSlideShow = function() {
	Pic.each(function(image) {
		new Element('img', {
			'src' : image
		}).setStyle('opacity', 0).inject($('productImg'));
	});

	$('productImg').getElement('img').destroy();
	$('productImg').getElement('img').setStyle('opacity', 1);

	initSlideShowPeriodical();

	$('controls').setStyle('opacity', 0);

	$$('div.control').each(function(control) {
		control.addEvents({
			'mouseenter' : function() {
				this.getElement('img').set('src', this.getElement('img').get('src').replace('.', '_blue.'));
			},
			'mouseleave' : function() {
				this.getElement('img').set('src', this.getElement('img').get('src').replace('_blue', ''));
			}
		});
	})

	$('slideshow').addEvents({
		'mouseenter' : function() {
			$('controls').fade('in');
		},
		'mouseleave' : function() {
			if ($('control_play').getStyle('display') == 'inline') {
				$('controls').fade('out');
			}
		}
	});

	$('control_play').addEvent('click', function() {
		pauseSlideShow();
	});

	$('control_pause').addEvent('click', function() {
		initSlideShowPeriodical();
	});

	$('control_next').addEvent('click', function() {
		pauseSlideShow();
		nextSlide();
	});

	$('control_previous').addEvent('click', function() {
		pauseSlideShow();
		previousSlide();
	});
}

var pauseSlideShow = function() {
	$('control_play').setStyle('display', 'none');
	$('control_pause').setStyle('display', 'inline');
	$clear(timeoutSlideshow);
};

var initSlideShowPeriodical = function() {
	$('control_pause').setStyle('display', 'none');
	$('control_play').setStyle('display', 'inline');
	$clear(timeoutSlideshow);
	timeoutSlideshow = nextSlide.periodical(3000);
}

var nextSlide = function() {
	$('productImg').getElement('img').fade('out').inject($('productImg'));
	$('productImg').getElement('img').fade('in'); 
}

var previousSlide = function() {
	$('productImg').getElement('img').fade('out')
	$('productImg').getElements('img').getLast().inject($('productImg'), 'top').fade('in');
}

var Search = function() {
    if (window.location.pathname != '/zoeken' && window.location.pathname != '/zoeken/') {
        return;
    }

    $('cx_loading').removeClass('hidden');
    
    var index = urlParams.index;
    if (index < 1) { index = 1; }

    var query = urlParams.q

    if (query == '' || query == undefined) {
        $('cx_loading').addClass('hidden');
        $('cx_error').set('html', 'Geef een zoekterm op.');
        return;
    }

    if (query.length < 3) {
        $('cx_loading').addClass('hidden');
        $('cx_error').set('html', 'Geef een zoekterm van minimaal 3 karakters op.');
        return;
    }
    
    var url = 'https://www.googleapis.com/customsearch/v1';
    url += '?key=' + Search.options.key;
    url += '&cx=' + Search.options.cx;
    url += '&num=' + Search.options.perPage;
    url += '&start=' + index;
    url += '&q=' + query;
    url += '&callback=' + Search.options.callback;
    url += '&alt=json';

    new Element('script', {
        'type' : 'text/javascript',
        'src' : url
    }).inject($('container'));
}

Search.callback = function(response) {

    if (response.error != undefined) {
        $('cx_loading').addClass('hidden');
        $('cx_error').set('html', 'Fout bij ophalen resultaten voor zoekterm <em>' + urlParams.q + '</em>');
        return;
    }

    var prevIndex, index = response.queries.request[0].startIndex;
    var count = response.queries.request[0].count;
    var total = response.queries.request[0].totalResults;
    var query = response.queries.request[0].searchTerms;
    
    if (total == 0) {
        $('cx_loading').addClass('hidden');
        $('cx_error').set('html', 'Geen resultaat voor zoekterm <em>' + query + '</em>.');
        return;
    }

    $('cx_query').set('html', '<p><strong>Resultaat ' + index + ' - ' + (index + count - 1) + ' van ' + total + ' voor zoekterm</strong> <em>' + query + '</em></p>');

    response.items.each(function(item) {
        new Element('div', {
            'html' : '<p class="titel"><a href="' + item.link + '">' + item.htmlTitle + '</a></p><p class="omschrijving">' + item.htmlSnippet + '</p><p class="url"><a href="' + item.link + '">' + item.link.replace('http://', '') + '</a></p>'
        }).inject($('cx_results'));
    });

    if (index > 1) {
        prevIndex = index - count
        if (prevIndex < 1) { prevIndex = 1; }

        new Element('p', {
            'class' : 'vorige',
            'html' : '<a href="?q=' + query + '&amp;index=' + prevIndex + '">Vorige</a>'
        }).inject($('cx_paging'));
    }

    if (index + count < total) {
        new Element('p', {
            'class' : 'volgende',
            'html' : '<a href="?q=' + query + '&amp;index=' + (index + count) + '">Volgende</a>'
        }).inject($('cx_paging'));
    }

    $('cx_loading').addClass('hidden');
    
    $('content').setStyle('height', ($('cx').getSize().y + 100) + 'px');
    resizeContent();
};

Search.options = {
    perPage : 10,
    key : 'AIzaSyD31b92s_z4VEY0A1YjxEyWdx24b1VVVSc',
    cx : '001631565600874010309:bh8dppi6pdi',
    callback : 'Search.callback'
};

var urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       urlParams[d(e[1])] = d(e[2]);
})();
