window.euca = window.euca || {};
//String.prototype.ucfirst = function(){return this.replace(/\b([a-z])/gi,function(c){return c.toUpperCase()});};

window.l = window.console && console.log ? function () {console.log.apply(console, arguments);} : $.noop;

$.encodeURIComponent = function(uri){
	return encodeURIComponent(uri.replace(/€/g, '__EURO__')).replace(/__EURO__/g, '%80');
};
$._lang = $._lang || {},
$.lang = function(a){
	return $._lang[a] ? $._lang[a] : a || '';
};
$.addLang = function(a){$.extend($._lang, a)};
$.safeLang = function(a, code){
	if(!a || typeof(a) == 'string') return a;
	code = code || euca._LANGCODE;
	if(a[code])
		return a[code];
	var ret = '';
	$.each(a, function(code, val){
		ret = val;
		return false;
	});
	return ret;
};
$.humanizeSize = function(size){
	size = parseInt(size) || 0;
	var byteSize = Math.round(size / 1024 * 100) * .01;
	var suffix = 'KB';
	if (byteSize > 1000) {
		byteSize = Math.round(byteSize *.001 * 100) * .01;
		suffix = 'MB';
	}
	var sizeParts = byteSize.toString().split('.');
	if (sizeParts.length > 1) {
		byteSize = sizeParts[0] + '.' + sizeParts[1].substr(0,2);
	} else {
		byteSize = sizeParts[0];
	}
	return byteSize+suffix;
};
$.humanizeDuration = function(sec){
	sec = parseFloat(sec.toString().replace(',', '.')) || 0;
	var s = Math.round((sec%60)*100)/100;
	var m = Math.round(((sec - s)/60));
	var h = '';
	if(m > 59){
		var m_ = Math.round((m%60)*100)/100;
		h = Math.round(((m - m_)/60)) + 'h ';
		m = m_;
	}
	return h + m + 'm ' + s + 's';
};
$.count = function(obj){
	var ret = 0;
	$.each(obj, function(){ret++});
	return ret;
};
$.loading = function(){
	if(!$._loading){
		$._loading = $('<div class="ui-widget-overlay"></div>' +
			'<div style="position:absolute;top:0;background:url('+euca.theme_path+'/'+euca.theme+'/images/ajax_indicator_01.gif) no-repeat center"></div>')
			.appendTo('body');
		$._loading.css({zIndex: 10001, width: $(window).width(), height: $(window).height()});
		$(window).resize(function(){
			$._loading.css({width: $(window).width(), height: $(window).height()});
		});
	}
	$._loading.show();
};
$.loadingMsg = function(){
	if(!$._loadingMsg)
		$._loadingMsg = $('<div id="fetchMsg" class="ui-widget ui-state-highlight">'
			+ '<span class="ui-icon ui-icon-signal-diag"></span>'
			+ $._lang._FETCHING + '</div>').appendTo('body');
	$._loadingMsg.show();
};
$.endLoading = function(){$._loading.hide();};
$.endLoadingMsg = function(){$._loadingMsg && $._loadingMsg.hide();};
$.loadScripts = function(p, callback){
	var toLoad = [], t;
	$.each(p, function(){
		var t = this.toString();
		$.fn[t] || toLoad.push(t);
	});
	if(toLoad.length){
		$.ajaxSetup({cache: true});
		$.getJSON(_ROOT + '/load.php?plugin=' + toLoad.toString() + '&callback=?', function(d){
			$.each(d.css, function(){
				$('head').append('<link type="text/css" href="' + this + '" rel="stylesheet"/>');
			});
			var i = 0;
			(function g(){
				if(d.script.length > i)
					$.getScript(d.script[i++], g);
				else callback && callback();
			})();
		});
	} else callback && callback();
};
$.alert = function(str, cb){
	var buttons = {};
	buttons[$.lang('_ACCEPT')] = function() {
		$(this).dialog('close');
	}
	$('<div><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + str +'</p></div>').dialog({
		title: euca.sitename,
		modal: true,
		buttons: buttons,
		close: function(){cb && cb();$(this).remove()}
	});
};

/**
 * @param options : title, message, onClick, buttonA, buttonB
 */
$.confirm = function(options){
	var $dialog,
		buttons = {},
		o = $.extend({
			title: euca.sitename,
			message: '',
			onClick: $.noop
		},options);
	buttons[o.buttonB ? o.buttonB : $.lang('_CANCEL')] = function() {
		$(this).dialog('close');
		o.onClick.call($dialog,false);
	}
	buttons[o.buttonA ? o.buttonA : $.lang('_ACCEPT')] = function() {
		$(this).dialog('close');
		o.onClick.call($dialog,true);
	}
	$dialog = $('<div><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + (o.message) +'</p></div>').dialog({
		title: o.title,
		modal: true,
		buttons: buttons,
		close: function(){$dialog.remove()}
	});
	$dialog.dialog('open');
};
$.prompt = function(options, complete){
	if(complete)
		options = {message: options, complete: complete};
	var o = $.extend({
		cancelName: $.lang('_CANCEL'),
		submitName: 'OK',
		message: '',
		value: '',
		title: euca.sitename,
		fieldType: 'input',
		complete: $.noop,
		width: 300
	}, options);
	var buttons = {};
	buttons[o.cancelName] = function() {
		$(this).dialog('close');
	};
	buttons[o.submitName] = function() {
		$(this).find('form').submit();
	};
	var field = o.fieldType == 'textarea'
		? '<textarea style="resize=none; width:' + (o.width - 34) + 'px;height:60px">' + o.value + '</textarea>'
		: '<input type="text" value="' + o.value + '" style="width: ' + (o.width - 34) + 'px;"/><input type="submit" style="display:none"/>';
	$('<div id="promptDialog" class="ui-state-highlight"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + (o.message) +'</p>\
			<form>' + field + '</form>\
		</div>').dialog({
		title: o.title,
		width: o.width,
		modal: true,
		buttons: buttons,
		close: function(){$(this).dialog('destoy').remove()}
	}).find('form').submit(function(){
		o.complete($(this).find('input, textarea').val());
		$('#promptDialog').dialog('close');
		return false;
	}).find('input:first').focus();
};

