/* Loading Ajax Gif */

function getLoading(context, bars, center, innerRadius, size, color) {
    var animating = true,
        currentOffset = 0;
  
    function makeRGBA(){
        return "rgba(" + [].slice.call(arguments, 0).join(",") + ")";
    }
    function drawBlock(ctx, barNo){
        ctx.fillStyle = makeRGBA(color.red, color.green, color.blue, (bars+1-barNo)/(bars+1));
        ctx.fillRect(-size.width/2, 0, size.width, size.height);
    }
    function calculateAngle(barNo){
        return 2 * barNo * Math.PI / bars;
    }
    function calculatePosition(barNo){
        angle = calculateAngle(barNo);
        return {
            y: (innerRadius * Math.cos(-angle)),
            x: (innerRadius * Math.sin(-angle)),
            angle: angle
        };
    }
    function draw(ctx, offset) {
        clearFrame(ctx);
        ctx.save();
        ctx.translate(center.x, center.y);
        for(var i = 0; i<bars; i++){
            var curbar = (offset+i) % bars,
                pos = calculatePosition(curbar);
            ctx.save();
            ctx.translate(pos.x, pos.y);
            ctx.rotate(pos.angle);
            drawBlock(context, i);
            ctx.restore();
        }
        ctx.restore();
    }
    function clearFrame(ctx) {
        ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);  
        //catch(err) {  }
    }
    function nextAnimation(){
        if (!animating) {
            return;
        };
        currentOffset = (currentOffset + 1) % bars;
        draw(context, currentOffset);
        setTimeout(nextAnimation, 50);
    }
    nextAnimation(0);
    return {
        stop: function (){
            animating = false;
            clearFrame(context);
        },
        start: function (){
            animating = true;
            nextAnimation(0);
        }
    };
    }

var loadingController;
var loadingState = 0;

function startLoadingAnimation(afterJquery)
{
	if(loadingState != 1)
	{
		var canvas = document.createElement("canvas");
      	canvas.width= 200;
      	canvas.height = 200;
      	canvas.style.cssText="";
      	//document.getElementById('spinner').appendChild(canvas); // 
      	document.body.appendChild(canvas);
      	loadingController = getLoading(canvas.getContext("2d"), 9, {x:100, y:100}, 13, {width: 4, height:16}, {red: 102, green: 102, blue: 102});
	    
	    //setTimeout('stopLoadingAnimation();', 15000);
	    
    }
}

function stopLoadingAnimation()
{
	loadingController.stop();
	$('canvas').remove(); // Get rid of any previous canvases
	loadingState = 0;
}


/* Browse Javascript */

function checkForPrompt()
{
	if($('#content #prompt').html() == null)
	{
		// remove any other prompts 
		$('#prompt').each(function(){
			$(this).remove();
		});
		
		$('#content').prepend('<div id="prompt">Loading...</div>');
	}
}

function onSkip()
{
	$('#prompt').html($('#promptLoading').html());
	$('.loading').html(' ');
	$('#prompt').fadeIn('slow'); 
	startLoadingAnimation('.loading');
	$.post("index.php?_m=ajax",
		{ cmd: 'skip' },
	  	function(data){
	    	if(testForRedirect(data))
		    {
		    	data = '';
		    	$.get("settings.php"
		    	,{}
		    	,function(dSettings){
		    		$('#promptSettings').html(dSettings);
		    		onSkip();
		    	});
		    }
		    if(data != '')
		    {
		    	$('#content').html(data);
		    	hs.preloadImages(6);
		    }
		   
		    $('#prompt').fadeOut();	
		     stopLoadingAnimation();	    
	  	}
	);  
	
	
}

function onBack()
{
	$('#prompt').html($('#promptLoading').html());
	$('.loading').html(' ');
	$('#prompt').fadeIn('slow'); 
	startLoadingAnimation('.loading');
	$.post("index.php?_m=ajax",
		{ cmd: 'back' },
	  	function(data){
	    	if(testForRedirect(data))
		    {
		    	data = '';
		    	$.get("settings.php"
		    	,{}
		    	,function(dSettings){
		    		$('#promptSettings').html(dSettings);
		    		onSkip();
		    	});
		    }
		    if(data != '')
		    {
		    	$('#content').html(data);
		    	hs.preloadImages(6); 
		    }
		    $('#prompt').fadeOut();
		    stopLoadingAnimation();
	  	}
	);
}

function onDelete(_id)
{
	$('#prompt').html($('#promptLoading').html());
	$('.loading').html('Deleting...');
	
	startLoadingAnimation('.loading');
	$.post("index.php?_m=ajax",
		{ cmd: 'delete', pE_id: _id  },
	  	function(data){
	    	if(testForRedirect(data))
		    {
		    	data = '';
		    	$.get("settings.php"
		    	,{}
		    	,function(dSettings){
		    		$('#promptSettings').html(dSettings);
		    		onSkip();
		    	});
		    }
		    if(data != '')
		    {
		    	$('#content').html(data);
		    	hs.preloadImages(6);
		    }
		    $('#prompt').fadeOut();
		    stopLoadingAnimation();
	  	}
	);
}

