/**
 * Whomore - Freestyle Democracy
 * 
 * Global Whomore Javascripts
 * Handles AJAX requests and dynamic content delivery
 */
	
/**
 * Uygulamamızın başladığı an'a hoşgeldiniz!
 * Show başlasın!
 */
$(document).ready(function() {
	// HTML5 Placeholder özelliği simüle ediliyor
    var tst = document.createElement('input');
    if (!('placeholder' in tst)) {
	    $('[placeholder]').focus(function() {
	      var input = $(this);
	      if (input.val() == input.attr('placeholder')) {
		    input.val('');
		    input.removeClass('placeholder');
	      }
	    }).blur(function() {
	      var input = $(this);
	      if (input.val() == '' || input.val() == input.attr('placeholder')) {
		    input.addClass('placeholder');
		    input.val(input.attr('placeholder'));
	      }
	    }).blur();
    }
    
    $('#cm_question').jqEasyCounter({
		maxChars: 90,
		maxCharsWarning: 70,
		msgFontSize: '20px',
		msgFontColor: '#999',
		msgFontFamily: 'Arial',
		msgTextAlign: 'left',
		msgWarningColor: '#f00',
		msgFloat: 'left',
		msgMargin: '0px 0 0 10px',
		msgWidth: '25px',
		msgAppendMethod: 'insertAfter',
		msgLineHeight:'34px'
	});
	
    //@todo Bu şekilde attribute kullanımı oldukça yavaş çalışır. Class eklenip onun üzerinden CSS selection yapılmalı
	$("*[id\^='cm_option\_']").jqEasyCounter({
		maxChars: 40,
		maxCharsWarning: 30,
		msgFontSize: '20px',
		msgFontColor: '#999',
		msgFontFamily: 'Arial',
		msgTextAlign: 'left',
		msgWarningColor: '#f00',
		msgFloat: 'left',
		msgMargin: '7px 0 0 10px',
		msgWidth: '25px',
		msgAppendMethod: 'insertAfter',
		msgLineHeight:'34px'
	});
	
	$('#update_name').jqEasyCounter({
		maxChars: 30,
		maxCharsWarning: 20,
		msgFontSize: '11px',
		msgFontColor: '#ccc',
		msgFontFamily: 'Arial',
		msgTextAlign: 'left',
		msgWarningColor: '#f00',
		msgFloat: 'left',
		msgMargin: '0px 4px',
		msgWidth: '15px',
		msgAppendMethod: 'insertAfter',
		msgLineHeight:'29px'
	});
    
    Search.init();
});



var Voting = function() {
    // Private
    var timeout = null;
    var timer_delay = 300;
    var votes = 0;
    var option_id = null;
    
    var clickHandler = function() {
        // oylar bir artırılıyor (başlangıçta sıfır)
        votes++;
        // tıklanan seçeneğin id si
        option_id = $('> img', this).attr("alt");
        $("#votes" + option_id).css("vote", $("#votes" + option_id).html());
        //tıklama sayısı kullanıcıya gösteriliyor
        $("#click" + option_id).html("+" + votes);
        //verileri gönder
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            $("#click"+ option_id).html("<img src='img/option_click_buton.gif'/>");
            request(option_id + '~' + votes);
            votes = 0;
        }, 300);
    };
    
    var requestHandler = function(msg){
        try {
            var response = $.parseJSON(msg);

            if (response['error']) {
                //@todo Hata kontrolü
                alert(response['error']);
            } else if (response['votes']) {
                // Maksimum oy hesabı
                var max_vote = 0;
                var total_vote = 0;
                for (var key in response['votes']) {
                    total_vote += parseInt(response['votes'][key]);
                    if (parseInt(response['votes'][key]) > max_vote)
                        max_vote = response['votes'][key];
                }
                $('#total_vote').html(total_vote);
                var end_vote_coeff = Math.ceil(Math.log(max_vote) / Math.LN10);
                if (end_vote_coeff < 2)
                    end_vote_coeff = 2;

                var end_vote = Math.pow(10, end_vote_coeff);
                
                for (var key in response['votes']) {
                    $({
                        vote : parseInt($("#votes" + key).data('vote')),
                        self : $("#votes" + key)
                    }).animate({
                        vote : parseInt(response['votes'][key])
                    }, {
                        duration: 'slow',
                        step: function (vote) {
                            this.self.data('vote', Math.round(vote));
                            
                            this.self.html(Math.round(vote));
                        }
                    });
                    var vote_id = parseInt(response['votes'][key]);
                    var bar_width = Math.round(vote_id * 456 / end_vote);
                    $("#bar" + key).animate({width: bar_width}, 'slow');
                    var slider_pos = (end_vote_coeff - 2) * (-50);
                    $({
                        pos: parseInt($("#level" + key).data('pos')),
                        self: $("#level" + key)
                    }).animate({
						pos:  slider_pos
					}, {
						duration: 'slow',
						step: function (level, fx) {
                            this.self.data('pos', Math.round(level));
							this.self.css('backgroundPosition', Math.round(level) + 'px 0');
						}
					});
                }
            }
        } catch (e) {
            console.log(e);
            //@todo Hata kontrolü
            var styleSheets = document.styleSheets;
            for (var i = 0; i < styleSheets.length; i++) {
                styleSheets[i].disabled = true;
            }
            $('body').html(msg);
        }
    };
   
    var request = function(aMessage) {
        $.post('voting', { 'votes': aMessage }, requestHandler);
    };
    
    // Public
    return {
        init: function(oid_for_dummy_request) {
            if (oid_for_dummy_request)
                request(oid_for_dummy_request.toString() + '~0');

            //@todo Bu tarz CSS seçimleri yavaş oluyor.
            $('.option_votes').data('vote', 0);
            $('.option_level').data('pos', 0);
            $("div[id$='option_buton']").mouseup(clickHandler);
        }
    };
}();





