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

/**
 * This code is from James Padolsey - http://james.padolsey.com
 * and here: https://gist.github.com/527683
 * 
 * Used to detect IE version properly. 
 * Contains the ie version number (5,6,7, etc) or undefined if not
 * using an ie browser.
 */
var ie = (function(){var undef,v = 3,div = document.createElement('div'),all = div.getElementsByTagName('i');while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',all[0] );return v > 4 ? v : undef;}());

/**
 * Definition of the custom jQuery 
 * plugins used on the website.
 * 
 * @param {Object} $ the jQuery object
 */
(function($) {
    
    /**
     * Plugin used to limit the words in 
     * textareas or input text fields on forms.
     * 
     */
    $.fn.limitWords = function(options) {
        
        var defaults = {
                maxLength: 100
            },
            opts = $.extend(defaults, options),
            lengthToCheck = opts.maxLength;
        
        return this.each(function() {
            
            if (this.tagName.toLowerCase() !== 'textarea'
                && (this.tagName.toLowerCase() !== 'input' 
                    && this.type === 'text')) {
                return; 
            }
            
            $(this).mousedown(function() {
                checkLength(this, lengthToCheck);
            }).keydown(function() {
                checkLength(this, lengthToCheck);
            }).keyup(function() {
                checkLength(this, lengthToCheck);
            });
        });
    };
    
    /**
     * Used on the auto generated forms to add appropriate css 
     * classes to inputs and their container. 
     * Built to work with forms using Zend decorators.
     * 
     */
    $.fn.addFormClasses = function() {
        
        return this.each(function() {
            var tagName = this.tagName.toLowerCase(),
                extraClass;
            
            if (tagName === 'input') {
                extraClass = this.type.toLowerCase();
            } else {
                extraClass = tagName;
            }
            
            if (extraClass === 'hidden') {
                //return;
            }
            
            this.className+= ' ' + extraClass;
            $(this).parent('dd').removeClass().addClass(extraClass)
                .end().parent('label').parent().removeClass().addClass(extraClass);
            
        });
    }
    
    /**
     * Check the length of an input. 
     * Used on the 'limitWords' function
     * 
     */
    function checkLength (input, maxLength) {
        var value = input.value;
        if(value.length >= maxLength) {
            input.value = value.substring(0, maxLength);
        }
        return true;
    }
    
}(jQuery));

/**
 * Global object
 */
Parenting = {};

/** 
 * Modules to initialise. They
 * must have an init method.
 */
Parenting.modules = [
    'Layout', 
    'Header',
    'Homepage', 
    'MembershipTable', 
    'Comments', 
    'Portal',
    'Publications',
    'OnlineForms'
];

/**
 * Not used for now, but who knows...
 */
Parenting.pageConfig = {};

/**
 * Constant definition..
 */
Parenting.IE_STYLESHEET_PATH = '/styles/ie_hacks.css';
Parenting.CORNER_PLUGIN_PATH = '/external/javascript/jquery.corner.min.js';

/**
 * Simple function to append a stylesheet 
 * dynamically to the website.
 * 
 * @param {Object} href URL/path of the stylesheet
 * @return void
 */
Parenting.appendStylesheet = function(href) {
    var link = document.createElement('link');
    link.href = href;
    link.type = 'text/css';
    link.rel = 'stylesheet';
    document.getElementsByTagName('head')[0].appendChild(link);
};

/**
 * Init the website
 */
Parenting.init = function() {
    
    var modules = Parenting.modules,
        moduleCount = modules.length,
        curModule;
        
    // init all the modules
    for (var i=0; i < moduleCount; i++) {
        curModule = Parenting[modules[i]];
        if (!!curModule
            && curModule.init 
            && typeof curModule.init == 'function') {
            curModule.init();
        } else {
            try {
                console.log('Cannot load the '+ modules[i] + ' module');
            } catch(e) {}
        }
    }
    
    // If the user if using an IE browser < 9,
    // we add extra stuffs
    if (ie && ie < 9) {
        // 
        $('html').addClass('ie-' + ie);
        
        // Append the ie hacks stylesheet
        Parenting.appendStylesheet(Parenting.IE_STYLESHEET_PATH);
        
        // also load the jquery.corner plugin
        // for the main menu
        $.getScript(Parenting.CORNER_PLUGIN_PATH, function() {
            $('.main-nav', '#header').find('ul.level1 > li').corner('top 10px');
        });
    }
};

/**
 * Header module
 */
Parenting.Header = (function() {
    var DEFAULT_SEARCH_TEXT = 'Site search';
    
    /**
     * Init the main menu
     */
    var initMenu = function() {
        $('.main-nav', '#header').find('li').each(function() {
            var self = $(this);
            self.hover(
                function() {
                    self.addClass('hovered');
                }, function() {
                    self.removeClass('hovered');
                }
            );
        }).end()
            .find('ul.level2').each(function() { 
                $(this).find('li').last().addClass('last-child')
            });
    };
    
    return {
        
        init: function() {
            
            initMenu();
            
            // set focus event and default value for the site search 
            // keywords input at the top
            $('#header').find('#keywords').focus(
                function() {
                    if (this.value !== DEFAULT_SEARCH_TEXT) {
                        return;
                    }
                    this.value = '';
                }
            ).val(function(index, value) {
                return value.length ? '' : DEFAULT_SEARCH_TEXT;
            })
            .end().find('form').submit(function() {
                var keywords = $(this).find('#keywords')[0];
                if (keywords.value === DEFAULT_SEARCH_TEXT) {
                    keywords.value = '';
                }
            });
            
            // click event to toggle the visibility 
            // of the login form at the top
            var loginFormContainer = $('.loginFormContainer', '#header');
            $('.button-2, .login-form-title', '#header').click(function() {
                loginFormContainer.slideToggle();
                return false;
            });
        }
        
    };
    
}());

/**
 * General layout module
 */
Parenting.Layout = (function() {
    
    /**
     * Prepare buttons markup to be 
     * easily stylable with css
     * 
     * @return void
     */
    var prepareButtons = function() {
        $('#homepage-body-top .right-box .snippet-link,'
          + '#homepage-body-bottom .snippet-link,'
          + '#x-marketing .x-marketing-box .snippet-link,'
          + '#boxes-container .left-box .snippet-link,'
          + '#boxes-container .newsletter-box .snippet-link,'
          + '#x-marketing .x-marketing-events .snippet-read-more-link').prepend('<span class="post-button"></span>');
    };
    
    
    return {
        
        init: function() {
            prepareButtons();
            
            // little hack to have the same style on the the static menus 
            // home folder as on the dynamic ones
            $('.menu', '#sub-nav').find('ul.level1 > li')
                .first().addClass('home').removeClass('selected');
            
            // hack for arrows on listing items to display nicely on ie
            // (@see the parent portal - "parent courses" box items)
            // this is quite ugly though
            $('ul.items').children('li').each(function() {
                var self = $(this);
                self.find('.title > a').append(self.find('span.arrow'));
            });
  
            // This is used on the resource listing page to hide a second
            // search box that is only visibile when reviewing 
            // a selected resource.
            $('.feature-search-form:gt(0)', '#body').addClass('hidden');
            
            // remove the greater/lower than signs
            // on pagination next/prev buttons
            $('.pagination').find('a.next, a.previous').each(function() {
                var self = $(this),
                    newText = self.text().replace(' >', '').replace('< ', '');
                    
                self.text(newText);
            });
            
            // init classes for search forms
            $('.feature-search-form').find('input, textarea, select').addFormClasses();
            
            // fix issue with flash videos showing up above
            // the rest of the elements
            // this won't work in IE so it just to make sure
            // it works at least on modern browsers
            var wmodeParam = document.createElement("param");
            wmodeParam.setAttribute('name', 'wmode');
            wmodeParam.setAttribute('value', 'opaque');
            $('.embedded-video').find('object').each(function() {
                this.appendChild(wmodeParam);
            });
            
            
            // little TEMPORARY hack striping out the
            // a tag from the keywords on the resource pages
            var keywords = []
                keywordsEl = $('.keywords');
            keywordsEl.find('a').each(function() {
                keywords.push(this.innerHTML);
                $(this).remove();
            }).end().html(keywordsEl.find('span')).append(keywords.join(', '));
            
            var pukEventListing = $('.puk-event-listing');
            if (pukEventListing.length) {
                pukEventListing.find('.date').prepend($('<span/>', { html: 'Date: '}))
                    .end().find('.location').prepend($('<span/>', { html: 'Venue: '}));
            }
        }
    };
    
}());

/**
 * Homepage module
 */
Parenting.Homepage = (function() {
    
    return {
        
        init: function() {
            
            var slideshow = new Parenting.Slideshow({
                fx: 'fade',
                target: '.main-box > ul',
                context: '#homepage-body-top',
                next: '',
                prev: ''
            });
            slideshow.run();
        }
    };
}());

/**
 * Default date config for date pickers
 * 
 * @type object
 */
Parenting.dateConfig = {
    dateFormat: 'yy-mm-dd',
    changeYear: true,
    changeMonth: true,
    yearRange: '-100:+20',
    defaultDate: null
};

/**
 * Membership table module
 */
Parenting.MembershipTable = (function() {
    var checkedClassName = 'checked';
    
    return {
        
        init: function(config) {
            var membershipTable = $('.membership-table'),
                radioButtons;
            
            if (!membershipTable.length) {
                return;
            }
            
            var config = config || {};
            
            numSubUsers = config.numSubUsers;
            
            var voucherCodeInput = $('#voucherCode'),
                voucherCodeMessageDiv = $('div.voucher-code-message'),
                firstTd = $('div.membership-table').find('td.first'),
                freeSpans = firstTd.children('span').filter('.free'),
                otherSpans = firstTd.children('span').not('.delimiter, .free'),
                ajaxOpts = {
                    type: 'POST',
                    url: '/xhr_check_voucher_code/',
                    success: function(data) {
                        // update message div to display 
                        // error or success message
                        if (data.content) {
                            voucherCodeMessageDiv.html(data.content);
                            // update membership table 
                            // if voucher code is valid
                            if (data.success) {
                                $('.freeMembershipType').addClass('checked')
                                    .siblings().removeClass('checked')
                                 .end().show()
                                    .find('input[type="radio"]')[0].checked = true;
                                $('#paymentInfo').hide();
                            }
                        }
                    }
                },
                remainingUsers = $('.remainingUsers'),
                numUserToDelete = $('.numUserToDelete');;
                
            $('#vc-confirm').click(function() {
                ajaxOpts.data = 'voucherCode='+voucherCodeInput.val();
                $.ajax(ajaxOpts);
                return false;
            });
            
            var userTable = $('#users-table'),
                deleteSubUsers = $('input#deleteSubUsers');
            
            if (userTable) {
                userTable.hide();
            }
            
            var hidePaymentInfoFor = $.trim($('#hidePaymentInfoFor').text());
            hidePaymentInfoFor = hidePaymentInfoFor.split(/,/g);
            
            $('input[name="membershipTypeId"]').each(function () {
                var self = $(this),
                    membershipId = this.value,
                    trParent = self.parent().parent(),
                    newMaxSubUsers,
                    newUsersToDelete;
                    
                self.click(function() {
                    if ($.inArray(membershipId, hidePaymentInfoFor) !== -1) {
                        $('#paymentInfo').hide();
                    } else {
                        $('#paymentInfo').show();
                    }
                    
                    if (!userTable) {
                        return true;
                    }
                    
                    if (config[membershipId] 
                        && (newMaxSubUsers = config[membershipId].maxSubUsers) !== null
                        && newMaxSubUsers < numSubUsers) {
                        
                        remainingUsers.text(newMaxSubUsers);
                        newUsersToDelete = newMaxSubUsers - numSubUsers;
                        
                        if (newUsersToDelete < 0) {
                            numUserToDelete.text('all your');
                        } else {
                            numUserToDelete.text(newMaxSubUsers - numSubUsers);
                        }
                        
                        userTable.fadeIn();
                        deleteSubUsers.val(1);
                    } else {
                        userTable.fadeOut();
                        deleteSubUsers.val(0);
                    }
                }).change(function() {
                    trParent.toggleClass('checked', this.checked);
                    if (this.checked) {
                        trParent.siblings().removeClass(checkedClassName);
                    }
                });
            });
            
            $('#vc-clear').click(function() {
                $('.freeMembershipType').hide().find('input[type="radio"]')[0].checked = false;
                $('#paymentInfo').show();
                return false;
            });
            
            var billingInfoFields = $('.billing-info input, .billing-info select'),
                matchingFields = {
                    'billingAddress1': 'address1',
                    'billingAddress2': 'address2',
                    'billingAddress3': 'address3',
                    'billingTown': 'town',
                    'billingPostcode': 'postcode',
                    'billingCountryId': 'countryId'
                };
                
            $('#useProfileAddress').click(function() {
                if (this.checked) {
                    billingInfoFields.each(function() {
                        var name = this.name;
                        
                        if (!(name in matchingFields)) {
                            return true;
                        }
                        
                        if (typeof this.selectedIndex !== 'undefined') {
                            this.selectedIndex = $('#' + matchingFields[name]).val();
                        } else {
                            this.value = $('#' + matchingFields[name]).val();
                        }
                    });
                } else {
                    billingInfoFields.each(function() {
                        if (!(this.name in matchingFields)) {
                            return true;
                        }
                        
                        this.value = '';
                        if (this.selectedIndex) {
                            this.selectedIndex = 0;
                        }
                    });
                }
            });
            
            $('span.remove').click(function() {
                $(this).parent().parent().remove();
                numSubUsers--;
            });
        }
    };
}());


/**
 * Comments module
 */
Parenting.Comments = (function() {
    var disclaimer = 'Your email address will not be published on the site '
                   + 'and will only be used if we need to contact you '
                   + 'about your comment.';
    return {
        
        init: function() {
            var commentsDiv = $('#commentsDiv');
            
            if(!commentsDiv.length) {
                return; 
            }
            
            commentsDiv
                .find('dt > label').append('<span class="req">*</span>')
            .end().end()
                .find('div.comment > span.author')
                    .prepend('Comment from ').append(' on ');
                
            $('#submitCommentForm').append(
                '<div class="disclaimer">' + disclaimer + '</div>'
            );
        }
    };
}());

/**
 * Portal module
 */
Parenting.Portal = (function() {
    
    /**
     * Just some jquery bits to display/hide answers and clicking
     * on the questions
     * 
     * @return void
     */
    var initFaq = function() {
        $('.question').each(function (){
            var question = $(this),
                answer = question.next().hide();
            
            question.click(function() {
                answer.slideToggle();
                question.toggleClass('active');
            });
        });
    };
    
    return {
        
        init: function() {
            
            initFaq();
            
            if (!$('#custom-doc').hasClass('portal')) {
                return;
            }
            
            var slideshow = new Parenting.Slideshow({
                target: '.portal-slideshow > ul',
                context: '.slideshow-container'
            }).run();
            
            var bookSlideshowItems = $('.portal').find('.middle-col').find('li');
            
            // append link to the text to satisfy design
            if (bookSlideshowItems.length) {
            
                $('.portal').find('.middle-col').find('li').each(function () {
                    var self = $(this);
                    self.find('.text').append($(this).find('.link'))
                })
                // add prev/next links to the middle col
                .end().find('.snippet-items').append(
                    '<span class="slideshow-prev">Prev</span>',
                    '<span class="slideshow-next">Next</span>'
                );
                    
                var bookSlideshow = new Parenting.Slideshow({
                    target: 'ul',
                    context: '.portal .middle-col'
                }).run();
            }
            
        }
    };
}());


/**
 * Online Forms module
 */
Parenting.OnlineForms = (function(){
    
    return {
        
        init: function() {
            $('div.onlineForm').find('input, textarea, select').addFormClasses();
        }
    }
}());


/**
 * Publications module
 */
Parenting.Publications = (function(){
    var pubDownloadLink = '/our-work/our-publications/download/?u='
        toStripOut = 'http://pelorous.totallyplc.com/public/cms';
    return {
        
        init: function() {
            var publicationListing = $('div.publication-listing', '#body');
            
            if (!publicationListing.length) {
                return;
            }
            publicationListing.find('div.pub-download > a').each(function() {
                var href = this.href;
                href = pubDownloadLink + href.replace(toStripOut, '');
                this.href = href;
            });
        }
    }
}());
/**
 * FormManager class
 * 
 * Add a set of form elements dynamically to the dom
 * by cloning an existing group of elements.
 * 
 * This function is used on the registration page and the dashboard.
 * 
 * @param {Object} button
 * @return void
 */
Parenting.FormManager = function(config) {
    
    var multiFormElements = config.multiFormElements || {};
    
    return {
        
        addFormElements: function(button) 
        {
            var ulParent = $(button).parent(),
                liParent = ulParent.parent()[0],
                prefix = liParent.className.split('-')[1],
                subFormFields = ulParent.clone().removeClass('first-sub-form-fields'),
                newId;
            
            if(!multiFormElements[prefix]) {
                multiFormElements[prefix] = 1;
            }
            
            newId = multiFormElements[prefix];
            
            multiFormElements[prefix]++;
            
            subFormFields.find('li').each(function() {
                var self = $(this),
                    fieldName = self.find('label').attr('for');
                    
                self.find('textarea, input').each(function() {
                    this.name = prefix + '[' + newId + '][' + fieldName + ']';
                    this.id   = prefix + '-' + newId +'-' + fieldName;
                }).val('');
            }).end().find('.minus').removeClass('inactive');
            
            subFormFields.find('.date > input')
                            .removeClass('hasDatepicker')
                            .datepicker(Parenting.dateConfig);
            
            liParent.appendChild(subFormFields[0]);
        }
    };
    
};

/**
 * Slideshow class.
 * 
 * Wrap the call to third party slideshow (like cycle, jCarousel etc.) plugin 
 * so if have to replace it by something else the code is centralised.
 * 
 * @param {Object} config
 * @return object
 */
Parenting.Slideshow = function(config) {
    
    var defaultConfig = {
            fx:     'scrollHorz', 
            next:   '.slideshow-next', 
            prev:   '.slideshow-prev', 
            timeout: 4000,
            speed: 700
        },
        config = config || {};
    
    config = $.extend({}, defaultConfig, config);
    
    if (config.context) {
        config.next = config.next 
                    ? config.context + ' ' + config.next
                    : '';
        config.prev = config.prev
                    ? config.context + ' ' + config.prev
                    : '';
    }
    
    return { 
    
        /**
         * Run the slideshow
         */
        run: function() {
            
            var target = config.target,
                context = config.context,
                obj;
            
            obj = context
                ? $(target, context)
                : $(target);
                
            // call to cycle plugin
            try {
                obj.cycle(config);
            } catch(e) { }
        }
    };
};

$(function() {
    Parenting.init();
});

