$(document).ready(function() {
    var hr = new Hires();

    var userAgent = window.navigator.userAgent;
    if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)) {
        isMobile = true;
    } else {
        isMobile = false;
    }

    
    Shadowbox.init({ 
        opacity:1,
        overlayOpacity:1,
        onOpen: function(e) { 
    
            if (isMobile) {
                        setTimeout ( function(){
                            var w = $('#sb-container').width();
                            var h = $('#sb-container').height();
                            $('#sb-container').width(1024)
                            $('#sb-container').height(h+100)                            
                        }, 500 );


                $('#sb-container').css({position:"absolute", top: window.pageYOffset+"px", left: window.pageXOffset+"px"});
            } 
            $('#sb-title').after($('#sb-info')); 
            $('#sb-counter').hide();
            $('#sb-nav-next').html('Next');
            $('#sb-nav-previous').html('Prev | ');
//            $('#sb-nav-previous').after(" | ");
            $('#sb-nav-next').before($('#sb-nav-previous'))
            $('#sb-nav-close').html('Close');
        },
        onClose:function(e){
            if (isMobile) {

            } 
            
        }
    }); 

    // $('body').keyup(function(event) {
    //     if (event.keyCode == 69) {
    //         $('#container').animate({rotate: '+=10deg'}, 0);
    //     }
    // })


});





var Hires = function ( )  
{    
    
    var _self = this;
    this.page = 1;
    this.filter = '';
    
    // if($('li:eq(2) a', $('#nav')).hasClass('current')) {
    //     $('#subnav').slideToggle('slow');   
    // }

    if($('.archive').size()>0) {
        $('#subnav').slideToggle('slow');   
    }
    
    
    $("#search").focus(function() {
        $(this).val('');
    });
    $("#searchFrm").submit(function() {
        
        
        
        // if ($('input', this).val() == "egg") {
        //     $.getJSON('https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=scarry%20easter%20egg&callback=?', function(data) {
        //         console.log(data);
        //       $.each(data.responseData.results, function(key, val) {
        //           console.log(val.unescapedUrl);
        //       });
        //     });
        // }
        
        var url = 'http://hi-res.net/search/'+$('input', this).val()+'.html';
        _self.loadUrl(url);
        return false;
    });


    $('#subnav a').click(function() {
        var selector = $(this).attr('filters');
        if (selector == '.lucky') {
            var r = $('.box').size();
            var i = Math.round(r*Math.random()) - 1;
            $('.showProject','.box:eq('+i+')').click();
            return false;
        }
        _self.$i.isotope({ filter: selector });
        return false;
    });
    
    $("#pagination").hide();
    var myFile = document.location.toString();

    $('.box').live('mouseover mouseout', function(event){
        if (event.type == 'mouseover') {
            $(this).find('img').stop().animate({opacity:'.6'},{queue:false,duration:300});
        } else {
            $(this).find('img').stop().animate({opacity:'1'},{queue:false,duration:300});   
        }
	});
    $('.clients li').css({opacity:'.3'});
    $('.clients li').live('mouseover mouseout', function(event){
        if (event.type == 'mouseover') {
		    $(this).stop().animate({opacity:'1'},{queue:false,duration:300});
		} else {
		    $(this).stop().animate({opacity:'.3'},{queue:false,duration:300});   
		}
	});
    $('.clients li a').live('click', function(){
        
        var c = $(this, 'a').attr('id');
    });


	$('.tagger').hide();
	$('#tags').live("click", function(event){
	   $('.tagger').slideToggle('slow');
       $('body').one('click',function() {
         $('.tagger').slideToggle('slow');
       });
       event.stopPropagation();
	});

	$('#backOverview').live("click", function(){
        var url = './';
        _self.loadUrl(url);
        return false;
	});

    window.onpopstate = function(event) {
        //_self.loadUrl(document.location);
    };



    this.setUpIsotope();

    $('#sb-body').live('click', function(){
        Shadowbox.next();
    })


    $('.showProject, .tagger a').live('click', function(){
        $('#subnav').hide();
        var url = $(this).attr('href');
        _self.loadUrl(url);
        
        return false;
    });
    $('.desc').animate({opacity:'.1'},{queue:false,duration:300})
    $('.pict').live('mouseover mouseout', function(event){
        if (event.type == 'mouseover') {
		    $(this).stop().animate({opacity:'0.3'},{queue:false,duration:300});
		    $('.desc', $(this).parent()).stop().animate({opacity:'1'},{queue:false,duration:300});   
		} else {
		    $(this).stop().animate({opacity:'1'},{queue:false,duration:300});   
		    $('.desc', $(this).parent()).stop().animate({opacity:'0'},{queue:false,duration:300});
		}
	});

    
    if (BGBODY) {
        $('body').css('backgroundImage','url('+BGBODY+')');
    }
    
    $.getScript('http://twitter.com/statuses/user_timeline/HiResLondon.json?callback=twitterCallback');

    $('.desc').each(function(index) {
        var t = 255/2 - $(this).height()/2;
       $(this).css({top:t});
    });
    $('#page_nav').hide();

    
    // $(window).bind( 'keyup', function(event){
    //     console.log(event.keyCode);
    //     if (event.keyCode == 82) {
    //         $('#homepage').randomize(".box").isotope('destroy')
    //         $('#homepage').isotope({
    //             itemSelector : '.box',
    //             masonry : {columnWidth : 246},
    //             animationEngine : $.browser.opera ? 'jquery' : 'best-available'
    //         });;
    //     }
    // });

}