/**
 * Yorum sistemi AJAX otları ve b*kları
 * Yorum ekleme, şikayet etme, yükleme vs gibi tüm özellikleri bu nesne sağlıyor
 */
var Comments = function() {
    // Private
    var SortMode = {
        Asc : 0,
        Desc: 1
    };
    
    var sort = SortMode.Desc;
    var loaded = {
        asc : 0,
        desc: 0,
		max: 0
    };
    
    var fetchMoreTimeout;
    
    var fetchResponse = function (resp, add) {
        try {
            response = $.parseJSON(resp);
            if (response.length == 0) {
                $('#fetch-more').hide();
            } else if (response.error) {
                //@todo Javascript hatalarının ortak paydada yönetilmesi ve işlenmesi şart
                //      ayrıca hataların sunucuya bildirilerek kaydedilmesi de çok önemli
                
                //@todo Hata durumunda sunucuya hata bildirimi yapılmalı
                alert(response.error); // ceyhun kaldırdı! neden sürekli bu hata çıkıyor?
            } else {
                // Sonraki yüklemeler için id kayıtları tutuluyor
                var last_id = (sort == SortMode.Asc) ? 0 : Number.MAX_VALUE;
                var newComments = '';
                
                if (response.commentCount)
                    $('#comment_count').html(response.commentCount);
                
                for (var i = 0; i < response.comments.length; i++) {
                    newComments += '<div class="comment" comment_id="' + response.comments[i].id + '"><div class="comment_post">' + response.comments[i].text + '</div><br /><div class="comment_info"><a href="profile/' + response.comments[i].user_id + '">' + response.comments[i].name  + '</a> ' + '<abbr class="timeago">' + jQuery.timeago(response.comments[i].date) +'</abbr>'  + '</div></div>';
                    if ((sort == SortMode.Asc && parseInt(response.comments[i].id) > last_id) || (sort == SortMode.Desc && parseInt(response.comments[i].id) < last_id)) {
                        last_id = response.comments[i].id;
                    }
                    if (response.comments[i].id > loaded.max)
                        loaded.max = response.comments[i].id;
                }
                if (add)
                    $('#comments').prepend(newComments);
                else
                    $('#comments').append(newComments);
                    
                if (add == false) {
                    if (last_id == response.max_id)
                        $('#fetch-more').hide();
                    else
                        $('#fetch-more').show();
                }
                    
                if (sort == SortMode.Asc)
                    loaded.asc = last_id;
                else
                    loaded.desc = last_id;
            }
        } catch ($ex) {
            // Gelen veri JSON formatında olmadığından fırlatılan exception sonucu
            // buradayız. Şu an sunucu hatasını yorum alanına basıyoruz.
            
            //@todo Allahın cezası hataları kontrol altına almalıyız!
            //      mesela "Hata oluştu! Buraya tıklayarak tekrar yüklemeyi deneyin"
            //      gibi bir çıktı üretmeliyiz.
            
            /*
            var styleSheets = document.styleSheets;
            for (var i = 0; i < styleSheets.length; i++) {
                styleSheets[i].disabled = true;
            }*/
            var header = '<h1>Error occured while fetching comments</h1>';
            $('#comments').html(header);
            $('#comments').append('<iframe id="comment_frame" width="100%"><html><body></body></html></iframe>');
            $('#comment_frame').contents().find('body').html(resp);
            $('#comment_frame').height($('#comment_frame').contents().find('body').height() + 300);
        }
    };
    
    /**
     * Elementin görünen alanda olup olmadığını kontrol eder.
     */
    var is_visible = function(elem) {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
    };
    
    // Public
    return {
        fetch: function(_limit) {
            // Eğer yapacağımız yükleme son yükleme olacaksa limit fazla kaçabilir.
            // Bunu engelleyerek aynı yorumların tekrar yüklenmesini engelliyoruz.
            var max_limit = loaded.desc - loaded.asc;
            if (max_limit > 0 && max_limit < _limit)
                _limit = max_limit;
            
            var uri = 'comments/';
            uri += (sort == SortMode.Asc) ? loaded.asc : loaded.desc;
            uri += '/' + sort;
            uri += '/' + _limit;
            $.get(uri
                  , {}
                  , function(response) { fetchResponse(response, false); });
        },
        
        init: function() {
            // Scroll yapıldığında yorumlar yükleniyor
            if ($('#fetch-more').length > 0) {
                $(window).scroll(function() {
                    if ($('#fetch-more').is(':visible') && is_visible($('#fetch-more'))) {
                        clearTimeout(fetchMoreTimeout);
                        timeout = setTimeout(function () {
                            fetch(8);
                        }, 300);
                    }
                });
            }
        },
        
        add: function() {
            if ($('#comment-add').val() == $('#comment-add').attr('placeholder'))
                return false;
                
            $('#comment-add-form > *').attr('disabled', 'disabled');
            var uri = 'comments/';
            uri += loaded.max;
            uri += '/' + sort;
            $.post(uri, {
				'comment': $('#comment-add').val()
            }, function(response) {
                fetchResponse(response, true);
				$('#comment-add').val('').blur();
                $('#comment-add-form > *').removeAttr('disabled');
            });
            return false;
        }
    };
}();

