var ACTIVITY_LOADED = 1;
var ARTICLE_LOADED = 1;
var STATS_LOADED = 1;
var HEADLINE_LOADED = 0;
var NEW_ARTICLE_LOADED = 0;
var HEADLINE_AGE = 'today';
var NOT_FOUND = 'Belum ada headline di sini. Coba cek toko sebelah';
var WINDOW_FOCUS = 1;
var TIME_ACCELERATOR = 10;

$(function(){
	//Default Action
	$(".tab_content").css({'left':'-9999px'});//Hide all content
	$("ul.tabs li:first").addClass("active").show(); //Activate first tab
	$(".tab_content:first").css({'left':0}); //Show first tab content
	
	//On Click Event
	$("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").css({'left':'-9999px'});//Hide all content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).css({'left':0})//fadeIn(); //Fade in the active content
		return false;
	});
	
		//Default Action
	$(".tab_dir_content").hide(); //Hide all content
	$("ul.tabs_dir li:first").addClass("active").show(); //Activate first tab
	$(".tab_dir_content:first").show(); //Show first tab content
	
	//On Click Event
	$("ul.tabs_dir li").click(function() {
		$("ul.tabs_dir li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_dir_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		return false;
	});
  
  	//Default Action
	$(".tab_vid_content").hide(); //Hide all content
	$("ul.tabs_vid li:first").addClass("active").show(); //Activate first tab
	$(".tab_vid_content:first").show(); //Show first tab content
	
	//On Click Event
	$("ul.tabs_vid li").click(function() {
		$("ul.tabs_vid li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_vid_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		return false;
	});
  
	/* Lala */
	//Default Action
	/*
	$(".tab_profil_content").hide(); //Hide all content
	$("ul.tabs_profil li:first").addClass("active").show(); //Activate first tab
	$(".tab_profil_content:first").show(); //Show first tab content
	
	//On Click Event
	$("ul.tabs_profil li").click(function() {
		$("ul.tabs_profil li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_profil_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		return false;
	});
	*/
  
  	//Default Action
	$(".tab_user_content").hide(); //Hide all content
	$("ul.tabs_user li:first").addClass("active").show(); //Activate first tab
	$(".tab_user_content:first").show(); //Show first tab content
	
	//On Click Event
	$("ul.tabs_user li").click(function() {
		$("ul.tabs_user li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_user_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		return false;
	});
   
  $('.avatar-reply').bind('click', function(){
		$('#komentar-text').val() == 'Komentar Anda...' ? $('#komentar-text').val('') : '';
		var value = $('#komentar-text').val() + '@'+$(this).attr('value')+ ': ';
		$('#komentar-text').val(value).focus();
		$("#komentar-text").removeClass('inactive');
	});


	$('#toggle').bind("click", function() {
	if ($(this).attr("class") == "play")
	$(this).attr("class", "pause");
	else
	$(this).attr("class", "play");
	});	
	
	
	$(".slidingList .slidingListWrapper .slidingListSources ul li a").click(function(){
	
		sourceContainer = $(this).parent().parent().parent().siblings(".slidingListContainers").find("div#" + $(this).parent().attr("id") + "Container");
		sourceContainer.css("display", "block");

		listSourcesWrapper = $(this).parent().parent().parent().parent();
		listSourcesWrapper.animate({"marginLeft": "-270px"}, 270);
		if($(this).parent().parent().is('ul.list-sites')){
			getNewArticles($(this).parent().attr('id'), ''+$(this).attr('rel')+'');
		}
		return false;
	});
	
	$(".slidingList .slidingListWrapper .slidingListContainers .itemContainerBackButton a ").click(function(){
		sourceContainer = $(this).parent().parent();
		listSourcesWrapper = $(sourceContainer).parent();
		
		listSourcesWrapper.animate({"marginLeft": "0"}, 270, function(){
			$(sourceContainer).find(".itemContainer").css("display", "none");
		});
		return false;
	});
	
	$(".slidingListUser .slidingListWrapper .slidingListSources ul li a").click(function(){
	
		sourceContainer = $(this).parent().parent().parent().siblings(".slidingListContainers").find("div#" + $(this).parent().attr("id") + "Container");
		sourceContainer.css("display", "block");

		listSourcesWrapper = $(this).parent().parent().parent().parent();
		listSourcesWrapper.animate({"marginLeft": "-250px"}, 250);
		return false;
	});
	
	$(".slidingListUser .slidingListWrapper .slidingListContainers .itemContainerBackButton a ").click(function(){
		sourceContainer = $(this).parent().parent();
		listSourcesWrapper = $(sourceContainer).parent();
		
		listSourcesWrapper.animate({"marginLeft": "0"}, 250, function(){
			$(sourceContainer).find(".itemContainer").css("display", "none");
		});
		return false;
	});
	
  $('#coda-slider-1').codaSlider({
		autoSlide: true,
		autoSlideInterval: 4000,
		autoSlideStopWhenClicked: true
	});
	

	/* kakilangit */
	$(window).bind('blur', function() {
	   WINDOW_FOCUS = 0;
		TIME_ACCELERATOR = 1;
	});

	$(window).bind('focus', function() {
	   WINDOW_FOCUS = 1;
		TIME_ACCELERATOR = 10;
	});
	/* 
		* New Actitivities 
		* 1 minute
	*/
	$("#salsil-activities").everyTime((60000/TIME_ACCELERATOR),function() {
		if(ACTIVITY_LOADED){
			getActivities();
		}
	});
	$("#salsil-activities").everyTime(1500,function() {
		var activity = $(".ta").children()[0];
		$(this).prepend(activity);
		old_activity = $(this).children()[10];
		if (old_activity) {
			$(old_activity).empty();
			$(old_activity).remove();
		}
		$(activity).slideDown("medium");
	});		
	/* 
		* Statistic 
		* 30 minutes
	*/
	$('span.user_count').everyTime(1800000, function(){
		if(STATS_LOADED){
			setStats();
		}
	});

	$("span.timelapse").readable();
	/* 
		* Readable time 
		* 1 minute
	*/
	setInterval(function(){ $("span.timelapse").readable(); }, 60000);
	/* 
		* Reset All 
		* 30 minutes
	*/
	setInterval("resetAll()", 1800000);
});

function resetAll(){
	ACTIVITY_LOADED = 1;
	ARTICLE_LOADED = 1;
	STATS_LOADED = 1;
	return false;
}

function evokePopup(popup_id) {
	$("#" + popup_id).css("top", window.scrollY);
	$("#" + popup_id).fadeIn("fast");
	$("#" + popup_id + " .closeTrigger").one('click', function(){$("#" + popup_id).fadeOut("fast"); return false});
	return false;
}

function getNewArticles(id, source){
	if(source == 'salsil') source = 0;
	var article = '';
	var ty;
	var ap;
	NEW_ARTICLE_LOADED = 0;
	$.getJSON(document.base_url + 'ajax/getLatestArticles/' + source,  function(json){
		NEW_ARTICLE_LOADED = 1;
		if(json.length > 0)
		{	
			for(i=0; i<json.length; i++) {
				ty = '06';
				ap = json[i].application_id ? json[i].application_id : source;
				$.post(document.base_url+"ajax/cekAsikLatestArticles", {appId:ap,postId:json[i].post_id}, 
					function(data){
						if(data == "0") {
						} else {
							evt =data.split('-');
							$('#fave-06-'+evt[0]+'-'+evt[1]).removeClass('b-asik');
							$('#fave-06-'+evt[0]+'-'+evt[1]).addClass('b-asik-faved');
						}
					});
				article += '<li class="clearfix"> <img class="webicon" src="images/favicons/'+json[i].application_slug+'.png"><h4><a href="'+json[i].post_link+'">'+json[i].post_title+'</a></h4><ul class="sh_fav"><li class="asik"><a id="fave-'+ty+'-'+ap+'-'+json[i].post_id+'" class="b-asik" onclick="favePost(\'fave-'+ty+'-'+ap+'-'+json[i].post_id+'\',6,'+ap+','+json[i].post_id+');" title="Ingat artikel ini" href="javascript:void(0)">Asik</a></li></ul></li>';
			}
			
		}else{
			article += '<li class="notebox">'+NOT_FOUND+'</li>';
		}
		$('#'+id+'Articles').html(article).show();
	});
	return false;
}

function showHeadline(source){
	HEADLINE_LOADED = 0;
	var headline  = '';
	var loading = '<li class="loadingSection"> </li>';
	var rel = 0;

	$('.headlines').hide();
	rel = $('#headline-'+source+'').attr('class');
	if(rel == 'active'){
		$('#headline-'+source+'').removeClass('active').hide();
	}else{
		$('#headline-'+source+'').html(loading).show();
		$.getJSON(document.base_url + "ajax/get_headlines/"+source+"/"+HEADLINE_AGE+"/",  function(json){
			HEADLINE_LOADED = 1;
			if(json.length > 0){
				for(i=0; i<json.length; i++) {
					headline  += '<li class="item"><img src="'+json[i].application_url+'images/users/'+json[i].user_id+'-32.jpg" alt="'+json[i].user_name+'" width="32" height="32"/><div class="item-right"> <div class="bubble"> <div class="speach"><a href="'+json[i].application_url+'a/'+json[i].article_id+'#komentar">'+json[i].article_comments+'</a></div> <div class="arrow"></div></div> <a href="'+json[i].application_url+'a/'+json[i].article_id+'" target="_blank"><strong>'+json[i].article_title_limit+'</strong></a> <small class="notes"><a href="'+document.base_url+'profil/'+json[i].user_name+'">'+json[i].user_penname+'</a> - '+json[i].timelapse+'</small></div></li>';
				}

			}else{
				headline += '<li class="notebox">'+NOT_FOUND+'</li>';
			}
			$.getJSON(document.base_url + "ajax/getCountHeadlines/"+source+"/"+HEADLINE_AGE+"/",  function(c){ $('#headline-count-'+source+'').html(c); });
			$('#headline-'+source+'').addClass('active').html(headline).show();
		});		
	}
}

function getActivities(){
	ACTIVITY_LOADED = 0;
	$.getJSON(document.base_url + 'ajax/getCacheActivities/0/' + document.activity_id + '/',  function(json){
		ACTIVITY_LOADED = 1;
		if(json.length > 0)
		{
			var activity;
			var activities = $('.ta');
			for(i=0; i<json.length; i++) {
	   		$(activities).prepend('<li class="odd none"><img width="32" src="'+document.base_url+'images/users/'+json[i].sender_uid+'-32.jpg"/> <p>'+ json[i].post_body_short +'</p><div class="clearfix"></div> </li>');
			}
			document.activity_id = json[0].post_id;
		}
	});
}

function getArticles(){
	ARTICLE_LOADED = 0;
	$.getJSON(document.base_url + 'ajax/getArticles/' + document.article_id,  function(json){
		ARTICLE_LOADED = 1;
		if(json.length > 0)
		{	
			var article;
			var articles = $('.tp');
			var ty;
			var ap;
			for(i=0; i<json.length; i++) {
				ty = json[i].application_id ? '3' : '1';
				ap = json[i].application_id ? json[i].application_id : '0';
				$(articles).prepend('<li class="none" id="article-new-'+json[i].post_id+'"> <ul class="toolbar"> <li><a href="#" class="tb-share">share</a> <ul> <li><a href="http://www.facebook.com/sharer.php?u='+json[i].article_link+'&amp;t='+json[i].article_title+'" class="fb">Facebook</a></li><li><a href="http://twitter.com/home/?status='+json[i].article_title+' '+json[i].article_link+'" class="twitter">Twitter</a></li> <li><a href="http://digg.com/submit?phase=2&amp;url='+json[i].article_link+'&amp;title='+json[i].article_title+'&amp;media=news&amp;topic=" class="digg">Digg</a></li> <li><a href="http://delicious.com/save?jump=yes&amp;url='+json[i].article_link+'&amp;title='+json[i].article_title+'" class="delicious">Delicious</a></li> <li><a href="http://www.myspace.com/Modules/PostTo/Pages/?l=3&amp;u='+json[i].article_link+'&amp;t='+json[i].article_title+'&amp;c=" class="myspace">MySpace</a></li> </ul> </li> <li><a href="javascript:void(0);" onclick="favePost(this,'+ty+','+ap+','+json[i].post_id+');" class="tb-favorite">favorit</a></li></ul><img src="'+document.base_url+'images/favicons/'+json[i].application_slug+'.png" class="webicon" /><h4>'+json[i].article_a+'</h4><p class="notes"><img width="16" src="'+document.base_url+'images/users/'+json[i].uid+'-16.jpg"/> '+json[i].user_alias+', <span class="timelapse" title="'+json[i].article_time_utc+'">'+json[i].article_time+'</span></p></li>');
			}

			document.article_id = json[0].article_timestamp;
			after_dom();
		}
	});
}

function favePost(obj, ty,ap,ar)
{
	if(!$("#logout").length) {
		evokePopup('loginBox');
	} else {
			obj = '#'+obj;
			if($(obj).attr('class') == 'b-asik-faved' ) {
				$.post(document.base_url+'ajax/unbookmark/', {ty:ty, ap:ap, ar:ar}, function(data){
					$(obj).removeClass('b-asik-faved'); $(obj).addClass('b-asik');
				}, "text");  
			} else if($(obj).attr('class') == 'b-asik' ) {
				$.post(document.base_url+'ajax/bookmark/', {ty:ty, ap:ap, ar:ar}, function(data){
					$(obj).addClass('b-asik-faved'); $(obj).removeClass('b-asik');
				}, "text");  
			}
		}
		return false;
}

function setStats(){
	STATS_LOADED = 0;
	var stat1 = 0; var stat2 = 0; var stat3 = 0;
	var stat4 = 0; var stat5 = 0; var stat6 = 0;
	$.getJSON(document.base_url + "ajax/getUserRegisteredCount/",  function(json){
		stat1 = 1; json = number_format(json, 0, ',', '.'); $('span.user_count').html(json);
	});
	$.getJSON(document.base_url + "ajax/getArticlesPostCount/",  function(json){
		stat2 = 1; json = number_format(json, 0, ',', '.'); $('span.article_count').html(json);
	});
	$.getJSON(document.base_url + "ajax/getBlogCount/",  function(json){
		stat3 = 1; json = number_format(json, 0, ',', '.'); $('span.blog_count').html(json);
	});
	$.getJSON(document.base_url + "ajax/getBlogPostCount/",  function(json){
		stat4 = 1; json = number_format(json, 0, ',', '.'); $('span.blog_post_count').html(json);
	});
	$.getJSON(document.base_url + "ajax/getTwitterUserCount/",  function(json){
		stat5 = 1; json = number_format(json, 0, ',', '.'); $('span.twitter_count').html(json);
	});
	$.getJSON(document.base_url + "ajax/getTwitterCount/",  function(json){
		stat6 = 1; json = number_format(json, 0, ',', '.'); $('span.tweet_count').html(json);
	});
	if(stat1 && stat2 && stat3 && stat4 && stat5 && stat6){
		STATS_LOADED = 1;
	}
}

function after_dom(){
	$("span.timelapse").readable();
	setInterval(function(){ $("span.timelapse").readable(); }, 5000);
}
function getCookie(cookie_name){
	if (document.cookie.length > 0){ 
		cookie_start = document.cookie.indexOf(cookie_name + "=");
		if (cookie_start!=-1){
    		cookie_start = cookie_start + cookie_name.length + 1;
    		cookie_end = document.cookie.indexOf(";",cookie_start);
    		if (cookie_end == -1) cookie_end = document.cookie.length;
    		return unescape(document.cookie.substring(cookie_start,cookie_end));
    	}
  	}
	return "";
}

function setCookie(cookie_name, value, expiredays){
	var exdate = new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = cookie_name+ "=" +escape(value)+
	( (expiredays==null) ? "" : ";expires="+exdate.toGMTString() );
}

function number_format (number, decimals, dec_point, thousands_sep) {
	var n = number, prec = decimals;

	var toFixedFix = function (n,prec) {
	    var k = Math.pow(10,prec);
	    return (Math.round(n*k)/k).toString();
	};

	n = !isFinite(+n) ? 0 : +n;
	prec = !isFinite(+prec) ? 0 : Math.abs(prec);
	var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
	var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

	var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

	var abs = toFixedFix(Math.abs(n), prec);
	var _, i;

	if (abs >= 1000) {
	    _ = abs.split(/\D/);
	    i = _[0].length % 3 || 3;

	    _[0] = s.slice(0,i + (n < 0)) +
	          _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
	    s = _.join(dec);
	} else {
	    s = s.replace('.', dec);
	}

	var decPos = s.indexOf(dec);
	if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
	    s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
	}
	else if (prec >= 1 && decPos === -1) {
	    s += dec+new Array(prec).join(0)+'0';
	}
	return s;
}
function utf8_decode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
    
    str_data += '';
    
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}

function urlencode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

    str = (str+'').toString();
    
    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                                                    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}