/* Ext params */
Ext.BLANK_IMAGE_URL = '/js/ext/resources/images/aero/s.gif';

Ext.DEBUG = true;

var bpm = {};

/*
 * Logger
 */
var log = {
	msg: function(/* string */message) {
		if (Ext.DEBUG !== true) {
			return;
		}
		if (typeof(console) != 'undefined') {
			console.log(message);
		}
	}
}

/*
 * Archive functionality
 */
var archive = {
	channelNames: ['channels', 'recent', 'audio', 'dollar', 'free'],
	
	currentChannel: '',
	
	initNav: function() {
		/*
		for (cname in this.channelNames) {
			var id = '#nav-archive-' + cname + '@click';
			Ext.addBehaviors({
			 id : makeArchiveClickHandler(cname)
			});
		}
		*/
		Ext.addBehaviors({
			'#nav-archive-channels@click': this.makeArchiveClickHandler('channels'),
			'#nav-archive-recent@click': this.makeArchiveClickHandler('recent'),
			'#nav-archive-audio@click': this.makeArchiveClickHandler('audio'),
			'#nav-archive-dollar@click': this.makeArchiveClickHandler('dollar'),
			'#nav-archive-free@click': this.makeArchiveClickHandler('free')
		});
	},
	
	makeArchiveClickHandler: function(/* string */cname) {
		return function(e, t) { archive.show(cname) };
	},
	
	getArchive: function(/* string */cname) {
		return Ext.getDom('archive-' + cname);
	},
	
	getArchiveBtn: function(/* string */cname) {
		return Ext.getDom('nav-archive-' + cname);
	},
	
	hide: function(/* string */cname) {
		var btn = this.getArchiveBtn(cname);
		if (btn) {
			btn.className = 'nav-archive-' + cname + '-off';
		}
		this.getArchive(cname).style.display = 'none';
	},
	
	setPane: function(/* string */cname) {
		this.currentChannel = cname;
	},
	
	show: function(/* string */cname) {
		if ('' != this.currentChannel) {
			this.hide(this.currentChannel);
		}
		var btn = this.getArchiveBtn(cname);
		if (btn) {
			btn.className = 'nav-archive-' + cname + '-on';
		}
		this.getArchive(cname).style.display = 'block';
		this.currentChannel = cname;
	},
	
	showFirst: function() {
		this.show(this.channelNames[0]);
	}
};

Ext.onReady(function() {
	archive.initNav();
});


/*
 * Search functionality 
 */
var searcher = {
	go: function() {
		var t = Ext.getDom('form-search-terms');
		if ('Search Video Archive' == t.value || '' == t.value) {
			return false;
		}
		top.location="/catalog/search/" + t.value;
		return false;
	}
};

/*
 * Comment and "email a friend" handler 
 */
