/*
 * General JS-file for vemringde.se, 
 * it relies heavily on jQuery 1.4.2
 * 
 * @author: Carl-Fredrik Herö, carlfredrik.hero@gmail.com
 */


$(document).ready(function() {
	
	$('#front #q').focus();

	$('#front #more-site-info').hide();
	$('#front .more-site-info').click(function(){
		$('#front #more-site-info').slideDown();
		$(this).hide();
	});
	
	$("input#q").autocomplete({
	    source: '/ajax/autocomplete/',
	    minLength: 3,
	    select: function(event, ui) {
			$(this).val(ui.item.value);
			this.form.submit();
		},
		open: function(){
			$('.mobile-ad-wrapper').css({'visibility': 'hidden'});
		},
		close: function(){
			$('.mobile-ad-wrapper').css({'visibility': 'visible'});
		}
	});
	
	$('#organisation').tipsy({title: 'placeholder'});
	$('a.tooltip').tipsy({gravity:'s'});
	$('.rate').tipsy({gravity:'w'});
	
	// share buttons
	
	if (jQuery('#fb_btn').length && jQuery('#tw_btn').length) {
		  var fb_code = "";
		  var tw_code = "";
		  var fl_code = "";
		  
		  var url = "";
		  
		  var rel = jQuery('#tw_btn').attr('rel');
		  
		  if(rel!='undefined'){
			  url = 'http://vemringde.se/?q='+rel;
		  } else {
			  url = window.location.href;
		  }
		  
		  url = encodeURIComponent(url);
		  text = encodeURIComponent(rel+' på vemringde.se');

		  tw_code += '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?url='+url+'&amp;text='+text+'&amp;via=vemringde&amp;count=vertical&amp;related=carlfredrikhero" style="width:55px; height:65px;"></iframe>';

		  fb_code += "<iframe src=\"http://www.facebook.com/plugins/like.php?href=" + url +"&amp;show_faces=false&amp;action=like&amp;layout=box_count\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden;width:100%;height:65px;\" allowTransparency=\"true\" >";

		  jQuery('#fb_btn').html(fb_code);
		  jQuery('#tw_btn').html(tw_code);
		}
	
	// show olämplig-links in hovered comment
	$('.comment').hover(function(){
		$(this).find('.report').removeClass('hidden');
	}, function(){
		$(this).find('.report').addClass('hidden');
	});
	
	// hide some call reports
	$('#calls li:gt(10)').hide();
	
	if($('#calls li:hidden').length){
		$('<div id="morecalls" class="call-more-info small quiet grey center"><a href="#" class="showmorecalls">Visa fler samtal</a> | <a href="#" class="showallcalls">Visa alla samtal</a></div>')
			.insertAfter($('#calls ol.table'));
	
		$('.showmorecalls').click(function(){
			$('#calls li:hidden:lt(10)').show();
			if(!$('#calls li:hidden').length){
				$('#morecalls').remove();
			}
			return false;
		});
		
		$('.showallcalls').click(function(){
			$('#calls li:hidden').show();
			$('#morecalls').remove();
			return false;
		});
	}
	
	$('.answers').each(function(){
		size = $('.answer', this).size();
		if(size > 4){
			size = size - 3;

			$('.answer:lt('+size+')').hide();
		}
	});

	$('.showallanswers').click(function(){
		$(this).parent().siblings(':hidden').show();
		$(this).parent().hide();
	});
	
	$('#organisation').focus(function(){
		$(this).next().css('visibility','visible');
	});
	
	$('#calls li').hover(function (){
		$(this).addClass('hover');
	}, function (){
		$(this).removeClass('hover');
	});
	
	$('.report').click(function(){
		url = $(this).attr('href');
		title = $(this).attr('title');
		$.ajax({
			type: 'GET',
			url: url,
			success: function(response, txtStatus){
				$(response).dialog({
			         title: title,
			         modal: true,
			         draggable: false,
			         resizable: false,
			         closeText: 'stäng',
			         height: 500,
			         width: 800
			   });
			}
		});
		return false;
	});
	
	$('#calls').delegate('a.trashCall','click', function(){
		url = $(this).attr('href');
		$.ajax({
			type: 'GET',
			url: url,
			dataType: 'json',
			success: function(data, txtStatus){
				
				if (data.status=='success'){
					$('#call-'+data.callId).fadeOut('slow', function(){
						$('.message','#calls').remove();
					});
					
				} else {
					$.each(data.errors, function(key,value){
						$('#savecall').prepend('<p class="error">'+ value +'</p>');
					});
				}
			}
		});
		return false;
	});
	
	$('#comments').delegate('a.trashComment','click', function(){
		url = $(this).attr('href');
		$.ajax({
			type: 'GET',
			url: url,
			dataType: 'json',
			success: function(data, txtStatus){
				
				if (data.status=='success'){
					$('#comment-'+data.commentId).fadeOut('slow');
				} else {
					$.each(data.errors, function(key,value){
						$('#savecomment').prepend('<p class="error">'+ value +'</p>');
					});
				}
			}
		});
		return false;
	});
	
	$('#comments').delegate('a.replyComment', 'click',function(){
			clearReplyForms();
			addReplyForm(this);
	});
	
	$('#comments').delegate('a.editComment','click', function(){
		url = $(this).attr('href');
		$.ajax({
			type: 'GET',
			url: url,
			dataType: 'json',
			success: function(data, txtStatus){
				
				if (data.status=='success'){
					// populate form
					$.each(data.output, function(key,value){
						$('#'+key, '#savecomment').val(value);
					});
					// focus in form
					$("#savecomment :input:visible:enabled:first").focus();
				} else {
					$.each(data.errors, function(key,value){
						$('#savecomment').prepend('<p class="error">'+ value +'</p>');
					});
				}
			}
		});
		return false;
	});
	
	$('#comments').delegate('a.rate', 'click', function(){
		url = $(this).attr('href');
		button = this;
		$.ajax({
			type: 'GET',
			url: url,
			dataType: 'json',
			success: function(data, txtStatus){
				
				if (data.status=='success'){
					rateContainer = $('.rating', '#comment-' + data.commentId);
					oldRating = rateContainer.text();
					if(oldRating == ''){
						oldRating = 0;
					}
					oldRating = parseInt(oldRating);

					newRating = oldRating + parseInt(data.value);
					rateContainer.empty().append(newRating);
					if(newRating > 0){
						rateContainer.addClass('positive');
					} else if(newRating < 0){
						rateContainer.addClass('negative');
					}
					
					$(button).addClass('rated');
				} else {
					$.each(data.errors, function(key,value){
						$('#comment-'+data.commentId).before('<li class="comment error">'+ value +'</li>');
					});
				}
				
				
			}
		});
		$(button).siblings().addClass('disabled').attr('title','');
		return false;
	});
	
	$('#savecall form').submit(function(){
		var form = this;
		var action = $(form).attr('action');
		var data = $(form).serialize();
		$.ajax({
			type: "POST",
			url: action,
			data: data,
			dataType: 'json',
			beforeSend: function(){
				$("input.submit", form).val("Sending...").attr("disabled","disabled");
				$("#savecall .error").remove();
			},
			success: function(data, txtStatus){
				if (data.status=='success'){
					if (!$('#calls ol').length){
						location.reload();
					} else{
						$('#calls ol').prepend(data.output);
						$('#calls ol').prev().before('<p class="message">Tack, berätta gärna mer <a href="#savecomment">i en kommentar</a></p>');
					}
					
					$.scrollToElement('#call-'+data.callId, 0, 260)
					.css('backgroundColor','#feffef')
					.animate({
						'backgroundColor': '#fff'
					},5000);
					
					$(form).clearForm();
							
				} else {
					$.each(data.errors, function(key,value){
						$('#savecall').prepend('<p class="error">'+ value +'</p>');
					});
					
					$.each(data.formErrors, function(key,value){
						$.each(value, function(errorKey, errorValue){
							$('#'+key).after('<p class="error">'+ errorValue + '</p>');
						});
					});
				}
				$("input.submit", form).val("   Spara   ").attr("disabled","");
			}
		});
		return false;
	});
	
	// fixed sidebar
	// http://jqueryfordesigners.com/fixed-floating-elements/
	if($('#secondary').length){
		var top = $('#secondary').offset().top;
		var left = Math.ceil($('#secondary').offset().left);
		  $(window).scroll(function (event) {
			// what the y position of the scroll is
			var y = $(this).scrollTop() +92;

			// whether that's below the form
			if (y >= top) {
			  // if so, ad the fixed class
			  $('#secondary').addClass('fixed');
			} else {
			  // otherwise remove it
			  $('#secondary').removeClass('fixed');
			}
		  });
	}
});

