(function($){
	// Even faster way to loop through elements
	// https://gist.github.com/500145
	$.fn.quickEach = (function(){

		var jq = jQuery([1]);

		return function(c) {
			var i = -1, el, len = this.length;
			try {
				while (
					++i < len &&
					(el = jq[0] = this[i]) &&
					c.call(jq, i, el) !== false
				);
			} catch(e){
				delete jq[0];
				throw e;
			}

			delete jq[0];
			return this;

		};

	}());

})(jQuery);

(function( $ ){

	var settings = {
		'tabSelector'		: 'ul li',
		'paneSelector'		: 'div',
		'activeTabClass'	: 'tabs-active',
		'hiddenPaneClass'	: 'tabs-hidden'
	};

	var methods = {
		// Show/hide tabs when clicked
		toggleTab : function(event){

			event.preventDefault();

			var $this = $(this), $a = $(this).find('a')[0];
			var hash = '#' + $a.hash.slice(1);

			if(!$this.hasClass(settings.activeTabClass)) {
				$this.siblings().removeClass(settings.activeTabClass).end()
					.addClass(settings.activeTabClass);

				$(hash).siblings(settings.paneSelector).addClass(settings.hiddenPaneClass).end()
					.removeClass(settings.hiddenPaneClass);
			}

		},
	
		// Initialises tabs
		init : function( options ) {

			// If options exist, lets merge them
			// with our default settings
			if ( options ) { 
				$.extend( settings, options );
			}

			return this.quickEach(function(){

				var $this = $(this), data = $this.data('tabs');

				$(settings.paneSelector, $this).addClass(settings.hiddenPaneClass);
				$(settings.tabSelector, $this).bind('click', methods.toggleTab).first().trigger('click');

			});

		}
	};

	$.fn.tabs = (function( method ) {

		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
		}    

	});

})( jQuery );

$(function(){
	IEPin.initSite();
});

var IEPin, btn1, btn2;

if (!IEPin) 
	IEPin = {};

IEPin.atlasImg = null;

IEPin.channel = 'pinning';

IEPin.statActive = 'active';

IEPin.lightbox = null;

IEPin.discoverLightbox = null;

IEPin.atlas = {
	fbLikeBottom: 'http://view.atdmt.com/action/UMIRF_IE9_BOW_Final_FacebookLikeBottom',
	fbLikeTop: 'http://view.atdmt.com/action/UMIRF_IE9_BOW_Final_FacebookLikeTop',
	downloadJQuery: 'http://view.atdmt.com/action/UMIRF_IE9_Pinning_DownloadjQuery', // Any links to pinify
	downloadIE: 'http://view.atdmt.com/action/UMIRF_IE9_Pinning_DownloadStart',
	sectionToggle:'http://view.atdmt.com/action/UMIRF_IE9_Pinning_ExpandCollapse',
	exportFavicon: 'http://view.atdmt.com/action/UMIRF_IE9_Pinning_ExportFavicon',
	getCode: 'http://view.atdmt.com/action/UMIRF_IE9_Pinning_GetCode', // Called when assets are downloaded
	atlasHome:'http://view.atdmt.com/action/UMIRF_IE9_Pinning_HomePage',
	ideaBookDownload: 'http://view.atdmt.com/action/UMIRF_IE9_Pinning_IdeaBookDownload',
	importLogo: 'http://view.atdmt.com/action/UMIRF_IE9_Pinning_ImportLogo',
	linkMSDN: 'http://view.atdmt.com/action/UMIRF_IE9_Pinning_LinkMSDN'};

IEPin.btn1;

IEPin.btn2;

IEPin.scrollOpts = {
	containerID: 'to_top', // fading element id
	containerHoverClass: 'to_top_hover', // fading element hover class
	scrollSpeed: 1200,
	easingType: 'easeOutQuart'
};

