/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);

var SM = {};

//helper function - do preload of images
//keep this function outside so that it can be used immediately
SM.preloadImages = function(base, imgArr, callback) {
    var i,
    j,
    img,
    imgObjs = [],
    imgCtr = 0;

    function incrementAndTestComplete() {
        imgCtr++;
        if (imgCtr === j - 1) {
            (callback ||
            function() {})();
        }

    }

    for (i = 0, j = imgArr.length; i < j; i++) {
        imgObjs[i] = new Image();
        imgObjs[i].onload = imgObjs[i].onerror = incrementAndTestComplete;
        imgObjs[i].src = base + imgArr[i];
    }
};



$(function() {
    //check if this is an ipad, iphone,ipod touch
    var iOS = navigator.userAgent.match(/like Mac OS X/i);

    //some constants, used in animation
		var resetLimit = 380;
    var topLimit = 524;
    var slideShowLimit = 950;
    var slideshowWidth = 860;
    var slideshowHeight = 880;
		var slideshowAnimLength = 300;
    var headerLimit = 360;

		var animationLength = 400;

    //slideshow class
    SM.Slideshow = function(options) {
        var _t = this;
        this.el = $(options.el);
        this.imgs = $('.images img', this.el);
        this.imgs.css({
            opacity: 0
        });
        this.length = this.imgs.length;
        this.preload(options.onload ||
        function() {});
        this.loaded = false;
        this.index = 0;
        this.width = options.width || slideshowWidth;
        this.mutex = false;


				this.dotsCnt = $('.dots', this.el);

				
				
				this.imgs.each(function(index, img){
					var dot = $('<div class="dot">&nbsp;</div>');
					if(index==0){
						dot.addClass('active');
						_t.activeDot = dot;
					}
					var i = index;
					dot.click(function(){
						_t.moveTo(i, true);
					});
					$(_t.dotsCnt).append(dot);
				});
				this.dots = $('.dots .dot', this.el);
    };

    SM.Slideshow.prototype = {
        start: function() {
            this.index = 0;

            this.imgs.slice(1).css({left: this.width + 'px', opacity:0});
            this.imgs.first().css({left: 0, opacity:1});
            //this.imgs.css({opacity: 1});
						
						$(this.dots).removeClass('active');
						$(this.dots.get(0)).addClass('active');
						this.activeDot = $(this.dots.get(0));
						
						
						this._tick();

        },
				_tick:function(){
					var _t = this;
					try{clearInterval(this.tick);}catch(e){}
					this.tick = setInterval(function(){
						_t.moveTo( (_t.index+1) % _t.length );
					}, 7000);
				},
				stop:function(){
					clearInterval(this.tick);
				},

				moveTo:function(i, reset){
					var _t = this;
					var proceed = (i!==this.index && this.mutex===false);
					if(proceed){
						if(reset){
							this.stop();
						}

						$(this.activeDot).removeClass('active');
						$(this.dots.get(i)).addClass('active');
						this.activeDot = $(this.dots.get(i));
						
						
						
						this.mutex = true;
						$(this.imgs.get(i)).css({left:i<this.index?(-1*this.width):this.width}).animate({left:0, opacity:1}, slideshowAnimLength, 'linear');
						$(this.imgs.get(this.index)).animate({left:i<this.index?this.width:(-1*this.width), opacity:0}, slideshowAnimLength, 'linear', function(){
							_t.mutex = false;
							_t.index = i;
						});
						
					}
					return proceed;
				},
        preload: function(onload) {
            var i,
            j,
            imgCtr = 0,
            _t = this;

            function begin() {
                _t.start();
                onload();
            }

            if (_t.loaded) {
                begin();
            }

            for (i = 0, j = this.length; i < j; i++) {
                var img = this.imgs.get(i);
                img.onload = img.onerror = function() {
                    imgCtr++;
                    if (imgCtr == _t.length) {
                        _t.loaded = true;
                        begin();
                    }
                };
                img.src = $(img).attr('_src');
            }
        }
    };

    // cache slideshow instances here
    SM.slideshows = {};

		SM.activeSS = null;

    // maintain reference to some important elements
    var eles = {};
    eles.main = $('#main');
    eles.header = $('.titles');
    eles.footer = $('footer');
    eles.slideshowEl = null;
    //current slideshow container

    //call this to start a particular slideshow
    //pass in project name
    SM.slideshow = function(project) {
        var slideshowEl = $('#slideshows .slideshow[project="' + project + '"]').get(0);
        $('html,body').animate({
            scrollTop: resetLimit
        },
        500, 'swing');


				if (slideshowEl !== eles.slideshowEl) {  //ie- if clicked project is not the current slideshow, then...
					$('.loader').css({opacity:1});
					$(eles.slideshowEl).animate({opacity:0},eles.slideshowEl?animationLength*2:0);
					eles.main.animate({top:resetLimit}, eles.slideshowEl?animationLength:0, 'swing', function(){
						
						$(eles.slideshowEl).hide();
						if(SM.activeSS){SM.activeSS.stop();}
						  
						eles.slideshowEl = slideshowEl;
						
						if(!SM.slideshows[project]){
							SM.activeSS = SM.slideshows[project] = new SM.Slideshow({
								el:slideshowEl,
								width:slideshowWidth,
								onload:function(){
									$('.loader').css({opacity:0});
									$(slideshowEl).animate({opacity:1},animationLength*2);
									
									$(slideshowEl).show();
									eles.main.animate({top:topLimit + $(slideshowEl).height()}, animationLength, 'swing');
								}
							});
						}
						else{
							$('.loader').css({opacity:0});
							SM.activeSS = SM.slideshows[project];
							SM.slideshows[project].start();
							$(slideshowEl).show();
							$(slideshowEl).animate({opacity:1},animationLength*2);

							eles.main.animate({top:topLimit + $(slideshowEl).height()}, animationLength, 'swing');
							
						}
					});
				}
    };

    //do a reset of the page
    SM.reset = function() {
        $('html,body').animate({
            scrollTop: 0
        },
        500, 'swing');
        if (eles.slideshowEl) {
            eles.main.animate({
                top: resetLimit
            },
            animationLength, 'swing',
            function() {
                $('.slideshow').hide().css({opacity:0});
								SM.activeSS.stop();
                eles.slideshowEl = null;
								window.location.hash = '';
            });
        }
    };

		var projects = [];

		SM.onhashchange = function(){
			var project = (window.location.hash||'').slice(1);
			if ($.inArray(project, projects)>-1){
				SM.slideshow(project);
			}
			else if(project==''){
					SM.reset();
			}
		};
		

    SM.start = function() {
        $('#portfolio-grid .unit').click(function(evt) {
            //SM.slideshow($(evt.currentTarget).attr('project'));
						window.location.hash = $(evt.currentTarget).attr('project');
        }).each(function(index, el){
					projects.push($(el).attr('project'));
				});

        $('.logo, .close').click(function(){
					SM.reset();
				});

				SM.onhashchange();
    };

		$(window).bind('hashchange',SM.onhashchange);



    SM.start();

		



});