function reportForm(form){
	var action = $(form).attr('action');
	var data = $(form).serialize();
	$.ajax({
		type: "POST",
		url: action,
		data: data,
		beforeSend: function(){
			$("input.submit", form).val("Sending...").attr("disabled","disabled");
			
		},
		success: function(data, txtStatus){
			$('#reportForm *').replaceWith(data);
		
			$("input.submit", form).val("   Rapportera   ").attr("disabled","");
		}
	});
	return false;
}

function clearReplyForms(){
	$('.answer .savecomment').each(function(){
		comment = $(this).parents('.comment');
		$(this).remove();
		if(comment.find('.answer').size() == 1){
			comment.find('.answers').remove();
		} else {
			comment.find('.answer:last').append('<a href="javascript:void(0);" class="reply">Svara</a>');
		}
	});
}

function addReplyForm(el){
	comment = $(el).parents('.comment');
	commentId = comment.attr('id');
	commentId = commentId.substring(8);
	

	if(comment.find('.answers li.answer').size() == 0){
		// add answers list
		$('<ol class="answers"><li class="answer"></li></ol>').appendTo(comment);
	}

	formWrapper = comment.find('.answer:last');
	$(formWrapper).empty();
	$('.savecomment')
	.clone()
	.attr('id','')
	.find('input[name="parentId"]').val(commentId)
	.end()
	.appendTo(formWrapper)
	.find(':input:visible:enabled:first').focus().end()
	.find('.submit')
	.after('<a href="javascript:clearReplyForms();" class="grey small" style="margin-left:20px">avbryt</a>');
}

