$(document).ready(function() {

	tab = 'null';

	$('.apankLoadPage').live('click', (function(e){
		e.preventDefault();
		
		id = this.id;
		
		status = cekStatus(id);
		
		if(status === true){
			tab = tab+'____'+id;
			tambahHeadTab(id);
			tambahBodyTab(id);
			loadPage(id);
		}else{
			tampilTab(id);
		}
	}))
	
	cekStatus = function(id){
		nTab = tab.split('____');
		juml = nTab.length;
		for(i = 1; i <= juml; i++){
			if(nTab[i] === id){
				return false;
			}
		}
		return true;
	}
	
	tambahHeadTab = function(id){
	
		title = $('#'+id).attr('alt');
	
		$('.tab').removeAttr('class').addClass('tab');
	
		$('#headNull')
		.removeAttr('id')
		.attr('id', 'head-'+id)
		.html('<a href="#" title="content-'+id+'" class="tab active" id="aHead-'+id+'">'+title+'</a><span id="close-'+id+'" class="closeContent">&nbsp;&nbsp;&nbsp;</span>')
		.after('<li id="headNull"></li>');
	}
	
	tambahBodyTab = function(id){
	
		idBody = 'content-'+id;
	
		$('.content').css('display', 'none');
	
		$('#bodyNull')
		.removeAttr('id')
		.attr('id', idBody)
		.addClass('content')
		.after('<div id="bodyNull"></body>');
	}
	
	loadPage = function(id){
		$('#content-'+id).html('<div class="loadingPage">Loading....</div>');
		$.ajax({
		type: 'GET',
			url: ''+id,
			data: $(this).serialize(),
			success: function(data) {
				$('#content-'+id).html(data);
			}
		})
	}
	
	tampilTab = function(id){
		nId = '#aHead-'+id;
	
        $('.tab').removeClass("active");
		$(nId).addClass("active");
        $(".content").slideUp();
        var content_show = 'content-'+id;
        $("#"+content_show).slideDown();
	}
	
	$('.closeContent').live('click',(function(){
		id = this.id;
		id = id.replace('close-', '');
		nId = '____'+id;
		tab = tab.replace(nId, '');
		$('#content-'+id).remove();
		$('#head-'+id).remove();
	}))
	
    $("a.tab").live('click',(function () {
        $(".active").removeClass("active");
        $(this).addClass("active");
        $(".content").slideUp();
        var content_show = $(this).attr("title");
        $("#"+content_show).slideDown();
    }));
}); 

