/*
 INCLUDES
 **********************************************/
// specify which javascripts to include on the webpage
js('/files/javascript/jquery.ba-bbq.min.js');
js('/files/javascript/jquery.colorbox-min.js');

// jQuery init script
$(function () {
	activateAjaxShopping();
	bindProductImage();
	//bindGroupImgResize();

	// get GLS data on the delivery page
	activateGLS();

	initializeBBQ();


	// standard lightbox feature for productinfo page - building the container
	updateProductImagesLightbox();

	// standard lightbox feature for productinfo page - activating the overlay
	$('#productImages a').colorbox({
		inline: true,
		opacity: 0.5,
		href: '#productImagesLightbox',
		onOpen: function () {
			$('#productImagesLightbox').find('.imageContainer img[src$="' + escape($(this).attr('href')) + '"]:first, .imageContainer img:first').eq(0).show().siblings('img').hide();
			$('#productImagesLightbox').find('.productImageActions').html($('#productAdditions').children().clone(true));
		},
		onComplete: function () {
			$('#productImagesLightbox').find('.imageContainer').css({
				height: $('#productImagesLightbox').find('.imageContainer').height()
			});

			$('#colorbox').find('.imageContainer').css('height', 'auto');

			setTimeout(function () {
				$.fn.colorbox.load();
			}, 200);

			if ($('#productImagesLightbox').find('.imageContainer img').size() > 1) {
				updateLightboxButtons();

				$('#productImagesLightbox').find('.imageContainer .lightboxNavigation').click(function () {
					$this = $(this);
					$img = $this.siblings('img:visible');

					if ($img.siblings('img').size() > 0) {
						if ($img.next('img').size() > 0 && $this.hasClass('next')) {
							$img.fadeOut('fast', function () {
								$img.next('img').fadeIn('slow');
								updateLightboxButtons();
							});
						}
						else if ($img.prev('img').size() > 0 && $this.hasClass('prev')) {
							$img.fadeOut('fast', function () {
								$img.prev('img').fadeIn('slow');
								updateLightboxButtons();
							});
						}
					}
				});
			}
			else {
				$('#productImagesLightbox').find('.imageContainer .lightboxNavigation').hide();
			}
		}
	});

	// manage delivery type, and displayed fields on Delivery.xsl
	manageDelivery();
});

// manage delivery type, and displayed fields on Delivery.xsl
function manageDelivery(){
	
	$('input[name=paymentid]').each(
		function() {
			if ($(this).val() == 'COD' && $(this).is(':checked'))
			{
				$('#deliverytype2').attr('disabled', 'disabled');
				$('#deliverytype3').attr('disabled', 'disabled');
				
				$('#deliverytype1').trigger('click'); // Clean selections!
			}
			else
			{
				$('#deliverytype2').removeAttr('disabled');
				$('#deliverytype3').removeAttr('disabled');
			}
			
			$(this).click(function() {
				if ($(this).val() == 'COD')
				{
					$('#deliverytype1').attr('checked', 'checked');
					$('#deliverytype2').removeAttr('checked');
					$('#deliverytype3').removeAttr('checked');
					$('#deliverytype2').attr('disabled', 'disabled');
					$('#deliverytype3').attr('disabled', 'disabled');
					
					$('#deliverytype1').trigger('click'); // Clean selections!
				}
				else
				{
					$('#deliverytype2').removeAttr('disabled');
					$('#deliverytype3').removeAttr('disabled');
				}
			});
		}
	);
	
	$('#deliverytype1').click(function() {
		$('#altdelivery_box').hide();
		$('#jsGlsdata').hide();
		$('#deliverytype1info').show();
		var formular = $('.jsGlspostalcode').closest('form').get(0);
		if (formular != null)
		{
			formular.company2.value = '';
			formular.contact2.value = '';
			formular.street2.value = '';
			formular.postalcode2.value = '';
			formular.city2.value = '';
			formular.region2.value = '';
			formular.country2.value = '';
		}
	});
	
	$('#deliverytype2').click(function() {
		$('#deliverytype1info').hide();
		if ($('#b2btest').val() != '1') {
			$('#altdelivery_box').show();
			$('#jsGlsdata').show();
			getGLS();
		}
		else
		{
			$('#altdelivery_box').show();
			var formular = $('.jsGlspostalcode').closest('form').get(0);
			if (formular != null)
			{
				formular.company2.value = '';
				formular.contact2.value = '';
				formular.street2.value = '';
				formular.postalcode2.value = '';
				formular.city2.value = '';
				formular.region2.value = '';
				formular.country2.value = '';
			}
		}
	});

	$('#deliverytype3').click(function() {
		$('#deliverytype1info').hide();
		$('#jsGlsdata').hide();
		$('#altdelivery_box').show();
	});
	var formular = $('.jsGlspostalcode').closest('form').get(0);
	if (formular != null)
	{
		if (formular.postalcode2.value != null)
		{
		}
		else
		{
			if (formular.company2.value != null)
			{
				formular.company2.value = '';
			}
			if (formular.contact2.value != null)
			{
				formular.contact2.value = '';
			}
			if (formular.street2.value != null)
			{
				formular.street2.value = '';
			}
			if (formular.postalcode2.value != null)
			{
				formular.postalcode2.value = '';
			}
			if (formular.city2.value != null)
			{
				formular.city2.value = '';
			}
			if (formular.region2.value != null)
			{
				formular.region2.value = '';
			}
			if (formular.country2.value != null)
			{
				formular.country2.value = '';
			}
		}
	}
	
	if ($('#deliverytype1').is(':checked'))
	{
		$('#altdelivery_box').hide();
		$('#jsGlsdata').hide();
		$('#deliverytype1info').show();
	}
}

