$( document ).ready(function() {
	renderLinks('.jqm-list a');
	$( ".jqm-search-link" ).one( "click", function() {
		renderLinks('.jqm-search-panel .jqm-list a');
	});
	
	$( ".ui-icon-home" ).trigger('click');
	
});
$( document ).on( "pageinit", function() {
	$( document ).on( "swipeleft", function(e) {
		$( ".jqm-search-panel" ).panel( "open" );
		$( ".jqm-search-link" ).trigger( "click" );
    });
	$( document ).on( "swiperight", function(e) {
		$( ".jqm-navmenu-panel" ).panel( "open" );
    });
});

/*
 * API sites
 */

function renderLinks(selector) {
	$(selector).on( "click",function( e ) {
		href = $( this ).attr( "href" );
		if(href != '#'){
			if(selector == '.ui-link'){
				var urlexp = new RegExp( '(http|ftp|https)://[\\w-]+(\\.[\\w-]+)+([\\w-.,@?^=%&:/~+#-]*[\\w@?^=%&;/~+#-])?' );
				if ( urlexp.test(href) ){
					//alert('test');
					window.open($(this).attr('href'), '_blank', 'location=yes');
					return false;
				}else{
					href = href.replace(/([/])/g, "");
					href = 'entries/'+href+'.html';
				}
			}
			$.mobile.loading( "show", {
		            text: $.mobile.loader.prototype.options.text,
					textVisible: true,
					theme: 'a'
				});
			$.ajax({
				url: href,
				dataType: "html",
				isLocal: true
			}).done(function( result ) {
				$("#main_content").html(result).trigger("create").trigger("pagebeforecreate").h2linker();
				SyntaxHighlighter.highlight();
				runDemo();
				$("html, body").animate({scrollTop: 0}, "fast");
				changeImgPath();
				renderLinks('.ui-link');
				$.mobile.loading( "hide" );
				$(".jqm-navmenu-panel, .jqm-search-panel").panel("close")
			}).error(function() {
				$.mobile.loading( "hide" );
				// show error message
				$.mobile.loading( "show", {
		            text: $.mobile.pageLoadErrorMessage,
					textVisible: true,
					textonly: true
				});
				// hide error message
				setTimeout(function(){
					$.mobile.loading( "hide" );
				},1500);
			});
			return false;
		}
	});
} 

function runDemo() {
	$( ".entry-example" ).each(function() {
		var iframeSrc,
			src = $( this ).find( ".syntaxhighlighter" ),
			output = $( this ).find( ".code-demo" );

		if ( !src.length || !output.length ) {
			return;
		}

		// Get the original source
		iframeSrc = src.find( "td.code .line" ).map(function() {
			// Convert non-breaking spaces from highlighted code to normal spaces
			return $( this ).text().replace( /\xa0/g, " " );
		// Restore new lines from original source
		}).get().join( "\n" );

		iframeSrc = iframeSrc
			// Insert styling for the live demo that we don't want in the
			// highlighted code
			.replace( "</head>",
				"<style>" +
					"html, body { border:0; margin:0; padding:0; }" +
					"body { font-family: 'Helvetica', 'Arial',  'Verdana', 'sans-serif'; }" +
				"</style>" +
				"</head>" )
			// IE <10 executes scripts in the order in which they're loaded,
			// not the order in which they're written. So we need to defer inline
			// scripts so that scripts which need to be fetched are executed first.
			.replace( /<script>([\s\S]+)<\/script>/,
				"<script>" +
				"window.onload = function() {" +
					"$1" +
				"};" +
				"</script>" )
			.replace( "//code.jquery.com/jquery-1.10.2.js",
				"/js/jquery.js");

		var iframe = document.createElement( "iframe" );
		iframe.width = "100%";
		iframe.height = output.attr( "data-height" ) || 250;
		output.append( iframe );

		var doc = (iframe.contentWindow || iframe.contentDocument).document;
		doc.write( iframeSrc );
		doc.close();
	});
};
function changeImgPath(){
	$("#long-desc .image img").each(function() {
		var imgpath = $(this).attr('src');
		$(this).attr('src','/img'+imgpath);
	});
	
	// Quick link with fixed header
	$('.jqm-quicklink-panel a[href^="#"]').on('click',function (e) {
	    e.preventDefault();
		$('.jqm-quicklink-panel').panel('close');
	    var target = this.hash;
	    var $target = $(target);

	    $('html, body').stop().animate({
	        'scrollTop': $target.offset().top - $('.jqm-header').height() - 60
	    }, 'fast');
	});
}

/*var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        //app.receivedEvent('deviceready');
		app.addEventListener("backbutton", this.onBackKeyDown, false);
    },
    // Update DOM on a Received Event
    onBackKeyDown: function(e) {
        e.preventDefault();
    }
};

app.initialize();
*/