/** @Name		pt Health Initilization
 ** @URI		http://www.pthealth.ca/
 ** @Author		PxO Ink
 ** @AuthorURI	http://www.pxoink.net/
 ** @License	Proprietary.
 ** @Copyright	© 2011 PxO Ink. All Rights Reserved.
 **/

//Declare global variables.
var	map;
var	bounds;
var	directions;
var	directionsRender;
var	infoWindow;
var	markerArray	=	new Array();
var	show	=	4;
var	page	=	0;
var	pagMax	=	0;
var	pagMin	=	0;
var	change;

jQuery(document).ready(function() {
	//Handle categorical link activation.
	jQuery('.pt-nav-activate ul li a').each(function() {
		//Declare variables.
		var	exp	=	new	RegExp(jQuery(this).attr('href'), 'i');
		
		if (jQuery(location).attr('href').search(exp) > 0) {
			jQuery(this).addClass('active');
		} 
	});
	
	//Ensure that nods are removed.
	jQuery('.nav-nod').each(function() {
		jQuery(this).removeClass('nod');
	});
	
	//Ensure each navigation element that is set for hoverable action.
	jQuery('.nav-nod > div').each(function() {
		//Grab the old class and reform it.
		var	id			=	'hover-' + jQuery(this).attr('class');
		
		//Add the new class.
		jQuery(this).addClass('nav-hover');
		
		//Add the new ID.
		jQuery(this).attr('id', id);
		
		//Hide the element.
		jQuery(this).hide();
	});
	
	//For each navigational element.
	jQuery('.pt-hover > ul li a').each(function() {
		//Declare variables.
		var	id					=	'#hover-' + jQuery(this).attr('id');
		var	height				=	0;
		window.ptID				=	id;
		window.ptFocus			=	false;
		var	position			=	jQuery(this).position();
		var	containerWidth		=	jQuery('#container').width();
		var	containerPosition	=	jQuery('#container').position();
		
		//Set the location of the megamenu element. V3.
		if (((position.left - 20) + jQuery(id).outerWidth()) < (containerPosition.left + containerWidth)) {
			jQuery(id).css('left', Math.ceil(position.left - 20));
		} else if (((position.left - 40) - (((position.left - 20) + jQuery(id).outerWidth()) - ((containerPosition.left) + containerWidth))) > containerPosition.left) {
			jQuery(id).css('left', Math.ceil((position.left - 40) - (((position.left - 20) + jQuery(id).outerWidth()) - ((containerPosition.left) + containerWidth))));
		} else {
			jQuery(id).css('left', Math.ceil((containerPosition.left + (containerWidth - jQuery(id).outerWidth()) / 2)));
		}
		
		/*//Set the location of the megamenu element. V2.
		if ((position.left + jQuery(id).outerWidth() - containerPosition.left) > containerWidth) {
			jQuery(id).css('left', Math.ceil((containerPosition.left + (containerWidth - jQuery(id).outerWidth()) / 2)));
		} else if ((position.left - containerPosition.left) < 20) {
			jQuery(id).css('left', position.left);
		} else {
			jQuery(id).css('left', Math.ceil(position.left - 20));
		}*/
		
		/*//Set the location of the megamenu element. V1.
		if (((position.left - containerPosition.left) + (jQuery(id).outerWidth()  - (0.05 * containerWidth))) > containerWidth) {
			jQuery(id).css('left', Math.ceil((containerPosition.left + (containerWidth - jQuery(id).outerWidth()) / 2)));
		} else if ((position.left - containerPosition.left) < (0.05 * containerWidth)) {
			jQuery(id).css('left', position.left);
		} else {
			jQuery(id).css('left', Math.ceil(position.left - (0.025 * containerWidth)));
		}*/
		
		//Handle hover intention.
		jQuery(this).hoverIntent(function() {		
			//Slide the element down.
			jQuery(id).slideDown(500, function() {
				//Ensure the heights are set correctly.
				jQuery(id + ' .nav-break').each(function() {
					if (jQuery(this).outerHeight() > height) {
						height = jQuery(this).outerHeight();
					}
					
					//Determine if this is the last child.
					if (jQuery(this).index() == jQuery(this).siblings().length) {
						jQuery(id + ' .nav-break').each(function() {
							//Set the height.
							jQuery(this).css('height', height);
						});
					}
				});
			});
			
			//If the mouse enters into the object.
			jQuery(id).mouseenter(function() {
				//Alert the system that the user has focused.
				window.ptFocus	=	true;
			}).mouseleave(function() {
				//Alert the system that the user has lost focus.
				window.ptFocus	=	false;
				
				//Slide the element up.
				jQuery(this).slideUp(500);
			});
		}, function() {
			//Set a timer in case the user focuses. 
			setTimeout(function() {
				if (window.ptFocus != true) {
					//Slide up.
					jQuery(id).slideUp(500);
				}
			}, 500);
		});
	});

	//If autocomplete is there.
	if (jQuery.autocomplete) {
		//Set the autocomplete to active.
		jQuery('.location-search').autocomplete('/lib/autocomplete-regional.php', {minChars:'2'});
	}
	
	//Always allow the first tab to be visible.
	jQuery('.tabbed-content > div').first().show();
	
	//Always activate the first tab to be visible.
	jQuery('.tabs > li a').first().addClass('active');
	
	//Tabbed navigation control.
	jQuery('.tabs a').click(function() {
		//Remove the active class.
		jQuery('.tabs a').each(function() {
			jQuery(this).removeClass('active');
		});
		
		//Fade all of the content out.
		jQuery('.tabbed-content > div').each(function() {
			jQuery(this).fadeOut('fast');
		});

		//Fade the content in.
		jQuery(jQuery(this).attr('title').toLowerCase().replace(/ /g, '')).fadeIn('medium');
		
		//Set the active class.
		jQuery(this).addClass('active');
	});
	
	//Remove the border from the last tab.
	jQuery('div#tab-navigation ul li:last-child a').css('border-width', '0px');
	
	//Fade out all of the listing.
	jQuery('.pagination').children('.listing').hide(function() {
		//Initialize pagination.
		jQuery('.pagination').children('.listing').slice(0, show).show();
		
		//Set the maximum and minimum number of pages.
		pagMax	=	jQuery('.pagination').children('div.listing').size();
		pagMin	=	Math.floor(pagMax / show);
	});
	
	//Slide toggle app.
	jQuery('.slide-toggle').click(function() {
		jQuery('.' + jQuery(this).attr('id')).slideToggle();
	});
	
	//Insure the banners are hidden if empty.
	if (jQuery('#banner:empty')) jQuery('#banner').hide();
	
	//Process request for submissions.
	jQuery('input.green-button[type="submit"]').click(function() {
		formDisplayProcessRequest(this);
	});
});

