
// 
// Debug
//

if( debug )
{
	$('').ajaxComplete( function() { log("ajax complete"); } );
	$('').ajaxError(    function() { log("ajax error")     } );
	$('').ajaxSend(     function() { log("ajax send")      } );
	$('').ajaxStart(    function() { log("ajax start")     } );
	$('').ajaxStop(     function() { log("ajax stop")      } );
	$('').ajaxSuccess(  function() { log("ajax success")   } );
}

//
// bind on load -----------------------------------------------------------
//

$(document).ready( function() {
	if( $.browser.msie && $.browser.version < 7 )
	{
		try
		{
			document.execCommand( "BackgroundImageCache", false, true );
		} 
		catch(e) 
		{
		}
	}

	bindStep( '#register', null );
	bindDisabled('#chooselicence');
	bindDisabled('#choosedownload');
	bindDisabled('#chooseactivation');		

    // Disable caching of AJAX responses 
	$.ajaxSetup ({
	    cache: false
	});
});

// Section Loading --------------------------------------------------------
   
var ctxloading = [];   
   
function sectionLoad( ctx, location, parameters, callback )
{
	log( "sectionLoad(): ctx=" + ctx + ", location=" + location + ", loading=" + ctxloading[ctx] );
			   
	$(ctx).find(".wrapper").show();				   
			   
	// post-load stack				   
			    
   	var cbBindStep    = function() { log("cbBindStep()"); bindStep( ctx, null ); }
   	var cbHideLoading = function() { log("cbHideLoading()"); hideLoading( ctx, cbBindStep ); };
   	var cbSyncHeight  = function() { log("cbSyncHeight()"); syncHeight( ctx, null, cbHideLoading ); };	
   	var cbLoaded      = function( responseText, textStatus, XMLHttpRequest ) 
   	{
   		/* "timeout" | "error" | "notmodified" | "success" | "parsererror" */
   		log( "cbLoaded(): status=" + textStatus );
		ctxloading[ctx] = false;
   		if( callback ) { callback.apply(); }
    	cbSyncHeight( ctx );
   	};    	
	 
	// pre-load stack		
	
   	var cbLoad = function() 
	{
		// data[data.length] = { name: "decorator",  value: "ajax" };	
		log( "cbLoad: " + location );
		if( ctxloading[ctx]==true ) 
		{
			log( "Already loading - ignoring." );
			return false;
		}
		ctxloading[ctx]=true;
		var params = jQuery.extend( parameters, { "decorator": "ajax" } );
		$( ctx ).find( ".dynamiccontent" ).load( 
			location + " .ajinc", 
			params, 
			cbLoaded
		);	
	};

	var cbScrollTo    = function() { scrollTo( ctx, cbLoad ); }
	var cbShowLoading = function() { showLoading( ctx, cbScrollTo ); }
   
	syncHeight( ctx, 100, cbShowLoading );
}
   
function sectionUpdate( ctx, location, parameters, callback )
{
	log( "sectionUpdate(): ctx=" + ctx );
			   
	$(ctx).find(".wrapper").show();				   
			   
	// post-load stack				   
	  	var cbBindStep    = function() { bindStep( ctx, null );  }
	  	var cbSyncHeight  = function() { syncHeight( ctx, null, cbBindStep ); };	
	  	var cbLoaded      = function() 
	  	{
	  		if( callback ) { callback.apply(); }
	   		cbSyncHeight( ctx );
	  	};    	
	
	// pre-load stack		
	  	var cbLoad = function() 
		{
			// data[data.length] = { name: "decorator",  value: "ajax" };	
			log( "cbLoad: (section): " + location );
			var params = parameters;
			$( ctx ).find( ".dynamiccontent" ).load( 
				location + " .ajinc", 
				params, 
				cbLoaded
		);	
	};

    syncHeight( ctx, 100, cbLoad );
}    

// Create Account Section -------------------------------------------------

function sectionCreateAccount()
{
	sectionLoad( "#register", ctxp + "/account/createaccount.action" );
}

function actionLogin()
{
	sectionLoad( "#register", ctxp + "/account/loginto.action", {destination: "/account/loginsuccess.action"} );	
}

function actionCreateAccount()
{
	sectionLoad( "#register", ctxp + "/account/register.action" );	
}

   // Choose Licence Section -------------------------------------------------

