
var uri = new URI(window.location);
var currentURL = uri.get('directory')+uri.get('file');
// console.log('URI:'+uri+', URL:'+currentURL);
if (currentURL != '/web/guest/noflash' && swfobject.getFlashPlayerVersion().major < 10) {
	window.location = '/web/guest/noflash?url=' + encodeURIComponent(window.location);
}
else if (currentURL == '/web/guest/noflash' && swfobject.getFlashPlayerVersion().major >= 10) {
	if (uri.getData().url) window.location = uri.getData().url;
}


var InstanceRegister = new Class({
	instances: [],
	addInstance: function(object) {
		this.instances.push(object);
	},
	broadcastMessage: function(msg) {
		$A(this.instances).each(function(item, index) {
			item.processMessage(msg);
		});
	}
});
var Register = new InstanceRegister();


var Base = new Class({
	ClassName: 'Base',
	Implements: Options,
	initialize: function(options) {
		this.setOptions(options);
		Register.addInstance(this);
	},
	processMessage: function(msg) {
		// For inheritance
	},
	sendMessage: function(msg) {
		Register.broadcastMessage(msg);
	}
});

var MonsterAPI = new Class({
	ClassName: 'MonsterAPI',

	login: function(username, password, movieId, callback) {
		// console.log('Monster.login... ', username, movieId, callback);
		this.username = username;
		this.password = password;
		if (themeDisplay.isSignedIn()) {
			console.warn('ERROR: User already logged in.');
			return;
		}

		this.casFrame = $("casloginiframe");
		if (!$defined(this.casFrame)) {
			console.warn('ERROR: MonsterAPI: CAS frame not found.');
		} else {
			this.setupCASFrame();
		}
	},

	setupCASFrame: function() {
		// console.log('Monster.login: setting up login form...');
		this.casFrame.removeEvents('load');
		this.casFrame.addEvent('load', function() { this.submitCASForm() }.bind(this));
		var uri = new URI(window.location);
		var src = '/cas/login?service=' + encodeURIComponent('http://' + uri.get('host') + (uri.get('port') && uri.get('port') != 80 ? ':'+uri.get('port'):'') + '/c/portal/login');
		// console.log('CAS form action: ', src);
		this.casFrame.set('src', src);
	},

	submitCASForm: function() {
		// console.log('Monster.login: submitting login form...');
		// Get form inside of frame
		this.casForm = $(this.casFrame.contentWindow.document.body).getElement('#fm1');
		if (!$defined(this.casForm)) {
			console.warn('ERROR: Monster.login: CAS form not found.');
			return;
		}

		// Submit login form
		this.casForm.set('target', "_parent");
		this.casForm.elements['username'].value = this.username;
		this.casForm.elements['password'].value = this.password;
		this.casForm.submit();
	},

	logout: function() {
		// console.log('Monster.logout...');
		window.location = "/c/portal/logout?url=" + encodeURIComponent(window.location);
	},

	flashMovie: function(movieName) {
		if(navigator.appName.indexOf("Microsoft") != -1) {
			return window[movieName];
		}
		else {
			return document[movieName];
		}
	},

	msecToMinSec: function(milliseconds) {
		var seconds = Math.round(milliseconds/1000);
		var minutes = Math.floor(seconds/60);
		return this.zeroPad(minutes,2) + ':' + this.zeroPad(seconds%60,2);
	},

	zeroPad: function(num, digits) {
		var result  = num.toString();
		while (result.length < digits) result = '0' + result;
		return result;
	},

	dateToISO8601: function(timestamp) {
		return  this.zeroPad(timestamp.getFullYear(),4) + this.zeroPad(timestamp.getMonth()+1,2) + this.zeroPad(timestamp.getDate(),2) + 'T' +
				this.zeroPad(timestamp.getHours(),2)    + this.zeroPad(timestamp.getMinutes(),2) + this.zeroPad(timestamp.getSeconds(),2) + 'Z';
	},

	dateFromISO8601: function(timestamp) {
		var date = new Date();
		date.setFullYear(timestamp.substr(0,4), parseInt(timestamp.substr(4,2), 10) - 1, timestamp.substr(6,2));
		date.setHours(timestamp.substr(9,2), timestamp.substr(11,2), timestamp.substr(13,2));
		return date;
	},

	ellipsis: function(text, count) {
		if (text.length > count) {
			return text.substr(0, count) + '...';
		} else {
			return text;
		}
	},

	location: function(address, city, region, country) {
		var location = address||'';
		if (city) {
			if (location) location += ', ';
			location += city;
		}
		if (region) {
			if (location) location += ', ';
			location += region;
		}
		if (country) {
			if (location) location += ' (' + country + ')'; else location = country;
		}
		return location;
	}
});

var Monster = new MonsterAPI();


/* FOR DEBUGGING ONLY */
var Listener = new Class({
	initialize: function() {
		this.ignoreMessages = false;
		Register.addInstance(this);
	},
	processMessage: function(msg) {
		if (msg.msg == 'stopListener') this.ignoreMessages = true;
		if (msg.msg == 'startListener') this.ignoreMessages = false;
		if (this.ignoreMessages) return;
		console.log('Listener: msg received:');
		if (console.dir) console.dir(msg);
	}
});
new Listener();


/* Extension for DOM Elements */
Element.implement({
	isVisible: function() {
		var el = this;
		while (el) {
			if (el.getStyle('display') == 'none') return false;
			el = el.getParent();
		}
		return true;
	},
	show: function(mode){
		if (!mode) mode = 'block';
		this.set('styles', { 'display': mode });
		return this;
	},
	hide: function(){
		this.set('styles', { 'display': 'none' });
		return this;
	},
	absolutize: function() {
		if (this.getStyle('position') != 'absolute')
			this.setStyles(this.getCoordinates(this.getParent())).setStyle('position', 'absolute');
		return this;
	}
});


if (!$defined(window.console))		{ window.console       = {} }
if (!$defined(window.console.log))	{ window.console.log   = function() {} }
if (!$defined(window.console.dir))	{ window.console.dir   = function() {} }
if (!$defined(window.console.error)){ window.console.error = function() {} }
if (!$defined(window.console.warn)) { window.console.warn  = function() {} }
