// Greg Babula
// Front-End Developer
// QuinnCom.net

$().ready( function(){
	var error = function( jqXHR, textStatus, errorThrown ) {
			var message = null,
				display = null;
			
			if ( jqXHR.status == 0 )
				message = 'You are offline! \n Please check your network.';
			else if ( jqXHR.status == 404 )
				message = 'Requested URL not found.';
			else if ( jqXHR.status == 500 )
				message = 'Internal server error.';
			else if ( textStatus == 'parsererror' )
				message = 'Parsing JSON Request failed.';
			else if ( textStatus == 'timeout' )
				message = 'Request time out.';
			else 
				message = 'Unknown Error.';
			
			if ( message )
				$( 'body' )
					.append( '<div id="notification"><div style="width:900px;margin:0 auto;">' + message + '<br />' + jqXHR.responseText + '</div>' 
					)
					.find( 'div#notification' )
					.css({
						display: 'none',
						position: 'absolute',
						zIndex: '9999',
						top: 0,
						left: 0,
						background: '#ffecc7',
						color: '#964f16',
						overflow: 'hidden',
						width: '100%',
						padding: '60px 0',
						fontSize: '16pt',
						borderBottom: '1px solid #e3b794'
					})
					.show( 500, function(){
						setTimeout( '$("div#notification").fadeOut( 1000, function(){ $( this ).remove(); });', 5000 );
					});
			};
			
	$.ajaxSetup({ error: error });
});