function sectionChooseLicence()
{
	sectionLoad( "#chooselicence", ctxp + "/account/chooselicence.action" );	
}

function actionTimeLimited()
{
	sectionLoad( "#chooselicence", ctxp + "/account/tll.action" );		
}

function actionHomeLicence()
{
	sectionLoad( "#chooselicence", ctxp + "/account/requesthome.action" );			
}	

function actionRegisterSerial()
{
	sectionLoad( "#chooselicence", ctxp + "/account/reglic!input.action" );			
}

function actionFreeProducts()
{
	sectionLoad( "#chooselicence", ctxp + "/account/freelist.action" );			
}

// Download Section -------------------------------------------------------

function sectionChooseDownload()
{
	sectionLoad( "#choosedownload", ctxp + "/account/choosedownload.action" );
}

   // Activate Section -------------------------------------------------------

function sectionActivate()
{
	sectionLoad( "#chooseactivation", ctxp + "/account/chooseactivation.action" );		
}

// Help -------------------------------------------------------------------

function help( ctx, location, back )
{
	// var req = contextPath + "/account/help.action?location=" + escape(location);
	var req = ctxp + "/account/helpexample.action";
	log( "help(): " + req );
	sectionLoad( ctx, req, null, function(){
		$(ctx).find(".dynamiccontent").append( "<a href='" + back + "'>&lt; back</a>" );		
	});
}	

// Content Loading --------------------------------------------------------

function bindStep( ctx, callback )
{
    log( "bindStep()" );
	checkComplete( ctx );
	
	// form
	$(ctx).find("form.wwform").submit( function() { log("form submit"); return false; } );
	
	// submit buttons
	$(ctx).find(":submit").click( function() { 
		if( $(this).attr("disabled") == true )
		{
			log("ignore disabled submit clicked"); 		
			return false;
		} 
		$(this).attr('disabled','disabled'); 
		log("submit clicked"); 
		return submitForm($(this),ctx); 
	} );
		  
	// links
	$(ctx).find("a:not([@target])").click( function() { 
		log("link clicked"); 
		return submitLink($(this),ctx); 
	} );		
	
	bindForms( ctx );

	if( callback )
	{
		callback.apply();
	}
}

function checkComplete( ctx )
{
	var el = $(ctx).find('.subprocessstatus');

	if( el!=null && el.length!=0 )
	{
		var status = el.text().split(':');
		log("checkComplete(): status message - " + status[0] + "=" + status[1] );					
		switch( status[0] )
		{
			case 'createaccount':
				sectionUpdate( "#chooselicence", ctxp + "/account/chooselicence.action" );
				$('#chooselicence').removeClass('disabled');	
				$('#choosedownload').removeClass('disabled');
				$('#chooseactivation').removeClass('disabled');
				$('#nav').load( ctxp + "/navbar.action .ajinc" );
				highlightThrob( '#chooselicence',"#F7F8FA","#dae0c8", 2 );							
				break;
			case 'chooselicence':
				sectionUpdate( "#chooseactivation", ctxp + "/account/chooseactivation.action" );
				break;					
			default:
				// 
		}
	}
}

function submitForm( el, ctx )
{
	var action = $(ctx).find('form.wwform').attr("action");
	var data = $(ctx).find('form.wwform').serializeArray();
	data[data.length] = { name: $(el).attr("name"), value: $(el).attr("value") };
	data[data.length] = { name: "decorator",  value: "ajax" };	
	sectionLoad( ctx, action, data );
	return false;
}
	
function submitLink( el, ctx )
{
	var link = $(el).attr('href');
	var data = new Array();
	data[data.length] = { name: "decorator",  value: "ajax" };		
	log( data );
	sectionLoad( ctx, link, data );
	return false;
}		
	
function bindForms( ctx )
{
	$(ctx).find('.wwtextfield').focus( function() {
		$('.error').fadeOut();
		var err = $('#' + $(this).attr('id') + '_error');
		if( err ) err.fadeIn();
	} );
	
	$(ctx).find('.wwtextfield').blur( function() {
		$('.error').fadeOut();
	} );		
}	
	
// Heartbeat and logging in / out -----------------------------------------

var userLoggedIn = false;

