if (!window.console) {
	window.console = {
		log: function () {},
		group: function () {},
		error: function () {},
		warn: function () {},
		groupEnd: function () {}
	};
}

(function($) {
	jQuery.fn.placeholder = function(options) {
		settings = jQuery.extend({
			onClass: false,
			offClass: 'placeholder',
			placeholderSupport: (function(){
				return 'placeholder' in document.createElement('input');
			})()
		}, options);
		return this.each(function() {
			var input = this;
			if(!settings['placeholderSupport']){
				$(input).data('defaultValue', $(input).attr('placeholder'));
				if(settings['offClass'] && $(input).val() == $(input).data('defaultValue')){
					$(input).addClass(settings['offClass']);
				}
			}
			$(input).bind('focus', function(){
				if(!settings['placeholderSupport'] && ($(this).val() == $(this).data('defaultValue'))){
					if (!settings['offClass'] || $(this).hasClass(settings['offClass'])){
						$(this).val('');
					}
				}
				if(settings['onClass']) $(this).addClass(settings['onClass']);
				if(settings['offClass']) $(this).removeClass(settings['offClass']);
			}).bind('blur', function(){
				if(!settings['placeholderSupport'] && !$(this).val().length){
					$(this).val($(this).data('defaultValue'));
					if(settings['offClass']) $(this).addClass(settings['offClass']);
				}
				if(settings['onClass']) $(this).removeClass(settings['onClass']);
			});
			$(input).closest('form').bind('submit', function(){
				if (!settings['offClass'] || $(this).hasClass(settings['offClass'])){
					$(input).val('');
				}
			});
			if(!settings['placeholderSupport']){
				$(input).blur();
			}
		});
	};
})(jQuery);

$(function() {
	$.ajaxSetup({ cache: false });

	$.datepicker.setDefaults({
		dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
		changeMonth: true,
		changeYear: true,
		numberOfMonths: 2,
		showButtonPanel: true,
		showOn: 'both',
		buttonImageOnly: true,
		buttonImage: '/app/images/icons/calendar-gray.gif',
		buttonText: 'Calendar'
	});

	// Override: Set date upon click "Today" button.
	$.datepicker._gotoToday = function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		} else {
			var date = new Date();
			inst.selectedDay = date.getDate();
			inst.drawMonth = inst.selectedMonth = date.getMonth();
			inst.drawYear = inst.selectedYear = date.getFullYear();
			this._setDateDatepicker(target, date);
			this._selectDate(id, this._getDateDatepicker(target));
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	}

	$('input[type=text][placeholder],textarea[placeholder]').placeholder();

	$('.tooltip, .tooltip-info, .tooltip-text, .assign-filter, .tooltip-header, .tooltip-realtime, .tooltip-search').twipsy({
		live: true
	});

	$('#create-jira-issue-action').colorbox({'iframe': true, 'innerWidth': 770, 'height': 400});

	// Enable Bootstrap dropdown menus on hover vs. click
	$('.topbar .nav > li.dropdown').bind({
		'mouseenter': function(e) {
			$('.dropdown-toggle', this).trigger('click');
		},
		'mouseleave': function(e) {
			$(this).removeClass('open');
		},
		'click': function(e) {
			if ($(this).is('.open'))
				e.stopPropagation();
		}
	});

	$('.topbar .nav > li.search form').bind('submit', submit_header_search);
	$('.topbar .nav > li.search .dropdown-menu *').click(function(e) {
		e.stopPropagation();
	});
	$('.topbar .nav > li.search .dropdown-menu *').mouseleave(function(e) {
		e.stopPropagation();
	});

	// Fix to allow text inputs/selects inside of labels to be clicked and not fire off the label's event.
	$('label input[type="text"], label select').live('click', function(e) {
		e.preventDefault();
	});

	/**
	 * Double click prevention.
	 *
	 * NOTE: We make the assumption that the action is complete if an AJAX call completes
	 * so we re-enable any buttons disabled by this code.
	 */
	$(document).ajaxComplete(function() {
		enable_dblclk_prevented_buttons();
	});
	$('button[type="submit"], button.dblclk_prevent').live('click', function(e) {
		if (!$(this).data('events')) {
			e.preventDefault();
			$(this).closest('form').trigger('submit');
		}
		$(this).addClass('dblclk_prevented').prop('disabled', true);
	});
});

function enable_dblclk_prevented_buttons() {
	$('button.dblclk_prevented').removeClass('dblclk_prevented').removeProp('disabled');
}

function twipsy_destroy() {
	$('.twipsy').remove();
}

function popover_destroy() {
	$('.popover').remove();
}

function close_message(el) {
	$(el).parent().fadeOut(250);
}

function submit_form(el, prevent_dblclk) {
	if (prevent_dblclk !== false) {
		if ($(el).hasClass('disabled')) {
			return false;
		}
		$(el).addClass('disabled');
	}

	var frm = $(el).closest('form');

	if (!$.support.placeholder) {
		frm.find('.placeholder').each(function() {
			if ($(this).val() == $(this).attr('placeholder')) {
				$(this).val('');
			}
		});
	} else {
		frm.find('placeholder').each(function() {
			if ($(this).val() == $(this).attr('placeholder')) {
				$(this).val('');
			}
		});
	}

	frm.trigger('submit');

	return false;
}

var delay = (function() {
	var timer = 0;
	return function(callback, ms) {
		clearTimeout(timer);
		timer = setTimeout(callback, ms);
	};
})();

function submit_header_search() {
	var action = {
		'work': '/search-work',
		'users': '/search',
		'groups': '/search-groups'
	}[$('select[name="type"]', this).val()];
	$(this).attr('action', action);
	return true;
}

function my_in_array(arr, obj) {
	for(var i=0; i<arr.length; i++) {
		if (arr[i] == obj) return true;
	}
	return false;
}

function implode(data, separator) {
	if (typeof data == 'object') {
		return data.join(separator);
	}
	return '';
}

function format_currency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";

	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();

	if(cents<10)
		cents = "0" + cents;

	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));

	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function get_as_num(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = 0;
	else
		num = parseFloat(num);
	return num;
}

function bytesToSize(bytes, precision) {
	var kilobyte = 1024;
	var megabyte = kilobyte * 1024;
	var gigabyte = megabyte * 1024;
	var terabyte = gigabyte * 1024;

	if ((bytes >= 0) && (bytes < kilobyte)) {
		return bytes + ' B';
	} else if ((bytes >= kilobyte) && (bytes < megabyte)) {
		return (bytes / kilobyte).toFixed(precision) + ' KB';
	} else if ((bytes >= megabyte) && (bytes < gigabyte)) {
		return (bytes / megabyte).toFixed(precision) + ' MB';
	} else if ((bytes >= gigabyte) && (bytes < terabyte)) {
		return (bytes / gigabyte).toFixed(precision) + ' GB';
	} else if (bytes >= terabyte) {
		return (bytes / terabyte).toFixed(precision) + ' TB';
	} else {
		return bytes + ' B';
	}
}

function strip_protocol(str) {
	str = str.replace('http://', '//');
	str = str.replace('https://', '//');
	return str;
}

