﻿var CGO = CGO || { Controllers: {}, Utilities: {} };
var _gaq = _gaq || [];

CGO.Utilities = {
	onFocusHideDefault: function () {
		if (this.value === this.defaultValue) {
			this.value = '';
		}
	},
	onBlurShowDefault: function () {
		if (this.value === '') {
			this.value = this.defaultValue;
		}
	},
	handleJsonError: function (xhr, textStatus, errorThrown) {
		var err = eval('(' + xhr.responseText + ')');
		alert('There was a problem with that request: ' + err.Message);
	},
	jsonEncode: function (val) {
		return val.replace(new RegExp('\"', 'g'), '\\"');
	}
};

if (typeof Array.prototype.contains === 'undefined') {
	Array.prototype.contains = function (o) {
		var i;
		for (i = this.length; --i; ) {
			if (this[i] === o) {
				return true;
			}
		}
		return false;
	};
}

CGO.Publisher = {
	_subscribers: {
	// event type: subscribers
},
subscribe: function (fn, type) {
	type = type || 'hideAll';
	if (typeof this._subscribers[type] === 'undefined') {
		this._subscribers[type] = [];
	}
	this._subscribers[type].push(fn);
},
fire: function (type) {
	type = type || 'hideAll';
	this.visitSubscribers('publish', type);
},
visitSubscribers: function (action, type) {
	var pubtype = type || 'any',
            subscribers = this._subscribers[pubtype],
            i,
            max = subscribers.length;

	for (i = 0; i < max; i += 1) {
		if (action === 'publish') {
			subscribers[i]();
		} else {
			if (subscribers[i] === arg) {
				subscribers.splice(i, 1);
			}
		}
	}
},
makePublisher: function (o) {
	var i;
	for (i in CGO.Publisher) {
		if (CGO.Publisher.hasOwnProperty(i) && typeof CGO.Publisher[i] === 'function') {
			o[i] = CGO.Publisher[i];
		}
	}
	o.subscribers = { any: [] };
}

};

CGO.openWindow = function (href, width, height) {
	var left = (screen.width - width) / 2,
		top = (screen.height - height) / 2;
	window.open(href, 'gallery', 'left=' + left + ', top=' + top + ', width=' + width + ', height=' + height + ', scrollbars=no,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no');
};

CGO.Controllers.Publisher = {
	init: function () {
		CGO.Publisher.makePublisher(this);
	},
	hideAll: function () {
		CGO.Publisher.fire();
	}
};

CGO.Controllers.Navigation = (function () {
	var settings = {
		buttons$: null,
		submenus$: null,
		selectedMenu$: null
	},
	attachHandlers = function () {
		// show or hide subnav (first 3 items)
		settings.buttons$.mouseenter(function () {
			settings.buttons$.removeClass('active');
			$(this).addClass('active');
			var idx = settings.buttons$.index(this);
			if (idx < 3) { // has drop-down menu
				var selected$ = settings.submenus$.eq(idx);
				settings.submenus$.hide(); // hide all boxes        
				selected$.toggle(); // toggle selected box
				selected$.find('div:eq(0)').show(); // show section default info
				selected$.css('background-image', 'url(' + selected$.find('div:eq(0) img').attr('src') + ')');
				settings.selectedMenu$ = selected$;
			} else { // other menu
				settings.submenus$.hide();
			}
			return false;
		}).mouseleave(function () {
			if ($(this).hasClass('button')) {
				settings.buttons$.removeClass('active');
			}
		});

		// hide on mouseout
		settings.submenus$.mouseleave(function () {
			$(this).hide();
			settings.buttons$.removeClass('active');
		})
		.each(function () { // subnav content - show on mouseover / hide on mouseout
			$(this).find('ul li').each(function (idx) {
				$(this).mouseenter(function () {
					var actualIdx = idx + 1, // 1st div is the section default info
						submenu$ = $(this).parent().parent(),
						page$ = submenu$.children('div:eq(' + actualIdx + ')');
					$('.submenu > div').hide(); // hide all divs
					page$.show(); //show selected
					submenu$.css('background-image', 'url(' + $('img', page$).attr('src') + ')');
				}).mouseleave(function () {
					$('.submenu > div').hide();
				});
			});
		});
	},
		init = function () {
			var buttons$, submenus$;
			settings.buttons$ = $('#hd .nav a');
			settings.submenus$ = $('#hd-submenus > div');

			buttons$ = settings.buttons$;
			submenus$ = settings.submenus$;

			if (!buttons$.length) { return; }

			submenus$.each(function (index) {
				var button$ = buttons$.eq(index),
					left = button$.position().left + button$.parent().position().left;
				$(this).css('left', left);
			});
			attachHandlers();
		},
		closeNav = function () {
			if (settings.selectedMenu$ && settings.selectedMenu$.length) {
				settings.selectedMenu$.hide();
			}
			if (settings.buttons$ && settings.buttons$.length) {
				settings.buttons$.removeClass('active');
			}
		};

	return { init: init, closeNav: closeNav };

} ());

