// Preliminary stuff

$.debug = function(object) {			
	var string;
	$.each(object, function(name, value) {
		string += name+' => '+value+"\r";
	});
	alert(string);
}

$.fn.buttons = function() {
	var c = this.attr('class');

	this.append('<span class="button-cap"></span>');
	
	if (! $.browser.version.match(/1\.9/) && $.browser.mozilla) {
		var newheight = parseInt($('.'+c).css('height'))+parseInt($('.'+c).css('padding-top'))+10;
		$('.'+c).css('height', newheight+'px');
	}
	
	/* Fix for FF 2 */
	$('.fi').each(function(i, e) {
		var e = $(e);
		if (e.find('.fi-content').length > 0) {
			e.addClass('fi-has-content-div');
		}
	});
}

$.fn.tabs = function(sectionClass) {
	$.each(this, function(index, element){
		var list = $(element);
		var sections = list.parent().children('.'+sectionClass);
		
		sections.hide().eq(0).show();
		
		list.find('a').click(function(e){
			e.preventDefault(); // So we can set the hash manually
			
			list.children().removeClass('current');
			$(e.target).parent().addClass('current');
		
			var target = 0;
			
			list.children().each(function(i, e){
				if ($(e).is('.current')) {
					target = i;
				}
			});
			
			sections.hide().eq(target).show();
			
			// Oh man. Multi-level hash permalinks. Hold your breath...
			var hash = slug($(e.target).text());
			
			if (location.hash.replace(/[^a-z]/g, '') != '') {
				var match = false;
				// Go through the current list and see if anything there is currently in the hash
				list.find('a').each(function(index, element) {
					var tempSlug = slug($(element).text());
					if (searchHash(tempSlug)) {
						match = true;
						regex = new RegExp(tempSlug);
						hash = location.hash.replace(regex, slug($(e.target).text()));
					}
				});
				// If not, add the new item to the hash
				if (! match) {
					hash = location.hash+'+'+hash;
				}
			}
			
			if (hash.substring(0,1) != '#') hash = '#'+hash;
			location.hash = hash;
		});
		
		// Is there a hash? Show the correct section
		if (location.hash != '') {
			list.find('a').each(function(index, element) {
				if (searchHash(slug($(element).text()))) {
					$(element).click(); // I love you, jQuery
				}
			});
		}
	});
}

$.fn.slidingDoors = function(controller, height) {
	var t = this;
	//var height = parseInt(t.css('height'));
	var controller = this.parent().find(controller);
	
	controller.mouseover(function(e) {
		$(this).attr('rel', 'clicked');
		
		var i = 0;
			
		controller.each(function(index, element){
			if ($(element).attr('rel') == 'clicked') i = index;
		});
		
		controller.attr('rel', '');
		
		t.css('background-position', '0 -'+(i*height)+'px');
	});
}

// The meat and potatoes

$(document).ready(function() {
	$('.button').buttons();
	$('.smallTabs, .protabs').tabs('tabSection');
	ql = $('#customers-list a.customer').quicklist({autoTime:7000, items:4, nextPrev:false});
	
	Customers.handle();
	Contact.handle();
	SignupStep1.handle();
	SignupStep2.handle();
	Pf.handle();
	Admin.handle();
	Charlimit.handle();
	Wufoo.handle();
	Dashboard.handle();
	GettingStarted.handle();
	
	$('body').addClass('js');
	
	$('a[rel=lightbox]').lightBox({
		imageLoading:  'http://b2b.viddler.com/images/lightbox/lightbox-ico-loading.gif',
		imageBtnClose: 'http://b2b.viddler.com/images/lightbox/lightbox-btn-close.gif',
		imageBtnPrev:  'http://b2b.viddler.com/images/lightbox/lightbox-btn-prev.gif',
		imageBtnNext:  'http://b2b.viddler.com/images/lightbox/lightbox-btn-next.gif'
	});
	
	var email = $('a[href=mailto:#]');
	email.text(email.text().replace(/ \*at\* /, '@').replace(/ \*dot\* /, '.').replace(/\s/, ''));
	email.attr('href','mailto:'+email.text());
});

