String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


function displayField(value, useDot,title) {
	if(!title)title="Not Entered"
	if (useDot == undefined) {
		useDot = false;
	}
	if (!value) {
		if (useDot) {
			return '<img class="dot" src="template/icons/dot.png" alt="'+title+'" title="'+title+'" />';
		} else {
			return '';
		}
	} else {
		return value;
	}
}

function displayColor(value, useDot) {
	if ($.isArray(value)) {
		var displayValue ='';
		for (var i=0; i<value.length; i++) {
			if (i >0) {
				displayValue += '/';
			}
			displayValue += value[i];
		}
		return displayValue;
	}	
	return displayField(value, useDot);
}
		
function formatNumber(num) {
	var str = '';
	while (num > 1000) {
		var units = num % 1000;
		num = (num - units) /1000;
	
		//make the units variable  a string
		units = units + '';
		while (units.length < 3) {
			units = "0" + units;
		}
		str = units + (str ? ',' : '') + str;
	}	
	return num + (str ? ',' : '') + str;
}

function log10 (arg) {
  
    return Math.log(arg) / Math.LN10;
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}


function roundToSignificantDigits(number, numDigits) {
	if (!isNumber(number)) {
		return '';
	}
	if(number == 0) {
        return 0;
    }

    //this is the number of digits in the number
    d = Math.ceil(log10(number < 0 ? -number: number));
    
    power = numDigits - d;

    magnitude = Math.pow(10, power);
    shifted = Math.floor(number*magnitude);
    
    return shifted/magnitude;
}

function formatDate(dateStr, formatStr) {
	if (dateStr == null) return displayField(dateStr);
	if (formatStr == undefined) formatStr = "M j, Y <br/> g:ia";
	var date = Date.parseDate(dateStr, "Y-m-d H:i:s");
	if (date) {
		return date.dateFormat(formatStr);
	} else{
		return "Unknown Date";
	}
}
	
function formatMoney(amount) {
	if (amount == 0) {
		return '--';
	}

	return '$' + Math.round(amount,2);
}

function getShortLengthDisplayString(length, abbreviations) {

	if (abbreviations == undefined) {
		abbreviations = true;
	}
	
	if (abbreviations) {
		var words = {
			'seconds' : 'sec',
			'minutes': 'min',
			'hours': 'hr'
		}
	} else {
		var words = {
			'seconds' : 'second',
			'minutes': 'minute',
			'hours': 'hour'
		}		
	}
	
	length = Math.round(length);
	
	if (length < 100) {
		return length + ' ' + words['seconds'];
	}
	
	var minutes = length/60;
	if (parseInt(minutes) != minutes) {
		return '~' + Math.round(minutes) + ' ' + words['minutes'];
	} else {
		return minutes +' '+ words['minutes'];
	}

}

function getLengthDisplayString(length, abbreviations) {
	if (abbreviations == undefined) {
		abbreviations = true;
	}
	
	if (abbreviations) {
		var words = {
			'seconds' : 'sec',
			'minutes': 'min',
			'hours': 'hr'
		}
	} else {
		var words = {
			'seconds' : 'second',
			'minutes': 'minute',
			'hours': 'hour'
		}		
	}
	
	length = Math.round(length);
	var seconds = length % 60;
	length -= seconds;
	var minutes = (length % (60 *60)) /60;
	length -= length % (60 *60);
	var hours = length / (60*60);
	
	var minStr ="";
	var hourStr ="";
	var secondsStr ="";
	
	if (minutes > 0) {
		minStr = minutes + ' ' + words['minutes'];
		if (minutes >1 && !abbreviations) {
			minStr += "s";
		}
	}
	
	if (hours > 0) {
		hourStr = hours + ' ' + words['hours'];
		if (hours >1 && !abbreviations) {
			hourStr += "s";
		}
	}
		
	if (seconds > 0) {
		secondsStr = seconds + ' ' + words['seconds'];
		if (seconds >1 && !abbreviations) {
			secondsStr += "s";
		}
	}

	if (hourStr && minStr) {
		return hourStr + ", " + minStr;
	
	} else if (minStr && secondsStr) {
		return  minStr + ", " + secondsStr; 
	} else if (hourStr && secondsStr) {
		return hourStr; 
	} else if (hourStr || minStr || secondsStr) {
		return hourStr + minStr + secondsStr; 
	} 	
	return '0 ' + words['seconds'];
}

