ITV.index = function() {

	var GIGYA_CONF = { APIKey: ITV.gigyaId }

	var PROVIDERS = "facebook,twitter,google,aol"

	var GIGYA_LOGIN_PARAMS = {
		forceAuthentication: true,
	    showTermsLink: false,
	    hideGigyaLink: true,
	    height: 220,
	    width: 280,
	    autoDetectUserProviders: '',
	    facepilePosition: 'none',
	    facebookExtraPermissions: "friends_likes,user_likes",
	    extraFields: "interests,activities",
	    enabledProviders: PROVIDERS
	}	


	// handle the hash bange
	if (location.hash.indexOf("#!") === 0) {
		window.location.pathname = location.hash.slice(2)
		return	
	}
	
	var $main = $("body > article")
	var init = ITV[ITV.currentPage]

	if (typeof init === "function") init()

	$("#login").live("click", function(e) { 
		showLoginUI()
		e.preventDefault()
	})
	
	$(".requiresLogin").live("click", function(e) {
		if (ITV.loggedIn) return
		var $el = $(this)
	    showLoginUI(function() {
			$el.trigger("click")
	    })
	    e.preventDefault()
		return false
	})
	
	// we don't really need to log them out of gigya	
	$("#logout").live("click", function(e) { 
		e.preventDefault()
		gigya.services.socialize.logout(GIGYA_CONF)
	})
	
	$(".toggleNav").click(function(e) {
		e.preventDefault()
		$(document.body).toggleClass("activeHeader")
	})
	
	$(".searchButton").live("click", updateList)
	$("search").live("submit", updateList)	
	$(".searchBox").live("keyup", updateList)
		
	gigya.services.socialize.addEventHandlers(GIGYA_CONF, {   
		onLogin: function(response) {
			$.post("/login", response.user, function(user) {

                // REMOVED (4954f96) admin/permission stuff
                $("body").addClass("loggedIn")
                $("#user_thumbnail").attr("src", response.user.thumbnailURL)
                $("#user_name").text(response.user.nickname)
                ITV.loggedIn = true
                ITV.user = user
			})
		},
		onLogout: function(gigya) {
			window.location.href = "/logout"
		}
	})
		
	// public methods
	ITV.showShareUI = function(showcard) {
		var link = showcard.link || document.URL
		var act = new gigya.services.socialize.UserAction()
		act.setTitle(showcard.title)
		act.setUserMessage("I just checked in to " + showcard.title + " on i.TV")
		act.setDescription(showcard.description)
		act.addMediaItem({type:"image", href:link, src: "http://media.i.tv.s3.amazonaws.com/db_photos/showcards/" + showcard.showcardId + "/p" + showcard.showcardId + "_b_v3_aa.jpg"})
		act.addActionLink("Check It Out", link)
		act.setLinkBack(link)
	
		gigya.services.socialize.showShareUI(GIGYA_CONF, {
			userAction: act,
			onSendDone: function() { 
				$.ajax({
					url: "/shares/" + ITV.user.loginProvider + "/show/" + showcard.showcardId,
					success: function(data) {
						// not sure what to do honestly
						// maybe update the feed?
					},
					type: "POST"
				})
			}
		})
	}
	
	// private methods
	function showLoginUI(cb) {
		cb = typeof cb === "function" ? cb : function(){}
		GIGYA_LOGIN_PARAMS.callback = cb
		gigya.services.socialize.showLoginUI(GIGYA_CONF, GIGYA_LOGIN_PARAMS)
	}
		
	function updateList(e) {
		e.preventDefault()
		var query = $(".searchBox").val()
		updateListWithQuery(query)
	}
	
	function updateListWithQuery(query) {
		
		if(query.length < 2) return $main.empty()
		
		// so good, ooh yeah
		if (history.replaceState) {
		    history.replaceState({}, "", "/search/" + query)
	    } else {
			location.hash = "#!/search/" + query
	    }
	    
	    $("body").removeClass("home guide showlists").addClass("search")
	    
		$.get("/search/" + encodeURI(query), function(html) {
			$main.html(innerShiv(html))
			ITV.search()
		})
	}

}

