Ext.override(Ext.form.Field, {
    showContainer: function() {
        this.enable();
        this.show();
        this.getEl().up('.x-form-item').setDisplayed(true); // show entire container and children (including label if applicable)
    },
    
    hideContainer: function() {
        this.disable(); // for validation
        this.hide();
        this.getEl().up('.x-form-item').setDisplayed(false); // hide container and children (including label if applicable)
    },
    
    setContainerVisible: function(visible) {
        if (visible) {
            this.showContainer();
        } else {
            this.hideContainer();
        }
        return this;
    }
});  

Ext.BLANK_IMAGE_URL = '/images/ext/resources/images/default/s.gif';

Ext.onReady(function(){
		
	Ext.Ajax.timeout = 120000;
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	
	Set_Entry_Cookies();

	/*********************************************************
	Create Ajax Tooltip for User Info
	**********************************************************/
	UserQuickTip = new Ext.ToolTip({
		target: 'welcome',
		dismissDelay: 30000,
		width: 250,
		html: '<div id="ttConvert"></div><div id="ttLeft"></div><div id="ttStatus"></div><div id="ttEmail"></div>',
		title: 'User Status',
		listeners: {
			show: function (combo, record, index) {
				Ext.Ajax.request({
					url : 'ajax/ajax_get_userinfo.php' , 
					params : { username : document.getElementById('setuserid').value },
					method: 'POST',
					success: function ( result, request ) { 
						var AjaxData = Ext.util.JSON.decode(result.responseText);
						//username, used, status, trialleft
						document.getElementById('ttConvert').innerHTML 	= AjaxData.used;
						document.getElementById('ttStatus').innerHTML 	= AjaxData.status;
						document.getElementById('ttEmail').innerHTML 		= AjaxData.email;
						document.getElementById('ttLeft').innerHTML 		= AjaxData.trialleft;
					},
					failure: function ( result, request) { } 
				});						
			}
		}
	});
	
	/*********************************************************
	Create Tabbed Info Panel
	**********************************************************/	

	var menu_tabs = new Ext.TabPanel({
	    renderTo: 'NavMenu',
	    id: 'MenuTabs',
	    activeTab: 0,
	    width:800,
	    height:400,
	    plain:true,
	    defaults:{autoScroll: true},
	    items:[{
	            title: 'New & Updates',
	            autoLoad:'news.php'
	        },{
	            title: 'How to use',
	            autoLoad:'directions.php'
	        },{
	            title: 'Info',
	            autoLoad:'thanks.php'
	        },{
	            title: 'Donations',
	            autoLoad:'donations.php'
	        }
	    ]
	});

	/*********************************************************
	Create Download Content Info Window
	**********************************************************/

	WinDownload = new Ext.Window({
		el:'download-dlg',
		id:'winDL',
		layout:'fit',
		width:630,
		height:500,
		shadow:true,
		modal:true,
		minWidth:300,
		minHeight:300,
		closeAction:'hide',
		plain: true,
	  items: [ new Ext.Panel({
								id: 'DLPanel',
								collapsible:false,
								width:'100%',
								html: '<div id="dlplayer" align="center"></div><div align="center" style="font-weight: bold; font-size: 10px; color: red; text-decoration: blink;">Your video will be avalible for 24 hours please download your converted video now.</div><div id="dlusage" align="center" style="font-size: 8px"></div><br><br><div style="font-size: 6px" id="dllink" align="center"></div>'
  					 })
  				 ],
		buttons: [{
			text:'Download Video',
			handler: function(){
				if(document.getElementById('sDLurl').value != '')
					window.open (document.getElementById('sDLurl').value,"downloadwindow");
					
			}
		},{
			text: 'PayPal Donation',
			handler: function(){
				WinDownload.hide();
				Create_Paypal_Window();
			}
		},{
			text: 'Close',
			handler: function(){
				WinDownload.hide();
			}
		}]
	});
	
	/*********************************************************
	Create Main Form For Download
	**********************************************************/
	Ext.namespace('Ext.formatdata');
	Ext.formatdata.fmt = [
		['wmv', 'Windows Media Video'],
		['flv', 'Original Flash Video'],
		['mp4', 'Ipod Video (mp4)'],
		['mp4', 'PSP (mp4)'],
		['mov', 'Quicktime Video'],
		['mpg', 'Mpeg Format'],
		['avi', 'AVI format']
	];
	
  var main_form = new Ext.FormPanel({
        labelWidth: 150, // label settings here cascade unless overridden
        url:'process_video.php',
        title : ' &nbsp; ',
        fileUpload: true, 
        frame:true,
        buttonAlign: 'left',
        bodyStyle:'padding:5px 5px 0',
        width: 600,
        defaults: {width: 400},
        defaultType: 'textfield',

        items: [{
                fieldLabel: 'EA Skate Url',
                name: 'skateurl',
                id: 'FLDurl',
                allowBlank:false
            },{
                fieldLabel: 'Flash Video File (.flv)',
        				id: 'FLDupload',
        				name: 'skatefile',
        				inputType: 'file',
        				allowBlank: false,
        				hidden: true,
        				disabled:true
            },	new Ext.form.Checkbox({
									boxLabel: 'Upload FLV file',
									labelSeparator: '',
				        	checked : false,
				        	inputValue: 1,
				        	id: 'uploadcontent',
									listeners: {
										check: function (combo, record, index) {
											Toggle_Upload_Field();
										}
									}
    				}), new Ext.form.ComboBox({
        					store: new Ext.data.SimpleStore({id: 'DS_Format', fields: ['id', 'name'], data : Ext.formatdata.fmt}),
        					fieldLabel: 'Movie Format',
        					id: 'fldFormat',
        					hiddenName:'format',
									displayField:'name',
									valueField: 'id',
        					typeAhead: false,
        					mode: 'local',
        					triggerAction: 'all',
        					editable: false,
        					emptyText:'Select a conversion format...',
        					selectOnFocus: true,
        					allowBlank: false,
        					width:250
    				}), {xtype:'fieldset',
			            title: 'Advance Conversion Options',
			            collapsible: true,
			            collapsed: true,
			            autoHeight:true,
			            defaults: {width: 210},
			            defaultType: 'textfield',
			            items :[{
			                    fieldLabel: 'Video Codec',
			                    value: 'not active yet',
			                    disable: true
			                },{
			                    fieldLabel: 'Video Bitrate',
			                    value: 'not active yet',
			                    disable: true
			                },{
			                    fieldLabel: 'Audio Codec',
			                    value: 'not active yet',
			                    disable: true
			                },{
			                    fieldLabel: 'Audio Bitrate',
			                    value: 'not active yet',
			                    disable: true
			                }
            ]}
        ],

        buttons: [{
					text: 'Convert Movie',
					handler: function(){
						if(main_form.getForm().isValid()){							
							main_form.getForm().submit({
								params:{
									action:'submit',
									StUsername:document.getElementById('setuserid').value
								},
								reset: false,
								waitMsg: 'Converting Video...',
								success: function(form, action){
									Create_Download_Window(action.result.flvurl, action.result.filename, action.result.fmt, action.result.username, action.result.usage);
								},
								failure: function(form, action){	
									Ext.MessageBox.alert('Error Message', action.result.msg); 
									Set_Username(action.result.username);
								}
							});
						}else{
							Ext.MessageBox.alert('Errors', 'Please fill in the required fields');
						}
					}			
				},{
					text: 'PayPal Donate',
					handler: function(){
						Create_Paypal_Window();
					}
				},{
					text: 'Amazon Donate',
					handler: function(){
						window.open ("http://www.amazon.com/Amazon-com-Gift-Certificate/dp/B00067L6TQ","donationwindow");
					}
				}]
    });
		
		/*** Do random Stuff after form is loaded ***/
		Ext.getCmp('FLDupload').defaultAutoCreate.size = 50;
		main_form.render('skate-form');
		main_form.el.enctype = 'multipart/form-data';

		var setuser = document.getElementById('setuserid').value;
		if(setuser.length == 0)
			Ext.getCmp('uploadcontent').disable();

		var preffmt = getCookie('eauserfmt');
		if(preffmt != '')
			Ext.getCmp('fldFormat').setValue(preffmt);

		Ext.getCmp('FLDupload').hideContainer();

	/*********************************************************
	Create PayPal Donation Form
	**********************************************************/
	Ext.namespace('Ext.donationdata');

	Ext.donationdata.amt = [
		['5', '$5 USD'],
		['10', '$10 USD'],
		['25', '$25 USD'],
		['50', '$50 USD']
	];		

    var paypal_form = new Ext.FormPanel({
        labelWidth: 150,
        url:'paypal_gen.php',
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        defaults: {width: 200},
        defaultType: 'textfield',

        items: [{
        				fieldLabel: 'EA Skate UserID',
					      id: 'ppUSERID',
					      name: 'skateusername',
					      emptyText:'Xbox GamerTag or PS3 ID',
					      allowBlank:false
            },{
					      fieldLabel: 'Email Address',
					      name: 'skateemail',
					      emptyText:'joe@example.com',
					      allowBlank:false,
					      vtype:'email'
            },new Ext.form.ComboBox({
			            store: new Ext.data.SimpleStore({id: 'DS_Format', fields: ['id', 'name'], data : Ext.donationdata.amt}),
        					fieldLabel: 'Donation Amount',
        					id: 'ppAMT',
        					hiddenName:'amt',
									displayField:'name',
									valueField: 'id',
        					typeAhead: false,
        					mode: 'local',
        					editable: false,
        					triggerAction: 'all',
        					emptyText:'Select donation amount...',
        					selectOnFocus: true,
        					allowBlank: false
  					})
        ]
    });
      	
		var paypal_pan = new Ext.Panel({
				id: 'PPPanel',
				collapsible:true,
				width:'100%',
				html: '<div id="pptxt" align="center" style="font-weight: bold; font-size: 15px"><br><br>Please enter your username exactly how it is showen on the EA skate site or else you may not get credit instantly for your donation. Case sensitive & No spaces. Also please make sure you have converted at least one video before you donate.<br><br></div>'
	  });

	/*********************************************************
	Create PayPal Donation Window
	**********************************************************/
	WinDonation = new Ext.Window({
		el:'donations-dlg',
		id:'DonationWin',  
		modal:true,
		autoTabs:false,
		width:630,
		height:275,
		shadow:true,
		minWidth:300,
		minHeight:275,
		items: [paypal_pan,paypal_form],
		buttons:[{
				text: 'Make Donation',
				handler: function(){
					if (paypal_form.getForm().isValid()) {
						paypal_form.getForm().submit({
							params:{action:'submit',username:Ext.getCmp('ppUSERID').getValue()}, 
							reset: false,
			   			success: function(form, action) { Submit_Paypal_Form(action.result.code, action.result.title, action.result.amt);
			   																				Ext.MessageBox.alert('Thank you', 'Please wait while you are redirected to Paypal to complete your transaction');},
			   			failure: function(form, action) { Ext.MessageBox.alert('Error Message', action.result.msg); }
						});	
						
					}
					else{
						Ext.MessageBox.alert('Errors', 'Please fill in the required fields');
					}
				}
				},{
				text: 'Cancel',
				handler: function(){
					WinDonation.hide();
				}
		}]
	});
	  
/**** END OF ONLOAD FUNCTION ****/
});



