// JavaScript Document
Event = new function(){
    this.Delegates = new Array();
	var Me = this;
	this.AddToDomReady = function(func){
		if(func != null)
		    Me.Delegates.push(func);
	}
}
window.onload = function(){
	$(function(){
		for(var i in Event.Delegates){
			Event.Delegates[i].call();
		}
	});
}

/* Default width of right sidebar upon page load. */
var sidebarWidth = 5;

$(function()
{

	var t_height = setTimeout(function(){
		var dh = $(document).height();
		$(".sidebar_wrapper").css('height', dh);
		clearTimeout(t_height);
	}, 1500);
	
	/*
	$(".sidebar_wrapper").hoverIntent({
		sensitivity: 3,
		interval: 200,
		over: function(){ $(this).animate({"width": '410px' }, { duration: 300, specialEasing: { height: 'easeInOutExpo' } }); },
		out: function(){ $(this).animate({"width": '5px' }, { duration: 300, specialEasing: { height: 'easeInOutExpo' } }); }
	});
	*/
	
	/* For the input textboxes in the footer's newsletter subscription area. */
	$('input[type=text]').each(function(){
		var title = $(this).attr('title');
		$(this)
			.focus(function(){if($(this).val() == title) $(this).val('');})
			.blur(function(){if($(this).val() == '') $(this).val(title);});
	});
	
	$('.search').submit(function(){

		var val = $('input[name=q]').val();
		if(val.length > 2){
			emailRegEx = /[\*\\\/\~\`\+\}\]\|\#]+/i;
			if(val.match(emailRegEx)) return false;
			
			return true;
		}
		else return false;
	});
	
	/* For the auto-show/hide of the header's cart dropdown during mouseover/mouseout. */
	/*$('.basket_link').click(function(){
		$('.small_basket').slideToggle(300);
	});*/
	$('a.basket_link').live('mouseover', function() {$('ul.small_basket').css({"display" : "block"})});
	$('a.basket_link').live('mouseout', function() {$('ul.small_basket').css({"display" : "none"})});
	$('ul.small_basket').live('mouseover', function() {$(this).css({"display" : "block"});} );
	$('ul.small_basket').live('mouseout', function() {$(this).css({"display" : "none"});} );
	
	$('#drop_panel_button').click(function(){		
		$('#drop_panel').slideToggle(300);
		return false;
	});
	
	$("#nav li.menu-drop-item-wrap").hoverIntent({
		sensitivity: 2,
		interval: 100,
		over: function(){
			var cur = $(this);
			var parent = $(this).find('.menu-dropdown');
			cur.addClass('hover');
			parent.animate({"height": Math.abs(parent.find('.md-category').height() + 5)}, {
				duration: 300,
				specialEasing: {height: 'easeInOutExpo'}
			});
		},
		out: function(){
			var cur = $(this);
			var parent = $(this).find('.menu-dropdown');
			
			parent.animate({"height": 0}, {
				duration: 300,
				specialEasing: {height: 'easeInOutExpo'},
				complete: function() 
                { 
                    cur.removeClass('hover');
                }
			});
		}
	});
        
    /* FOR IE, not recognizing the CSS last-child selector applied in the main stylesheet. */
	if(jQuery.support.scriptEval == false)
	{
		//$('div.nav_wrap li:last-child a.menu-drop-item').css('background-image' , 'none');
        $('div.nav_wrap > ul > li:last').css('background-image', 'none');
	}
	
	$(document).bind('click', function(e) {
		var $clicked = $(e.target);
		//if (!$clicked.parents().hasClass("location_dropdown")) $(".location_dropdown dd ul").hide();
		if ((!$clicked.parents().hasClass("small_basket")) && (!$clicked.hasClass("basket_link"))) $(".small_basket").hide();
	});

	/* Code related to custom select dropdown on checkout page */
	/*
	createDropDown();
	
	$(".location_dropdown dt a").click(function() {
		$(".location_dropdown dd ul").toggle();
		return false;
	});
	
	$(".location_dropdown dd ul li a").click(function() {
		var text = $(this).html();
		$(".location_dropdown dt a span").html(text);
		$(".location_dropdown dd ul").hide();
		//$("#result").html("Selected value is: " + getSelectedValue("sample"));
		return false;
	});
	
	
	$(".location_dropdown dd ul li a").click(function() {
		var text = $(this).html();
		
		if (text.search('select country') > 0) $(this).find('span.location_value').html('0');
		
		$(".location_dropdown dt a").html(text);
		$(".location_dropdown dd ul").hide();
		
		var source = $("select[name=COUNTRY_ORDER_PROP_8]");
		var locVal = $(this).find('span.location_value').html();
				
		$("select[name=COUNTRY_ORDER_PROP_8] option").each(function() {
			
			if (parseInt($(this).attr('value')) == locVal) $(this).attr('selected', 'selected');
			else $(this).attr('selected', '')
		});
		
		return false;
	});
	

	// Codes for creation and behaviors of custom radio buttons on checkout page
	$('.order_form_table').find('input[type=radio]').each(function() {
		$(this).after('<span class="checkout_radio"></span>');
		
		if ($(this).attr('checked')==true) $('span.checkout_radio').addClass('checkout_radio_tick');
		$(this).toggle();
	});
	
	$('.delivery_payment_form_group span.checkout_radio').click(function() {
		$('.delivery_payment_form_group span.checkout_radio').each(function() {
			$(this).removeClass('checkout_radio_tick');
			$(this).prev().removeAttr('checked') } );
		
		$(this).toggleClass('checkout_radio_tick');
		
		if ($(this).prev().attr('checked')==false) $(this).prev().attr('checked', 'checked');
		else $(this).prev().removeAttr('checked');
	});
	
	$('#pay_options span.checkout_radio').click(function() {
		$('#pay_options span.checkout_radio').each(function() {
			$(this).removeClass('checkout_radio_tick');
			$(this).prev().removeAttr('checked') } );
		
		$(this).toggleClass('checkout_radio_tick');
		
		if ($(this).prev().attr('checked')==false) $(this).prev().attr('checked', 'checked');
		else $(this).prev().removeAttr('checked');
		
		$('#pay_options span.checkout_radio').each(function() { console.log($(this).prev().attr('checked')); });
	});
	**/
	
	/* Codes for creation and behaviors of custom checkboxes. */
	$('.order_form_table').find('input[type=checkbox]').each(function() {
		if($(this).find('checkout_checkbox').andSelf( ).length == 0) {
			$(this).after('<span class="checkout_checkbox"></span>');
			$(this).next().css({position: 'relative', top: '3px'});
			
			if ($(this).attr('checked')==true) $(this).next().addClass('checkout_checkbox_tick');
			$(this).toggle();
		}
	});
	
	if ( $('input#check_terms_conditions:checked').length != 0 )
		$('span.checkout_checkbox').toggleClass('checkout_checkbox_tick');
	
	$('span.checkout_checkbox').live('click', function() {
		$(this).toggleClass('checkout_checkbox_tick');
		if ( $('input#check_terms_conditions').attr('checked')==false)
			$('input#check_terms_conditions').attr('checked', 'checked');
		else
			$('input#check_terms_conditions').removeAttr('checked');
	});
	
	/* Check if the terms and conditions box has been checked. */
	$('input.buy3').live('click', function(e)
	{
		if($('input#check_terms_conditions').attr('checked') == false)
		{
			alert('Accepteer de algemene voorwaarden om verder te gaan.');
			e.stopImmediatePropagation();
			return false;
		}
		//jQuery.stop();
		var checkedDelivery = $('div.delivery_item input:checked').length;

		if (checkedDelivery == 0)
		{
			alert('Je moet kiezen voor een levering optie.');
			e.stopImmediatePropagation();
			return false;
		}
		
		var errField = false;
		$('input.required').each(function(e) {
			var val = $(this).val();
			
			if(val == '')
			{
				//$(this).parent().addClass('err');
				$(this).css({'background-color': '#FEEFED'});
				errField = true;
			}
			else if($(this).attr('name') == 'ORDER_PROP_7')
			{
				var validateEmail = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
				if( !validateEmail.test( val ) )
				{
					//$(this).parent().addClass('err');
					$(this).css({'background-color': '#FEEFED'});
					errField = true;
				}
				else
					$(this).css({'background-color': '#FFF'});
					//$(this).parent().removeClass('err');
			}
			else
				$(this).css({'background-color': '#FFF'});
				//$(this).parent().removeClass('err');
				
			if(errField == true)
			{
				e.stopImmediatePropagation();
				return false;
			}
		});
		
		return true;
	});
	
	/* For the checkout help icons. */
	$('a.help-icon').live('hover', 
        function() {
            $(this).next().toggle(); 
        }, 
        function() { 
            $(this).next().toggle();
        }
    );
	$('a.help-icon').live('click', function() {return false;});
	//alert("Hi "+$('.checkout_checkbox').length);
	$('.checkout_checkbox').live('click', function() {
		if ($('#check_terms_conditions').attr('checked')==true) $('#check_terms_conditions').next().addClass('checkout_checkbox_tick');
		//$('#check_terms_conditions').toggle(); 
	});

	// For the payment method descriptions that are appearing below the payment method radio buttons.
	$('input[name=PAY_SYSTEM_ID]').live('click', function() {
		var descId = $(this).attr('id');
		
		$('div.payment_desc').removeClass('active_desc');
		
		$('div[title='+descId+']').addClass('active_desc');
	});
	
	/* For the checkout form submission, checking on required textfields. */
	var errField = false;
	$('#ORDER_FORM_ID_NEW').live('submit', function() {
		$('.props_item_req').find('.text').each(function()
		{
			var val = $(this).val();
			
			if(val == '')
			{
				//$(this).parent().addClass('err');
				$(this).css({'background-color': '#FEEFED'});
				errField = true;
			}
			else if($(this).attr('name') == 'ORDER_PROP_7')
			{
				var validateEmail = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
				if( !validateEmail.test( val ) )
				{
					//$(this).parent().addClass('err');
					$(this).css({'background-color': '#FEEFED'});
					errField = true;
				}
				else
					$(this).css({'background-color': '#FFF'});
					//$(this).parent().removeClass('err');
			}
			else
				$(this).css({'background-color': '#FFF'});
				//$(this).parent().removeClass('err');
				
			if(errField == true)
			{
				e.stopImmediatePropagation();
				return false;
			}
		});
	});
	
		
	/* Behavior for the footer tab panels */
	$('div.footer_tab:eq(1), div.footer_tab:eq(2), div.footer_tab:eq(3)').toggle();
	
	/*
	$('div#footer_tablinks > a').click(function() {
												
	$(this).siblings().removeClass('current');
	$(this).addClass('current');

	var currentTab = $(this).attr('rel');
	$('div.footer_tab').each(function() {
		// Get the height of the current tab and apply it to the footwrap div.
		var footerTabHeight = $(this).css('height');
		
		$(this).parent().css({'min-height' : footerTabHeight});
		$(this).hide().removeClass('current');
		
		
	});
	return false;
	});*/
	$('#footer_tablinks > a').click(function() {
		var rel = $(this).attr('rel');
		
		$('#footer_tablinks > a').removeClass('current');		
		$(this).addClass('current');
		
		var footerTabHeight = '';
		
		$('div.footer_tab').removeClass('current').css('display', 'none');
		
		$('div.footer_tab.'+rel).css('display', 'block').addClass('current')
		
		/* Get the height of the current tab and apply it to the footwrap div. */
		footerTabHeight = $('div.footer_tab.'+rel).css('height');
		
		//if(jQuery.support.scriptEval == false) footerTabHeight += 'px';
		
		$('#footer div.footwrap').css({'height': footerTabHeight, 'min-height': footerTabHeight});
		
		if(jQuery.support.scriptEval == false)
		{
			footerTabHeight = parseInt($('div.footer_tab.'+rel).height());
			$('#footer div.footwrap').height(footerTabHeight + 40).css({'height': footerTabHeight+'px', 'min-height': footerTabHeight+'px'});
		}
		
		/*
		 If the merken tab (currently the second tab) is "current", get the height and apply it
		 to the footwrap div (prevents a broken layout/inconsistent background-color when the
		 brand tab gets higher/lower as the number of active brands shown increase/decrease).
		*/
		if ($('div.footer_tab:eq(1)').hasClass('current'))
		{
			footerTabHeight = $('div.footer_tab:eq(1)').css('height');
			$('#footer div.footwrap').css({'height': footerTabHeight, 'min-height': footerTabHeight});
			
			// Automatically set the width of brand list columns in the footer tab.
			var merkenTabWidth = $('div.footer_tab:eq(1)').css('width');
			var merkenColCount = $('div.merkentab > ul.merkenfooter > li').length;
			if (merkenColCount <= 6)
			{
				var colResize = parseInt((parseInt(merkenTabWidth)/parseInt(merkenColCount)) * 0.85);
				$('div.merkentab > ul.merkenfooter > li').css('min-width', colResize);
			}
			else
			{
				var colResize = parseInt((parseInt(merkenTabWidth)/parseInt(merkenColCount)) * 1.2);
				$('div.merkentab > ul.merkenfooter > li').css('min-width', colResize);
			}
		}
		else
		{
			//$('#footer div.footwrap').css({'height': '460px'});
            $('#footer div.footwrap').css({'height': '300px'});
		}
		return false;
	});
	
	/* Set line heights for first and last table rows in table.table_basket, esp. on IE */
	$('.table_basket tbody tr:first-child, .table_basket tbody tr:last-child').css('line-height', '0');
	
	/* Change fonts for footer headings in IE 8 */
	$('#footer_tab .footer_tab h5').each(function() {
		if(jQuery.support.scriptEval == false && parseInt($.browser.version)>=8.0)
		{
			Cufon.now();
			Cufon.set('fontFamily', 'Univers');
			Cufon.replace($(this)).replace('#footer_tab .footer_tab h4, div.footer_stores li strong, div.footer_contact p span');
		}
	});
	
	/* Change fonts for footer headings in IE 7 */
	$('#footer_tab .footer_tab h5').each(function() {
		if(jQuery.support.scriptEval == false && parseInt($.browser.version)<8.0)
		{
			$(this).css({'font': 'normal normal bold 13px/20px Helvetica, Arial, sans-serif'});
		}
	});
	$('#footer_tab .footer_tab h4').each(function() {
		if(jQuery.support.scriptEval == false && parseInt($.browser.version)<8.0)
		{
			$(this).css({'font': 'normal normal bold 15px Helvetica, Arial, sans-serif'});
		}
	});
	$('#footer_tab div.footer_tab .footer_contact p span, #footer_tab div.footer_tab .footer_contact h5').each(function() {
		if(jQuery.support.scriptEval == false && parseInt($.browser.version)<8.0)
		{
			$(this).css({'font': 'normal normal bold 12px/20px Helvetica, Arial, sans-serif', 'text-indent': '0'});
		}
	});
	
	
	/* Search suggest enhancement on header search area. */
	$('form.search input[name=q]').live('keyup', function() {
		var query = $(this).val();
		var jsonUrl = '/.action/autocomplete.php';
		
		if (query.length == 0)
		{
			$(this).stop().focus();
			stopSuggest();
		}
		else
		{
			$.ajaxSetup({cache:false});
			
			var jsonResponse = $.getJSON(jsonUrl,
				{'query' : query},
				function(jsonMsg) {
					stopSuggest();
					var searchSuggestList = '<div class="search-suggest"><ul class="search_suggest">';
					
					$.each(jsonMsg.suggestions, function(key, val) {
						searchSuggestList += '<li>' + val + '</li>';
					});
					
					searchSuggestList + '</ul></div>';
					
					$('div.form').append(searchSuggestList);
                });
		}
	});
	
	$('ul.search_suggest li').live('click', function() {
		$('form.search input[name=q]').val($(this).html());
			stopSuggest();
	});	
	
	/* For the header's main nav dropdown shadows (to adapt to the current width of the div containing it,
	   since it stretches too long when setting a width/minimum width to it) */
	var multiColWrap = 0;
	$('a.menu-drop-item').live('mouseover', function() {
		$(this).next('div.multicol').children('div').each(function() {
			multiColWrap += parseInt($(this).width());
		});
		
		multiColWrap += 65;
		
		$(this).next('div.multicol').css({'width': multiColWrap+'px', 'min-width': multiColWrap+'px'});
		
		multiColWrap = 0;
	});
    
    $('div.buying_details a.inshoe').click(function() {
        // Invoke updating the favorites sidebar listing.
        fetchProductItemFavorites();
        return false;
    });
	
	
	/* For the sidebar twitter and favorites tabs. */
    $('div.sidebar_wrapper label.sidebar_label').click(function()
    {
        if ($(this).hasClass('active_label'))
        {
            /* Slide the right sidebar wrapper in/out on clicking of label. */
            if (sidebarWidth == 5)
                sidebarWidth = 410;
            else
                sidebarWidth = 5;
            
            $(".sidebar_wrapper").animate({"width": sidebarWidth+'px'}, {duration: 300, specialEasing: {height: 'easeInOutExpo'}});            
        }
        else
        {
            $('label.sidebar_label').removeClass('active_label');
            $(this).addClass('active_label');
            
            if (sidebarWidth == 5)
            {
                sidebarWidth = 410;            
                $(".sidebar_wrapper").animate({"width": sidebarWidth+'px'}, {duration: 300, specialEasing: {height: 'easeInOutExpo'}});
            }
        }
    });
    
    /* For the header user login button. */
    $("a#userlogin").colorbox(
                        { 
                            title: false, 
                            href: "/.includes/header/login-user.php", 
                            transition:'elastic', 
                            speed:500, 
                            iframe : false 
                        }, 
                        function(response) { }
                    );
    $("a#userlogout").colorbox(
                        { 
                            title: false, 
                            href: "/.action/user-logout.php", 
                            transition:'elastic', 
                            speed:500, 
                            iframe : false 
                        }, 
                        function(response)
                        { 
                            var t= setTimeout("window.location.reload()", 300);                            
                        }
                    );
});

function tab_sidebar(el){
	$('.selected_bar').removeClass('selected_bar');
	$(el).parent().addClass('selected_bar');
}

function stopSuggest()
{
	$('div.search-suggest').remove();
}

function addToBasket( id )
{
	/* For automatic updating of the cart items in header section of page. */
	$.ajaxSetup ({cache: false}); 
	$.post('/.action/addtobasket.php', {'id' : id},
		   function( res ) {
				if(res == 'success')
                {
                    var reloadRequest = reloadBasket();
					// startAlert('add-item-success');
                    /*
                    setTimeout(reloadBasket(), 5000);
                    
                    $('ul.small_basket').css({"display" : "block"});
					
					var h = Math.abs( $('ul.small_basket li').length * 81);
					$('ul.small_basket')
						.animate({"height": h }, {
							duration: 8000,
							specialEasing: { height: 'easeInOutExpo' },
							complete: function() { $(this).animate({"height": 0 }, { duration: 8000, specialEasing: { height: 'easeInOutExpo' } }); }
						});
                        */
				}
			}
		);
}

function addToBasketSub( id, pos ){
	$.post('/.action/addtobasket.php', {'id' : id}, function( res ){if(res == 'success'){reloadBasket();hideVariant( pos );startAlert('add-item-success');}});
}

function openVariant( id ){
	$('.popupvar_' + id).animate({'top':'0px'}, 'fast');
}

function hideVariant( id ){
	$('.popupvar_' + id).animate({'top':'265px'}, 'fast');
}

function reloadBasket(){
	$.post('/.includes/common/small.basket.php', {'action' : 'reload'}, 
    function( res )
    {
        $('.basket_wrap').html( res );
		//$('ul.small_basket').css({"display" : "block"});
					
		var h = Math.abs( $('ul.small_basket li').length * 81);
		
		/*
		$('ul.small_basket')
			.animate({"height": h },
			{
				duration: 300,
				specialEasing: { height: 'easeInOutExpo' },
				complete: function()
				{
					$(this).animate({"height": 0 }, 
					{
						duration: 300, specialEasing: { height: 'easeInOutExpo' }
					}); 
				}
			});
			*/
		$('ul.small_basket').slideToggle(800, function()
			{
				setTimeout(function() {$('ul.small_basket').slideToggle(800);}, 1500);
			});
    });
    
    return true;
}

function startAlert( href )
{
	var url = '/.action/message.php?msg=' + href;	
	c_init = $('<a>').attr('href', url);
	$('body').prepend(c_init.colorbox({onClosed:function(){c_init.remove();}, transition:'elastic', speed:500}));
	c_init.click();
}

function centerdiv()
{
	var left, top, w, h, centerDiv, canterImg, parentWrapper;
	
	centerDiv = $('.center_this');
	canterImg = centerDiv.find('img');	
	parentWrapper = centerDiv.parent();
	
	canterImg.load(function(){
		left = Math.ceil(parentWrapper.width() - canterImg.width()) / 2;
		top = Math.ceil(parentWrapper.height() - canterImg.height()) / 2;
	
		if((parentWrapper.css('position') != 'absolute') && (parentWrapper.css('position') != 'relative')) parentWrapper.css({'position':'relative'});
		centerDiv.css({'position':'absolute', 'left':left, 'top':top});
	});
}

// Emulates PHP's in_array() function.
function in_array(needle, haystack, argStrict) {
    var key = '',
        strict = !! argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}


/* Functions to generate the custom styled dropdown in checkout page */
function createDropDown(){
	$('select[name=COUNTRY_ORDER_PROP_8]').toggle();
	
    var source = $("select[name=COUNTRY_ORDER_PROP_8]");
    var selected = source.find("option[selected]");  // get selected <option>
    var options = $("option", source);  // get all <option> elements
    // create <dl> and <dt> with selected value inside it
    $("#LOCATION_ORDER_PROP_8").append('<dl id="location_target" class="location_dropdown"></dl>');
    $("#location_target").append('<dt><a href="#">' + selected.text() + 
        '<span class="location_value">' + selected.val() + 
        '</span></a></dt>');
    $("#location_target").append('<dd><ul></ul></dd>');
    // iterate through all the <option> elements and create UL
    options.each(function(){
        $("#location_target dd ul").append('<li><a href="#">' + 
            $(this).text() + '<span class="location_value">' + 
            $(this).val() + '</span></a></li>');
    });
}

function getSelectedValue(id) {
	return $("#" + id).find("dt a span.value").html();
}


/** scroll control javascript function **/
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollTop(){
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
