/**
 * Bootstrap.js - JavaScript bootstrapper
 *
 * @author Webstores <info at webstores dot nl>
 *         Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 */

$(document).ready(function() {

	// Utilities
	WS.Util.externalLinks();
	WS.Util.rowClick();
	WS.Util.fixPlaceholders();

	// AJAX loading
	$(document.body).ajaxStart(function() {
		$(this).addClass('loading');
	}).ajaxComplete(function() {
		$(this).removeClass('loading');
	});

	// Carousels
	var syc = new YouTubeCarousel('#spotlight-items', {height: 300, autoSize: false, startMuted: false});

	// Togglers
	$('.accordion').each(function() {
		switch(this.id) {
			//case 'widget-accordion':
			case 'profile-details-accordion':
			case 'contact-details-accordion':
				new Toggler(this).expand($(this).find('li:first-child'));
				break;
			default:
				new Toggler(this);
				break;
		}
	});

	if($('#checkout .tabs').length) {
		$('#checkout .tabs').tabs();
	}

	$('#products-nav-inner').tabs({
		show: function(event, ui) {
			if('#'+ui.panel.id == window.location.hash) {
				$(window).scrollTop(0);
			}
		}
	});

	$('#products-nav-inner .toggler').each(function(i) {
		if($(this).hasClass('selected')) {
			$('#products-nav-inner').tabs('select', i);
		}
	});

	// YouTube players
	$('.youtube:not(#spotlight .youtube, .modal-youtube .youtube)').each(function() {
		new YouTubePlayer(this);
	});

	// Modal YouTube
	if($('.modal-youtube .youtube')) {
		var modalPlayah = new YouTubePlayer('.modal-youtube .youtube', {
			autoPlay: true
		});
	}

	// Validation
	$('form').each(function() {
		$(this).validate({
			highlight: function(el, errorClass, validClass) {
				var errorEl = null;

				switch(el.type) {
					case 'radio':
						errorEl = $(el).parents('ul.options');
						break;
					case 'checkbox':
						errorEl = $(el).parent();
						break;
					default:
						errorEl = $(el);
						break;
				}

				errorEl.removeClass(validClass).addClass(errorClass);
			},
			unhighlight: function(el, errorClass, validClass) {
				var errorEl = null;

				switch(el.type) {
					case 'radio':
						errorEl = $(el).parents('ul.options');
						break;
					case 'checkbox':
						errorEl = $(el).parent();
						break;
					default:
						errorEl = $(el);
						break;
				}

				errorEl.removeClass(errorClass).addClass(validClass);
			}
		});
	});

	// Product overview ajax calls
	if($('#product-overview-filters').length) {
        // Prevent default submit and execute an ajax request instead
		$('#product-overview-filters').submit(function(e) {
			e.preventDefault();
			createLoader();
			$.ajax({
				type: 'POST',
				url: $(this).attr('action'),
				data: $(this).serialize(),
				dataType: 'html',
				success: function(response) {
					createProductOverview(response);
				}
			});

			//$('#filter-search-term').autocomplete('close');
		});
		

        // Autocomplete search field and perform form submit on selection
		/*$('#filter-search-term').autocomplete({
			source: function(request, response) {
				$.ajax({
					type: 'POST',
					url: '/connector/web/communicator/livesearch',
					//url: 'livesearch-results.json', // Voor testdoeleinden
					data: 'search='+request.term+'&'+$('#product-overview-filters').serialize(),
					dataType: 'json',
					success: function(data) {
						response(data);
					}
				});
			},
			minLength: 6,
			select: function(event, ui) {
				createLoader();
				$.ajax({
					type: 'POST',
					url: $('#product-overview-filters').attr('action'),
					data: 'filter-id='+ui.item.id+'&'+$('#product-overview-filters').serialize(),
					dataType: 'html',
					success: function(response) {
                        createProductOverview(response);
					}
				});
			}
		});*/

		// specified filter checkboxes change
		$('input.reload').change(function() {
			createLoader();
			$.ajax({
				type: 'POST',
				url: $('#product-overview-filters').attr('action'),
				data: $('#product-overview-filters').serialize(),
				dataType: 'html',
				success: function(response) {
                    createProductOverview(response);
				}
			});
		});
		
		$('#show-more-results').live('click', function(e){
			e.preventDefault();
			$('#option-2').attr('checked', false).change();
		});

	}

	// toggle columns
	$('.toggle-column').change(function() {
		if($(this).attr('checked')) {
			$('.'+$(this).val()).removeClass('hide');
		} else {
			$('.'+$(this).val()).addClass('hide');
		}
	});

    // Shadowbox
	Shadowbox.init({
		overlayOpacity: 0.8,
        troubleElements: ['select']
	});

	// Product overview spinners
	if($('#product-overview').length) {
		$('#product-overview').find('.spinner-input').each(function() {
			new Spinner(this, {min: 0, max: $(this).attr('data-max')});
		});
	}

	// Rim result spinner
	if($('.modal-rim .spinner-input').length) {
		$('.modal-rim .spinner-input').each(function() {
			new Spinner(this, {min: 0, max: $(this).attr('data-max')});
		});
	}


	if(typeof(CheckoutForm) != 'undefined') {
		var cf = new CheckoutForm('#checkout');
	}

	// Colorpicker
	if($('.colorpicker').length) {
		$('.colorpicker').miniColors();
	}

	// Price calculation method togglprint_r

	if($('#price-calculation-methods').length) {
		$('.calculation-method').hide();

		$('.calculation-method-toggler').each(function() {
			if($(this).attr('checked')) {
				$('#'+$(this).attr('value')).show();
			}

			$(this).change(function() {
				$('.calculation-method').hide();
				$('#'+$(this).attr('value')).show();
			});
		});
	}

	// Disable color fields when default checkbox is checked
	if($('.use-default').length) {
		$('.use-default').each(function() {
			if($(this).attr('checked') === true) {
				$('#'+$(this).attr('id').split('-default')[0]).miniColors('disabled', true);
			}
			$(this).change(function() {
				if($(this).attr('checked') === true) {
					$('#'+$(this).attr('id').split('-default')[0]).miniColors('disabled', true);
				} else {
					$('#'+$(this).attr('id').split('-default')[0]).miniColors('disabled', false);
				}
			});
		});
	}

	// Toggle combobox
	if($('.combobox').length) {
		$($('.combobox .toggler').attr('href')).toggle();
		$('.combobox .toggler').click(function(e) {
			e.preventDefault();
			$($(this).attr('href')).toggle();
		});
	}

	// Rim filter options
	if($('.rim-filter-options').length) {
		$('.rim-filter-options').change(function(e) {
			var self = this;

			$.ajax({
				type: 'POST',
				url: $(self).attr('action'),
				data: $(self).serialize()
			});
		});
	}

	// Rim modal window submit
	if($('#modal-rim-form').length) {

		$('#modal-rim-form').bind('submit', function(e) {
			var postData = $(this).serialize();
			if(typeof(e.url) != 'undefined') {
				postData = 'url='+e.url+'&'+$(this).serialize()
			}
            createLoader();
			e.preventDefault();

 			$.ajax({
				type: 'POST',
				url: $(this).attr('action'),
				data: postData,
				dataType: 'json',
 				success: function(response) {
                     if (response.url !== undefined || response.url != '') {
                        window.parent.document.location = response.url;
                    }
				}
			});
		});

		$('#modal-rim-form a').click(function(e) {
			e.preventDefault();
			var self = this;

			$('#modal-rim-form').trigger({
				type: 'submit',
				url: $(self).attr('href')
			});
		});
	}

	// Default actions when loading product overview form
	productOverviewActions();
});

