/* Logo Selector */
function selectAttachable(type, id) {
	if(id == 'nil' || id == '') {
		$(type + '_preview').firstChild.src = 'about:blank';
		$(type + '_preview').firstChild.alt = '';
	} else {
		new Ajax.Request('/' + type + '/select/' + id, {asynchronous:true, evalScripts:true});
	}
}

function updateLogoSelector() {
	new Ajax.Request('/logo/update_selector', {asynchronous:true, evalScripts:true});
}

/* Hide Elements */
function hideHidden() {
	document.getElementsByClassName('hidden').each(function(element) { Element.hide(element); });
}

/* Multipurpose Popup */
function popWindow(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=640,height=480');");
}

/* Login Form Helper */
function submitEnter(e, ev) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (ev) keycode = ev.which;
	else return true;

	if (keycode == 13) {
		e.form.submit();
		return false;
	} else return true;
}

/* Radio Selection Helper */
function radioSelect(e) {
	$(e).checked = true;
}

/* My Account - Print Invoice */
function popPrintInvoice(oid) {
	day = new Date();
	id = day.getTime();
	URL = '/order/print_invoice/' + oid;
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=720,height=480');");
}

/* Personalization - Word Count */
function updateSummaryMessage(source) {
	if(source.value.length < 128) {
		$('summary_note_message').innerHTML = source.value.substr(0, 128) + "...";
	}

}

function updateWordCount(source, indicator, limit) {
	text = source.value;
	count = 0;
	text = text.replaceAll('\n', ' ');
	text = text.split(' ');
	for(i = 0; i < text.length; i++) {
		if (text[i].length > 0) count++;
	}

	diff = limit - count;
	plur = Math.abs(diff) == 1 ? 'word' : 'words';

	if (diff >= 0) {
		indicator.innerHTML = diff;
		$('condition').innerHTML = plur + ' left';
	} else {
		indicator.innerHTML = Math.abs(diff);
		$('condition').innerHTML = plur + ' too many';
	}
}

/* frt_multipart patch */
function evalScripts(t){eval(t);}

// Replaces all instances of the given substring.
String.prototype.replaceAll = function(
	strTarget, // The substring you want to replace
	strSubString // The string you want to replace in.
	){
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );

	// Keep looping while an instance of the target string
	// still exists in the string.
	while (intIndexOfMatch != -1){
	// Relace out the current instance.
	strText = strText.replace( strTarget, strSubString )

	// Get the index of any next matching substring.
	intIndexOfMatch = strText.indexOf( strTarget );
	}

	// Return the updated string with ALL the target strings
	// replaced out with the new substring.
	return( strText );
}
