﻿/// <reference path="jquery-1.3.2-vsdoc.js" />

var month = 0, year = 0, day = 0, eventId;

var firstLoad = true;
var marginValue = -620;
var animationSpeed = 500;

var calendarCache = new Array();
var animationRunning = false;
var mainMargin = 0;

var hoverCount = 0;
var infoContainer = null;
var infoOver = false;

var animateTimeout = 0;
var animateUpcomingTimeout = 0;


function log(x) {
	if (typeof (console) != "undefined")
		console.log(x);
	else
		alert(x);
}


function getCalendar(m, y) {
	$.getJSON("Calendar.ashx?type=dates&month=" + m + "&year=" + y, function(data) {

		$("#calendar").empty();

		for (var i = 0; i < data.dayCount; i++) {
			$("#calendar").append("<div>" + (i + 1) + "</div>");
			if (i == 0)
				$("#calendar div").css("margin-left", 47 * data.startDate);
			if (i == data.day - 1)
				$("#calendar div:nth-child(" + (i + 1) + ")").addClass("today");
			for (var j = 0; j < data.eventDays.length; j++) {
				if (data.eventDays[j] == i + 1) {
					$("#calendar div:nth-child(" + (i + 1) + ")").addClass("event");
				}
			}
		}

		month = parseInt(data.month);
		year = parseInt(data.year);

		$("#calendar_arrows span").html(getMonth(month) + " " + year);

		Cufon.refresh();

		$("div.event").hover(
				function() {
					if (!animationRunning) {
						$(this).addClass("hover");
						hoverCount++;
						day = (typeof (Cufon) != "undefined") ? $(this).find(".cufon-alt").html() : $(this).html();
						var infoTop = $(this).offset().top - 22;
						var infoLeft = $(this).offset().left + ((mainMargin == 0) ? -$("div#info").width() : $(this).width());

						var cacheKey = year + "-" + month + "-" + day;
						if (calendarCache[cacheKey] == null) {
							$.getJSON("Calendar.ashx?type=events&day=" + day + "&month=" + month + "&year=" + year, function(data) {
								calendarCache[cacheKey] = data;
								setCalendarInfo(data, infoTop, infoLeft);
							});
						}
						else {
							setCalendarInfo(calendarCache[cacheKey], infoTop, infoLeft);
						}
						infoContainer = this;

					}
				},
				function() {
					var obj = this;
					hoverCount--;
					$(obj).removeClass("hover");
					setTimeout(function() {
						if (!infoOver && hoverCount < 1) {
							$("div#info").hide();
							hoverCount = 0;
							infoContainer = null;
						}
					}, 100);
				}
			);

		$("div#info").hover(
				function() {
					infoOver = true;
					if (infoContainer != null) $(infoContainer).addClass("hover");
				},
				function() {
					infoOver = false;
					if (infoContainer != null) $(infoContainer).removeClass("hover");
					$(this).hide();
				}
			);

	});

}



function setCalendarInfo(data, infoTop, infoLeft) {

	var eventslist = "";
	for (var i = 0; i < data.events.length; i++) {
		eventslist += "<li id=\"" + data.events[i].id + "\">";
		eventslist += "<div style=\"background: url(event/thumb/" + data.events[i].img + ");\"><img src=\"_img/info-imgcorner.png\" class=\"png\" alt=\"\" /></div>";
		eventslist += "<p><span>" + data.events[i].name + "</span><br />" + data.events[i].type + "<br />" + data.events[i].loc + "</p>";
		eventslist += "</li>";
	}
	$("div#info ul").html(eventslist);
	$("div#info li")
		.hover(function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); })
		.click(function() {
			checkSWF("pause");
			eventId = $(this).attr("id");
			getEvent();
			window.location.hash = year + "/" + month + "/" + day + "/" + eventId;
		}
	);

	$("div#info #arrow").attr("class", mainMargin == 0 ? "right" : "left");

	$("div#info").css({ top: infoTop, left: infoLeft }).show();
}