var Customers = {
	handle: function() {
		$('#customers .customers-detail:not(:first)').hide();
		$('#customers-list a.customer:first').addClass('current');
		
		$('#customers-list a.customer').click(Customers.change);
		$('#customers .next, #customers .prev').click(Customers.nextPrev);
	},
	change: function(e) {
		e.preventDefault();
		
		var t = $(this);
		var i;
		$('#customers-list a.customer').removeClass('current');
		$(this).addClass('current');
		
		$('#customers-list a.customer').each(function(index, element){
			if ($(element).is('.current')) {
				i = index;
			}
		});
		
		$('.customers-detail').hide().eq(i).show();
	},
	nextPrev: function(e) {
		e.preventDefault();
		var t = $(this);
		var p = t.parents('.customers-detail');
		var l = $('#customers-list a.customer');
		p.hide();
		
		if (t.is('.next')) {
			var index = ql.lastIndex+1;
			if (p.next('.customers-detail').length > 0) {
				p.next().show();
				l.filter('.current').removeClass('current').next().addClass('current');
			} else {
				p.parent().children('.customers-detail:first').show();
				l.removeClass('current').filter(':first').addClass('current');
				index = 1;
			}
			if (! $('#customers a.customer.current').is(':visible')) {
				ql.change(null, index);
			}
		} else {
			var index = ql.lastIndex-1;
			if (p.prev('.customers-detail').length > 0) {
				p.prev().show();
				l.filter('.current').removeClass('current').prev().addClass('current');
			} else {
				p.parent().children('.customers-detail:last').show();
				l.removeClass('current').filter(':last').addClass('current');
			}
			if (! $('#customers a.customer.current').is(':visible')) {
				ql.change(null, index);
			}
		}
	}
}

var SignupStep1 = {
	returl  : null,
	bsuid   : null,
	account : null,
	action  : null,
	dataSent: false,
	required: [
		'first_name',
		'last_name',
		'email',
		'company',
		'lead_source',
		'00N80000002in2c'
	],
	handle: function() {
		this.nextStep();
		
		$('form#signup').submit(SignupStep1.submit);
		
		$('form#signup #next_step').click(SignupStep1.nextStep);
		$('#next_step').click(SignupStep1.switchDestination);
		
		SignupStep1.returl = $('[name=retURL]').val();
		SignupStep1.bsuid  = $('[name=b2bsignupid]').val();
	},
	switchDestination: function(e) {
		var e = $(this).children(':selected');
		
		var firstSubmit = $('#contact [type=submit]:eq(0)');
		var accountType = e.text().toLowerCase().match(/startup|basic|enterprise|plus/);
		
		SignupStep1.account = accountType;
		
		if (accountType != null) {
			firstSubmit.val('Next Step');
			$('[name=retURL]').val(SignupStep1.returl.replace(/contact\/\?thankyou/, 'signup/'));
			// alert($('[name=retURL]').val());
		} else {
			firstSubmit.val('Submit');
			$('[name=retURL]').val(SignupStep1.returl.replace(/signup.*$/, 'contact\/\?thankyou'));
		}
	},
	submit: function(e) {
		if (validate($('form#signup'), SignupStep1.required)) {
			if (SignupStep1.dataSent) {
				//window.location = $('[name=retURL]').val()
				if (! e) $('form#signup').submit();
				return true;
			} else {
				SignupStep1.interceptData();
			}
		}
		if (e) e.preventDefault();
		return false;
	},
	nextStep: function() {
		var t        = $('#next_step');
		var selector = '';
		var all      = $('.contactbox:visible');
		
		if (t.find(':selected').attr('title')) {
			selector = t.find(':selected').attr('title');
		}
		
		if ($(all).length > 0) {
			$('.contactbox:visible').fadeOut('medium',function() {
				$(selector).fadeIn('medium');
			});
		} else {
			$(selector).fadeIn('medium');
		}
	},
	interceptData: function() {
		data = []
		
		$('form#signup [name]').each(function(index, element){
			var e = $(element);
			
			data.push(escape(e.attr('name'))+'='+escape(e.val()));
		});
		request = data.join('&');
		
		var root = location.href.replace(/signup\/?.*$/, '');

		$('.ajaxError').remove();
		
		$.ajax({
			type   : 'POST',
			url    : root+'/_signup/salesforce.php',
			data   : 'b2bsignupid='+SignupStep1.bsuid+'&'+request,
			success: function(msg){
				SignupStep1.dataSent = true;
				SignupStep1.submit();
			},
			error  : function () {
				$('.centered form:first').before(
					'<p class="error ajaxError">We\'re sorry, but an error occurred while trying to send your submission. Please try again.</p><p class="error ajaxError">If this problem persists, you can still send us a business inquiry at the <a href="../contact/">contact</a> page.</p><p class="error ajaxError">We would greatly appreciate it if you would <a href="http://www.viddler.com/about">contact Viddler</a> to report the issue. Thanks!</p>'
				);
			}
		});
	}
}