function saveComment(form){
		var action = $(form).attr('action');
		var data = $(form).serialize();
		$.ajax({
			type: "POST",
			url: action,
			data: data,
			dataType: 'json',
			beforeSend: function(){
				$("input.submit", form).val("Sending...").attr("disabled","disabled");
				$('.savecomment .error').remove();
			},
			success: function(data, txtStatus){
				if (data.status=='success'){
					// check to se if commentId exists
					if($('#comment-'+ data.commentId).length){
						// if so, replace content (it's an edit)
						$('#comment-'+data.commentId).replaceWith(data.output);
					} else {
						// if not
						if(data.parentId == undefined){
							// or else, place content at the top.
							if(!$('#comments li').length){
								$('#comments').before('<h1>Kommentarer</h1>');
							}
							$('#comments').prepend(data.output);
						} else {
							// is parentId defined?
							// if so, replace form with content (it's an answer)
							$(form).parents('li.answer').replaceWith(data.output);
						}
					}
					// scroll to comment and flash it if not reply
					if(data.parentId == undefined){
						color = $('#comment-'+data.commentId).css('backgroundColor');
						$.scrollToElement('#comment-'+data.commentId, 0)
							.css('backgroundColor','#feffef')
							.animate({
								'backgroundColor': color
							},3000);
					}
					$(form).clearForm();
							
				} else {
					$.each(data.errors, function(key,value){
						$('#savecomment').prepend('<p class="error">' + value + '</p>');
					});
					
					$.each(data.formErrors, function(key,value){
							$.each(value, function(errorKey, errorValue){
								$('#'+key).after('<span class="error">'+ errorValue + '</span>');
							});
					});
				}
			
				$("input.submit", form).val("   Spara   ").attr("disabled","");
			}
		});
		return false;
}

