/**
 *	Load scripts snippets
 */
$(document).ready(function() {
	$('#latest-events li, #shops li').hover(
		function() {
			$(this).find('.meta').stop(true, true).animate({
				bottom: 0
			}, 150);
		},
		function() {
			$(this).find('.meta').stop(true, true).animate({
				bottom: -20
			}, 150);
		}
	);
	
	$('#board-members li').hover(
		function() {
			$(this).find('.meta').stop(true, true).fadeIn(100);
		},
		function() {
			$(this).find('.meta').stop(true, true).fadeOut(100);
		}
	); 	
	
	// gallery layout
	$('#gallery .album-wrap:nth-child(4n+1)').addClass('alpha');
	$('#gallery .album-wrap:nth-child(4n+4)').addClass('omega');
});

function custom_events_scripts() {
	// initial active tab
	var activeTab = $('#event-portal ul.sidebar-list li a.active');
	
	$('#event-portal ul.sidebar-list li a').click(function() {
		activeTab.removeClass('active');
		$(this).addClass('active');
		activeTab = $(this);
	});
}

function load_events(data) {	
	// send GET request
	if ($(this).hasClass('active') == false) {
	
		// remove events list
		$('#event-list').fadeOut(100, function() { 
			$(this).html('<div class="loading"></div>').fadeIn(100);
		});
		
		if (typeof data == 'undefined') {
			data = { all : 'true' }
		}
		
		$.ajax({
			type	: 'GET',
			cache	: false,
			data	: data,
			url		: '/events/view/',
			success	: function(data) {
				$('#event-list').fadeOut(100, function() { 
							$(this).find('div.loading').remove(); 
							$(this).html(data).fadeIn(100);
					});
			}
		});
	}
	return false;
}

function add_countdown_animation(fields) {
	function updateCountdown() {
		var remaining = $(this).attr('maxlength') - $(this).val().length;
		$(this).siblings('span.countdown').text(remaining + ' characters remaining');
	}

	function hideCountdown() {
		$(this).siblings('span.countdown').empty();
	}
	
	fields.each(function() {
		$(this).focus(updateCountdown);
		$(this).keyup(updateCountdown);
		$(this).blur(hideCountdown);
	});
}

function custom_marketplace_scripts() {
	// initial active tab
	var activeTab = $('#marketplace ul.sidebar-list li a.active');
	
	$('#marketplace ul.sidebar-list li a').click(function() {
		activeTab.removeClass('active');
		$(this).addClass('active');
		activeTab = $(this);
		
		$('#items header h4').text($(this).text());
	});
}

function load_marketplace_items(data) {
	$('div.marketplace-wrap').fadeOut(100, function() { 
			$(this).html('<div class="loading"></div>').fadeIn(100);
	});
	
	if (typeof data == 'undefined') {
		data = { 
			all 	: 'true',
			offset	: 0
		}
	}

	$.ajax({
		type	: 'GET',
		cache	: false,
		data	: data, 
		url		: '/marketplace/view/',
		success	: function(data) {
			$('div.marketplace-wrap').fadeOut(100, function() {
					$(this).find('div.loading').remove();
					$(this).html(data).fadeIn(100);
			});
		}
	});
}