CGO.Controllers.RegionMap = (function () {
	// private methods
	var attachHandlers = function () {
			$('#cities-map area, #landing-links a').mouseenter(function () {
				idx = $(this).parent().find('>*').index(this);
				showMapArea(idx);
				return false;
			}).mouseleave(function () {
				hideMapAreas();
				return false;
			});
		},
		showMapArea = function (idx) {
			$('#map-hovers img:eq(' + parseInt(idx, 10) + ')').show();
		},
		hideMapAreas = function () {
			$('#map-hovers img').hide();
		},
		init = function () {
			attachHandlers();
			// ----- region/city map -----
			// check for default index
			var mapIdx = $('.map-index').text();
			if (mapIdx.length  && +mapIdx !== -1) {
				showMapArea(mapIdx);
			} else {
				return;
			}
		};

	return { init: init };
} ());

CGO.Controllers.Activity = (function () {
	var attachHandlers = function () {
		$('#other-activites').change(function () {
			var idx = $(this).val();
			showDocument(idx);
			return false;
		});
	},
	showDocument = function (idx) {
		$('#doc-details > h4, #doc-details > div').hide(); // hide all
		if (!isNaN(idx)) {
			$('#doc-details h4:eq(' + idx + '), #doc-details div:eq(' + idx + ')').show(); // show clicked    
		}
	},
	hideAll = function () {
		if ($('#activity-right-container').length > 0) {
			$('#doc-details').removeClass('activity-detail');
			$('#doc-details > h4, #doc-details > div').hide(); // hide all
		}
	},
	init = function () {
		attachHandlers();
	};

	return { init: init, hideAll: hideAll };
} ());

CGO.Controllers.ThingsToKnow = (function () {
	var thingsToKnow$ = null,
		showThingsToKnow = function (idx) {
			$('div > div', thingsToKnow$).hide(); // hide all content
			$('div > h2:eq(' + idx + ')', thingsToKnow$).addClass('down');
			$('div > div:eq(' + idx + ')', thingsToKnow$).show().addClass('down');
		},
		attachHandlers = function () {
			// show on click
			$('div h2', thingsToKnow$).click(function () {
				$('div > h2', thingsToKnow$).removeClass('down');
				$('div div', thingsToKnow$).hide();
				var idx = $('div > h2', thingsToKnow$).index(this);
				showThingsToKnow(idx);
			});
		},
		init = function () {
			thingsToKnow$ = $('#things-to-know');
			if (!thingsToKnow$.length) { return; }
			// show 1st item

			$('table tbody tr:odd', thingsToKnow$).addClass('odd');
			showThingsToKnow(0);
			attachHandlers();
		};
	return { init: init };
} ());

CGO.Controllers.MediaScroller = (function () {
	var attachHandlers = function () {
		$('#media-title .button').click(function () {
			if (!$(this).hasClass('active')) {
				$(this).siblings().removeClass('active').end().addClass('active');
				$('.photos-scroll').toggle();
				$('.videos-scroll').toggle();
			}
			return false;
		});
	},
		init = function () {
			var medianContainer$ = $('#media-container'),
				btPhotos$ = $('#bt_photos');

			if (!medianContainer$.length) { return; }
			btPhotos$.addClass('active');

			$('.photos-scroll').mediaScroll({
				gallery: 'gallery',
				options: {
					maxWidth: 690,
					maxHeight: 460,
					scalePhotos: true,
					current: 'Picture {current} of {total}'
				}
			});
			$('.videos-scroll').mediaScroll({
				gallery: 'videos',
				options: {
					innerWidth: 425,
					innerHeight: 344,
					iframe: true,
					current: 'Video {current} of {total}'
				}
			});

			if ($('#fb-stream').length) {
				$('#media-container').addClass('short');
			}
			attachHandlers();
		};

	return { init: init };
} ());