$(document).ready(function() {

	//Sub Nav Toggle
	$( '.sub-nav .toggle' ).click( function( click_event ) {
			var a = $( this );

			a.next().toggle('slow');
			a.toggleClass('up-arrow');
			//return false;
		}).next().hide();

	$('ul.active-menu').show();

	$('.careers-and-culture').click(function() {
		$(this).toggleClass('careers-and-culture')
	});

	//Slideshow
	$(function(){
		$('.featured-img img:gt(0)').hide();
		setInterval(function(){$('.featured-img :first-child').fadeOut('slow').next('img').fadeIn('slow').end().appendTo('.featured-img');}, 4500);
	});

	//Learn More Button
	$('.learn-more a').hover(function() {
		$(this).prev('span').toggleClass('hvr');
	});

	//Smooth Scroll To Top
	$(".return-top").click(function() {
		$("html, body").animate({
			scrollTop: $($(this).attr("href")).offset().top + "px"
		}, {
			duration: 250,
			easing: "swing"
		});
		return false;
	});

    //Remove padding from last paragraph
     $(".cols p:last-child").css("padding-bottom","0");

	//HTML5 Placeholder Fallback

	// Create input element to do tests
	var input = document.createElement('input');

	// Add placeholder support for non HTML5 browsers
	var support_placeholder = 'placeholder' in input;
	if(!support_placeholder){
		$(':input[placeholder]').each(function() {
			var $$ = $(this);
			if($$.val() === '') {
		   
				$$.addClass('placeholder');
				$$.val($$.attr('placeholder'));
			}
			$$.focus(function() {
				$$.addClass('focus');
				if($$.val() === $$.attr('placeholder')) {
					$$.val('');
					$$.removeClass('placeholder');
				}
			}).blur(function() {
				$$.removeClass('focus');
				if($$.val() === '') {
					$$.addClass('placeholder');
					$$.val($$.attr('placeholder'));
				}
			});
		});
	}

	// Add autofocus support for non HTML5 browsers
	var support_autofocus = 'autofocus' in input;
	if(!support_autofocus){
		$('input[autofocus]').eq(0).focus();
	}else{
		// Fix for opera
		$('input[autofocus]').eq(0).val('');	
		$('input[autofocus]').eq(0).removeClass('placeholder');
	}

	// Handler form validation
	$('input,textarea').keyup(function() {
		validate(this);
	});

	// Validate an element
	function validate(element){
		var $$ = $(element);
		var validator = element.getAttribute('type'); // Using pure javascript because jQuery always returns text in none HTML5 browsers
		var valid = true;
		var apply_class_to = $$;
		
		var required = element.getAttribute('required') == null ? false : true;
		switch(validator){
			case 'email': valid = is_email($$.val()); break;
			case 'url': valid = is_url($$.val()); break;
			case 'number': valid = is_number($$.val()); break;
		}
		
		// Extra required validation
		if(valid && required && $$.val().replace($$.attr('placeholder'), '') == ''){
			valid = false;
		}
		
		// Set input to valid of invalid
		if(valid || (!required && $$.val() == '')){
			apply_class_to.removeClass('invalid');
			apply_class_to.addClass('valid');
			return true;
		}else{
			apply_class_to.removeClass('valid');
			apply_class_to.addClass('invalid');
			return false;
		}
	}

	// Add required class to inputs
	$(':input[required]').addClass('required');

	// Block submit if there are invalid classes found
	$('form').submit(function() {
		$('input,textarea').each(function() {
			validate(this);
		});
		if(($(this).find(".invalid").length) == 0){
			// Delete all placeholder text
			$('input,textarea').each(function() {
				if($(this).val() == $(this).attr('placeholder')) $(this).val('');
			});
			return true;
		}else{
			return false;
		}
	});

	function is_email(value){
		return (/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/).test(value);
	}

	function is_url(value){
		return (/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i).test(value);
	}

	function is_number(value){
		return (typeof(value) === 'number' || typeof(value) === 'string') && value !== '' && !isNaN(value);
	}
	
	/* add a click handler to any links with the
	 * class `contact` to display a dialog box with
	 * the contact information form 
	 */
	$( '.contact-us' ) /* select `contact` anchors */
		.click( function( click_event ){ /* attach a click event */
			var	anchor = $( this ),
				options = {
					trigger: anchor,
					heading: 'Contact Us',
					message: ' ',
					url: 'contact-us.html',
					width: 500,
					after_show: function( contents, dialog ){
						$( contents ).find( 'input#name' ).focus();
					},
					buttons: [ { 
						label: 'Submit', 
						click:	function( button, contents, dialog ){
									var errors = [],
										options = {};
									
									/* don't allow a second submit */
									dialog.buttons[0].disable();
									/* show a progress meter */
									dialog.meter = $( dialog.footer )
									   .prepend( '<img src="images/progress.gif" style="margin:0 20px 5px 0;vertical-align:middle;" />' )
									   .find( 'img' )
									   ;
								    
									$( contents ).find( 'label.required' ).each( function( index ){
										var label = $( this ),
											value = '';
										
										if ( label.find( 'textarea' ).length > 0 ) 
											value = label.find( 'textarea' ).val();
										else 
											value = label.find( 'input' ).val();
									
										if ( value === '' || value === null )
											errors.push( label.attr( 'for' ) + ' can not be left empty.' );
									});
									
									if ( errors.length > 0 ){
										options = {
											trigger: button,
											heading: 'Oops! Problems found.',
											message: errors,
											classes: 'error',
											autoclose_delay: 5000
										};
										window.dialog( options );
                                        
                                        /* reenable the send button */
                                        dialog.buttons[0].disable( false );
                                        /* hide the progress meter */
                                        dialog.meter.remove();
                                        
										return false;
									} else {
										/* this area is where we take the form information
										 * and e-mail it to the client or send it to another
										 * php page that will stuff it into a database
										 */
										 $.ajax({
                                            context: $( contents ),
                                            data: {
                                            	to: $( 'select#to' ).val(),
                                            	department: $( 'select#to option:selected' ).text(),
                                            	name: $( 'input#name' ).val(),
                                            	company: $( 'input#company' ).val(),
                                            	email: $( 'input#email' ).val(),
                                            	phone: $( 'input#phone' ).val(),
                                            	message: $( 'textarea#message' ).val()
                                            },
                                            dataType: 'html',
                                            success: function( data ){
                                            	$( this ).html( data );
                                            	$( dialog.buttons[0].reference ).hide();
                                            	$( dialog.buttons[1].reference ).html( 'Close' );
                                            },
                                            error: function( jqXHR, textStatus, errorThrown){
                                    			var message = null,
                                    				display = null;
                                    			
                                    			if ( jqXHR.status == 0 )
                                    				message = 'You are offline! \n Please check your network.';
                                    			else if ( jqXHR.status == 404 )
                                    				message = 'Requested URL not found.';
                                    			else if ( jqXHR.status == 500 )
                                    				message = 'Internal server error.';
                                    			else if ( textStatus == 'parsererror' )
                                    				message = 'Parsing JSON Request failed.';
                                    			else if ( textStatus == 'timeout' )
                                    				message = 'Request time out.';
                                    			else 
                                    				message = 'Unknown Error.';
                                    			
                                    			if ( message )
                                    				$( 'body' )
                                    					.append( '<div id="notification"><div style="width:900px;margin:0 auto;">' + message + '<br />' + jqXHR.responseText + '</div>' 
                                    					)
                                    					.find( 'div#notification' )
                                    					.css({
                                    						display: 'none',
                                    						position: 'absolute',
                                    						zIndex: '9999',
                                    						top: 0,
                                    						left: 0,
                                    						background: '#ffecc7',
                                    						color: '#964f16',
                                    						overflow: 'hidden',
                                    						width: '100%',
                                    						padding: '60px 0',
                                    						fontSize: '16pt',
                                    						borderBottom: '1px solid #e3b794'
                                    					})
                                    					.show( 500, function(){
                                    						setTimeout( '$("div#notification").fadeOut( 1000, function(){ $( this ).remove(); });', 5000 );
                                    					})
                                    					;

                                                dialog.meter.remove();
                                                dialog.buttons[0].enable();
                                            },
                                            type: 'POST',
                                            url: 'contact-us-process.asp'
										 });
										 
										return false;
									}
								}
						},
						{ label: 'Cancel' }
					]
				},
				dialog = window.dialog( options );
				
				click_event.preventDefault();
		});
});
