try{Typekit.load();}catch(e){}

function wopen(url, name, w, h) {
    w += 32;
    h += 96;
    var win = window.open(url,
        name, 
        'width=' + w + ', height=' + h + ', ' +
        'location=no, menubar=no, ' +
        'status=no, toolbar=no, scrollbars=no, resizable=no');
    win.resizeTo(w, h);
    win.focus();
}

$.fn.fancySelect = function() {
    var realSelect = $(this),
        parent = realSelect.parent(),
        fs = [],
        options = realSelect.children('option'),
        size = options.size(),
        selected = realSelect.children('option:selected');
    
    if(realSelect.get(0).tagName != 'SELECT') {
        return;
    }
    
    // Generate the fancy select markup
    options.each(function(index) {
        var _option = $(this),
            label = _option.attr('label'), 
            selectedClass = '',
            className = _option.attr('value') || 'empty';
        if(index == 0) {
            if(selected.length > 0) {
                label = selected.attr('label');
            }
            fs.push('<a class="option-selected">'+label+'</a>');
            fs.push('<ul>');
        }
        if(_option.is(':selected')) {
            selectedClass = ' class="selected"';
        } 
        fs.push('<li'+selectedClass+'><a class="'+className+'">'+label+'</a></li>');
        if(index == size-1) {
            fs.push('</ul>');
        }
    });
    // Create the fancy select  and instanciate a jQuery object
    // so we can work with it afterward
    var fancyDiv = $('<div class="fancy-select">');
    parent.append(fancyDiv.html(fs.join('')));
    
    // catching click event to remove the 'active' state on
    // the fancy select list when the user
    // click everywhere but on the fancy select itself
    $(document).click(function(e) {
        if($(e.target).attr('class') != 'option-selected') {
            fancyDiv.children('ul').removeClass('active');
            e.stopPropagation();
        }
    });
    
    // Add the click behaviour on the links
    fancyDiv.find('a').click(function() {
        var link = $(this),
            value = (link.attr('class') === 'empty') ? '': link.attr('class'),
            text = this.innerHTML;
        
        if(link.hasClass('option-selected')) {
            link.next().toggleClass('active');
            return;
        }
        
        fancyDiv.find('a.option-selected').text(text);
        fancyDiv.find('li').removeClass('selected');
        link.parent().addClass('selected');
        realSelect.children('option[value="'+value+'"]').attr('selected','selected');
    });
    
    realSelect.addClass('real-select');
}

