(function($) {
	$.fn.lightbox = function(id, width, title, closeButton) {
		// Overlay contains the translucent background, inner is a wrapper that handles positioning.
		var overlay = $(document.createElement('div')).attr('id', 'overlay_' + id).addClass('overlay');
		var inner = $(document.createElement('div')).addClass('overlayInner').css('width', width).appendTo(overlay);

		if (title) {
			$(document.createElement('span')).addClass('overlayTitle').append(title).appendTo(inner);
		}
		
		if (closeButton) {
			$(document.createElement('img')).attr('src', '/images/gallery_close.png').addClass('overlayClose').appendTo(inner).bind('click', function() { $('.overlay').hide(); });
		}
		
		$(document.createElement('div')).addClass('clear').appendTo(inner);
		
		// Loop through the elements that lightbox where called on.
		this.each(function() {
			$(this).appendTo(inner);
			$(this).bind('click', function() { // Required to cancel out the bubbling click event on overlay
				return false;
			});
		});
		
		$(inner).bind('click', function() { // Required to cancel out the bubbling click event on overlay
			return false;
		});
		
		$(overlay).bind('click', function() {
			$('.overlay').hide();
		});
		
		return overlay; // Return the element to maintain some sort of chainability.
	};
	
})(jQuery);

function lightboxImage(id, linkTarget, imagePath, width, title, closeButton, animation) {
	if (window.jQuery) { // Will only equate to true if jQuery has been included.
		
		if (animation == null || !animation.length) {
			animation = 'swing';
		}
		
		$(linkTarget).click(function() {
			if ($('#overlay_' + id).length) { // Overlay already exists, no need to create images again, just show it.
				$('#overlay_' + id).show();
			}
			else { // Overlay doesn't exist, create a new one.
				$(document.createElement('div'))  // Create wrapper, append img with preloader, lightbox it, append it to body, show.
					.addClass('overlayImageWrap')
					.append(
						$(document.createElement('img'))
						.attr({ 
							src: '/images/loader.gif', 
							id: 'overlay_' + id + '_Image' 
						}))
					.lightbox(id, width, title, closeButton)
					.appendTo('body')
					.show();
	
				$(document.createElement('img')).attr('src', imagePath).load(function() { // This function triggers once the image is done loading, then switches the preloader for it.
					$(this).hide().insertAfter($('#overlay_' + id + '_Image'));
					$('#overlay_' + id + '_Image').hide().remove();
					$(this).attr('id', 'overlay_' + id + '_Image').show();
					$('#overlay_' + id).find('.overlayInner').css('height', '100px').animate({ height: $(this).height() + 18, width: $(this).width() }, 500, animation);
				});	
			}
		});		
	}
	else {
		// console.log("Cannot use lightboxImage Loader. jQuery has not been included.");
	}
}

function lightboxGallery(id, linkTarget, dataSource, startIndex, closeButton, animation) {
	var preloader = $(document.createElement('img')).addClass('gallery_image').attr({ src: '/images/gallery_loader.gif', className: 'gallery_loader' });
	var overlay = $(preloader).lightbox(id, '200px', '', true).hide().appendTo('body');

	if (typeof(dataSource) == 'string') {
	  // URL to JSON data
	  var load = function() {
	  jQuery.getJSON(dataSource, function(data, status) {
      $(overlay).data('imageData', data);
      if ($(overlay).css('display') != 'none') {
        lightboxGalleryOpen($(overlay).data('open_to'), overlay);
      }
    });
	  };
	
    //setTimeout(load, 5000);
    load();
	} else {
	  // JS array of data
  	$(overlay).data('imageData', dataSource);
 	}
	
	if (animation == null || !animation.length) {
		animation = 'swing';
	}
	
	$(linkTarget).data('overlay', $(overlay)[0]);
	$(overlay).data('animation', animation);
	
	$(linkTarget).bind('click.gallery', lightboxGalleryOpen);
}

/* KNOWN BUGS:
  - Scrollbar width detection doesn't work in Webkit-based browsers
	- Wobbles a bit when scaling to an almost the same size image
*/

