/*
 * jQuery plugin for overview + detail gallery
 *
 * @author Filip Williamsson
 */

(function($) {
    $.fn.overviewGallery = function(options) {

        var
        defaults = {
            duration: 300,
            detail_name: "#gallery_detail",
            swipe_window: "#swipe_window",
            buttonLeft: "#button_left",
            buttonRight: "#button_right"
        },
        settings = $.extend({}, defaults, options),
        $isIOS = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))),
        $isWebKit = (navigator.userAgent.match(/WebKit/i)),
        $isIE = (navigator.userAgent.match(/IEMobile\/7/i));
        object = document.getElementById("gallery_detail");
        hasCSS3 = ('backgroundSize' in object.style) ? hasCSS3 = true : hasCSS3 = false;

        if (!this) return false;
        
        this.each(function() {
            var $gallery = $(this);
            var $items = $gallery.find('.item');
            var $detail_items;
            var windowWidth = 0;
            var $swiper = $(settings.swipe_window+" ul");
            var currItem = 0;
            var touchEvents = new Array();
            
            /* Clone all items, append to detail view */
            if(hasCSS3) {
            	// Webkit means CSS3 is supported
				$items.each(function() {
            		url = $(this).children('a').children('img').attr('src');
            		$swiper.append('<li class="item"><div class="image_placeholder" style="background:url('+url+') center top no-repeat;"></div></li>');
            	});
            }
            else {
            	// CSS3 probably isn't supported by the browser
	            $detail_items = $items.clone().appendTo($swiper);
            }
            
            /* On resize and start, set width on detail window */
            setupSwipeWindow();
            $(window).resize(function() {
                setupSwipeWindow();
            });

            //this.addEventListener('orientationchange', setupSwipeWindow, false);
            if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
                $(settings.swipe_window)[0].addEventListener('touchstart', touch, false);
                $(settings.swipe_window)[0].addEventListener('touchmove', touch, false);
                $(settings.swipe_window)[0].addEventListener('touchend', touchEnd, false);
                $(settings.swipe_window)[0].addEventListener('touchcancel', touchEnd, false);
            }
            
            
            $(settings.detail_name).bind("touchstart, touchmove", function(e) {
                e.stopPropagation();
                e.preventDefault();
            });
            
            $(settings.detail_name+" ul").bind("click", function(e) {
                swipeLeft();
                e.stopPropagation();
                e.preventDefault();
                return false;
            });
            
            $(settings.buttonRight).bind("click", function(e) {
                swipeLeft();
                e.stopPropagation();
                e.preventDefault();
                return false;
            });

            $(settings.buttonLeft).bind("click", function(e) {
                swipeRight();
                e.stopPropagation();
                e.preventDefault();
                return false;
            });
            
            $(settings.detail_name).bind("click", function(e) {
                closeDetail();
                e.stopPropagation();
                e.preventDefault();
                return false;
            });
            
            /* For each item in gallery */
            $items.each(function(index) {
                
                /* CLICK event handler */
                $(this).click(function(e) {
                    var $obj = $(this);
                    open(index);
                    e.preventDefault();
                    e.stopPropagation();
                });
            });
            
            function setupSwipeWindow() {
                windowWidth = $(window).width();
                windowHeight = (height = window.innerHeight ? window.innerHeight : $(window).height());
                optimalHeight = windowHeight-107;
                
                $swiper.css({   'width' : ($items.length*windowWidth)+'px',
                    'overflow' : 'hidden',
                    'margin': '0'
                });
                
                /* Open Detail */
                
                $(settings.detail_name).css({
                    'width' : ($(window).width())+'px',
                    'height' : windowHeight+'px',
                    'top' : ($(window).scrollTop())+'px',
                    'left' : ($(window).scrollLeft())+'px'
                });
                
                $(settings.detail_name).css({"width":"100%"});
                $swiper.children().each(function() {
                    $(this).css({'width' : (windowWidth)+'px'}); //MARGIN: windowWidth-(2*10)
                    if(hasCSS3) {
                    	$(this).css({'height' : (optimalHeight)+'px'});
                    	$(this).children().css({'height' : (optimalHeight)+'px'});
                    }
                });
                
                slide(currItem);
                checkButtons();
            }
            
            /*
             * Slide
             *
             * 
             */
            function slide(index) {
                var xValue = (-1)*index*windowWidth;
                if ($isIOS) {
                    $swiper.css({'-webkit-transform' : 'translate3d('+xValue+ 'px, 0,0)'});
                } else {
                    $swiper.css({'left' : xValue+'px'});
                }
            }
            
            function open(index) { 
                setupSwipeWindow();
                currItem = index;
                
                /* Activate thumbnail */
                var obj = $($items[currItem]).addClass("active");
                setTimeout(function(){obj.removeClass("active");}, 1000);
                
                if(hasCSS3) {
	                $("#gallery_detail #buttons").addClass("css3");
    	            $("#gallery_detail #text").addClass("css3");
				}

                $(settings.detail_name).show();
                setTimeout(function(){$(settings.detail_name).addClass("active");}, 10);
                
                slide(currItem);
                checkButtons();
                
                /* Prevent scroll TODO: add scroll events */
                //document.ontouchstart = function(e){ console.log("touch start");e.stopPropagation();e.preventDefault(); }
                //document.ontouchmove = function(e){ e.stopPropagation();e.preventDefault(); }
            };
            
            function touch(e) {
                pushTouchEvent(e);
                var p1 = touchEvents[0];
                var pn = touchEvents[touchEvents.length-1];
                
                $swiper.css({'-webkit-transition' : 'none'});
                if(p1.pos.x >= pn.pos.x) {
                    $swiper.css({'-webkit-transform' : 'translate3d('+(-1)*((currItem*windowWidth)+(p1.pos.x - pn.pos.x)) + 'px, 0,0)'});
                } else {
                    $swiper.css({'-webkit-transform' : 'translate3d('+(-1*(currItem*windowWidth)+(pn.pos.x - p1.pos.x)) + 'px,0,0)'});
                }

                if(Math.abs(p1.pos.x-pn.pos.x)>Math.abs(p1.pos.y-pn.pos.y)) {
                    e.preventDefault();
                }
            }

            // Tycker ner touch eventet i arrayen fÃƒÂ¶r att man sedan ska kunna berÃƒÂ¤kna swipe
            function pushTouchEvent(e) {
                var t = e.touches[0];
                touchEvents.push({
                    id: t.identifier,
                    pos: {
                        x: t.clientX,
                        y: t.clientY
                    },
                    time: (new Date).getTime()
                });
            }

            // Kolla swipe och tÃƒÂ¶mmer arrayen nÃƒÂ¤r swipen ÃƒÂ¤r slut
            function touchEnd(e) {
                 
                if(!swipeCheckDirection()) {
                    // Animerar tillbaka bilden om ingen riktning ÃƒÂ¤r funnen
                    setTransition();
                    slide(currItem);
                }
                touchEvents = new Array();
            }
            // Analyserar resultatet av swipeCheck fÃƒÂ¶r vilken riktning
            function swipeCheckDirection() {
                var sd = swipeCheck();
                if(sd.swipe && sd.dXVal > 0 && currItem < $items.length-1) {
                    swipeLeft();
                    return true;
                } else if(sd.swipe && sd.dXVal < 0 && currItem > 0) {
                    swipeRight();
                    return true;
                } else {
                    return false;
                }
            }

            function swipeCheck() {
                var dX = touchEvents[0].pos.x - touchEvents[touchEvents.length-1].pos.x;
                var dY = touchEvents[0].pos.y - touchEvents[touchEvents.length-1].pos.y;
                var t = touchEvents[touchEvents.length-1].time - touchEvents[0].time;
                
                if((Math.abs(dX) > (($(settings.swipe_window).width()) * 0.45)) || (Math.abs(dX) > (($(settings.swipe_window).width()) * 0.45*(t/300)))) {
                    return {
                        swipe: true,
                        dXVal: dX
                    }
                }
                return {
                    swipe: false,
                    dxVal: 0
                };
            }
            
            function swipeLeft() {
                if (currItem < $items.length-1) {
                    currItem++;
                    setTransition();
                    slide(currItem);
                }
                checkButtons();
                return;
            }

            function swipeRight() {
                if (currItem > 0) {
                    currItem--;
                    setTransition();
                    slide(currItem);
                }
                checkButtons();
                return;
            }
            
            function setTransition() {
                $swiper.css({   '-webkit-transition' : 'all '+settings.duration+'ms ease-in-out',
                    '-moz-transition' : 'all '+settings.duration+'ms ease-in-out',
                    '-o-transition' : 'all '+settings.duration+'ms ease-in-out',
                    'transition' : 'all '+settings.duration+'ms ease-in-out'});
            }
            
            function closeDetail() {
                $(settings.detail_name).removeClass("active");
                setTimeout(function(){$(settings.detail_name).hide();}, 500);
                
                $($items[currItem]).addClass("deactive");
                setTimeout(function(){$($items[currItem]).removeClass("deactive");}, 500);
            };
            
            
            function checkButtons() {
                var optimal_height = (height = window.innerHeight ? window.innerHeight : $(window).height())-107;
                
                setTimeout(function() {
                    if (optimal_height > $("#swipe_window ul").height()) {
                        optimal_height = $("#swipe_window ul").height();
                    }
                    $(settings.swipe_window).css({"height": optimal_height+"px"});
                }, 500);
                
                $("#text_current").text(currItem+1);
                
                if (currItem == 0) {
                    $(settings.buttonLeft).addClass('disabled');
                } else {
                    $(settings.buttonLeft).removeClass('disabled');
                }
                if (currItem == $items.length-1) {
                    $(settings.buttonRight).addClass('disabled');
                } else {
                    $(settings.buttonRight).removeClass('disabled');
                }
            }
        });
        return this;
    };
    
})(jQuery);