var commenter = {
	btnSubmit: false,
	commentform: false,
	comments: [],
	emailform: false,
	emailFormIsRendered: false,
	feedbackDiv: false,
	formIsRendered: false,
	playerContent: false,
	posturl: '/responders/product.php?do=',
	reportLink: false,
	reportWrapper: false,
	
	/* Can be passed number of comments.  If 0, we can opt not to show on load */
	init: function(/* int */num) {
		Ext.addBehaviors({
			'#btn-comment-cancel@click': this.makeClickHandler('cancel'),
			'#btn-comment-create@click': this.makeClickHandler('create'),
			'#btn-comment-post@click': this.makeClickHandler('post'),
			'#btn-comment-view@click': this.makeClickHandler('view'),
			'#btn-email-cancel@click': this.makeClickHandler('cancel'),
			'#btn-email-friend@click': this.makeClickHandler('email'),
			'#btn-email-send@click': this.makeClickHandler('emailsend'),
			'#link-comments-hide@click': this.makeClickHandler('hideall')
		});
		
		this.doLayout();
		
		if (num == 0) {
			this.doClick('hideall');
		} else {
			/* Create "report this comment" forms/buttons */
			var parentNode = Ext.get('wrapper-comments-inner');
			this.comments = Ext.DomQuery.select('.wrapper-comment-row/.posted/.wrapper-link-report-comment/.report-comment');
			var reg = new RegExp(/report-comment-([0-9]+)/);
			for (var i = 0; i < this.comments.length; i++) {
				var id = reg.exec(this.comments[i].id)[1];
				Ext.get(this.comments[i]).on('click', this.makeClickHandler('report', id), this, {preventDefault: true});
			}
		}
	},
	
	/* doClick: Dispatch actions from click events */
	doClick: function(/* string */action, /* mixed */id, /* mixed */obj) {
		var commentsWrapper = Ext.getDom('wrapper-comments');
		var emailWrapper = Ext.getDom('wrapper-form-email');
		var formWrapper = Ext.getDom('wrapper-form-comment');
		
		/* Cancel/hide either form */
		if ('cancel' == action) {
			emailWrapper.className = 'hide';
			formWrapper.className = 'hide';
		}
		/* Show the comment form */
		if ('create' == action) {
			commentsWrapper.className = 'hide';
			emailWrapper.className = 'hide';
			formWrapper.className = '';
			this.renderForm('comment');
		}
		/* Hide all panes */
		if ('hideall' == action) {
			commentsWrapper.className = 'hide';
			emailWrapper.className = 'hide';
			formWrapper.className = 'hide';
		}
		/* Post the comment form */
		if ('post' == action) {
			this.doSubmit();
		}
		/* View comments */
		if ('view' == action) {
			commentsWrapper.className = '';
			emailWrapper.className = 'hide';
			formWrapper.className = 'hide';
		}
		/* Show the email form */
		if ('email' == action) {
			commentsWrapper.className = 'hide';
			emailWrapper.className = '';
			formWrapper.className = 'hide';
			this.renderForm('email');
		}
		/* Post the email form */
		if ('emailsend' == action) {
			this.sendEmail();
		}
		/* Show comment report form */
		if ('report' == action) {
			if (null !== id) {
				this.reportLink = Ext.get('wrapper-link-report-comment-' + id);
				/*
				var x = this.reportLink.getLeft();
				var y = this.reportLink.getTop();
				*/
				var fo = new Ext.Form({url: this.posturl + 'report&id=' + id});
				fo.column({width: 90});
				fo.fieldset(
					{hideLabels: true, cls: 'report-comment-field'},
					new Ext.form.Checkbox({
						boxLabel: 'Spam?',
						name: 'spam'
					})
				);
				fo.end();
				fo.column({width: 90, clear: true});
				fo.fieldset(
					{hideLabels: true, cls: 'report-comment-field-2'},
					new Ext.form.Checkbox({
						boxLabel: 'Offensive?',
						name: 'offensive'
					})
				);
				fo.end();
				fo.addButton('Cancel', this.makeClickHandler('report-cancel', id, fo));
				fo.addButton('Report this', this.makeClickHandler('report-submit', id, fo));
				fo.end();
				this.reportWrapper = Ext.DomHelper.insertAfter(this.reportLink.findParent('p.posted'), {
					tag: 'div', 
					id: 'wrapper-comment-report-' + id,
					cls: 'form-report-comment',
					html: ''
				});
				Ext.getDom(this.reportLink).style.display = 'none';
				fo.render(this.reportWrapper);
				var clearDiv = Ext.DomHelper.insertAfter(this.reportWrapper, {
					tag: 'div', 
					cls: 'clear'
				});
				fo.on({
					actioncomplete: function(form, action) { 
						commenter.reportWrapper.style.display = 'none';
						commenter.reportWrapper = null;
						//commenter.reportLink.style.display = '';
						var confirm = Ext.DomHelper.insertAfter(commenter.reportLink, {
							tag: 'span',
							cls: 'report-comment-confirm',
							html: action.result.data
						});
					},
					actionfailed: function(form, action) { Ext.MessageBox.alert('Error', action.result.data); }
				});
			}
		}
		/* Submit comment report form */
		if ('report-submit' == action) {
			if (obj != null) {
				obj.submit({waitMsg: 'Reporting this comment for review'});
			}
		}
		/* Cancel comment report form */
		if ('report-cancel' == action) {
			if (this.reportLink) {
				commenter.reportWrapper.style.display = 'none';
				commenter.reportWrapper = false;
				Ext.getDom(commenter.reportLink).style.display = '';
			}
		}
	},
	
	doLayout: function() {
		var layout = new Ext.BorderLayout("wrapper-comments", {
			center:  {
				autoScroll: true,
				titlebar: false
			}
		});
		
		var commentsPanel = new Ext.ContentPanel("wrapper-comments-inner"); 
		
		layout.beginUpdate();
		layout.add("center", commentsPanel);
		layout.endUpdate();
	},
	
	doSubmit: function() {
		var email = Ext.getDom('form_comment-email').value;
		if (Ext.getDom('form_comment-name').value == '' || email == '') {
			return this.showError('You need to enter your name and email address.');
		}
		
		if (!validator.isEmail(email)) {
			return this.showError('Your email address doesn\'t seem valid.');
		}
		
		if (Ext.getDom('form_comment-body').value == '') {
			return this.showError('You need to enter a comment.');
		}
		
		this.commentform.submit({
			waitMsg: 'Saving your comment...'
		});
	},
	
	/* Experimental: Hide player when Ext shows alert */
	hidePlayer: function() {
		var pl = document.getElementById('video-player');
		if (typeof(pl) == 'object') {
			var flash = Ext.getDom('playlist');
			w = pl.offsetWidth;
			h = pl.offsetHeight;
			commenter.playerContent = pl.innerHTML;
			var styles = 'background:#222;height:' + h + 'px;left:0;position:absolute;top:0;width:' + w + 'px;z-index:5000;';
			var elm = document.createElement('div');
			Ext.id(elm);
			Ext.DomHelper.applyStyles(elm,styles);
			var playerNode = Ext.DomHelper.insertFirst(pl, elm);
		}
	},
	
	makeClickHandler: function(/* string */action, /* mixed */id, /* mixed */obj) {
		id = (id == null) ? null : id;
		obj = (obj == null) ? null : obj;
		return function(e, t) { commenter.doClick(action, id, obj) };
	},
	
	renderForm: function(/* string */formName) {
		if ('comment' == formName) {
			if (!this.formIsRendered) {
				this.commentform = new Ext.form.BasicForm(
					'form-comment',
					{ url: this.posturl + 'add' }
				);
				
				this.commentform.on({
					actioncomplete: function(form, action) { commenter.commentform.reset(); commenter.showFeedback(action.result.data, true); },
					actionfailed: function(form, action) { commenter.showFeedback(action.result.data, false); }
				});
				
				this.formIsRendered = true;
			}
		}
		if ('email' == formName) {
			if (!this.emailFormIsRendered) {
				this.emailform = new Ext.form.BasicForm(
					'form-email',
					{ url: this.posturl + 'email' }
				);
				
				this.emailform.on({
					actioncomplete: function(form, action) { commenter.emailform.reset(); Ext.MessageBox.alert('Email sent', action.result.data); },
					actionfailed: function(form, action) { Ext.MessageBox.alert('Error', action.result.data); }
				});
				
				this.emailFormIsRendered = true;
			}
		}
	},
	
	sendEmail: function(/* string */msg, success) {
		var senderEmail = Ext.getDom('form_email-sender').value;
		var recipEmail = Ext.getDom('form_email-recip').value;
		if (senderEmail == '') {
			return this.showError('You need to enter your email address.');
		}
		
		if (!validator.isEmail(senderEmail)) {
			return this.showError('Your email address doesn\'t seem valid.');
		}
		
		if (recipEmail == '') {
			return this.showError('You need to enter your friend\'s email address.');
		}
		
		if (!validator.isEmail(recipEmail)) {
			return this.showError('Your friend\'s email address doesn\'t seem valid.');
		}
		
		this.emailform.submit({
			waitMsg: 'Sending your email...'
		});
	},
	
	showError: function(/* string */msg) {
		Ext.MessageBox.alert('Error', msg);
		return;
	},
	
	showFeedback: function(/* string */msg, success) {
		var dh = Ext.DomHelper;
		var cssClass = (success) ? 'feedback' : 'feedback feedback-error';
		var parentDiv = Ext.getDom('wrapper-comments-inner');
		
		var fo = {tag: 'p', cls: cssClass, html: msg};
		if (this.feedbackDiv !== false) {
			parentDiv.removeChild(this.feedbackDiv);
			this.feedbackDiv = null;
		}
		this.feedbackDiv = dh.insertFirst(parentDiv, fo);
		
		/* Our date string */
		var dt = new Date();
		dtString = dt.format('M d Y \\a\\t h:i a');
		
		var newRow = dh.insertAfter('title-comments', {
			tag: 'div', cls: 'wrapper-comment-row', children: [
				{tag: 'p', html: Ext.getDom('form_comment-body').value},
				{tag: 'p', cls: 'posted', html: 'Posted by ' + Ext.getDom('form_comment-name').value + ' | ' + dtString}
			]
		});
		this.doClick('view');
	}
}

