var dbgtrk = false;
/**
 * tracks clicks on "a href"-links and maintains original target attribute
 * @param a - JQuery link object
 * @param push - Array of GA data
 * @param href - alternate link destination (optional, defaults to html attribute)
 * @param target - alternate link target window (optional, defaults to html attribute)
 * @return boolean - always false, JS handles location change
 */
function trakk_link(a, push, href, target) {
	href = href || a.href;
	target = target || a.target || '_self';
	push = push[0] instanceof Array ? push : [push];
	_gaq.push.apply(window._gaq, push);
	if(typeof href != 'undefined') {
		window.setTimeout(function() {
			window.open(href, target);
		}, 100 * push.length );
	}

	if(dbgtrk) console.log(push);
	return false;
};

/**
 * tracks clicks on dom objects
 * @param push - Array of GA data
 * @return boolean - always false
 */
function track_click(push) {
	push = push[0] instanceof Array ? push : [push];
	_gaq.push.apply(window._gaq, push);
	if(dbgtrk) console.log(push);
	return false;
};

/**
 * tracks clicks on flash catalog opening buttons ("Jetzt blättern");
 * triggered from JS-Popup function order/catalog.js::document.ready()
 * @param link - url to track
 */
function track_catalogOpening(link) {
	_gaq.push(function(){
		var pageTracker = _gat._getTrackerByName(); // Gets the default tracker.
		var linkerUrl = pageTracker._getLinkerUrl(link);
		// order/catalog.js
		openPopup(linkerUrl);
	});
}

/**
 * displays overlaying div to hovered elements indicating that "me" is tracked by GA through other functions
 * @param me - JQuery object
 * @return me - JQuery object
 */
function debugTracking(me) {
	$(me).hover(
		function() {
			$(this).append(
				$('<div></div>').addClass('trackingDebug').css({
					'z-index': '20000',
					'position': 'relative',
					'left':'0px',
					'bottom':'20px',
					'border': '1px dashed red',
					'background-color': 'orange',
					'color': 'black',
					'width': '50px'
				}).html('tracked')
			);
			return true;
		},
		function(){
			$('.trackingDebug', this).remove();
			return true;
		}
	);
	return me;
}