IEPin.initSite = function () {

	$('#steps a').bind('click', IEPin.softScroll);

	$('.expandToggle').bind('click', IEPin.toggleSection).quickEach(function () {
		$(this).data('IEPin.orig', $(this).html())
	});

	// Open external links in another window
	/*$('a').filter(function () { return this.hostname !== location.hostname; } 
		).attr('target', '_blank');
	$('.download, .pdf, .link').attr('target', '_blank');*/


	// Back to top
    // //Removed because it is adding a link "To top" at the end of the page
	//$().UItoTop(IEPin.scrollOpts); ;

	//SyntaxHighlighter.defaults['toolbar'] = false;
	SyntaxHighlighter.all()

	// Enable tabs
	$('.codeblock').tabs({ 'paneSelector': '.codewrapper' });

	// Idea gallery events
	$('#idea_gallery')
		.delegate('.idea, .download', 'mouseenter', IEPin.statsMouseover)
		.delegate('.idea, .download', 'mouseleave', IEPin.statsReset)
		.delegate('.idea', 'click', IEPin.statsLightbox);

	$('#discoverability_gallery')
		.delegate('a', 'click', IEPin.discoverExample);

	// IE9 pinning features
	IEPin.makePinnable();

	// Wrapping in a try/catch to keep from throwing errors in
	// browsers that do not support pinning
	try {
		if (window.external.msIsSiteMode()) {
			// In case this was still set
			window.external.msSiteModeClearIconOverlay();
			IEPin.triggerDynamicJumpList();
			IEPin.initThumbnailButtons();
		}
	} catch (ex) {
		// Fail silently.
	}

	$("#example_notification").bind('click', IEPin.flashTaskbar);

	$("#example_overlay").bind('click', IEPin.addOverlay);

	$('#nav_language a').bind('click', function (event) { event.preventDefault(); });

	$.fn.pinable({
	    message: IEPin.sitePinningMessage,
		cookieLength: 90,
		discStyle: 'toast',
		useCookie: true,
		logoPath: 'http://www.esecurityplanet.com/img/esp-32.png'
	});

	// TRACKING //

	// Set atlas image
	IEPin.atlasImg = $("#atlasimg");

	// Trigger home page view in atlas
	IEPin.logAtlas(IEPin.atlas.atlasHome);

	// Capture download event for tracking
	$('#idea_gallery .download, .ideabook .download').bind('click', function (event) {
		event.preventDefault();
		IEPin.logAtlas(IEPin.atlas.ideaBookDownload);
		window.location = $(this).attr('href');
	});

	$('#intro .download').bind('click', function (event) {
		event.preventDefault();
		IEPin.logAtlas(IEPin.atlas.downloadIE);
		window.location = $(this).attr('href');
	});

	// Tracking pinify
	$('.download_plugin, .pinify_more').bind('click', function (event) {
		IEPin.logAtlas(IEPin.atlas.downloadJQuery);
	});

	// Tracking msdn instructions
	$('.msdn, .msdn_more').bind('click', function (event) {
		IEPin.logAtlas(IEPin.atlas.linkMSDN);
	});

	// Icon import/export
	$(document).bind('IEPin.expandToggle', IEPin.logSection)
		.bind('IEPin.xicon.Export', IEPin.logIconExport)
		.bind('IEPin.xicon.Import', IEPin.logIconImport);

	// Assets download
	$('.discoverability .download, .assets_download').bind('click', function (event) {
		event.preventDefault();
		IEPin.logAtlas(IEPin.atlas.getCode);
		_om_gbls.trackLink("step_5", $(this), "endSection");
		window.location = $(this).attr('href');
	});

	$('.share .facebook').bind('click', function (event) {
		event.preventDefault();
		IEPin.logAtlas(IEPin.atlas.fbLikeBottom);
		_om_gbls.trackLink("facebook", $(this), "share");
		window.location = $(this).attr('href');
	});

	// Submitting site to IE Gallery
	$('.site_submit a').bind('click', function (event) {
		event.preventDefault();
		_om_gbls.trackLink("step_7", $(this), "endSection");
		window.location = $(this).attr('href');
	});

};

IEPin.toggleSection = function (event) {

	//prevent the default action for the click event
	event.preventDefault();

	var $this = $(this), closing = $this.parents('section').hasClass('expanded') ? true : false, origHTML = $this.data('IEPin.orig'), hash = $this[0].hash.slice(1);

	// Swap the text
	if (closing) {
		$(document).trigger({ type: 'IEPin.expandToggle', item: hash, oEventType:'collapseSection', trigger: $(this) });
		$this.attr('title', origHTML).html(origHTML);
	} else {
		// Trigger event for stats
		$(document).trigger({ type: 'IEPin.expandToggle', item: hash, oEventType:'expandSection', trigger: $(this) });
		var msg = 'Collapse', altMsg = $this.attr('data-collapse-msg');
		if (altMsg !== null) {
			msg = altMsg;
		}
		$this.attr('title', 'Collapse').html(msg);
	}

	// Swap classes and slide
	$this.parents('section:first').toggleClass('expanded').find('.expandable').slideToggle('slow');

	// If we're opening, scroll to top of step
	if (!closing) {

		var target_top = $('#' + hash).offset().top, href = $(this).attr('href');

		try {
			//prevent the default action for the click event
			event.preventDefault();

			//go to that anchor by setting the body scroll top to anchor top
			$('html, body').animate({ scrollTop: target_top }, target_top / 1.5, "easeOutCubic", function () {
				window.location.href = href; // Set this after scroll to prevent page jump
			});

		}
		catch (err) {
			//Handle errors here
			window.location.href = href;
		}

	}

}