var Wjr = function() {
    
    /**
     * A variable usefull to work with...
     * @type    string
     */
    var host = 'http://' + window.location.host;
    
    /**
     * URL of the current page
     * @type    string
     */
    var currentUrl = window.location.href;
    
    
    /** 
     * Initialise the homepage main 
     * image boxes + the homepage appeal
     * 
     * @return  void
     * 
     */
    var initHomepageBoxes = function() 
    {
        $cache.homepageBoxLink = $('a.box-link', '#homepage-links');
        $cache.homepageBoxLink.filter(':first').addClass('selected');
        $cache.homepageBoxLink.filter('.middle').addClass('no-border-bottom');
        $cache.homepageBoxLink.hover(
            function(){
                var _this = $(this);
                $cache.homepageBoxLink.removeClass(
                    'selected no-border-top no-border-bottom'
                );
                _this.addClass('selected');
                $('.homepage-image').hide();
                var id = _this.attr('id').replace("link-", "");
                $('#image-'+id).show();
                if (!_this.is(":last-child") && !$(this).is(":first-child")) {
                    _this.addClass('no-border');
                } else if (_this.is(":last-child")) {
                    _this.prev().addClass('no-border-bottom');
                }else if (_this.is(":first-child")) {
                    _this.next().addClass('no-border-top');
                }
            }, function() { }
        );
        
        $('#home-emergency-appeal .image .image-carousel').cycle();
    };
    
    /** 
     * Initialise the homepage latest
     * news/events/blog box
     * 
     * @return  void
     * 
     */
    var initHomepageLatestBox = function() 
    {
        $cache.latestBox = $('#latest-box');
        
        
        // add useful class to the event widget markup
        if ($cache.latestBox.find('.eventWidgetUpcomingEvents .eventItem').length > 0) {
            $cache.latestBox.find('.eventWidgetUpcomingEvents').addClass('cmsListings home-listing');
            $cache.latestBox.find('.eventWidgetUpcomingEvents').prepend('<h2 class="title"></h2>');
            $cache.latestBox.find('.eventWidgetUpcomingEvents h2.title').text($cache.latestBox.find('.eventWidgetUpcomingEvents span.widgetTitle').text());
            $cache.latestBox.find('.eventWidgetUpcomingEvents .eventItem').addClass('listingItem');
        }
        $cache.latestBox.prepend('<div class="titles"/>');
        $cache.latestBox.find('.cmsListings h2.title').prependTo($('#latest-box .titles'));
        $cache.latestBox.find('.titles').append('<a class="rss" href="/rss/">RSS</a>');
        $cache.latestBox.find('.cmsListings:not(:first)').hide();
        $cache.latestBox.find('.cmsListings:first').show();
        $cache.latestBox.find('h2.title:first').addClass('selected');
        $cache.latestBox.find('h2.title').hover(
            function(){ $(this).addClass('hover'); }, 
            function(){ $(this).removeClass('hover'); }
        );
        $cache.latestBox.find('h2.title').click(function(){
            $cache.latestBox.find('h2.selected').removeClass('selected');
            $(this).addClass('selected');
            index = $cache.latestBox.find('h2.title').index(this);
            $cache.latestBox.find('.cmsListings').hide();
            $cache.latestBox.find('.cmsListings').eq(index).show();
        });
        
        $cache.latestBox.find('.cmsListings .listingItem').each(function(){
            var _this = $(this);
            var url = host + _this.find('.title a').attr('href');
            _this.append('<div class="facebook-like"><fb:like href="'+encodeURI(url)+'" layout="button_count" show_faces="false" width="75" font="arial"></fb:like></div>');
            _this.append('<div class="twitter-tweet"><a href="http://twitter.com/share?url='+encodeURI(url)+'" class="twitter-share-button">Tweet</a></div>');
        });
        
        $cache.latestBox.find('.cmsListings').each(function(index) {
            var link, linkTitle, appendNewsletter;
            var linkTitles = new Array(
                'See all news', 'See all blog posts', 'See all events'
            );
            var links = new Array('/news/', '/news/blog/', '/events/');
            appendNewsletter = false;
            link = links[index];
            linkTitle = linkTitles[index];
            if(index == 0) {
                appendNewsletter = true;
            }
            var _this = $(this);
            _this.append('<a href="'+link+'" class="goto">'+linkTitle+'</a>');
            if(appendNewsletter) {
                _this.append(
                    '<a href="/news/newsletter/" class="goto">View latest newsletter</a>'
                );
            }
            
        });
    };
    
    /** 
     * Initialise the get involved box
     * (with the internal scroll)
     * 
     * @return  void
     * 
     */
    var initHomepageGetInvolvedBox = function() 
    {
        $cache.homeGetInvolved = $('#home-get-involved');
        $cache.homeGetInvolved.prepend('<a class="scroll-up" href="#"></a>');
        $cache.homeGetInvolved.prepend('<a class="scroll-down" href="#"></a>');
        $cache.homeGetInvolved.serialScroll({ target:'.get-involved-item',
            items:'.content-item', prev:'a.scroll-up', next:'a.scroll-down',
            start:0, duration:1200, force:true, axis:'y', stop:true,
            lock:false, cycle:false
        });
    };
    
    /**
     * Initialise the map 
     * (homepage and where we work)
     * 
     * @return  void
     * 
     */
    var initMap = function() 
    {
        var pointIdPrefix = 'point-';
        var pinIdPrefix = 'pin-';
        $cache.mapPoints = $('ul.map-points');
        if ($cache.mapPoints.length > 0) {
            // create and place pins on the map
            $cache.mapPoints.find('li').each(function(index){
                var _this = $(this);
                var xCoordinate = $.trim(_this.find('.x-coordinate').text()) + 'px';
                var yCoordinate = $.trim(_this.find('.y-coordinate').text()) + 'px';
                var newPin = $('<a class="map-pin" />');
                
                newPin.css('left', xCoordinate);
                newPin.css('bottom', yCoordinate);
                
                newPin.attr('id', pinIdPrefix + index);
                _this.attr('id', pointIdPrefix + index);
                $('div.snippet-map-points').append(newPin.wrapInner(_this));
            });
            
            // pin hover effect
            $('a.map-pin').hover(function(){
                $(this).children('li').show();
            }, function(){
                $(this).children('li').hide();
            });
        }
        if ($("#home-map .snippet-tip").length) {
        	if (!$("#home-map .snippet-tip").find('div').length) {
        		$("#home-map .snippet-tip").remove();
        	}
        }
    };
    /** 
     * Initialise the sidebar on homepage
     * 
     * @return  void
     * 
     */
    var initHomepageSidebar = function() 
    {
        // Featured video
        if ($cache.sidebar.find('div.snippet-video div.url').length) {
            var domObject = $cache.sidebar.find('div.snippet-video div.url');
            var url = $.trim(domObject.text());
            domObject.text('').append('<a href="'+url+'" id="media-video"></a>');
            $('a#media-video').media({
                type:'swf', height: 190, width: 280
            });
        }
        $cache.tabbedItems = $('#sidebar ul.tabbed-items');
        // Tabbed items
        if ($cache.tabbedItems.length) {
            $cache.tabbedItems.prepend(
                '<div class="tabs"/>'
            ).append('<div class="content"/>');
            $cache.tabbedItems.find('li .title').appendTo(
                $('#sidebar ul.tabbed-items .tabs')
            );
            $cache.tabbedItems.find('li').appendTo(
                $('#sidebar ul.tabbed-items .content')
            );
            $cache.tabbedItems.find('div.tabs .title:first').addClass(
                'firstElement active'
            );
            $cache.tabbedItems.find('li:first').addClass('firstElement');
            $cache.tabbedItems.find('li.firstElement').show();
            $cache.tabbedItems.find('.tabs .title').hover(
                function(){ $(this).addClass('hover'); }, 
                function(){ $(this).removeClass('hover'); }
            );
            $cache.tabbedItems.find('.tabs .title').click(function() {
                $cache.tabbedItems.find('.tabs .active').removeClass('active');
                $(this).addClass('active');
                $cache.tabbedItems.find('li').hide();
                if ($(this).hasClass('firstElement')) {
                    $cache.tabbedItems.find('li.firstElement').show();
                } else {
                    $cache.tabbedItems.find('li:not(.firstElement)').show();
                }
            });
        }
        
    };
    
    /**
     * Common parts of the website to initialise
     * 
     * @return  void
     * 
     */
    var initCommon = function() 
    {
        /** Header */
        $('#header-search-form').prependTo($('.top-header'));
        $('.snippet-newsletter-sign-up-link .link').attr('href','#').click(
            function(){
                var target = $('.onlineForm', '#ft');
                $('html, body').animate({scrollTop:$("body").attr("scrollHeight")}, 2000);
            }
        );
        $('.top-links', $cache.header).prependTo($('.top-header'));
        if( $cache.headerSearchKeywords.attr('value') == '') {
            $cache.headerSearchKeywords.attr('value', 'Search');
        }
        $cache.headerSearchKeywords.focus(function(){
            if ($cache.headerSearchKeywords.attr('value') == 'Search') {
                $cache.headerSearchKeywords.attr('value', '');
            }
        });
        /** Main menu */
        var pattern = new RegExp("\/", 'g');
        $('div.main-menu li', $cache.header).each(
            function(){ 
                var _this = $(this);
                _this.addClass(
                    _this.children('a').attr('href').replace(pattern, '')
                ); 
            }
        );
        $('div.main-menu ul.level2', $cache.header).append('<span class="bottom" />');
        $('div.main-menu ul.level1 > li > a, .snippet-tip', $cache.header).corner('5px');
        $('div.menu ul.level1 li:first a', '#left-column').corner('5px top');
        $('div.main-menu ul.level1 > li', $cache.header).each(function(){
            var _this = $(this);
            if(!_this.find('ul.level2').length) {
                _this.addClass('no-child');
            }
            _this.hover(
                function(){
                    if($(this).hasClass('no-child')) {
                        return;
                    }
                    $(this).toggleClass('hover');
                }
            );
        });
		
		var onlineForm = $('.onlineForm');
		
		onlineForm.find('input').each(function() {
			$(this).addClass($(this).attr('type'));
		});
		
        /** Footer */
        $('div.onlineForm', '#ft').appendTo($('#footer'));
        $('div.onlineForm', $cache.footer).prepend('<h2>Newsletter Sign-up</h2>');
        $('div.onlineForm input#submit', $cache.footer).attr('value', 'Sign-up');
        $('div.onlineForm input#submit', $cache.footer).hover(
            function() {
                $(this).addClass('hover');
            }, function() {
                $(this).removeClass('hover');
            }
        );
    };
    
    /**
     * Initialise feature pages
     * 
     * @return  void
     */
    var initFeature = function() 
    {
        // process feature images
        if ($('.feature .snippet-primary-image:not(:empty)').length > 0) {
            var href = $('.feature .snippet-primary-image .additional-images .800x600').attr('src');
            $('.feature .snippet-primary-image .image').wrap('<a href="'+href+'" />');
            $('.feature .snippet-primary-image .additional-images .image-additional:not(.800x600)').wrap('<a href="'+href+'"></a>');
            $('.feature .snippet-primary-image').removeClass('snippet-primary-image').addClass('feature-images');
            
            $('.feature .snippet-other-images ul li').each(function(){
                href = $(this).find('.additional-images img.800x600').attr('src');
                $(this).find('.image').wrap('<a href="'+href+'" />');
                $(this).find('a').appendTo('.feature .feature-images');
                var wrap = $(this).find('.additional-images .image-additional:not(.800x600)').wrap('<a href="'+href+'"></a>').parent();
                wrap.appendTo('.feature .feature-images .additional-images');
            });
            $('img.800x600').remove();
            $('.feature .feature-images > a:not(:first)').hide();
            $('.feature .feature-images > a').append('<img src="/images/icons/enlarge.png" alt="Enlarge" class="enlarge-image" />');
            $('.feature .feature-images .additional-images').appendTo($('.feature .feature-images'));
            
            $('.feature .feature-images .additional-images img:last').addClass('last-image');
            $('.feature .feature-images a').fancybox();
            
            $('.feature .feature-images .additional-images a').hover(
                function() {
                    $('.feature .feature-images > a').hide();
                    $('.feature .feature-images > a').eq($(this).index()).show();
                }, function() { }
            );
        }
        // process quotes
        if ($('.feature .quote').length > 0) {
            $('.feature .quote').each(function(){
                $(this).wrap('<div class="quote-container"/>');
            });
            $('.quote-container').prepend('<div class="quote-start" />');
            $('.quote-container').append('<div class="quote-end" />');
        }
        
        // blog posts
        if ($('.blog-post').length > 0) {
            $('.blog-post .snippet-author').prepend('posted by ');
            $('.blog-post .date').prepend('on ');
            $('.blog-post .snippet-date').after('<div class="delimiter" />');
        }
        
        if($('div.appeal-feature').length > 0) {
        }
        
    };
    
    /**
     * Initialise the extended feature
     * 
     * @return  void
     */
    var initExtendedFeature = function() 
    {
        if($('.extended-feature').length > 0) {
            $('.extended-feature .content .feature-images').prependTo($('.extended-feature .content'));
            $('.extended .extended-feature .content').after($('#project-list'));
            
            if(!$('.donate-box .snippet-items ul.items').length) {
                $('.donate-box').addClass('donate-box-empty');
            }
            
            if(!$.trim($('.donate-box').text())) {
                $('.donate-box').remove();
            }
            if(!$.trim($('.extended-feature .grey-box').text())) {
                $('.extended-feature .grey-box').remove();
            }
            if($('#project-list .info').length) {
                var pathname = window.location.pathname;
                pathname += pathname.slice(-1) == '/' ? '': '/' 
                $('#project-list h2.title').prepend($('#project-list .info'));
                $('#project-list .info').wrapInner('<a href=""></a>');
                $('#project-list .info a').attr('href', pathname+'projects/');
            }
            if(!$.trim($('#project-list').text())) {
                $('#project-list').remove();
            }
            if ($('.project-feature').length) {
                // include fb and twitter button if needed
                if ($('.snippet-facebook-twitter-counters .include').length) {
                    $('.snippet-facebook-twitter-counters .include').append('<fb:like href="' + currentUrl + '" layout="box_count" show_faces="false" width="60" font="arial"></fb:like>');
                    $('.snippet-facebook-twitter-counters .include').append('<a href="http://twitter.com/share" class="twitter-share-button" data-count="vertical">Tweet</a>');
                    $('.snippet-facebook-twitter-counters .include').appendTo('.snippet-body .body');
                }
                $('.grey-box').append('<a class="read-more-link">Expand</a>');
                $('.grey-box .read-more-link').click(function(){
                    if(!$(this).hasClass('expanded')) {
                        $(this).text('Collapse');
                    } else {
                        $(this).text('Expand');
                    }
                    $(this).toggleClass('expanded');
                    $('.grey-box .snippet-body').slideToggle();
                });
                
            }
            $('.feature-images', '#body').after($('.grey-box'));
        }
    };
    
    /**
     * Initialise left hand column
     * 
     * @return  void
     */
    var initLeftColumn = function()
    {
        if($('.menu', '#left-column').length > 0) {
            $('.menu ul.level1 li:first', '#left-column').addClass('heading');
            $('.menu .level1 > li:not(.selected, .heading) > a', '#left-column').append('<div class="separator"/>');
        }
        $('#news-box #news-list').cycle();
    };
    
    /**
     * Initialise the sidebar 
     * 
     * @return  void
     */
    var initSidebar = function()
    {
        $('#sidebar .x-marketing').each(function(){
            if($(this).find('.pink').length > 0) {
                $(this).addClass('pink-box');
            }
        });
    };
    
    /**
     * Initialise listings
     * 
     * @return  void
     */
    var initListings = function()
    {
    	/** Standard Listings */
        if($('.standard-listing').length > 0) {
            $('.standard-listing .result').each(function(){
                $(this).find('.order').remove();
            });
        }
    	
        /** Pagination*/
        if ($('.pagination').length > 0) {
            $('.pagination').each(function(){
                if($(this).find('.previous').length <= 0) {
                    $(this).find('span:first').addClass('previous');
                }
                if($(this).find('.next').length <= 0) {
                    $(this).find('span:last').addClass('next');
                }
                $(this).find('.next').text($(this).find('.next').text().replace(' >', ''));
                $(this).find('.previous').text($(this).find('.previous').text().replace('< ', ''));
                $(this).find('span:not(.next, .previous), a:not(.next, .previous)').addClass('page');
                $(this).wrapInner('<div class="pages"/>');
                $(this).find('.disabled').remove();
                if($(this).find('.pages').children().length == 1) {
                    $(this).find('.pages').remove();
                } 
            });
            $('.pagination').eq(1).addClass('bottom-pagination');
            $('.cmsListings .info, .searchResults .info, .listings .info').appendTo('.pagination');
        }
        
        /** Blog Listings */
        if($('.blog-listing').length > 0) {
            $('.blog-listing .listingItem').each(function(){
                $(this).find('.author').wrapInner('<span class="authorName"/>');
                $(this).find('.author').prepend('posted by ');
                $(this).find('.date').prepend('on ');
            });
        }
        
        /** Project listings */
        if($('.project-listing').length > 0) {
            $('.project-listing .result.firstItem').before('<h1 class="title"></h1>');
            var listingTitle = $('.breadcrumbs .lastBreadcrumb').prev().find('a').text() + ' ' + $('.breadcrumbs .lastBreadcrumb').text();
            $('.project-listing h1.title').text(listingTitle);
            $('.project-listing').find('.listingItem, .result').each(function(){
                $(this).find('.title').after('<div class="project-info"></div>');
                $(this).find('.who-benefits, .type-of-project, .where').appendTo(
                    $(this).find('.project-info')
                );
                $cache.whoBenefits = $(this).find('.who-benefits');
                $cache.typeOfProject = $(this).find('.type-of-project');
                $cache.where = $(this).find('.where');
                if($.trim($cache.whoBenefits.text())) {
                    $cache.whoBenefits.wrapInner('<span class="value"></span>')
                    $cache.whoBenefits.prepend('<span class="prefix">Who Benefits:</span>');
                } else {
                    $cache.whoBenefits.addClass('hidden');
                }
                if ($.trim($cache.typeOfProject.text())) {
                    $cache.typeOfProject.wrapInner('<span class="value"></span>')
                    $cache.typeOfProject.prepend('<span class="prefix">Type of Project:</span>');
                } else {
                    $cache.typeOfProject.addClass('hidden');
                }
                if ($.trim($cache.where.text())) {
                    $cache.where.wrapInner('<span class="value"></span>')
                    $cache.where.prepend('<span class="prefix">Where:</span>');
                } else {
                    $cache.where.addClass('hidden');
                }
            });
        }
        
        /** Event listings */
        if($('.eventListings').length > 0) {
            $('.standard-listing .eventItem .date').prepend(
                '<span class="bold">Date: </span>'
            );
            $('.eventListings h1.title').insertAfter(
                $('.eventListings .pagination').eq(0)
            );
        }
    };
    
    /**
     * Initialise comments box
     * 
     * @return  void
     */
    var initComments = function()
    {
        if ($('#commentsDiv').length > 0) {
            /** Customise comments listing */
            if($('#commentsDiv .comment').length > 0) {
                $('#commentsDiv .comment').each(function(){
                    $(this).find('.author').wrapInner('<span class="authorName"/>');
                    $(this).find('.author').prepend('posted by ');
                    $(this).find('.datePosted').prepend('on ');
                });
            }
            
            /** Customise comment form */
            $('#submitCommentForm #webLink-element').remove();
			$('#submitCommentForm #webLink-label').remove();
            $('#submitCommentForm .element-comment').parent().appendTo($('#submitCommentForm table tbody'));
            $('#submitCommentForm .element-postComment').parent().appendTo($('#submitCommentForm table tbody'));
            
            $('#submitCommentForm .label-author').html('Your name:<span class="required">*</span>');
            $('#submitCommentForm .label-email').html('Your email:<span class="required">*</span>');
            $('#submitCommentForm .label-comment').html('Your comment:<span class="required">*</span>');
            
            $('#submitCommentForm #postComment').val('Submit your comment');
			
			
            $('#submitCommentForm #comment-label').appendTo($('#submitCommentForm dl'));
		    $('#submitCommentForm #comment-element').appendTo($('#submitCommentForm dl'));
            $('#submitCommentForm #postComment-element').appendTo($('#submitCommentForm #security-element'));
            $('#submitCommentForm #security-label').appendTo($('#submitCommentForm dl'));
            $('#submitCommentForm #security-element').appendTo($('#submitCommentForm dl'));
			
            $('#submitCommentForm #author-label').html('Your name:<span class="required">*</span>');
			$('#submitCommentForm #email-label').html('Your email:<span class="required">*</span>');
            $('#submitCommentForm #comment-label').html('Your comment:<span class="required">*</span>');
        }
    };
    
    /**
     * Initialise event page
     * 
     * @return void
     */
    var initEvent = function() 
    {
        if ($('.event').length > 0) {
            $('.event h1.title').after('<div class="event-info"/>');
            $('.event div.image').insertAfter($('.event .time'))
            $('.event .date, .event .time').appendTo($('.event-info'));
            $('.event .date').prepend('<span class="bold">Date: </span>');
            $('.event .time').prepend('<span class="bold">Time: </span>');
            $('#buyTickets').prepend('<h2 class="title">Attend this event</h2>');
            $('#eventTickets .submitBuyTickets').hover(function(){ $(this).addClass('submit-hover'); }, function(){ $(this).removeClass('submit-hover'); });
        }
        if($('.eventBooking').length > 0) {
            $('#basketForm input.submitCheckout').hover(function(){ $(this).addClass('submit-hover'); }, function(){ $(this).removeClass('submit-hover'); });
            $('.guestDetailsInfo').parent('tr').addClass('guestDetails');
        }
        if($('.customerInfo').length > 0) {
            $('.customerInfo input.submitCheckout').hover(function(){ $(this).addClass('submit-hover'); }, function(){ $(this).removeClass('submit-hover'); });
        }
        if($('#eventGuestDetails').length) {
            $('#body > h1').addClass('event-title');
        }
    }
    
    /**
     * Initialise the donate process
     * 
     * @return void
     */
    var initDonate = function() 
    {
        // step 1
        if($('div.donate-step-one').length) {
            $('ul#amount-tabs').find('li.amount-tab').corner('top 5px');
            $('ul#amount-desc').find('li').corner('5px');
            $('ul#amount-tabs').find('li.amount-tab:first').addClass('hover');
            $('ul#amount-desc').find('li:first').addClass('hover');
            $('ul#amount-tabs').find('li.amount-tab').hover(
                function() {
                    var id = this.id;
                    id = id.substring(id.lastIndexOf('-'));
                    $('ul#amount-desc').find('li').removeClass('hover');
                    $('ul#amount-tabs').find('li.amount-tab').removeClass('hover');
                    $('ul#amount-desc').find('#amount-desc'+id).toggleClass('hover');
                    $(this).toggleClass('hover');
                    
                }, function() {
                    
                }
            )
            $('.formBox input#regularAmount, .formBox input#oneOffAmount').parent().prepend(
                '<span class="poundSign">&pound;</span>'
            );
            $('#regularDonationForm td.element-regularNextStep').prepend(
                '<div class="snippet-donate-button"><a href="#" class="link">Next Step</a></div>'
            );
            $('#oneOffForm td.element-oneOffNextStep').prepend(
                '<div class="snippet-donate-button"><a href="#" class="link">Next Step</a></div>'
            );
        }
        
        // step 2
        if($('div.donate-step-two').length) {
            $('#donateStepTwo').appendTo($('div.appeal-feature'));
            $('fieldset.donation-amount').find('dt label').text('Donation amount (£):');
            $('#donateStepTwo form input[type="text"]').addClass('text');
            var html = $('fieldset.your-details legend').html();
            $('fieldset.your-details').prepend('<h2 class="title">'+html+'</h2>');
            html = $('fieldset.gift-aid legend').html();
            $('fieldset.gift-aid').prepend('<h2 class="title">'+html+'</h2>');
            $('fieldset.gift-aid h2 .sectionDescription').insertAfter($('fieldset.gift-aid h2'));
            html = $('fieldset.other legend').html();
            $('fieldset.other').prepend('<h2 class="title">'+html+'</h2>');
            html = $('fieldset.your-donation legend').html();
            $('fieldset.your-donation').prepend('<h2 class="title">'+html+'</h2>');
            $('#giftaidcheckbox-element label').html(
                $('#giftaidcheckbox-element label').find('input')
            );
            $('#keepmeinformedaboutwjrsvitalwork-element label').html(
                $('#keepmeinformedaboutwjrsvitalwork-element label').find('input')
            );
            $('#giftaidcheckbox-label').find('label').html(
                $('#giftaidcheckbox-label').find('label > span')
            );
            $('#donateStepTwo form #submit-element').prepend(
                '<div class="snippet-donate-button"><a href="#" class="link">Next Step</a></div>'
            );
            $('select#title').fancySelect();
            $('select#country').fancySelect();
            $('select#howdidyouhearaboutwjr').fancySelect();
            $('form .required', '#donateStepTwo').append('<span class="red">*</span>');
        }
        
        if($('div.thank-you-page').length) {
            if (!$('.snippet-facebook-twitter-buttons .include').length) {
                $('a.facebookShareButton, a.twitterShareButton').remove();
            } else {
                $('a.facebookShareButton, a.twitterShareButton').appendTo($('div.thank-you-page'))
                $('a.facebookShareButton, a.twitterShareButton').click(function(){
                    wopen(this.href, 'Share', 700, 400);
                    return false;
                });
            }
        }
    }
    /**
     * Initialise miscellaneous pages of the site
     * 
     * @return  void
     */
    var initMisc = function()
    {
        // FAQ page
        if($('.faq-item').length) {
            $('.faq-item .snippet-question .text').hover(
                function() {
                    $(this).addClass('hover');
                }, function() {
                    $(this).removeClass('hover');
                }
            );
            $('.faq-item .snippet-question .text').click(
                function() {
                    $(this).parent().next().slideToggle();
                }
            );
        }
        // Contact us page
        if($('#contact-form').length) {
            $('#contact-form #submit').val('Send');
            $('#contact-form #submit').hover(function(){ $(this).addClass('submit-hover'); }, function(){ $(this).removeClass('submit-hover'); });
        }
        
        // Photogallery
        if($('.photo-gallery').length) {
            try {
                $('.gallery-thumb a.fancybox').fancybox();
            }catch(e) {}
        }
        
        // Newsletter sign up page
        if($('#newsletter-form', '#body').length) {
            $('#newsletter-form', '#body').appendTo($('.feature'));
            $('#newsletter-form', '#body').prepend('<h2 class="title">Newsletter sign-up</h2>');
            $('#newsletter-form input[type="text"]', '#body').addClass('text');
            
            $('#newsletter-form #submit-element', '#body').prepend(
                '<div class="snippet-submit-button"><a href="#" class="link">Submit</a></div>'
            );
            $('#newsletter-form #receivehardcopy-element input', '#body').change(function(){
                if($(this).is(':checked')){
                    $('#addressline1-label, #addressline1-element,#addressline2-label,#addressline2-element,#towncity-label,#towncity-element,#country-element,#country-label,#postcode-label,#postcode-element ', '#body #newsletter-form').show();
                } else {
                    $('#addressline1-label, #addressline1-element,#addressline2-label,#addressline2-element,#towncity-label,#towncity-element,#country-element,#country-label,#postcode-label,#postcode-element ', '#body #newsletter-form').hide();
                }
            });
            $('#newsletter-form', '#body').find('.snippet-submit-button a').live('click', function(){
                $('#newsletter-form #submit', '#body').click();
                return false;
            });
            $('#newsletter-form').submit(function(){
                
            });
        }
        // login+extra data forms
        $('#extractForm #submit, #login #_login').hover(function(){ $(this).addClass('submit-hover'); }, function(){ $(this).removeClass('submit-hover'); });
    }
    /**
     * Utility function which transform the submit buttons,
     * playing with the markup
     * 
     * @return void
     */
    var prepareDonateButton = function()
    {
        var snippetButton = $('#body').find('div.snippet-donate-button, div.snippet-submit-button');
        if (snippetButton.find('a.link').length > 0) {
            var href = snippetButton.find('a.link').attr('href');
            snippetButton.prepend('<a class="button-left" href="' + href + '"></a>').append('<a class="button-right" href="' + href + '"></a>');
            snippetButton.find('a').hover(function(){
                $(this).parent().find('a.button-right, a.button-left').toggleClass('b-hover');
                $(this).parent().find('a.link').toggleClass('link-hover');
            }).click(function() {
            	var submitButton = $(this).parent().siblings('input');
            	if(submitButton.length) {
            		submitButton.click();
                	return false;
            	}
            });
        }
    }
    
    return {
        /**
         * Init method
         * 
         * @return  void
         */
        init: function () {
            initCommon();
            initMap();
            // Homepage
            if ($('#custom-doc.home').length > 0) {
                initHomepageBoxes();
                initHomepageLatestBox();
                initHomepageGetInvolvedBox();
                initHomepageSidebar();
            }
            // Left Column
            initLeftColumn();
            // Sidebar
            initSidebar();
            // Feature
            initFeature();
            // Comments
            initComments();
            // Listings
            initListings();
            // Extended feature
            initExtendedFeature();
            // Event
            initEvent();
            // Donate
            initDonate();
            // FAQ and others
            initMisc();
            
            
            prepareDonateButton();
        },
        /**
         * Initialise the twitter status on the footer
         * 
         * @return  bool    true if success, false otherwise
         */
        xhrInitTwitterStatus: function() {
            $.ajax({
                url: '/xhr-get-twitter-status/',
                cache: true,
                method: 'get',
                success: function(data, textStatus){
                    if(data === null || data.success === null) {
                        data = {};
                        data.date = '';
                        data.content = 'Unable to fetch the latest tweet';
                    }
                    
                    $('div.social-media', $cache.footer).append('<div class="twitter-status" />');
                    $('div.twitter-status', $cache.footer).append('<div class="date">'+data.date+'</div>');
                    $('div.twitter-status', $cache.footer).append('<div class="content">'+data.content+'</div>');
                    return true;
                },
                dataType: 'json'
            });
            return false;
        }
    };
}();

$(document).ready(function() {
    // Cache the element we'll use 
    // more than once
    window.$cache = {
        sidebar : $('#sidebar'),
        header : $('#header'),
        headerSearchKeywords : $('#header-search-form #keywords'),
        footer : $('#footer')
    };
    
    Wjr.init(); 
//    Wjr.xhrInitTwitterStatus();
});
