/*
 * Use of '(function () {})()' cunstruction allow us to hide all js code from
 * outside world.
 *
 * (<i>js literal</i>)() - this snippet creates <i>js literal</i> and
 * executes it, in our case js literal is a function that take no parameters
 * and executes some code.
 */

(function ()
{
	/*
	 * Initialization steps
	 */
	YAHOO.util.Connect.setDefaultPostHeader(false);
	YAHOO.util.Connect.initHeader("Content-Type", "application/json; charset=utf-8", true);
	Ext.QuickTips.init();

	/*
	 * Create constructor for send email form,
	 * below we will extend it by Ext.form.Form
	 */
	/**
	 * @constructor Constructor of sendEmail form
	 */
	function sendEmailForm(config)
	{
		sendEmailForm.superclass.constructor.call(this, config);

		// this function is private in relation to sendEmailForm class
		function initFormElements()
		{
			var fieldConfig = {
				width: 300,
				allowBlank: false,
				msgTarget: 'side'
			};

			this.add(
				new Ext.form.TextField(Ext.applyIf({fieldLabel: '<b>Your&nbsp;Name</b>', name: 'senderName'}, fieldConfig)),
				new Ext.form.TextField(Ext.applyIf({fieldLabel: '<b>Your&nbsp;Email</b>', name: 'senderEmail', vtype: 'email'}, fieldConfig)),
				new Ext.form.TextField(Ext.applyIf({fieldLabel: '<b>Friend&nbsp;Name</b>', name: 'recipientName'}, fieldConfig)),
				new Ext.form.TextField(Ext.applyIf({fieldLabel: '<b>Friend&nbsp;Email</b>', name: 'recipientEmail', vtype: 'email'}, fieldConfig))
			);
		}

		this.container = null;
		this.action = 'Send-to-Friend.aspx';
		this.connection = new Ext.data.Connection();

		initFormElements.call(this);
	}

	/*
	 * Extend our form with Ext.form.Form and add additional public methods
	 * by passing it in third parameter to Ext.extend
	 */
	Ext.extend(sendEmailForm, Ext.form.Form,
	{
		render : function (container)
		{
			this.container = Ext.get(container)
			sendEmailForm.superclass.render.call(this, container);
		},
		submit : function ()
		{
			if (!this.isValid()) return false;

			var params = new Object;
			this.items.each(function (i) { params[i.name] = i.getValue(); });

			obj = document.getElementById('ListingId');
            params["ListingId"] = obj.value;

			dialog.getEl().mask('Sending Message to Friend...', 'x-mask-loading');

			this.connection.request({
				url: this.action,
				params: params,
				method: 'GET',
				callback: function (options, success, response)
				{
					dialog.getEl().unmask();

					if (response.responseText == 'success')
					{
    					dialog.messageSent = true;
	    				dialog.body.mask('Your message has been successfully sent', 'x-mask-message');
		    			dialog.buttons[0].hide();
		    			dialog.buttons[1].hide();
		    			dialog.buttons[2].show();

			    		var delayedHide = new Ext.util.DelayedTask(dialog.hide, dialog).delay(5000);	// auto hide after 5 seconds
					}
					else
					{
                        dialog.messageSent = false;
                        dialog.body.mask('Your message failed to send. Please try again', 'x-mask-error');

                        var delayedHide = new Ext.util.DelayedTask(dialog.body.unmask, dialog.body).delay(5000);

        				/*	var responseObject = Ext.util.JSON.decode(response.responseText)

		    			if (!success) {
			    			this.markInvalid(responseObject.errors)
			    			return false
			    		}
			    		*/
					}
				},
				scope: this
			})
		}
	});

	function sendEmailDialog(el, config)
	{
		sendEmailDialog.superclass.constructor.call(this, el, config);
		this.messageSent = false;	// this flag indicates if message from form inside dialog are sent
	}

	Ext.extend(sendEmailDialog, Ext.BasicDialog,
	{
		hide: function ()
		{
			sendEmailDialog.superclass.hide.call(this);

			if (this.messageSent)	// reset form
			{
				form.items.each(function (i) { i.setRawValue(''); });
				this.body.unmask();
				this.buttons[0].show();
				this.buttons[1].show();
				this.buttons[2].hide();
				this.messageSent = false;
			}
		}
	});

	var form = new sendEmailForm({
		labelWidth: 80,
		buttonAlign: 'center',
		autoCreate: {tag: 'div'}
	});

	var dialog;		// create dialog later, because it renders in constructor call

	/*
	 * Above this line we create all object and done work that don't need
	 * interation with DOM tree. Now we add listener to documentReady event.
	 * This event occur when DOM tree loaded, but images & external resources
	 * don't.
	 */
	Ext.EventManager.onDocumentReady(function ()
	{
		// render form to DOM element with passed ID
		dialog = new sendEmailDialog('dialog-box', {
			width: 450,
			height: 215,
			shadow: true,
			modal: true,
			proxyDrag: true,
			collapsible: false,
			resizable: false
		});

		dialog.addKeyListener(27, dialog.hide, dialog);		// ESC can also close the dialog
		dialog.addButton('Send', form.submit, form);
		dialog.addButton('Cancel', dialog.hide, dialog);
		dialog.addButton({text: 'Close', hidden: true}, dialog.hide, dialog);

		var button = document.getElementById('SendListingToFriendButton');
		button.onclick = function () { dialog.show(this); return false; }

        form.render('form-box');
	});
})()