(function($) {
    $.fn.tipsy = function(options) {

        options = $.extend({}, $.fn.tipsy.defaults, options);
        
        return this.each(function() {
            
            var opts = $.fn.tipsy.elementOptions(this, options);
            
            $(this).hover(function() {

                $.data(this, 'cancel.tipsy', true);

                var tip = $.data(this, 'active.tipsy');
                if (!tip) {
                    tip = $('<div class="tipsy"><div class="tipsy-inner"/></div>');
                    tip.css({position: 'absolute', zIndex: 100000});
                    $.data(this, 'active.tipsy', tip);
                }

                if ($(this).attr('title') || typeof($(this).attr('original-title')) != 'string') {
                    $(this).attr('original-title', $(this).attr('title') || '').removeAttr('title');
                }

                var title;
                if (typeof opts.title == 'string') {
                    title = $(this).attr(opts.title == 'title' ? 'original-title' : opts.title);
                } else if (typeof opts.title == 'function') {
                    title = opts.title.call(this);
                }

                tip.find('.tipsy-inner')[opts.html ? 'html' : 'text'](title || opts.fallback);

                var pos = $.extend({}, $(this).offset(), {width: this.offsetWidth, height: this.offsetHeight});
                tip.get(0).className = 'tipsy'; // reset classname in case of dynamic gravity
                tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
                var actualWidth = tip[0].offsetWidth, actualHeight = tip[0].offsetHeight;
                var gravity = (typeof opts.gravity == 'function') ? opts.gravity.call(this) : opts.gravity;

                switch (gravity.charAt(0)) {
                    case 'n':
                        tip.css({top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('tipsy-north');
                        break;
                    case 's':
                        tip.css({top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('tipsy-south');
                        break;
                    case 'e':
                        tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}).addClass('tipsy-east');
                        break;
                    case 'w':
                        tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}).addClass('tipsy-west');
                        break;
                }

                if (opts.fade) {
                    tip.css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: 0.8});
                } else {
                    tip.css({visibility: 'visible'});
                }

            }, function() {
                $.data(this, 'cancel.tipsy', false);
                var self = this;
                setTimeout(function() {
                    if ($.data(this, 'cancel.tipsy')) return;
                    var tip = $.data(self, 'active.tipsy');
                    if (opts.fade) {
                        tip.stop().fadeOut(function() { $(this).remove(); });
                    } else {
                        tip.remove();
                    }
                }, 100);

            });
            
        });
        
    };
    
    // Overwrite this method to provide options on a per-element basis.
    // For example, you could store the gravity in a 'tipsy-gravity' attribute:
    // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
    // (remember - do not modify 'options' in place!)
    $.fn.tipsy.elementOptions = function(ele, options) {
        return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
    };
    
    $.fn.tipsy.defaults = {
        fade: false,
        fallback: '',
        gravity: 'n',
        html: false,
        title: 'title'
    };
    
    $.fn.tipsy.autoNS = function() {
        return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
    };
    
    $.fn.tipsy.autoWE = function() {
        return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
    };
    
})(jQuery);


/*
 * ScrollToElement 1.0
 * Copyright (c) 2009 Lauri Huovila, Neovica Oy
 *  lauri.huovila@neovica.fi
 *  http://www.neovica.fi
 *  
 * Dual licensed under the MIT and GPL licenses.
 */

(function($) {
    $.scrollToElement = function( element, speed, offset ) {

        speed = speed || 0;
        offset = offset || 190;


        $("html, body").animate({
            scrollTop: $(element).offset().top - offset,
            scrollLeft: $(element).offset().left
        },
        speed,
        'swing');
        return $(element);
    };

    $.fn.scrollTo = function( speed ) {
        speed = speed || "normal";
        return $.scrollToElement( this, speed );
    };
})(jQuery);

$.fn.clearForm = function() {
	  return this.each(function() {
	    var type = this.type, tag = this.tagName.toLowerCase();
	    if (tag == 'form')
	      return $(':input',this).clearForm();
	    if (type == 'text' || type == 'password' || tag == 'textarea' || tag == 'email' || tag == 'date')
	      this.value = '';
	    else if (type == 'checkbox' || type == 'radio')
	      this.checked = false;
	    else if (tag == 'select')
	      this.selectedIndex = -1;
	  });
	};
