(function(){
	var ns = __namespace( "Astro.Blog.Layout.MainFrame" );

	/** @type {System.Cycle} */
	var Cycle                                         = __import( "System.Cycle" );
	/** @type {System.Cycle.Trigger} */
	var Trigger                                       = __import( "System.Cycle.Trigger" );
	/** @type {System.utils.IKey} */
	var IKey                                          = __import( "System.utils.IKey" );
	/** @type {System.utils.DataKey} */
	var DataKey                                       = __import( "System.utils.DataKey" );
	/** @type {System.utils.Perf} */
	var Perf                                          = __import( "System.utils.Perf" );
	/** @type {Dandelion} */
	var Dand                                          = __import( "Dandelion" );
	/** @type {Dandelion.IDOMElement} */
	var IDOMElement                                   = __import( "Dandelion.IDOMElement" );
	/** @type {Dandelion.Window} */
	var wsupp                                         = __import( "Dandelion.Window" );
	/** @type {System.Debug} */
	var debug                                         = __import( "System.Debug" );
	/** @type {Astro.Bootstrap} */
	var Bootstrap                                     = __import( "Astro.Bootstrap" );
	/** @type {Astro.Mechanism.CharacterCloud} */
	var CharacterCloud                                = __import( "Astro.Mechanism.CharacterCloud" );
	/** @type {Astro.Mechanism.Parallax} */
	var Parallax                                      = __import( "Astro.Mechanism.Parallax" );
	/** @type {Astro.Blog.Components.Bubble} */
	var Bubble                                        = __import( "Astro.Blog.Components.Bubble" );

	var postData                                      = __import( "System.Net.postData" );

	// __import( "Dandelion.CSSReset" ); CSS_RESERVATION
	// __import( "Dandelion.CSSAnimations" ); CSS_RESERVATION
	// __import( "Astro.Blog.SharedStyle" ); CSS_RESERVATION
	// __import( "Astro.Starfall.Element.Layer" ); CSS_RESERVATION

	/** @function {System.Net.getData} */
	var getData = __import( "System.Net.getData" );
	var mobile = __import( "System.Global.MOBILE" );

	var header;

	// menu and horizon
	var horizon;
	var contact;
	var	contact_page;
	var collapse_panel;
	var c_expand = false;

	var init = function ()
	{
		initTopButton();
		navControl();
		initBackgroundParallax();
		initArchiveButtons();
	};

	var initArchiveButtons = function()
	{
		Dand.id( "archive-save" )
			.setAttribute(
				"href", "https://archive.today/?run=1&url=" + encodeURIComponent( document.location )
			);
		Dand.id( "archive-view" )
			.setAttribute(
				"href", "https://archive.today/" + document.location.href
			);
		Dand.id( "archive-list" )
			.setAttribute(
				"href", "https://archive.today/" + encodeURIComponent( document.location.hostname )
			);
	};

	var topButtons = [];
	var initTopButton = function()
	{
		var fhorizon = Dand.id( "fhorizon" );
		// init params
		header = Dand.id( "header" );
		horizon = Dand.id( "horizon" );

		contact_page = Dand.id( "contact" );
		collapse_panel = Dand.id( "collapse_panel" );

		horizon.style.backgroundColor
			= fhorizon.style.backgroundColor
			= "purple";

		contact = Dand.id( "menu_cont", true );
		contact.addEventListener( "Click", loadContactForm );

		Dand.id( "menu", true ).foreach(
			1, function( e )
			{
				e = IDOMElement( e );
				topButtons.push( e );
				if( e.getDAttribute( "active" ) !== null )
				{
					e.setAttribute( new DataKey( "master", true ) );
				}
			}
		);
	};

	var loadContactForm = function( e )
	{
		getData( "/ajax/get-snippet/ContactForm", function( data )
		{
			var data = JSON.parse( data );
			var wrapper = IDOMElement( contact_page ).first( 1 );
			if ( wrapper )
			{
				wrapper.innerHTML = data["mesg"];
				Cycle.next( function()
				{
					PrepareForm();
					expandContact( e );
					wrapper.style.marginTop = .5 * ( 400 - wrapper.clientHeight ) + "px";
				} );
			}
		} );
	};

	var cBubble;
	var PrepareForm = function()
	{
		var captcha = Dand.id( "contact-recaptcha", true );
		var mesgform = Dand.id( "cc-send-mesg", true );
		var reUUID = Perf.uuid;
		var limit = 5;

		var sitekey = captcha.getDAttribute( "sitekey" );
		var src = captcha.getDAttribute( "src" );
		var action = captcha.getDAttribute( "ast-action" );
		var script = Dand.wrapna( "script", new IKey( "src", src ) );
		document.head.appendChild( script );

		/** @type {_3rdParty_.Recaptcha} */
		var Recaptcha;

		if( !cBubble )
		{
		   	cBubble = new Bubble();
			document.body.appendChild( cBubble.init() );
		}

		var i = 0;
		var errMesg = Dand.id( "contact-errmesg" );

		var submitMessage = function( action, name, email, mesg )
		{
			postData( action, {
				"name": name, "email": email, "mesg": mesg
				, "recaptcha_response_field": Recaptcha.getResponse().trim()
			}
			, function ( e ) {
			   	doCollapse();

				if( e.status )
				{
					// pop message
					cBubble.setColor( "cornflowerblue" );
					Cycle.next( function () { cBubble.pop( "Message sent" ); } );

					// blurp after 1 sec
					Cycle.delay( function () { cBubble.blurp(); }, 3500 );
				}
			}
			, function( err )
			{
				errMesg.innerHTML = "Error occurred";

				if( !err.status )
				{
					errMesg.innerHTML = err[ "mesg" ];
				}

				errMesg.removeAttribute( "data-disabled" );
			} );
		};

		mesgform.addEventListener( "Submit", function( e ) {
			var name = Dand.id( "contact-name" ).value.trim();
			var email = Dand.id( "contact-email" ).value.trim();
			var mesg = Dand.id( "contact-message" ).value.trim();

			errMesg.setAttribute( "data-disabled", 1 );

			try
			{
				if( !name )
					throw new Error( "How should I address You?" );
				if( !email )
					throw new Error( "Please enter your email." );
				if( !mesg )
					throw new Error( "And your message?" );
			}
			catch( ex )
			{
				errMesg.removeAttribute( "data-disabled" );
				errMesg.innerHTML = ex.message;
				return;
			}

			submitMessage( action, name, email, mesg );

		} );

		var CaptchaReady = function()
		{
			captcha.clear();
			try
			{
				Recaptcha.render( "contact-recaptcha", {
					"theme": "light", "sitekey": sitekey
				} );
			}
			catch( ex )
			{
			   debug.Error( ex );	
			}
		};

		Cycle.perma(
			reUUID, function()
			{
				if( limit < i ++ )
				{
					var mesg = Dand.glass( "c_so_sorry" );
					if( mesg.length ) mesg[0].style.display = "block";
				}

				if( Recaptcha = window["grecaptcha"] )
				{
					Cycle.permaRemove( reUUID );
					CaptchaReady();
				}
			} , 500
		);
	};

	var navControl = function ()
	{
		// Page control
		/** @type {Dandelion.IDOMElement} */
		var page_control = Dand.id( "top_control", true );
		var bottom_control = Dand.id( "bottom_control" );

		if ( page_control && bottom_control )
		{
			var appendp = function( elem, self )
			{
				var clone = elem.cloneNode( true );
				if( clone.className == "p_navigation" )
				{
					IDOMElement( clone ).reverseChild();
				}
				bottom_control.appendChild( clone );
				return true;
			};

			page_control.last( document.ELEMENT_NODE, appendp );
			page_control.first( document.ELEMENT_NODE, appendp );
		}
	};

	/////// Menu
	// Contact
	var expandContact = function ()
	{
		// disable click event on the button
		contact.removeEventListener( "Click", loadContactForm );
		// enable click event for collapse
		collapse_panel.onclick = doCollapse;

		// Expand contact panel
		contact.style.cursor = "default";
		contact_page.style.height = "400px";
		header.style.marginTop = "400px";

		// Save horizon color to collapse panel
		collapse_panel.style.backgroundColor = horizon.style.backgroundColor;

		horizon.style.backgroundColor = "dimgray";

		for( var i in topButtons ) topButtons[i].removeAttribute( "data-active" );
		contact.setAttribute( new DataKey( "active" ) );

		c_expand = true;
	};

	var doCollapse = function ()
	{
		// disable click event for collapse
		collapse_panel.onclick = null;

		Trigger.height( contact_page, 0, function()
		{
			// enable click event on the button
			contact.addEventListener( "Click", loadContactForm );
		} );
		
		// Reverting states
		contact_page.style.height
			= contact.style.color
			= contact.style.cursor
			= header.style.marginTop
			= "";

		// Apply saved color to horizon
		horizon.style.backgroundColor = collapse_panel.style.backgroundColor;

		for( var i in topButtons )
		{
			if( topButtons[i].getDAttribute( "master" ) )
			{
				topButtons[i].setAttribute( new DataKey( "active" ) );
			}
			else
			{
				topButtons[i].removeAttribute( "data-active" );
			}
		}

		c_expand = false;
	};

	var initBackgroundParallax = function ()
	{
		var bg = Dand.id("main_background");
		if( !bg )
		{
			debug.Info( "Parallax Container is not available" );
			return;
		}
		// far from observer
		var slide_1 = { lowerLimit: 70, upperLimit: 100 }
		// bottom cloud, concentrated
		, slide_2a = { lowerLimit: 0, upperLimit: 200 }
		, slide_2b = { lowerLimit: 0, upperLimit: 200 }
		, slide_2c = { lowerLimit: 0, upperLimit: 200 }

		, slide_3 = { lowerLimit: 20, upperLimit: 100 }
		, slide_4 = { lowerLimit: 70, upperLimit: 100 }

		, cloudRange_1 = { lowerLimit: 0, upperLimit: 100, leftLimit: -10, rightLimit: 110 }
		, cloudRange_2a = { lowerLimit: 180, upperLimit: 200, leftLimit: -10, rightLimit: 110 }
		, cloudRange_2b = { lowerLimit: 290, upperLimit: 300, leftLimit: -10, rightLimit: 110 }
		, cloudRange_2c = { lowerLimit: 390, upperLimit: 400, leftLimit: -10, rightLimit: 110 }
		, cloudRange_3 = { lowerLimit: 0, upperLimit: 300, leftLimit: -10, rightLimit: 110 }
		, cloudRange_4 = { lowerLimit: 80, upperLimit: 100, leftLimit: -10, rightLimit: 110 }

		, cCloudSymbol = ["\u25CF", "\u25CF", "\u25CF", "\u25CB", "\u25CB"]
		, cCloudSymbol2 = ["\u25CC" ]

		// , colors = ["FF1D25", "662D91", "3FA9F5", "7AC943", "FF7BAC", "603813", "FF931E"]
		, colors = ["FF1D25", "662D91", "7AC943", "FF7BAC", "603813", "FF931E"]
		, i = new Date().getDay()

		, cCloud_1 = CharacterCloud.create( cCloudSymbol2, "spin", 5, cloudRange_1 )
		, cCloud_2a = CharacterCloud.create( cCloudSymbol, null, 10, cloudRange_2a )
		, cCloud_2b = CharacterCloud.create( cCloudSymbol, null, 20, cloudRange_2b, 10 )
		, cCloud_2c = CharacterCloud.create( cCloudSymbol, null, 30, cloudRange_2c, 5 )
		, cCloud_3 = CharacterCloud.create( cCloudSymbol2, "spin cw", 5, cloudRange_3 )
		, cCloud_4 = CharacterCloud.create( cCloudSymbol, null, 5, cloudRange_4 );

		if( mobile )
		{
			bg.appendChild( Parallax.cssSlide( cCloud_2a, 0, slide_2a ) );
			bg.appendChild( Parallax.cssSlide( cCloud_2b, 1, slide_2b ) );
		}
		else
		{
			bg.appendChild( Parallax.cssSlide( cCloud_1, 0, slide_1 ) );
			bg.appendChild( Parallax.cssSlide( cCloud_2a, 1, slide_2a ) );
			bg.appendChild( Parallax.cssSlide( cCloud_2b, 1, slide_2b ) );
			bg.appendChild( Parallax.cssSlide( cCloud_2c, 1, slide_2c ) );
			bg.appendChild( Parallax.cssSlide( cCloud_3, 2, slide_3 ) );
			bg.appendChild( Parallax.cssSlide( cCloud_4, 3, slide_4 ) );
		}

		IDOMElement( bg ).foreach( 1, function(e)
		{
			e.style.color = "#" + colors[i ++];
			if (colors.length < i) i = 0;
		});

		Parallax.attach( window, wsupp, 0.5 );

		var cp = 0;
		var pp = 0;
		var bWrapper = Dand.id( "begin-wrapper" );
	};

	Bootstrap.regInit( init );
})();