Ext.onReady(function() {
	var elements = Ext.DomQuery.select('tdgicode[source]');
    var el;

    var doTdgiElements = function (el) {
        el = Ext.get(el);

        var divEl = Ext.DomHelper.insertAfter(el, {
            tag: 'div',
            id : Ext.id()
        });


        var collapsed;
        if (typeof el.dom.attributes.collapsed != 'undefined') {
            collapsed = el.dom.attributes.collapsed.nodeValue;
            if (collapsed === 'false') {
                collapsed = false;
            }
            else {
                collapsed = true;
            }
        }
        else {
            collapsed = true;
        }
        var contentPanelCfg = {
                    style      : 'background: #FFF;',
                    border     : true,
                    height     : 'auto',
                    width      : 'auto',
                    autoScroll : true
            };

        if (! collapsed) {
            Ext.apply(contentPanelCfg, contentPanelCfg, {
                autoLoad :  '/tdgi_getcode.php?file=' + el.dom.attributes.source.nodeValue,
                loaded   : true
            });
        }

        //console.log(contentPanelCfg);

        var contentPanel  =  new Ext.Panel(contentPanelCfg);
        var panel = new Ext.Panel({
            renderTo    : divEl,
            title	    : el.dom.attributes.paneltitle.nodeValue || code,
            style       : 'margin-left: 5px; margin-bottom: 10px; padding: 0px;',
            bodyStyle   : 'background: #FFFFFF;',
            collapsed   : collapsed,
            border      : true,
            frame 	    : true,
            collapsible :true,
            bodyCls     : 'entry',
            height      : 'auto',
            width	    : 710,
            //items : [ //contentPanel
            //],
            autoScroll  : true
        });
        panel.on('expand', function() {
            if(!panel.loaded) {
                panel.getUpdater().update({
                    url : '/tdgi_getcode.php?file=' + el.dom.attributes.source.nodeValue
                });
                panel.loaded = true;
            }
            var tsk = new Ext.util.DelayedTask(function() {
                //console.info(panel.el.getHeight());
                if (panel.el.getHeight() > 400) {
                    panel.setHeight(400);
                }
            });
            tsk.delay(200);

        });

        panel.getUpdater().on('update', function() {
            if (panel.el.getHeight() > 400) {
                panel.setHeight(400);
            }
        });
    };

	Ext.each(elements, doTdgiElements);

    var body = Ext.getBody(),
        maskEl;
//	if (Ext.get('extSrchCombo')) {
//		var ds = new Ext.data.Store({
//			url: '/tdgi_wp_postQuery.php',
//			reader: new Ext.data.JsonReader({
//			root: 'records',
//			//totalProperty: 'totalCount',
//			id: 'post_id'
//			}, [
//				{name: 'postTitle', mapping: 'postTitle'},
//				{name: 'postLink', mapping: 'postLink'},
//				{name: 'snippet', mapping: 'postBody'}
//			])
//		});
//		var tpl = new Ext.XTemplate(
//			'<tpl for="."><div class="search-item">',
//				'<div class="search-item-title"><img src="/icons/icons/arrow_go.gif" style="margin-right: 3px;">{postTitle}</div>',
//				'<div class="search-tiem-snippet">{snippet}</div>',
//			'</div></tpl>'
//		);
//
//		var srchCombo = new Ext.form.ComboBox({
//			renderTo	: 'extSrchCombo',
//			id 	     	: 'srchCombo',
//			name		: 'srchCombo',
//			typeAhead	: false,
//			forceSelection	: true,
//			listWidth	: 210,
//			displayField	: 'title',
//			emptyText	: 'Search Here...',
//			width		: 210,
//			tpl		: tpl,
//			loadingText	: 'Querying....',
//			//pageSize	: 10,
//			minChars	: 3,
//			queryDelay	: 10,
//			hideTrigger	: true,
//			itemSelector	: 'div.search-item',
//			store		: ds,
//			onSelect	: function (record) {
//				window.location=record.data.postLink;
//
//			}
//
//
//		});
//	}

	if (Ext.get('contact_us_link')) {
		var contactForm,
            contactFormCt = Ext.get('contact-form-ct');

		contactForm = new Ext.form.FormPanel({
			labelWidth  :  90,
            width       : 1000,
            id          : 'contact-form',
            cls         : 'contact-form',
			defaultType : 'textfield',
			labelAlign  : 'right',
            style       : 'margin: 0px auto; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;',
			bodyStyle   : 'padding: 5px',
            buttonAlign : 'center',
            defaults    : {
                allowBlank : false,
                anchor     : '-10'
            },
			items       : [
				{ 
					name       : 'name',
					fieldLabel : 'Your Name'
				},
                {
                    name       : 'email',
                    fieldLabel : 'Email Address'
                },
                {
                    name       : 'phone',
                    fieldLabel : 'Phone Number'
                },
                {
					xtype      : 'textarea',
                    name       : 'message',
					fieldLabel : 'Message',
                    height     : 100
				}
			],
			buttons : [
				{ 
					text    : 'Send now',
                    height  : 25,
                    width   : 50,
					handler : function () {
						if (contactForm.form.isValid()) {
							contactForm.body.mask('Please wait...', 'x-mask-loading');
                            contactForm.fbar.items.items[0].disable();
                            contactForm.fbar.items.items[1].disable();
							contactForm.form.submit({
								url : '/doMail.php',
								params : { dataObj : Ext.util.JSON.encode(contactForm.form.getValues()) },
								success : function(){
                                    contactForm.body.unmask();
                                    contactForm.fbar.items.items[0].disable();
                                    contactForm.fbar.items.items[1].enable();
                                    contactForm.fbar.items.items[0].setText('Mail sent');
                                    contactForm.body.mask('Thanks for contacting us.  Someone will get back to you shortly.');
								},
								failure : function(){
                                    contactForm.body.unmask();
                                    contactForm.fbar.items.items[0].enable();
                                    contactForm.fbar.items.items[1].enable();
									Ext.MessageBox.alert('Error!', 'There was an error submitting your message.  Please fill in all required fields and submit again.');
								}
											   
							});
						}
					}
				},
				{ 
					text    : 'Get me out of here',
                    height  : 25,
                    width   : 50,
					handler : function () {
                        contactForm.el.switchOff({
                            duration : 1,
                            easing   : 'bounceOut',
                            callback : function() {
                                contactFormCt.setHeight(0, {
                                    duration : 1,
                                    easing   : 'bounceOut'
                                });
                            }
                        });
                        contactForm.form.reset();
					}
				}
			]
		});


        var doContactUsToggle = function() {
            if (contactFormCt.getHeight() < 10) {
                contactFormCt.setHeight(240, {
                    duration : .5,
                    easing   : 'easeOut',
                    callback : function() {
                        if (!contactForm.rendered) {
                            contactForm.render('contact-form-ct');
                        }
                        contactForm.el.fadeIn({
                            duration : .75,
                            easing   : 'easeOut',
                            callback : function() {
                                var firstField = contactForm.items.items[0];
                                firstField.focus();
                            }
                        });

                    }
                });
            }
            else if (contactFormCt.getHeight() === 240) {
                contactForm.el.fadeOut();
                contactFormCt.setHeight(0, {
                    duration : .5,
                    easing   : 'easeIn'
                });
            }
        };

		Ext.get('contact_us_link').on('click', function(evtObj) {

            evtObj.stopEvent();

            var scrollEl = Ext.get(document.documentElement || document.body),
            scrollTop = scrollEl.dom.scrollTop;

            if (scrollTop > 0) {
                scrollEl.scrollTo('top', 0, {
                    duration : (scrollTop > 200) ?  2 : 1,
                    easing  : 'easeOutStrong',
                    callback : doContactUsToggle
                });
            }
            else {
                doContactUsToggle();
            }

        });







        var legacyVideoElements = Ext.DomQuery.select('tdgivideo[videosource]');
        Ext.each(legacyVideoElements, function (el) {
            var vidEl = Ext.get(el);
            var height = vidEl.dom.attributes.videoheight.nodeValue;
            var width = vidEl.dom.attributes.videowidth.nodeValue;
            var source = vidEl.dom.attributes.videosource.nodeValue;

            var divId = 'tdgivideo_' + Ext.id();
            var divEl = Ext.DomHelper.insertAfter(vidEl, {
                tag: 'div',
                id: divId
            });
            var s1 = new SWFObject('/js/mediaplayer/player.swf', divId, width, height, '9');
            s1.addParam('allowfullscreen', 'true');
            s1.addParam('allowscriptaccess', 'always');
            s1.addParam('flashvars', 'file=' + source);
            s1.write(divId);
        });

		
	}
});
