$PWT.Class.create
(
	{
		$namespace:	'SC',
		$name:		'Core',
		$traits:
		[
			$PWT.trait.Observable,
			app.trait.Message,
			app.trait.Mask
		]
	}
)
(
	{
		config:
		{
			initMaskEl:	false
		},
		events:
		{
			onLibsReady:	true,
			onReady:		true,
			playerInitiated:true
		},
		API:			null,
		mask:			null,
		maskEl:			null,
		audiocenter:	false,
		ready:			false,
		init:	function()
		{
			Ext.onReady
			(
				function()
				{
//					$PWT.GC.scripts();	//TODO: IE doesn't like this - fix it.
					this.mask=new Ext.LoadMask(Ext.getBody(),{msg:'Loading Page. Please Wait...'});
					this.mask.show();
					this.maskEl=Ext.query('.x-mask-loading').first();
					this.mask.hide();//Note - Added this to hide loading issue until can be resolved later.
					Ext.QuickTips.init();
					$PWT.util.include
					(
						$COREROOT+'direct/API/?event=true',
						'js',
						function()
						{
//							this.mask.hide();
//							if (Object.isDefined(window.google) && Object.isDefined(window.google.loader))
//							{
//								google.load('jquery','1.4');
//								google.setOnLoadCallback(this.onLibsReady.bind(this));
//							}
//							else
//							{
//								$PWT.util.include($SCRIPTS+'new/jquery/jquery-1.4.2.min.js','js',this.onLibsReady.bind(this));
//							}
							
							this.observeOnce
							(
								'onLibsReady',
								function()
								{
									Ext.Direct.onProviderData=Ext.Direct.onProviderData.createInterceptor
									(
										function(provider,e)
										{
											if (Object.isDefined(e.xhr) && /(Fatal error|Parse error)/.test(e.xhr.responseText))
											{
												Ext.Msg.show
												(
													{
														title:	'Server Error',
														msg:	e.xhr.responseText,
														buttons:Ext.Msg.OK,
														icon:	Ext.Msg.ERROR
													}
												);
												throw new Error(e.xhr.responseText);
												return false;
											}
										},
										Ext.Direct
									);
									Ext.Direct.on
									(
										'console',
										function(event)
										{
											if ((Object.isArray(event.data.data) && event.data.data.length>20)
											|| (Object.isArray(event.data.data[0]) && event.data.data[0].length>20))
											{
												console[event.data.type].call(console,{data:event.data.data});
											}
											else
											{
												console[event.data.type].call(console,event.data.data);
											}
										}
									);
									if ($DEBUG)
									{
										Ext.Direct.on
										(
											'exception',
											function(exception)
											{
												Ext.Msg.show
												(
													{
														title:	'Server Exception',
														msg:	exception.message,
														buttons:Ext.Msg.OK,
														icon:	Ext.Msg.ERROR
													}
												);
												var message	=exception.message.match(/Message:\<\/b\> (.*)\<\/p\>/)[1],
													file	=exception.message.match(/File:\<\/b\> (.*)\<\/p\>/)[1],
													line	=exception.message.match(/Line:\<\/b\> (.*)\<\/p\>/)[1];
												throw new Error(message+' in File '+file+' on Line '+line);
											}
										);
									}
//									this.API.Direct.API.enableBuffer=false;
									Ext.Direct.addProvider.apply(Ext.Direct,new this.API.Direct().API);
									//Initiate Search Handlers.
									this.initSearch();
									this.hideMask();
									//Set Player Initiated to false
									window.playerInitiated=false;
									//Set an observer for the player initiated status.
									this.observePlayerInitiated();
									//TODO: Make this behave in IE.
									$PWT.when
									(
										function()
										{
											return !Object.isNull($('launchAudioCenter'));
										}
									).isTrue
									(
										function()
										{
											var ACLink=$('launchAudioCenter');
											if (!Object.isNull(ACLink)
											&& !ACLink.hasClassName('disabled'))
											{
												ACLink.onclick=function()
												{
													this.launchAudioCenterWindow();
												}.bind(this);
											}
										}.bind(this)
									);//.andWhen
		//							(
		//								function()
		//								{
		//									return !Object.isNull($('launchListManager'));
		//								}
		//							).isTrue
		//							(
		//								function()
		//								{
		//									var LMLink=$('launchListManager');
		//									if (!Object.isNull(LMLink) && !LMLink.hasClassName('disabled'))
		//									{
		//										LMLink.onclick=function()
		//										{
		//											this.openListManager();
		//										}.bind(this);
		//									}
		//								}.bind(this)
		//							);
									//Indicate readyness.
									this.fireEvent('onReady',this);
								}.bind(this)
							);
							$PWT.util.include($SCRIPTS+'new/jquery/jquery-1.4.2.min.js','js',this.onLibsReady.bind(this));
						}.bind(this)
					);
				}.bind(this)
			);
		},
		observePlayerInitiated: function()
		{
			window.playerInitiated=false;
			$PWT.when(window,'playerInitiated').isTrue
			(
				function()
				{
					this.fireEvent('playerInitiated');
					$PWT.when
					(
						function()	
						{
							return this.audioCenterIsOpen();
						}.bind(this)
					).isFalse(this.observePlayerInitiated.bind(this));
				}.bind(this)
			);
		},
		initSearch: function()
		{
//			this.simpleSearch	=new SC.search.Simple();
			if (Object.isUndefined(SC.search) || Object.isUndefined(SC.search.Core))
			{
				return;
			}
			this.search			=new SC.search.Core();
			$PWT.when
			(
				function()
				{
					return !Object.isNull($('search_view'));
				}
			).isTrue
			(
				function()
				{
					jQuery('#search_view').click
					(
						function()
						{
							this.search.show();
						}.bind(this)
					);
				}.bind(this)
			).andWhen
			(
				function()
				{
					return !Object.isNull($('search_quick'));
				}
			).isTrue
			(
				function()
				{
					var performSearch=function()
					{
						this.search.show();
						this.search.search.simple.field.query.setValue(jQuery('#search_quick').val());
						this.search.performSearch();
					}.bind(this)
					jQuery('#search_quick').focus
					(
						function()
						{
							var	field	=jQuery('#search_quick'),
								val		=field.val();
							if (val=='Enter search term...')
							{
								field.val('');
							}
						}
					).blur
					(
						function()
						{
							var	field	=jQuery('#search_quick'),
								val		=field.val();
							if (Object.isEmpty(val))
							{
								field.val('Enter search term...');
							}
						}
					).keyup
					(
						function(event)
						{
							var	field	=jQuery('#search_quick'),
								val		=field.val();
							if (!Object.isEmpty(val))
							{
								jQuery('#search_quick_go').attr('disabled','');
								if (event.keyCode==13)
								{
									performSearch();
								}
							}
							else
							{
								jQuery('#search_quick_go').attr('disabled','disabled');
							}
						}
					);
					jQuery('#search_quick_go').click(performSearch);
				}.bind(this)
			);
			
//			this.quick			=new SC.search.Quick();
		},
		onLibsReady: function()
		{
			jQuery.noConflict();
//			window.$=window.$.sequencedJoin(function(element)
//			{
//				if (window.noElement && !element.__extended)
//				{
//					Object.extend(element,Element.prototype);
//					element.__extended=true;
//				}
//				return element;
//			});
			$=$.sequencedJoin(function(element)
			{
				if (window.noElement && !element.__extended)
				{
					Object.extend(element,Element.prototype);
					element.__extended=true;
				}
				return element;
			});
			this.maskEl=$(this.maskEl);
			this.ready=true;
			this.fireEvent('onLibsReady',this);
		},
		onReady: function(callback)
		{
			if (Object.isFunction(callback))
			{
				if (this.ready)
				{
					callback();
				}
				else
				{
					$PWT.when(this,'ready').isTrue(callback);
				}
			}
		},
		launchAudioCenterWindow: function()
		{
			if (!this.audiocenter || this.audiocenter.closed)
			{
				this.audiocenter=window.open($HTTPROOT+'audiocenter/','audiocenter','width=800,height=600,resizable=1,scrollbars=0');
			}
			else
			{
				this.audiocenter.focus();
			}
			return this;
		},
		audioCenterIsOpen: function()
		{
			return (!this.audiocenter || this.audiocenter.closed)?false:true;
		},
		focusAudioCenter: function()
		{
			this.audiocenter.focus();
			return this;
		},
		blurAudioCenter: function()
		{
			this.audiocenter.blur();
			return this;
		},
		compRegister: function()
		{
		    var form = new Ext.FormPanel
		    (
		    	{
			        labelWidth: 75,
			        bodyStyle:'padding:5px 5px 0',
			        width: 450,
			        defaults: {width: 300},
			        defaultType: 'textfield',
			        items:
			        [
			        	{
			                fieldLabel: 'First Name',
			                name: 'firstname',
			                allowBlank: false
			            },{
			                fieldLabel: 'Last Name',
			                name: 'surname',
			                allowBlank: false
			            },{
			                fieldLabel: 'Email',
			                name: 'account_email',
			                allowBlank: false
			            },{
			                fieldLabel: 'Confirm Email',
			                name: 'account_email_confirm',
			                allowBlank: false
			            },{
			                fieldLabel: 'Password',
			                name: 'account_password',
			                inputType: 'password',
			                allowBlank: false,
			                minLength: 6,
			                maxLength: 64
			            }, {
			                fieldLabel: 'Confirm Password',
			                name: 'account_password_confirm',
			                inputType: 'password',
			                allowBlank: false,
			                minLength: 6,
			                maxLength: 64
			            }, {
			            	xtype:	'textarea',
			                fieldLabel: 'Terms and Conditions',
			                width: 350,
			                height: 200,
			                readOnly: true,
			                value:
			                [
			                	'SC Competition Terms Aug 10',
								'Please note that this competition is conducted by the organization identified above (the “Organiser”). SongCentral is not responsible for the conducting of the competition nor does it have any interest in the competition or its outcome. By participating in the competition you acknowledge and agree to the following:\r\n\r\n',
								'1.	SongCentral provides a technical platform for the Organiser to operate the competition and no more\r\n\r\n',
								'2.	 SongCentral is not responsible for the conduct of the competition or any of its outcomes, which are the sole responsibility of the Organiser.\r\n\r\n',
								'3.	All matters to do with the handling of entries, appointment of judges, actual judging,  communications with entrants, and any other aspect of the competition, are the sole responsibility of the Organiser.\r\n\r\n',
								'4.	SongCentral  has no liability for or in respect of any aspect of the competition and/or its conduct.\r\n\r\n',
								'5.	SongCentral does not endorse the competition nor the Organiser, nor is it affiliated with the Organiser in any way, unless expressly stated otherwise'	                	
			                ].join('')
			            }, {
			                fieldLabel: 'I agree to the Terms and Conditions',
			                name: 'terms_agreed',
			                xtype: 'checkbox',
			                inputValue: 1
			            }
			        ]
		    	}
		    );
			var win = new Ext.Window
			(
				{
					items: form,
					width: 500,
					height: 480,
					title: 'Register as a SongCentral Guest',
					resizable: false,
					modal: true,
			        bbar:
			        [
						'->',
				        {
				            text: 'Register',
				            iconCls: 'icon-accept',
				            handler: function()
				            {
				            	if(form.get(4).getValue().length < 6)
				            	{
				            		application.error('Your password must be at least 6 characters long.');
				            		return;
				            	}
				            	
				            	if(form.get(4).getValue().length > 64)
				            	{
				            		application.error('Your password must be at leess than 64 characters long.');
				            		return;
				            	}
				            	
				            	if(form.get(4).getValue() != form.get(5).getValue())
				            	{
				            		application.error('Passwords must match.');
				            		return;
				            	}
				            	
				            	if(!/\w+[@\.]*?\w+/.test(form.get(2).getValue()))
				            	{
				            		application.error('You must have a valid Email Address');
				            		return;
				            	}
				            	
				            	if(form.get(2).getValue() != form.get(3).getValue())
				            	{
				            		application.error('Emails must match.');
				            		return;
				            	}
				            	
				            	if(!form.getForm().isValid())
				            	{
				            		application.error('You must fill out all form fields.');
				            		return;
				            	}
				            	
				            	if(form.get(4).getValue() != form.get(5).getValue())
				            	{
				            		application.error('Passwords must match.');
				            		return;
				            	}
				            	
				            	if(!form.get(7).getValue())
				            	{
				            		application.error('You must accept the terms and conditions.');
				            		return;
				            	}
				            	
				            	application.API.customer.CRUD.create
				            	(
				            		form.getForm().getValues(),
				            		function(response)
				            		{
				            			if(response.success)
				            			{
				            				win.close();
				            				application.message(response.message);
				            			}
				            			else
				            			{
				            				application.error(response.message);
				            			}
				            		}
				            	);
				            }
				        },{
				            text: 'Cancel',
				            iconCls: 'icon-cancel',
				            handler: function()
				            {
				            	win.close();
				            }
				        }
			        ]
				}
			);
			win.show();
		},
		compLogin: function()
		{
		    var form = new Ext.FormPanel
		    (
		    	{
            		method: "post",
            		url: $COREROOT+"login/",
            		standardSubmit: true,
            		border:		false,
			        labelWidth: 85,
			        bodyStyle:'padding:5px 5px 0',
			        width: 450,
			        defaults: {width: 150},
			        defaultType: 'textfield',
			        items:
			        [
			        	{
			        		xtype:	'hidden',
			        		name:	'redirectURL',
			        		value:	'/competition/list/'
			        	},
			        	{
			                fieldLabel: 'Email Address',
			                name: 'email',
			                allowBlank: false
			            },
			            {
			                fieldLabel: 'Password',
			                name: 'password',
			                inputType: 'password',
			                allowBlank: false,
			                minLength: 6,
			                maxLength: 64
			            },
			            {
			            	inputType: 'hidden',
			                name: 'newURL',
							value: window.location
			            }
			        ]
		    	}
		    );
			var win = new Ext.Window
			(
				{
					items: form,
					width: 300,
					height: 117,
					title: 'Login to Song Central',
					resizable: false,
					modal: true,
			        bbar:
			        [
						'->',
				        {
				            text: 'Login',
				            iconCls: 'icon-accept',
				            handler: function()
				            {
				            	form.getForm().submit();
				            }
				        },
				        {
				            text: 'Cancel',
				            iconCls: 'icon-cancel',
				            handler: function()
				            {
				            	win.close();
				            }
				        }
			        ]
				}
			);
			win.show();
		},
		openListManager: function(config)
		{
			this.listmanager=new listmanager(config);
			return;
		}
	}
);
window.application=new SC.Core();