/**
 * Arama ile ilgili herşey!
 * 
 * Otomatik tamamlama özelliğini bu nesne sağlıyor.
 */
var Search = function() {
    // Private
    var timeout;
    var selected;
    
    var fetchResponse = function (response) {
		$('#search_matches').html('');
        if (response.matches.length > 0) {
			for(var i = 0; i < response.matches.length; i++) {
				$('#search_matches').append('<a href="match/' + response.matches[i].id + '-' + response.matches[i].link + '"><li>' + response.matches[i].name + '</li></a>');
			}
			$('#matches').show();
		} else {
			$('#matches').hide();
		}
		$('#search_options').html('');
        if (response.options.length > 0) {
			for(var i = 0; i < response.options.length; i++) {
				$('#search_options').append('<a href="match/' + response.options[i].id + '-' + response.options[i].link + '"><li>' + response.options[i].header + '</li></a>');
			}
			$('#options').show();
		} else {
			$('#options').hide();
		}
		
		if ( (response.matches.length > 0) || (response.options.length > 0) ) {
            $('#search_output li').highlight($('#search_input').val());
            $('#search_output a').mouseover(function (e) {
                $('#search_output a').removeClass('selected');
                $(this).addClass('selected');
            });
			$('#search_output').fadeIn();
		} else {
			$('#search_output').hide();
        }
    };
    
    var doServerSearch = function() {
        var uri = '';
        
        if (!$('#search_input').val())
            return false;
        
        // Internet Explorer 8'in base tagine garezi var
        if ($.browser.msie && parseInt($.browser.version, 10) == 8) {
            uri += $('base').first().attr('href');
        }
        uri += 'search/all/' + $('#search_input').val();
        $(location).attr('href', uri);
    };
    
    // Public
    return {
        search: function() {
            var searchval = $('#search_input').val();
            if (searchval.length == 0)
                return false;
                
            var uri = 'search/all/' + $('#search_input').val();
			$.ajax({
			  url: uri,
			  dataType: 'json',
			  success: function(data) {
				fetchResponse(data);
			  },
			  error: function() {
				$('#search_matches').html('');
				$('#search_options').html('');
				$('#search_output').hide();
			  }
			});
        },
        
        init: function() {
            // Arama için otomatik tamamlama özelliği
            $('#search_input').keyup(function(e){
                if (e.which == 13) {
                    // ENTER tuşuna basılması ile seçilmiş oylamaya veya arama sayfasına
                    // yönlendirilmesi sağlanıyor
                    var selected = $('#search_output a.selected');
                    if (selected.length == 1) {
                        // Autocomplete listesinden seçilmiş bir match veya option var.
                        var uri = '';
                        if ($.browser.msie && parseInt($.browser.version, 10) == 8) {
                            uri += $('base').first().attr('href');
                        }
                        uri += selected.first().attr('href');
                        $(location).attr('href', uri);
                    } else if (selected.length == 0) {
                        // Herhangi bir öneri yok veya seçim yapılmadı
                        doServerSearch();
                    }
                    e.preventDefault();
                } else if (e.which == 38 || e.which == 40) {
                    // Aşağı ve yukarı tuşlarının kontrol edilmesi.
                    // Aşağı ve yukarı tuşları ile match ve option'lar arasında seçim yapılıyor.
                    // Seçim sonrası enter tuşuna basılarak seçili oylamaya gidilebiliyor.
                    if ($('#search_output a').length > 0) {
                        var selected = $('#search_output a.selected');
                        if (selected.length == 1) {
                            if (e.which == 40) {
                                if (selected.first().next().length != 0) {
                                    $('#search_output a').removeClass('selected');
                                    selected.first().next().addClass('selected');
                                } else {
                                    var opts = selected.parent().parent().next().find('a');
                                    if (opts.length > 0) {
                                        $('#search_output a').removeClass('selected');
                                        opts.first().addClass('selected');
                                    }
                                }
                            } else {
                                if (selected.first().prev().length != 0) {
                                    $('#search_output a').removeClass('selected');
                                    selected.first().prev().addClass('selected');
                                } else {
                                    var opts = selected.parent().parent().prev().find('a');
                                    if (opts.length > 0) {
                                        $('#search_output a').removeClass('selected');
                                        opts.last().addClass('selected');
                                    }
                                }
                            }
                        } else {
                            // Bir saçmalık sonucu birden fazla seçim var.
                            // Bu durumda ilk elemanı seçili hale getiriyoruz.
                            $('#search_output a').first().addClass('selected');
                        }
                    }
                    // Yukarıda işlenen özel karakterler için varsayılan davranışlarının engellenmesi sağlanıyor.
                    e.preventDefault();
                } else {
                    // Yazım işlemi. Bu durumda sürekli olarak timeout'u güncelleyerek
                    // Kullanıcının yazmayı bıraktığında öneriler gösteriyoruz
                    clearTimeout(timeout);
                    timeout = setTimeout(function () {
                        Search.search();
                    }, 800);
                }
            });
            
            // Eğer arama textbox'ına tıklanırsa seçimi temizliyoruz. Böylece kişi arama sayfasına erişebiliyor.
            $('#search_input').click(function() {
                $('#search_output a').removeClass('selected');
            });
            
            //@todo Burada timeout dışında bir çözüm bulunmalı. Önerilere tıklandığında
            //      arama textbox'ı focus'unu kaybettiğinden öneriler gizleniyor.
            
            // Arama textbox'ı focus aldığında ve kaybettiğinde önerileri gösteriyoruz veya gizliyoruz.
            var focusTimeout;
            $('#search_input').focus(function(){
                if ($('#search_output ul a').length > 0) {
                    clearTimeout(focusTimeout);
                    focusTimeout = setTimeout(function () {
                        $('#search_output').fadeIn('fast');
                    }, 100);
                }
            });
            $('#search_input').blur(function(){
                clearTimeout(focusTimeout);
                focusTimeout = setTimeout(function () {
                    $('#search_output').fadeOut('fast');
                }, 100);
            });
            // Focus durumunda gizlenmeyi engellemek için focus'u geri veriyoruz.
            // focusTimeout'unu da kaldırıyoruz ki öneriler kapanmasın
            //@todo Bunun daha güzel bir çözümü olmalı
            $('#search_output').click(function() {
                $('#search_input').focus();
                clearTimeout(focusTimeout);
            });
            
            $('img.search_image').click(doServerSearch);
        }
    };
}();

