// INITIALIZE jQuery extensions
jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} })

function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
        });
}

jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

// focused element
jQuery.extend($.expr[':'], {
    focused: function(elem) { return elem.hasFocus; }
});


jQuery.fn.submitWithAjax = function() {
	
	this.unbind('submit', false);
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })

  return this;
};

//Send data via get if <acronym title="JavaScript">JS</acronym> enabled
jQuery.fn.getWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    $.get($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

// Send data via Post if <acronym title="JavaScript">JS</acronym> enabled
 jQuery.fn.postWithAjax = function() {
   this.unbind('click', false);
   this.click(function() {
     $.post($(this).attr("href"), $(this).serialize(), null, "script");
 		return false;
   })
   return this;
 };


jQuery.fn.putWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    $.put($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

jQuery.fn.deleteWithAjax = function() {
  this.removeAttr('onclick');
  this.unbind('click', false);
  this.click(function() {
		if ( confirm("Are you sure you want to delete?") ){
    $.delete_($(this).attr("href"), $(this).serialize(), null, "script");
		}
    return false;
  })
  return this;
};

jQuery.fn.editComment = function() {
  this.removeAttr('onclick');
  this.unbind('click', false);
  this.click(function() {
		var ID = $(this).attr("id");
		// close main comment form
		$(".commentbox-holder").hide();
		
		$("#comment-edit-place"+ID).html("<form id='edit-comment-form"+ ID +"' method='POST' action='" + $(this).attr("href") + "'><textarea name='comment[body]' rows='10' cols='10' class='comment-edit-box' id='comment-edit-box"+ID +"'>"+trimText($("#comment-body"+ID).html())+"</textarea><br /><input type='submit' name='commit' value='update'/><input type='hidden' name='_method' value='put'></form>");
		
		$("#comment-edit-place"+ID).append("<a onclick=\"javascript:$('#comment-edit-place"+ID+"').hide();$('#comment-body"+ID+"').toggle();\">Cancel</a>");
		
		$("#comment-body"+ID).toggle();
		$("#comment-edit-place"+ID).toggle();		
		$("#edit-comment-form"+ID).submitWithAjax();
		$("#comment-edit-box"+ID).focus();


		return false;
  })
  return this;
};

/* WORDCOUNT MORE LINK ------------------------------------------------------ */
jQuery.fn.wordCount = function(params){
	var p = {
		counterElement:"display_count"
	};
	var total_words;
	
	if(params) {
		jQuery.extend(p, params);
	}
	
	//for each keypress function on text areas
	this.keypress(function()
	{ 
		total_words=this.value.split(/[\s\.\?]+/).length;
		jQuery('#'+p.counterElement).html(total_words);
	});	
};



/* HIGHLIGHT FADE  ---------------------------------------------------- */
jQuery.fn.highlightFade = function(settings) {
	var o = (settings && settings.constructor == String) ? {start: settings} : settings || {};
	var d = jQuery.highlightFade.defaults;
	var i = o['interval'] || d['interval'];
	var a = o['attr'] || d['attr'];
	var ts = {
		'linear': function(s,e,t,c) { return parseInt(s+(c/t)*(e-s)); },
		'sinusoidal': function(s,e,t,c) { return parseInt(s+Math.sin(((c/t)*90)*(Math.PI/180))*(e-s)); },
		'exponential': function(s,e,t,c) { return parseInt(s+(Math.pow(c/t,2))*(e-s)); }
	};
	var t = (o['iterator'] && o['iterator'].constructor == Function) ? o['iterator'] : ts[o['iterator']] || ts[d['iterator']] || ts['linear'];
	if (d['iterator'] && d['iterator'].constructor == Function) t = d['iterator'];
	return this.each(function() {
		if (!this.highlighting) this.highlighting = {};
		var e = (this.highlighting[a]) ? this.highlighting[a].end : jQuery.highlightFade.getBaseValue(this,a) || [255,255,255];
		var c = jQuery.highlightFade.getRGB(o['start'] || o['colour'] || o['color'] || d['start'] || [255,255,128]);
		var s = jQuery.speed(o['speed'] || d['speed']);
		var r = o['final'] || (this.highlighting[a] && this.highlighting[a].orig) ? this.highlighting[a].orig : jQuery.curCSS(this,a);
		if (o['end'] || d['end']) r = jQuery.highlightFade.asRGBString(e = jQuery.highlightFade.getRGB(o['end'] || d['end']));
		if (typeof o['final'] != 'undefined') r = o['final'];
		if (this.highlighting[a] && this.highlighting[a].timer) window.clearInterval(this.highlighting[a].timer);
		this.highlighting[a] = { steps: ((s.duration) / i), interval: i, currentStep: 0, start: c, end: e, orig: r, attr: a };
		jQuery.highlightFade(this,a,o['complete'],t);
	});
};

jQuery.highlightFade = function(e,a,o,t) {
	e.highlighting[a].timer = window.setInterval(function() { 
		var newR = t(e.highlighting[a].start[0],e.highlighting[a].end[0],e.highlighting[a].steps,e.highlighting[a].currentStep);
		var newG = t(e.highlighting[a].start[1],e.highlighting[a].end[1],e.highlighting[a].steps,e.highlighting[a].currentStep);
		var newB = t(e.highlighting[a].start[2],e.highlighting[a].end[2],e.highlighting[a].steps,e.highlighting[a].currentStep);
		jQuery(e).css(a,jQuery.highlightFade.asRGBString([newR,newG,newB]));
		if (e.highlighting[a].currentStep++ >= e.highlighting[a].steps) {
			jQuery(e).css(a,e.highlighting[a].orig || '');
			window.clearInterval(e.highlighting[a].timer);
			e.highlighting[a] = null;
			if (o && o.constructor == Function) o.call(e);
		}
	},e.highlighting[a].interval);
};

jQuery.highlightFade.defaults = {
	start: [255,255,128],
	interval: 50,
	speed: 400,
	attr: 'backgroundColor'
};

jQuery.highlightFade.getRGB = function(c,d) {
	var result;
	if (c && c.constructor == Array && c.length == 3) return c;
	if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))
		return [parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];
	else if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))
		return [parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];
	else if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))
		return [parseInt("0x" + result[1]),parseInt("0x" + result[2]),parseInt("0x" + result[3])];
	else if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))
		return [parseInt("0x"+ result[1] + result[1]),parseInt("0x" + result[2] + result[2]),parseInt("0x" + result[3] + result[3])];
	else
		return jQuery.highlightFade.checkColorName(c) || d || null;
};

