/* 	filename: library.js 
	author: Brian Teryek
*/

function getPageName()
{
	var urlstring = location.href;
	var pattern = /\/[a-zA-Z0-9-_]+[\/]*$/;
	
	var position = urlstring.search(pattern);
	var pagename = urlstring.substr(position + 1);
	
	var hyperlinks = document.getElementById('top-navigation-container').getElementsByTagName('a');
	
	for(var i in hyperlinks)
	{
		if(hyperlinks.item(i).getAttribute('href') == pagename)
		{
			hyperlinks.item(i).style.color = '#000';	
		}
	}						 
}

function preloader()
{
	var images = new Array();
	images[0] = 'images/icons/failed_mark.png';
	images[1] = 'images/icons/check_mark.png';
	images[2] = 'images/background_images/black_texture.png';
	images[3] = 'images/buttons/send_button_disabled.png';
	images[4] = 'images/buttons/send_button.png';
	images[5] = 'images/icons/apps_icon_hover.png';
	images[6] = 'images/icons/conversion_icon_hover.png';
	images[7] = 'images/icons/database_icon_hover.png';
	images[8] = 'images/icons/design_icon_hover.png';
	images[9] = 'images/icons/maintain_icon_hover.png';
	images[10] = 'images/icons/seo_icon_hover.png';
	
	for(var i = 0; i < images.length; i++)
	{
		var imgObject = new Image();
		imgObject.src = images[i];
	}
}

function init()
{
	getPageName();
	preloader();
	//RecentWork.items = totalScreenShots();
	//RecentWork.images = getImagesArray();
	//addIdsToImages();
	//setInterval('swapImage()', RecentWork.speed);
	document.getElementById('contact').style.display = 'none';
}

var BrowserDetect = 
{
	userAgent: navigator.userAgent,
	browser: navigator.appName
}

var Sites =
{
	titles: new Array('Bible Studies', 'JasperEcoTech', 'St. Augustine Cast Stone', 'Milestone Graphics', 'Studies in the Book', 'Ecotech Light &amp; Energy', 'St. Seraphims Fellowship'),
	descriptions: new Array('Design, HTML5, CSS, Javascript, jQuery, Php, MySQL', 'Design, HTML5, CSS, Javascript, jQuery, Php', 'Design, XHTML, Javascript, JQuery, PHP, MySQL, Custom CMS', 'PSD to XHTML, CSS, Javascript, JQuery, Php', 'Design, XHTML, CSS, Javascript, JQuery, Php, MySQL, Content Management System', 'Design, XHTML, CSS, Javascript, JQuery, Php, SEO', 'Design, XHMTL, CSS, Javascript, Php', 'Design, XHTML, CSS, Javascript, JQuery, Php, MySQL, Ajax') 
}

var RecentWork = 
{
	//properties
	speed: 3000, //in milliseconds
	animationSpeed: 900,
	list: 'site-screen-shots', //id where images are located
	title: 'site-title', //id of where title is placed
	description: 'site-description', //id of where description is placed
	items: 0, //default
	count: 0,
	images: null //default
	
	//methods
	
	
} //end RecentWork object

function addIdsToImages()
{	
	for(i = 0; i < RecentWork.images.length; i++)
	{
		RecentWork.images.item(i).setAttribute('id', ''+i+'');	
	}
	
}

function getImagesArray()
{
	return document.getElementById(RecentWork.list).getElementsByTagName('img');
}

function totalScreenShots()
{
	return document.getElementById(RecentWork.list).getElementsByTagName('img').length;
}

function swapSiteText(image, count)
{
	document.getElementById(RecentWork.title).innerHTML = Sites.titles[count];
	document.getElementById(RecentWork.description).innerHTML = Sites.descriptions[count];
	
	
	$('#'+RecentWork.title).css({ opacity: .5 });
	$('#'+RecentWork.description).css({ opacity: .5 });
	$('#'+count).css({ opacity: .5 });
	
	$('#'+RecentWork.title).animate({ opacity: 1 }, RecentWork.animationSpeed, function() { });
	$('#'+RecentWork.description).animate({ opacity: 1 }, RecentWork.animationSpeed, function() { });
	$('#'+count).animate({ opacity: 1 }, RecentWork.animationSpeed, function() { });

}

function showContactInfo()
{
	//$('#contact').animate({ top:0+'px' }, 700, function() { } );
	$('#contact').css({ display: 'block' });
	$('#contact').animate({ height:460+'px' }, 700, function() { } );
}

function hideContactInfo()
{
	$('#contact').animate({ height:0+'px' }, 700, function() { $('#contact').css({ display: 'none' }); } );
}


function swapImage()
{
	var i;
	var image = document.getElementById(RecentWork.list).getElementsByTagName('img');
	
	
	for(i = 0; i < RecentWork.items; i++)
	{

		
		
		if(image.item(i).style.display == 'block')
		{
			RecentWork.count+= 1;
			image.item(i).style.display = 'none';
		}
		
		
		if(i == RecentWork.count)
		{
			image.item(i).style.display = 'block';
			swapSiteText(image, i);
		}
		
		else
		{
			image.item(i).style.display = 'none';
		}
		
		if(RecentWork.count == RecentWork.items)
		{
			image.item(0).style.display = 'block';
			swapSiteText(image, 0);
			RecentWork.count = 0;
		}
		
		//console.log(RecentWork.count);
		
	}
}

