/*
 * 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();

	function applyListingForm(config)
	{
		applyListingForm.superclass.constructor.call(this, config);

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

			this.add( new Ext.form.TextArea(Ext.applyIf({fieldLabel: '<b>Message</b>', name: 'applyMessage'}, fieldConfig)) );
		}

		this.container = null;
		this.action = 'apply-listing.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(applyListingForm, Ext.form.Form,
	{
		render : function (container)
		{
			this.container = Ext.get(container);
			applyListingForm.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('Applying Listing...', '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.listingApplyed = true;
	    				dialog.body.mask('Listing has been successfully applyed', '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(2000);	// auto hide after 5 seconds
					}
					else
					{
                        dialog.listingApplyed = false;
                        dialog.body.mask(response.responseText, 'x-mask-error');

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

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

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

			if (this.listingApplyed)	// 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.listingApplyed = false;
			}
		}
	});

	var form = new applyListingForm({
		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 ()
	{
		var button = document.getElementById('ContactEmployerButton');
		if (!button) return;

		var loginUrl = document.getElementById('LoginUrl').value;

		if (loginUrl != '')
		{
			button.onclick = function() { location.href = loginUrl; return false; }
			return;
		}

		// render form to DOM element with passed ID
		dialog = new applyListingDialog('apply-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('Apply', form.submit, form);
		dialog.addButton('Cancel', dialog.hide, dialog);
		dialog.addButton({text: 'Close', hidden: true}, dialog.hide, dialog);

		button.onclick = function () { dialog.show(this); return false; }
        form.render('apply-form-box');
	});
})();

