/*
 Nomensa jquery init file
 author: nomensa
 website: http://www.nomensa.com
*/
$(document).ready( function(){
    $('body').jsEnabled();
    
    /* load accessibile tabs */
    $('#findPostsTab div[id^=filter]').acctabs();
    
    /* toggle filters and cookie state */
    $('#findPosts #findPostsHeader').toggleCookie();
    
    /* Photo gallery page thumbnail switcher */
    ThumbnailSwitcher(".photo-gallery");
    
    /* light js validation for comments */
    $('#commentform').validate({
        errorPlacement: function(error, element) { 
            error.appendTo(element.parent().find("label"));
        },
        errorElement: "span"
    });
    
    /* GOOGLE LINK TRACKING */
    try {
        // header and footer links
    	$('#headerWrapOne .nomensaIcon').click(function() {pageTracker._trackEvent('Header','Nomensa.com');});
    	$('#headerWrap .logo a').click(function() {pageTracker._trackEvent('Header','HT home');});
        $('#footerWrapTwo .nomensaLogo').click(function() {pageTracker._trackEvent('Footer','Nomensa.com');});
    	$('#footerWrapTwo .defactoLogo').click(function() {pageTracker._trackEvent('Footer','Defacto-cms.com');});
        $('#footerWrapTwo .humanTechLogo').click(function() {pageTracker._trackEvent('Footer','HT home');});
        
        // article sharing links
        $('#contentBlock .retweet').click(function() {pageTracker._trackEvent('Sharing','Tweet this');});
        $('#contentBlock .buttonFacebook a').click(function() {pageTracker._trackEvent('Sharing','Share on FB');});
        $('#contentBlock .socialBookmarks .emailIcon a').click(function() {pageTracker._trackEvent('Sharing','Email');});
        $('#contentBlock .socialBookmarks .deliciousIcon a').click(function() {pageTracker._trackEvent('Sharing','Delicious');});
        $('#contentBlock .socialBookmarks .diggIcon a').click(function() {pageTracker._trackEvent('Sharing','Digg');});
        $('#contentBlock .socialBookmarks .diigoIcon a').click(function() {pageTracker._trackEvent('Sharing','Diigo');});
        $('#contentBlock .socialBookmarks .facebookIcon a').click(function() {pageTracker._trackEvent('Sharing','Facebook');});
        $('#contentBlock .socialBookmarks .googleIcon a').click(function() {pageTracker._trackEvent('Sharing','Google');});
        $('#contentBlock .socialBookmarks .netvibesIcon a').click(function() {pageTracker._trackEvent('Sharing','Netvibes');});
        $('#contentBlock .socialBookmarks .redditIcon a').click(function() {pageTracker._trackEvent('Sharing','Reddit');});
        $('#contentBlock .socialBookmarks .stumbleuponIcon a').click(function() {pageTracker._trackEvent('Sharing','StumbleUpon');});
        $('#contentBlock .socialBookmarks .technoratiIcon a').click(function() {pageTracker._trackEvent('Sharing','Technorati');});
        $('#contentBlock .socialBookmarks .twitterIcon a').click(function() {pageTracker._trackEvent('Sharing','Twitter');});
    } catch(err) {}
});


/* ADD CLASS OF JS TO THE BODY */
jQuery.fn.jsEnabled = function () {
    $(this).addClass("js");
};


/* CREATES TABS FOR FILTERS */
jQuery.fn.acctabs = function () {
    //Creates the UL list from the any H3 in the filter blocks this list will become the tabs
    var $ul = $('<ul></ul>').prependTo('#filterOne');
    $('#filterOne div').each(function() {$('<li><a href="#' + this.id + '">' + $('h3', this).text() + '</a></li>').appendTo($ul);}); 
    
    var ul = $('<ul></ul>').prependTo('#filterTwo');
    $('#filterTwo div').each(function() {$('<li><a href="#' + this.id + '">' + $('h3', this).text() + '</a></li>').appendTo(ul);}); 
    
    //hides the any h3s as they are nolonger needed
    $(".filters h3").addClass("rm"); 
    
    //tab effect for filters
    $(".filters").tabs();
};


