// Browser object for mobile device detection
var Browser = Browser || {};
 Browser.ua = navigator.userAgent.toLowerCase();
 Browser.ie6 = Browser.ua.indexOf('windows nt 5.1') > -1;

try {
 document.createEvent('TouchEvent');
 Browser.supportsTouch = true;
} catch(e) {
 Browser.supportsTouch = false;
}

// Markup based unobtrusive comprehensive dom ready execution
// http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/
// Remove these comments and replace CLIENTNAME with the name of the client or site.
ANDCULTURE = {
	common : {
		init : function() {
			ANDCULTURE.common.sidebarscroll.init();
			ANDCULTURE.common.twitterNew.init();
		},
		sidebarscroll : {
			init : function() {
				var move;
				var msie6 = $.browser == 'msie' && $.browser.version < 7;
				
				if (!msie6) {
					var sideTop;
			
					if($('#sidebar').length) {
						sideTop = $('#sidebar').offset().top - 40;
						
						$(window).scroll(function (event) {
							// what the y position of the scroll is
							var y = $(this).scrollTop();
						  
							// whether that's below the form
							if (y >= sideTop) {
							// if so, ad the fixed class
							$('#sidebar').addClass('fixed');
							} else {
							// otherwise remove it
							$('#sidebar').removeClass('fixed');
							}
							
							//New
							var inview = '#' + $('#content > section > header > h1:in-viewport:first').parents('section').attr('id');
							
							var $link = $('#sidebar li a').filter('[hash=' + inview + ']');
							$link = $link.parent();
							
							if ($link.length && !$link.is('.selected') ) {
								$('#sidebar li').removeClass('selected');
								$link.addClass('selected');	          	
							} else if (y == 0) {
								$('#sidebar li').removeClass('selected');
								$('#sidebar li:first').addClass('selected');
							}
						});
					}
				}
			}
		},
		twitter : {
			init : function() {
				$('#twitter-footer').getTwitter({
					userName: "andculture",
					numTweets: 1,
					loaderText: "Loading tweets...",
					slideIn: true,
					slideDuration: 750,
					showHeading: false,
					headingText: "Follow us here",
					showProfileLink: false,
					showTimestamp: true
				});
			}
		},
		twitterNew : {
			init : function() {
				$('#twitter-footer').jTweetsAnywhere({
				    username: 'andculture',
				    count: 1,
				    showTweetFeed: {
				    	includeRetweets: false,
				    	showTimestamp: {
				    		refreshInterval: 15
				    	},
				    	autorefresh: {
				    		mode: 'trigger-insert',
				    		interval: 30
				    	}
				    },
				    onDataRequestHandler: function(stats, options) {
				        if (stats.dataRequestCount < 11) {
				            return true;
				        }
				        else {
				            stopAutorefresh(options);
				        }
				    }
				});
			}
		},
		finalize : function() {
		  function getParameterByName(name) {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=?([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if(results == null) {
          return null;
        } else {
          return decodeURIComponent(results[1].replace(/\+/g, " "));
        }
      }
      if(getParameterByName('g') !== null) {
        $.scrollTo($('p[id="' + getParameterByName('g') + '"]').offset().top - 50, {duration: 800});
      }
    }
	},
	home : {
		init : function() {
			ANDCULTURE.home.masonry();
			ANDCULTURE.home.lettering();
			ANDCULTURE.home.tweets();
		},
		masonry : function() {
			$('#grid').masonry({
				singleMode: true,
				columnWidth: 320,
				itemSelector: 'article'
			});
		},
		lettering : function() {
			$('.callouts p').lettering('lines');
		},
		tweets : function() {
			if ($('.tweets').length) {
				$('.tweets').each(function() {
					var $article = $(this),
						tweetID = $article.find('.tweet-id').attr('data-tweet-id'),
						url = 'http://api.twitter.com/1/statuses/show/' + tweetID + '.json';
					$.ajax({
						url:		url,
						dataType:	'jsonp',
						success: function(data) {
							$('#tweetTmpl').tmpl(data, {
								date: function() {
									var date = new Date(data.created_at),
										m = (date.getMonth() < 10 ? '0' + date.getMonth() : date.getMonth()),
										d = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()),
										y = date.getFullYear();
									return m + '.' + d + '.' + y;
								}
							}).prependTo($article);
						}
					});
				});
			}
		}
	},
	about : {
		init : function() {
			ANDCULTURE.about.teamGrid();
		},
		teamGrid : function() {
			$('#team').masonry({
				columnWidth: 156,
				itemSelector: 'article'
			});
		}
	},
	connect : {
		init : function() {
			ANDCULTURE.connect.liveval.init();
			ANDCULTURE.connect.formlock.init();
			ANDCULTURE.connect.formtoggle.init();
			ANDCULTURE.connect.formUI.init();
		},
		liveval : {
			init : function() {
				$("#email-form").slideLock({
					labelText: "Slide to Unlock - proves you're a human!",
					noteText: "",
					lockText: "Locked",
					unlockText: "Unlocked",
					iconURL: "images/captcha_arrow.png",
					inputID: "sliderInput",
					onCSS: "#333",
					offCSS: "#aaa",
					inputValue: 1,
					saltValue: 9,
					checkValue: 10,
					js_check: "js_check",
					submitID: "#submit-email"
				});
			}
		},
		formlock : { 
			init : function() {
				//Form Validation
				var first = new LiveValidation('first');
					first.add(Validate.Presence, {failureMessage: "Required", wait: 500});
				var last = new LiveValidation('last');
					last.add(Validate.Presence, {failureMessage: "Required", wait: 500});
				var company = new LiveValidation('company');
					company.add(Validate.Presence, {failureMessage: "Required", wait: 500});
				
				var emailtext = new LiveValidation('emailtext');
					emailtext.add(Validate.Presence, {failureMessage: "Required", wait: 500});
					emailtext.add(Validate.Email, {failureMessage: "Must be a valid email address", wait: 2500});
			}
		},
		formtoggle : {
			init : function() {
				//Hiding other fields
				$('#contact-form .phone, #contact-form .twitter, #contact-form .snail').hide();
			
				//Always setting email to checked on refresh
				$('.toggle input')[1].checked = true;
				
				$('.toggle input').click(function() {
					var fieldshow = $(this).attr('id');
					$('.indent .row').siblings('div').css('display', 'none');
					$('.indent .' + fieldshow + '').css('display', 'block');
				});
			}
		},
		formUI : {
			init : function() {
				$('.radio span').buttonset();
				$('.project-checkbox span').buttonset();
			}
		}
	}
};

UTIL = {
	fire : function(func,funcname, args){
		var namespace = ANDCULTURE;
		
		funcname = (funcname === undefined) ? 'init' : funcname;
		if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function'){
			namespace[func][funcname](args);
		}
	},
	loadEvents : function() {
		var bodyId = document.body.id;
		
		// Fire common scripts first.
		UTIL.fire('common');
		
		// Fire scripts based on body class and id.
		$.each(document.body.className.split(/\s+/),function(i,classnm){
			UTIL.fire(classnm);
			UTIL.fire(classnm,bodyId);
		});
		
		// Fire low priority scripts last.
		UTIL.fire('common','finalize');
	}
};

$(function() { UTIL.loadEvents() });

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

// catch all document.write() calls
(function(doc){
  var write = doc.write;
  doc.write = function(q){ 
    log('document.write(): ',arguments); 
    if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);  
  };
})(document);

