$.ajaxSetup({ type: "POST", dataType: "json" });

var Utility = {
	sMakeString: function(oObject) { return JSON.stringify({ json: JSON.stringify(oObject) }); },
	sSafeName: function(sName) { return sName.toLowerCase().replace(/[\s]/gim, '-').replace(/[^a-z0-9\-\/]/gim, ''); },
	sURLEncode: function(sUnencoded) {
		sUnencoded = sUnencoded.replace(/\s/g, '+');
		return sUnencoded;
	},
	sURLUnencode: function(sEncoded) {
		sEncoded = sEncoded.replace(/\+/g, ' ');
		return sEncoded;
	},
	bValidEmail: function(sEmail) {
		var rEmail = new RegExp("^([a-zA-Z0-9_\\-\\.\\']+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", "gim");
		var sMatch = sEmail.match(rEmail);
		return (sMatch !== null);
	},
	Debug: function(e) {
		try {
		if (console === undefined) { return false; }
		console.log(e);
		} catch(e) {}
	},
	sDelimeter : '|||||'
}

$(document).ready(function(){
						   
	$('a[href="/forum"]').attr('rel', 'external');
						   
	$('a[rel="external"]').live('click', function(e){
		e.preventDefault();
		window.open($(this).attr('href'));
	});
	
	$('form[id!="search-form"]').each(function(){
		if ($(this).closest('section.login').length) { return; }
		formcheck.init(this);
	}); // not quite... nearly //this is a bit wasteful and needs to be cleaned up.
	
	$('nav#upcoming-events ol').each(function(){
		importevents.init(this);
	});
	
	if ($('body>section.login').length) { login.init(); }
	
	$('a#logout').click(function(e){ e.preventDefault(); login.logout($(this).attr('href')); })

	$('section#search input').each(function(){
		var oForm = $('<form action="/search" method="post"></form>');
		$(this).wrap(oForm);
		$(this).attr('name', 'search');
	});
	
	$('dl.protected ol.downloads a').each(function(){
		$(this).removeAttr('rel');
		$(this).attr('data-download', $(this).attr('href'));
		$(this).attr('href', '#');
		$(this).click(function(e){
			e.preventDefault();
			if ($(this).closest('dl').find('input.protected').is(':checked')) {
				window.open($(this).attr('data-download'));	
			}
		})
	});
	
	$('select[data-linked="true"]').change(function() {
		var sSelected = $(this).find(':selected').attr('data-linked') || '';
		$(this).find('option').each(function(){
			$('#' + ($(this).attr('data-linked') || '')).hide();
			$('#' + ($(this).attr('data-linked') || '')).find('input[data-required-if-visible="true"]').removeAttr('required');
		});
		$('#' + sSelected).show()
		$('#' + sSelected).find('input[data-required-if-visible="true"]').attr('required','')
	});
	
});

var importevents = {
	oNav : null,
	sRootURL : 'http://www.i2group.com',
	init : function(oNav) {
		if (!$(oNav).length) { return; }
		$(oNav).empty();
		this.oNav = $(oNav);
		var jqxhr = $.ajax({ url: "/interface.asp", data: {'function' : 'GetEventsData'} })
			.success(function(data) { importevents.success(data); })
			.error(function() { Utility.Debug('error'); })
			.complete(function() {});
	},
	success : function(oData) {
		for (sEvent in oData) {
			oData[sEvent].sEventTitle = (oData[sEvent].sEventTitle === null) ? oData[sEvent].sEventName : oData[sEvent].sEventTitle;
			$(this.oNav).append('<li class="' + Utility.sSafeName(oData[sEvent].sEventName) + '"><a href="' + this.sRootURL + oData[sEvent].sUrl + '" rel="external">' + oData[sEvent].sEventTitle + '</a></li>');
		}
		if ($(this.oNav).not(':visible')) {
			$(this.oNav).fadeIn('fast');	
		}
	}
}

			