function load_marketplace_form() {
	$('div.marketplace-wrap').fadeOut(100, function() { 
		$(this).html('<div class="loading"></div>').fadeIn(100);
	});
	
	$.ajax({
		type	: 'GET',
		cache	: false,
		url		: '/wp-content/themes/umimsa/marketplace_form.php',
		success	: function(data) {
			$('div.marketplace-wrap').fadeOut(100, function() {
					$(this).find('div.loading').remove();
					$(this).html(data).fadeIn(100);
					load_marketplace_form_validation();
			});
		}
	});
	
	/**
	 *	Validate marketplace submission form
	 */
	function load_marketplace_form_validation() {
		function requirePhone(element) {
			return $('#require-phone option:selected').text() === 'Yes';
		};

		$("#marketplace form").validate({
			groups: {
				phone: 'area prefix ext'
			},
			rules: {
				ioption: "required",
				iname: "required",
				price: "required",
				description: "required",
				category: "required",
				uname: "required",
				uemail: {
					required: true,
					email: true
				},
				area: {
					number: true,
					required: {
						depends: requirePhone
					}
				},
				prefix: {
					number: true,
					required: {
						depends: requirePhone
					}
				},
				ext: {
					number: true,
					required: {
						depends: requirePhone
					}
				},
			},
			messages: {
				ioption: "Pick an option",
				iname: "Please specify the item name",
				price: "Please specify the price",
				description: "Please provide a short description for this item",
				category: "Pick a category",
				uname: "Please specify your name",
				uemail: {
					required: "Your email address will be the primary contact method",
					email: "Your email address must be in the format of your@email.com"
				},
				area: "Please provide a valid phone number",
				prefix: "Please provide a valid phone number",
				ext: "Please provide a valid phone number" 
			},
			errorPlacement: function(error, element) {
				if (element.attr('name') == 'prefix' || 
					element.attr('name') == 'ext') {
					error.insertBefore($('#ph1'));
				} else {
					error.insertBefore(element);
				}
			},
			wrapper: 'div',
			submitHandler: function(form) {
				$('#marketplace div.marketplace-wrap').fadeOut(100, function() { 
						$(this).html('<div class="loading"></div>').fadeIn(100);
				});
				
				$.ajax({
					type	: 'POST',
					cache	: false,
					data	: $(form).serializeArray(), 
					url		: '/marketplace/submit/',
					success	: function(data) {
						$('#marketplace div.marketplace-wrap').fadeOut(100, function() {
								$(this).find('div.loading').remove();
								$(this).html(data).fadeIn(100);
						});
					}
				});
			
				return false;
			}
		});
		
		// manipulate price input
		$('#price').blur(function() {
			// will convert nothing if input contains no number
			$(this).formatCurrency({
				symbol: '',
				groupDigits: false,
				negativeFormat: '\-%s%n'
			});
			
			var MAX_VALUE = 9999.99,
				MIN_VALUE = 0.00,
				value = parseFloat($(this).val());
			
			// boundary check
			if (value > MAX_VALUE) {
				$(this).val(MAX_VALUE);
			} else if (value < MIN_VALUE || isNaN(value)) {
				$(this).val('0.00');
			}
		});
		
		// enable/disable phone number field
		$('#require-phone').change(function() {
			var option = $('#require-phone option:selected').text();
			
			if (option === 'No') {
				$('#marketplace div.phone-wrap input').each(function() {
					$(this).val('');
					$(this).attr('disabled', 'disabled');
				});
				$('#marketplace div.phone-wrap label.error').parent('div').remove();
			} else {
				$('#marketplace div.phone-wrap input').each(function() {
					$(this).removeAttr('disabled');
				});
				
				$('input[name="area"]').keyup(function() {
					if ($(this).val().length == 3) $('input[name="prefix"]').focus();
				});
				
				$('input[name="prefix"]').keyup(function() {
					if ($(this).val().length == 3) $('input[name="ext"]').focus();
				});
			}
		});
		
		// characters remaining countdown
		add_countdown_animation($('#iname, #description, #uname, #uemail'));
	}
}

/**
 *	Load marketplace fancybox (to display items)
 */
function load_marketplace_fancybox(data) {
	$.fancybox.showActivity();
	var options = {
		'centerOnScroll':	true,
		'changeFade'	:	0,
		'changeSpeed'	:	0,
		'cyclic'		:	true,
		'overlayColor'	:	'#000',
		'overlayOpacity':	0.8,	
		'overlayShow'	:	true,
		'titlePosition'	:	'over',
		'transitionIn'	:	'none',
		'transitionOut'	:	'none',
		'speedIn'		:	0, 
		'speedOut'		:	0
	};
	
	$.ajax({
		type	: 'GET',
		cache	: false,
		data	: data, 
		url		: '/marketplace/view/single/',
		success	: function(data) {
			options['content'] = data;
			$.fancybox(options);
		}
	});
}

/**
 *	Load gallery fancybox
 */
