/*
	Intellectual property of Twig Interactive LLC
	Do not reuse or alter without express permission
	http://www.twiginteractive.com
*/

/*
	Current version of Drupal-installed jQuery is 1.2.6
	Script to perform whatever DOM manipulation is required
*/

/* Twig Class */
var TWIG = {};

// Statics
TWIG.defaultTuringTestValue = 'Enter code...';
TWIG.defaultSearchValue = 'Enter Search Topic...';

// Toggles between default value and empty string
TWIG.toggleTextInputValue = (function() {
	function T(o,evt,defVal,len) {
		if (typeof(len) == 'undefined') {
			len = 60; // Default max length
		};
		if (evt == 'focus') {
			if (jQuery.trim(o.value) == defVal) {
				o.maxLength = len;
				o.value = '';
			};
		};
		if (evt == 'blur') {
			if (jQuery.trim(o.value) == '') {
				o.maxLength = defVal.length;
				o.value = defVal;
			};
		};
	}

	return T;
})();


// Checks email address against RFC rules
// Based on original PHP code by Cal Henderson (http://iamcal.com/publish/articles/php/parsing_email)
// Twig converted to JS regex
TWIG.isValidEmailAddress = (function() {
	function T(email) {
		var qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
		var dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
		var atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'+'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
		var quoted_pair = '\\x5c\\x00-\\x7f';
		var domain_literal = '\\x5b('+dtext+'|'+quoted_pair+')*\\x5d';
		var quoted_string = '\\x22('+qtext+'|'+quoted_pair+')*\\x22';
		var domain_ref = atom;
		var sub_domain = '('+domain_ref+'|'+domain_literal+')';
		var word = '('+atom+'|'+quoted_string+')';
		var domain = sub_domain+'(\\x2e'+sub_domain+')*';
		var local_part = word+'(\\x2e'+word+')*';
		var addr_spec = local_part+'\\x40'+domain;
		var filter = eval('/^' + addr_spec + '$/');
		
		if (filter.test(email)) { // Passes RFC RegEx
			// Sanity check for period '.' following @
			if (email.indexOf('.',email.indexOf('@')) >= 0) {
				return true;
			}
		}
		return false;
	}
	
	return T;
})();

// Checks input against RegEx for valid website URL
TWIG.isValidURL = (function() {
	function T(URL) {
		var urlMatch = /^https?:\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
		if (urlMatch.test(URL)) { // Passes RegEx
			// Sanity check for period '.' following //
			if (URL.indexOf('.',URL.indexOf('//')) >= 0) {
				return true;	
			}
		}
		return false;
	}
	
	return T;
})();

// Open a pop-up window with set parameters
TWIG.openWindow = (function() {
	function T(URL,Name,W,H,L,T,Scrolls,Resize) {
		// Used to control params of pop-ups
		var defProps = 'copyhistory=no,directories=no,fullscreen=no,location=no,menubar=no,status=no,titlebar=yes,toolbar=no';
		var poppedProps = '';
	
		if (W != null) {
			if (Scrolls == true) { W += 16; } // Allow for chrome in IE
			poppedProps += ('width='+W+',');
		}
		if (H != null) { poppedProps += ('height='+H+','); }
		if (L != null) { poppedProps += ('left='+L+','); }
		if (T != null) { poppedProps += ('top='+T+','); }
		poppedProps += 'scrollbars=' + ((Scrolls != false) ? 'yes' : 'no') + ',' ; // Default 1
		poppedProps += 'resizable=' + ((Resize != false) ? 'yes' : 'no') + ',' ; // Default 1
		poppedProps += defProps;

//		alert(poppedProps);		
		poppedUp = window.open(URL,Name,poppedProps);
		if (poppedUp) { setTimeout("poppedUp.window.focus();",100); };
		return poppedUp;
	}
	return T;
})();

// Used to set anchor targets for external links and pop-ups
TWIG.setExternalLinks = (function() {
	function T() {
		var anchors = jQuery('a'); // Get <a> tags
		anchors.each(function(idx){
			var a = jQuery(this);
			if (a.attr('class') == 'external') {
				if (a.attr('href').indexOf('.connectopensource.org/') == -1) {
					a.attr('target','_blank'); // Set target
				};
			};
		});
	}
	
	return T;
})();

// Enforce maximum lengths on text input boxes and textareas, driven by attributes
// Assumes length given by either 'maxlength' or 'cols' attributes 
TWIG.limitInputLengths = (function() {
	function T() {
		var limitTextInputs = (function(evt) {
			var maxLength = (jQuery(this).attr('cols') ? jQuery(this).attr('cols') : jQuery(this).attr('maxlength'));
			var inputLength = this.value.length;
	
			if (evt.type == 'keypress') { // Text added via keyboard
				var key = evt.which;
				if (!evt.ctrlKey && (key >= 32 || key == 13)) { // Allow deletion and CTRL shortcuts
					if (inputLength >= maxLength) {
						evt.preventDefault(); // Prevent addition
					};
				};
			}
			else if (evt.type == 'change') { // Text added via mouse
				if (inputLength >= maxLength) {
					jQuery(this).val(jQuery(this).val().substr(0, maxLength)); // Crop
				};
			};
		});

/*
		// Text and password inputs, but not Turing tests
		jQuery('input[type="text"],input[type="password"]').not('.turingTest').unbind('keypress.limitInputLengths').bind('keypress.limitInputLengths', limitTextInputs);
		jQuery('input[type="text"],input[type="password"]').not('.turingTest').unbind('change.limitInputLengths').bind('change.limitInputLengths', limitTextInputs);
*/	

		// Textarea inputs
		jQuery('textarea').unbind('keypress.limitInputLengths').bind('keypress.limitInputLengths', limitTextInputs);
		jQuery('textarea').unbind('change.limitInputLengths').bind('change.limitInputLengths', limitTextInputs);
	};

	return T;
})();