function formatBitField(value) {
	if (value ==0) {
		value = "N";
	} else if (value ==1) {
		value = "Y";
	}
	return displayField(value);
}

function formatColor(color,icon) {
	if (!color) {
		return '';
	}
	
	if ($.isArray(color)) {
		var displayValue ='';
		for (var i=0; i<color.length; i++) {
			if (i >0) {
				displayValue += '/';
			}
			displayValue += color[i];
		}
	} else {
		displayValue = color;
	}
	
	switch (displayValue) {
		case 'b&w':
			return displayValue.toUpperCase() + (icon ? ' <img src="template/icons/color-bw.png" alt ="' + displayValue.toUpperCase() + '"/>' :'');
		case 'color':
			return displayValue.toUpperCase() + (icon ? ' <img src="template/icons/color-color.png" alt ="' + displayValue.toUpperCase() + '"/>' : '');
		default:
			return displayValue.toUpperCase() + (icon ? ' <img src="template/icons/color-both.png" alt ="' + displayValue.toUpperCase() + '"/>' : '');
	}
}

function formatCondition(condition, conditionId) {
	if (condition == null) {
		return '<span class="noValue">Not entered</span>';
	}
	return condition + ' <img src="template/icons/condition-' + conditionId + '.png" alt ="' + condition.toUpperCase() + '"/>';

}

function formatTags(tags) {
	var first = true;
	var tmpDiv = $("<div />")
	$.each(tags, function(name, value) {
		if (!first) {
			tmpDiv.append(", ");
		}
		first = false;
		tmpDiv.append(
			$('<span/>')
				.addClass("tag")
				.text(value.tag)
			);
	});
	if (first) 
		return displayField(null);
	return tmpDiv.html();
}

function formatKeywords(keywords) {
	var first = true;
	var tmpDiv = $("<div />")
	$.each(keywords, function(name, value) {
		if (!first) {
			tmpDiv.append(", ");
		}
		first = false;
		
		tmpDiv.append(
			'<abbr title="(' + value.partOfSpeech + ') ' + value.definition + '">' + value.word + '</abbr>'
			
			);
	});
	if (first) 
		return displayField(null);
	return tmpDiv.html();
}

function nl2br(str, filler) {
	if (filler  == undefined) {
		filler = true;
	}
	if (!str && filler) {
		return displayField(str, false);
	}
	str = str.replace("<", "&lt;");
	str = str.replace(">", "&gt;");
	
	str = str.replace("&lt;em&gt;", "<em>");
	str = str.replace("&lt;/em&gt;", "</em>");
	str= str.replace(/\n/g, '<br />');
	return str;
	
}

function formatDateField(str, delimiter, order, useDot) {
	if (str === undefined) {
		return displayField(null, useDot);
	}
	if (delimiter == undefined) {
		delimiter = "/";
	}
	if (order == undefined) {
		order = "mdy";
	}
	if (str.match(/(\d\d\d\d)\-(\d\d)\-(\d\d)/)) {
		switch (order) {
			case 'mdy':
				return RegExp.$2 + delimiter + RegExp.$3 + delimiter +  RegExp.$1;
			case 'ymd':
				return RegExp.$1 + delimiter + RegExp.$2 + delimiter +  RegExp.$3;
		}
		
	} else {
		return "Unknown";
	}
	
}

function displayFieldWbr(value, useDot) {
	if (!value) {
		return displayField(value, useDot);
	}
	//value = value.replace(/([^\w<\/(?=em)])/gi, "$1<wbr>");
	value = value.replace(/(\s|&|\/(?!em)|\-|\.,)/gi, "$1&#8203;");
	
	return  value;
}

function displayRange(start, end, useDot) {
	if (start && end) {
		if (start != end) {
			return displayField(start) +  "-" + displayField(end);
		} else {
			return displayField(start);
		}
	} else if (start) {
		return displayField(start);
	} else if (end) {
		return displayField(end);
	} else {
		return displayField(null,useDot);
	}
}

function displayTCRange(start, end, useDot) {
	if (start && end && start != end) {
	//	var tcStart = new Timecode(start);
	//	var tcEnd = new Timecode(end);
		return '<span class="tcIn">' + start+ '</span> - ' +
			'<span class="tcOut">' +end + '</span>';
	} else {
		return displayField(null,useDot);
	}
}