function resizeLightbox(adjustTo) {
  if (!$(document).data('scrollbarWidth')) {
    $(document).data('scrollbarWidth', scrollbarWidth());
  }
  
  var overlay = $(adjustTo).parents('.overlay');
	var width = $(adjustTo).find('.gallery_image').width();
	if (width < 300)
	{
		width = 300;
	}
	$(overlay).find('.overlayImageWrap').width(width);

	var height = $(adjustTo).height();
	var maxHeight = $(overlay).height() - 100;
	if (height > maxHeight)
	{
		height = maxHeight;
		width += $(document).data('scrollbarWidth');
  	$(overlay).find('.overlayImageWrap').width(width);
    $(overlay).find('.overlayImageWrap').css({ overflow: 'auto', height: height });
	}
	else {
		height = $(adjustTo).height();
    $(overlay).find('.overlayImageWrap').css({ overflow: 'hidden', height: height });
	}
	var controlHeight = $(overlay).find('.controlBox').height();
	$(overlay).find('.overlayInner').stop().animate({ height: height + controlHeight, width: width }, 500, $(overlay).data('animation'));
}

function lightboxGalleryOpen (item, overlay) {
  if (typeof(overlay) == 'undefined') {
    var overlay = $(this).data('overlay');
  }
  
  if (typeof(overlay) == 'string') {
    $(overlay).data('open_to', item);
  }
  
  if ($(overlay).data('initalized')) { // gallery already initialized, make sure it starts at the right image and show it.
    if (typeof(item) == 'string') {
      var goingTo = $(overlay).find('img[src='+item+']').parent();
    } else {
      var goingTo = $(this).data('gallery_slide');
    }

		// Need to find the one we're looking for, then reshuffle the whole thing!
		// Worst case scenario: We want to show the last one in the system, and need to reshuffle all other elements, how slow would that be compared to using indexes?
		Array.prototype.reverse.call($(goingTo).prevAll()).appendTo($(overlay).find('.overlayImageWrap')); // Get all the siblings before this one, and move them to the end.
		$(overlay).find('.active').removeClass('active').addClass('inactive'); // Set the previous active slide to inactive
		$(goingTo).removeClass('inactive').addClass('active'); // Give our new slide the active class.
		$(overlay).find('.overlayInner').css({width: '200px', height: '200px'});
		$(overlay).show();
		
		var active = $(overlay).find('.active');
    updateCounter(active);
    resizeLightbox(active);
	}	else if (typeof ($(overlay).data('imageData')) != 'undefined') { // gallery not initialized
		var wrapper = $(document.createElement('div')).addClass('overlayImageWrap');
		
		var overlayIndex = ($(overlay).attr('id').split('_'))[1];
		
		var next = function() {
		  var overlay = $(this).parents('.overlay');
			var active = $(overlay).find('.active');
			$(active).appendTo($(overlay).find('.overlayImageWrap'));
			$(active).removeClass('active').addClass('inactive');
			newActive = $(overlay).find('.inactive:first').removeClass('inactive').addClass('active');
			$(overlay).find('counter').text(newActive.data('galleryIndex'));
			
			updateCounter(newActive);
      resizeLightbox(newActive);
		};

		var imageLoad = function() {
		  var replace = $(this).data('replace');
			replace.replaceWith(this);
			$(this).attr('id', replace.attr('id'));
			$(this).data('replace', null);

			var active = $(this).parents('.overlay .active');
			if (active.length) {
        resizeLightbox(active);
			}
		};
		
		var imageArray = $(overlay).data('imageData');
		for (var i = 0; i < imageArray.length; i++) {
			var cssClass = "";
			if (typeof(item) == 'string') {
        (imageArray[i].ImageUrl == item) ? cssClass = "active" : cssClass = "inactive";
			} else {
        (this.id == imageArray[i].ThumbnailID) ? cssClass = "active" : cssClass = "inactive";
			}
			
      var container = $(document.createElement('div')).addClass(cssClass).attr('id', 'gallery_' + overlayIndex + '_' + i);
      if (imageArray[i].Title) {
			  var title = $(document.createElement('div')).addClass('gallery_title').attr('id', 'gallery_' + overlayIndex + '_' + i + '_title').append(imageArray[i].Title);
      } else {
        var title = '';
      }
			var extra = $(document.createElement('div')).addClass('gallery_text').attr('id', 'gallery_' + overlayIndex + '_' + i + '_extra').append(imageArray[i].Extra);
			
			$(jq('#' + imageArray[i].ThumbnailID)).data('gallery_slide', $(container)[0]);
			
			$(container).append(title, extra);
			$(container).data('galleryIndex', i+1);
			
      var image = $(document.createElement('img')).addClass('gallery_image').attr('src', imageArray[i].ImageUrl).click(next);
			if (image.attr('complete')) {
			  container.append(image);
			  resizeLightbox(container);
			} else {
        var preloader = $(document.createElement('img')).addClass('gallery_image').attr({ src: '/images/gallery_loader.gif', id: 'gallery_' + overlayIndex + '_' + i + '_image' });			  image.data('replace', preloader)
			  image.load(imageLoad);
			  container.append(preloader);
			}
			
			$(wrapper).append(container);
		}
		
		$(overlay).find('.gallery_loader').replaceWith(wrapper);
		var active = $(overlay).find('.active');

		// Generate "control box"
		$(overlay).find('.overlayClose').after('<div class="controlBox"><img class="prevArrow" src="/images/gallery_back.png" alt="«" /><span> <span class="counter">' + active.data('galleryIndex') + '</span> / ' + imageArray.length + ' </span><img class="nextArrow" src="/images/gallery_fwd.png" alt="»" /></div>')
		var nextArrow = $('.nextArrow');
		var prevArrow = $('.prevArrow');
		
		$(nextArrow).click(next);
		
		$(prevArrow).click(function() {
		  var overlay = $(this).parents('.overlay');
			var active = $(overlay).find('.active');
			$(active).removeClass('active').addClass('inactive');
			active = $(overlay).find('.inactive:last').removeClass('inactive').addClass('active').prependTo($(overlay).find('.overlayImageWrap'));

			updateCounter(active);
      resizeLightbox(active);
		});
		
    $(overlay).data('initalized', 1);
		Array.prototype.reverse.call($(active).prevAll()).appendTo($(overlay).find('.overlayImageWrap')); // reshuffle elements
		$(overlay).show();

		if (active.length) {
      resizeLightbox(active);
		}
	} else { // gallery data not loaded
		$(overlay).show();
	}
	
	return false;
}