/* LINKIFY POST NAV */
$(function setLinks() {

    // Gather elements
    var targetContainers = $(".linkified-box, .linkified-heading, .linkified-image");

    // Stores linked elements
    var linkedContainers = new Array();

    // Add links loop
    $(targetContainers).each(function(i){
        var targetContainer = $(targetContainers[i]);

        linkedContainers.push(new linkContainer(targetContainer))
    });

    function linkContainer(targetContainer) {

        // Get the first link (although there should only really be one)
        var sourceLink = $(targetContainer.find("a")[0]);

        if (targetContainer.is(".linkified-box")) {
            // adding an onclick to the container element
            var targetElement = targetContainer;

            linkify(targetElement, sourceLink);
        }
        if (targetContainer.is(".linkified-heading")) {
            // adding a "linkified span" to the first and highest heading (prioritising highest over first)
            var heading = $(targetContainer.find("h1, h2, h3, h4, h5")[0]);
            // Add a span with the heading content
            var targetElement = $("<span></span>").html(heading.html());
            // Clear the heading content and replace it with the span
            heading.empty();
            heading.append(targetElement);

            linkify(targetElement, sourceLink);
        }
        if (targetContainer.is(".linkified-image")) {
            // adding an onclick to the first image
            var targetElement = $(targetContainer.find("img")[0]);
            linkify(targetElement, sourceLink);
        }


        // Linkify the element with the source link target
        function linkify(targetElement, sourceLink) {

            // Ensure there are no child links that would be rendered inaccessible (ignoring the source link)
            var noChildren = false;
            var allLinks = targetElement.find("a");
            if (allLinks.length > 0) {
                // There are child links

                if (allLinks.length < 2 || allLinks[0] == sourceLink[0]) {
                    // There is more than one child link, or the one link doesn't equal the source link
                    noChildren = true;
                }
            }

            // OK to proceed
            if (noChildren == true) {

                // Add class for styling
                targetElement.addClass("linkified");

                // Add and remove hover styles when hovering, also set window status to url
                targetElement.mouseover(function(){
                    // Apply to all linked elements
                    targetContainer.addClass("hover");
                    window.status = sourceLink[0];
                });
                targetElement.mouseout(function(){
                    // Apply to all linked elements
                    targetContainer.removeClass("hover");
                    window.status = window.defaultStatus;
                });

                // Map onClick Event to sourceLink Click handler
                targetElement.click(function(){
                    self.location.href = sourceLink[0];
                });
            }
        }


    }
});


/* ADD FILTER TOGGLES AND COOKIE STATE */
jQuery.fn.toggleCookie = function () {
    var a = $('<a class="toggleFilters tabLink" href="#"><span>Hide</span> Filters and search</a>');
    $(this).after(a);
    
    // the div that will be hidden/shown
    var panel = $("#findPosts .findPostsBlock");
    //the button that will toggle the panel
    var button = $("#findPosts .toggleFilters");
    // do you want the panel to start off collapsed or expanded?
    var initialState = "expanded"; // "expanded" OR "collapsed"
    // the class added when the panel is hidden
    var activeClass = "filterClosed";
    // the text of the button when the panel's expanded
    var visibleText = "Hide filters and search";
    // the text of the button when the panel's collapsed
    var hiddenText = "Show filters and search";
    // Detect IE < 8, as earlier versions look weird when show/hide is not fast.
    if(($.browser.msie) && ($.browser.version.substr(0,1)<"8")) {
      var badie = 1;
     }
    //---------------------------
    // don't edit below this line
    //---------------------------
    if($.cookie("panelState") == undefined) {
        $.cookie("panelState", initialState);
    }
    var state = $.cookie("panelState");
    if(state == "collapsed") {
        panel.hide();
        button.text(hiddenText);
        button.addClass(activeClass);
    }

    //Target IE7 and below for toggle else uses slide toggle
    if ($.browser.msie && $.browser.version <= 7 ) {
        $(".toggleFilters").click(function(){
            if ($.cookie("panelState") == "collapsed") {
                $.cookie("panelState", "expanded");
                $("#findPosts .findPostsBlock").show();
                $(this).removeClass("filterClosed");
                $(".toggleFilters span").html("Hide");
                return false;
            } else {
                $.cookie("panelState", "collapsed");
                $("#findPosts .findPostsBlock").hide();
                $(this).addClass("filterClosed");
                $(".toggleFilters span").html("Show");
                return false;
            }
        });
    } else {
        $(".toggleFilters").click(function(){
            if ($.cookie("panelState") == "collapsed") {
                $.cookie("panelState", "expanded");
                $("#findPosts .findPostsBlock").slideDown("slow");
                $(this).removeClass("filterClosed");
                $(".toggleFilters span").html("Hide");
                return false;
            } else {
                $.cookie("panelState", "collapsed");
                $("#findPosts .findPostsBlock").slideUp("slow");
                $(this).addClass("filterClosed");
                $(".toggleFilters span").html("Show");
                return false;
            }
        });
    }
};


