// prefix integer with zero when nessessary
function pad(val) {
	val = parseInt(val, 10);
	return val >= 10 ? val : "0" + val;
}

// display seconds in hh:mm:ss format
function secondsToTime(sec) {

	var h = Math.floor(sec / 3600);
	var min = Math.floor(sec / 60);
	sec = sec - (min * 60);

	if (h >= 1) {
		min -= h * 60;
		return pad(h) + ":" + pad(min) + ":" + pad(sec);
	}

	return pad(min) + ":" + pad(sec);
}

// convert time (hh:mm:ss, mm:ss or ss) to seconds. Will return NaN if time is not correctly formatted (parseInt failed or too many : segments).
function timeToSeconds(time) {
	var el = time.split(':');
	if (el.length == 1) {
		return parseInt(el[0], 10)
	} else if (el.length == 2) {
		return parseInt(el[1], 10) + 60*parseInt(el[0], 10);
	} else if (el.length == 3) {
		return parseInt(el[2], 10) + 60*parseInt(el[1], 10) + 60*60*parseInt(el[0], 10);
	}	
	return NaN;
}

// convert bytes to human-friendly format
function readablizeBytes(bytes) {
	bytes = parseInt(bytes);
	if (bytes < 0) {
		bytes = 0;
	}

	var s = ['bytes', 'kb', 'MB', 'GB'];
	var p = [0, 0, 1, 2, 3];

	var pow = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
	pow = Math.min(pow, 3);
	var bytes = bytes / (1 << (10 * pow));

	return bytes.toFixed(p[pow]) + ' ' + s[pow];
}

// open show asset overlay
function open_show_asset_overlay(asset_id, type)
{
	if(type == 'file'){
		openOverlay({url: 'assets/popup/show_asset/' + project_id + '/' + asset_id,  callback: overlayClosed});
	} else {
		openOverlay({url: 'assets/popup/show_asset/' + project_id + '/' + asset_id, iframe_class: 'wide',  callback: overlayClosed});
	}
}

function openSetResourcePermissionsOverlay(resource_id)
{
	openOverlay({url: 'permissions/set_resource_access/' + project_id + '/' +  resource_id, iframe_class: 'medium'});
	return false;
}

// split too long filenames in order to have proper wrapping
function splitTooLongName(string, piece_length, string_length){

	var parts = string.split(' ');
	for(i in parts){
		if(parts[i].length > piece_length){
			parts[i] = [parts[i].substr(0,piece_length), parts[i].substr(piece_length,piece_length), parts[i].substr((piece_length*2),piece_length)].join(' ');
		}
	}
	string = parts.join(' ');

	if(string.length > string_length) {
		string = string.substr(0, string_length) + '...';
	}
	return string;
}

function handleError(result)
{
	if (result.result == 'error') {
		alert(result.error);
		return true;
	}
	return false;
}

function getAvatarUrl(avatar_url)
{
	if (avatar_url.substr(0, 4) != 'http') {
		avatar_url = uploaded_media_url + avatar_url;
	}
	return avatar_url;
}

function htmlspecialchars (string, quote_style, charset, double_encode) {
	// http://kevin.vanzonneveld.net
	// +   original by: Mirek Slugen
	var optTemp = 0,
		i = 0,
		noquotes = false;
	if (typeof quote_style === 'undefined' || quote_style === null) {
		quote_style = 2;
	}
	string = string.toString();
	if (double_encode !== false) { // Put this first to avoid double-encoding
		string = string.replace(/&/g, '&amp;');
	}
	string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');

	var OPTS = {
		'ENT_NOQUOTES': 0,
		'ENT_HTML_QUOTE_SINGLE': 1,
		'ENT_HTML_QUOTE_DOUBLE': 2,
		'ENT_COMPAT': 2,
		'ENT_QUOTES': 3,
		'ENT_IGNORE': 4
	};
	if (quote_style === 0) {
		noquotes = true;
	}
	if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
		quote_style = [].concat(quote_style);
		for (i = 0; i < quote_style.length; i++) {
			// Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
			if (OPTS[quote_style[i]] === 0) {
				noquotes = true;
			}
			else if (OPTS[quote_style[i]]) {
				optTemp = optTemp | OPTS[quote_style[i]];
			}
		}
		quote_style = optTemp;
	}
	if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
		string = string.replace(/'/g, '&#039;');
	}
	if (!noquotes) {
		string = string.replace(/"/g, '&quot;');
	}

	return string;
}

function getFileExtension(filename) {
	return filename.split('.').pop().toLowerCase();
}

function positionFooter(){
    var win_h = ($(window).height());
    var body_h = ($('#container').height())+55;
    if(body_h < win_h){
        $('#container').css(
            {'min-height': win_h-55+'px'}
        );
    }
}

function addOverlayCloseAlert() {
	$('a.close, #exposeMask').unbind();
	$('a.close, #exposeMask').bind('click', function(){
		var prompt = confirm("Are you really sure you want to close upload window? There is upload in progress and this progress will be lost");
		if(prompt){
			closeOverlay();
		} else {
			return false;
		}
	});
}

function addUrlChangeToOverlayClose() {
	$('a.close, #exposeMask').unbind();
	$('a.close, #exposeMask').bind('click', function(){
		removeAssetIdFromUrl();
	});
}

function addReloadParentToOverlayClose() {
	$('a.close, #exposeMask').unbind();
	$('a.close, #exposeMask').bind('click', function(){
		window.location.reload();
	});
}

function removeOverlayCloseAlert() {
	$('a.close, #exposeMask').unbind();
	$('a.close, #exposeMask').bind('click', function(){
		closeOverlay();
	});
}

function getFileExtension(filename) {
	return filename.split('.').pop();
}

function getFileName(filename) {
	return filename.replace('.'+getFileExtension(filename), '');
}

function positionFooter(){
    var win_h = ($(window).height());
    var body_h = ($('#container').height())+55;

    $('#container').css(
        {'min-height': win_h-55+'px'}
    );
}

function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    //var difference_ms = Math.abs(date1_ms - date2_ms)
    
    // Convert back to days and return
    return Math.round((date1_ms - date2_ms)/ONE_DAY)

}

function nl2br(input_string)
{
    return input_string.replace(/(\r\n|\r|\n)/g, '<br />');
}

function setSameHeight( elements ) {
	var max_panel_height = 0;

	elements.each(function(){
		 if($(this).height() > max_panel_height){
			max_panel_height = $(this).height();
		}
	});

	elements.height(max_panel_height);
}