var Facebook = function() {
    var status = {
        NO_INIT: 0,
        LOADED : 1,
        INIT_OK: 2
    };
    var init_status = status.NO_INIT;
    var whomore_init = null;

    var do_login = function() {
        window.location.href = "login/facebook";
    };

    var async_init = function() {
        FB.init({
          appId   : '155864261139817',
          //session : <?php //echo json_encode($session); ?>, // don't refetch the session when PHP already has it
          status  : true, // check login status
          cookie  : true, // enable cookies to allow the server to access the session
          xfbml   : false // parse XFBML
        });

        // whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', do_login);
        
        init_status = status.INIT_OK;
        
        if (whomore_init !== null)
            whomore_init();
    };

    var init = function() {
        if (init_status === status.NO_INIT) {
            var e = document.createElement('script');
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            e.async = true;
            e.onload = async_init;
            if ($.browser.msie) {
                e.onreadystatechange = function() {
                    if (e.readyState == 'loaded' || e.readyState == 'complete') {
                        async_init();
                    }
                }
            }
            document.getElementById('fb-root').appendChild(e);
            init_status = status.LOADED;
        }
    };
    
    return {
        login: function() {
            if (init_status === status.INIT_OK) {
                FB.getLoginStatus(function(response) {
                    if (response.session) {
                        do_login();
                    } else {
                        FB.login(function(r){}, {perms:'email'});
                    }
                });
            } else {
                whomore_init = this.login;
                init();
            }
        }
    };
}();