function clearVal(obj, deftxt) {	
	//Clear the value.
	if (jQuery(obj).val() == deftxt) jQuery(obj).val('');
}

function initializeMap(id) {
	//Declare variables.
	var	latlng			=	new google.maps.LatLng(56.130366, -106.346771);
	var myOptions 		=	{
								zoom:		4,
								center:		latlng,
								mapTypeId:	google.maps.MapTypeId.ROADMAP
							};
	map					=	new google.maps.Map(document.getElementById(id), myOptions);
	bounds				=	new google.maps.LatLngBounds();
	directions			=	new google.maps.DirectionsService();
	directionsRender	=	new google.maps.DirectionsRenderer();
	infoWindow			=	new google.maps.InfoWindow({content : 'Loading...'});
}

function getLatLng(obj) {
	//Declare variables.
	var	latitude	=	jQuery(obj).children('.latlng').children('.latitude').text();
	var	longitude	=	jQuery(obj).children('.latlng').children('.longitude').text();

	var	coordinates	=	new google.maps.LatLng(parseFloat(latitude), parseFloat(longitude));

	//Return the coordinates.
	return coordinates;
}

function addMarker(title, content, latlng) {
	//Create a marker.
	var	marker	=	new google.maps.Marker({
										position:	latlng,
										map:		map,
										title:		title
										});
	
	//Extend the bounds.
	bounds.extend(marker.position);
	
	//Add the marker click listener.
	google.maps.event.addListener(marker, 'click', function() {
		//Set the content.
		infoWindow.setContent(content);
		infoWindow.open(map, this); 
	});
	
	//Add the marker to the array.
	markerArray.push(marker);
	
	//Fit the bounds.
	map.fitBounds(bounds);
}