function load_gallery_fancybox() {
	function titleFormat(title, currentArray, currentIndex, currentOpts) {
		return '<div id="fancybox-title-over"><span class="image-index">Image ' + 
				(currentIndex + 1) + ' of ' + currentArray.length + 
				'</span><span class="view-full"><a href="' + currentArray[currentIndex] 
				+ '" target="_blank">View full size</a></span></div>';
	}
	
	var options = {
		'centerOnScroll':	true,
		'changeFade'	:	0,
		'changeSpeed'	:	0,
		'cyclic'		:	true,
		'overlayColor'	:	'#000',
		'overlayOpacity':	0.8,	
		'overlayShow'	:	true,
		'titlePosition'	:	'over',
		'titleFormat'	:	titleFormat,
		'transitionIn'	:	'none',
		'transitionOut'	:	'none',
		'speedIn'		:	0, 
		'speedOut'		:	0
	};

	$("#gallery a.fancybox-hook").fancybox(options);
}

/**
 *	Load MCN registration form when clicked
 */
function load_mcn_regform() {
	var options = {
		'centerOnScroll':	true,
		'changeFade'	:	0,
		'changeSpeed'	:	0,
		'content'		: 	'<iframe src="https://docs.google.com/spreadsheet/embeddedform?formkey=dHZmTEhsMnBmYWhVcnU4Y2tuR00xVnc6MQ" width="760" height="949" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>',
		'overlayColor'	:	'#000',
		'overlayOpacity':	0.8,	
		'overlayShow'	:	true,
		'titlePosition'	:	'over',
		'transitionIn'	:	'fade',
		'transitionOut'	:	'fade',
		'speedIn'		:	200, 
		'speedOut'		:	0
	};
	
	$("#mcn-details a.register").fancybox(options);
}

/**
 *	Load google map on the Member Discounts page 
 *	and assigns onclick event to the shops' thumbnails
 */