IEPin.softScroll = function (event) {

	//get the top offset of the target anchor
	var $this = $(this), hash = '#' + $this[0].hash.slice(1), target_top = $(hash).offset().top, href = $(this).attr('href');

	event.preventDefault();

	try {

		$('html, body').animate({ scrollTop: target_top }, target_top / 1.5, "easeOutCubic", function () {
			window.location.href = href; // Set this after scroll to prevent page jump
		});

	}
	catch (err) {
		//Handle errors here
		window.location.href = href;
	}

}

IEPin.flashTaskbar = function (event) {

	try {
		if (window.external.msIsSiteMode()) {
			window.setTimeout(function () {
				window.external.msSiteModeActivate();
			}, 5000);
		} else {
			alert('You have the site pinned to view the demo.');
		}
	} catch (ex) {
		alert('Must be using IE9+ and in Site Mode.');
		
	}

}

IEPin.addOverlay = function (event) {
	var $this = $(this);
	try {
		if (window.external.msIsSiteMode()) {
			if ($this.data('overlayActive') !== true) {
				$this.html('Remove Overlay').data('overlayActive', true);
				window.external.msSiteModeSetIconOverlay("/img/overlay.ico", "Example Notification");
			} else {
				$this.html('Show Overlay!').data('overlayActive', false);
				window.external.msSiteModeClearIconOverlay();
			}

		} else {
			alert('You have the site pinned to view the demo.');
		}
	} catch (ex) {
		alert('Must be using IE9+ and in Site Mode.');
	}
}

IEPin.statsMouseover = function(event){
	event.preventDefault();

	$.doTimeout('hover', 170, function(elem){
		var hash = '#' + $(elem).parent().find('a.idea')[0].hash.slice(1);
		$('#pinning_stats img').removeClass(IEPin.statActive);
		$(hash).addClass(IEPin.statActive);
	}, this);
}

IEPin.statsReset = function(event){
	event.preventDefault();

	$.doTimeout( 'hover', 170, function(elem){
		$('#pinning_stats img').removeClass(IEPin.statActive);
		$('#ideas_default').addClass(IEPin.statActive);
	}, this);
};

IEPin.statsLightbox = function(event){

	event.preventDefault();

	var el = $(this).attr('data-lightbox'), $el = $('#' + el);

	IEPin.lightbox = $el.lightbox_me({
		centered: true,
		appearEffect: 'fadeIn',
		closeSelector: '.close',
		lightboxSpeed: '340',
		appearEase: 'easeOutQuart'});

};

IEPin.discoverExample = function (event) {

	event.preventDefault();

	var hash = $(this)[0].hash.substring(1), message = '', pinningExamples = '#pinningToastExample, #pinningPushUpExample, #pinningTopHatExample, #pinning-discoverability', msg, settings = { debug: true, logoPath: 'http://10.1.44.60/xampp/pin/esp-32.png' }, opts = {};

	$(pinningExamples).remove();

	switch (hash) {
		case "toast":
			msg = IEPin.exampleToastMessage;
			opts = { discStyle: 'toast', elementId: 'pinningToastExample', message: msg };
			break;
		case "topHat":
			msg = IEPin.exampleTopHatMessage;
			opts = { discStyle: 'topHat', elementId: 'pinningTopHatExample', message: msg };
			break;
		case "pushUp":
			msg = IEPin.examplePushUpMessage;
			opts = { discStyle: 'pushUp', elementId: 'pinningPushUpExample', message: msg };
			break;
	}

	settings = $.extend(settings, opts);

	$.fn.pinable('init', settings);

};

IEPin.discoverMouseover = function (event) {
	event.preventDefault();

	$.doTimeout('hover', 170, function (elem) {
		var hash = '#' + $(elem).find('a')[0].hash.substring(1);
		$('#pinning_types a').removeClass(IEPin.statActive);
		$(elem).find('a').addClass(IEPin.statActive);
		$('#step_5 .step_graphic').removeClass(IEPin.statActive);
		$(hash).addClass(IEPin.statActive);
	}, this);
}