var SignupStep2 = {
	required: [
		'username',
		'password',
		// 'tou',
		'email',
		'password-confirm'
	],
	handle: function() {
		$('[id^=viddler-account]').click(SignupStep2.viddlerAccount);
		$('form#signup-step-2 [type=radio]:checked').click();
		$('form#signup-step-2').submit(SignupStep2.submit);
		
		if ($('#section-b').is(':visible')) {
			SignupStep2.required.push('business-agreement');
		}
		
	},
	viddlerAccount: function() {
		if ($(this).attr('id') == 'viddler-account-1') {
			$('#password-confirm, #email, #tou').parents('.form-item:hidden').show();
			
			$(this).parents().children('.notebox').text('Choose a username and password for your Viddler account below');
			
			// Make sure email, tou, and password confirm are required
			$('[name^=email]').attr('name', 'email');
			$('[name^=tou]').attr('name', 'tou');
			$('[name^=password-confirm]').attr('name', 'password-confirm');
		} else {
			$('#password-confirm, #email, #tou').parents('.form-item:visible').hide();
			
			$(this).parents().children('.notebox').text('Enter your username and password below');
			
			// Make sure email, tou, and password confirm are not required
			$('[name^=email]').attr('name', 'email-off');
			$('[name^=tou]').attr('name', 'tou-off');
			$('[name^=password-confirm]').attr('name', 'password-confirm-off');
		}
	},
	submit: function(e) {
		if (SignupStep2.validate()) {
			return true;
		} else {
			e.preventDefault();
			return false;
		}
	},
	validate: function() {
		return validate($('form#signup-step-2'), SignupStep2.required);
	}
}

var Contact = {
	required: [
		'first_name',
		'last_name',
		'email',
		'company',
		'00N80000002in2c'
	],
	handle: function() {
		$('form#contact').submit(Contact.validate);
	},
	validate: function() {
		return validate($('form#contact'), Contact.required);
	}
}

var Pf = {
	handle: function() {
		$('.pf a').mouseover(function(e){
			$(this).parents('.pf-right').find('.pf li').removeClass('current');
			$(this).parent().addClass('current');
		});
		
		$('#simplePlayer').slidingDoors('ul.pf a', 243);
		$('#fullPlayer').slidingDoors('ul.pf a', 259);
		
		$('#simplePlayer, #fullPlayer').attr('title', 'Click to see the next image');
		
		$('#simplePlayer, #fullPlayer').click(function(e) {
			var currentLink = $(this).parent().find('ul.pf li.current');
			var currentList = currentLink.parent();
			
			if (currentLink.next().length > 0) {
				currentLink.next().children('a').mouseover();
			} else {
				if (currentList.next().length > 0) {
					currentList.next().find('a:first').mouseover();
				} else {
					currentList.parent().find('ul.pf a:first').mouseover();
				}
			}
		});
	}
}

var Admin = {
	handle: function() {
		$('fieldset[id^=customer-] *').hide().filter('legend, a').show();
		$('.toggleCustomer').click(Admin.toggleCustomer);
		$('a:contains(Refresh Database)').click(function(e){
			var result = confirm('Are you sure you want to do this? It may take a few minutes');
			
			if (! result) {
				e.preventDefault(); return false;
			} else {
				return true;
			}
		});
		
		$('[id^=account-type]').click(function(e) {
			// Private
			if ($(this).attr('id') == 'account-type-1') {
				$('.privateOnly [type=checkbox]').attr('disabled', '');
			} else {
			// Public
				$('.privateOnly [type=checkbox]').attr('disabled', 'disabled').attr('checked', 'checked');
			}
		});
		
		if ($('fieldset[id^=customer-] ul.errors').length > 0) {
			$('ul.errors').parents('fieldset').find('*').show().parent().find('.toggleCustomer').text('Close');
		}
		
		// Create new client validation
		
		$('legend:contains(New Client)').parents('form').submit(function(e) {
			
			var required = [
				'username',
				'email',
				'first_name',
				'last_name',
				'company',
				'account_type'
			];
			
			if ($('#viddler_signup:checked').length > 0) required.push('password');
			
			if (! validate($(this), required)) {
				e.preventDefault();
				return false;
			}
			
			return true;
		})
		
		// Log user in to Viddler
		$('#viddlerLoginButton').click(function(e) {
			e.preventDefault();
			$('#viddlerLoginForm').submit();	
		});
		
		// Notebox hover
		
		$('#account-settings .form-item').hover(function(){
			$(this).find('.notebox').addClass('notebox-hover');
		}, function(){
			$(this).find('.notebox').removeClass('notebox-hover');
		});
		
	},
	toggleCustomer: function(e){
		e.preventDefault();
		if ($(this).text() == 'Edit') {
			$(this).parent().find('*').show();
			$(this).text('Close');
		} else {
			$(this).parent().children().hide().filter('legend, a').show();
			$(this).text('Edit');
		}
	}
}