function toggleSlices(id, state)
{
	
	var sliceElement = document.getElementById(id);
	var source = sliceElement.getElementsByTagName('img').item(0).src;
	var hover;
	
	switch(state)
	{
		case'over':
			hover = source.replace('.png', '_hover.png');
			sliceElement.getElementsByTagName('img').item(0).src = hover;
			sliceElement.style.backgroundImage = 'url(images/background_images/white_slice.png)';
			break;
			
		case 'out':
			hover = source.replace('_hover.png', '.png');
			sliceElement.getElementsByTagName('img').item(0).src = hover;
			sliceElement.style.backgroundImage = 'url(images/background_images/gray_slice.png)';
			break;
	}
	//sliceElement.style.color = "#fff";
	
}



//static Pattern class
	var Pattern = 
	{
		email: 					/^([a-zA-Z0-9_\.-])+@([a-zA-Z0-9])+\.([a-zA-Z.])+$/,
		phoneWithAreaCode:		/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/,
		phoneWithoutAreaCode:	/^[0-9]{3}-[0-9]{4}$/,
		onlyAlphaCharacters:	/^\w+$/,
		wordCharctersWithSpace: /^[a-zA-Z ]+$/
	}
	
	var FormValidation =
	{
		formID: 'message',
		pass: '<img src="images/icons/check_mark.png" alt="Passed" />',
		fail: '<img src="images/icons/failed_mark.png" alt="Failed" />',
		validationCount: 0, //default
		requiredFields: 4,
		
		validateNotEmpty: function(string, name)
		{
			if(string == null || string == '')
				FormValidation.showValidationStatus(name, 'failed');
			else
				FormValidation.showValidationStatus(name, 'passed');
		},
		
		validateWordCharactersWithSpace: function(string, name)
		{
			if(Pattern.wordCharctersWithSpace.test(string))
			
				FormValidation.showValidationStatus(name, 'passed');
			else
				FormValidation.showValidationStatus(name, 'failed');
		},
		
		validateOnlyAlphaCharacters: function(string, name)
		{
			if(Pattern.onlyAlphaCharacters.test(string))
			
				FormValidation.showValidationStatus(name, 'passed');
			else
				FormValidation.showValidationStatus(name, 'failed');
		},
		
		validateEmail: function(email, name)
		{
			if(Pattern.email.test(email))
				//show check mark
				FormValidation.showValidationStatus(name, 'passed');
			else
				//show X mark
				FormValidation.showValidationStatus(name, 'failed');
				
			var emailValue = document.getElementById(FormValidation.formID).elements[name].value;
			//alert(emailValue);
		},
		
		
		validatePhoneNumber: function(number, type, name)
		{
			switch(type)
			{
				case 'phoneWithAreaCode':
					if(Pattern.phoneWithAreaCode.test(number))
						FormValidation.showValidationStatus(name, 'passed');
					else
						FormValidation.showValidationStatus(name, 'failed');
					break;
				
				case 'phoneWithoutAreaCode':
					if(Pattern.phoneWithoutAreaCode.test(number))
					FormValidation.showValidationStatus('phone', 'passed');
					else
						FormValidation.showValidationStatus('phone', 'failed');
					break;
			}
		},
		
		showValidationStatus: function(elementName, status)
		{
			var indicatorId = elementName+'Indicator';
			
			
			
			switch(status)
			{
				case 'failed':
					updateStatus(indicatorId, FormValidation.fail);
					break;
				
				case 'passed':									
					updateStatus(indicatorId, FormValidation.pass);
					break;
			}
			
			checkRequiredFields();
		}
	};
	
	
function updateStatus(id, status)
{
	document.getElementById(id).innerHTML = status;
}
	
function clearValidationStatus(newElement, placeAfterThisNode)
{
	if(placeAfterThisNode.nextSibling.tagName == 'SPAN')
	{
		document.getElementById(FormValidation.formID).removeChild(placeAfterThisNode.nextSibling);	
	}
}

function checkRequiredFields()
{
	var images = document.getElementById(FormValidation.formID);
	var length = images.getElementsByTagName('img').length;
	
	if(length == FormValidation.requiredFields)
	{
		
		FormValidation.validationCount = 0;
		
		for(var i = 0; i < length; i++)
		{
			if(images.getElementsByTagName('img').item(i).getAttribute('alt') == 'Passed')
				FormValidation.validationCount++;
		}
		
	}
	
}

function sendForm()
{
	if(FormValidation.validationCount == FormValidation.requiredFields)
		return true;
	else
	{
		alert('All fields are required and must be filled out correctly!');
		return false;
	}
}