function updateCounter(active) {
  var overlay = $(active).parents('.overlay');
	$(overlay).find('.counter').text(active.data('galleryIndex'));
}

function scrollbarWidth() {
  var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
  // Append our div, do our calculation and then remove it
  $('body').append(div);
  var w1 = $('div', div).innerWidth();
  div.css('overflow-y', 'scroll');
  var w2 = $('div', div).innerWidth();
  $(div).remove();
  if (w1 == w2) {
    return 16;
  }
  return (w1 - w2);
}


function lightboxBlogShare(id, linkTarget, width, productUrl, productImageUrl, altText, title, message, closeButton) {
	if (window.jQuery) {// Will only equate to true if jQuery has been included.
		var link = "";
		if (productImageUrl != null && productImageUrl.length) {
			if (altText.length) {
				link = "<img src=\"" + productImageUrl + "\" alt=\"" + altText + "\" border=\"0\" />";
			}
			else {
				link = "<img src=\"" + productImageUrl + "\" border=\"0\" />";
			}
		}
		else {
			link = altText;
		}
		var output = $(document.createElement('div')).addClass('blog_share_inner').append(message + "<br><form><textarea><a href=\"" + productUrl + "\">" + link + "</a></textarea></form>");
		$(linkTarget).click(function() {	
			$(output).lightbox(id, width, title, closeButton).appendTo('body').show();
		});
	}
	else {
		console.log("Cannot use lightboxBlogShare Loader. jQuery has not been included.");
	}
}

