// IE setTimeout/setInterval extra arguments fix
// http://webreflection.blogspot.com/2007/06/simple-settimeout-setinterval-extra.html
/*@cc_on
(function(f){
 window.setTimeout =f(window.setTimeout);
 window.setInterval =f(window.setInterval);
})(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c.apply(this,a)},t)}});
@*/

function trace (argument) { console.log(argument); }

var mm = {
  
  _init : function() {
    _h._init();
    mm.prepInterface();
    $.historyInit(pageload, "");
  }
  
  ,prepInterface : function() {
    mm.loadingSpan();
    mm.setupDimensions();
    mm.prepNavigation();
    //mm.scrollable();
    mm.appendCreditsToScroller();
    mm.disableSelection();
		//mm.postForm();
  }

	,postForm : function() {
		if ($('form').length > -1) {
			$('form').each(function() {
				var postUrl = $(this).attr('action');
				$(this).submit(function() {
					$.post(postUrl, null, function() {
						window.open(postUrl);
					})
					return false;
				})
			})
		};
	}
  
  ,prepNavigation : function() {
    mm.prepAjax();
  }
  
  ,loadingSpan : function() {
    $(window).ready(function() {
      setTimeout(function() {
        $('span#loading').animate({ opacity: 0 }, 1000, function() {$('span#loading').remove()});
      }, 5000);
    });
  }
  
  ,prepAjax : function() {
    $('#nav li a,div.tag a,a.view').live("click", function() {
      var item = $(this);
      var url = $(this).attr('href');
      $("div#nav ul li").removeClass("active");
      mm.addNavActiveState(this);
      mm.ajaxPage(url);
      pageTracker._trackPageview(url);
      return false;
    });
  }
  
  ,ajaxPage : function(url) {
    // start animation: move footer down
    $('div#main').animate({
      opacity: 0
    }, 1000, function() {
			
$(window).scrollTop(0, 1000)
      //remove main content      
      $.get(url, null, function(data) {
        $('div#main').html($($(data).find('div#main')).html());
        // push content to UI
        // finish animation: make sure footer is still on bottom
        
        mm.setupDimensions();
        mm.appendCreditsToScroller();
        //show the content
        $('div#main').animate({ opacity: 1 }, 1000 );
        
        /*if (url.indexOf('view') >-1) {
          $('img').lazyload({
  					container: $('div.scrollable'), 
  					effect : "fadeIn"
  				});
        };*/
				//$(window).bind("load", function() { 
			  //  var timeout = setTimeout(function() {$("img").trigger("sporty")}, 5000);
				//}); 
				//prep the scrollers
        mm.innerPageNavActiveState();
        /*if ($('div#print-view').length > 0 || $('div#illustration-view').length > 0 || $('div#motion-view').length > 0 || $('div#web-view').length > 0 || $('div#tactiles-view').length > 0 || $('div#news-view').length > 0) {
          if(!$.browser.msie.version < 7.0) {
            //mm.innerProjectsScrollable();
          }
        } else {
          //mm.scrollable(); 
        };*/
				//mm.postForm();
        // jquery.history
        var hash = url;
  			hash = hash.replace(/^.*#/, '');
  			$.historyLoad(hash);
        $.swapImage(".swapImage");
      });
    });
  }
  
  ,scrollable : function() {
    if ($('div.scrollable').length > 0) {
      // initialize scrollable  
      var size = 1;
      if ($('div#print-gallery').length > 0 || $('div#illustration-gallery').length > 0 || $('div#motion-gallery').length > 0 || $('div#web-gallery').length > 0 || $('div#tactiles-gallery').length > 0) {
        size = 4;
      };
      var api = $("div.scrollable").scrollable({
        vertical: true,  
        size: size, 
        clickable: false
      }).mousewheel({ 
        api: true
      });
      api.onBeforeSeek = function() {  }
    }
  }
  
  ,setupDimensions : function() {
    /*$('div.scrollable').css({
      height: ($(window).height()) + 'px'
    });*/
    $('div#footer').css({
      width: ($(window).width()) + 'px'
    })
    $('div#footer div#actions').css({
      marginRight: (($(window).width() - $('.scrollable, .scroll-pane').width()) /2) + 'px'
    });
    $('div#footer div#nav').css({
      marginLeft: (($(window).width() - $('.scrollable, .scroll-pane').width()) /2) + 'px'
    });
    $('div#main').css({
      height: ($(window).height()) + "px"
    })
		$('#container').css({
			height: $(document).height() + "px"
		})
  }
  
  ,appendCreditsToScroller : function() {
    $("div.mod_article div.mod_newslist").append("<div class='credits'><img alt='© MaricorMaricar 2010. All rights reserved' class='left' src='assets/images/copy_right.png'><a target='_blank' href='http://gea-interactive.com.au' class='right'><img alt='built by gea' src='assets/images/gea.png'></a></div>");
  }
  
  ,addNavActiveState : function(item) {
    if ($(item).parent().hasClass('active')) {
      mm.clearNavActiveState();  
    };
    $(item).parent().addClass('active');
  }
  
  ,clearNavActiveState : function() {
    $("div#nav ul li").removeClass("active");
  }
  
  ,innerProjectsScrollable : function() {
    if ($('div#print-view').length > 0 || $('div#illustration-view').length > 0 || $('div#motion-view').length > 0 || $('div#web-view').length > 0 || $('div#tactiles-view').length > 0 || $('div#news-view').length > 0) {
      $("div#main").children().children().css({
        width: $("div#main").children().children().width() + (($(window).width() - $("div#wrapper").width()) / 2) + "px",
        overflow: "auto"
      });
      mm.jumpProjects();
    };
  }
  
  ,scrollProjects : function() {
    var position = $("div.current_item").offset().top;
  }
  
  ,innerPageNavActiveState : function() {
    if ($('div#print-view').length == 1) {
      $("#nav li#print").addClass("active");
    };
    if ($('div#illustration-view').length == 1) {
      $("#nav li#illustration").addClass("active");
    };
    if ($('div#motion-view').length == 1) {
      $("#nav li#motion").addClass("active");
    };
    if ($('div#web-view').length == 1) {
      $("#nav li#web").addClass("active");
    };
    if ($('div#tactiles-view').length == 1) {
      $("#nav li#tactiles").addClass("active");
    };
    if ($('div#news-view').length == 1) {
      $("#nav li#news").addClass("active");
    };
  }
  
  ,disableSelection : function() {
    $('.disableSelection').disableTextSelect(); // and enableTextSelect() to re-enable it again
  }

  ,jumpProjects : function() {
    var counter = 0;
    $("div.mod_newslist div.layout_full").each(function() {
      $(this).attr({rel: counter});
      counter++;
    });
    var theStart = parseInt($("div.current_item").attr("rel"));
    currentItem = theStart;
		
    if (!isNaN(theStart) && ($('div#print-view').length > 0 || $('div#illustration-view').length > 0 || $('div#motion-view').length > 0 || $('div#web-view').length > 0 || $('div#tactiles-view').length > 0 || $('div#news-view').length > 0)) {
      $("div#main div.scrollable").serialScroll({
    		start: theStart,
        items:'div.layout_full',
        //prev:'a.prevPage', 
        //next:'a.nextPage', 
        axis:'y', 
        duration:800, 
    		offset:-200, 
    		force:true, 
    		step:1, 
				lazy:true
				//onBefore: function(event_obj, targeted_element, element_to_te_scrolled, collection_of_items, position_of_targeted_element) { trace(position_of_targeted_element); }
      });
      mm.keyboardJumpProjects();
    }
		
		if ($('a.nextPage').attr('rel') != 'clickified') {
			$('a.nextPage').click(function() {
				if ($('div.current_item').next('div.layout_full').length > 0) {
					// scroll to next item
		      $('div.current_item').next('div.layout_full').addClass('current_item');
					$($('div.current_item').get(0)).removeClass('current_item');
				} else {
					// scroll to top
					$($('div.current_item').get(0)).removeClass('current_item');
					$($('div.scrollable div.layout_full').get(0)).addClass('current_item');
				}
				var newScrollPosition = $('div.current_item').position().top;
				$('div#main div.scrollable').scrollTo({top:(newScrollPosition)+'px', left:'290px'}, 800);
				$('div#main div.scrollable h2 img').each(function() {
				  $(this).attr('src', $(this).attr('original'));
				})
			});
			$('a.prevPage').click(function() {
				if ($('div.current_item').prev('div.layout_full').length > 0) {
					// scroll to next item
					var last = $($('div.current_item').get(0));
		      $('div.current_item').prev('div.layout_full').addClass('current_item');
					last.removeClass('current_item');
				} else {
					// scroll to top
					var last = $($('div.current_item').get(0));
					last.removeClass('current_item');
					$($('div.scrollable div.layout_full').get($('div.scrollable div.layout_full').length-1)).addClass('current_item');
				}
				var newScrollPosition = $('div.current_item').position().top;
				$('div#main div.scrollable').scrollTo({top:(newScrollPosition)+'px', left:'290px'}, 800);
				$('div#main div.scrollable h2 img').each(function() {
				  $(this).attr('src', $(this).attr('original'));
				})
			});
			$('a.nextPage').attr('rel', 'clickified');
		};
  }
  
  ,keyboardJumpProjects : function() {
    /*$(document).keyup(function(event) {
      if (event.which == '38') {
        $($('a.prevPage').get(0)).click();
      };
    })
    
    $(document).keyup(function(event) {
      if (event.which == '40') {
        $($('a.nextPage').get(0)).click();
      };
    });*/
  }
};


function pageload(hash) {
	// alert("pageload: " + hash);
	// hash doesn't contain the first # character.
	if(hash) {
		// restore ajax loaded state
		if($.browser.msie) {
			// jquery's $.load() function does't work when hash include special characters like aao.
			hash = encodeURIComponent(hash);
		}
		//mm.ajaxPage(hash);
	} else {
		// start page
		//$("#load").empty();
	}
}


var _h = {
  
  _init : function() {
    _h.prepInputs();
  }
  
  ,prepInputs : function() { $('input').click(function() { $(this).select(); }); }
  ,t : function (argument) { return jQuery.trim(argument); }                          // trim
  
};


$(function() {
  mm._init();
});

jQuery.event.add(window, "load", mm.setupDimensions);
jQuery.event.add(window, "resize", mm.setupDimensions);
