﻿// (c) 2010 Microsoft Australia


$(document).ready(function () {
	$("a#navhandler").click(function () {
		$("#navlayer").show();
		return false;
	});
	var closeHandler = $("<a id='navclose'>x</a>").prependTo("#navlayer");
	closeHandler.click(function () {
		$("#navlayer").hide();
		return false;
	});
	setViewHeight(true);
	setBrowser();
	if (document.getElementById("containerslots")) {
		prepareSessions();
	}
	if (document.getElementById("chklist")) {
		$("#chklist label:has(input:checked)").addClass("selected");
		$("#chklist label input").click(function () {
			if (this.checked) $(this).parent().addClass("selected");
			else $(this).parent().removeClass("selected");
		});
		$("#chklist label#chkSelect input").click(function () {
			if (this.checked) {
				$("#chklist label input").attr("checked", true);
				$("#chklist label").addClass("selected");
			} else {
				$("#chklist label input").attr("checked", false);
				$("#chklist label").removeClass("selected");
			}
		});
	}
	if (document.getElementById("c_sessions")) {
		$("#c_sessions h3").click(function () {
			$(this).next("ul").toggle();
			$(this).toggleClass("up");
		});
	}
	if (document.getElementById("twhelp")) {
		prepareTwitter();
	}
	if (document.getElementById("mypage")) {
		prepareMyPage();
	}
});
var window_height;
var window_width;
var is_landscape;
var extra_height;
var itempad = 50;
function setBrowser() {
	var b = $(document.body).data("MajorBrowser");
	if (b == 10) {
		$(document.body).addClass("opera");
	} else if (b == 9) {
		$(document.body).css("font-size", "0.9em");
	}
	if (!('ontouchstart' in window) || b == 2) $(document.body).addClass("nonswipe");
	
	if (b != 9) {
		$(window).resize(setViewHeight);
	}
}
function setViewHeight(bset) {
	window_height = parseInt($(window).height() - 10);
	window_width = parseInt($(window).width()) - 5;
	if ($(document.body).data("MajorBrowser") == 9) {
		window_width = document.body.offsetWidth;
		window_height = 300;
	}
	is_landscape = (window_width > window_height) ? true : false;
	if (window.opera) {
		if ($(document.body).data("MajorBrowser") == 10) {
			window_width = 250;
			window_height = 300;
			if (is_landscape) {
				window_width = 400;
				window_height = 200;
			}
			$("html").width(window_width);
		}
	}
	$("#navlayer").width(window_width - 35);
	if (is_landscape) {
		$(document.body).addClass("landscape");
	} else {
		$(document.body).removeClass("landscape");
	}
	$(".twblock .dvtweetbox").width(window_width - parseInt($(".twblock .dvtweetbox").css("marginLeft")) - 10);
}
function prepareMyPage() {
	var aMyPageSession = $("#aMyPageSession");
	aMyPageSession.click(function () {
		aMyPageSession.html('&nbsp;');
		aMyPageSession.addClass("loading");
		$.get(aMyPageSession.attr("call"), function (data) {
			aMyPageSession.replaceWith("<span>" + data + "</span>");
			
		});
		return false;
	});
	$(".remove").click(function () {
		var ar = $(this);
		ar.html('&nbsp;');
		ar.addClass("loading");
		$.get(ar.attr("call"), function (data) {
			if (data == "success") {
				ar.parent().parent("li").remove();
			} else {
				ar.replaceWith("<span>Could not remove!</span>");
			}
		});
	});
}
function prepareTwitter() {
	var txCode = $("#txCode");
	var autosessions = $("#autosessions");
	var autoresults = autosessions.find("#autoresults");
	var btTweet = $("#btTweet");
	var btSignout = $("#btSignout");
	//var twreplys = $(".twreply");
	var txTweet = $("#txTweet");
	//var twretweets = $(".twretweet");
	$("form").submit(function (event) {
		event.preventDefault();
	});
	
	if ($(document.body).data("MajorBrowser") >= 9) {
		txCode.focus(function () {
			$("#twhelp").show();
		});
		txCode.blur(function () {
			$("#twhelp").hide();
		});
		$("#search").show();

	}
	var hook = false;
	txCode.keyup(function () {
		
		$("#twhelp").hide();
		if (txCode.val().length == 0) {
			autosessions.hide();
		} else {

			if (!hook) {
				hook = true;
				window.setTimeout(function () {
					$.post($(document.body).data("SearchUrl"), { l: txCode.val() }, function (data) {
						if (data.length > 0) {
							autosessions.find("div.empty").hide();
						} else {
							autosessions.find("div.empty").show();
						}
						autoresults.html(data);
						autosessions.show();
						hook = false;
					});
				}, 500);
			}
		}
	});
	$("a#sclose").click(function () {
		txCode.val(txCode.attr("oCode"));
		autosessions.hide();
	});
	btTweet.click(function () {
		if (txTweet.val() == "") {
			alert('Write something! Anything!');
			return;
		}
		var val = $(".tbox span").text() + " " + txTweet.val();
		if (val.length > 140) {
			alert("Keep it to 140 characters!");
			return;
		}
		var sid = "";
		if (txTweet.attr("s_id") != "") {
			sid = txTweet.attr("s_id");
		}
		btTweet.addClass("loading");

		$.post($(document.body).data("TwitterUpdateUrl"), { s: val, sid: sid }, function (data) {
			btTweet.removeClass("loading");
			$(data).prependTo(".tw ul");
			txTweet.val('');
		});
		btTweet.ajaxError(function (e, r, s, ex) {
			
			btTweet.removeClass("loading");
			$('<li>Oh oh! Your tweet hasn\'t been posted, try again later.</li>').prependTo(".tw ul");

		});
	});
	btSignout.click(function () {
		btSignout.addClass("loading");
		$.get($(document.body).data("TwitterSignOutUrl"), { c: txCode.attr("oCode") }, function (data) {
			btSignout.removeClass("loading");
			btSignout.parent("div").html(data);
		});
	});
	$("body").delegate(".twreply","click", function () {
		var link = $(this).siblings("a#hlName");
		txTweet.val("@" + link.attr("u_id") + " ");
		txTweet.attr("s_id", link.attr("s_id"));
	});
	$("body").delegate(".twretweet","click", function () {
		var t = $(this);
		var link = t.siblings("a#hlName");
		var sid = link.attr("s_id");
		t.addClass("loading");
		$.post($(document.body).data("TwitterRetweetUrl"), { sid: sid }, function (data) {
			t.removeClass("loading");
			$(data).prependTo(".tw ul");
		});
	});
	lastcolor = parseInt($(".tw ul").find("li:first").css("backgroundColor").substring(1));
	window.setTimeout(refreshTweets, 60000);// 


}
var lastcolor;