/**
 * Creates an icon and returs de jQuery object
 * 
 * @param options {onCLick: func(), icon: 'info', title: '', container: $()}
 */
$.createIcon = function(options){
	var o = $.extend({
		onClick: $.noop,
		icon: 'info',
		title: '',
		container: null,
		cssFloat: 'left'
	}, options);
	
	var $ret = $('<span style="cursor: pointer; float: ' + o.cssFloat + '; border:1px solid transparent; display: inline-block">\n\
			<span class="ui-icon ui-icon-' + o.icon + '"></span>\n\
		</span>')
			.attr('title', o.title)
			.click(o.onClick)
			.hover(function(){$(this).toggleClass('ui-state-hover')});
	
	if(o.container)
		$ret.appendTo(o.container);
	
	return $ret;
};

// DOM functions
$.fn._resize = function(delay){
	return this.setTimeout(function(){this.trigger('resize');}, delay);
};
	//desplaza la ventana para que el elemento se muestre entero
$.fn.inWindow = function(margin, speed){
	margin = margin || 0;
	var o = this.offset(),
		wTop = $(window).scrollTop(),
		wBottom = $(window).height() + wTop,
		targetTop,
		height = this.height() + parseInt(this.css('padding-top')) + parseInt(this.css('padding-bottom')),
		bottom = o.top + height;
	if(o.top < wTop + margin)
		targetTop = o.top - margin;
	else if(bottom > wBottom - margin){
		targetTop = wTop + o.top - wBottom + height + margin;
	}
	if(targetTop){
		if(targetTop < wTop - margin)
			targetTop = o.top - margin;
		$($.browser.webkit ? 'body' : 'html').animate({scrollTop: Math.max(0, targetTop)}, speed);
	}
	return this;
};
	//desplaza la ventana para que el elemento se muestre entero
$.fn.inWindowH = function(options){
	var s = $.extend({
		margin: 0
	});
	var o = this.offset(),
		wTop = $(window).scrollTop(),
		wBottom = $(window).height() + wTop,
		targetTop,
		height = this.height() + parseInt(this.css('padding-top')) + parseInt(this.css('padding-bottom')),
		bottom = o.top + height;
	if(o.top < wTop + s.margin)
		targetTop = o.top - s.margin;
	else if(bottom > wBottom - s.margin){
		targetTop = wTop + o.top - wBottom + height + s.margin;
	}
	if(targetTop){
		if(targetTop < wTop - s.margin)
			targetTop = o.top - s.margin;
		$($.browser.webkit ? 'body' : 'html').animate({scrollTop: Math.max(0, targetTop)}, s.speed);
	}
	return this;
};
$.fn.setTimeout = function(fn, t){
	t = t || 100;
	var dom = this;
	setTimeout(function(){
		fn.call(dom);
	}, t);
	return this;
};
$.fn.exec = function(fn){
	fn.call(this);
	return this;
};
$.fn.newOverlay = function(options){
	return this.each(function(){
		$(this).overlay($.extend(options, {api: true})).load();
	});
};
$.fn.error = function(){
	return this.divMsg('error', 'alert');
};
$.fn.highlighted = function(){
	return this.divMsg('highlight');
};
$.fn.divMsg = function(state, icon){
	state = state || 'default';
	icon = icon || 'info';
	return this.addClass('ui-widget ui-state-' + state + ' ui-corner-all').css('padding', '0.7em').each(function(){
		var content = $(this).html();
		$(this).html('<p><span class="ui-icon ui-icon-' + icon + '" style="float: left; margin-right: .3em;"></span> ' + content + '</p>');
	});
};

(function(){
var lastData;
$.ajaxSetup({
	url: euca.path + '/ajax',
	//cache: false,
	dataType: 'json',
	error: function(request, status, error){
		switch(status){
			case 'timeout':
				msg("El servidor no responde");
				break;
			case 'parsererror':
				msg("Respuesta inesperada del servidor: "+lastData);
				break;
			case 'error':
			case 'notmodified':
			default:
				// comentado porque al cambiar la url si hay una petición ajax (p.e. chat)
				// TODO: buscar una solución
				//msg("Error en la respuesta del servidor."+status);
		}
	},
	//beforeSend: $.loadingMsg,
	//complete: $.endLoadingMsg,
	dataFilter: function(data, type){
		lastData = data;
		return data;
	}
});
}());

$(function(){
	//User
	function setUser(){
		$('#usernav').html('<span>' + $.lang('_WELCOME') + ' ' + euca.uname + '</span> | <a href="'+_ROOT+'/user?op=logout">'+$.lang('Exit')+'</a>');
	}
	if(euca.uid){
		setUser();
	} else if($.fn.login){
		$('#usernav').login({success: setUser});
	}
	
	//logLinks
	if(euca.logLink !== false){//true si no se anula expresamente asignado false.
		$('a').click(function(){
			if(this.hostname == location.hostname)
				return;
			if(this.href.substr(0,4) != 'http')
				return;
			$.ajax({
				data: {
					op: 'logLink',
					ln: this.href
				},
				type: 'post',
				async: false
			});//return false;
		});
	}
});