function onAdd(_id)
{
	$('#prompt').html($('#promptLoading').html());
	$('.loading').html('Adding To Strand...');
	
	startLoadingAnimation('.loading');
	$.post("index.php?_m=ajax",
		{ cmd: 'add', pE_id: _id  },
	  	function(data){
	    	if(testForRedirect(data))
		    {
		    	data = '';
		    	$.get("settings.php"
		    	,{}
		    	,function(dSettings){
		    		$('#promptSettings').html(dSettings);
		    		onSkip();
		    	});
		    }
		    if(data != '')
		    {
		    	$('#content').html(data);
		    	hs.preloadImages(6);
		    }
		    $('#prompt').fadeOut();
		    stopLoadingAnimation();
	  	}
	);
}

function saveSettings()
{
	startLoadingAnimation('.loading');
	$('#settings .title').html('<span class="pink">Saving... Please wait...</span>');
	$('#btnSettingsBack').fadeOut('fast',function(){
		$('#prompt #frmSettings').submit();
	});
	
}

function testForRedirect(data)
{
	//alert(data);
	if(data.match('{!!{reload}!!}') != null)
	{
		window.location = 'index.php';
		return true;
	}
	return false;
}

function promptDelete()
{
	checkForPrompt();
	$('#prompt').html($('#promptDelete').html());
	$('#prompt').fadeIn();
}

function promptAdd()
{
	checkForPrompt();
	$('#prompt').html($('#promptAdd').html());
	$('#prompt').fadeIn();
}

function showSpinner()
{
	
}

function hideSpinner()
{
	//$('#spinner').remove();
}

settingState = 0;

function toggleSettings()
{
	if(settingState == 0)
	{
		showSettings();
	}
	else
	{
		// hideSettings();
	}
}

function showSettings()
{
	settingState = 1;
	startLoadingAnimation('.loading');
	$('#browseCache').html($('#browse').html());
	$('#browse').html(' ');
	$('body').addClass('settings');	
	$('#prompt').html($('#promptLoading').html());
	$('.loading').html(' ');
	$('#prompt').fadeIn('slow',function(){
		$('#prompt').html($('#promptSettings').html());
		$('#header .settings').fadeOut('slow',function(){
			$('#header .settings').addClass('viewSettings');
			$('#header .settings').fadeIn('slow');
			stopLoadingAnimation();		
		});		
	});
}

function hideSettings()
{
	settingState = 0;	
	$('#browse').html($('#browseCache').html());
	$('body').removeClass('settings');
	$('#prompt').fadeOut();
	$('#header .settings').fadeOut('slow',function(){
			$('#header .settings').removeClass('viewSettings');
			$('#header .settings').fadeIn('slow');
		});
	
}

/* orentation javascript */
function updateOrientation()
{
	//alert('ornientation change: '+window.orientation);
	setTimeout(scrollTo, 0, 0, 0);
	switch(window.orientation)
	{		
		case 90:
		case -90:
			switchToChatWallView();
			break;
				
		case 0:
		case 180:
			switchToBrowseView();			
			break;
	}
}

function switchToBrowseView()
{
	//alert('switch to browse view');
	// If it is hidden
	if($('#content #browse').html() == null)
	{
		// fade browse out
		$('#chatwall').fadeOut('normal',function(){
			// Take the chat wall out of the contentCache
			var _wall = $('#contentCache').html();
			// Move the browse to the contentCache
			$('#contentCache').html($('#content').html());
			
			// replace the wall into the content overriding the browse
			$('#content').html(_wall);
			setTimeout(scrollTo, 0, 0, 0);
			$('#browse').fadeIn('normal', function(){
				$('#rotate-note').fadeOut('normal', function(){
					$('#rotate-note').html('Rotate for Chat Wall');
					$('#rotate-note').fadeIn();
				});
			});
		});
		
		// Turn black back on 
		$('#black').css('background', '#000000');
	}
}

function switchToChatWallView()
{
	//alert('switch to chatwall view');
	if($('#content #chatwall').html() == null)
	{
		// fade browse out
		$('#browse').fadeOut('normal',function(){
			// Take the chat wall out of the contentCache
			var _wall = $('#contentCache').html();
			// Move the browse to the contentCache
			$('#contentCache').html($('#content').html());
			
			// replace the wall into the content overriding the browse
			$('#content').html(_wall);
			setTimeout(scrollTo, 0, 0, 0);
			$('#chatwall').fadeIn('normal', function(){
				$('#rotate-note').fadeOut('normal', function(){
					$('#rotate-note').html('Rotate for Browse');
					$('#rotate-note').fadeIn();
				});
			});
			
		});
		
		// Turn off the black screen on highslide
		$('#black').css('background', 'none');
	}
}

function toggleChatBrowseView()
{
	if($('#content #chatwall').html() == null)
	{
		switchToChatWallView();
	}
	else
	{
		switchToBrowseView();
	}
}

function changeWallView()
{
	var _wall = $('#general-chat-room').val();
	var _view = $('#general-chat-view').val();
	
	$.get('chatwall.php?w='+_wall.toString()+'&v='+_view.toString()
	,function(_r)
	{
		$('#chatwall').fadeOut('normal',function(){		
			$('#chatwall').html(_r);
			$('#chatwall').fadeIn();		
		});
	});
}