(function ($) {
	$.fn.mediaScroll = function (options) {
		var settings = $.extend({
			gallery: 'gallery',
			options: null,
			prev: '.prev',
			next: '.next'
		}, options || {});

		return this.each(function () {
			var // private properties
				gallery$ = $(this),
				items$ = $('.scroll-items', gallery$),
				index = 0,
				numElements = $('a', $(this)).length,
				isCircular = numElements > 4 ? true : false,

			// private methods 
				isVisible = function () {
					return gallery$.is(':visible');
				},
				changeIndex = function (ind) {
					if (isVisible()) {
						var item$ = $('a', items$).eq(ind),
							swapItem$;
						if (item$.length) {
							index = ind;
							if (isCircular) {
								if (ind < 0) {
									swapItem$ = $('a:last', items$);
									items$.css('left', items$.position().left - swapItem$.outerWidth());
									swapItem$.prependTo(items$);
									++index;
								} else if (ind > numElements - 5) {
									swapItem$ = $('a:first', items$);
									items$.css('left', items$.position().left + swapItem$.outerWidth());
									swapItem$.appendTo(items$);
									--index;
								}
							}
							items$.animate({ left: -item$.position().left });
						}
					}
				};

			$('a[rel="' + settings.gallery + '"]', $(this)).colorbox(settings.options);
			$(settings.prev).click(function (e) {
				e.preventDefault();
				changeIndex(index - 1);
			});

			$(settings.next).click(function (e) {
				e.preventDefault();
				changeIndex(index + 1);
			});
		});
	};
} (jQuery));

CGO.Controllers.FishFinder = (function () {
	var fishFinder$ = null,

		fishTypeIds = [],

	// dropdowns
		fishbox$ = null,
		fish$ = null,
		regionbox$ = null,

	// dropdown triggers
		speciesDropDown$ = null,
		regionDropDown$ = null,

	// data
		fishData = [],
		regionId = 0,
		fishId = 0,

	// private methods
	attachHandlers = function () {
		// dropdowns
		speciesDropDown$.click(function () {
			regionbox$.fadeOut('fast');
			fishbox$.toggle();
		});

		regionDropDown$.click(function () {
			fishbox$.fadeOut('fast');
			regionbox$.toggle();
		});

		$('li', regionbox$).click(function () {
			regionbox$.fadeOut('fast');
			regionId = $(this).attr('id');

			regionDropDown$.text($(this).text());
		});

		fish$.click(function () {
			$(this).toggleClass('selected');
		});

		$('.button', fishFinder$).click(function () {
			search();
		});

		$(document).keypress(function (e) {
			if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) {
				search();
			}
		});
	},
	search = function () {
		fishbox$.fadeOut();
		regionbox$.fadeOut();
		fishId = 0;
		$('.fish.selected', fishbox$).each(function (index) {
			if (index === 0) {
				fishId = [];
			}
			fishId.push(+$(this).attr('id'));
		});
		if (fishId === 0) {
			speciesDropDown$.text('All Species');
		} else if ($.isArray(fishId)) {
			if (fishId.length === 1) {
				speciesDropDown$.text($('#' + fishId[0], fishbox$).text());
			} else {
				speciesDropDown$.text('Multiple Species');
			}
		}
		CGO.Controllers.Map.filterResults({
			fishId: fishId,
			regionId: regionId
		});
	},
	init = function () {
		fishFinder$ = $('#fish-finder');
		if (!fishFinder$.length) { return; }
		fishbox$ = $('#fishbox', fishFinder$);
		regionbox$ = $('#regionbox', fishFinder$);
		speciesDropDown$ = $('#species', fishFinder$);
		regionDropDown$ = $('#regions', fishFinder$);

		$.ajax({
			type: 'POST',
			url: '/services/member-types.asmx/GetRegions',
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			error: CGO.Utilities.handleJsonError,
			success: function (data) {
				var markup = '';
				if (data.d) {
					$.each(data.d, function () {
						markup += '<li id="' + this.TypeID + '">' + this.TypeLabel + '<\/li>';
					});
					regionbox$.append(markup);
				}
			}
		});

		$.ajax({
			type: 'POST',
			url: '/services/member-types.asmx/GetFishTypes',
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			error: CGO.Utilities.handleJsonError,
			complete: function () {
				attachHandlers();
				setTimeout(function () {
					search();
				}, 1000);
			},
			success: function (data) {
				var markup = '',
					fishPerRow = 3;

				if (data.d) {
					$.each(data.d, function (index) {
						var classes = ['fish'];
						classes.push(this.TypeLabel.replace(' ', '-').toLowerCase());
						if (index % fishPerRow === 0) {
							classes.push('clear');
						}
						markup += '<li id="' + this.TypeID + '" class="' + classes.join(' ') + '">' + this.TypeLabel + '<\/li>';
						fishTypeIds.push(+this.TypeID);
					});
					fishbox$.html(markup);
				}
				fish$ = $('.fish', fishbox$);
			}
		});
	};
	return { init: init, fishTypeIds: fishTypeIds };
} ());