function refreshTweets() {

	var mid = $(document.body).data('MaxId');
	if (mid == null || mid == "") {
		return;
	}
	var isauth = $(document.body).data('IsAuth');
	if (isauth == null) isauth = false;

	$.post($(document.body).data("RefreshUrl"), { mid: mid, a: isauth, c: $("#txCode").attr("oCode") }, function (data) {
		// if data is not null, do show an updating butotn for few seconds

		if (data != "") {
			$(".refresh").show();

			window.setTimeout(function () {
				// add one to bg color 242424 -> 343434 
				
				if (isNaN(lastcolor) || lastcolor > 600000) {
					lastcolor = 242424;
				}
				lastcolor += 101010;

				$(data).filter("li").css("background-color", "#" + lastcolor).end().prependTo(".tw ul");

				$(".refresh").hide();
				$(document.body).data('MaxId', $(".tw ul li:first").find("a:first").attr("maxid"));

			}, 1000);
		}
		setTimeout(refreshTweets, 30000);
	});
}
function prepareSessions() {
	extra_height = 88;
	if ($(document.body).data("MajorBrowser") == 9) {
		extra_height = 55;
	}
	var o = new SessionSlots("#containerslots", "#sessionslots");
	o.cssLandscape = "landscape";
	o.Init();
	o.DataBind();
}
function SessionSlots(containersel, sel) {
	this.Jo = null;
	var upSwitch = null;
	var dnSwitch = null;
	var that = this;
	this.container = null;
	this.slots = null;
	this.ActiveSlot = null;
	this.PreviousActiveSlot = null;
	this.cssLandscape = "";
	this.onItemDataBound = null;
	this.onResize = null;
	this.onInit = null;
	var hasTouch = false;
	var container_width = 0;
	this.showSlot = function () {
		var c = (container_width + that.ActiveSlot.paddings) * that.ActiveSlot.index - 20;
		var s = (c < 0) ? "+20px" : "-" + c + "px";
		that.Jo.css("left", s);
	};
	var isEmpty = false;
	this.Init = function () {
		that.slots = createSlots();
		if (that.slots.length == 0) {
			isEmpty = true;
			return;
		}
		setNavSlot();
		if (that.ActiveSlot == null) {
			that.ActiveSlot = that.slots[0];
			that.ActiveSlot.item.addClass("active");
		}
		that.Jo = $(sel);
		that.container = $(containersel);
		dnSwitch = $("<a class='snext'></a>").insertAfter(that.container);
		upSwitch = $("<a class='sprev'></a>").insertBefore(that.container)
		if (!that.ActiveSlot.isLast) {
			dnSwitch.addClass("active");
		}
		if (!that.ActiveSlot.isFirst) {
			upSwitch.addClass("active");
		}
		hasTouch = ('ontouchstart' in window);
		if (typeof (that.onInit) == "function") that.onInit();
	};
	this.DataBind = function () {
		if (!isEmpty) {
			if (typeof (that.onItemDataBound) == "function")
				triggerItemDataBound();
			that.Render();
		}
	};
	this.Render = function () {
		bindSwitch();
		that.showSlot();
		bindWindowResize();
		bindSwipe();
	};
	function triggerItemDataBound() {
		$.each(that.slots, function (i, o) {
			o.item.trigger('itemdatabound', [o.item]);
		});
	}
	function createSlots() {
		var o = $(sel + ">li");
		var oArray = new Array();
		$.each(o, function () {
			var e = sessionSlot(this);
			if (typeof (that.onItemDataBound) == "function") {
				e.item.bind('itemdatabound', that.onItemDataBound);
			}
			if (e.isActive) that.ActiveSlot = e;
			oArray[oArray.length] = e;
		});
		return oArray;
	}
	function setNavSlot() {
		$.each(that.slots, function (i, o) {
			o.SetNextSlot();
			o.SetPrevSlot();
		});
	}
	function sessionSlot(ilo) {
		var o = $(ilo);
		return { item: o,
			index: o.index(),
			isActive: o.hasClass("active"),
			htitle: o.find("h4").text(),
			isFirst: o.is(":first-child"),
			isLast: o.is(":last-child"),
			paddings: calculatePaddings(o),
			SetNextSlot: function () {
				if (that.slots[this.index + 1] != null) this.nextSlot = that.slots[this.index + 1];
				else this.nextSlot = null;
			},
			SetPrevSlot: function () {
				if (that.slots[this.index - 1] != null) this.prevSlot = that.slots[this.index - 1];
				else this.prevSlot = null;
			}
		};
	}
	function calculatePaddings(v) {
		var m = [v.css("margin-left"), v.css("margin-right"), v.css("padding-left"), v.css("padding-right")];
		var ret = 0;
		for (mi = 0; mi < 4; mi++) {
			ret += isNaN(parseInt(m[mi])) ? 0 : parseInt(m[mi]);
		}
		return ret;
	}
	this.track = {};
	this.startTracking = function (e) {
		that.track = {
			startX: e.pageX,
			startY: e.pageY
		};
	};
	this.stopTracking = function () {
		that.track = {};
	};
	this.swipe = function (e) {
		
		var deltaX = e.pageX - that.track.startX;
		if (deltaX < -50) {
			dnSwitch.click();
		}
		if (deltaX > 50) {
			upSwitch.click();
		}
		that.stopTracking();
	};
	var started = false, moving, ended;
	function bindSwipe() {
		if (hasTouch) {
			that.container.bind("touchstart", function (e) {
				e.originalEvent.cancelBubble = true;
				var touches = (e.originalEvent.touches || e.originalEvent.touch && [e.originalEvent.touch] || null);
				if (touches != null) {
					that.startTracking({ pageX: touches[0].pageX, pageY: touches[0].pageY });
					
					started = true;
				}
			});
			// if touchmove, set a flag, reset on touch end

			that.container.bind("touchmove", function (e) {
				if (started) {
					moving = true;
					started = false;
				}
			});
			that.container.bind("touchend", function (e) {
				e.preventDefault();
				if (moving) {
					
					var touches = e.originalEvent.changedTouches;
					if (touches != null) {
						that.swipe({ pageX: touches[0].pageX, pageY: touches[0].pageY, event: e });

					}
				}
				started = false;
				moving = false;
			});
		}
	}
	var allowResize = true;
	function bindSwitch() {
		dnSwitch.click(function () {
			allowResize = false;
			if (that.ActiveSlot.isLast) return;
			upSwitch.addClass("active");
			that.PreviousActiveSlot = that.ActiveSlot;
			that.ActiveSlot = that.ActiveSlot.nextSlot;
			if (that.ActiveSlot.isLast) {
				dnSwitch.removeClass("active");
			}
			that.animate("-");
			return false;
		});
		upSwitch.click(function () {
			allowResize = false;
			if (that.ActiveSlot.isFirst) return;
			dnSwitch.addClass("active");
			that.PreviousActiveSlot = that.ActiveSlot;
			that.ActiveSlot = that.ActiveSlot.prevSlot;
			if (that.ActiveSlot.isFirst) {
				upSwitch.removeClass("active");
			}
			that.animate("+");
			return false;
		});
	}
	this.animate = function (dir) {
		if ($(document.body).data("MajorBrowser") == 9) {
			that.Jo.css("left", "-" + (container_width * that.ActiveSlot.index));
			that.ActiveSlot.item.addClass("active");
			that.PreviousActiveSlot.item.removeClass("active");
		} else {
			that.Jo.animate({ left: dir + "=" + (container_width + that.PreviousActiveSlot.paddings) }, 400, function () {
				allowResize = true;
				that.ActiveSlot.item.addClass("active");
				that.PreviousActiveSlot.item.removeClass("active");
			});
		}
	};
	function fixSizes(bset) {
		if (!allowResize) return;
		var h = 0;
		that.container.width(window_width);
		container_width = that.container.width() - itempad;
		that.Jo.width((that.container.width()) * that.slots.length);
		$.each(that.slots, function (i, t) {
			t.item.width(container_width);
			h = Math.max(t.item.height(), h);
		});
		dnSwitch.height(h);
		upSwitch.height(h);
		that.showSlot();
	}
	function bindWindowResize() {
		$(window).resize(fixSizes);
		fixSizes(true);
		if (typeof (that.onResize) == "function") $(window).resize(that.onResize);
	}
}