function getEvent() {

	$("#event_details").html("<div id=\"ajax-loader\"></div>");
	$("#event_title p").html("&nbsp;").stop(true).css("left", 10);
	$("#event_meta").html("&nbsp;");
	clearTimeout(animateTimeout);

	$.getJSON("Calendar.ashx?type=event&eventDetailId=" + eventId, function(data) {

		$("#event_title p").html(data.name);
		if ($("#event_title p").width() > 470) animateTimeout = setTimeout("animateTitle()", 2000);

		$("#event_meta").html(data.date + " " + data.time + ", " + data.loc);

		$("div#event_details")
			.html("<img id=\"event_img\" src=\"event/image/" + data.img + "\" width=\"" + data.width + "\" height=\"" + data.height + "\" alt=\"" + data.name + "\" />" + data.detail + "<br /><br />")
			.jScrollPane({ maintainPosition: false, wheelSpeed: 30, showArrows: true, scrollbarWidth: 15, reinitialiseOnImageLoad: true });

		pageTracker._trackPageview("/event: " + year + "." + month + "." + day + " / " + data.name + " / " + data.loc);
		dcsMultiTrack("DCS.dcsuri", "/#" + year + "." + month + "." + day + " / " + data.name + " / " + data.loc, "WT.ti", "event page")
		
		$("input[name=eventDetailId]").val(eventId);

		var sbUrl = encodeURIComponent(window.location.href.replace("#", ""));
		var sbTitle = encodeURIComponent(data.name + " / " + data.date + " " + data.time + " / " + data.loc);
		$("meta[name=description]").attr("content", decodeURIComponent(sbTitle));
		$("#share-event .facebook").attr("href", "http://www.facebook.com/share.php?u=" + sbUrl + "&t=" + sbTitle);
		$("#share-event .twitter").attr("href", "http://twitter.com/home?status=" + sbTitle + "%3A+" + sbUrl);
		$("#share-event .friendfeed").attr("href", "http://friendfeed.com/?url=" + sbUrl + "&title=" + sbTitle);
		$("#share-event .delicious").attr("href", "http://delicious.com/post?url=" + sbUrl + "&title=" + sbTitle);
		$("#share-event .stumbleupon").attr("href", "http://www.stumbleupon.com/submit?url=" + sbUrl + "&title=" + sbTitle);
		$("#share-event .tumblr").attr("href", "http://www.tumblr.com/share?v=3&u=" + sbUrl + "&t=" + sbTitle + "&s=");
	});

	infoOver = false;
	$("div#info").hide();
	$("div.event").removeClass("hover");
	animationRunning = true;

	if (firstLoad && window.location.hash.length > 9) {
		$("#main").css({ marginLeft: marginValue });
		eventCallback();
	} else {
		$("#main").animate({ marginLeft: marginValue }, animationSpeed, "swing", function() { eventCallback(); });
	}

};


function animateTitle() {
	var width = $("#event_title p").width();
	var left = $("#event_title p").css("left").replace("px", "");
	var diff = 480 - $("#event_title p").width();
	var speed = ($("#event_title p").width() - 460) * 20;
	
	//log("width: " + width + ", left: " + left + ", dif: " + diff + ", speed: " + speed + ", timeout: " + animateTimeout);
	$("#event_title p").stop(true);
	clearTimeout(animateTimeout);
	
	if (left == 10)
		$("#event_title p").animate({ left: diff }, speed, "linear", function() { animateTimeout = setTimeout("animateTitle()", 2000) });
	else if (left == diff)
		$("#event_title p").animate({ left: 10 }, speed, "linear", function() { animateTimeout = setTimeout("animateTitle()", 2000) });
}


function animateUpcomingTitle() {
	var width = $("#upcoming-title p").width();
	var left = $("#upcoming-title p").css("left").replace("px", "");
	var diff = 415 - $("#upcoming-title p").width();
	var speed = ($("#upcoming-title p").width() - 405) * 20;

	//log("width: " + width + ", left: " + left + ", dif: " + diff + ", speed: " + speed + ", timeout: " + animateUpcomingTimeout);
	$("#upcoming-title p").stop(true);
	clearTimeout(animateUpcomingTimeout);

	if (left == 10)
		$("#upcoming-title p").animate({ left: diff }, speed, "linear", function() { animateUpcomingTimeout = setTimeout("animateUpcomingTitle()", 2000) });
	else if (left == diff)
		$("#upcoming-title p").animate({ left: 10 }, speed, "linear", function() { animateUpcomingTimeout = setTimeout("animateUpcomingTitle()", 2000) });
}


function eventCallback() {
	firstLoad = false;
	mainMargin = marginValue;
	animationRunning = false;
	//setTimeout(function() { $("div#event_details").jScrollPane({ maintainPosition: false, wheelSpeed: 30 }); }, 50);
}