/*
 * Cart functionality
 */
var cart = {
	
	/*
	 * Check out to PayPal by submitting the checkout form
	 */
	checkout: function() {
		Ext.getDom('form-checkout-paypal').submit();
	},
	
	/**
	 * Look for important form values and set up behaviors
	 */
	init: function() {
		Ext.addBehaviors({
			'#link-quantities-update@click': function() { cart.updateQuantities(); }
		});
	},
	
	/*
	 * Replace 'add to cart' button with feedback from JSON response
	 */
	showAddFeedback: function(/* string */div, /* string */msg, /* boolean */success) {
		var cssClass = (success) ? 'cart-msg-success' : 'cart-msg-error';
		var msg = Ext.DomHelper.overwrite(div, {tag: 'p', cls: cssClass, html: msg});
		
		/* The Ext way:
		 * Ext.Msg.alert('Success', 'This has been added to your cart.');
		 */
	},

	/*
	 * Change cart number to whatever is passed in newNum
	 */
	updateCartItems: function(/* int */newNum) {
		var cur = parseInt(Ext.getDom('summary-cart-items').innerHTML);
		if (cur !== newNum) {
			var items = (newNum == 1) ? 'item' : 'items';
			Ext.getDom('summary-cart-items').innerHTML = newNum + ' ' + items;
		}
	},
	
	/**
	 * Populate quantities form and submit
	 */
	updateQuantities: function() {
		page.showFeedback('Saving changes...', 'quantity-feedback');
		
		var inputs = Ext.DomQuery.select("input.input-quantity");
		
		var form = new Ext.form.Form({
			url: '/catalog/cart/update', 
			method: 'post'
		});
		
		form.on({
			actioncomplete: function(form, action) {
				if (action.result) {
					page.showFeedback(action.result.data, 'quantity-feedback');
				}
			}
		});
		
		Ext.each(inputs, function(item, index, arr) {
			
			var input = new Ext.form.TextField({
				name: item.id,
				value: item.value
			});
			
			input.hide();
			
			form.add(input);
		});
		
		form.render('form-control');
		form.submit();
	}
	
}