var Wufoo = {
	handle: function() {
		Wufoo.form = $('#business-ad-submission-form');
		Wufoo.form.find('#saveForm').click(Wufoo.submit);
	},
	submit: function(e) {
		e.preventDefault();
		
		var f = Wufoo.form;
		
		var fields = [
			['Field10', 'email'],
			['Field21'],
			['Field20', '!Select...'],
			['Field6', '!Select...']
		];
		
		for (var x in fields) {
			var item = f.find('#'+fields[x][0]);
			
			if (fields[x].length < 2) {
				if (item.val() == '') {
					Wufoo.makeErrorMsg(item, 'This field is required');
				} else {
					Wufoo.removeErrorMsg(item);
				}
			} else {
				if (fields[x][1] == 'email') {
					if (! item.val().match(/^(.+)@([^\(\);:,<>]+\.[a-zA-Z]{2,4})/)) {
						Wufoo.makeErrorMsg(item, 'Please enter a valid email address');
					} else {
						Wufoo.removeErrorMsg(item);
					}
				}
				if (fields[x][1].substring(0,1) == '!') {
					var not = fields[x][1].substring(1);
					if (item.children(':selected').text() == not) {
						Wufoo.makeErrorMsg(item, 'Please choose an option');
					} else {
						Wufoo.removeErrorMsg(item);
					}
				}
			}
		}
		
		// Start date validation
		var error = false;
		for (var x=0;x<2;x++) {
			if (x > 0) {
				extra = '-'+x;
			} else {
				extra = '';
			}
			var item = f.find('#Field0'+extra);
			if (item.val() == '' || item.val().match(/[^0-9]/)) {
				error = true;
			}
		}
		
		if (error) {
			Wufoo.makeErrorMsg(f.find('#Field0'), 'Please enter a date');
		} else {
			Wufoo.removeErrorMsg(f.find('#Field0'));
		}
		
		// CPM validation
		
		if (f.find('#Field9').val().match(/[^0-9]/) || f.find('#Field9-1').val().match(/[^0-9]/)) {
			Wufoo.makeErrorMsg(f.find('#Field9'), 'Please enter numeric characters only');
		} else {
			Wufoo.removeErrorMsg(f.find('#Field9'));
		}
		
		if (f.find('p.error').length == 0) {
			f.submit();
		}
	},
	makeErrorMsg: function(e, msg) {
		if (e.parent().parent().find('p.error').length == 0) {
			e.parents('li').addClass('error');
			e.parent().parent().children('div').after('<p class="error">'+msg+'</p>');
		}
	},
	removeErrorMsg: function(e) {
		e.parents('li').removeClass('error');
		e.parent().parent().find('p.error').remove();
	}
}

var Dashboard = {
	checked: [],
	handle: function() {
		$('#admin-table input[type=checkbox]').click(function(e){
			var id = $(this).attr('name').replace(/[^0-9]/g, '');
			
			if ($(this).is(':checked')) {
				Dashboard.checked.push(id);
			} else {
				for(x in Dashboard.checked) {
					var item = Dashboard.checked[x];
					if (item == id) {
						Dashboard.checked.splice(x, 1);
					}
				}
			}
			if (Dashboard.checked.length > 0) {
				$('.tableActions a:contains(Edit)').attr('href', 'edit/'+Dashboard.checked.join('+'));
				$('.tableActions a:contains(Delete)').attr('href', 'delete/'+Dashboard.checked.join('+'));
			} else {
				$('.tableActions a').attr('href', '#');
			}
		});
		
		$('.tableActions a:contains(Delete), #admin-table a:contains(Delete)').click(function(e){
			var answer = confirm('Are you sure you want to do this?');
			
			if (! answer) {
				return false;
			}
		});
	}
}

