$().ready(function() {
    // Remove vote buttons
    $('.vote-form').remove();
    
    // Remove link for voting
    $('.item-mid .item-vote-link-wrap').each(function(){
        var copy_inner = $(this).html();
        $(this).parent().html(copy_inner);
    });
	
	// Bind search
	 $("#search_text").focus(function(srcc)
    {
        if ($(this).val() == "Search for things")
        {
            $(this).addClass("active");
            $(this).val("");
        }
    });
    
    $("#search_text").blur(function()
    {
        if ($(this).val() == "")
        {
            $(this).removeClass("active");
            $(this).val("Search for things");
        }
    });
    
    // Bind nav
	$("div.subnav").prev().prepend("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)

	$("ul.nav li .more").click(function() { //When trigger is clicked...
			$(this).addClass("subhover");
			//Following events are applied to the subnav itself (moving subnav up and down)
			$(this).parent().find("div.subnav").show(); //Drop down the subnav on click

			$(this).parent().hover(function() {
			}, function(){
				$(this).parent().find("div.subnav").hide(); //When the mouse hovers out of the subnav, move it back up
				$(this).parent().find(".more").removeClass("subhover");
			});
			return false;
		//Following events are applied to the trigger (Hover events for the trigger)
		});

    // Hide intro
    $(".intro-close").click(function(){ 
        $("#intro").fadeOut("fast");
        $.cookie('faveone_hide_intro', 'true', { path: '/' });
        return false; 
    });
    
    // Extras for forms 
    $(".form-wrap input").focus(function(){
        $(this).parent().addClass("highlight");
    })
    .blur(function(){
        $(this).parent().removeClass("highlight");
    });
    
    // Bind Single Vs View events
    vsPageBind();
    
    // Bind Create form events
    vsFormBindEvents();
    
    // Bind registration form events
    registrationFormBindEvents();
});

function vsPageBind(){

	$('.go-to-comments').anchorAnimate();
	
		
	$('.vs-meta').hover(function(){
		$('.vs-meta').removeClass('faded');
	});

    $('[class*=vs-wrap]').each(function(){
        
        var vid = $(this).attr("id").replace("vs-","");

        $('#vs-'+vid+' .item').each(function(){
            if($("#vs-"+vid).find('.item-results span').length == 0){
                var iid = this.className.split(' ')[1].substring(9);
                
                $(this).click(function(){
                        VVI(vid, iid);                
                    }
                );
            }
        });    
    });
}

function vsFormBindEvents() {    
    
    $(".create-question-link").click(function(){
        $(this).css("display","none");
        $("#common-field").css("display","none");
        $("#question-field").css("display","");    
        $(".choose-question-link").css("display",""); 
        $("input[name='nq']").val("1");
        return false;
    });
    
    $(".choose-question-link").click(function(){
        $(this).css("display","none");
        $("#question-field").css("display","none");
        $("#common-field").css("display","");    
        $(".create-question-link").css("display","");
        $("input[name='nq']").val("0");        
        return false;
    });
    
    function formatItem(row) {
		return row[0];// + " (<strong>id: " + row[1] + "</strong>)";
	}
	function formatResult(row) {
		return row[0].replace(/(<.+?>)/gi, '');
	}

    $(".item-auto-search").autocomplete("/item/autocomplete_name_search/", {
    		width: 344,
    		selectFirst: false,
            matchContains: true,
            minChars: 2,
            formatItem: formatItem,
            formatResult: formatResult
    	});
        
    $(".item-auto-search").result(function(event, data, formatted) {
        if (data){        
            $("input[name='"+this.id + "_id']").val(data[1]);
			$(this).parent().css('background', "url("+data[2]+") no-repeat center");
        }
    });

	$(".item-auto-search").blur(function(){
		var textBox = this;
        $.ajax({
		   type: "GET",
		   url: "/item/find_item/"+$(this).val(),
		   success: function(data){
				if(data != "fail"){
					// Parse returned data
					var item = $.parseJSON(data);
					// Set the proper text
					$(textBox).val(item.name);
					// Preload the image
					var cacheImage = document.createElement('img');
					cacheImage.src = item.picture_path;
					// Once the image loads, set it in the background
					$(cacheImage).load(function(){
						$(textBox)
							.parent()
							.css('background', "url("+item.picture_path+") no-repeat center")
							.fadeIn();
					});
					
				}else{
					$(textBox).parent().css('background', "");
				}
		   }
		 });
    });  	

	$(".autosize").autoResize({extraSpace:0});
	$(".autosize").maxLength({maxCharacters:199});
}

function registrationFormBindEvents(){
        
	$("#username").keyup(function(){
		$(".username-url").html($("#username").val());
	});
		
    var v = $("#registration-form").validate({
		rules: {
			username: {
				required: true,
				maxlength: 15,
				minlength: 5,
                remote: "/people/check/username"
			},
            email: {
				required: true,
                email: true,
                remote: "/people/check/email"
			},
            password:{
                required: true,
                minlength: 5
            },
            passwordconf:{
                required: true,
                minlength: 5,
                equalTo: "#password"
            }
		},
		messages: {
			username: {
				required: "Call yourself something!",
                remote: jQuery.format("That username is already in use on the site")
			},
            email: {
				required: "We need your email!",
                email: "Email is invalid",
                remote: jQuery.format("That email is already in use on the site")
			},
            password: {
                required: "Please enter a password!",
                minlength: jQuery.format("Enter at least {0} characters")
            },
            passwordconf: {
                required: "Please confirm your password!",
                minlength: jQuery.format("Enter at least {0} characters"),
                equalTo: "Passwords do not match"
            }
		}
	});        
		
    $("#reset").click(function() {
        v.resetForm();
    });
}

function VVI(vid, iid){    
    
    $('#vs-'+vid+' .item').unbind().css('cursor', '');
    $(".item-col-"+iid).addClass('voted');
    $.post("/vs/vote", {"vid": vid, "iid": iid}, 
            function(data) {
                if(data != "fail"){             
                    $('#vs-'+vid).removeClass('no-vote');
                    
                    var jsondata = $.parseJSON(data);
                    for (var i in jsondata[vid]) {
                        if(jsondata[vid][i]['value'] != null && jsondata[vid][i]['value'] != 0)
                            $('#vs-'+vid+' .item-results-'+jsondata[vid][i]['item_id']+' ').html(jsondata[vid][i]['value'] + " votes").slideToggle("fast");
                        else
                            $('#vs-'+vid+' .item-results-'+jsondata[vid][i]['item_id']+' ').html("0 votes").slideToggle("fast");
                    }
					
                }else{
                    $('#vs-'+vid+' .item-vote-link-wrap').fadeIn("fast");
                    $('#vs-'+vid+' .item-col-'+iid+' .item-top').removeClass('voting');
                }			
            }
    ); 
}

function TV(){
        $.ajax({
		   type: "GET",
		   url: "/totalvotes",
		   success: function(data){
				if(data != "fail"){
					// Parse returned data
					var count = $.parseJSON(data);
                    $('.total-votes .number').html(count);
				}else{
				}
		   }
		 });
}


function FC(cid){
	$.post("/comment/flag", {"cid": cid}, 			
            function(data) {
				$("#comment-"+cid+" .comment-flag").fadeOut("fast");				
                if(data != "fail"){					
                    $("#comment-"+cid+" .comment-flag-wrap").html('| (flagged)');
                }else{
				    $("#comment-"+cid+" .comment-flag").fadeIn("fast");
                }                
            }
    ); 
}

function FLTR(obj,type, filter){
	if($(obj).hasClass('inactive')){
		$(obj).removeClass('inactive');
	}else{
		$(obj).addClass('inactive');
	}
}

jQuery.fn.anchorAnimate = function(settings) {

 	settings = jQuery.extend({
		speed : 800
	}, settings);	
	
	return this.each(function(){
		var caller = this
		$(caller).click(function (event) {	
			event.preventDefault()
			var locationHref = window.location.href
			var elementClick = $(caller).attr("href")
			
			var destination = $(elementClick).offset().top;
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
				window.location.hash = elementClick
			});
		  	return false;
		})
	})
}

