
$(function(){
	
	
	var mainMenu        = $("#mainMenu > li");
	var container980    = $(".container980");
	var content         = $("#content");
    var footerBoxes     = $("#footer > .container980 > .sameheight");
    var hallOfFame      = $("#hallOfFame");
    var hallOfFameList  = $("#hallOfFame ul");
	var backToTop       = $("a[href=#top]");
	
	var mostActiveBox      = $("#mostActiveContainer");         // most active container
	var mostActiveMenu     = $("#mostActiveMenu");              // most active menubar
	var mostActiveOC       = $("#mostActiveOC");                // most active open/close button
    var mostActiveComBtn   = $("#mostActiveByComments");        // most active comments button
    var mostActiveTwtBtn   = $("#mostActiveByTweets");          // most active twitter button
    var mostActiveComBox   = $("#mostActiveComments");          // most active comments box
    var mostActiveTwtBox   = $("#mostActiveTweets");            // most active comments box
    var mostActiveH2Com    = $("#mostActiveMenu h2.orangeS");   // most active comments header
    var mostActiveH2Twt    = $("#mostActiveMenu h2.blueS");     // most active comments header
	
	var scrollToCommentsLink = $("#scrollToInput");
	var commentName        = $("#commentName");
    var commentMail        = $("#commentMail");
    var commentWebsite     = $("#commentWebsite");
    var commentText        = $("#comment");

	var theMargin         = 215;    //  margin left+right for fixed-fluid layout
    var mAfadeSpeed       = 300;    // fade speed for most active box
 
	// livesearch (c)@derblub
    derBlub.LiveSearch    = new LiveSearch("Enter your search...");

	// fix for linked images in singlepost
	$(".contentwrapper a").each(function(){
		if ($(this).children("img")){
			$(this).css("border",0);
		}
	});
/*
	if( currentPage == "single" ){
        var contentheight = $("#content").height();
        var offsetSocialMeta = $("#singleSocialMetaShare").offset();
	    var topPadding = 400;
	    $(window).scroll(function() {
	        if ( $(window).scrollTop() > offsetSocialMeta.top -250 ) {
				if ($(window).scrollTop() < ( contentheight - offsetSocialMeta.top -420)){
				    $("#singleSocialMetaShare").stop().animate({ marginTop: $(window).scrollTop() - offsetSocialMeta.top + topPadding });	
				}
	        } else {
	            $("#singleSocialMetaShare").stop().animate({ marginTop: 0 });
	        };
	    });
	}
*/
    // searchfield events for live-search
    var livesearchbox      = $("#searchformwrapper");
    var livesearchresults  = $("#livesearchdata");
	var searchinput        = $("#searchbox");
    var searchtype         = $("#searchtype");
    searchinput.focus(function(){
		searchtype.val("2");
	}).blur(function(){
        searchtype.val("1");
	}).keydown(function(e){
        var code = e.keyCode;
        if (code == 27 || code == 13 || code == 9) { // escape, enter or tab
            searchtype.val("1");
        }else{
            searchtype.val("2");
		}
	});
	//hide live-search when clicked outside
    $(document).click(function(e){ livesearchresults.hide(); });
    livesearchbox.click(function(e){ e.stopPropagation(); });


	// link full head on twitter updates in sidebar
	$("#twitterFeedHead").click(function(){
		window.open("http://twitter.com/1stwebdesigner/");
	});



	// lazy load images
	$("img:not(:.nolazyload)").lazyload({ 
	    threshold : 600,
		placeholder : template_url + "/img/grey.gif",
		effect : "fadeIn"
	});

	// remove last hr from tweets
	$("#twitterFeed hr:last").hide();
	
	//overwrite search-button/Newsletter value
	$("#searchbutton, #subscribeNLbutton").val(" ");
	
	// equal height boxes on footer
    // makeEqualHeight(footerBoxes);


    // animated scroll to top
    backToTop.click(function(){
       $("html, body").animate({scrollTop:0}, "slow");
       return false;
    });
	
    // animated scroll to comments + focus form-field
    scrollToCommentsLink.click(function(){
	   var offsetTop = $("#writeYourComment").offset().top;
       $("html, body").animate({scrollTop:offsetTop}, "slow");
	   if(commentName.val() != ""){
	   	   commentText.focus();
	   }else{
	       commentName.focus();
	   }
       return false;
    });
   
    
    // most active box stuff
		// open/close
	    var oldTitle = mostActiveOC.attr("title");
		mostActiveOC.click(function(){
			if( mostActiveBox.hasClass("opened") ){ closeMostActive(); }
			else{ openMostActive(); };
			return false;
		});
		
		// hide most active tweets (50ms after loading because of scrollbar)
		function hideMostActiveTweetBox(){ mostActiveTwtBox.css("display","none"); }
		setTimeout(hideMostActiveTweetBox,50);
		
		// switch comments/tweets
         mostActiveH2Twt.hide();
		
        mostActiveTwtBtn.click(function(){
			openIfClosed();
            mostActiveTwtBox.stop().fadeTo(mAfadeSpeed, 1);
            mostActiveH2Com.stop().fadeTo(mAfadeSpeed, 0);
            mostActiveH2Twt.stop().fadeTo(mAfadeSpeed, 1);
            mostActiveComBox.stop().fadeTo(mAfadeSpeed, 0, function(){ mostActiveComBox.hide(); });
            mostActiveComBtn.removeClass("current");
            mostActiveTwtBtn.addClass("current");
			mostActiveMenu.addClass("blueS").removeClass("orangeS");
			return false;
			setTimeout(reInitJSP,50);
        });
        mostActiveComBtn.click(function(){
            openIfClosed();
            mostActiveComBox.stop().fadeTo(mAfadeSpeed, 1);
            mostActiveH2Twt.stop().fadeTo(mAfadeSpeed, 0);
            mostActiveH2Com.stop().fadeTo(mAfadeSpeed, 1);
            mostActiveTwtBox.stop().fadeTo(mAfadeSpeed, 0, function(){ mostActiveTwtBox.hide(); });
            mostActiveTwtBtn.removeClass("current");
            mostActiveComBtn.addClass("current");
            mostActiveMenu.addClass("orangeS").removeClass("blueS");
            return false;
			setTimeout(reInitJSP,50);
        });
    
        function openMostActive(){
            mostActiveBox.addClass("opened");
            mostActiveOC.attr("title",oldTitle);
            mostActiveOC.children("span").removeClass("icon_arrowLeft").addClass("icon_arrowDown");
            mostActiveBox.stop().animate({height:"380px"},250);
			
        };
    
        function closeMostActive(){
			mostActiveBox.removeClass("opened");
			mostActiveOC.attr("title","Click to Open");
			mostActiveOC.children("span").removeClass("icon_arrowDown").addClass("icon_arrowLeft");
			mostActiveBox.stop().animate({height:"46px"},250);
        };
		
		function openIfClosed(){
			if( !mostActiveBox.hasClass("opened") ){ openMostActive(); };
			setTimeout(reInitJSP,50);
		};
        if( currentPage == "single" ){closeMostActive();}


    // dropdown menu animation
	mainMenu.children("ul").hide();
	mainMenu.hover(function(){
		$(this).children("ul").fadeIn(150);
	},function(){
        $(this).children("ul").fadeOut(150);
	});
	
	
	// scroll share box
	function scrollShareBox(){
    // .theSinglePostSocialbox
	    if( currentPage == "single" ){
	        
	    }
	}
	
	

    // clear/restore default values of search/newsletter text-input boxes
    $(".clearDefault").each(function(){
        var default_value = this.value;
        $(this).focus(function(){
            if(this.value == default_value){ this.value = "";}
        });
        $(this).blur(function(){
            if(this.value == ""){ this.value = default_value; }
        });
    });
	
 	
	
    // scrollpane parts - most active comments
    var scrollPaneMostActive1       =   $(".scroll-paneMostActive1");
    var scrollContentMostActive1    =   $(".scroll-contentMostActive1");
    // scrollpane parts - most active tweets
    var scrollPaneMostActive2       =   $(".scroll-paneMostActive2");
    var scrollContentMostActive2    =   $(".scroll-contentMostActive2");
    // scrollpane parts - pagination
    var scrollPanePagination       =   $(".scroll-panePagination");
    var scrollContentPagination    =   $(".scroll-contentPagination");
        
    
		
	

    

	// pagination scroll buttons with custom mousehold-event
    $("#toRight").mousehold(function(){
		$("#pagination").data("jsp").scrollBy(20, 0);
    });
    $("#toLeft").mousehold(function(){
        $("#pagination").data("jsp").scrollBy(-20, 0);
    });
    $("#paginationArrows a").click(function(){ return false; });

	
	
	
	
	
    function slidersWidth(){
        var pagination = $("#pagination ul");
        var paginationPages = $("#pagination ul").children().size();
		pagination.css("width", 60*paginationPages +"px");
		
	    var mostActive1width = $("#mostActiveCommentsWrapper").children().size();
	    $("#mostActiveCommentsWrapper").css("width", mostActive1width *216);
	    var mostActive2width = $("#mostActiveTweetsWrapper").children().size();
	    $("#mostActiveTweetsWrapper").css("width", mostActive2width *216);
		
    };
	slidersWidth();
	
	
	

    $(".scroll-pane").jScrollPane({animateDuration:50});
    
	
    // fixed-fluid width
    $(window).bind("resize", fixedFluid);
    function fixedFluid(){
        reInitJSP();
		/*
		if(currentPage != "premiumpage"){
	        var browserWidth = $(window).width();
	        if( browserWidth >= 1200 && browserWidth <= 1365 ){
	          container980.css("width",browserWidth - (theMargin)+70);
	          content.css("width",browserWidth - (theMargin + 20 + 310)+70 ); // -margin, space, sidebar
	          hallOfFame.css("width",browserWidth - (theMargin + 250 + 250 + 25 + 25)+70); // -margin, 2xfooter-sidebar, 2xfootermargin
	          hallOfFameList.css("width",browserWidth-750); // same like above + 2xpadding
	        }else if(browserWidth > 1365){
	          container980.css("width",1365 - theMargin);
	          content.css("width",1365 - (theMargin + 20 + 310)); // -margin, space, sidebar
	          hallOfFame.css("width",1365 - (theMargin + 250 + 250 + 25 + 25)+70); // -margin, 2xfooter-sidebar, 2xfootermargin
	          hallOfFameList.css("width",1365-750); // same like above + 2xpadding
	        };
		}else{
            var browserWidth = $(window).width();
            if( browserWidth >= 1200 && browserWidth <= 1365 ){
              $(".container980)").css("width",browserWidth - (theMargin)+70);
              hallOfFame.css("width",browserWidth - (theMargin + 250 + 250 + 25 + 25)+70); // -margin, 2xfooter-sidebar, 2xfootermargin
              hallOfFameList.css("width",browserWidth-750); // same like above + 2xpadding
            }else if(browserWidth > 1365){
              $(".container980)").css("width",1365 - theMargin);
              hallOfFame.css("width",1365 - (theMargin + 250 + 250 + 25 + 25)+70); // -margin, 2xfooter-sidebar, 2xfootermargin
              hallOfFameList.css("width",1365-750); // same like above + 2xpadding
            };
		}
		*/
    };
	setTimeout(fixedFluid,1000);


    // validate mail
    function isValidEmail(emailAddress) {
        var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
        return pattern.test(emailAddress);
    }
	
	//contact mailer
    $("#contactSubmit").click(function(){
        var contactName     = $("#contactName").val();
        var contactMail     = $("#contactMail").val();
        var contactText     = $("#contactText").val();
        
        if ((contactName == "") || (contactName.length < 3)){
            $("#contactName").css("border","1px solid red").focus();
            return false;
        }
        if ((contactMail == "") || (contactMail.length < 6) || (isValidEmail(contactMail) == false)){
            $("#contactMail").css("border","1px solid red").focus();
            return false;
        }
        if ((contactText == "") || (contactText.length < 10)){
            $("#contactText").css("border","1px solid red").focus();
            return false;
        }
            
        var writeContactString = $("#writeContact").serialize();
        $.ajax({
            beforeSend: function(){
                $("#toLoadingContent").append("<p id='sendentext'>Sending, please wait.</p>");
                $("#writeContact input").attr("disabled","disabled");
            },
            type:"GET",
            url: template_url + "/bin/contactform.php",
            data: writeContactString,
            success: function(){
                $('#theContactForm').html("<div id='success'></div>");  
                $('#success').html("<h3>Thank you " + contactName + "!</h3>")  
                .append("<p>Your message was sent successfully.</p>")
                .hide().fadeIn(1500);
            }
        });
       return false;
    });

	
	
	// comment textarea/allowed-tags focus-fix
	$("#comment").focus(function(){
		$("#allowedTags").addClass("allowedTagsfocused");
		commentTextHasFocus = true;
	}).blur(function(){
		$("#allowedTags").removeClass("allowedTagsfocused");
	});
	
	
	
	
	
	
	setTimeout(hidePaginationArrows,4000);
	
});






