﻿var hasConsole = typeof console != "undefined" ? true : false;
var E21 = E21 || {};
var WARN_PREFIX = "WARN: ";
var TRACE_PREFIX = "TRACE: ";

var w = $(window), d = $(document);

if (typeof console == "undefined") {
	var console = {
		"log": function (a) { return false; },
		"info": function (a) { return false; },
		"warn": function (a) { return false; },
		"error": function (a) { return false; }
	};
}


function the_timestamp() {
	var date = new Date();
	// TODO: There's probably a build-in JS method
	return date.getFullYear() + "/" + date.getMonth() + "/" + date.getDay() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "." + date.getMilliseconds();
}

/* PERFORMANCE & TRACE */
function performance() {
	function warn(str) {
		if (hasConsole) console.log(the_timestamp() + ": " + WARN_PREFIX + "" + str);
	}

	function write(str) {
		if (hasConsole) console.log(the_timestamp() + ": " + str);
	}

	this.write = write;
	this.warn = warn;
}

var perf = new performance();
var dummy = null;

E21.Public = {
	'helpers': {
		'isInt': function (s) {
			return (s.toString().search(/^[0-9]+$/) == 0);
		}
	}
};

$(function () {
	// Frontpage banner cycle
	var cycleOpts = {
		fx: "fade",
		timeout: 8000,
		speed: 700,
		prev: "div#banner div.prev",
		next: "div#banner div.next"
	};

	$("div.slides").cycle(cycleOpts);

	// 
	$("input[title!='']").hint();

	// To be replaced
	$("ul.menulist li").each(function (i) {
		var a = $("a", this);

		if (i > 0) {

			if (window.location.pathname.indexOf(a.attr("href")) != -1)
				$(this).addClass("active");
		} else {
			if (window.location.pathname == a.attr("href")) $(this).addClass("active");
		};
	});

	// Picture groups
	if ($(".picture-group").length > 0) $(".picture-group").picturegroup();


	// OLD & PREPARE FOR REFACTOR
	var imgRe = new RegExp("\/picture\/(\\d+).*Width=(\\d+).*Height=(\\d+)");
	var t = $("#lightbox-body"), close = $("#lightbox-close"), overlay = $("#lightbox-overlay");
	var groupPictures = $('.picture-group a');
	centerElement(t);

	if ($("div.picture-group").length != 0) $("div.picture-group").picturegroup();

	// Hint forms
	$("input[title!='']").hint("blur");

	// Extend
	try {
		$.extend(pictureData, { 34: { 'ContentID': 42, 'IsGroup': true, 'Pictures': ideakorttiData} });
	}
	catch (e) {
	}

	var 
		generateLinkList = function (list) {
			console.info('generateLinkList() start');

			var _f;
			if (typeof (list) !== 'undefined') {
				if (list.length > 0) {
					_.each(list, function (item) {
						_f = _f + '<a href="' + item.Url + '" class="external-link"><i></i> ' + item.Name + '</a>';
					});
				}
				else {
					_f = '';
				}
			}

			console.info('generateLinkList: ', _f);

			return _f;
		},
		lightboxContentCallback = function (data) {
			console.info('lightboxContentCallback() start', data);

			var _f = '<span id="lb-description">' + data.Description + '</span>';

			console.info(data);

			try {
				if (typeof data.UsedProducts !== 'undefined' && data.UsedProducts.length > 0) {
					var usedProducts = generateLinkList(data.UsedProducts).replace('undefined', '');
					_f = _f +
					'<div id="usedproducts">' +
					'  <div class="heading">Kuvassa käytetyt tuotteet:</div>' +
					'  <div id="usedproducts-links">' +
						usedProducts +
					'  </div>' +
					'</div>';
				}
			}
			catch (ex) {
				console.error(ex);
			}

			console.info('lightboxContentCallback: ', _f);

			return _f;
		};

	var 
		thumbs = $('.picture-group:not(.ideakortti-group) .as-thumbnail a').lightbox({ extraWidth: 24 }),
		singlethumbs = $(':not(.image) > .as-thumbnail a').lightbox({ extraWidth: 30 }),
		ideakuvasto = $('.picture-group.ideakortti-group .as-thumbnail a').lightbox({
			contentCallback: lightboxContentCallback,
			contentCallbackInDescription: true,
			extraWidth: 30
		});

	//console.info('thumbs: ', thumbs, '; ideakuvasto: ', ideakuvasto);

});

function showLightbox(data) {
	var overlay = $("#lightbox-overlay");
	var body = $("#lightbox-body");
	var pictureHolder = $("#lightbox-picture");
	var pictureLinks = $("#lightbox-picture-links");

	var type = data.type;
	var isGroup = data.isGroup;

	var description = data.description;
	var title = data.name;
	var fullUrl = data.fullUrl;
	var iW = data.width;
	var iH = data.height;
	var extra = data.extra;

	pictureHolder.hide();

	if (type == 'picture') {
		var attrs = { "src": data.thumbUrl, "alt": title, "width": (iW > 0 ? iW : 700), "height": (iH > 0 ? iH : 700) };

		var image = new Image();
		var thumbUrl = data.thumbUrl;
		perf.warn("thumbUrl = " + thumbUrl);

		image.src = data["thumbUrl"];
		image.onload = function (e) {
			perf.warn("image.onload()");
			var i = this;
			var img = $("#lb-image");
			img.attr(attrs);
			$("#lb-description").width(iW);
			centerElement(body);
		}

		if (typeof (extra) != "undefined") {
			if (extra.length > 0) {
				// #usedproducts-links
				for (var num in extra) {
					$("<a></a>")
					.attr({ href: extra[num].Url, title: extra[num].Name, "class": "external-link", style: "display: block;" })
					.html("<i></i>" + extra[num].Name)
					.appendTo($("#usedproducts-links"));
				}
			}
		}

		if (title)
			$("#lb-description").show().html(title + ": " + description);

		image = null;
		pictureHolder.show();
	}

	centerElement(body);
	overlay.width(d.width()).height(d.height()).fadeIn("fast");
	body.fadeIn("fast");
}

function hideLightbox() {
	var lb = $("#lightbox-overlay, #lightbox-body");

	data = null;
	var img = $("#lb-image");

	lb.hide();
	img.attr("src", "/includes/images/ajax-loader.gif");
	$("#usedproducts-links a").remove();
}

function centerElement(element) {
	var elem = $(element);
	var posY = w.height() / 2 + d.scrollTop() - elem.height() / 2;
	var posX = w.width() / 2 + d.scrollLeft() - elem.width() / 2;

	elem.css("top", posY);
	elem.css("left", posX);
}