var createLoader = function() {
	$('#product-overview-table').html('<div id="product-overview-loader"><img src="/img/loader.gif" alt="De gegevens worden opgehaald, ogenblik geduld a.u.b." width="48" height="48"></div>');
};

var createProductOverview = function(data) {
    data = data.replace(/td>\s+<td/g,'td><td');
    $('#product-overview-table').html(data);
    Shadowbox.setup('#product-overview-table .product-photo-link[rel=shadowbox]');
    $('#product-overview-table').find('.spinner-input').each(function() {
        new Spinner(this, {min: 0, max: $(this).attr('data-max')});
    });
    productOverviewActions();
};

var productOverviewActions = function() {
	$('#product-overview-form .order-button').click(function() {
        var $productForm = $('#product-overview-form');
		var self = this;
		setTimeout(function() {
            $.ajax({
                type: 'POST',
                url: $productForm.attr('action'),
                data: $productForm.serialize(),
                dataType: 'json',
                success: function(response) {
					if (response.url !== undefined || response.url != '') {
                        if ($('.extern #product-overview-form .order-button').length) {
                            window.document.location = response.url;
                        } else {
                            parent.document.location = response.url;
                        }
                    }
                }
            }, 10);
		});
        /*setTimeout(function() {
            $.ajax({
                type: 'POST',
                url: $productForm.attr('action'),
                data: $productForm.serialize(),
                dataType: 'json',
                success: function(response) {
					if(response.alert === true) {
						$('#profile-nav .shopping-cart a').after('<div id="cart-message" class="alert" style="display: none;">'+response.alertMessage+'</div>');
					} else {
						$('#profile-nav .shopping-cart a').after('<div id="cart-message" style="display: none;">'+response.alertMessage+'</div>');
					}
	                $('html, body').animate({
						scrollTop: $('#profile-nav').offset().top - 10
					});
	                $('#profile-nav .shopping-cart #cart-message').fadeIn();
                    if(response.status === 'success') {
                        $productForm.find('.spinner-input').val(0);
                    }
	                var cartMessageTimeout = setTimeout(function() {
		                $('#profile-nav .shopping-cart #cart-message').fadeOut(400, function() {
			                $(this).remove();
		                });
	                }, 6000);
                }
            }, 10);
        });*/
    });

	/*$('#product-overview-form').submit(function(e) {
		e.preventDefault();
		var $productForm = $('#product-overview-form');
		$.ajax({
			type: 'POST',
			url: $productForm.attr('action'),
			data: $productForm.serialize(),
			dataType: 'json',
			success: function(response) {
				if(response.alert === true) {
					$('#profile-nav .shopping-cart a').after('<div id="cart-message" class="alert" style="display: none;">'+response.alertMessage+'</div>');
				} else {
					$('#profile-nav .shopping-cart a').after('<div id="cart-message" style="display: none;">'+response.alertMessage+'</div>');
				}
				$('html, body').animate({
					scrollTop: $('#profile-nav').offset().top - 10
				});
				$('#profile-nav .shopping-cart #cart-message').fadeIn();
				if(response.status === 'success') {
					$productForm.find('.spinner-input').val(0);
				}
				var cartMessageTimeout = setTimeout(function() {
					$('#profile-nav .shopping-cart #cart-message').fadeOut(400, function() {
						$(this).remove();
					});
				}, 6000);
			}
        });
	});*/

	// Sort table header click
	$('#product-overview-form th.sortable').click(function(e) {
		e.preventDefault();
		createLoader();
		var sortDirection = $(this).hasClass('sort-asc') ? 'asc' : 'desc';
		$.ajax({
			type: 'POST',
			url: $('#product-overview-filters').attr('action'),
			data: 'sort-id='+this.id+'&'+'current-sort-direction='+sortDirection+'&'+$('#product-overview-filters').serialize(),
			dataType: 'html',
			success: function(response) {
				createProductOverview(response);
			}
		});

		//$('#filter-search-term').autocomplete('close');
	});

	$('#product-overview-table .pagination a').click(function(e) {
		var $self = $(this);
		e.preventDefault();
        var $productForm = $('#product-overview-form');
        setTimeout(function() {
            $.ajax({
                type: 'POST',
				url: $self.attr('href'),
				data: $self.serialize(),
				dataType: 'html',
				success: function(response) {
                    createProductOverview(response);
				}
            }, 10);
        });
    });
	if($('#product-overview-form').length) {
		$('#product-overview-form .order input[type=radio]').css({
			position: 'absolute',
			left: '-9999px'
		});
	}
};