function validateEmail(email) {
	var email_regex = new RegExp(/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i);
	return email_regex.test(email);
}

function lightboxEmailShare(id, linkTarget, width, productUrl, title, message, formAction, task, closeButton, languageId, productId, browseNodeId) {
	if (window.jQuery) { // Will only equate to true if jQuery has been included.
		$(linkTarget).click(function() {
			if ($('#overlay_' + id).length) { // Overlay already exists, no need to create images again, just show it.
				$('#overlay_' + id).show();
			}
			else { // Overlay doesn't exist, create a new one.
				$(document.createElement('div'))  // Create wrapper, append img with preloader, lightbox it, append it to body, show.
					.addClass('overlayEmailWrap')
					.append("<br />\
						<form id=\"email_share_form\" method=\"post\" action=\"" + formAction + "\">\
						<label>Din e-mail: </label><br />\
						<input id=\"email_share_form_sender\" name=\"sender\" type=\"text\" /><div id=\"email_share_form_sender_error\"></div><br />\
						<label>Mottagarens e-mail: </label><br />\
						<input id=\"email_share_form_receiver\" name=\"receiver\" type=\"text\" /><div id=\"email_share_form_receiver_error\"></div><br />\
						<label>Ditt meddelande: </label>\
						<br /><textarea name=\"message\">" + message + "</textarea></form>")						
					.lightbox(id, width, title, closeButton)
					.appendTo('body')
					.show();
				$('#email_share_form').append($(document.createElement('input')).attr({ type: 'button', value: 'Skicka' }).click(function() {
							var valid = true;
							if (validateEmail($('#email_share_form_sender').attr('value'))) {
								$('#email_share_form_sender_error').html("<img src=\"/images/valid.gif\">");
							}
							else
							{
								$('#email_share_form_sender_error').html("<img src=\"/images/invalid.gif\"> Ogiltig e-postadress.");
								valid = false;
							}
							
							if (validateEmail($('#email_share_form_receiver').attr('value'))) {
								$('#email_share_form_receiver_error').html("<img src=\"/images/valid.gif\">");
							}
							else
							{
								$('#email_share_form_receiver_error').html("<img src=\"/images/invalid.gif\"> Ogiltig e-postadress.");
								valid = false;
							}
							
							if (valid) {
								var loader = $(document.createElement('img')).attr({ src: '/images/loader.gif', id: 'email_share_loader' });
								$.post(formAction, $("#email_share_form").serialize(), function(data, status) {
									if (status == 'success') {
										if (data == 'ok') {
											$('#email_share_loader').remove();
											$('#email_share_form').parent().append('<div id="email_share_success" style="padding: 20px;">Ditt meddelande har skickats.</div>');
											$('#email_share_form').remove();
										}
										else if (data.substring(0,14) == 'invalid_email_') {
											$('#email_share_loader').remove();
											$('#email_share_form').show().parent().css('text-align', 'left');
											if (data == 'invalid_email_1')	{
												$('#email_share_form_sender_error').html("<img src=\"/images/invalid.gif\"> Ogiltig e-postadress.");
											}
											else if (data == 'invalid_email_2') {
												$('#email_share_form_receiver_error').html("<img src=\"/images/invalid.gif\"> Ogiltig e-postadress.");
											}
											else if (data == 'invalid_email_12') {
												$('#email_share_form_sender_error').html("<img src=\"/images/invalid.gif\"> Ogiltig e-postadress.");
												$('#email_share_form_receiver_error').html("<img src=\"/images/invalid.gif\"> Ogiltig e-postadress.");
											}
										}
									}
									else
									{
										$('#email_share_loader').remove();
										$('#email_share_form').parent().append('<div id="email_share_success" style="padding: 20px;">Internt serverfel, försök igen senare.</div>');
										$('#email_share_form').remove();
									}
								});
								$('#email_share_form').hide().parent().css('text-align', 'center').append(loader);
								$('#email_share_loader').show();
							}
						}));
				$('#email_share_form').append('<input type="hidden" name="language_id" value="' + languageId + '" />\
					<input type="hidden" name="module" value="Shop" />\
					<input type="hidden" name="subModule" value="ProductTree" />\
					<input type="hidden" name="task" value="' + task + '" />\
					<input type="hidden" name="id" value="' + productId + '" />\
					<input type="hidden" name="browseNode" value="' + browseNodeId + '" />');
			}
		});
	}
	else {
		console.log("Cannot use lightboxEmailShare Loader. jQuery has not been included.");
	}
}