function updateLoginStatus( newStatus )
{
	if( userLoggedIn && !newStatus )
	{
		$('#chooselicence').addClass('disabled');	
		$('#choosedownload').addClass('disabled');
		$('#chooseactivation').addClass('disabled');
		$('#nav').load( ctxp + "/navbar.action .ajinc" );
		sectionLoad( "#createaccount", ctxp + "/account/createaccount.action" );									
	}
	else if( !userLoggedIn && newStatus )
	{
		$('#chooselicence').removeClass('disabled');	
		$('#choosedownload').removeClass('disabled');
		$('#chooseactivation').removeClass('disabled');
		$('#nav').load( ctxp + "/navbar.action .ajinc" );
		sectionLoad( "#createaccount", ctxp + "/account/createaccount.action" );				
	}
	userLoggedIn = newStatus;
}
	
$(document).ready( function() {
	$('#heartbeatcount').heartbeat( {
		timeout: 180000,
		callback: function() 
		{ 
			log( "heartbeat_callback" );
			var hb = $('#heartbeatcount'); 
			hb.text( parseInt( hb.text() ) + 1 ); 
			
			$.getJSON(
				ctxp + "/account/heartbeat.action",
				{}, 
				function( json )
				{
					  log( "Logged in: " + json.user.loggedin );
					  updateLoginStatus( json.user.loggedin );
				}
			);

			highlightThrob( '#heartbeat', "#00FF00", "#DADADA", 1 );
		}
	} );
	
});		
	
// Loading Indicator ------------------------------------------------------
	
function showLoading( ctx, callback )
{
	$(ctx).find(".wrapper .loadingindic").fadeIn( "fast", callback );	
}

function hideLoading( ctx, callback )
{
	$(ctx).find(".wrapper .loadingindic").fadeOut( callback );
}	

function syncHeight( ctx, min, callback )
{
	var content = $( ctx ).find('.dynamiccontent');
	var attr = ($.browser.msie && $.browser.version < 7) ? 'height' : 'min-height';
	var h = content.height() + 1;
	
	if( min && h < min ) h = min;
	
	h += "px";
	
	$(ctx).find('.wrapper').css(attr,h);
	$(ctx).find(".loadindicinner").css(attr,h);
	$(ctx).find(".loadingindic").css(attr,h);	
	
	// $(ctx).find(".disabledwrapper").css(attr,h);
	$(ctx).find(".disabledinner").css(attr,h);	
	$(ctx).find(".disabledinner2").css(attr,h);	
						
	if( callback ) 
	{ 
		callback.apply(); 
	}
}

function scrollTo( target, callback )
{
	var target = $(target);
	var targetOffset = target.offset().top - 50;
	var scrollOffset = Math.max( $('html').attr("scrollTop"), $('body').attr("scrollTop") );
	if( scrollOffset > targetOffset )
	{
		if( callback )
		{			
			log( "scrollTo: animate with callback" );
			// can't work out how to get jQuery to call back only once, instead
			// of per matched element so this is a workaround
			var wrappedCb = (function() {
				var run = 0;
				return function() {
					if( run > 0 ) return;
					run++;
					callback.apply();
				};
			})();	
			$('html,body').animate( {scrollTop: targetOffset}, 500, "swing", wrappedCb );
		}
		else
		{
			log( "scrollTo: animate without callback" );		
			$('html,body').animate( {scrollTop: targetOffset}, 500, "swing" );			
		}
	}
	else
	{
		if( callback ) 
		{			
			log( "scrollTo: default callback" );		
			callback.apply();
		}
	}
}

// Disabled Indicator -----------------------------------------------------

function bindDisabled( ctx )
{
	var context = $(ctx);
	
	context.find('.disabledinner').css( "opacity", "0.8" );
	
	context.find('.disabledinner')
		   .css( "opacity", "0.8" )
		   .click( 
				function(e) {
					showDisabled( e, ctx );
				}
	);
	
	context.find('.disabledinner2').mouseout(
		function(e) {
			hideDisabled( e, ctx );
		}
	);
	
	syncHeight( ctx, null, null );
}

function showDisabled( e, ctx )
{
	$(ctx).find('.disabledinner2').fadeIn('slow');
	return false;				
}

function hideDisabled( e, ctx )
{
	// ignore events bubbled from children
	if (!e) var e = window.event;
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toelement;
	while (reltg.tagName != 'BODY'){
		if (reltg.id == this.id){return;}
		reltg = reltg.parentNode;
	}
	
	$(ctx).find('.disabledinner2').fadeOut('slow'); 
	return false;	
}
