﻿function loadDemo(path) {

	resetDemos();

	$.get(path, function(data) {
	
		data = data.replace(/<script.*>.*<\/script>/ig,""); // Remove script tags
		data = data.replace(/<\/?link.*>/ig,""); //Remove link tags
		data = data.replace(/<\/?html.*>/ig,""); //Remove html tag
		data = data.replace(/<\/?body.*>/ig,""); //Remove body tag
		data = data.replace(/<\/?head.*>/ig,""); //Remove head tag
		data = data.replace(/<\/?!doctype.*>/ig,""); //Remove doctype
		data = data.replace(/<title.*>.*<\/title>/ig,""); // Remove title tags
		data = data.replace(/<iframe(.+)src=(\"|\')(.+)(\"|\')>/ig, '<iframe$1src="'+'/'+section+'/'+'$3">');; // Change iframe src
		data = data.replace(/<img([^<>]+)src=(\"|\')([^\"\']+)(\"|\')([^<>]+)?>/ig, '<img$1src="'+'/'+section+'/'+'$3" $5/>');; // Change images src
		data = $.trim(data);

		$('style.demo-style').remove();
		$('#demo-frame').empty().html(data);
		$('#demo-frame style').appendTo('head').addClass('demo-style');
		$('#demo-link a').attr('href', path);
		updateDemoNotes();
		updateDemoSource(data);

	});

}

function updateDemoNotes() {

	var notes = $('#demo-frame .demo-description');
	if ($('#demo-notes').length == 0) {
		$('<div id="demo-notes"></div>').insertAfter('#demo-config');
	}
	$('#demo-notes').empty().html(notes.html());
	notes.hide();

}

function updateDemoSource(source) {
	if ($('#demo-source').length == 0) {
		$('<div id="demo-source"><a href="#" class="source-closed">View Source</a><div><pre><code></code></pre></div></div>').insertAfter('#demo-notes');
		$('#demo-source').find("> a").click(function() {
			$(this).toggleClass("source-closed").toggleClass("source-open").next().toggle();
			return false;
		}).end().find("> div").hide();
	}
	$('#demo-source code').empty().text(source);
}

function resetDemos() {
	( $.datepicker && $.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional[''])) );
	$(".ui-dialog-content").remove();
}

$(document).ready(function() {

	//Do not run on /demos/ root page.
	if ( (/demos\/(#.*)?$/i).test(window.location) ) {
		return;
	}
	
	//Rewrite and prepare links of right-hand sub navigation
	$('#demo-config-menu a').each(function() {
		$(this).attr('target', 'demo-frame');
		$(this).click(function(e) {

			resetDemos();
			$(this).parents('ul').find('li').removeClass('demo-config-on');
			$(this).parent().addClass('demo-config-on');

			//Set the hash to the actual page without ".html"
			window.location.hash = this.getAttribute('href').match((/\/([^\/\\]+)\.html/))[1];

			loadDemo(this.getAttribute('href'));
			e.preventDefault();

		});
	});
	
	//If a hash is available, select the right-hand menu item and load it
	if(window.location.hash && window.location.href.indexOf('/demos/') != -1) {
		loadHash();
	}

	resetDemos();

	updateDemoNotes();
	updateDemoSource($.trim($('#demo-frame').html()));
	
	//Prepare the option types
	
	$('#widget-docs dd.option-type').each(function() {
		
		var html = $(this).text();
		var words = $.map(html.split(','), function(n) { return paramDescriptions[$.trim(n)] ? '<span>'+$.trim(n)+'</span>' : $.trim(n); });
		$(this).html(words.join(', '));
		
		$('span', this).click(function() {
			if(paramDescriptions[this.innerHTML]) $('<div>'+paramDescriptions[this.innerHTML]+'</div>').dialog({ open: function() { $(this).parent().attr('id', 'demo-dialog'); }, modal: true, title: this.innerHTML, width: 500 });
		});

	});

	
	$("#widget-docs").tabs();
	$("#widget-docs > div").addClass('clearfix'); //This fixes clearing of containers

	//show details/hide details
	$("#options .options-list, #events .events-list").before('<div class="toggle-docs-links"><a class="toggle-docs-detail" href="#">Show All</a></div>');
	
	//show details/hide details
	$("#stuff .options-list, #events .events-list").before('<div class="toggle-docs-links"><a class="toggle-docs-detail" href="#">Show All</a></div>');

	$("#methods .methods-list").before('<div class="toggle-docs-links"><a class="toggle-docs-detail" href="#">Show All</a></div>');

	var showExamples = true;
	$(".toggle-docs-detail").toggle(function(e){
		var details = $(this).text("Hide All")
			.parent().next("ul").find("li > div:first-child").addClass("header-open");
		if ( showExamples ) {
			details.nextAll().show();
		} else {
			details.next().show();
		}
		e.preventDefault();
	},function(e){
		$(this).text("Show All")
			.parent().next("ul").find("li > div:first-child").removeClass("header-open")
			.nextAll().hide();
		e.preventDefault();
	});

	$(".toggle-docs-example").click(function(e){
		if ( showExamples ) {
			showExamples = false;
			$(".toggle-docs-example").text("Show examples").parent().next("ul").find("div.header-open ~ .option-examples, div.header-open ~ .event-examples").hide();
		} else {
			showExamples = true;
			$(".toggle-docs-example").text("Hide examples").parent().next("ul").find("div.header-open ~ .option-examples, div.header-open ~ .event-examples").show();
		}
		e.preventDefault();
	});

	//Initially hide all options/methods/events
	$('div.option-description, div.option-examples, div.event-description, div.event-examples, div.method-description, div.method-examples').hide();
	
	//Make list items collapsible
	$('div.option-header h3, div.event-header h3, div.method-header h3').live('click', function() {
		var details = $(this).parent().toggleClass('header-open');
		if ( showExamples ) {
			details.nextAll().toggle();
		} else {
			details.next().toggle();
		}
	});
	
	//Hide theming tabs for interactions that cannot be themed
	(/(draggable|droppable|sortable)$/i).test(section) && $('#widget-docs > ul li:last').hide();

	//Load themeswitcher
	$('#switcher').themeswitcher({loadTheme: 'UI lightness'});
	
	listenToHashChange();

});

$(window).bind('load', function() {
	//If we use it as docs page, go to the selected option
	if(window.location.hash && window.location.href.indexOf('/docs/') != -1) {
		gotoHash();
	}
});

function listenToHashChange() {
	
	var savedHash = window.location.hash;
	
	window.setInterval(function() {
		
		if(savedHash != window.location.hash) {
			savedHash = window.location.hash;
			if(window.location.hash && window.location.href.indexOf('/docs/') != -1)
				gotoHash();
			//Since we have bind click event on demos link and load hash on document.ready
			//if(window.location.hash && window.location.href.indexOf('/demos/') != -1)
			//	loadHash();
		}
		
	},200);
	
}

function loadHash() {
	
	$('#demo-config-menu a').each(function() {
		if(this.getAttribute('href').indexOf('/'+window.location.hash.substr(1)+'.html') != -1) {

			$(this).parents('ul').find('li').removeClass('demo-config-on');
			$(this).parent().addClass('demo-config-on');

			loadDemo(this.getAttribute('href'));
		}
	});
	
}

function gotoHash() {
	
	var hash = window.location.hash.substr(1).split('-');
	var go = hash[1] ? hash[1] : hash[0];
	var resolve = { overview: 0,option: 1,event: 2,method: 3,theming: 4 };

	$("#widget-docs").tabs('select', resolve[hash[0]]);
	var h3 = $("#widget-docs a:contains("+go+")").parent();
	h3.parent().parent().toggleClass("param-open").end().next().toggle();
	
	$(document).scrollTop(h3.parent().effect('highlight', null, 2000).offset().top);
		
}