function	loadDirections(address) {
	//Declare variables.
	loadedContent	=	new Array();
	
	//Set the content to be loaded.
	loadedContent.push(
		'<h3>Get Directions</h3>',
		'<form action="location.php" onsubmit="return false;" method="get">',
			'<label for="start">Your Address* </label><input id="start" type="text" style="width: 80%;" name="start" /><input class="orange-button" type="submit" name="do" value="Get Directions" onclick="getDirections(\'' + address + '\');" />',
		'</form>'
	);
	
	//Set the content.
	jQuery('#get-directions').html(loadedContent.join(''));
	
	//Fade the content down.
	jQuery('#get-directions').slideDown();
}

function	getDirections(destination) {
	//Declare variables.
	var	request	=	{
						origin:			jQuery('#start').val(),
						destination:	destination,
						travelMode:		google.maps.DirectionsTravelMode.DRIVING
					}
	
	//Set the directions rendering map.
	directionsRender.setMap(map);
	
	//Suppress info windows.
	directionsRender.suppressInfoWindows	=	true;
	
	//Set the text directions rendering panel.
	directionsRender.setPanel(document.getElementById('show-directions'));
	
	//Calculate the route.
	directions.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			//Set the directions in the map.
			directionsRender.setDirections(response);
			
			//Slide down the actual directions.
			jQuery('#show-directions').slideDown();
			
			//Slide up the directional box.
			jQuery('#get-directions').slideUp();
		}
	});
}

function	drillDown() {
	//Declare variables.
	var	province	=	jQuery('#region').val();
	var	city		=	jQuery('#city').val();
	var	service		=	jQuery('#service').val()
	var	results		=	new Array();
	
	//Use JSON to get asynchronous data.
	jQuery.ajax({
		url:		'/lib/location-json-response.php',
		dataType:	'json',
		data:		{
						region	:	province,
						city	:	city,
						service	:	service
					},
		success:	function (data) {
			//Get the data.
			jQuery.each(data, function(index, array) {
				results[index]		=	array;
			});
			
			//Depending on the type of data.
			if (results['province']) {
				//Remove all options.
				jQuery('#region').empty();
				
				//If there is no province.
				if (!province || province == '%')	jQuery('#region').append(jQuery('<option></option>').val('%').html('Select a Region'));
				
				//Add the options.
				jQuery.each(results['province'], function(index, data) {
					jQuery('#region').append(jQuery('<option></option>').val(data).html(data));
				});
			}
			
			if (results['city']) {
				//Remove all options.
				jQuery('#city').empty();
				
				//If there is no city.
				if (!city || city == '%')	jQuery('#city').append(jQuery('<option></option>').val('%').html('Select a City'));
				
				//Add the options.
				jQuery.each(results['city'], function(index, data) {
					jQuery('#city').append(jQuery('<option></option>').val(data).html(data));
				});
			}
			
			if (results['service']) {
				if (jQuery('#service')) {
					//Remove all options.
					jQuery('#service').empty();
				
					//If there is no service.
					if (!service || service == '%')	jQuery('#service').append(jQuery('<option></option>').val('%').html('Select a Service'));
					
					//Add the options.
					jQuery.each(results['service'], function(index, data) {
						jQuery('#service').append(jQuery('<option></option>').val(index).html(data));
					});
					
					//Final option.
					jQuery('#service').append(jQuery('<option></option>').val('Other').html('Other or N/A'));
				}
			}
		},
	error: function(xhr, textStatus, thrownError) {
		//Error handling.
		console.log('There was an error processing the JSON request.');
		console.log('JSON XHR XML: ' + xhr.responseXML);
		console.log('JSON XHR XML: ' + xhr.responseText);
		console.log('JSON Status: ' + textStatus);
		console.log('JSON Error as follows:');
		console.log(thrownError);
		}
	});
}