var GettingStarted = {
	lastId: '',
	handle: function() {
		$('.get-started .columnA .section').hide();
		
		$('.get-started .columnA .section:first').show();
		
		$('.get-started a[href^=#]').click(GettingStarted.swap);
		GettingStarted.addClass();
			
		// If there is a permalink to a specific topic in the hash, show that topic
		
		var hashArray = location.hash.split('+');
		$.each(hashArray, function(index, item) {
			if (item.substring(0,1) == '#') item = item.substring(1);
			if (item && $('#'+item).length > 0) {
				$('a[href=#'+item+']').click();
			}
		});
	},
	setHash: function(id) {
		var hash = id.substring(1);
		// If the hash has anything in it...
		if (location.hash.replace(/[^a-z]/g, '') != '') {
			var match = false;
			// Go through the current list and see if anything there is currently in the hash
			$('.topic-list a').each(function(index, element) {
				var tempSlug = $(element).attr('href').substring(1);
				if (searchHash(tempSlug)) {
					match = true;
					regex = new RegExp(tempSlug);
					hash = location.hash.replace(regex, hash);
				}
			});
			// If not, add the new item to the hash
			if (! match) {
				hash = location.hash+'+'+hash;
			}
		}
		
		if (hash.substring(0,1) != '#') hash = '#'+hash;
		location.hash = hash;
	},
	swap: function(e) {
		var t = $(this);
		var id = $(this).attr('href');
		
		// if (location.hash == id) return;
		
		// Set the hash manually
		e.preventDefault();
		GettingStarted.setHash(id);
		
		// Scroll to the top
		
		function showHide() {
			if ($(id).length > 0) {
				// Hide
				$('.get-started .columnA .section').hide();
				
				// Show
				GettingStarted.findSection(id).show();
				GettingStarted.addClass();
			}
		}
		
		var amount = 0;
		if ($('a:contains(Getting Started)').length > 0) amount = 93;
		if ($('a:contains(Admin)').length > 0) amount = 146;
		
		if (amount != $(window).scrollTop()) {		
			$('html,body').animate({ // Both html and body needed in selector for browser compatibility
				'scrollTop': amount
			}, 400, 'swing', showHide);
		} else {
			showHide();
		}
	},
	addClass: function() {
		var id = $('.get-started .columnA .section:visible h2').attr('id');
		
		var t = $('.columnB a[href=#'+id+']');		
		// Add a class, if it's in the topic-list
		t.parents('ul').children('li').removeClass('current').children('a')
		
		t.parents('li:eq(0)').addClass('current');
		t.animate({'paddingLeft': '20px'}, 400, 'swing').parent().siblings().children('a').animate({'paddingLeft': '10px'}, 400, 'swing');
	},
	findSection: function(id) {
		if (! id.match(/^#/)) {
			id = '#'+id;
		}
		return $('.get-started .columnA '+id).parents('.section').eq(0);
	}
}

var Charlimit = {
	handle: function() {
		$('textarea[rel^=limit:]').keyup(Charlimit.keyup);
	},
	keyup: function(e) {
		var limit = parseInt($(this).attr('rel').replace(/limit:/,''));
		if ($(this).val().length > limit) {
			val = $(this).val().substring(0, limit);
			$(this).val(val);
		}
	}
}

// Handy functions

function validate(f, required) {
	var errors = [];
		
	f.find('input, textarea, select').each(function(index, element) {
		var input = $(element);
		if (inArray(input.attr('name'), required) && input.val() == '') {
			errors.push({name: input.attr('name'), message: 'This field is required'});
		} else {
			switch (input.attr('name')){
				case 'email':
					if (! input.val().match(/^([^ ]+)@([^\(\);:,<>]+\.[a-zA-Z]{2,4})/))
						errors.push({name: input.attr('name'), message: 'Please enter a valid email address'});
					break;
				case 'username':
					if (input.val().match(/[^0-9a-z]/i))
						errors.push({name: input.attr('name'), message: 'Username must contain only numbers and letters'});
					break;
			}
		}
	});
	
	$('span.error').remove();
	if (errors.length > 0) {
		for (x in errors) {
			var name  = errors[x].name;
			var input = $('[name='+name+']');
			
			if (name == 'business-agreement') {
				$('[for='+name+']').after('<span class="error">'+errors[x].message+'</span>');
			} else {
				input.parent().append('<span class="error">'+errors[x].message+'</span>');
			}
		}
		return false;
	}
	return true;
}

function inArray(needle, haystack) {
	for (x in haystack) {
		if (needle == haystack[x]) {
			return true;
		}
	}
	return false;
}

function slug(text) {
	return text.toLowerCase().replace(/\s/,'-').replace(/[^a-z\-]/g, '');
}

function searchHash(query) {
	var hash = location.hash.substring(1);
	var hashList = hash.split('+');
	//alert(query+' vs. '+hashList);
	return inArray(query, hashList);
}