var current_feature = 0;
var num_of_features = 0;

$(function(){
	
	$.ajax({
		type: 'GET',
		url: '_includes/get_home_pano.php',
		success: display_dyk,
		error: ajax_error
	});
	
});

function display_dyk(data)
{
	data = eval("("+data+")");
	
	// show an error if small array
	num_of_features = data['error'].length;
	var txt = "";
	
	if(data['error'][0] != "")
	{
		txt += '<div class="home_item">';
		txt += 	'<div class="feature_desc">' + data['error'][0] + '</div>';
		txt += '</div>';
		
		$("#home_pano").html(txt);
	}
	else
	{
		// loop through all items and create feature divs
		for(var i = 0; i < num_of_features; i++)
		{	
			txt += '<div class="home_item" id="feature_area_'+i+'">';
			txt += 		'<div class="feature_desc">' + data['content'][i] + '</div>';
			txt += '</div>';
		}
		
		if(num_of_features > 1)
		{
			var btn = '<div class="btn_nav" style="margin:10px;">';
			btn += '<div id="dyk_prev" class="button">&lt;</div>';
			btn += '<div id="dyk_pause" class="button middle">||</div>';
			btn += '<div id="dyk_next" class="button">&gt;</div>';		
			btn += '</div>';
			
			$("div.home_pano").prepend(btn);
		}
		
		$("#home_pano").html(txt);
		$("#feature_area_"+current_feature).fadeIn(500);
		
		// =========================================
		//	SET UP TIMER FOR FEATURES
		// =========================================
		if(num_of_features > 1)
		{
			$(document).everyTime(5000, function(){
				
				// increase the id by one (must increase after assign or it ends up like '01' instead of '1')
				id = current_feature;
				id++;
				
				// if outside of bounds set to start (loop)
				if(id >= num_of_features)
					id = 0;
				
				change_item(id);
			});
		}
		
		// =========================================
		//	SET UP FEATURE BUTTONS
		// =========================================
		$("#dyk_pause").click(function(){
			$(document).stopTime();
		});
		
		$("#dyk_next").click(function(){
			$(document).stopTime();
			
			// increase the id by one (must increase after assign or it ends up like '01' instead of '1')
			id = current_feature;
			id++;
			
			// if outside of bounds set to start (loop)
			if(id >= num_of_features)
				id = 0;
			
			change_item(id);
		});
		
		$("#dyk_prev").click(function(){
			$(document).stopTime();
			
			// increase the id by one (must increase after assign or it ends up like '01' instead of '1')
			id = current_feature;
			id--;
			
			// if outside of bounds set to end (loop)
			if(id < 0)
				id = num_of_features - 1;
			
			change_item(id);
		});
	}
}

function ajax_error(XMLHttpRequest, textStatus, errorThrown)
{
	$("#home_pano").html(textStatus);
}

function change_item(id)
{
	$("#feature_area_"+current_feature).fadeOut(200, function()
	{
		// set currently selected element	
		current_feature = id;
		
		// fade the new feature in
		$("#feature_area_"+current_feature).fadeIn(500);
	});
}