function goHome() {
	if (mainMargin != 0) {
		animationRunning = true;
		/*
		if ($.browser.msie && $.browser.version < 8) {
		$("div#event_details").jScrollPaneRemove();
		$("div#event_details").css("overflow", "hidden");
		}
		*/
		$("div#info").hide();
		$("#main").animate({ marginLeft: 0 }, animationSpeed, "swing", function() { mainMargin = 0; animationRunning = false; /*checkSWF("play");*/ });
		window.location.hash = "";
		$("meta[name=description]").attr("content", "Burn Enerji İçeceği'nin kurumsal web sitesi");
	}
}


function getMonth(i) {
	var months = ["OCAK", "ŞUBAT", "MART", "NİSAN", "MAYIS", "HAZİRAN", "TEMMUZ", "AĞUSTOS", "EYLÜL", "EKİM", "KASIM", "ARALIK"];
	return months[i - 1];
}


function trim(str) {
	return str.replace(/^\s+|\s+$/g, '');
}

function validateEmail(str) {
	return str.match(/^[_A-Za-z0-9](([\.\-]?[_a-zA-Z0-9\+]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/);
}

function setEmbedCode() {
	var url = "http://" + document.location.hostname + document.location.pathname;
	var embedCode = "<object width=\"557\" height=\"331\"><param name=\"movie\" value=\"" + url + "_swf/AS3-VideoPlayer.swf\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><param value=\"vp0=" + url + "/_vid/burn_reklamfilmi1_ucurum.flv&vp1=" + url + "/_vid/burn_reklamfilmi2_motor.flv&vdl0=" + url + "/_vid/burn_reklamfilmi1_ucurum.mpg&vdl1=" + url + "/_vid/burn_reklamfilmi2_motor.mpg&vi=" + url + "/_vid/kaplan.jpg&rv=true&autoPlay=false\" name=\"flashvars\"><embed src=\"" + url + "_swf/AS3-VideoPlayer.swf\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" flashvars=\"vp0=" + url + "/_vid/burn_reklamfilmi1_ucurum.flv&vp1=" + url + "/_vid/burn_reklamfilmi2_motor.flv&vdl0=" + url + "/_vid/burn_reklamfilmi1_ucurum.mpg&vdl1=" + url + "/_vid/burn_reklamfilmi2_motor.mpg&vi=" + url + "/_vid/kaplan.jpg&rv=true&autoPlay=false\" width=\"557\" height=\"331\"></embed></object>";
	$("#embed input").val(embedCode).click(function() { $(this).select(); });
}


function closeForwardPage() {
	$("#forward").fadeOut(100, function() {
		$("#forward-bg").fadeOut(300, function() {
			$("#result").html("");
			$(".input").removeClass("warning").find("input").blur();
		});
	});
}


function closeProductPage() {
	animationRunning = true;
	$("#burn").animate({ height: 1, marginTop: 142 }, animationSpeed, "swing", function() { animationRunning = false; /*if (mainMargin == 0) checkSWF("play");*/ }).fadeOut(300);
}


var myInterval;

function checkSWF(event) {
	var flashName = "video";
	var flashMovie = (window[flashName]) ? window[flashName] : document[flashName];
	if (flashMovie.playVid == null) {
		myInterval = clearInterval(myInterval);
		myInterval = setInterval(checkSWF, 2000, event);
	}
	else {
		callFunction(event);
	}
}

function callFunction(event) {
	var flashName = "video";
	var flashMovie = (window[flashName]) ? window[flashName] : document[flashName];
	if (event == "play")
		flashMovie.playVid();
	else if (event == "pause")
		flashMovie.pauseVid();
	else if (event == "download")
		flashMovie.getVideo();
	myInterval = clearInterval(myInterval);
}


jQuery(function() {

	if (window.location.hash.length > 9) {
		var hashArray = window.location.hash.replace("#", "").split("/");
		year = hashArray[0];
		month = hashArray[1];
		day = hashArray[2];
		eventId = hashArray[3];
		getEvent();
		getCalendar(month, year);
	}
	else
		getCalendar();

	$("#cal-reset").click(function() { getCalendar(); });
	$("#cal-forward").click(function() { getCalendar(month + 1, year); });
	$("#cal-back").click(function() { getCalendar(month - 1, year); });

	$("#btn-geri").click(function() { goHome(); });

	$("#btn-burn").click(function() {
		closeForwardPage();
		checkSWF("pause");
		animationRunning = true;
		$("#burn").show().animate({ height: 432, marginTop: -290 }, animationSpeed, "swing", function() {
			animationRunning = false;
			pageTracker._trackPageview("/product page");
			dcsMultiTrack("DCS.dcsuri", "/#burn", "WT.ti", "product page")
		});
	});

	$("#burn a").click(function() {
		closeProductPage();
	});

	$("#share .btn-forward").click(function() { $("#forward-bg").css("filter", "alpha(opacity=70)").fadeIn(100, function() { $("#forward").fadeIn(300); }); });

	$("input[name=senderName]").defaultvalue("Adın Soyadın?").alphanumeric({ allow: ". " });
	$("input[name=senderEmail]").defaultvalue("E-posta Adresin?").alphanumeric({ allow: ".@-_+" });
	$("input[name=receiverName]").defaultvalue("Arkadaşının Adı Soyadı?").alphanumeric({ allow: ". " });
	$("input[name=receiverEmail]").defaultvalue("Arkadaşının E-posta Adresi?").alphanumeric({ allow: ".@-_+" });

	$(".input input")
		.focus(function() { $(this).parent().addClass("focus"); })
		.blur(function() { $(this).parent().removeClass("focus"); })
		.keypress(function(e) { if ((e.which == 13 || e.keyCode == 13)) { return false; } });

	$("#forward .btn-forward").click(function() {

		$("#result").fadeOut(100);

		var input, formFail = 0;

		input = $("input[name=senderName]");
		if (trim(input.val()) == "" || trim(input.val()) == "Adın Soyadın?")
			input.parent().addClass("warning");
		else
			input.parent().removeClass("warning");

		input = $("input[name=senderEmail]");
		if (trim(input.val()) == "" || !validateEmail(input.val()) || trim(input.val()) == "E-posta Adresin?")
			input.parent().addClass("warning");
		else
			input.parent().removeClass("warning");

		input = $("input[name=receiverName]");
		if (trim(input.val()) == "" || trim(input.val()) == "Arkadaşının Adı Soyadı?")
			input.parent().addClass("warning");
		else
			input.parent().removeClass("warning");

		input = $("input[name=receiverEmail]");
		if (trim(input.val()) == "" || !validateEmail(input.val()) || trim(input.val()) == "Arkadaşının E-posta Adresi?")
			input.parent().addClass("warning");
		else
			input.parent().removeClass("warning");

		$(".warning").each(function(i) { formFail++; });

		if (formFail == 0)
			$.ajax({
				type: "POST",
				url: "https://" + window.location.host + "/Inviter.ashx",
				data: $(".input input").serialize(),
				success: function(result) {
					$("#result").html(result).fadeIn(300);
					$("input[name=receiverName], input[name=receiverEmail]").val("").blur();
					pageTracker._trackPageview("/forward success: " + year + "/" + month + "/" + day + "/" + eventId);
					dcsMultiTrack("DCS.dcsuri", "/#forward", "WT.ti", "forwarded event: " + year + "/" + month + "/" + day + "/" + eventId)

				},
				error: function(result) {
					$("#result").html("Sistemde bir hata oluştu, lütfen tekrar dene.").fadeIn(300);
				}
			});
		else
			$("#result").html("Tüm alanları hatasız olarak doldurmalısın!").fadeIn(300);

		$("#result").ajaxStart(function() { $("#forward .btn-forward").css("background-position", "0 -33px").click(function() { return false; }); });
		$("#result").ajaxComplete(function() { $("#forward .btn-forward").css("background-position", "0 0"); });

	});

	$("#btn-close").click(function() {
		closeForwardPage();
	});


	$.getJSON("Upcoming.ashx", function(data) {
		$("#upcoming-title p").html(data.name);
		if ($("#upcoming-title p").width() > 415) animateUpcomingTimeout = setTimeout("animateUpcomingTitle()", 2000);
		$("#upcoming-date-loc").html(data.datetime + " | " + data.loc);
		$("#upcoming-desc").html(data.detail);
		$("#upcoming-thumb").css("background-image", "url(event/thumb/" + data.url + ".jpg)");
		$("#upcoming-detail").click(function() {
			closeForwardPage();
			closeProductPage();
			checkSWF("pause");
			eventId = data.url;
			getEvent();
			window.location.hash = data.urldate + "/" + eventId;
		});
	});

	$("#btn-download").click(function() {
		checkSWF("download");
	});

});