/*
 * Page controller 
 */
var page = {
	currentMsg: false,
	
	fadeMessage: function() {
		if (this.currentMsg === false) {
			return;
		}
		if (typeof(Ext.get(this.currentMsg)) == 'undefined') {
			return;
		}
		Ext.get(this.currentMsg).fadeOut({duration: 1, easing: 'easeOut', remove: true});
	},
	
	showFeedback: function(msg, containerId) {
		var para = {tag: 'p', html: msg, id: 'temp-message'};
		var msgContainer = Ext.get(containerId);
		if (typeof(msgContainer) == 'undefined' || msgContainer == false) {
			return;
		}
		Ext.DomHelper.overwrite(msgContainer, para);
		this.currentMsg = Ext.get('temp-message');
		window.setTimeout('page.fadeMessage()', 4000);
	}
}

/**
 * Validation
 */
var validator = {
	re_email: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/,
	re_filename: /^\S+\.(gif|jpg|jpeg|png)$/,
	
	isEmail: function(/* string */str) {
		if (typeof(str) != 'string') {
			return false;
		}
		return str.match(this.re_email);
	}
}

/**
 * Contact form controller
 */
var contact = {
	isGood: true,
	
	checkEmail: function() {
		if (!validator.isEmail($("#field-email").val())) {
			contact.showError("#field-email", "Your email address doesn't seem right.  Please take another look.");
		} else {
			$("#field-email").removeClass("input-error");
			$(".form-error").remove();
			contact.isGood = true;
		}
	},
	
	init: function() {
		
		/* Validate form on submit */
		$("#form-contact").submit(function() {
			contact.isGood = true;
			contact.checkEmail();
			if (contact.isGood) {
				if ("" == $("#field-name").val()) {
					contact.showError("#field-name", "Please tell us your name.");
				} else {
					$("#field-name").removeClass("input-error");
				}
			}
			if (contact.isGood) {
				if ("" == $("#field-message").val()) {
					contact.showError("#field-message", "Please enter a message.");
				} else {
					$("#field-message").removeClass("input-error");
				}
			}
			return contact.isGood;
		});
		
		/* In addition, validate email field on blur */
		$("#field-email").blur(function() {
			contact.checkEmail();
		})
	},
	
	showError: function(id, msg) {
		contact.isGood = false;
		$(id).addClass("input-error");
		$(".form-error").remove();
		$("#form-contact fieldset").prepend('<div class="form-error pagemessage">' + msg + '</div>');
		$(id).focus();
	}
}
