/********************************************************************
* ConnectABILITY: jQuery Enhancements                               *
*                                                                   *
* version: 1.0                                                      *
* date:    Aug 8, 2010                                              *
********************************************************************/

// Ensure no conflict with other jQuery plugins
var $ca = jQuery.noConflict();

// Blank transparent gif (used for IE6 png transparency fix)
var blank = new Image();
blank.src = themeRoot + 'images/x.gif';

var feedbackScriptURL = themeRoot + 'cgi-bin/contact.php';

// Preload hover images
$ca( '<img src="' + themeRoot + 'images/form-btn-bg-hover.png" alt="" class="hidden" />' ).appendTo( 'body' );

var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

// Search form enhancements
$ca( document ).ready( function()
{
	// Add Feedback button
	var feedbackURL = $ca( '#footer .feedback-link' ).attr( 'href' );
	if ( !isIE6andBelow() ) {
		$ca( '<a class="feedback-link" href="' + feedbackURL + '" title="Tell us what you think about the site"><img src="' + themeRoot + 'images/feedback-btn.png" alt="Feedback [button]" /></a>' ).appendTo( 'body' );
	}
	
	// Dialog base code
	$ca( '<div id="feedback-dialog"></div>' ).appendTo( '#content' );
	$ca( '<div id="login-dialog"></div>' ).appendTo( '#content' );
	
	// Feedback vars
	var feedbackDialog = $ca( '#feedback-dialog' );
	var feedbackThankYou = '<h1>Thank You!</h1><p>We received your submission.</p><input id="feedback-close" class="button" type="submit" title="Close Window" value="Close" name="feedback-close">';
	var feedbackForm = '';
	var feedbackEnabled = false;
	var cacheEmail = '';
	
	// Configure feedback overlay dialog
	var feedbackDialogOpts = {
		dialogClass: 'feedback-dialog',
		modal: true,
		resizable: false,
		width: 660,
		height: 'auto',
		show: 'fade',
		hide: 'fade',
		open: function( event, ui )
		{
			var emailField = feedbackDialog.find( '#feedback-email' );
			emailField.val( cacheEmail );
			emailField.val() ? feedbackDialog.find( '#feedback-comment' ).focus() : emailField.focus();
			feedbackEnabled = true;
		},
		close: function( event, ui )
		{
			feedbackDialog.find( 'form' ).html( feedbackForm );
		}
 	};
	
	// Load feedback form
	$ca.get( feedbackURL, function( data )
	{
		// Get AJAX response text
		var data = $ca( data );
		
		// Find feedback form within response data
		var feedbackContent = data.find( '#feedback-form' );
		
		// Append feedback form html to dialog wrapper
		feedbackDialog.append( feedbackContent );
		feedbackEnabled = true;
		
		// Save form html
		feedbackForm = feedbackContent.html();
		feedbackDialog.find( 'form' );
		
		// Enable inline error checking
		feedbackDialog.find( 'form' ).submit( function( $e ) {
			$e.preventDefault();
			
			if ( feedbackEnabled ) {
				
				feedbackEnabled = false;
				
				// "Send" button action
				if ( feedbackDialog.find( '#feedback-send' ).length ) {
				
					// Error checking
					var foundErrors = false;
					var emailField = feedbackDialog.find( '#feedback-email' );
					var commentField = feedbackDialog.find( '#feedback-comment' );
					var emailFunc = function( $e ) {
						if ( !( emailFilter.test( emailField.val() ) ) ) {
							if ( !emailField.parent().has( '.error' ).length ) {
								foundErrors = true;
								feedbackDialog.find( 'label[for="feedback-email"]' ).append( '<span class="error"> - Please enter your email address</span>' );
								emailField.addClass( 'error' );
								emailField.focus();
							}
						} else {
							feedbackDialog.find( 'label[for="feedback-email"] span' ).remove();
							emailField.removeClass( 'error' );
						}
					}
					var commentFunc = function( $e ) {
						if ( !$ca.trim( commentField.val() ).length ) {
							if ( !commentField.parent().has( '.error' ).length ) {
								foundErrors = true;
								feedbackDialog.find( 'label[for="feedback-comment"]' ).append( '<span class="error"> - Please enter your comment</span>' );
								commentField.addClass( 'error' );
								commentField.focus();
							}
						} else {
							feedbackDialog.find( 'label[for="feedback-comment"] span' ).remove();
							commentField.removeClass( 'error' );
						}
					}
					
					// Trigger blur events to highlight errors, if any
					commentFunc( null );
					emailFunc( null );
					
					// Process form submission
					if ( !foundErrors ) {
						
						// Cache email address
						cacheEmail = emailField.val();
						
						// Send form
						var formVals = {
							'ajax'             : '1',
							'feedback-type'    : feedbackDialog.find( 'input[name="feedback-type"]:checked' ).val(),
							'feedback-email'   : emailField.val(),
							'feedback-comment' : commentField.val()
						};
						
						var success = function( data )
						{
							feedbackDialog.find( 'form' ).fadeOut( 'slow', function() {
								feedbackDialog.find( 'form' ).html( feedbackThankYou );
								feedbackDialog.find( 'form' ).fadeIn( 'slow' );
								feedbackEnabled = true;
							} );
						}
						
						$ca.post( feedbackScriptURL, formVals, success );
						
					} else {
						feedbackEnabled = true;
						emailField.keyup( emailFunc );
						commentField.keyup( commentFunc );
					}

				// "Close" button action
				} else {
					feedbackDialog.dialog( 'close' );
				}
			}
		});
	} );
	
	// Configure login/feedback overlay dialog
	$ca( '.feedback-link' ).click( function( $e ) 
	{
		$e.preventDefault();
		
		feedbackDialog.dialog( feedbackDialogOpts );
		
	} );
	
	// Enable "Print" option for posts
	$ca( '.post-options .print a' ).click( function()
	{ 
		window.print();
		return false;
	} );
	
	// If resolution is too low, hide feedback button
	function positionFeedbackBtn()
	{
		var minClearance = 30;	// min distance between #wrap and the button
		var availSpace = ( $ca( window ).width() - $ca( '#wrap' ).width() ) / 2;
		if ( availSpace >= minClearance ) {
			var newWidth = availSpace - 40;	// leave some space for scrollbars
			$ca( '#feedback-btn' ).css( 'visibility', 'visible' );
		} else {
			$ca( '#feedback-btn' ).css( 'visibility', 'hidden' );
		}
	}
	
	// Apply feedback button positioning on initial load and on resize window event
	positionFeedbackBtn();
	$ca( window ).bind( 'resize', positionFeedbackBtn );
	
	// Preload and enable hover images for primary navigation
	// NOTE: The script generates hover image filename by appending '-hover' 
	//       to the existing filename (e.g., 'image.png' -> 'image-hover.png')
	$ca( '#nav ul.primary li a img' ).each( function()
	{
		var initImg = $ca( this ).attr( 'src' );
		tmpImg = initImg.replace( /\-hover/, '' );	// currently selected image already has '-hover'
		var hoverImg = tmpImg.replace( /(.+?)(\.[^.]*$|$)/, '$1-hover$2' );
		$ca( '<img src="' + hoverImg + '" alt="" class="hidden" />' ).appendTo( 'body' );
		$ca( this ).hover( function()
		              { 
		                $ca( this ).attr( 'src', hoverImg );
										if ( isIE6andBelow() ) { fixPng( this ); };
									}, 
									function()
									{
										$ca( this ).attr( 'src', initImg );
										if ( isIE6andBelow() ) { fixPng( this ); };
									} );
	} );

	// Move 'Go' button next to keywords field in search form
	//$ca( '#search-go' ).insertAfter( '#search-keywords' );
	
	// Add 'Advanced Options' link to search form
	//$ca( '<p><a href="#" id="search-advanced-link">Advanced Options</a></p>' ).appendTo( '#searchform' );
	
	/* Open login screen in lightbox
	$ca('.option-login').click(function(){
		$ca.dialog( $ca(this).attr('href')+' #login', {
			complete: function(response) {
				response.find('#user_login').focus();
			}	
		});
		return false;
	});*/
	
	// Fix PNG transparency for IE6
	if ( isIE6andBelow() ) {
	 // get all pngs on page
	 $ca( 'img[src$=.png]' ).each( function() {
		 if ( !this.complete ) {
			 this.onload = function() { fixPng( this ) };
		 } else {
			 fixPng( this );
		 }
	 });
	}
});

function isIE6andBelow()
{
	var badBrowser = ( /MSIE ((5\.5)|6)/.test( navigator.userAgent ) && navigator.platform == 'Win32' );
	return badBrowser;
}

// Fix PNG transparency for IE6 and below
function fixPng( png )
{
	// get src
	var src = png.src;
	
	// set width and height
	if ( !png.style.width ) { png.style.width = $ca( png ).width(); }
	if ( !png.style.height ) { png.style.height = $ca( png ).height(); }
	
	// replace by blank image
	png.onload = function() { };
	png.src = blank.src;
	
	// set filter (display original image)
	png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
}



