(function($){
    $.fn.extend({
        puffshow: function(options) {

            var defaults = {
                width: 670,
                height: 350,
            	previousBtnLabel: "FÖREGÅENDE",
				nextBtnLabel: "NÄSTA",
				autoSlide: true,
				delay: 5200,
				isHomepage: false,
				homepageLabel: ""
			};

            var options = $.extend(defaults, options);

            return this.each(function() {
				
				var _slideshow_container =  $(this).parents('.global_slideshow');
                var _container = $(this);
                var _width = options.width;
                var _height = options.height;
				var _numOfSlides = $(_container).find('div.puff').length;

				var _pagContainer, _pagBtnContainer, _prevBtn, _nextBtn, _timer;
				var _pagIndex = _slideIndex = _posLeft = 0;
				var _delay = options.delay;
				var _autoSlide = options.autoSlide;
				var _isRunning = false;
				var _isHomepage = options.isHomepage;
				var _imgs = [];
				
				$(_container).css({position:"relative",left:0});
				
				
				//set font size tips
				$(_container).find('div.tips_container div.info_container').each(function(){
					var h2 = $(this).find('h2');
					var _text = h2.text();
					var l = _text.length;
					
					var size  = 36;
					
					if(l > 120 && l <= 160){
						size = 32;
					}else if(l > 160 && l <= 200){
						size = 28;
					}else if(l > 200 && l <= 240){
						size = 25;
					}else if(l > 240 && l <= 285){
						size = 22;
					}else if(l > 285){
						size = 18;
					}
					
					h2.css('font-size' , size + 'px');
					
					var h = parseInt(h2.height());
					
					var y = Math.floor((300 *.5) - (h *.5));
					$(this).css('top' , y + 'px');
					
				});
				
				
				//set href and add_to_list id to product
				$("div.single_produkt").each(function(){
					var me = $(this);
					var add_to_list_id = me.find('a.the_image img').attr('alt');
					var href = me.find('a.the_image').attr('href');
					me.find('.price_box a.cta').attr('href' , href);
					me.find('.price_box a.add_to_list').attr('id' , add_to_list_id);	
				});
				
				//set href and add_to_list id to comp product
				$("div.comp_produkt").each(function(){
					var me = $(this);
					var add_to_list_id = me.find('a.the_comp_image img').attr('alt');
					me.find('a.add_to_list').attr('id', add_to_list_id);
				});
				
				//set desc length produkt mall2
				$("div.puff.produkt .desc").each(function(){
					$(this).text(stripLength($(this).text(), 150));
				});
				
				function stripLength(str, maxLength, cap){
					var _str = str;
					if(cap){
						_str = _str.capitalize();
					}
					return (_str.length > maxLength) ? _str.slice(0,maxLength - 3) + "..." : _str;
				};
				
				var createPagination = function(){
					var pag_id = '' + Math.floor(Math.random()*100);
					_pagContainer = $('<div class="slide_pag_container"></div>').attr('id' , 'pag_id_' + pag_id);
					_pagBtnContainer = $('<div class="btn_container"></div>').attr('id' , 'pag_btns_' + pag_id);
					var alphaBg = $('<div class="alpha_bg"></div>').css('width', _width);
					
					$(_container).parent().append(_pagContainer);
					$(_pagContainer).append(alphaBg);
					$(_pagContainer).append(_pagBtnContainer);
					$(_pagContainer).css('top', _height);
					
					var xx = (_width *.5) - ((_numOfSlides *.5) * 16) - ((_numOfSlides - 1) *3);
					$(_pagBtnContainer).css('left', xx);
				};
				
				createPagination();
				
				var pushPagButton = function(){
					var pagItem = $('<a class="pag_btn"></a>').attr('id' , 'pag_' + _pagIndex);
					$(_pagBtnContainer).append(pagItem);
					if(_pagIndex == 0){
						$(pagItem).addClass('active');
					}
					_pagIndex++;
				}
				/*duplicate fist and last for cycle*/
				var pushDuplicate = function(obj){
					var cloned = $(obj).clone().appendTo(_container);
					if(eachCounter == 1){
						$(cloned).css({position:"absolute",left:(_numOfSlides * _width)});
					}else{
						$(cloned).css({position:"absolute",left:(-_width)});
					}
				}
				
				var eachCounter = 0;
				
				$(_container).children().each(function(){
					$(this).css({position:"absolute",left:_posLeft});
					_posLeft += _width;
					pushPagButton();
					eachCounter++;
					
					/*duplicate fist and last for cycle*/
					if(eachCounter == 1 || eachCounter == _numOfSlides){
						pushDuplicate($(this));
					}
				});
				
				/*$(_container).find('img').each(function(){
					var img = $(this);
					var src = $(img).attr('src');
					$(img).attr('src', '');
					$(img).load(function () {
			            $(this).fadeIn(350);
						$(_slideshow_container).removeClass('loading');
			        }).error(function () {
			            // notify the user that the image could not be loaded
			        }).attr('src', src);
				});*/
				
				
				if(_numOfSlides < 2)
				{
					return;
				}
				
				
				if(_isHomepage){
					var label = $('<h2 id="slideshow_label"></h2>').html(options.homepageLabel);
					$(_pagContainer).append(label);
				}
				_prevBtn = $('<a class="pag_left_btn"></a>').html(options.previousBtnLabel);
				_nextBtn = $('<a class="pag_right_btn"></a>').html(options.nextBtnLabel);
				$(_pagContainer).append(_nextBtn);
				$(_pagContainer).append(_prevBtn);
				
				/*runtime funcitonality*/
				$(_container).parent().hover(function(){
					stopTimer();
					$(_pagContainer).addClass("is_hover");
					$(_pagContainer).stop(true, false).animate({'top': _height - 50}, 200);
				}, function(){
					stopTimer();
					startTimer();
					$(_pagContainer).removeClass("is_hover");
					$(_pagContainer).stop(true, false).animate({'top': _height}, 250);
				});
				
				$(_prevBtn).click(function(){
					goToPrevious();
				});
				
				$(_nextBtn).click(function(){
					goToNext();
				});
				
				$('.pag_btn').click(function(){
					if(_isRunning == true){
						return false;
					}
					var _clickedID = parseFloat($(this).attr('id').split("_")[1]);
					_slideIndex = _clickedID;
					slideToPagIndex();
				});
				
				var slideToPagIndex = function(){
					_isRunning = true;
					stopTimer();
					var xx = (_slideIndex * _width) * -1;
					$(_container).stop(true, true).animate({'left': xx}, 500, function(){
						$(_container).css('left', ((_slideIndex * _width) * -1));
						if(!$(_pagContainer).hasClass("is_hover")){
							stopTimer();
							startTimer();
						}
						_isRunning = false;
					});
					
					if(_slideIndex < 0){
						_slideIndex = _numOfSlides - 1;
					}
					if(_slideIndex > _numOfSlides - 1){
						_slideIndex = 0;
					}
					updatePagBtns();
				};
				
				var updatePagBtns = function(){
					$('.pag_btn').each(function(){
						if(parseFloat($(this).attr('id').split("_")[1]) == _slideIndex){
							$(this).addClass('active');
						}else if($(this).hasClass('active')){
							$(this).removeClass('active');
						}
					});
				};
				var goToNext = function(){
					if(_isRunning == true){
						return false;
					}
					_slideIndex++;
					if(_slideIndex > _numOfSlides){
						_slideIndex = 0;
					}
					slideToPagIndex();
				}
				var goToPrevious = function(){
					if(_isRunning == true){
						return false;
					}
					_slideIndex--;
					if(_slideIndex < -1){
						_slideIndex = _numOfSlides - 1;
					}
					slideToPagIndex();
				}
				var startTimer = function(){
					if(_autoSlide == true){
						_timer = setInterval(onTimerHandler, _delay);
					}
				}
				var onTimerHandler = function(){
					goToNext();
				}
				var stopTimer = function(){
					clearInterval(_timer);
				}
				
				startTimer();
            });
        }
    });
})(jQuery);