// Google Analytics: page navigation tracking
$(document).ready(function(){
	// daten über aktuelle seitenebene parsen
	gaEventTrackingLevelInfo = $.parseJSON(gaEventTrackingLevelInfo);

	// "1" Logo
	$('#jh-s_logo a').addClass('dbgtrk').bind('click', function (){
		return trakk_link(this, ['_trackEvent', 'Teaser/' + gaEventTrackingLevelInfo.root, '1', 'Logo']);
	});

	// "2" komplette Hauptnavigation, WK-Hover und Button
	$('#jh-s_MainLevel1 .jh-c_navMainLevel1Item a, #jh-c_navMainCartOverlay_HoverSwitch a').addClass('dbgtrk').bind('click', function (me){
		return trakk_link(this, ['_trackEvent', 'Navigation/' + gaEventTrackingLevelInfo.root, '2', 'Head']);
	});

	// startseite
	if(gaEventTrackingLevelInfo.level == 0) {
		// 3.X Teaser Startseite
		// 3.1.x Herobox
		// 3.1.0 Herobox Hauptbild
		$(	'.jh-s_container_herobox .jh-c_herobox_stage #jh-s_herobox0 a').addClass('dbgtrk').bind('click', function (){
			return trakk_link(this, [
				'_trackEvent',
				'Teaser/' + gaEventTrackingLevelInfo.root,
				'3.1.0',
				$(this).attr('title')
			]);
		});

		window.setTimeout(function() { // timeout, da jcarousel erst aufgebaut werden muss
			// 3.1.1.x Herobox-Slider vor/zurück Buttons
			$(	'.jh-s_container_herobox .jcarousel-container .jcarousel-prev, '+
				'.jh-s_container_herobox .jcarousel-container .jcarousel-next'
				).each(function(index, item) {
					$(item).addClass('dbgtrk').bind('click', function (){
						return trakk_link(this, [
								'_trackEvent',
								'Teaser/' + gaEventTrackingLevelInfo.root,
								'3.1.1.' + (index+1),
								'Slider'+($(this).hasClass('jcarousel-prev')?' links':' rechts')
						]);
					});
			});

			// 3.1.2.x Herobox-Slider jcarousel-Items
			$(	'.jh-s_container_herobox .jcarousel-container .jcarousel-item').each(function(index, item) {
				$('a', item).addClass('dbgtrk').bind('click', function (){
					return trakk_link(this, [
						'_trackEvent',
						'Teaser/' + gaEventTrackingLevelInfo.root,
						'3.1.2.' + (index+1),
						$(this).attr('title')
					]);
				});
			});
		}  ,100);

		// 3.3.x Cms Teaser (Produktempfehlungen, darin alle Links außer DirectToCart)
		$('.jh-c_product_box').each(function(index, container){
			// Links zu ADS
			$('a', container).not('.jh-c_linkToOverlay, :has(.jh-c_btn_directToCart)').addClass('dbgtrk').bind('click', function (){
				return trakk_link(this, [
					'_trackEvent',
					'Teaser/' + gaEventTrackingLevelInfo.root,
					'3.3.' + (index+1),
					$(this).attr('title')
				]);
			});
			// directToCart-Links
			$('a.jh-c_linkToOverlay', container).has('.jh-c_btn_directToCart').addClass('dbgtrk').bind('click', function (){
				return track_click([
					'_trackEvent',
					'DirectToCart_geöffnet/' + gaEventTrackingLevelInfo.root,
					'3.3.' + (index+1),
					$(this).attr('title')
				]);
			});
		});
	}
	// gruppenseiten
	else {
		// "3.x.Y": Produkt-/Gruppenboxen in Gruppen-Clustern (Produktboxen, ohne DirectToCart Links)
		$('.jh-s_container_product').each(function(groupIndex, groupContainer){
			$('.jh-s_container_groupBox, .jh-s_container_productBox', groupContainer).not('.jh-c_container_movieBox').each(function(boxIndex, box){
				// Links zu ADS oder Gruppenseiten (unter Ausschluss von: Direct-to-Cart, Film-Button und allem was jh-c_overlay nutzt )
				$('a[rel!=#jh-c_overlay]', box).not('.jh-c_linkToOverlay, :has(.jh-c_btn_directToCart)').addClass('dbgtrk').bind('click', function (){
					return trakk_link(this, [
						'_trackEvent',
						'Teaser/Kategorieebene' + gaEventTrackingLevelInfo.level + '/' + gaEventTrackingLevelInfo.root,
						'3.'+ (groupIndex+1) +'.'+ (boxIndex+1),
						$(this).attr('title')
					]);
				});
				// directToCart-Links
				$('a.jh-c_linkToOverlay', box).has('.jh-c_btn_directToCart').addClass('dbgtrk').bind('click', function (){
					return track_click([
						'_trackEvent',
						'DirectToCart_geöffnet/Kategorieebene' + gaEventTrackingLevelInfo.level + '/' + gaEventTrackingLevelInfo.root,
						'3.'+ (groupIndex+1) +'.'+ (boxIndex+1),
						$(this).attr('title')
					]);
				}); // bind
			}); // loop Group-/ProductBoxes
		}); // loop groupContainer
	}

	// "4.x" Sidebar
	$('.jh-c_sidebar_container', '#jh-s_sidebar').each(function(index, container){
		// extrahiert "sidebar-vorteile" aus id="jh-c_sidebar_container__sidebar-vorteile"
		// und erzeugt ["_trackEvent", "Sidebar/Startseite", "4.2", "sidebar-vorteile"]
		$('a', container).addClass('dbgtrk').bind('click', function (){
			return trakk_link(this, [
				'_trackEvent',
				'Sidebar/' + gaEventTrackingLevelInfo.root,
				'4.' + (index+1),
				'' + $(container).attr('id').substr( $(container).attr('id').lastIndexOf('__')+2 )
			]);
		});
	});

	// Direkt-Bestellung / Sidebar
	$("form#orderAddArticle").bind('submit', function (){
		return track_click(['_setCustomVar', 2, 'Direktbestellung', 'genutzt', 2]);
	});

	// "5" komplette Footer-Box
	$('#jh-s_footer_box a').addClass('dbgtrk').bind('click', function (){
		return trakk_link(this, ['_trackEvent', 'Footer/' + gaEventTrackingLevelInfo.root, '5', $(this).attr('title')]);
	});

	// ADS ==========================
	// 1.1.x Mediathek-Vorschaubilder
	$(".jh-c_mt_previewListItem_detail a").each(function(index, item) {
		$(item).addClass('dbgtrk').bind('click', function() {
			track_click([
				'_trackEvent',
				'MediathekVorschaubilder/' + gaEventTrackingLevelInfo.leaf,
				'1.1.' + (index+1),
				$('img', this).attr('alt')
			]);

		});
	});
	window.setTimeout(function(){
	// 1.2.x Mediathek-Slider vor/zurück Buttons
	$(	'.jh-c_mt_detail_previewList .jcarousel-container .jcarousel-prev, '+
		'.jh-c_mt_detail_previewList .jcarousel-container .jcarousel-next'
		).each(function(index, item) {
			$(item).addClass('dbgtrk').bind('click', function (){
				track_click([
						'_trackEvent',
						'MediathekVorschaubilder/' + gaEventTrackingLevelInfo.leaf,
						'1.2.' + (index+1),
						'Slider'+($(this).hasClass('jcarousel-prev')?' links':' rechts')
				]);
			});
		});
	}, 200);
	// 1.3 Mediathek-Overlay geöffnet
	$(	'#jh-c_mt_stage_templates #jh-c_mt_detail_stage_template_img a,  .jh-c_mt_detail_stage_loupe a, .jh-c_mt_detail_stage a').addClass('dbgtrk').bind('click', function (){
		track_click([
			'_trackEvent',
			'Mediathek/' + gaEventTrackingLevelInfo.leaf,
			'1.3',
			'Detail-Bild geklickt (Overlay öffnen)'
		]);
	});

	// 1.4.x Mediathek-Overlay-... == Ajax-Request, siehe /general/relaunch_js/tracking/mediathek_overlay_previewList.js

	// order/add - Tracking der Änderung der Auswahl von Artikeloptionen (Größe, Farbe, ...)
	// bind change event to article options select boxes
	trackSelectOptionsChange($('form#orderAdd select[name^=optionData]'));

	// visual tracking debugger
	if(dbgtrk==true) window.setTimeout(function() { $('.dbgtrk').each(function(i,o){debugTracking(o);}); }, 2000);

});

/**
 * Attaches tracking events to select boxes, to track which box(name) was changed to what(txtValue).
 * Called from
 * - seld::document.ready()
 * - product/viewSmall.js
 * @param selectBoxes - selection of Jquery Selectbox objects
 */
function trackSelectOptionsChange(selectBoxes) {
	$(selectBoxes).each(function(index, selectBox){
		$(selectBox).bind('change', function() {
			name = ''+$(this).attr('id').split('-',2)[1];
			txtValue = ''+$($(this).attr('options')[$(this).attr('selectedIndex')]).attr('label');
			return track_click(['_trackEvent', name, txtValue]);
		});
	});
}