function displayColorIcon(color) {

	switch (color) {
		case 'color':
			return '<img src="template/icons/color-color.png" alt="'+color+'" title="Color" />';
		case 'b&w':
			return '<img src="template/icons/color-bw.png" alt="'+color+'" title="Black & White" />';
		case 'color / b&w':
			return '<img src="template/icons/color-both.png" alt="'+color+'" title="Mixed Color / BW" />';
		default:
			return '<img src="template/icons/dot.png" alt="Not set" title="Not Set" />';
			
	}

}

function displayConditionIcon(condition, caption) {
	if (condition) {
		return  '<img src="template/icons/condition-'+ condition +'.png" alt="'+caption+'" title="'+caption+'" />';
	}
	return  '<img src="template/icons/dot.png" alt="Not set" title="Not Set" />';
}

function displayCheckMark(value, yesCaption, noCaption) {
	if (value && value != 0) {
		return '<img src="template/icons/checkmark.png" alt="'+ yesCaption +'" title="'+ yesCaption+'" />';
	}
	return '<img src="template/icons/dot.png" alt="'+ noCaption +'" title="'+ noCaption+'" />';

}

function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}

function formatLength(value, useDot) {
	if (value == null) { return displayField(null, useDot); }
	return formatTimecode(value);
}

function formatTimecode(value, includeFrames) {
	if (includeFrames == undefined) {
		includeFrames = false;
	}
	var frames = 0;
	if (!includeFrames) {
		value = Math.round(value);
	} else {
		frames = 0;
	}
	var seconds = value % 60;
	value -= seconds;
	var minutes = (value % (60 *60)) /60;
	value -= value % (60 *60);
	var hours = value / (60*60);
	
	return pad(hours,2) + ":" + pad(minutes,2) + ":" + pad(seconds,2);	
}

function trimFrames(timecodeStr) {
	
	return timecodeStr.substring(0,8);

}

function formatBytes(bytes) {
	if (bytes == 0) {
		return '<span class="error">N/A</span>';
	}
	
	var ext = ['B', 'KB', 'MB', 'GB', 'TB'];
    var unitCount = 0;
    for(; bytes > 1000; unitCount++) bytes /= 1024;
    if (unitCount < 3) {
     	 return Math.round(bytes) +"&nbsp;" + ext[unitCount];
    }
     
     return Math.round(bytes,1) +"&nbsp;"+ ext[unitCount];

	
	/*
	
	var kb = Math.floor(bytes / 1024) + Math.round((bytes % 1024/ 1024)*10)/10 ;
	if (kb < 1024) {
		return Math.round(kb) + "&nbsp;kB";
	}
	var mb = Math.floor(bytes / (1024*1024)) + Math.round((bytes % (1024*1024)/ (1024*1024))*10)/10;
	if (mb < 1024) {
		return Math.round(mb) + "&nbsp;MB";
	}
	var gb = Math.floor(bytes / (1024*1024*1024)) + 
		Math.round((bytes % (1024*1024*1024)/ (1024*1024*1024))*10)/10;
	return gb + "&nbsp;GB";
	*/
}

function getThumbnailFromOffset(id, offset, size, className, specialAccess) {
	if (specialAccess == undefined) {
		specialAccess = false;
	}
	
	var url = "thumbnails/" + id + "/" + size + "/offset/" + offset + '.jpg';
	
	return '<img  class="' +className + '" src="'+ url +'" alt="thumbnail" />';
}

function getThumbnailFromIndex(id, index, size, className, useStrip, clipHash, clipType) {
	if (useStrip == undefined) {
		useStrip = false;
	}
	
	var url = getThumbnailUrlFromIndex(id, index, size, useStrip, clipHash, clipType);
	if (!useStrip) {
		return '<img  class="' +className + '" src="'+ url +'"  alt="thumbnail" />';
	} else {
		var position = getBackgroundPositionFromIndex(index);
		return '<div  class="' +className + '" style="background-image:url(\''+ url +'\');background-position:' + position + '"  alt="thumbnail" />';
	}
}

function getBackgroundPositionFromIndex(index) {
	var pos = index %THUMBNAILS_PER_STRIP * LARGE_THUMBNAIL_HEIGHT;
	return "0px -" + pos + "px";
}