// append ajax shopping and updating of previewbasket 
function activateAjaxShopping(){
	// remove products from basket and update basket preview
	$('#basketpreview input').live('click',function(){
		$(this).closest('form').submit(function(){
			$.post("post.aspx",{
				_Function: this._Function.value,
				_ReturnTo: 'dynamic.aspx?data=basket&template=basketpreview&ajax=1',
				productid: this.productid.value,
				quantity: this.quantity.value,
				pkid: this.pkid.value
			}, function(data){
				// find the body element  
				var startCut = data.indexOf('<body');
				var endCut = data.indexOf('</body>') + 7;
				
				// replace the old basketpreview with the body-content of 'data'
				$('#basketpreview').html($(data.substring(startCut,endCut)));
			},'html');
			
			// cancel the normal form submit
			return false;
		});
	});
	
	// add products to basket and update basketpreview
	$('#productinfo form, #productlist table form.addToBasket, #quickorderForm').submit(function(){
		$.post("post.aspx",{
				_Function: this._Function.value,
				_ReturnTo: 'dynamic.aspx?data=basket&template=basketpreview&ajax=1',
				productid: this.productid.value,
				quantity: this.quantity.value,
				_Message: this._Message.value
			}, function(data){
					// find the body element  
					var startCut = data.indexOf('<body');
					var endCut = data.indexOf('</body>') + 7;
					
					// replace the old basketpreview with the body-content of 'data'
					$('#basketpreview').html($(data.substring(startCut,endCut)));
			},'html');
			
		// this is used to show that the form have been sent to the server and the basket have been updated  
		 $('.added',this).show(1,function(a){
			setTimeout(function(){
				$('.added').fadeOut('slow');
			},1000)
		});
		
		if ($(this).is('#quickorderForm')){
			$('#jsproductid').val('');
			$('#jsquantity').val('1').focus().select();
		}
		// cancel the normal form submit
		return false;
	});
}

function bindProductImage(){
	$('.prodImg').bind('mouseenter',function(e){
		var $this_img = $('img', this); // <img/> inde i <a/>-tag'et, med style="display:none;"
		var $this = $(this); // Dette burde være selve Anchor-tag'et (<a class="prodImg" href="..."/>), men billedet bliver vist oppe i venstre hjørne af skærmen. HUSK at fjerne kommentaren fra "jQuery Init"-funktionen, øverst i dokumentet ;-)
		var img = $this_img.attr('src').substring($this_img.attr('src').lastIndexOf('/'));
		var varTop = $this.offset().top;
		if (($this.offset().top + 200) > document.body.clientHeight){
			varTop = $this.offset().top - 190;
		}
		$('<img id="prodImgBig" src="/images/medium' + img + '" alt=""/>').css({
			position: 'absolute',
			top: varTop +'px',
			left: ($this.offset().left + $this.width() + 10) +'px',
			border: '1px solid #aaa'
		}).appendTo('body');
	}).bind('mouseleave',function(){
		$('#prodImgBig').remove();
	});
}