function load_gmap() {
	// Map options
	var gmap_id = 'map-canvas',
		gmap_zoom = 15,
		gmap_lat = 42.277,
		gmap_long = -83.7375;
	
	// Marker options
	var marker_default_icon = 'http://maps.google.com/mapfiles/ms/micons/blue-dot.png',
		marker_active_icon = 'http://maps.google.com/mapfiles/ms/micons/orange-dot.png',
		marker_default_anim = google.maps.Animation.DROP;
	
	// Create the map
    var gmap = new google.maps.Map(
					document.getElementById(gmap_id), {
						center: new google.maps.LatLng(gmap_lat, gmap_long),
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						zoomControl: true,
						zoomControlOptions: { style: google.maps.ZoomControlStyle.LARGE },
						zoom: gmap_zoom
					});
	
	// get Markers' details in JSON format
	$.ajax({
		type	: 'POST',
		cache	: false,
		url		: '/wp-content/themes/umimsa/scripts/get-discount.php',
		success	: function(data) {
			process_map_events(jQuery.parseJSON(data));
		}
	});
	
	// Keep track of the current active marker
	var active_marker = null,
	
	// Create an info window (that will change its content/location based on the active marker)
		info_window = new google.maps.InfoWindow();
	
	// Close info window when the map is clicked
	google.maps.event.addListener(gmap, 'click', function() {
		if(active_marker) {
			active_marker.setIcon(marker_default_icon);
			active_marker = null;
			info_window.close();
		}
	});
	
	// Change marker icon when info window is closed
	google.maps.event.addListener(info_window, 'closeclick', function() {
		if(active_marker) {
			active_marker.setIcon(marker_default_icon);
			active_marker = null;
		}
	});
	
	/**
	 *	Create Markers, InfoWindows and set onclick events
	 *
	 * 	@param Object json JSON data 
	 */
	function process_map_events(json) {
		for(var i in json) {
			var entry = json[i];
			
			// Fetch column values 
			var title = entry['shop_name'],
				latitude = parseFloat(entry['shop_latitude']),
				longitude = parseFloat(entry['shop_longitude']),
				address = entry['shop_address'],
				phone = entry['shop_phone'],
				website = entry['shop_website'],
				discount = entry['discount_info'];	
			
			
	
			
			// Create a new marker
			var current_marker = create_marker(new google.maps.LatLng(latitude, longitude), title);
			
			// HTML for InfoWindow
			var html_infoWindow = '<div class="map-info-window">'
					+ '<h4 class="title">' + title + '</h4>'
					+ '<div class="meta">' 
					+ '<span class="address">' + address + '</span>';
			if(phone.toLowerCase() != 'none') {
				html_infoWindow += '<span class="phone">' + phone + '</span>';
			}
			html_infoWindow += '</div><span class="discount">' + discount + '</span></div>';			
			
			// HTML for shop info on the sidebar
			html_sidebar = '<h4 class="subsection-title">' + title + '</h4>'
						+ '<div class="meta">'
						+ '<div class="address">'
						+ '<span class="title">Address</span>'
						+ '<span>' + address + '</span>'
						+ '</div>'
						+ '<div class="phone">'
						+ '<span class="title">Phone Number</span>'
						+ '<span>' + phone + '</span>'
						+ '</div>' 
						+ '<div class="discount">'
						+ '<span class="title">Discount Info</span>'
						+ '<span>' + discount + '</span>'
						+ '</div></div>';	
			if(website.toLowerCase() != 'none')  {
				html_sidebar += '<div class="link-stamp"><a href="http://' + website + '" target="_blank">&raquo; Visit official website</a></div>';
			}
			// Show InfoWindow and sidebar info when thumbnails are clicked
			set_click_events(current_marker, 
				$('#shops li[title="' + title + '"]'), 
				html_infoWindow, 
				html_sidebar);
		}
		// Load initial sidebar message when the map processing is done
		$('#shop-info-wrap').html('<p>Click on the thumbnails to view more information.</p>');
	}
			
	/**
	 *	Creates a marker
	 *
	 * 	@param LatLng point Point to create marker at
	 * 	@param String title Tooltip title to display for marker
	 *	@return Marker The marker created
	 */
	function create_marker(point, title) {
		var marker = new google.maps.Marker({  
			animation: marker_default_anim,
			position: point,  
			map: gmap,  
			title: title,  
			clickable: true,  
			icon: marker_default_icon
		});
		return marker;
	}
	
	/**
	 *	Show InfoWindow and sidebar info when thumbnails are clicked
	 *
	 * 	@param Marker marker The marker
	 *	@param jQuery thumbnail The thumbnail
	 * 	@param String html_win HTML for InfoWindow
	 *	@param String html_side HTML for shop info on the sidebar
	 */
	 function set_click_events(marker, thumbnail, html_win, html_side) {		
		// When marker is clicked
		google.maps.event.addListener(marker, 'click', function() {
			// Set sidebar info
			$('#shop-info-wrap').html(html_side);
			
			// Activate InfoWindow 
			if(active_marker) {
				active_marker.setIcon(marker_default_icon);
			}
			active_marker = marker;
			active_marker.setIcon(marker_active_icon);
			info_window.close();
			info_window.setContent(html_win);
			info_window.open(gmap, marker);
		});
		
		// When thumbnail is clicked
		thumbnail.click(function() {
			// Set sidebar info
			$('#shop-info-wrap').html(html_side);
			
			// Activate InfoWindow 
			if(active_marker) {
				active_marker.setIcon(marker_default_icon);
			}
			active_marker = marker;
			active_marker.setIcon(marker_active_icon);
			info_window.close();
			info_window.setContent(html_win);
			info_window.open(gmap, marker); 
		});		
	 }
}


/**
 *	Validate contact form on the Contact us page
 */
function load_contact_form_validation() {
	$("#contact-us form").validate({
		rules: {
			uname: "required",
			uemail: {
				required: true,
				email: true
			},
			message: "required"
		},
		messages: {
			uname: "Please specify your name",
			uemail: {
				required: "We need your email address to contact you",
				email: "Your email address must be in the format of your@email.com"
			},
			message: "Please enter your message"
		},
		errorPlacement: function(error, element) {
			error.insertBefore(element);
		},
		wrapper: 'div',
		submitHandler: function(form) {
			$('#contact-us div.form-wrap').fadeOut(100, function() { 
				$(this).html('<div class="loading"></div>').fadeIn(100);
			});
			
			$.ajax({
				type	: 'POST',
				cache	: false,
				data	: $(form).serializeArray(), 
				url		: '/contact/submit/',
				success	: function(data) {
					$('#contact-us div.form-wrap').fadeOut(100, function() {
							$(this).find('div.loading').remove();
							$(this).html(data).fadeIn(100);
					});
				}
			});
			return false;
		}
	});
	
	// remaining characters
	add_countdown_animation($('#uname, #uemail, #subject, #message'));
}