jQuery.fn.jscroller = function() {
	var $self = $(this)
	return $(this).each(function() {
		var $ul = $(this).children("ul")
		var $lis = $ul.find("li")
		var numLis = $lis.length
		var liWidth = parseInt($($lis[0]).outerWidth(), 10)
		var ulWidth = liWidth * numLis + 150 
		$ul.width(ulWidth)
	})
}

jQuery.fn.updateFeed = function(showcardId, time) {
	showcardId = showcardId || 0
	time = ITV.feedTimes[showcardId] || 0
	var $self = $(this)
	var url = ITV.urls.feedSince.replace(":showcardId", showcardId).replace(":time", time)
	$.get(url, function(html, status, jqXHR) {
		var date = jqXHR.getResponseHeader("Date")
		ITV.feedTimes[showcardId] = new Date(date).getTime()
		$($(html).get().reverse()).each(function() {
			if (!$("#" + $(this).attr("id")).length) $self.prepend($(this))
		})
	}, "html")
}

jQuery.fn.startFeed = function(showcardId, time) {
	if (!ITV.feedTimes) ITV.feedTimes = {}
	showcardId = showcardId || 0
	time = time || 5000
	var $self = $(this)
	$self.updateFeed(showcardId)

	return setInterval(function() {
		$self.updateFeed(showcardId)
	}, time)
}

jQuery.fn.fetchNews = function(showcardId) {
	var $self = $(this)
	var url = ITV.urls.news.replace(":showcardId", showcardId)
	$.get(url, function(html) {
		if (html.match(/^\s*$/)) $self.closest("article").hide()
		$self.html(innerShiv(html))
	}, "html")
}

jQuery.fn.fetchNewsForUser = function(userId) {
	var $self = $(this)
	var url = ITV.urls.newsForUser
	$.get(url, function(html) {
		if (html.match(/^\s*$/)) $self.closest("article").hide()
		$self.html(innerShiv(html))
	}, "html")
}


jQuery.fn.fetchShowcardRecs = function(showcardId) {
	var $self = $(this)
	$.get(ITV.urls.showcardRecs.replace(":showcardId", showcardId), function(html) {
		if (html.match(/^\s*$/)) $self.closest("article").hide()
		$self.append(innerShiv(html))
	}, "html")
}

jQuery.fn.fetchUserRecs = function() {
	var $self = $(this)
	$.get(ITV.urls.userRecs, function(html) {
		if (html.match(/^\s*$/)) $self.closest("article").hide()
		$self.append(innerShiv(html))
	}, "html")
}

jQuery.fn.setupWallPost = function() {

	var $self = $(this)
	var $submit = $self.find("input[type=submit]")
	var $hidden = $self.find("input[type=hidden]")
	var $text = $self.find("input[name=message]")
	var options = {}
	
	$self.submit(function(e) {
		e.preventDefault()
		if (!ITV.loggedIn) return
		var message = $text.val()
		if (message.length > 140) message = message.slice(0, 140)
		options.message = message
		$hidden.each(function() {
			var name = $(this).attr("name")
			var val = $(this).val()
			options[name] = val
		})
		if (!message) return
		$.post($self.attr("action"), options, function(html, status, jqXHR) {
			$text.val("")
			var id = jqXHR.getResponseHeader("ActivityId")
			if (!$("#" + id).length) $("article.feed ul.feed").prepend(html)
		})
	})
	
	$text.keypress(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
	        e.preventDefault()
	        $submit.trigger("click");
        }
    })	

	$submit.click(function submitWallPost(e) {
		e.preventDefault()
		$(this).closest("form").trigger("submit").get(0).reset()
	})
	
}


// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function(callback, element){
				window.setTimeout(callback, 1000 / 60);
          };
}());