function bindGroupImgResize(){
	$('.groupImg').bind('mouseenter',function(e){
		var $this_img = $('img', this);
		var $this = $(this);
		$this.css({
			width: ($this.width() - 5) + 'px',
			height: ($this.height() - 5) + 'px'
		});
	}).bind('mouseleave',function(){
		var $this = $(this);
		$this.css({
			width: ($this.width() + 5) + 'px',
			height: ($this.height() + 5) + 'px'
		});
	});
}

function activateGLS(){
	
	if ($('.jsGlspostalcode').size() > 0){
		$('.jsGlspostalcode').blur(getGLS);
		$('#postalcode2').blur(getGLS);
		//getGLS(); // AS edit 29-10-2010
	}
	
}

function getGLS(){
	if ($('#deliverytype2').is(':checked'))
	{
		var formular = $('.jsGlspostalcode').closest('form').get(0);
		
		var strStreet = formular.street.value;
		var strPostalcode = formular.postalcode.value;
		
		if (formular.postalcode2) {
			if (formular.postalcode2.value != '') {
				strStreet = formular.street2.value;
				strPostalcode = formular.postalcode2.value;
			}
		}
		if (strPostalcode != ''){
			
			$.get("dynamic.aspx?data=glsdelivery&ajaxmode=1",{
				street: strStreet,
				postalcode: strPostalcode
			}, function(data){
				
				if (data != ''){
					// replace the old GLS data with new
					$('#jsGlsdata').replaceWith(data);
				} else {
					$('#jsGlsdata').empty('');
				}
				
				$('#jsGlsdata :radio:checked').click();
				
			},'html');
		
		}
	}
}


