/*!
 * Ext JS Library 3.2.0
 * Copyright(c) 2006-2010 Ext JS, Inc.
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
 
var ContactForms = new Array();
var ContactFormPanels = new Array();

function applyContactLinkActions(groupId)
{
	Ext.select('.'+groupId+'Link').on('click', function(e){
		e.preventDefault();
		ContactFormPanels[groupId].show();
		var rel = Ext.get(e.getTarget()).getAttribute('rel');
		if(rel) {
			var field = ContactForms[groupId].getForm().findField(groupId+'to');
			//var field = Ext.get('contact-'+rel);
			if(field) {
				field.setValue('contact-'+rel, true);
			}
			else {
				Ext.MessageBox.alert('Contacts Error', 'There is no contact with rel: '+rel);
			}
		}
	});	
}


function reapplyContactLinkActions()
{
	for(var groupId in contacts){
		applyContactLinkActions(groupId);
	}
}


Ext.onReady(function() {
	Ext.QuickTips.init();
	// turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'qtip';
	
    function makeForm(groupId) {
	    return new Ext.form.FormPanel({
	        baseCls: 'x-plain',
	        labelWidth: 70,
	        url: '/scripts/contact.php',
	        layout: {
	            type: 'vbox',
	            align: 'stretch'  // Child items are stretched to full width
	        },
	        defaults: {
	            xtype: 'textfield'
	        },
	
	        items: [{
	            xtype: 'checkboxgroup',
	            itemCls: 'x-check-group-alt',
	            columns: 3,
	            items: getContacts(groupId),
	            plugins: [ Ext.ux.FieldLabeler ],
	            fieldLabel: 'Send To',
	            name: 'to',
	            id: groupId+'to'
	        }, {
	            plugins: [ Ext.ux.FieldLabeler ],
	            fieldLabel: 'Your email',
	            allowBlank: false,
	            name: 'from',
	            id: groupId+'from',
	            vtype: 'email'
	        }, {
	            plugins: [ Ext.ux.FieldLabeler ],
	            fieldLabel: 'Subject',
	            allowBlank:false,
	            name: 'subject',
	            id: groupId+'subject'
	        }, {
	            xtype: 'textarea',
	            fieldLabel: 'Message text',
	
	            hideLabel: true,
	            allowBlank:false,
	            name: 'msg',
	            id: groupId+'msg',
	            flex: 1  // Take up all *remaining* vertical space
	        } ]
	    });
    }
    
    function getContacts(groupId){
        var c = new Array();
        try{
        for(var i = 0; i<contacts[groupId].length; i++) {
            c.push( {
            	style : {
            	},
            	id : (contacts[groupId][i].rel) ? 'contact-'+contacts[groupId][i].rel : null,
            	boxLabel: contacts[groupId][i].label, 
            	name: 'cb-to[]', 
            	inputValue: contacts[groupId][i].address,
            	checked: (contacts[groupId].length == 1)
            	} );
        }
        }
        catch(e){Ext.MessageBox.alert('Errors', 'There aren\'t any contacts defined.');}
        
        return c;
    };
    
    
    function buildWindow(groupId)
    {
    	var form = makeForm(groupId);
	    var ContactForm = new Ext.Window({
	    	id: groupId+'contactForm',
	        title: 'Compose message',
	        closable: false,
	        collapsible: false,
	        maximizable: true,
	        width: 750,
	        height: 500,
	        minWidth: 300,
	        minHeight: 200,
	        layout: 'fit',
	        plain: true,
	        bodyStyle: 'padding:5px;',
	        buttonAlign: 'center',
	        items: form,
	        buttons: [{
	            text: 'Send',
	            handler: send
	        },{
	            text: 'Cancel',
	            handler: hide
	        }]
	    });
	    
	    function hide(b,e){
	    	form.getForm().reset();
	        ContactForm.hide();
	        if(b) {
	            showResult("Your message has been cancelled.");
	        }
	    };
	    
	    function send(b,e) {
	        if(form.findById(groupId+'to').getValue().length==0) {
	            Ext.MessageBox.alert('Errors', 'Please select at least one recipient.');
	            return;
	        }
	        if(!form.getForm().isValid()) {
	            Ext.MessageBox.alert('Errors', 'Please fix the errors noted.');
	            return;
	        }
	        
	        form.getForm().doAction("submit",{
	            waitMsg: 'Sending...',
	            reset: true,
	            method: 'POST',
	            failure: function(a,b){Ext.MessageBox.alert('Errors: '+b.failureType, 'Oops!<br/>It looks like we have some technical difficulties.<br/>Please try your message again later.<br/>'+b.response.responseText);},
	            success: function(){showResult("Thank you! Your message has been sent.");hide();}
	            }); 
	    };
	    
	    ContactForms[groupId] = form;
	    ContactFormPanels[groupId] = ContactForm;
    }
    
    for(var groupId in contacts){
    	buildWindow(groupId);
    	applyContactLinkActions(groupId);
    }
    
});
