/**
 * @author David Irving
 * @version \$Id\$
 * @copyright 2008 Ditto Editions
 * @package myPrints.biz
 *
 * JavaScript for handling the ordering/validation of prints
 *
 **/

var orderDlg;
var contactDlg;
var clientNumForm;
var numberField;
var contactForm;

var winTmpl = new Ext.Template(
    '<div class="orderPrints" style="padding:5px;background:#CEDEF3">',
        '<p>If you are the artist that created this work and would like to order more prints, please enter your client number in the space provided and click the "Order Prints" button.</p>',
		'<div id="clientNumForm" class="form" style="background:#CEDEF3"></div>',
		'<p>If you are not the artist and would like more information, or wish to place an order, please contact the artist by clicking the "Contact Artist" button below.</p>',
    '</div>'
);

var contactTmpl = new Ext.Template(
	'<div style="padding:10px">',
		'<p>To contact the artist, please fill out the following form and then click the "Send Comments" button.</p>',
		'<div id="contactForm"></div>',
	'</div>'
);

Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

if (!Ext.state.Manager.get('authedSessions')) {
	Ext.state.Manager.set('authedSessions',{ });
}

/**
 * The following function is needed because Ext 2.0 seems to have an issue taking vertical
 * scrollbars in to account when adding a mask to a modal window
 **/
function resizeOverlays() {
	var overlays = Ext.DomQuery.select('div[class=ext-el-mask]');
	for (var i=0;i<overlays.length;i++) {
		Ext.get(overlays[i]).setSize('100%', Ext.lib.Dom.getViewHeight(true));
	}	
}

/**
 * Show the contact form
 * @param hashCode The hash for the artist information
 **/
function showContactForm(hashCode) {
    if (!contactDlg){
	
		Ext.QuickTips.init();
		Ext.form.Field.prototype.msgTarget = 'side';
	
        contactDlg = new Ext.Window({
            layout: 'fit',
            width: 550,
            height: 400,
            closeAction: 'hide',
			bodyStyle: 'font-size:12px;background:#CEDEF3',
			title: 'Contact The Artist',
            plain: true,
			html: contactTmpl.applyTemplate(),
			modal: true,
            buttons: [
			{
				text: 'Cancel',
				handler: function() {
					contactDlg.hide();
				}
			},{
				text: 'Send Comments',
				handler: function(){
					if (contactForm.getForm().isValid()) {
						contactDlg.body.mask('Sending Comments...');
						Ext.lib.Ajax.request(
							'POST',
							'/contactArtist.php',
							{success:function(oResponse){
								contactDlg.body.unmask();
								contactDlg.hide();
							}},	
							'&hash=' + contactDlg.hashCode +
							'&name=' + escape(contactForm.getForm().findField('clientName').getValue()) +
							'&email='+ escape(contactForm.getForm().findField('clientEmail').getValue()) +
							'&comments=' + escape(contactForm.getForm().findField('comments').getValue())
						);
					}
				}
			}]
		});
		contactDlg.on('show',function() {
			resizeOverlays();
			contactDlg.center();
			if (!contactForm) {
				contactForm = new Ext.form.FormPanel({
					items: [{}],
					header: false,
					bodyStyle: 'background:none repeat scroll 0% 50%;padding-top:8px;padding-bottom:5px;background:#C7D6E9',
					footer: false,
					hideBorders: true,
					border: false
				});
				contactForm.add(new Ext.form.TextField({
					id: 'clientName',
					name: 'clientName',
					width: 350,
					allowBlank: false,
					fieldLabel: 'Your Name'
				}));
				contactForm.add(new Ext.form.TextField({
					id: 'clientEmail',
					name: 'clientEmail',
					width: 350,
					allowBlank: false,
					fieldLabel: 'Your E-mail',
					vtype: 'email'
				}));
				contactForm.add(new Ext.form.TextArea({
					id: 'comments',
					name: 'comments',
					width: 350,
					height: 200,
					allowBlank: false,
					fieldLabel: 'Your Comments'
				}));
				contactForm.render(Ext.get('contactForm'));
			} else {
				contactForm.getForm().reset();
			}
		});
    }
	contactDlg.hashCode = hashCode;
    contactDlg.show();
}