jQuery.highlightFade.asRGBString = function(a) {
	return "rgb(" + a.join(",") + ")";
};

jQuery.highlightFade.getBaseValue = function(e,a,b) {
	var s, t;
	b = b || false;
	t = a = a || jQuery.highlightFade.defaults['attr'];
	do {
		s = jQuery(e).css(t || 'backgroundColor');
		if ((s  != '' && s != 'transparent') || (e.tagName.toLowerCase() == "body") || (!b && e.highlighting && e.highlighting[a] && e.highlighting[a].end)) break; 
		t = false;
	} while (e = e.parentNode);
	if (!b && e.highlighting && e.highlighting[a] && e.highlighting[a].end) s = e.highlighting[a].end;
	if (s == undefined || s == '' || s == 'transparent') s = [255,255,255];
	return jQuery.highlightFade.getRGB(s);
};

jQuery.highlightFade.checkColorName = function(c) {
	if (!c) return null;
	switch(c.replace(/^\s*|\s*$/g,'').toLowerCase()) {
		case 'aqua': return [0,255,255];
		case 'black': return [0,0,0];
		case 'blue': return [0,0,255];
		case 'fuchsia': return [255,0,255];
		case 'gray': return [128,128,128];
		case 'green': return [0,128,0];
		case 'lime': return [0,255,0];
		case 'maroon': return [128,0,0];
		case 'navy': return [0,0,128];
		case 'olive': return [128,128,0];
		case 'purple': return [128,0,128];
		case 'red': return [255,0,0];
		case 'silver': return [192,192,192];
		case 'teal': return [0,128,128];
		case 'white': return [255,255,255];
		case 'yellow': return [255,255,0];
	}
};

/* LAST PREPS ---------------------------------------------------- */