function reInitJSP(){
    $(".scroll-pane").jScrollPane({animateDuration:50});
}


function hidePaginationArrows(){
    if($("#pagination .jspHorizontalBar").length == 0){
        $("#paginationArrows").css("display", "none");
    }else{
        $("#paginationArrows").css("display", "block");
    }
}

function makeEqualHeight(columns){
    var tallest = 0;
    columns.each(function(){
        var thisHeight = $(this).height();
        if(thisHeight > tallest){
           tallest = thisHeight;
        }
    });
    columns.height(tallest);
}







// mousehold event
jQuery.fn.mousehold = function (f, options) {
    var defaults = {
        duration  : 150,
        speed     : 0.85,
        min       : 40
    };

    var opts = jQuery.extend(defaults, options);

    if (typeof jQuery.repeatedEvents === 'undefined') {
        jQuery.repeatedEvents = [];
    }

    if (typeof jQuery.repeatedElements === 'undefined') {
        jQuery.repeatedElements = [];
    }

    jQuery.repeatedEvents.push(f);
    jQuery.repeatedElements.push(this);

    var eventNum = jQuery.repeatedEvents.length - 1;

    return this.each(function () {
        repeatedEvent = function (eventNum, duration) {
            jQuery.repeatedElements[eventNum].each(
                jQuery.repeatedEvents[eventNum]
            );

            repeatedEventTimer = setTimeout(
                'repeatedEvent(' + eventNum + ', ' +
                (duration > opts.min ? duration * opts.speed : duration) + ')',
                duration
            );
        };

        jQuery(this).mousedown(function () {
            jQuery.repeatedEventDuration = opts.duration;
            repeatedEvent(eventNum, opts.duration);
        });

        var clearRepeatedEvent = function () {
            if (typeof repeatedEventTimer !== 'undefined') {
                clearInterval(repeatedEventTimer);
            }
        };

        jQuery(this).mouseout(clearRepeatedEvent);
        jQuery(this).mouseup(clearRepeatedEvent);
		
    });
};



