var Local = {

    onCommentReply: function(id) {
		Comments.openReply(id);
	},

    onCancelReply: function(id) {
		Comments.closeReply();
	}

};

if (!window['wt']) {
    window['wt'] = {};
    var wt = window['wt'];
}

(function() { // This is where jQuery code can safely go without foobarring prototype
	var $ = jQuery;
	
	$(document).ready(function() { // These functions get called on DOM ready
		$('a').click(function() { $(this).blur(); }); // prevents outlines on links for IE
		wt.hero(); // Crossfades hero shots if applicable
		
		setTimeout(center, 0);
        gallerycontroller.init();
        drawer();
        
    $(document, window).scroll(hidefooter);
    
	})
	
	$(window).load(function() { // These functions get called when everything has loaded
		$(window).resize(center);
        $('.date').each(function(){
            $(this).text($(this).text().match(/^\w+\s(.+),.*/)[1])
        })
        
        if($('html#portfolio').size()) {
            $('ul#portfolio-container').animate({
                marginLeft : '-30px'
            },500)
            
        }
	})
	
	wt.formDefaults = function() { // Swaps default text form input values to blank on focus and back to default text on blur
		$('input:text,textarea').each(function() {
			var elem = $(this);
			var defaultText = elem.val();
			elem.focus(function(){
				if(elem.val() == defaultText) {
					elem.val('');
				}
			});
			elem.blur(function(){
				if(elem.val() == '') {
					elem.val(defaultText);
				}
			})
		})
	}

	wt.hero = function() { // Heroshot crossfader; set options below this function

		if(!$('.heroshots').size()) {
			return;
		}
		$('.heroshots').each(function(index) {
            var heroshot = $(this);
            var interval = null;
    		var fade = heroshot.find('input[name=fadevalue]');
    		fade = fade.val() * 1000;
    		heroshot.find('input[name=fadevalue]').remove();

    		var dur = heroshot.find('input[name=showvalue]');
    		dur = dur.val() * 1000;
    		heroshot.find('input[name=showvalue]').remove();
    		
    		heroshot.attr({
                'fade': fade,
                'dur': dur
    		})
    		if(wt.hero.useForeground) {
    			heroshot.append(
    				$(jQuery('<div class="foreground" />'))
    			);
    		}
    		
    		if(wt.hero.useCaptions) {
    			if(heroshot.children('a:first-child').size()) {
    				var firstCaption = heroshot.children('a:first-child').children('img').attr('alt')
    			} else if(heroshot.children('img:first-child').size()) {
    				var firstCaption = heroshot.children('img:first-child').attr('alt')
    			} else {
    				var firstCaption = ''
    			}

    			heroshot.append(
    				$(jQuery('<div class="caption" />'))
    					.append(
    						$(jQuery('<span class="holder" />'))
    							.show()
    							.text(firstCaption)
    					)
    			)
    		}
    		
    		if(heroshot.children('a,img').size() < 2) { // Less than two images, we don't need to xfade or add controls
    			return
    		}
    		
    		if(wt.hero.useControls) {
    			heroshot.append(
    					$(jQuery('<div class="controls" />'))
    						.append(
    							$(jQuery('<ul />'))
    								.append(
    									$(jQuery('<li />'))
    										.append(
    											$(jQuery('<a href="#previous" class="previous" title="Previous">Previous</a>'))
    												.click(function(c){
    													c.preventDefault()
    													clearInterval(interval)
    													wt.hero.rotate('prev', heroshot)
    													heroshot.find('.pause').hide()
    													heroshot.find('.play').show()
    												})
    										)
    								)
    								.append(
    									$(jQuery('<li />'))
    										.append(
    											$(jQuery('<a href="#pause" class="pause" title="Pause">Pause</a>'))
    												.click(function(c){
    													c.preventDefault()
    													clearInterval(interval)
    													heroshot.find('.pause').hide()
    													heroshot.find('.play').show()
    												})
    												.css({display: 'block'})
    												.show()
    										)
    								)
    								.append(
    									$(jQuery('<li />'))
    										.append(
    											$(jQuery('<a href="#play" class="play" title="Play">Play</a>'))
    												.click(function(c){
    													c.preventDefault()
    													interval = setInterval(function(){
    														wt.hero.rotate('next', heroshot)
    													}, dur + fade)
    													heroshot.find('.pause').show()
    													heroshot.find('.play').hide()
    												})
    												.css({display: 'block'})
    												.hide()
    										)
    								)
    								.append(
    									$(jQuery('<li />'))
    										.append(
    											$(jQuery('<a href="#next" class="next" title="Next">Next</a>'))
    												.click(function(c){
    													c.preventDefault()
    													clearInterval(interval)
    													wt.hero.rotate('next', heroshot)
    													heroshot.find('.pause').hide()
    													heroshot.find('.play').show()
    												})
    										)
    								)
    						)
    				)
    		}
    		
    		heroshot.children('a:first-child,img:first-child').attr({current: 'current'})
    		heroshot.children('a:not(:first-child),img:not(:first-child)').hide()
    		if(jQuery.browser.safari) {
    			heroshot.children('a:not(:first-child),img:not(:first-child)').css({display: 'none'})
    		}
    		
    		interval = setInterval(function() {
    			wt.hero.rotate('next', heroshot)
    		}, dur + fade)
    		
		});

		


		wt.hero.rotate = function(dir, heroshot) {
			if(typeof dir == 'undefined') {
				var dir = 'next'
			}
			if(typeof heroshot == 'undefined') {
				return
			}
			
			var images = heroshot.children('a,img')
			var current = heroshot.children('a[current],img[current]')
			if(dir == 'next') {
				if(current.next('a,img').size()) {
					var to = current.next('a,img')
				} else {
					var to = $(images[0])
				}
			} else {
				if(current.prev('a,img').size()) {
					var to = current.prev('a,img')
				} else {
					var to = $(images[images.size() - 1])
				}
			}
            
            var fade = heroshot.attr('fade')
			current.removeAttr('current').fadeOut(fade)
			
			if(wt.hero.useCaptions) {
				heroshot.find('.holder').fadeOut(fade / 2, function(){
					heroshot.find('.holder').text(to.find('img').size() ? to.find('img').attr('alt') : to.attr('alt'))
					heroshot.find('.holder').fadeIn(fade / 2)
				})
			}

			if(wt.hero.useForeground) {
				if(to.href != 'undefined') {
					heroshot.find('.foreground').bind('click',function() {
						window.location = to.href
					})
				} else {
					heroshot.find('.foreground').unbind('click',function() {
						window.location = to.href
					})
				}
			}
			to.attr({current: 'current'}).fadeIn(fade)
		}
	}

	// Heroshot options
	wt.hero.useForeground = true
	wt.hero.useControls = true
	wt.hero.useCaptions = true
	
	var center = function(){
	    if ($('.image')) {$('.current-set').find('.image').each(function(i){
	        $(this).css({'width':$(window).width(),'height':$(window).height(),'left':$(window).width()*i});
            $(this).parent().css('left',-$(window).width())
            return this;
	    })}
	        
        if($('html#news-and-updates').size()) return ;
        var content = $('.content');
        if (content.is(':animated')) return;
        if($(window).width() <= content.outerWidth() + 25) {
            content.css({
                left: 0,
                marginLeft : 10

            }, 250)
        } else {
            content.animate({
                marginLeft: -480,
                left: '50%'
            }, 250)
        }
        
        hidefooter();
    }
    
    function hidefooter(){
          var f = $('#footer .left');
          var fo = $(window).height() - 30;
          var ci = $(document);
      //    var ch = ci.innerHeight() + parseInt(ci.css('margin-top')) + 90;
          var ch = ci.height() - $(document).scrollTop() - 90;

      console.log("test")

          if (ch  >= fo) {
              f.fadeOut('fast')
          } else {
              f.fadeIn('fast')
          }
    }

    var drawer = function(){
        var d = $('ul#portfolio-container'),
        w = d.outerWidth(),
        h = d.outerHeight(),
        handle = $('#handle'),
        self = this;
        this.vis = false;
        
        if ($('html#portfolio').size())
        self.vis = true
    
        d.css({
            position:'absolute',
            marginTop:-h/2,
            top:'50%',
            marginLeft:-w,
            opacity: 1.0
        });
        
        // $('#tab').css({height:h,marginTop:-h/2})
        
        handle.click(function(){
            if (self.vis == false){
                d.animate({
                    marginLeft:'-30px'
                },400)
                self.vis = true;
            } else {
                d.animate({
                    marginLeft:-w
                },400)
                self.vis = false;
            }
        })
    }


    var gallerycontroller = $.extend(new Object(), {
        init : function(){
            var self = this;
            this.timer = setInterval(function(){self.watch.apply(self)}, 20);
            this.galleries = {};
            this.hash = '';

            $("#portfolio .project").each(function(){
                var item = $(this),
                gal = self.galleries[item.attr('id')] = new gallery();
              //  gal.init(item);


            });
            
            $('#gallery-nav li.next a').click(function(e){e.preventDefault();self.next.apply(self)});
            $('#gallery-nav li.previous a').click(function(e){e.preventDefault();self.previous.apply(self)});
            
            $('#gallery-nav ul li.info a').click(function(e){
                if (e) {e.preventDefault();}
                var proj = self.currentproj();

                if ($(this).hasClass('on')) {proj.infoBox.close.apply(proj); return false;}
                else if ($(this).hasClass('off')) {proj.infoBox.open.apply(proj); return false;}
            });
            
            $(document).keydown(function(e){
                if (e.keyCode == 39) {self.next.apply(self);}
                if (e.keyCode == 37) {self.previous.apply(self);}
            })
            
            if (window.location.toString().match(/portfolio\/$/)) {
                var first = $('#portfolio-container').find('li.project:first').find('a').attr('href');
                window.location.replace(window.location+first.toString().match(/[#].\w+/));
            }



        },

        currentproj : function(){
            return this.galleries[this.hash.slice(2)];
        },

        next : function() {
            var proj = this.currentproj();
            proj.next.apply(proj);
        },

        previous : function() {
            var proj = this.currentproj();
            proj.previous.apply(proj);
        },
        watch : function(){
            var url = window.location.hash;

            if (url != this.hash) {

                var gall = this.galleries[url.slice(2)];
                var oldgal = this.galleries[this.hash.slice(2)];
                
                if (!gall.exists) 
                gall.init($('#portfolio #'+url.slice(2)));
                
                if (oldgal.exists) oldgal.hide();
                gall.show();


                
            };
            this.hash = url;
        }
    })

    var gallery = function(){};

        $.extend(gallery.prototype, {
            
            exists: false,
            nexted: false,
            init : function(item){
                // alert(item[0])
                if (!$('#portfolio')[0]) return;
                var self = this;
                // apply calls a function and passes in 'this' and an array of arguments
                this.exists = true,
                this.moving = false,
                this.n = 0,
                this.images = [],
                this.scrollx = 0,
                this.container = item;

                var anchors = this.container.children('.images').clone().find('a');
                
                this.populate(anchors);
                
                $('#gallery-nav').show();

                $('#close a').click(self.infoBox.close);

            
                return this;


            },


            show : function(){
                var self = this.container,
                    info = $('#infoBox .target');

                this.target.addClass('current-set');
                this.menuitem.addClass('current-item');
                
                info.empty().append(
                        self.children('.info').html()
                    ).parent().fadeIn('slow').hide(); // Uncomment the .hide() to turn infoBox back on
                ($('#gallery-nav span.project-name')).empty().append($('#infoBox h4').html())


                
                // $('#gallery-nav ul li.info a').removeClass('off').addClass('on'); Also uncomment this line and remove the next
                $('#gallery-nav ul li.info a').addClass('off');


            },

            hide : function() {
                 this.target.removeClass('current-set');
                 this.menuitem.removeClass('current-item');
            },

            populate : function(w){
                var thisproj = this.container,
                self = this;

                var target = $("<div>").attr({
                    id : "photos-for-"+this.container.attr('id')
                }).addClass('set');
                
                var menuitem = $('ul#portfolio-container ul li.work-'+this.container.attr('id'));
                
                this.target = target;
                this.menuitem = menuitem;
                
                $('#photos').append(target);
                var len = w.length;
                for (i=0; i<len; i++) {
                    var x = w[i],
                    j = i+1,
                    src = $(x).attr('href');
                    target.append($('<div class="image"></div>').append($('<img>').attr('src',src)));
                }


                target.find('.image').each(function(i,img){
                  self.images.push($(img)[0]);

            });
                this.space(target);
            },

            space : function(target){
                var galw = $(window).width(),
                galh = $(window).height(),
                proj = this.container.attr('id'),
                id = $('#photos-for-'+proj),
                count = $('#photos-for-'+proj+' .image').size();

            
                $('#photos-for-'+proj).css({
                    position: 'absolute',
                    top: 0,
                    left: -galw,
                    width: galw*(count+1)
                })

                $('#photos-for-'+proj+' .image').each(function(i){
                    $(this).css({
                        left: (galw*i)+galw,
                        width: galw,
                        height: galh
                    });
                });

                $('#photos-for-'+proj+' .image img').each(function(i){
                    $(this).css('opacity',0).load(function(){
                        var clone = $(this).clone().css({
                            opacity: 1,
                            left: '-5000px',
                            top: '-5000px',
                            position: 'absolute'
                        }).show().appendTo('body');
                        $(this).css({
                            left: '50%',
                            top: '50%',
                            marginLeft: -(1/2)*(clone.width()),
                            marginTop: -(1/2)*(clone.height()),
                            position: 'absolute',
                            opacity : 0

                        }).animate({opacity : 1.0},800)

                        
                        if ($(this).css('margin-left') == '0px')
                        {
                            $(this).css({
                                marginLeft: -(1/2)*($(this).width()),
                                marginTop: -(1/2)*($(this).height())
                            }).fadeIn('slow')
                        }
                        
                        if ($.browser.msie && $.browser.version=="6.0"){
                            $(this).ifixpng();
                        }
                        clone.remove();
                        
                    });

                })


                // var len = $('.set').size();
                // console.log(len);
                // 
                // var li = $('#photos-for-'+proj+' .image:last').clone().css('left',0).prependTo('#photos-for-'+proj);
                // var limg = li.find('img');
                // var lsib = limg.parent('.image').siblings(':eq(1)').find('img');
                // console.log($('.set').find('.image:eq(1)').find('img').css('margin-left'))
                // 
                // limg.show().css({
                //         // display:'inline',
                //         // position:'absolute',
                //         // top:'50%',
                //         // left:'50%',
                //         // marginLeft:-400,
                //         // marginTop:-300
                //         position : 'static',
                //         margin : 'auto',
                //         align : 'center'
                //     });




                    var set = $('#photos-for-'+proj),
                    total = set.children('.image').size(),
                    first = set.children('.image:first-child'), // 1 is first because the one at index 0 is a copy of the last one
                    visible = set.children('.image:eq(1)'),
                    last = set.children('.image:last-child'),
                    pagew = $(window).width(),
                    pos = $('.current-set').offset().left;
                    var leftVal = parseInt(last.css('left'));

                   ($(last).clone().css('left',0).addClass('new')).prependTo(set);  
                    // self.first.remove();     

                    set.children('.image:first-child').find('img').css('display','block')
                    set.children('.image:eq(1)').find('img').each(function(){
                        var item = $(this).css('display','block');
                    });


            },

            infoBox : {
              close : function(e){
                  if(e) e.preventDefault();
                  $('#infoBox').fadeOut('fast');
                  $('#gallery-nav ul li.info a').removeClass('on').addClass('off');
              },
              open : function(e){
                  if(e) e.preventDefault();
                  var box = $('#infoBox');
                  box.css({
                      marginLeft : -(box.width()/2)
                  });
                  box.fadeIn();
                  $('#gallery-nav ul li.info a').removeClass('off').addClass('on');
              }  
            },

            next : function(e){

                if(e) e.preventDefault();
                if (this.images.length == 0) return;
                if (this.moving) return;
                this.nexted = true;
                
                var self = this,

                set = $('.current-set');
                this.moving = true;
                this.total = set.children('.image').size();
                this.first = set.children('.image:eq(0)'); // 1 is first because the one at index 0 is a copy of the last one
                this.visible = set.children('.image:eq(1)');
                this.last = set.children('.image:last-child');
                var pagew = $(window).width(),
                pos = $('.current-set').offset().left;

                self.infoBox.close();

                set.animate({left: pos - pagew}, 400, function(){
                    var leftVal = parseInt(self.last.css('left'));
                    set.append($(self.visible).clone().css('left',leftVal+pagew).addClass('new'));  
                    self.first.remove();     
                    self.pos= $('.current-set').offset().left;   
                    self.moving = false; 
                });

            },

            previous : function(e){
                if(e) e.preventDefault();
                if (this.images.length == 0) return;
                if (this.moving) return;

                var self = this,
                pagewidth = $(window).width(),
                set = $('.current-set');
                this.moving = true;
                this._total = set.children('.image').size();
                this._togo = set.children('.image:last'); 
                this._next = set.children('.image:eq(0)');
                this._visible = set.children('.image:eq(1)');
                // this._toclone = set.children('.image:nth-child(this._total[0] -2)');
                this._toclone = set.children('.image:last').prev();
                var _leftVal = parseInt(self._next.css('left').replace('px',''));
                this.pos= $('.current-set').offset().left;    

                self.infoBox.close();
                

                
                $('.current-set').animate({left: self.pos +pagewidth}, 400, function(){
                    var suspect = set.children('.image:first-child').find('img');

                    if ( parseInt(suspect.css('marginLeft')) == 0)  {
                        suspect.parent().css({
                            'display' : 'block',
                            'position' : 'relative',
                            'width' : $(window).width(),
                            'height' : $(window).height()
                        })
                        suspect.css({
                            'left' : '50%',
                            'top' : '50%',
                            'position' : 'absolute',
                            'margin-left' : -suspect.width()/2,
                            'margin-top' : -suspect.height()/2
                        })

                    }

                    set.prepend($(self._toclone).clone().css('left', parseInt(self._visible.css('left'))-(2*pagewidth)).addClass('new'));  
                    set.children('.image:last-child').remove();
                    self.moving = false;
                });
            }
    });
    

})();