function getThumbnailUrlFromIndex(id, index, size, useStrip, clipHash, clipType) {
	if (useStrip == undefined) {
		useStrip = false;
	}
	if (clipHash == undefined) {
		clipHash = false;
	}
	//var url = "thumbnail.php?id=" + id + "&size=" + size + "&index=" + index;
	var basePath = "thumbnails/";
	if (clipHash) {
		basePath += clipType + '/' + clipHash + '/';
	} else {
		basePath += id + '/';
	}
	if (useStrip) {
		var stripNum = Math.floor(index /THUMBNAILS_PER_STRIP);
		var url = basePath + size + "/strip/" + parseInt(stripNum) + '.jpg';
	} else {
		var url = basePath + size + "/index/" + parseInt(index) + '.jpg';
	}
	return url;
}

function getThumbnail(doc, number, size, className) {
	if (doc.hasvideo) {
		var url = 'thumbnails/' + doc.file + '_' + doc.id + '/' + 
			doc.file + '_' + doc.id + '_thumb_' + size +'_' + pad(number, 3)+ '.jpg';
		return '<img  class="' +className + '" src="'+ url +'" alt="thumbnail" />';
	} else {
		//$("#result" + doc.id + ' .info').prepend('<img class="' +className + '" src="'+ url +'" alt="thumbnail" />');
		return '<img class="' +className + '" src="template/icons/thumbnail.png" alt="thumbnail" />';
	}
}

function unCamelCaseify(string){
	string=string.replace(/([A-Z])/g, ' $1')
    string=string.replace(/^./, function(str){ return str.toUpperCase(); })
	return string;
}

function capFirst(string){
	string=string.toLowerCase()
	string=string.substr(0,1).toUpperCase()+string.substr(1);
	return string;
}

function createPositionBar(tapeLength, start, end, width) {
	tapeLength = Number(tapeLength);
	if (!tapeLength) {
		return '<div class="outside" style="width:' + width + 'px">&nbsp;</div>';
	}
	end = (end == -1) ? tapeLength : end;
	var beforeWidth = Math.floor((start/tapeLength)  * width);
	var clipWidth = Math.max(2,Math.ceil(((end - start)/tapeLength) *width));
	var afterWidth = width - (beforeWidth + clipWidth);
	
	//Never display a bar that is wider than the width
	beforeWidth = Math.min(beforeWidth, width);
	clipWidth = Math.min(width - beforeWidth, clipWidth);
	
	var afterPos = beforeWidth + clipWidth;
	afterWidth = Math.min(width-afterPos, afterWidth);
	
	
	return '<div class="clip" style="width:' + clipWidth + 'px;left:' + beforeWidth + 'px">&nbsp;</div>';
}

function makeEditable(el, multiline, objectName, idValue, fieldName, defaultText) {
	if (defaultText == undefined) {
		defaultText = "<span>(Click to Edit)<\/span>";
	}
	
	$(el).editInPlace({
		html: false,
		multiline: multiline,
		saveCallBack: function(obj, text, originalContents) {
			
			if ( jQuery("<div/>").append(text).html() == jQuery("<div/>").append(defaultText).html()) {
				text ="";
			} else {
				text = jQuery("<div/>").append(text).text();
			}
			if (text == "") {
				obj.html(defaultText);
			}
			
			if (typeof(updateField) != 'undefined') {
				updateField(objectName, fieldName, text, originalContents, idValue, el);
			}
		},
		outsideClick: 'cancel',
		defaultMarkUp: defaultText,
		
		wysiwyg :false
	});
}

function getRegions(countryId, type) {
	$.ajax ({
		data: {
			action: 'getRegions',
			countryId: countryId
		},
		success: function(data) {
			if (type == 'billing') {
				var select = $("#billing_regionId");
			} else {
				var select = $("#mailing_regionId");
			}
			var regions = $.parseJSON(data);
			select.empty();
			select.append($("<option/>")
				.attr('value', '')
				.text('Select...'));
			var hasRegions = false;
			$.each(regions, function(name, value) {
				hasRegions = true;
				select.append(
					$("<option/>")
						.attr('value', value.id)
						.text(value.name)
				);
			});
			if (!hasRegions) {
				select.prop('disabled', true);
			} else {
				select.prop('disabled', false);
			}
		}
	});
}