CGO.Controllers.MapSearch = (function () {
	var container$,
		attachHandlers = function () {
			$('.button', container$).click(function (e) {
				e.preventDefault();
				search();
			});
		},
	search = function () {
		CGO.Controllers.Map.filterResults({
			regionId: +$('#regions', container$).val(),
			activityId: +$('#activityTypes', container$).val(),
			accomodationId: +$('#accomodationTypes', container$).val()
		});
	},
	init = function () {
		container$ = $('#search-criteria');
		if (!container$.length) { return; }
		var populateSelections = function (selector, method, callback) {
			$.ajax({
				type: 'POST',
				url: '/services/member-types.asmx/' + method,
				contentType: 'application/json; charset=utf-8',
				dataType: 'json',
				error: CGO.Utilities.handleJsonError,
				success: function (data) {
					var markup = '';
					if (data.d) {
						$.each(data.d, function () {
							markup += '<option value="' + this.TypeID + '">' + this.TypeLabel + '<\/option>';
						});
					}
					$(selector, container$).append(markup);
					if (typeof callback === 'function') {
						callback();
					}
				}
			});
		};
		attachHandlers();

		populateSelections('#activityTypes', 'GetActivityTypes', function () {
			var photoActivities$ = $('#activityTypes').clone();
			photoActivities$.attr('ID', 'photo-activities');
			$('#photo-search .inputs').prepend(photoActivities$);
		});
		populateSelections('#regions', 'GetRegions', function () {
			var photoRegions$ = $('#regions').clone();
			photoRegions$.attr('ID', 'photo-regions');
			$('#photo-search .inputs').prepend(photoRegions$);
		});
		populateSelections('#accomodationTypes', 'GetAccomodationTypes');
	};
	return { init: init };
} ());

(function ($) {
	$.fn.crossfadeRotate = function (options) {
		var settings = $.extend({
			interval: 4000,
			fade: 1000,
			scrollDuration: 300,
			bannerContainer: '.banners',
			thumbnailContainer: '.thumbnails',
			scrollLeft: '.left',
			scrollRight: '.right',
			buttonOpacity: 0.8
		}, options || {});

		return this.each(function () {
			var intervalID,
				index = 0,
				banners$ = $(settings.bannerContainer, $(this)).children(),
				thumbnailList$ = $('#splash-top .thumbnails');
				swapImage = function (ind) {
					if(typeof ind === 'undefined') {
						++index;
						if (index === banners$.length) {
							index = 0;
						}
					} else {
						index = ind;
					}
					banners$.parent().children(':visible').fadeOut(settings.fade);
					banners$.eq(index).fadeIn(settings.fade);
				},
				nextImage = function () {
					swapImage();
				},
				slide = function (list$, attr, distance, callback) {
					$(this).queue(function() {
						var that$ = $(this),
							isNegative = (distance < 0),
							options = (function () {
								var obj = {};
								obj[attr] = (isNegative ? '+=' : '-=') + Math.abs(distance);
								return obj
							} ()),						
							removedItem$ = $('li:' + (isNegative ? 'last' : 'first'), list$),
							clone$ = removedItem$.clone(true);

						if(isNegative) {
							list$.prepend(clone$).css(attr, distance);
						} else {
							list$.append(clone$);
						}

						list$.animate(options, settings.scrollDuration, function () {
							removedItem$.remove();
							if(!isNegative) {
								$(this).css(attr, $(this).position()[attr] + distance);
							}							
							if (typeof callback === 'function') {
								callback();
							}
							that$.dequeue();
						});
					});
				},
				onButtonHover = function() {
					$(this).fadeTo(200, 1);
				},
				onButtonLeave = function() {
					$(this).fadeTo(200, settings.buttonOpacity);
				};

			banners$.hide();
			banners$.eq(index).show();
			intervalID = setInterval(nextImage, settings.interval);

			$(settings.thumbnailContainer, $(this)).children().click(function() {
				var selectedIndex = $(this).data('index');
				if(selectedIndex !== index) {
					clearInterval(intervalID);
					intervalID = setInterval(nextImage, settings.interval);
					swapImage(selectedIndex);
				}
			}).each(function() {
				$(this).data('index', $(this).index());
			});

			$(settings.scrollLeft, $(this)).css({'opacity': settings.buttonOpacity})
				.mouseenter(onButtonHover)
				.mouseleave(onButtonLeave)
				.click(function() {
					slide(thumbnailList$, 'left', -104);
				});
			$(settings.scrollRight, $(this)).css({'opacity': settings.buttonOpacity})
				.mouseenter(onButtonHover)
				.mouseleave(onButtonLeave)
				.click(function() {
					slide(thumbnailList$, 'left', 104);
				});
		});
	};
}(jQuery));