function initializeBBQ(){
	
	// to prevent any empty page reloads, test if $ exists
	if (typeof $ == 'undefined') {
		return false;
	}
	
	// cancel the BBQ integration if the confirmation page is loaded
	
	//if ($('#tConfirmation').size() > 0 || $('.shopflowForm, .shopflowForm').size() > 0) {
	var strUrl = location.href.toLowerCase();
	if ($('#tConfirmation').size() > 0 || strUrl.indexOf('data=basket') >=0 || strUrl.indexOf('data=delivery') >=0 || strUrl.indexOf('data=payment') >=0 || strUrl.indexOf('data=dibs') >=0 || strUrl.indexOf('data=orderstatus') >=0 || strUrl.indexOf('data=confirmation') >=0){
  	return false;
  }
  
	
	// insert the needed classes and default content
	$('#content').addClass('jsBbq');
	$('#main').addClass('jsBbq-content').wrapInner('<div class="jsBbq-default"/>');
	
	// For each .bbq widget, keep a data object containing a mapping of
	// url-to-container for caching purposes.
	$('.jsBbq').each(function(){
		$(this).data('bbq', {
			cache: {
				// If url is '' (no fragment), display this div's content.
				'': $(this).find('.jsBbq-default'),
				'/': $(this).find('.jsBbq-default')
			}
		});
	});
	
	// For all links inside a .jsBbq widget, push the appropriate state onto the
	// history when clicked.
	$('#groupsmenu a[href*="Data=groups"]').live('click', function(e){
		var state = {},  // Get the id of this .jsBbq widget.
		id = $(this).closest('.jsBbq').attr('id'),  // Get the url from the link's href attribute, stripping any leading #.
		url = $(this).attr('href');
		
		// Set the state!
		state[id] = url;
		$.bbq.pushState(state);
		
		// save the request for the latest clicked url, so the callback knows which to show, even if the return order is not the same as the requested order
		$(this).closest('.jsBbq').data('currentLinkUrl',url);

		// And finally, prevent the default link click behavior by returning false.
		e.preventDefault();
		//return false;

	});
	
	// Bind an event to window.onhashchange that, when the history state changes,
	// iterates over all .bbq widgets, getting their appropriate url from the
	// current state. If that .bbq widget's url has changed, display either our
	// cached content or fetch new content to be displayed.
	$(window).bind('hashchange', function(e){
	
		// Iterate over all .bbq widgets.
		$('.jsBbq').each(function(){
			var that = $(this),   // Get the stored data for this .bbq widget.
			data = that.data('bbq'),   // Get the url for this .bbq widget from the hash, based on the
			// appropriate id property. In jQuery 1.4, you should use e.getState()
			// instead of $.bbq.getState().
			url = $.bbq.getState(that.attr('id')) || '';
			
			// If the url hasn't changed, do nothing and skip to the next .bbq widget.
			if (data.url === url) {
				return;
			}
			
			// Store the url for the next time around.
			data.url = url;
			
			// Remove .bbq-current class from any previously "current" link(s).
			that.find('a.selected').removeClass('selected');
			
			// Hide any visible ajax content.
			that.find('.jsBbq-content').children(':visible').hide();
			
			// Add .bbq-current class to "current" nav link(s), only if url isn't empty.
			url && that.find('#areaMenu a[href="' + url + '"]').addClass('selected');
			
			// create a url to the dynamic page, to get a faster and smaller page
			// the url could be built up of a dataformat, key and template
			
			var strLinkUrl = url.replace(/default.aspx\?load=main/i,'dynamic.aspx?ajaxmode=1');
			
			
			if (data.cache[url]) {
				// Since the widget is already in the cache, it doesn't need to be
				// created, so instead of creating it again, let's just show it!
				data.cache[url].show();
				
			}
			else {
				// Show "loading" content while AJAX content loads.
				that.find('.jsBbq-loading').show();
				
				// Create container for this url's content and store a reference to it in
				// the cache.
				
				$.ajax({
					url: strLinkUrl,
					success: function(strData){
						
						// find the body element  
						var startCut = strData.indexOf('<body');
						var endCut = strData.indexOf('</body>') + 7;
						
						// Create container for this url's content and store a reference to it in
						// the cache.
					
						var strStyle = '';
						if( that.data('currentLinkUrl') != url && typeof that.data('currentLinkUrl') != 'undefined') {
							strStyle = ' style="display: none;"';
						}
					
						// if the new page has content, insert it and scroll to it
						data.cache[url] = $('<div class="jsBbq-item"' + strStyle + '/>')				// Append the content container to the parent container.
						.appendTo(that.find('.jsBbq-content'))
						.html($(strData.substring(startCut, endCut)));
						
						// Content loaded, hide "loading" content.
						that.find('.jsBbq-loading').hide();
					}
				});
			}
		});
	});
	
	// Since the event is only triggered when the hash changes, we need to trigger
	// the event now, to handle the hash the page may have loaded with.
	$(window).trigger('hashchange');
}

// standard lightbox feature for productinfo page - building the container
function updateProductImagesLightbox(){
	
	$('#productImagesLightbox .imageContainer').find('img').remove()
		.end().prepend($('#productImages img').clone().removeAttr('id').removeAttr('onmouseover').removeAttr('onmouseout').removeAttr('width')).find('.zoom').remove()
		.end().find('img').each(function(){
	
			var strSrc = decodeURI($(this).attr('src').replace('/small/','/large/').replace('/medium/','/large/'));
			$(this).attr('src',strSrc);
		
		}).hide();
	
} // updateProductImagesLightbox end

// productImagesLightbox buttons update
function updateLightboxButtons(){
	
	var $imageContainer = $('#productImagesLightbox').find('.imageContainer');
	var $prev = $imageContainer.find('.prev'),
			$next = $imageContainer.find('.next'),
			$img = $imageContainer.find('img:visible');
	
	// enable/disable the next-button as needed
	if ($img.nextAll('img').size() < 1){ $next.addClass('disabled'); }
	else { $next.removeClass('disabled'); }
	
	// enable/disable the prev-button as needed
	if ($img.prevAll('img').size() < 1){ $prev.addClass('disabled'); }
	else { $prev.removeClass('disabled'); }

} // updateLightboxButtons end
