$(document).ready(function(){

	/* CUFON *********************************************************************************/
	if($('#menu li a').length){
		Cufon.replace('#menu > li > a', {
			hover: true,
			fontFamily: 'Helvetica Neue LT Pro'
		});
	}
	if($('#welcome h1').length){
		Cufon.replace('#welcome h1', {
			hover: false,
			fontFamily: 'Helvetica Neue LT Pro'
		});
	}
	/*if($('#welcome .shadow .shadow .content .twitter .accounts').length){
		Cufon.replace('#welcome .shadow .shadow .content .twitter .accounts', {
			hover: true,
			fontFamily: 'Helvetica Neue LT Pro'
		});
	}*/
	if($('.post .shadow .shadow .content .title a').length){
		Cufon.replace('.post .shadow .shadow .content .title a', {
			hover: true,
			fontFamily: 'Helvetica Neue LT Pro'
		});
	}
	if($('#navigation .pages').length){
		Cufon.replace('#navigation .pages', {
			hover: true,
			fontFamily: 'Helvetica Neue LT Pro'
		});
	}
	if($('#links .shadow .shadow .content .year').length){
		Cufon.replace('#links .shadow .shadow .content .year', {
			hover: true,
			fontFamily: 'Helvetica Neue LT Pro'
		});
	}
	if($('.post .shadow .shadow .content .text .hidden .information').length){
		Cufon.replace('.post .shadow .shadow .content .text .hidden .information', {
			hover: true,
			fontFamily: 'Helvetica Neue LT Pro'
		});
	}

	/* MENU *********************************************************************************/
	$('#menu li ul').css({'visibility':'hidden'});

	var timeout    = 200;
	var closetimer = 0;
	var ddmenuitem = 0;

	function jsddm_open(){
		jsddm_canceltimer();
		jsddm_close();
		ddmenuitem = $(this).find('ul:eq(0)').css('visibility', 'visible');
		$(this).addClass('hover');
	}

	function jsddm_close(){
		if(ddmenuitem){
			ddmenuitem.css('visibility', 'hidden');
		}
		$('#menu > li').removeClass('hover');
	}

	function jsddm_timer(){
		closetimer = window.setTimeout(jsddm_close, timeout);
	}

	function jsddm_canceltimer(){
		if(closetimer){
			window.clearTimeout(closetimer);
			closetimer = null;
		}
	}

	$('#menu > li').bind('mouseover', jsddm_open);
	$('#menu > li').bind('mouseout',  jsddm_timer);

	document.onclick = jsddm_close;

	/* SLIDESHOW *****************************************************************************/
/*
	if(jQuery('#slideshow .image').length){
		jQuery('#slideshow .image').jcarousel({
			scroll:1,
			wrap: 'last',
			initCallback: mycarousel_initCallback,
			buttonNextHTML: '<a href="javascript:;"></a>',
			buttonPrevHTML: '<a href="javascript:;"></a>'
		});
	}
*/

	/* POST A COMMENT ******************************************************************************/
	if($('.post-a-comment a').length){
		$('.post-a-comment a').click(function(){
			var add_comment_node = $(this).parent().parent().parent().parent().find('.add-comment');
			var send_friend_node = $(this).parent().parent().parent().parent().find('.send-friend');
			var comments_node = $(this).parent().parent().parent().parent().find('.jScrollPaneContainer');
			$(this).parent().siblings(".selected").removeClass('selected');
			if(add_comment_node.css('display')=='none'){
				add_comment_node.css({'display':'block'});
				$(this).parent().addClass('selected');
				comments_node.css({'display':'none'});
				send_friend_node.css({'display':'none'});
			}else{
				add_comment_node.css({'display':'none'});
				send_friend_node.css({'display':'none'});
				comments_node.css({'display':'block'});
				$(this).parent().removeClass('selected');
			}
			return false;
		});
	}

	/* SEND TO A FRIEND ****************************************************************************/
	if($('.send-to-friend a').length){
		$('.send-to-friend a').click(function(){
			var add_comment_node = $(this).parent().parent().parent().parent().find('.add-comment');
			var send_friend_node = $(this).parent().parent().parent().parent().find('.send-friend');
			var comments_node = $(this).parent().parent().parent().parent().find('.jScrollPaneContainer');
			$(this).parent().siblings(".selected").removeClass('selected');
			if(send_friend_node.css('display')=='none'){
				send_friend_node.css({'display':'block'});
				$(this).parent().addClass('selected');
				/* comments_node.css({'display':'none'}); */
				add_comment_node.css({'display':'none'});
			}else{
				add_comment_node.css({'display':'block'});
				send_friend_node.css({'display':'none'});
				/* comments_node.css({'display':'block'}); */
				$(this).parent().removeClass('selected');
			}
			return false;
		});
	}
		
	/* TWITTER SELECT *****************************************************************************/
	if($('#account1').length){
		$('#account1').click(function(){
			$(this).addClass('selected');
			$('#account2').removeClass('selected');
			//$('#account2').addClass('notselected');
			//$('.tweet1').css({'display':'block'});
			$('.tweet2').css({'display':'none'});
			$('.tweet1').fadeIn('fast', function() {
				// Animation complete
			});			
			return false;
		});
	}	

	if($('#account2').length){
		$('#account2').click(function(){
			$(this).addClass('selected');
			$('#account1').removeClass('selected');
			//$('#account1').addClass('notselected');
			//$('#account1').css({color:'#a0a0a0'});
			$('.tweet1').css({'display':'none'});
			//$('.tweet2').css({'display':'block'});
			$('.tweet2').fadeIn('fast', function() {
				// Animation complete
			});
			return false;
		});
	}	

	/* SCROLLBAR ******************************************************************************/
	if($('.opened .comments-scroll').length){
		$('.opened .comments-scroll').jScrollPane({showArrows:false});
	}

	/* POSTS OPENER-CLOSER ********************************************************************/
	$('.closed .hidden').css({'display':'none'});
	
	$('.opener-closer a').click(function(){
		var parent_node = $(this).parent().parent().parent().parent().parent();
		var hidden_node = parent_node.find('.hidden');
		var pid = $(this).parents('.post').attr('id');
		
		if(parent_node.hasClass('opened')){
			$(window).scrollTo({ top:parseInt(parent_node.offset().top), left:'0px'}, 200, {axis:'xy'});
			hidden_node.animate({'height':'hide'},300,function(){
				parent_node.removeClass('opened');
				parent_node.addClass('closed');
			});
		}else{
			$('.opened').each(function(){
				$(this).find('.hidden').css({'display':'none'});
				$(this).addClass('closed');
				$(this).removeClass('opened');
			});
			var thiss = $(this);
			hidden_node.animate({'height':'show'},200,function(){
				if (!hidden_node.hasClass('loaded')) {
					$.post(_ajax_load_url + '?pid=' + pid, {
		                	action:'load_post_ajax'
		            	}, function(data){
		            		hidden_node.prepend(data);
			            });
				}
				parent_node.addClass('opened');
				parent_node.removeClass('closed');
				parent_node.addClass('loaded');
				parent_node.find('.comments-scroll').jScrollPane({showArrows:false});
				$(window).scrollTo({ top:parseInt(parent_node.offset().top), left:'0px'}, 300, {axis:'xy'});
			});
		}
		
		return false;
	});
	
	/* IMAGE VOTING **************************************************************************/
	var voteForImage = function() {
		var fn = $(this);
		var link = fn.attr('href');
		var votesHandler = fn.parent().find('.votes em');
		//fn.unbind('click');
		fn.remove();
		$.get(link, {}, function(data){
			if (data != 'error') {
				votesHandler.text(data);
			}
		});
		return false;
	}
	
	/* LABELIFY ******************************************************************************/
	// Custom Select
/*    $.fn.SelectCustomizer = function(){
        // Select Customizer jQuery plug-in
            // based on customselect by Ace Web Design http://www.adelaidewebdesigns.com/2008/08/01/adelaide-web-designs-releases-customselect-with-icons/
            // modified by David Vian http://www.ildavid.com/dblog
        return this.each(function(){
            var obj = $(this);
                    var name = obj.attr('id');
                    var id_slc_options = name+'_options';
                    var id_icn_select = name+'_iconselect';
                    var id_holder = name+'_holder';
                    var custom_select = name+'_customselect';
            obj.after("<div id=\""+id_slc_options+"\"> </div>");
            obj.find('option').each(function(i){
                $("#"+id_slc_options).append("<div id=\"" + $(this).attr("value") + "\" class=\"selectitems\"><span>" + $(this).html() + "</span></div>");
            });
            obj.before("<input type=\"hidden\" value =\"\" name=\"" + this.name + "\" id=\""+custom_select+"\"/><div id=\""+id_icn_select+"\">" + this.title + "</div><div id=\""+id_holder+"\"> </div>").remove();
            $("#"+id_icn_select).click(function(){
                $("#"+id_holder).toggle(700);
            });
            $("#"+id_holder).append($("#"+id_slc_options)[0]);
            $("#"+id_holder+ " .selectitems").mouseover(function(){
                $(this).addClass("hoverclass");
            });
            $("#"+id_holder+" .selectitems").mouseout(function(){
                $(this).removeClass("hoverclass");
            });
            $("#"+id_holder+" .selectitems").click(function(){
                $("#"+id_holder+" .selectedclass").removeClass("selectedclass");
                $(this).addClass("selectedclass");
                var thisselection = $(this).html();
                $("#"+custom_select).val(this.id);
                $("#"+id_icn_select).html(thisselection);
                $("#"+id_holder).toggle('fast');
            });
        });
    }*/
	
	jQuery.fn.labelify = function(settings) {
      settings = jQuery.extend({
        text: "title",
        labelledClass: ""
      }, settings);
      var lookups = {
        title: function(input) {
          return $(input).attr("title");
        },
        label: function(input) {
          return $("label[for=" + input.id +"]").text();
        }
      };
      var lookup;
      var jQuery_labellified_elements = $(this);
      return $(this).each(function() {
        if (typeof settings.text === "string") {
          lookup = lookups[settings.text]; // what if not there?
        } else {
          lookup = settings.text; // what if not a fn?
        };
        // bail if lookup isn't a function or if it returns undefined
        if (typeof lookup !== "function") {return;}
        var lookupval = lookup(this);
        if (!lookupval) {return;}

        // need to strip newlines because the browser strips them
        // if you set textbox.value to a string containing them
        $(this).data("label",lookup(this).replace(/\n/g,''));
        $(this).focus(function() {
          if (this.value === $(this).data("label")) {
            this.value = this.defaultValue;
            $(this).removeClass(settings.labelledClass);
          }
        }).blur(function(){
          if (this.value === this.defaultValue) {
            this.value = $(this).data("label");
            $(this).addClass(settings.labelledClass);
          }
        });

        var removeValuesOnExit = function() {
          jQuery_labellified_elements.each(function(){
            if (this.value === $(this).data("label")) {
              this.value = this.defaultValue;
              $(this).removeClass(settings.labelledClass);
            }
          })
        };

        $(this).parents("form").submit(removeValuesOnExit);
        $(window).unload(removeValuesOnExit);

        if (this.value !== this.defaultValue) {
          // user already started typing; don't overwrite their work!
          return;
        }
        // actually set the value
        this.value = $(this).data("label");
        $(this).addClass(settings.labelledClass);

      });
    };
	
    var validateOptions = {
        rules:{
            author:{
                required:true,
                minlength:2
            },
            email:{
                required:true,
                email:true
            },
            comment:{
                required:true
            }
        },
        ignoreTitle: true,
        onkeyup: false,
        onfocusout: false,
        showErrors:function(errorMap, errorList){
            $.each(errorList, function(key, elm){
                $(elm.element)
                   .animate( {opacity: 0.2}, 175 )
                   .animate( {opacity: 1}, 150 )
                   .animate( {opacity: 0.2}, 150 )
                   .animate( {opacity: 1}, 150 )
                   .animate( {opacity: 0.2}, 150 )
                   .animate( {opacity: 1}, 150 );
            });
        },
        invalidHandler: function(form, validator) {
            $(this).find('input[type=text], textarea').blur();
        },
		submitHandler: function(form) {
			//alert("Thank you for your comment!"); 
			$(form).ajaxSubmit();
			var respond_node = $(form).parent().parent().parent().parent().find('.respond');
			var add_comment_node = $(form).parent().parent().parent().parent().find('.add-comment');
			var comments_node = $(form).parent().parent().parent().parent().find('.jScrollPaneContainer');
			add_comment_node.css({'display':'none'});
			comments_node.css({'display':'block'});
			respond_node.html('<p>Thank you for your comment!</p>');
			window.setTimeout(function(){respond_node.html('')}, 10000);
			//window.setTimeout(respond_node.html(''), 5000);
			//$(form).ajaxSubmit();
		}		
    };
	
	var validateOptions2 = {
        rules:{
            the_author:{
                required:true,
                minlength:2
            },
            auth_email:{
                required:true,
                email:true
            },
            friends_email:{
                required:true,
                email:true
            }
        },
        ignoreTitle: true,
        onkeyup: false,
        onfocusout: false,
        showErrors:function(errorMap, errorList){
            $.each(errorList, function(key, elm){
                $(elm.element)
                   .animate( {opacity: 0.2}, 175 )
                   .animate( {opacity: 1}, 150 )
                   .animate( {opacity: 0.2}, 150 )
                   .animate( {opacity: 1}, 150 )
                   .animate( {opacity: 0.2}, 150 )
                   .animate( {opacity: 1}, 150 );
            });
        },
        invalidHandler: function(form, validator) {
            $(this).find('input[type=text], textarea').blur();
        },
    };			
	
    $('div.post form.send-friend').each(function(key, form){
        $(form).validate(validateOptions2);
    });
	
    $('div.post form.add-comment').each(function(key, form){
        $(form).validate(validateOptions);
    });
		
	$('div.post form').find('input[type=text], textarea').labelify();

	//$('#s').labelify();
	
	$('div.post .vote-image a').click(voteForImage);
	
	$("a.grouped_elements").fancybox();
	
	function initLinks()
    {
        var links = $('#links');
        var arrows = links.find('a.up, a.down');
        var years = links.find('div.years > ul');

        years.filter(':last').show();
		
        arrows.click(function(){

            var fn = $(this);
            var o = years.filter(':visible');
            var n;

            if (fn.hasClass('up')) {
                n = o.next();
            } else if(fn.hasClass('down')) {
                n = o.prev();
				//alert('test: '+n);
            }

            if (n.length) {
                o.hide();
                n.show();
            }

            return false;
        });		
	}
	initLinks();
	
	/* LINKS *********************************************************************************/
    var links = $('#links');
	arrows = links.find('a.down, a.up');
	arrows.css({'visibility':'hidden'});

	var timeout2    = 300;
	var closetimer2 = 0;
	var ddmenuitem2 = 0;

	function jsddm2_open(){
		jsddm2_canceltimer();
		jsddm2_close();
		ddmenuitem2 = $(this).parent().find('a.up, a.down').css('visibility', 'visible');
		$(this).addClass('hover');
	}

	function jsddm2_close(){
		if(ddmenuitem2){
			ddmenuitem2.css('visibility', 'hidden');
		}
		$('#links').removeClass('hover');
	}

	function jsddm2_timer(){
		closetimer2 = window.setTimeout(jsddm2_close, timeout2);
	}

	function jsddm2_canceltimer(){
		if(closetimer2){
			window.clearTimeout(closetimer2);
			closetimer2 = null;
		}
	}

	links.bind('mouseover', jsddm2_open);
	links.bind('mouseout',  jsddm2_timer);

	document.onclick = jsddm2_close;	
});