IEPin.discoverReset = function (event) {
	event.preventDefault();

	$.doTimeout('hover', 170, function (elem) {
		$('#pinning_types a.active').removeClass(IEPin.statActive);
		$('#pinning_types a:first').addClass(IEPin.statActive);
		$('#step_5 .step_graphic').removeClass(IEPin.statActive);
		$('#step_5 .step_graphic:first').addClass(IEPin.statActive);
		$('#ideas_default').addClass(IEPin.statActive);
	}, this);
};

IEPin.makePinnable = function(){
	try {
		if (!window.external.msIsSiteMode()) {
			$('.pinning_icon').addClass('msPinSite').attr('alt', IEPin.sitePinningMessage);
		}
	} catch (ex) {
		// Fail silently.
	}
};

IEPin.triggerDynamicJumpList = function(){

	window.external.msSiteModeClearJumpList(); // Clear jump list
	window.external.msSiteModeCreateJumpList(IEPin.jumpListCategory); // Create new category
	
	if(document.getElementById('steps')){
	var steps = document.getElementById('steps'), stepsArray = steps.getElementsByTagName('a');

	// Looping through in reverse
	for (var i = stepsArray.length - 1; i >= 0; i--){

		var title = jQuery.trim(stepsArray[i].innerHTML.replace(/<[^>]*>[\s\S]<[^>]*>?/g, '').replace('<span class="step_title">', '').replace('</span>', '')), href = stepsArray[i].href;

		// Adding the steps to the list
		window.external.msSiteModeAddJumpListItem(title, href, "http://www.esecurityplanet.com/favicon.ico", 'self');
	};
	}

};

IEPin.initPrettyPrint = function(){
	var p = document.getElementsByTagName('pre'), pl = p.length, l , ll, nl, ev = '';
	while (pl--) {
		l = p[pl].innerHTML.match(/^(.+)$/mg), ll = l.length, nl = '';
		while(ll--) {
			ev = (ll % 2 === 0) ? '' : 'even'; // for IE
			if (l[ll].match(/(\/\/.*)/)) {          // for comments
				l[ll] = l[ll].replace(/(\/\/.+)/g, '<span class="nocode com">$1</span>');
			}
			l[ll] =l[ll].replace(/(\s\s)(?!=(?:<=^|>)[^><]+?(?=<|$))/g,'\u00A0 '); // only IE needed this

			nl = '<li class="' + ev + '"><span>' + l[ll] + '</span></li>' + nl;
		}
		p[pl].innerHTML = '<ol>' + nl + '</ol>';
	}

	prettyPrint();
};

IEPin.initThumbnailButtons = function(){
	IEPin.btn1 = window.external.msSiteModeAddThumbBarButton('/img/twitter.ico','Twitter');
	IEPin.btn2 = window.external.msSiteModeAddThumbBarButton('/img/facebook.ico','Facebook');

	if (document.addEventListener) {
		document.addEventListener('msthumbnailclick', IEPin.onButtonClicked, false);
	}
	else if (document.attachEvent) {
		document.attachEvent('onmsthumbnailclick', IEPin.onButtonClicked);
	}

	window.external.msSiteModeShowThumbBar();
};

IEPin.onButtonClicked = function(btn){
	switch (btn.buttonID) {
		case IEPin.btn1:
			// Handle button 1 click
			window.location = 'http://twitter.com/share?url=http://www.esecurityplanet.com&text=' + IEPin.twitterShare;
			break;
		case IEPin.btn2:
			// Handle button 2 click
			window.location = 'http://www.facebook.com/sharer.php?u=http://www.esecurityplanet.com&src=sp';
			break;
	}
};

IEPin.logAtlas = function (src) {
	if (src !== null && src !== undefined && src !== "") {
		try {
			IEPin.atlasImg.attr("src", "/images/layout/placer.png");
			IEPin.atlasImg.attr("src", src);
		} catch (e) { }
	}
};

IEPin.logSection = function(event){
	try {
		_om_gbls.trackLink(event.item, event.trigger, event.oEventType); // value, anchorElt, evts
	} catch (e){}

	IEPin.logAtlas(IEPin.atlas.sectionToggle); // Log with atlas
};

IEPin.logIdeaBookDownload = function(event){
	logAtlas(IEPin.atlas.ideaBookDownload);
}

IEPin.logIconImport = function(){
	try {
		_om_gbls.trackLink("step_1", true, "startSection");
	} catch(e){}
	IEPin.logAtlas(IEPin.atlas.importLogo); // Log with atlas
}

IEPin.logIconExport = function(){
	try {
		_om_gbls.trackLink("step_1", true, "endSection");
	} catch(e){}
	IEPin.logAtlas(IEPin.atlas.exportFavicon); // Log with atlas
}