function lightboxInfoEmail(id, linkTarget, width, productUrl, title, message, formAction, task, closeButton, languageId, productId, browseNodeId) {
	if (window.jQuery) { // Will only equate to true if jQuery has been included.
		$(linkTarget).click(function() {
			if ($('#overlay_' + id).length) { // Overlay already exists, no need to create images again, just show it.
				$('#overlay_' + id).show();
			}
			else { // Overlay doesn't exist, create a new one.
				$(document.createElement('div'))  // Create wrapper, append img with preloader, lightbox it, append it to body, show.
					.addClass('overlayEmailWrap')
					.append("<br />\
						<form id=\"email_info_form\" method=\"post\" action=\"" + formAction + "\">\
						<label>Din e-mail: </label><br />\
						<input id=\"email_info_form_sender\" name=\"sender\" type=\"text\" /><div id=\"email_info_form_sender_error\"></div><br />\
						<label>Ditt meddelande: </label>\
						<br /><textarea name=\"message\">" + message + "</textarea></form>")						
					.lightbox(id, width, title, closeButton)
					.appendTo('body')
					.show();
				$('#email_info_form').append($(document.createElement('input')).attr({ type: 'button', value: 'Skicka' }).click(function() {
							var valid = true;
							if (validateEmail($('#email_info_form_sender').attr('value'))) {
								$('#email_info_form_sender_error').html("<img src=\"/images/valid.gif\">");
							}
							else
							{
								$('#email_info_form_sender_error').html("<img src=\"/images/invalid.gif\"> Ogiltig e-postadress.");
								valid = false;
							}
							
							if (valid) {
								var loader = $(document.createElement('img')).attr({ src: '/images/loader.gif', id: 'email_info_loader' });
								$.post(formAction, $("#email_info_form").serialize(), function(data, status) {
									if (status == 'success') {
										if (data == 'ok') {
											$('#email_info_loader').remove();
											$('#email_info_form').parent().append('<div id="email_info_success" style="padding: 20px;">Ditt meddelande har skickats.</div>');
											$('#email_info_form').remove();
										}
										else if (data.substring(0,14) == 'invalid_email_') {
											$('#email_info_loader').remove();
											$('#email_info_form').show().parent().css('text-align', 'left');
											if (data == 'invalid_email_1')	{
												$('#email_info_form_sender_error').html("<img src=\"/images/invalid.gif\"> Ogiltig e-postadress.");
											}
										}
									}
									else
									{
										$('#email_info_loader').remove();
										$('#email_info_form').parent().append('<div id="email_info_success" style="padding: 20px;">Internt serverfel, försök igen senare.</div>');
										$('#email_info_form').remove();
									}
								});
								$('#email_info_form').hide().parent().css('text-align', 'center').append(loader);
								$('#email_info_loader').show();
							}
						}));
				$('#email_info_form').append('<input type="hidden" name="language_id" value="' + languageId + '" />\
					<input type="hidden" name="module" value="Shop" />\
					<input type="hidden" name="subModule" value="ProductTree" />\
					<input type="hidden" name="task" value="' + task + '" />\
					<input type="hidden" name="id" value="' + productId + '" />\
					<input type="hidden" name="browseNode" value="' + browseNodeId + '" />');
			}
		});
	}
	else {
		console.log("Cannot use lightboxEmailShare Loader. jQuery has not been included.");
	}
}