function Toggle_Upload_Field(){
	
	var objfile = Ext.getCmp('FLDupload');
	var objurl  = Ext.getCmp('FLDurl');
	var combo   = Ext.getCmp('fldFormat');
	var store		= Ext.StoreMgr.lookup('DSFormat');
	
	if(objurl.isVisible()){
		objurl.hideContainer();
		objfile.showContainer();
		
		//var store	= Ext.StoreMgr.lookup('DS_Format1');
		//combo.store = Ext.StoreMgr.lookup('DS_Format2');
		//combo.view.store = Ext.StoreMgr.lookup('DS_Format2');
		//combo.view.refresh();	
		Ext.getCmp('fldFormat').reset();

	}else{
		objfile.hideContainer();
		objurl.showContainer();
		
		//var store	= Ext.StoreMgr.lookup('DS_Format2');
		//combo.store = Ext.StoreMgr.lookup('DS_Format1');
		//combo.view.store = Ext.StoreMgr.lookup('DS_Format1');
		//combo.view.refresh();	
		Ext.getCmp('fldFormat').reset();
	}
	
}

//Create Download Window w/ Preview
function Create_Download_Window(flashurl, filename, fmt, username, usage){

		WinDownload.show();

		if(username != ''){
		 document.getElementById('poptitle').innerHTML = 'Converted Video for: '+username;
		 document.getElementById('dlusage').innerHTML = '<font size="2" face="Arial">username: '+username+' ['+usage+'] downloads remaining</font>';
		} 
		
		document.getElementById('dllink').innerHTML = '<font size="2" face="Arial">Download Link: <a href="http://colt45.chemlab.org/ea_skate/getfile.php?v='+filename+'&f='+fmt+'">http://colt45.chemlab.org/ea_skate/getfile.php?v='+filename+'&f='+fmt+'</a></font>';
    document.getElementById('sDLurl').value = 'getfile.php?v='+filename+'&f='+fmt;
    
		//Setup Flash Player
		document.getElementById('dlplayer').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="604" height="360" id="lecteur" align="middle"><param name="movie" value="flvplayer.swf?file=getflv.php?v='+filename+'&autoStart=false&showFs=false" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><embed id="flvmovie" src="flvplayer.swf?file=getflv.php?v='+filename+'&autoStart=true&showFs=false" quality="high" bgcolor="#ffffff" width="604" height="360" name="a" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';	
		
		if(username != ''){
			Ext.getCmp('uploadcontent').enable();
		}
		//Set Username
		Set_Username(username);
		
		//Set Last Save Format
		if(fmt != ''){
			SetCookie('eauserfmt',fmt, 365);
		}else{
			Ext.getCmp('fldFormat').reset();	
		}
		
		//Reset The Form Values
		Ext.getCmp('FLDurl').reset();
		Ext.getCmp('FLDupload').reset();
}