/* SPY --------------------------------------------------------------------------- */
// Timestamp for SPY functions, timezone detection included
function myTimestamp() {
 
 	var d = new Date();
	
	localTime = d.getTime();
	localOffset = d.getTimezoneOffset() * 60000;
	utc = localTime + localOffset;
	d = new Date (utc);
	
  // formated as yyyy-mm-dd HH:MM:ss
  return d.getFullYear() + '-' +
    pad(d.getMonth()+1) + '-' + // because month starts at zero
    pad(d.getDate()) + ' ' +
    pad(d.getHours()) + ':' +
    pad(d.getMinutes()) + ':' +
    pad(d.getSeconds());
}

function pad(n) {
  n = n.toString();
  return n.length == 1 ? '0' + n : n;
}

function timeSpy(){
	return entryTime;
}



// COMMENT Spy Runner ---------------------------------------
function runCommentSpy(entity){
	$('#commentSpy').spy({
	    'limit': 10000000000,
	    'fadeLast': 30000000,
	    'ajax': '/entities/comments_live_all/' + entity, 
	    /*'fadeInSpeed': 'slow', */
	    'timeout': 8000,
			'timestamp': myTimestamp,
			'push': pushLiveComments
			});
}

function runPostCommentSpy(post){
	$('#postCommentSpy').spy({
	    'limit': 10000000000,
	    'fadeLast': 30000000,
	    'ajax': '/posts/comments_live/' + post,
	    'timeout': 8000,
			'timestamp': myTimestamp,
			'push': pushLivePostComments
			});
}

function pushLivePostComments(response) {
	$('#' + this.id).prepend(response);
		$("#postCommentSpy").children().each(function(i) {
			postID = $("#"+this.id+" #star_post_id").val();	
			$("#comments-post"+postID).append($("#"+this.id));
			$("#postCommentSpy#"+this.id).remove();
			$("#"+this.id).slideDown("fast");
		});
}


function pushLiveComments(response) {
	$('#' + this.id).prepend(response);
		$("#commentSpy").children().each(function(i) {
			postID = $("#"+this.id+" #star_post_id").val();	
			$("#comments-post"+postID).append($("#"+this.id));
			$("#commentSpy#"+this.id).remove();
			$("#"+this.id).slideDown("fast");
		});
}


// POST Spy Runner ---------------------------------------
function runPostSpy(entity){
	entryTime = myTimestamp();	
	$('#all_posts').spy({
	    'limit': 10000000000,
	    'fadeLast': 30000000,
	    'ajax': '/entities/posts_live/' + entity, 
	    /*'fadeInSpeed': 'slow', */
	    'timeout': 10000,
			'timestamp': myTimestamp,
			'push': pushLivePosts
			});
	return entryTime;
}

function pushLivePosts(response) {
	$('#' + this.id).prepend(response.addClass('hiddenpost'));
	
	new_post_count = $("#all_posts .hiddenpost").size();
		// play sound on first message retrieval
			if(trimText($("#howmany_live").html())==""){
				$.sound.play("/snd/ding.wav");
			}
			
		$("title").prepend("("+ new_post_count +") ");
		$("#howmany_live").html("<a id='spy-open'>" + new_post_count + " new items</a>");
		$("#howmany_live").slideDown("slow");
			
	return new_post_count;
}
/* trim -------------------------------*/
function trimText(text) {
	return text.replace(/^\s+|\s+$/g,"");
}



// GO BABY! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// GO BABY! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// GO BABY! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