CGO.Controllers.Banners = (function () {
	var init = function () {
		$('#splash-top').crossfadeRotate({ interval: 5000 });

		};
	return { init: init };
} ());

CGO.Controllers.PhotoSearch = (function () {
	var iconPath = '/images/map/marker-photo.png',
		markers = [],
		getImageMarkup = function (url) {
			return '<img src="' + url + '" \/>';
		},
		keywords$,
		photoRegions$,
		photoActivities$,
		addHandlers = function () {
			$('#photo-search .button').click(function (e) {
				e.preventDefault();
				search();
			});
		},
		search = function () {
			var searchKeywords = '';
			if (!photoRegions$ || !photoRegions$.length) {
				photoRegions$ = $('#photo-regions');
			}
			if (!photoActivities$ || !photoActivities$.length) {
				photoActivities$ = $('#photo-activities');
			}
			if (keywords$.val().length > 0) {
				searchKeywords += ' ' + keywords$.val();
			}
			$.each(markers, function (index, value) {
				value.setMap();
			});
			markers = [];

			$.ajax({
				type: 'POST',
				cache: false,
				url: '/photo_search.aspx',
				dataType: 'xml',
				data: { 
					keywords: searchKeywords,
					photoRegions: photoRegions$.val(),
					photoActivities: photoActivities$.val()
				},
				error: CGO.Utilities.handleJsonError,
				success: function (data) {
					var infoWindow = new google.maps.InfoWindow(),
							infoWindowContent = '',
							points = [],
							map = CGO.Controllers.Map.getMap();

					if ($(data).length) {
						$('photo', data).each(function () {
							var latitude = +$(this).attr('latitude'),
									longitude = +$(this).attr('longitude'),
									photoTitle = $(this).attr('photoTitle'),
									isNew = true;

							if (latitude !== -1 && longitude !== -1) {
								$.each(points, function (index, value) {
									if (value.longitude === longitude && value.latitude === latitude) {
										isNew = false;
										value.photoTitle += getImageMarkup(photoTitle);
									}
								});
								if (isNew === true) {
									points.push({
										longitude: longitude,
										latitude: latitude,
										photoTitle: getImageMarkup(photoTitle)
									});
								}
							}
						});
						$.each(points, function (index, value) {
							var html = value.photoTitle,
									marker = new google.maps.Marker({
										position: new google.maps.LatLng(value.latitude, value.longitude),
										map: map,
										icon: iconPath
									});

							markers.push(marker);

							google.maps.event.addListener(marker, 'click', function () {
								infoWindow.setContent(html);
								infoWindow.open(map, marker);
							});
						});
					}
				}
			});
		},
		init = function () {
			keywords$ = $('#keywords');
			photoRegions$ = $('#photo-regions');
			photoActivities$ = $('#photo-activities');

			addHandlers();
			$('#photo-search .button').trigger('click');
		};
	return { init: init };
} ());