/* PHOTO GALLERY THUMBNAIL SWITCHER */
$('.category-photography').each(function(){ 
    
    //wrap the image list in a div for better targetting
    $('.category-photography .postEntry ul li img').parent().parent().wrap('<div class="photo-gallery"></div>');

    //wrap first img in a strong
    $('.category-photography .photo-gallery ul li:first img').each(function() {
        //wrap each img in a link
        $(this).wrap('<strong></strong>');
    });
    
    //wrap each img in a link 
    $('.category-photography .photo-gallery ul li>img').each(function() {
        $(this).wrap('<a href="#"></a>');
    }); 
    
    //get the first image and duplicate it as the large img
    $('.category-photography .photo-gallery ul li:first').append('<span class="overlay"> </span>');
    $('.category-photography .photo-gallery ul li:first img').clone().prependTo('.photo-gallery').addClass('large-image'); 
	
    //add a clearing br incase content follows
    $('.category-photography .photo-gallery').append('<br class="cl" />');
});


/* GALLERY THUMBNAIL SWITCHER */
function ThumbnailSwitcher(b){var c=$(b);var a=new Array();var d=function(j){var m=new Object();var l=$(j);var h=l.find("img").attr("src");m.imageUrl=h.substr(0,h.indexOf(".jpg")+4);m.altText=l.find("img").attr("alt");m.title_attr=l.find("img").attr("title");m.click=function(){};var k;var i;m.enabled="";m.disable=function(){if(m.enabled!=false){var o=k.clone();l.replaceWith(o);l=o;m.enabled=false}};m.enable=function(){if(m.enabled!=true){var o=i.clone();l.replaceWith(o);l=o;l.find("a").click(function(p){m.click(m);return false});m.enabled=true}};if(l.find("a").length==0){i=l.clone();k=l.clone();var g=window.location;var f=$("<a href='"+g+"'></a>");i.append(f);f.append(i.find("img"));i.find("strong").remove();i.find("span").remove();m.disable()}else{i=l.clone();k=l.clone();var n=$("<strong></strong>");k.append(n);n.append(k.find("img"));k.find("a").remove();k.append('<span class="overlay"> </span>');m.enable()}return m};var e=function(g){var j=$(g);var k=j.find("img").eq(0);var f=new Array();var h=j.find("li");function i(m){j.prepend('<span class="loading"> </span>');k.one("load",function(){j.find("span.loading").remove()});k.attr("src",m.imageUrl);k.attr("alt",m.altText);k.attr("title",m.title_attr);for(var l=0;l<f.length;l++){if(f[l]!=m){f[l].enable()}else{f[l].disable()}}}if(h.length>=1){h.each(function(m){var l=new d(h[m]);l.click=i;f.push(l)})}};if(c.length>=1){c.each(function(f){a.push(new e(c[f]))})}};