/*
	Replace line breaks with <br />
	Optionally replace 2 consecutive line breaks with </p><p> and/or tabs to X spaces
*/
TWIG.nl2br = (function() {
	function T(i, brs2p, t2s) {
		if (typeof(i)=='string') {
			var re = new RegExp("\\n","gim"); // Escape the \n
			var o = i.replace(re, "<br />"); // Standard
			delete re;
			
			if (brs2p==true) {
				var re = new RegExp("(<br />){2}","gim");
				o = o.replace(re, "</p><p>");
				delete re;
			};

			if ((typeof(t2s)=='number') && (t2s>0)) {
				var s=''; for (j=0;j<t2s;j++) { s=s+"&nbsp;"; };
				var re = new RegExp("\\t","gim"); // Escape the \t
				o = o.replace(re, s);
			};
			return o;
		};
		return false;
	}
	return T;
})();

/* onReady */
jQuery(document).ready(function($) { // Must use jQuery $ wrapper when running in noConflict mode

	// PNG fix for IE6
	$(document).pngFix();
	
	// Set external links using custom function
	TWIG.setExternalLinks();
	
	// FORM: Get Updates
		// Set toggles on form inputs
		$('#webform-client-form-289 #edit-submitted-email').bind('focus', function(evt) {
			TWIG.toggleTextInputValue(this,evt.type,'Email',250);
		});
		$('#webform-client-form-289 #edit-submitted-email').bind('blur', function(evt) {
			TWIG.toggleTextInputValue(this,evt.type,'Email');
		});
		$('#webform-client-form-289 #edit-submitted-organization').bind('focus', function(evt) {
			TWIG.toggleTextInputValue(this,evt.type,'Organization',250);
		});
		$('#webform-client-form-289 #edit-submitted-organization').bind('blur', function(evt) {
			TWIG.toggleTextInputValue(this,evt.type,'Organization');
		});

		$('#webform-client-form-289').bind('submit',function(evt) {
			/* evt.preventDefault(); */
			var e = $('#edit-submitted-email',this);
			var o = $('#edit-submitted-organization',this);
			var c = $('#edit-captcha-response',this);
			
			if (!TWIG.isValidEmailAddress(e.val())) {
				alert("Please enter a valid email address.");
				e.focus();
				return false;
			};
			if (($.trim(o.val()) == '') || ($.trim(o.val()) == 'Organization')) {
				alert("Please enter your organization.");
				o.focus();
				return false;
			};
			/* Homepage only */
			if ($('body').hasClass('front')) {
				if ($('fieldset#edit-captcha').length > 0) {
					// User is logged in - no CAPTCHA
					return true;
				}
				if (!$('fieldset.captcha img').hasClass('shown')) {
					$('#webform-component-email').add('#webform-component-organization').hide();
					$('#edit-submit').val('Enter Anti-Spam Code');
					$('fieldset.captcha img').addClass('shown');
					$('fieldset.captcha').show();
					alert("Please enter the anti-spam code displayed in the image to the left.");
					c.focus();
					return false;
				}
				else {
					if ($.trim(c.val()) == '') {
						alert("Please enter the characters shown in the spam-protection image to the left.");
						c.focus();
						return false;
					};
				};
			}
			else if ($.trim(c.val()) == '') {
				alert("Please enter the characters shown in the spam-protection image.");
				c.focus();
				return false;
			};
			return true;
		});
		
		$('#search_q_template').bind('focus', function(evt) {
			TWIG.toggleTextInputValue(this,evt.type,TWIG.defaultSearchValue,250);
		});
		$('#search_q_template').bind('blur', function(evt) {
			TWIG.toggleTextInputValue(this,evt.type,TWIG.defaultSearchValue);
		});
		if ($('#search_q_template').val() == '') { $('#search_q_template').val(TWIG.defaultSearchValue); };

		// Bind submit
		$('form#frm_search_template').bind('submit',function(evt){
			el = $('#search_q_template');
			if (($.trim(el.val()).length == 0) || (el.val() == TWIG.defaultSearchValue)) {
				alert("Please enter a keyword to search the site.");
				el.focus();
				return false;
			};
		});
	
	
	// Remove link from Products tab
	$('#mainNavigation li.menu-path-node-29 a[href="/product"]').attr('href','javascript:void(0);');
	
	// Ensure top tab is highlighted (bug in Blog section)
	$('#mainNavigation ul.nice-menu > li:has("a.active")').addClass('active-trail');
	$('body.section-blog #mainNavigation ul.nice-menu > li.menu-path-blog').addClass('active-trail');
	
	// Remove empty secondary navigation container: stupid IE whitespace issues requires iterating thru LIs
	if ((secNav = $('#secondaryNavigation')).length > 0) {
		var empty = true;
		$('> ul.menu > li', secNav).each(function(index, element) {
            if ($(element).height() > 0) {
				empty = false;
			};
        });
		if (empty) { secNav.remove(); };
	};

});
