var eCardFont = 'mtcorsva';

function showSendECardForm(url,width) {
        LoadingDialog.setText('Loading...');
        LoadingDialog.show();
        sendECardDialog = DialogManager.createDialog({
                withTitle: false,
                borderLeft: 'solid 5px #E9E9E9',
                borderRight: 'solid 5px #E9E9E9',
                borderTop: 'solid 5px #E9E9E9',
                borderBottom: 'solid 5px #E9E9E9',
                bodyPadding: "5px",
                dialogWidth: (width+36)+"px"
        });

        sendECardDialog.loadContentFrom(url, null, function() {
                LoadingDialog.hide();
                var content = sendECardDialog.getContent(),
                        closeButton = $(Builder.node('span', {style: "float: right"})),
                        img = $(Builder.node('img', {src: '/i/actions/delete.gif', title: "Close", style: "cursor: pointer"})),
                        testNode = $(Builder.node('div'));
                closeButton.appendChild(img);
                testNode.appendChild(closeButton);
                sendECardDialog.setContent(testNode.innerHTML+content);
                img=$(sendECardDialog.getContainer().getElementsByTagName('img').item(0));
                Event.observe(img, 'click', function() {if(sendECardDialog!=null) {sendDeleteCode(url);sendECardDialog.destroy();}});
        });

        return false;
}

function sendDeleteCode(url) {
        new Ajax.Request(url+'?close=1',
                {
                        method: 'post'
                }
        );
}

function showEcardPreview(id, type, message, withSend, email) {
	if (message.blank()) {
		$('tdiv').innerHTML = 'You should write a message!';
		$('tdiv').show();
	} else {
		$('tdiv').hide();
		$('cardindicator').show();
		message = message.gsub(/[\\\/\%]/, '');
		if (!message) {
			message = '_';
		}
		$('ecardPicture').src = '/ecard/' + id + '/' + eCardFont + '/' + type + '/' + encodeURIComponent(message) + '.jpeg';
		setTimeout("$('cardindicator').hide()", 3000);
		if (withSend) {
			setTimeout('sendEcard2Email(' + id + ', ' + type + ', \'' + message + '\', \'' + email + '\')', 3500);
		}
	}
}

function setECardFontValue(fname) {
	eCardFont = fname;
}

function sendEcard2Email(id, type, message, email) {
	$('cardindicator').hide();
	if (message.blank() || email.blank()) {
		$('tdiv').innerHTML = 'You should fill all fields!';
		$('tdiv').show();
	} else {
		$('tdiv').innerHTML = 'sending...';
		$('tdiv').show();
		new Ajax.Request('/eCard/sendEcard2Email', {
			method: 'post',
			parameters: { id: id, type: type, font: eCardFont, message: message, email: email },
			onSuccess: function(transport) {
				if (transport.responseText == 'ok') {
					$('tdiv').innerHTML = 'ECard sent!';
				} else {
					$('tdiv').innerHTML = 'Internal error occured while sending email. Please try again later.';
				}
			}
		});
	}
}