function sendQuestionnaire(form) {
	
	
	var hasError = false;
	var requiredFields = [];
	var errors = [];
	
		
	$('#form .required').each(function(i) {
				
		requiredFields.push(this.name);		
		validate(this);
		
	});
	
	//loop through required fields array to see if there are any that are false
	
	for(var index in requiredFields) {
		
		if(eval('RequiredFields.'+requiredFields[index]+'.valid') == false) {
			hasError = true;
			errors.push( eval('RequiredFields.'+requiredFields[index]+'.error') );
		}
		
	}
	
	if(hasError) {
				
		notifyOfError('There are Errors on the Form!<br /><br />'+errors.join('<br />'));
		return false;
		
	}	

	
	
	return true;

}


/*======================================= GLOBAL NOTIFICATION FUNCTIONS ========================================== */

function notification(msg, refresh, url) {

	$('body').append('<div id="global-notification">'+msg+'</div>');
	
	$('#global-notification').css({zIndex: 10, opacity: 0.95, top: '-50px'});
	
	$('#global-notification').animate({
			
		//animate to what?
		top: 0
	 
	}, 700, //duration of the entire animation
	
	function() { // a callback function once the animation is completed
	
		// Animation complete.
		
		setTimeout(function() {
		
		
			$('#global-notification').animate({
				
				//animate to what?
				top: '-50px'
			 
			}, 700, //duration of the entire animation
			
			function() { // a callback function once the animation is completed
			
				// Animation complete.
				
				$(this).remove();
				
				if(refresh) {
					
					if(url != null || url != '') {
						
						window.location = url;
						
					} else {
					
						window.location.reload();
					
					}
				} else {
				
					//$('#'+AMS.submitButton).val('Submit').css('opacity', 1).removeAttr('disabled');
				
				}
				
			});
			
		
		
		}, 3000);
		
	});
}


/* ====================================== Regular Expressions For Validation ================================== */

var Pattern = 
{
	email: 					/^([a-zA-Z0-9_\.-])+@([a-zA-Z0-9])+\.([a-zA-Z.])+$/,
	phoneWithAreaCode:		/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/,
	phoneWithoutAreaCode:	/^[0-9]{3}-[0-9]{4}$/,
	numbersAndDashes:		/^[0-9][0-9|\-\s]+$/,
	numbersAndSlashes:		/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/,
	onlyAlphaCharacters:	/^\w+$/,
	wordCharctersWithSpace: /^[a-zA-Z ]+$/,
	notEmpty:				/^[a-zA-Z0-9]+/,
	zipcode:				/^[0-9\-]+$/,
	numbersOnly:			/^[0-9]+$/,
	twonumbers:				/^[0-9]{1,2}$/,
	currencyNoCommas:		/^([0-9]+)([\.][0-9]{2})$/,
	servicePassword:		/^[a-zA-Z0-9]{6,15}$/,
	ampm:					/^(am)|(AM)|(pm)|(PM)$/
}



/* ============================================== Required Fields Object========================================= */

var RequiredFields = {	
	
	name: {
		valid:				false,
		error:				'You must enter your name',
		validation_type:	'notEmpty'
	},
	
	company: {
		valid:				false,
		error:				'You must enter your company name',
		validation_type:	'notEmpty'
	},
	
	phone: {
		valid:				false,
		error:				'You must enter your phone number',
		validation_type:	'notEmpty'
	},
	
	email: {
		valid:				false,
		error:				'You must enter a valid email',
		validation_type:	'email'
	}
	
}

//static Validate class


var Validate = {
	
	doValidation: function(string, type) {
		if(eval('Pattern.'+type+'').test(string))
			return true;
		else
			return false;
	}						
}


function validate(field)
{
	var fieldname = field.name;
	var value = jQuery.trim(field.value);
	var type = eval('RequiredFields.'+fieldname+'.validation_type');	
		
	if(!Validate.doValidation(value, type)) {
		//notifyOfError(field, eval('RequiredFields.'+(fieldname)+'.error'));
		eval('RequiredFields.'+(fieldname)+'.valid = false');
	}
	else {
		eval('RequiredFields.'+(fieldname)+'.valid = true');
	}
				
		
}

function notifyOfError(txt) {

	var message = $('<div class="form-message rounded-corners">'+txt+'</div>');
	$('body').append(message);
	
	w = $(message).width();
	h = $(message).height();
		
	$(message).css({marginTop: '-'+( (h / 2) - 20)+'px', marginLeft: '-'+( (w / 2) + 40)+'px', opacity:'0.0'});
	
	$(message).animate(
		{
			//animate to what?
			opacity: 0.8, 
	  	}, 
		
		500, //duration of the entire animation
	
		function() // a callback function once the animation is completed
		{
	    	setTimeout(function() {
	    	
	    		
	    		$(message).animate(
	    			{
	    				//animate to what?
	    				opacity: 0.0
	    		  	}, 
	    			
	    			350, //duration of the entire animation
	    		
	    			function() // a callback function once the animation is completed
	    			{
	    		    	// Animation complete.
	    		    	$(this).remove();
	    			}
	    		);
	    		
	    	
	    	}, 3000);
		}
	);
}