//Paypal Function
function Create_Paypal_Window(){

	WinDonation.show();
	//Set Username if exsist
	if(document.getElementById('setuserid').value != ''){

		Ext.getCmp('ppUSERID').disable();
		Ext.getCmp('ppUSERID').setValue(document.getElementById('setuserid').value);
		Ext.getCmp('ppAMT').focus();
	}

}	

//Submit Paypals Special Form
function Submit_Paypal_Form(code, title, amt){

	document.getElementById('pp_item').value = title;
	document.getElementById('pp_amt').value = amt;
	document.getElementById('pp_return').value = 'http://colt45.chemlab.org/ea_skate/autopay.php?code='+code;
	document.getElementById('paypalreal').submit();

}

//Update Menu Tabs
function reloadTab(){
	var tab = Ext.getCmp('MenuTabs').getActiveTab();
	var updater = tab.getUpdater();
	updater.refresh();
}

function Set_Username(un){
		
		if(un != ''){
			SetCookie('eauser',un, 365);
			document.getElementById('setuserid').value = un;
			document.getElementById('welcome').innerHTML = '<font size="1" face="Arial"><b>welcome back user: '+un+'</b></font>';
	  }
}

//Set Cookie Function
function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

//Get Cookie Value
function getCookie(c_name)
{
if (document.cookie.length>0){
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1){ 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
  } 
}

return "";
}

function Set_Entry_Cookies(){

	un = getCookie('eauser');
	if(un != ''){
		document.getElementById('setuserid').value = un;
		document.getElementById('welcome').innerHTML = '<font size="1" face="Arial"><b>welcome back user: '+un+'</b></font>';
	}
}

function Email_Contact(){
	document.location.href = "mailto:undertoe@chemlab.org?subject=EA Skate Converter";
}