/**
 * Show the order prints dialog window
 * @param string hash The hash of the job number
 * @param object target The target triggering the dialog window
 **/
function prints(hash, target) {
	
	var sessions = Ext.state.Manager.get('authedSessions');
	if (sessions && sessions[gup('p')]) {
		document.location = '/order.php?j=' + hash + '&c=' + sessions[gup('p')];
		return;
	}
	
    if (!orderDlg){
        orderDlg = new Ext.Window({
            layout: 'fit',
            width: 500,
            height: 200,
            closeAction: 'hide',
			bodyStyle: 'font-size:12px;background:#CEDEF3',
			title: 'Ordering Prints',
            plain: true,
			html: winTmpl.applyTemplate(),
			modal: true,
            buttons: [
			{
				text: 'Contact Artist',
				handler: function() {
					orderDlg.hide();
					// Show contact form
					showContactForm(orderDlg.hashCode);
				}
			},{
				text: 'Order Prints',
				handler: function(){
					orderDlg.body.mask('Verifying Client Number...');
					if (numberField.getValue() == '') {
						orderDlg.body.unmask();
						Ext.Msg.alert('Error', 'If you wish to order prints, you must enter your client number before proceeding.');
						resizeOverlays();
						return;
					}
					Ext.lib.Ajax.request(
						'POST',
						'/verification.php',
						{success:function(oResponse){
							var resp = null;
							orderDlg.body.unmask();
							try {
								resp = Ext.decode(oResponse.responseText);
							} catch (err) {	}
							if (resp) {
								if (!resp.success || resp.success != 1) {
									Ext.Msg.alert('Error', 'You have entered an invalid client number. Please try again.');
									resizeOverlays();
									var sessions = Ext.state.Manager.get('authedSessions');
									sessions[gup('p')] = null;
									Ext.state.Manager.set('authedSessions',sessions);
								} else {
									var sessions = Ext.state.Manager.get('authedSessions');
									sessions[gup('p')] = numberField.getValue();
									Ext.state.Manager.set('authedSessions',sessions);
									document.location = '/order.php?j=' + orderDlg.hashCode + '&c=' + numberField.getValue();
								}
							}
						}},	
						'&hash=' + orderDlg.hashCode +
						'&code=' + numberField.getValue()
					);
				}
			},{
				text: 'Close',
				handler: function(){
					orderDlg.hide();
				}				
			}]
		});
		orderDlg.on('show',function() {
			resizeOverlays();
			orderDlg.center();
			if (!clientNumForm) {
				numberField = new Ext.form.NumberField({
					id: 'clientNumber',
					name: 'clientNumber',
					allowBlank: true,
					fieldLabel: 'Client Number',
					allowDecimals: false,
					allowNegative: false
				});
				
				clientNumForm = new Ext.form.FormPanel({
					items: [{}],
					header: false,
					bodyStyle: 'background:none repeat scroll 0% 50%;padding-top:8px;padding-bottom:5px;background:#CEDEF3',
					footer: false,
					hideBorders: true,
					border: false
				});
				clientNumForm.add(numberField);
				clientNumForm.render(Ext.get('clientNumForm'));
			} else {
				numberField.setValue('');
			}
		});
    }
	orderDlg.hashCode = hash;
	//orderDlg.setAnimateTarget(target);
    orderDlg.show();
}

function gup(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

var checkNotices = function() {
	var noticeHolder = Ext.DomQuery.selectNode('div.notice');
	if (noticeHolder && Ext.DomQuery.selectNode('ul',noticeHolder)) {
		var notices = Ext.DomQuery.select('li',noticeHolder);
		if (notices && notices.length > 0) {
			for (var i=0;i<notices.length;i++) {
				Ext.Msg.show({
					title: 'Notice',
					msg: notices[i].innerHTML,
					buttons: Ext.Msg.OK,
					icon: Ext.MessageBox.INFO
				});
			}
		}
		Ext.get(noticeHolder).remove();
	}
}

Ext.onReady(checkNotices);
