(function($) {
	// plugin options
	var options = {};
	
	function setupPageTracker() {
		var host = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");

		$.extend(true, options, {onLoad: true});
		var src  = host + 'google-analytics.com/ga.js';
		
		// /-- Initiate page tracker ---
		function initAnalytics() {
			if (typeof _gat !== 'undefined') {
				var domainName = (options.domainName) ? options.domainName : host;			
				pageTracker = _gat._createTracker(options.accountId);
				pageTracker._setDomainName(domainName);
				pageTracker._trackPageview();
				if(options.debug) debug('Google Analytics is defined:'+options.accountId,'info');

				if(options.rollupAccountId) {
					rollupTracker = _gat._createTracker(options.rollupAccountId);
				    if(options.isCrossDomainTracking)
                        rollupTracker._setAllowLinker(true);
					rollupTracker._trackPageview();
					if(options.debug) debug('GA Rollup Tracker defined:'+options.rollupAccountId,'info');
				} else
					debug("No rollup tracker", "info");
			}
			else { 
				debug('Google Analytics is undefined','error');
			}
		}
		
		// /-- Get Google Analytics script ---
		function loadScript() {
			$.ajax({
				type: 'GET', dataType: 'script',
				url: src, cache: true,
				success: function() {          
					initAnalytics(); 
					if(options.debug) debug('Google Analytics script loaded','info');
				}
			});
		};
		
		// /-- Run when called or on page load ---
		if(options.onLoad) {
			$(window).load(loadScript)
		} else {
			loadScript();
		}
	}
	// /-- Track social fb and twitter
	function trackSocial(){
		//todo integrate twitter tweets and facebook likes/unlike/shares.
	}

	// /-- Track event method ---
	function trackEvent(category, action, label, value) {
		if(typeof pageTracker === 'undefined') {
			debug('Not able to track event without page tracker','error');
		}else {
			pageTracker._trackEvent(category, action, label, value);
		}
	}

	function crossDomain(extUrl){
		if(typeof pageTracker === 'undefined') {
			debug('No cross-domain tracking','error');
		} else {
			rollupTracker._link(extUrl);
		}
	}
	
	// /-- Track pageview method
	function trackPage(page_url){
		if(typeof pageTracker === "undefined"){
			debug("Not able to track page view - page tracker undefined", "error");
		} else {
			pageTracker._trackPageview(page_url);
		}
	}
	function setupEventHandlers() {
		var pp = "";
		if(options.pageProfile !== "")
			pp = options.pageProfile; // site name
		else
			pp = location.href.split(".com")[0].split(".")[1].replace("-","");

		for(hname in options.handlers) {
			var h = options.handlers[hname];
			$(h.selector).each(function() {
				for(h2Name in h.handlers[pp].handler) {
					var h2 = h.handlers[pp].handler[h2Name];
					var matcher = h2.matcher ? h2.matcher : h.matcher;
					if((matcher == null || matcher(this, h2)) && !$(this).hasClass("fancybox")) {
						$(this).bind(h.evtName, {h:h, h2:h2}, function(e) {
							var	h2 = e.data.h2,
									h=e.data.h,
									eHref = $(this).attr("href");									
							var category = h.getCategory(this, h2);
							var action = h.getAction(this, h2);
							var label = h.getLabel(this, h2);
							// this needs its own place outsite the nested loops
							if(typeof eHref==='undefined' && category!=="Hero")
								action = "Launch";					

							if(label.indexOf("/share")>-1)
								action = "Share";

							if(typeof category==="undefined")
								category = h.getCategory(this,h2);

							if(options.debug) {
								e.preventDefault();	
								debug('Category: ' + category + '\n' + 'Action: ' + action + '\n' + 'Label: ' + label + '\n','info');
								if(options.isCrossDomainTracking && typeof eHref!=='undefined' && eHref.match("secure.ncsoft"))
									debug("cross domain here: " + eHref, "info");
							} else {
								trackEvent(category, action, label);							
								if(options.isCrossDomainTracking && typeof eHref!=='undefined' && eHref.match("secure.ncsoft"))
									crossDomain(eHref);							
							}
						});
					} else if (options.debug){
						$(this).bind(h.evtName, function(e) {
							e.preventDefault();
							debug("Error has occured: ", "info");
							debug($(this), "info");
						});					
					}
				}
			});
		}
	}
	
	// /-- Debugging Function ---
	function debug(msg,type) {
		if(typeof window.console != 'undefined' && typeof window.console.log != 'undefined') {
			if(options.debug != true)
				return;
			if(type ==="debug"){
				console.debug(msg);
			}	
			else if(type === 'info'){
				console.info(msg);
			}else if(type === 'warning'){
				console.warn(msg);        
			}else if(type === 'error'){
				console.error('Custom Error: ' + msg);    
			}
		}
	}
	
	// /-- Create an Event Tracker Method ---
	// Note that because this plugin is only to be used once on a page, there is no need to try and preserve the 
	// default options.  This code merges override options directly into the "default options" because its cleaner that way.

	$.fn.ncsCustomEventTracker = function(overrideOptions){
		$.extend(true, options, overrideOptions);
		var category = options.cCategory,
				action = options.cAction,
				label = options.cLabel;		
		if(options.debug) {
					debug('Category: ' + category + '\n' + 'Action: ' + action + '\n' + 'Label: ' + label + '\n','info');
		}
		else { 
			trackEvent(category, action, label);		
		}
	}
	
	$.fn.ncsVirtualPageTracker = function (overrideOptions){
		$.extend(true, options, overrideOptions);
		var page_url = options.virtualPageUrl;
		if(options.debug){
				debug('Virtual Page View: ' + page_url,'info');
		}
		else{
			trackPage(page_url);
		}
		
	}
	
	$.fn.ncsEventTracker = function(overrideOptions) {
		var config_host_url = (("https:" == document.location.protocol) ? "https://a248.e.akamai.net/static.ncwest.origin.ncsoft.com/" : "http://static.ncsoft.com/");	
		$.getScript(config_host_url + "globalTracker/nc.globalTracker.config.js", function(data){	
			options = setOptions();	
			$.extend(true, options, overrideOptions);					
			if(options.isPageTracking){
				setupPageTracker();
			} 
			if(options.isEventTracking)
				setupEventHandlers();		
		}, true);
	}
		
})(jQuery);