function	resetLocation() {
	//Declare variables.
	var	results		=	new Array();
	
	//Use JSON to get asynchronous data.
	jQuery.ajax({
		url:'/lib/location-json-response.php',
		dataType: 'json',
		data:	{
					region	:	'',
					city	:	'',
					service	:	''
				},
		success:	function (data) {											
			//Get the data.
			jQuery.each(data, function(index, array) {
				results[index]		=	array;
			});
			
			//Depending on the type of data.
			if (results['province']) {
				//Remove all options.
				jQuery('#region').empty();
				
				//Initial option.
				jQuery('#region').append(jQuery('<option></option>').val('%').html('Select a Region'));
				
				//Add the options.
				jQuery.each(results['province'], function(index, data) {
					jQuery('#region').append(jQuery('<option></option>').val(data).html(data));
				});
				
				//Set the value.
				jQuery('#region').val('%');
			}
			
			if (results['city']) {
				//Remove all options.
				jQuery('#city').empty();
				
				//Initial option.
				jQuery('#city').append(jQuery('<option></option>').val('%').html('Select a City'));
				
				//Add the options.
				jQuery.each(results['city'], function(index, data) {
					jQuery('#city').append(jQuery('<option></option>').val(data).html(data));
				});
				
				//Set the value.
				jQuery('#city').val('%');
			}
			
			if (results['service']) {
				//Remove all options.
				jQuery('#service').empty();
			
				//Initial option.
				jQuery('#service').append(jQuery('<option></option>').val('%').html('Select a Service'));
				
				//Add the options.
				jQuery.each(results['service'], function(index, data) {
					jQuery('#service').append(jQuery('<option></option').val(index).html(data));
				});
				
				//Final option.
				jQuery('#service').append(jQuery('<option></option>').val('Other').html('Other or N/A'));
				
				//Set the value.
				jQuery('#service').val('%');
			}
		},
	error: function(xhr, ajaxOptions, thrownError) {
			//Error handling.
			console.log('There was an error processing the JSON request.');
			console.log('JSON Status: ' + xhr.status);
			console.log('JSON Error as follows:');
			console.log(thrownError);
			}
	});
}

function	movePagination(way) {
	//Handle pagination based upon type.
	if (way == 'first') {
		if (page > 0) {
			page	=	0;
			change	=	1;
		}
	} else if (way == 'previous') {
		if (page > 0) {
			page--;
			change	=	1;
		}
	} else if (way == 'next') {
		if (page < (Math.ceil(pagMax / show) - 1)) {
			page++;
			change	=	1;
		}
	} else if (way == 'last') {
		if (page < (Math.ceil(pagMax / show) - 1)) {
			page	=	(Math.ceil(pagMax / show) - 1);
			change	=	1;
		}
	}
	
	//If we're changing the page.
	if (change > 0) {
		//Fade everything out.
		jQuery('.pagination').children('.listing').fadeOut();
	
		//Set the page.
		jQuery('.pagination').children('.listing').slice((page * show), (show + (page * show))).fadeIn();
		
		//Reset the change.
		change		=	0;
	}
 }

function	displayProcessRequest() {
	//Declare variables.
	var	markup	=	new Array();
	
	//Assemble markup.
	markup.push(
		'<div id="process-request">',
			'<img src="/images/loader.gif" alt="Processing Request" title="Processing Request" />',
			'<h6>Processing Request</h6>',
		'</div>'
	);
	
	//Append the page.
	jQuery('body').append(markup.join(''));
	
	//Position the element in the center.
	jQuery('#process-request').css("top", (((jQuery(window).height() - jQuery('#process-request').outerHeight()) / 2) + jQuery(window).scrollTop()));
	jQuery('#process-request').css("left", (((jQuery(window).width() - jQuery('#process-request').outerWidth()) / 2) + jQuery(window).scrollLeft()));
	
	//Fade the new element in.
	jQuery('#process-request').fadeIn('medium');
}

function formDisplayProcessRequest(obj) {
	//Insure that the form was actually submit (redundancy.)
	jQuery(jQuery(obj).closest('form')).submit(function() {
		jQuery(jQuery(this).children('input[type="submit"]')).fadeOut(function() {
			displayProcessRequest();
		});
	});
}