var o = Hires;

o.prototype.loadUrl = function(url) {
    
    var stateObj = { url: url };

    if (typeof(window.history.pushState) == 'function'){
        window.history.pushState(stateObj, url, url);
    } else {
        window.location.hash = '#!'+url.substring(url.lastIndexOf('/') + 1);
    }

    $(window).unbind('.infscr');
    
    var i = 1;
    var _self = this;

  $.ajax({
    url: url,
    dataType: "html",
    complete: function(e) {
       $('.box').each(function (i) {
           $(this).delay(100*i).fadeTo(300,0).delay(1000*Math.random());
       }).delay(100*i, function(){
           $('#content').html(e.responseText);
                _self.setUpIsotope();
               Shadowbox.clearCache();
               Shadowbox.setup();
               $('.box').hide().each(function (i) {
                   $(this).delay(100*i).fadeTo(1000,1).delay(1000*Math.random());
               });           
           });
           $('.clients li').css({opacity:'.3'});   
           // if($('.archive').size()>0) {
           //     $('#subnav').slideToggle('slow');   
           // }         
        },

        success: function() {},
        error: function() {alert('error');}
    });

    

}

o.prototype.setUpIsotope = function() {
    var _self = this;
    this.$i = $('#homepage');
    this.$i.isotope({
        itemSelector : '.box',
      resizable: false,
        // layoutMode : 'fitRows',
        masonry : {
          columnWidth : 246
        },
//        animationEngine : 'css'
        animationEngine : $.browser.opera ? 'jquery' : 'best-available'
    });
    
    this.$i.infinitescroll({
      navSelector  : '#page_nav',    // selector for the paged navigation 
      nextSelector : '#page_nav a',  // selector for the NEXT link (to page 2)
      itemSelector : '.box',     // selector for all items you'll retrieve
      loadingImg : '/public/themes/hires5/images/ajax-loader.gif',
      loadingText: 'LOADING MORE ENTRIES',
      debug: false,
      errorCallback: function() { 
        // fade out the error message after 2 seconds
        $('#infscr-loading').animate({opacity: .8},2000).fadeOut('normal');   
      }
      },
      // call Isotope as a callback
      function( newElements ) {
          _self.$i.isotope( 'insert', $( newElements ) ); 
          $( newElements ).hide();
          $( newElements ).fadeIn();
      }
    );
    this.columns = null;
    $(window).smartresize(function(){
      var currentColumns = Math.floor( ( $('body').width() -10 ) / 246 );
      currentColumns = currentColumns>5?5:currentColumns;
      currentColumns = currentColumns<4?4:currentColumns;
      if ( currentColumns !== _self.columns ) {
        _self.columns = currentColumns;
        $('#content').width( _self.columns * 246 );
        _self.$i.isotope('reLayout');
      }
    }).smartresize();

}

function twitterCallback(tweets) {
    var tweet = tweets[Math.floor(Math.random()*tweets.length)];
    $("#twitter_update_list").html(tweet.text);
}