$(function() {
		// All non-GET requests will add the authenticity token
	  // if not already present in the data packet
	 $(document).ajaxSend(function(event, request, settings) {
	       if (typeof(window.AUTH_TOKEN) == "undefined") return;
	       // <acronym title="Internet Explorer 6">IE6</acronym> fix for http://dev.jquery.com/ticket/3155
	       if (settings.type == 'GET' || settings.type == 'get') return;
	       settings.data = settings.data || "";
       	 settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(window.AUTH_TOKEN);
	     });

// remote delete

	$('a.remote-delete').live('click', function(event) {
       if ( confirm("Are you sure?") )
           $('<form method="post" action="' + this.href.replace('/delete', '') + '" />')
               .append('<input type="hidden" name="_method" value="delete" />')
               .append('<input type="hidden" name="authenticity_token" value="' + AUTH_TOKEN + '" />')
               .appendTo('body')
							 .submitWithAjax()
               .submit();
       return false;
   });

// $('.comment-body').TruncExpandText({maxLength: '10', text_more: '...more',text_less: '...less'});

/* ALIVE EVENTS -------------------------------------- */	
	
	
	$("form.new_star").live('click', function(event){
		$("form.new_star").submitWithAjax();
	});
	
	$("#new_post").live('click', function(event){
		$("#new_post").submitWithAjax();
	});
	
	$(".comment-form").live('click', function(event){
		$(".comment-form").submitWithAjax();
	});
	
	$("form.new_vote").live('click', function(event){
		$("form.new_vote").submitWithAjax();
	});
	
	
	$("a.comment-edit").live('click', function(event) {
			var ID = $(this).attr("id");
			// close main comment form
			$(".commentbox-holder").hide();
			$("#comment-edit-place"+ID).html("<form id='edit-comment-form"+ ID +"' method='POST' action='" + $(this).attr("href") + "'><textarea name='comment[body]' rows='10' cols='10' class='comment-edit-box' id='comment-edit-box"+ID +"'>"+trimText($("#comment-content"+ID).html())+"</textarea><br /><input type='submit' name='commit' value='update'/><input type='hidden' name='_method' value='put'></form>");		
			$("#comment-edit-place"+ID).append("&nbsp;<a onclick=\"javascript:$('#comment-edit-place"+ID+"').hide();$('#comment-body"+ID+"').toggle();\">Cancel</a><br /><br />");
			$("#comment-body"+ID).toggle();
			$("#comment-edit-place"+ID).toggle();		
			$("#edit-comment-form"+ID).submitWithAjax();
			$("#comment-edit-box"+ID).elastic();
			$("#comment-edit-box"+ID).focus();
		return false;
  });
	
	
/* -------------------------------------- */
			

// SPY OPENER, appends items to #all_posts  ----------------------------------
		 $("#spy-open").live("click", function(){
				new_post_count = 0;

				$("#all_posts").find(".hiddenpost").removeClass("hiddenpost").show("fast");
				$("#all_posts").find(".hiddendivider").removeClass("hiddendivider").show();
				$("#howmany_live").slideUp("slow");
				$("#howmany_live").html(" ");
				$("title").html("KOPUBLIK");
				entryTime = myTimestamp();	
		return false;
		 });
			
// Upon successful ajax action, refresh the links so that new items created will work
			/* not necessary anymore - cnk
			$("body").ajaxSuccess(function(evt, request, settings){
					ajaxLinks();
			});
			*/
			
			

// Toggle Comment Input Box ------------------------------------------------------------
		$('.commentbox-open').live("click",function(){
			var ID = $(this).attr("id");
			$("#commentbox-holder"+ID).toggle(); 
			$("#comment-content"+ID).focus(); 
			
		return false;
		});
	
// Comments view all -----------------------------------------
$('.comments-all').live("click",function(){
	var ID = $(this).attr("id");
	
	$("#comment-sort-progress"+ID).show();
	
	var linktogo = $(this).attr("href");
	$(this).addClass("comment-sorting-selected");
	$(this).next("a").removeClass("comment-sorting-selected");
	$(this).prev("a").removeClass("comment-sorting-selected");	
	
	// $('#comments-post'+ID).hide();
	$.get(linktogo, function(data) {
	  $('#comments-post'+ID).html(data);
		$("#comment-sort-progress"+ID).hide();
	//	$('#comments-post'+ID).slideDown("fast");
	});
	return false;
});

// Comments view popular---------------------------------------
$('.comments-popular').live("click",function(){
	var ID = $(this).attr("id");
		$("#comment-sort-progress"+ID).show();
	var linktogo = $(this).attr("href");
	$(this).addClass("comment-sorting-selected");
	$(this).next("a").removeClass("comment-sorting-selected");
	$(this).prev("a").removeClass("comment-sorting-selected");	
	// $('#comments-post'+ID).hide();
	
	$.get(linktogo, function(data) {
	  $('#comments-post'+ID).html(data);
		$("#comment-sort-progress"+ID).hide();
		// $('#comments-post'+ID).slideDown("fast");
	});
return false;
});

// Comments view new -------------------------------------------
$('.comments-new').live("click",function(){
	$("#comment-sort-progress"+ID).show();
	var ID = $(this).attr("id");
	var linktogo = $(this).attr("href");
	$(this).addClass("comment-sorting-selected");
	$(this).next("a").removeClass("comment-sorting-selected");
	$(this).prev("a").removeClass("comment-sorting-selected");	
	// $('#comments-post'+ID).hide();
	
	
	$.get(linktogo, function(data) {	
	  $('#comments-post'+ID).html(data);
		// $('#comments-post'+ID).slideDown("fast");
		// $("#comment-sort-progress"+ID).hide();
	});
return false;
});

		
// Post Tabs ----------------------------------------------------------------
		$('#comment-tabs').tabs({ 
			remote: true,
			spinner: "<img src='/images/ui/progress-gray.gif' />",
			load: function(event, ui) { 
				// ajaxLinks();
				},
			select: function(event, ui){
					// remove the fake tab
					$("#new_post_tab_fake").remove();
					$("#new_post_tab_real").show();
				}
		});
		
		
		$('#comment-tabs').bind('tabsselect', function(event, ui) {
			// Live tab activates the post Spy, others disable it
			 if(ui.index == 1) {
					$("#livetab").attr('src','/images/ui/control_pause.png');
						if($('#all_posts').data('spyRunning') == 0){ $('#all_posts').trigger('playSpy'); }	
			 	} else {
					$("#livetab").attr('src','/images/ui/control_play.png');
						if($('#all_posts').data('spyRunning') == 1){ $('#all_posts').trigger('pauseSpy'); }
				}
		});
			
// Disable submit button for Post Textarea if content is empty -------------------		
$("textarea#post_title").bind("keyup",function(){
		var metin = $("textarea#post_title").val();
		metin = trimText(metin); 
		
				if(metin == ""){
						// bos
						// alert("bos");
						$("input#post_submit").attr('disabled','disabled');
						}else{
						// dolu
						// alert("dolu");
						$("input#post_submit").removeAttr('disabled');
				}
				
				if(metin.length >= 160){
					$("input#post_submit").attr('disabled','disabled');		
				} else if(metin != "") {
					$("input#post_submit").removeAttr('disabled');					
				}
				
	return false;
});	

// Disable submit button for Comments Textarea if content is empty ----------------
$(".commentbox-holder").live("keyup",function(e){
				var closestid = $(e.target).attr('title');			
				if(trimText($(e.target).val()) == ""){
						// bos
					$("#comment-submit"+closestid).attr('disabled','disabled');					
						}else{
							// dolu
					$("#comment-submit"+closestid).removeAttr('disabled');
				}
	return false;
});

		
		
// Mark the selected post type for the main form ----------------------------
	$(".post_question").click(function(){
		deselectPostType();
		$(this).addClass("new-post-type-selected");
		$("#post_type_selected_id").val(1);
	});

	$(".post_idea").click(function(){
		deselectPostType();
		$(this).addClass("new-post-type-selected");
		$("#post_type_selected_id").val(2);
	});
	
	$(".post_problem").click(function(){
		deselectPostType();
		$("#post_type_selected_id").val(3);
		$(this).addClass("new-post-type-selected");
	});
	$(".post_praise").click(function(){
		deselectPostType();
		$("#post_type_selected_id").val(4);
		$(this).addClass("new-post-type-selected");
	});
	
	function deselectPostType(){
				$(".post_question, .post_idea, .post_problem, .post_praise").removeClass("new-post-type-selected");
	}
	
// Make comment textarea and postbox grow -----------------------------------
	$(".commentbox").elastic();
	$(".postbox").elastic();

// Count characters	

	$("#post_title").charCount({
	    allowed: 160,		
	    warning: 20,
	    counterText: ' '	
	});
	
	
// CTRL ENTER Submit --------------------------------------------------------
// Main post form ctrl enter submit, if it is present
	if(!$("#post_title").length == 0){
		shortcut.add("Ctrl+Enter",function() {
		
				if($("#post_title").val()){
						$("#new_post").submit();
					};
				},{
					'type':'keydown',
					'propagate':false,
					'target':document.getElementById('post_title')
		});
	}

// ending main
return false;
}); // end main function