var formcheck = {
	form : null,
	init : function(oForm) {
		try {
			if ($(oForm).length == 0) { return; }
			if ($(oForm).attr('id') == 'searchform') { return; }
			this.form = null;
			this.form = $(oForm);
			this.sFunction = $(this.form).find('input[id$="function"]').val();
			if (this.sFunction == '') { return; }
			this.asArguments = ($(this.form).find('input[id$="fields"]').val()).split(',')
			$(this.form).unbind();
			$(this.form).submit(function(e){ formcheck.submitform(e, this) });
			this.countryreplace();
		} catch(e) {
			return;
		}
	},
	submitform : function(e, form) {
		e.preventDefault();
		$(this.form).find('input[type="submit"]').attr('disabled','');
		var asPasswords = [];
		$(this.form).find('input[type="password"]').each(function(){ asPasswords.push($(this).val()); });
		if (asPasswords.length > 1) {
			for (var i = 1; i < asPasswords.length; i++) {
				if (asPasswords[i] !== asPasswords[i-1]) {
					$(this.form).find('input[type="password"]').addClass('invalid');
					alert('Your passwords do not match'); // terrible!
					$(this.form).find('input[type="submit"]').removeAttr('disabled','');
					return false;
				}
			}
		}

		if (Modernizr.input.required) { this.sendform(); return; }
		
		/* Ok, so on the more modern browsers input[required] works (as it should),
			but on < IE8 we need to use input[required=""] -- perfect case for using yepnope */
		
		$(this.form).find('input[required=""], textarea[required=""]').removeClass('invalid');
		var bOk = true;
		$(this.form).find('input[required=""], textarea[required=""]').each(function(){
			if ($(this).val() == '') { $(this).addClass('invalid'); bOk = false; }
			if ($(this).attr('type') == 'checkbox' && $(this).is(':not(:checked)')) { $(this).addClass('invalid'); bOk = false; }
		});
		$(this.form).find('input[type="email"]').each(function(){
			if (!Utility.bValidEmail($(this).val())) { $(this).addClass('invalid'); bOk = false; }
		})
		bOk ? this.sendform() : $(formcheck.form).find('input[type="submit"]').removeAttr('disabled');
	},
	getarguments : function() {
		var asArguments = [];
		for (var i = 0; i < this.asArguments.length; i++) {
			asArguments[i] = $('#' + this.asArguments[i]).val();
		}
		return asArguments;
	},
	sendform : function() {
		var oSubmission = {
			'function' : this.sFunction,
			'arguments' : this.getarguments().join(Utility.sDelimeter),
			'delimeter' : Utility.sDelimeter
		};
		var jqxhr = $.ajax({ url: "/interface.asp", data: oSubmission })
			.success(function(data) { formcheck.success(data); })
			.error(function() { Utility.Debug('error'); })
			.complete(function() {
				$(formcheck.form).find('input[type="submit"]').removeAttr('disabled');
			});
	},
	success : function() {
		$(this.form).closest('section').closest('article').css('height', $(this.form).closest('section').closest('article').height() + 'px');
		$(this.form).closest('section').fadeOut('fast', function(){ $('#success-text').fadeIn('fast', function(){
			setTimeout("try { $.scrollTo('body', 500, {easing: 'swing' }); } catch(e) {}", 500);
		});});
	},
	countryreplace : function() {
		asCountries = ['England', 'Scotland', 'Wales', 'Northern Ireland', 'Ireland', 'United States', 'Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Andorra', 'Angola', 'Anguilla', 'Antarctica', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia', 'Bosnia-Herzegovina', 'Botswana', 'Bouvet Island', 'Brazil', 'Brunei Darussalam', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Cayman Islands', 'Central African Republic', 'Chad', 'Channel Islands', 'Chile', 'China', 'Christmas Island', 'Cocos (Keeling) Island', 'Colombia', 'Comoros', 'Congo', 'Cook Islands', 'Costa Rica', 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'East Timor', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Falkland Islands', 'Faroe Islands', 'Fiji', 'Finland', 'France', 'French Guiana', 'French Southern Territories', 'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Gibraltar', 'Greece', 'Greenland', 'Grenada', 'Guadeloupe', 'Guam', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Heard and McDonald Islands', 'Honduras', 'Hong Kong', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Isle of Man', 'Israel', 'Italy', 'Ivory Coast', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea (North)', 'Korea (South)', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macau', 'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Martinique', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Montserrat', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nepal', 'Netherlands', 'Netherlands Antilles', 'New Caledonia', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Niue', 'Norfolk Island', 'Northern Mariana Islands', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Pitcairn', 'Poland', 'Polynesia', 'Portugal', 'Puerto Rico', 'Qatar', 'Reunion', 'Romania', 'Russian Federation', 'Rwanda', 'S. Georgia and S. Sandwich Islands', 'Saint Kitts and Nevis', 'Saint Lucia', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia and Montenegro', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'Spain', 'Sri Lanka', 'St. Helena', 'St. Pierre &amp; Miquelon', 'St. Vincent &amp; Grenadines', 'Sudan', 'Suriname', 'Svalbard and Jan Mayen Islands', 'Swaziland', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Togo', 'Tokelau', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks and Caicos Islands', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican City State', 'Venezuela', 'Vietnam', 'Virgin Islands (British)', 'Virgin Islands (US)', 'Western Sahara', 'Yemen', 'Yugoslavia', 'Zaire', 'Zambia', 'Zimbabwe'];
		$(this.form).find('input[id$="country"][data-replace="true"]').each(function(){
			var oNew = $('<select></select>');
			for (var i = 0; i < asCountries.length; i++) { $(oNew).append('<option value="' + asCountries[i] + '">' + asCountries[i] + '</option>'); }
			if ($(this).attr('required') !== undefined) { $(oNew).attr('required', ''); }
			if ($(this).val() !== '') { $(oNew).find('option[value="' + $(this).val() + '"]').attr('selected','selected'); }
			var asID = [$(this).attr('id'),$(this).attr('name')];
			$(this).attr('id','').attr('name','');
			$(oNew).attr('id', asID[0]).attr('name', asID[1]);
			$(oNew).insertAfter($(this));
			$(this).remove();
		});
	}
}

var login = {
	init : function() {
		this.oLogin = $('section.login');
		$(this.oLogin).find('a[href="#login"], a[href="#forgot"], a[href="#register"]').each(function(){
			$(this).click(function(e){ e.preventDefault(); login.show($(this).attr('href')); });
		});
		$(this.oLogin).find('input[type="email"]').change(function(){
			$(login.oLogin).find('input[type="email"][id!="' + $(this).attr('id') + '"]').val($(this).val())
		})
		formcheck.init($('section.login form:visible'));
		formcheck.success = this.success;
	},
	show : function(sWhat) {
		sWhat = (sWhat.charAt(0) === '#') ? sWhat.substr(1) : sWhat; // yes this is incredibly redundant
		if ($('#' + sWhat).is(':visible')) { return; }
		$(this.oLogin).css('height', $(this.oLogin).height() + 'px');
		$(this.oLogin).children('section:visible[id!="' + sWhat + '"]').fadeOut('fast', function() {
			formcheck.init($('#' + sWhat).find('form'));
			$('#' + sWhat).fadeIn('fast');
			$(login.oLogin).css('height', 'auto');
		});
	},
	success : function(data) {
		if (data.redirect !== undefined && data.redirect != '') {
			if (data.redirect.indexOf('#') == 0) {
				login.show(data.redirect.slice(1));
			} else if (data.redirect.indexOf('/') == 0) {
				window.location = data.redirect;
			}
		}
		if (data.result !== undefined && data.result != '' && data.result != 'ok') {
			$('#success-text').html($('<p>' + data.result + '</p>'));
			if (data.clear === undefined || data.clear == false) { $('#success-text').fadeIn('fast'); }
		}
		if (data.clear !== undefined && data.clear == true) {
			login.show('success-text');	
		}
	},
	logout : function(sLocation) {
		var oSubmission = {
			'function' : 'Logout'
		};
		var jqxhr = $.ajax({ url: "/interface.asp", data: oSubmission })
			.success(function(data) { window.location = sLocation; })
			.error(function() { Utility.Debug('error'); })
			.complete(function() {});
	}
}