(function ($) {
	$.fn.modal = function (options) {
		var settings = $.extend({
				opacity: 0.7,
				duration: 1000
			}, options || {}),
			overlay$,
			box$,
			cont$,
			fun$,
			loadUrl = function (url) {
				cont$.load(url, function () {
					activate();
				});
			},
			activate = function() {
				overlay$.show().fadeTo(settings.duration, settings.opacity, function() {
					$(this).animate({ height: $('body').height() }, function () {
						box$.fadeIn(settings.duration);
					});
				});
				$(document).bind('keyup', keyHandler);
			},
			deactivate = function() {
				box$.fadeOut(function () {
					overlay$.animate({ height: 0 }, function() {
						$(this).hide();
					});
				});
				$(document).unbind('keyup', keyHandler);
			},
			attachHandlers = function () {
				$('a.close', box$).click(function(e) {
					e.preventDefault();
					deactivate();
				});
			},
			keyHandler = function (e) {
				if (e.keyCode === 27) { // ESC
					deactivate();
				}
			},
			init = (function () {
				var markup = '<div id="modal-overlay"><\/div>';
				markup += '<div id="modal-box">';
				markup += '<a href="#" class="close button">close</a>';
				markup += '<div class="cont"><\/div>';
				markup += '<\/div>';

				fun$ = $('#bd-r-fun');
				if(!fun$.length) { return; }

				$('body').append(markup);
				overlay$ = $('#modal-overlay');
				box$ = $('#modal-box');
				cont$ = $('.cont', box$);

				attachHandlers();
			}());

		return this.each(function() {
			$(this).click(function(e) {
				e.preventDefault();
				loadUrl($(this).attr('href'));
			});
		});
	};
}(jQuery));

CGO.Controllers.FunAndGames = (function () {
	var init = function () {
		 $('#bd-r-fun .game-cont a').modal();
	};
	return { init: init };
} ());

CGO.GoogleAnalytics = function (options) {
    var settings = $.extend({
        enabled: true,

        // Google account ID e.g. UA-0000000-00
        accountId: null,

        // clickable elements to attach events to
        elements: ['a', 'area'],

        // collection of link types, each of which may be 
        // identified and click-handled using custom logic
        linkTypes: {
            outbound: {
                cssClass: 'outbound',
                identify: function (obj) {
                    return !obj.href.match(/^mailto\:/) && (obj.hostname !== location.hostname);
                },
                onClick: function () {
                    _gaq.push(['_trackEvent', 'OutboundLink', 'Click', $(this).attr('href')]);
                }
            },
            download: {
                cssClass: 'download',
                identify: function (obj) {
                    var // download filetypes may be extended
							ext = ['pdf', 'doc'],
							pattern = (function () {
							    var p = '';
							    $.each(ext, function (index, value) {
							        p += '\\.' + value + '|';
							    });
							    p = p.substring(0, p.length - 1);
							    return '(' + p + ')$';
							} ()),
							m = obj.href.match(new RegExp(pattern, 'i'));

                    return (m && m.length >= 1);
                },
                onClick: function () {
                    var url = $(this).attr("href"),
							ext = url.split('.').pop().toUpperCase();
                    _gaq.push(['_trackEvent', 'Downloads', ext, url]);
                }
            }
        }
    }, options || {}),
		identifyElements = function () {
		    $.each(settings.linkTypes, function (key, obj) {
		        $.expr[':'][key] = obj.identify;
		        markElements(obj.cssClass);
		    });
		},
		markElements = function (className) {
		    $.each(settings.elements, function (index, value) {
		        $(value + ':' + className).addClass(className);
		    });
		},
		attachHandlers = function () {
		    $.each(settings.linkTypes, function (key, obj) {
		        $.each(settings.elements, function (index, value) {
		            $(value + ':' + key).click(obj.onClick);
		        });
		    });
		};

    identifyElements();

    if (settings.enabled === true) {
        if (!settings.accountId) {
            throw 'You must provide an account ID';
            return false;
        }
        attachHandlers();

        _gaq.push(['_setAccount', settings.accountId]);
        _gaq.push(['_trackPageview']);
        (function () {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        } ());
    }
};

CGO.isProduction = (function () {
    return (/canadasgreatoutdoors\.com$/).test(window.location.hostname);
} ());

$(function () {

    CGO.GoogleAnalytics({ enabled: CGO.isProduction, accountId: 'UA-5805188-15' });

	$.each(CGO.Controllers, function (name, controller) {
		if (controller.init && typeof controller.init === 'function') {
			setTimeout(function () {
				controller.init();
			}, 250);
		}
	});

	CGO.Publisher.subscribe(CGO.Controllers.Navigation.closeNav);
	CGO.Publisher.subscribe(CGO.Controllers.Activity.hideAll);

	$(document).click(CGO.Controllers.Publisher.hideAll);

	// ----- message maker -----
	$('#mm-preview').click(function () {
		var href = $(this).attr('href') + '?m=' + ($('.q1').get(0).selectedIndex + 1) + ',' + ($('.q2').get(0).selectedIndex + 1) + ',' + ($('.q3').get(0).selectedIndex + 1) + ',' + ($('.q4').get(0).selectedIndex + 1);
		CGO.openWindow(href, 765, 500);
		return false;
	});
});
