if(!window['chatc']) {
    window['chatc'] = {};
    var chatc = window['chatc'];
}

(function($){
    var protos = {
        'input':    $('<input />'),
        'label':    $('<label />'),
        'li':       $('<li />'),
        'close':    $('<a href="#close" class="close">Close &times;</a>'),
        'span':     $('<span />')
    }
    
    $(document).ready(function() {
        $.browser.mobile = (navigator.userAgent.toLowerCase().indexOf('mobile') != -1 || navigator.userAgent.toLowerCase().indexOf('android') != -1 || navigator.userAgent.toLowerCase().indexOf('palm') != -1);
        chatc.directory();
        chatc.jobs();
        chatc.messages();
        chatc.application();
        chatc.forms();
        chatc.lists();
        chatc.nav();
        chatc.mobile();
        chatc.hero();
        chatc.memberfilter();
        chatc.equalHeight($('div.item'));
        chatc.equalHeight($('div#main, div#sb'));
    });
    
    $(window).load(function() {
        if( $.browser.mobile ){
            setTimeout(function(){
                if($(window).scrollTop() == 0) {
                    window.scrollTo(0,0);
                }
            },10);
        }
    });
    
    
    chatc.browserSucks = (jQuery.browser.msie && jQuery.browser.version < 7) ? true : false;

    chatc.hero = function() {
        // Heroshot options
        chatc.hero.useControls = false
        chatc.hero.useCaptions = true

        if(!$('div.heroshot').size()) {
            return
        }

        chatc.hero.interval = null

        chatc.hero.container = $('div.heroshot');

        chatc.hero.fade = 1000;

        chatc.hero.dur = 8 * 1000;

        chatc.hero.slides = chatc.hero.container.find('div.slide');

        if(chatc.hero.useCaptions) {
            if(chatc.hero.container.children('div.slide').size()) {
                var firstCaption = chatc.hero.container.children('div.slide:first-child').find('img').attr('alt')
            } else if(chatc.hero.container.children('img:first-child').size()) {
                var firstCaption = chatc.hero.container.children('img:first-child').attr('alt')
            } else {
                var firstCaption = ''
            }

            chatc.hero.container.append(
                $(jQuery('<div />'))
                    .attr({id: 'hero-caption'})
                    .append(
                        $(jQuery('<span />'))
                            .attr({id: 'caption-holder'})
                            .show()
                            .text(firstCaption)
                    )
            )

            chatc.hero.container.append(
                $(jQuery('<ul />'))
                    .attr({id: 'hero-numbers'})
            )

            chatc.hero.slides.each(function(i){
                n = i + 1
                chatc.hero.container.children('ul#hero-numbers').append('<li>' + n + '</li>');
            })

        }

        if(chatc.hero.container.children('div.slide').size() < 2) { // Less than two images, we don't need to xfade or add controls
            return;
        }

        if(chatc.hero.useControls) {
            chatc.hero.container.append(
                    $(jQuery('<div />'))
                        .attr({id: 'hero-controls'})
                        .append(
                            $(jQuery('<ul />'))
                                .append(
                                    $(jQuery('<li />'))
                                        .append(
                                            $(jQuery('<a />'))
                                                .attr({
                                                    title: 'Previous Photo',
                                                    id: 'hero-previous',
                                                    href: '#previous-photo'
                                                })
                                                .click(function(c){
                                                    c.preventDefault()
                                                    clearInterval(chatc.hero.interval)
                                                    chatc.hero.rotate('prev')
                                                    $('#hero-pause').hide()
                                                    $('#hero-play').show()
                                                })
                                        )
                                )
                                .append(
                                    $(jQuery('<li />'))
                                        .append(
                                            $(jQuery('<a />'))
                                                .attr({
                                                    title: 'Pause Photos',
                                                    id: 'hero-pause',
                                                    href: '#pause-photos'
                                                })
                                                .click(function(c){
                                                    c.preventDefault()
                                                    clearInterval(chatc.hero.interval)
                                                    $('#hero-pause').hide()
                                                    $('#hero-play').show()
                                                })
                                                .css({display: 'block'})
                                                .show()
                                        )
                                )
                                .append(
                                    $(jQuery('<li />'))
                                        .append(
                                            $(jQuery('<a />'))
                                                .attr({
                                                    title: 'Play Photos',
                                                    id: 'hero-play',
                                                    href: '#play-photos'
                                                })
                                                .click(function(c){
                                                    c.preventDefault()
                                                    chatc.hero.interval = setInterval(function(){
                                                        chatc.hero.rotate('next')
                                                    }, chatc.hero.dur + chatc.hero.fade)
                                                    $('#hero-pause').show()
                                                    $('#hero-play').hide()
                                                })
                                                .css({display: 'block'})
                                                .hide()
                                        )
                                )
                                .append(
                                    $(jQuery('<li />'))
                                        .append(
                                            $(jQuery('<a />'))
                                                .attr({
                                                    title: 'Next Photo',
                                                    id: 'hero-next',
                                                    href: '#next-photo'
                                                })
                                                .click(function(c){
                                                    c.preventDefault()
                                                    clearInterval(chatc.hero.interval)
                                                    chatc.hero.rotate('next')
                                                    $('#hero-pause').hide()
                                                    $('#hero-play').show()
                                                })
                                        )
                                )
                        )
                )
        }
        
        if(!chatc.browserSucks) {
            chatc.hero.container.children('div.slide:first-child').attr({current: 'current'}).show()
            chatc.hero.container.find('ul#hero-numbers').children('li:first-child').attr({current: 'current'}).addClass('current')
        }
        chatc.hero.container.children('div.slide:not(:first-child)').hide()
        if(jQuery.browser.safari) {
            chatc.hero.container.children('div.slide:not(:first-child)').css({display: 'none'})
        }

        chatc.hero.interval = setInterval(function() {
            chatc.hero.rotate('next')
        }, chatc.hero.dur + chatc.hero.fade)

        chatc.hero.rotate = function(dir) {
            if(typeof dir == 'undefined') {
                var dir = 'next'
            }
            var images = chatc.hero.container.children('div.slide')
            var current = chatc.hero.container.children('div[current]')
            var numbers = chatc.hero.container.find('ul#hero-numbers').children('li')
            var current_number = chatc.hero.container.find('ul#hero-numbers').children('li[current]')
            if(dir == 'next') {
                if(current.next('div.slide').size()) {
                    var to = current.next('div.slide')
                    var to_number = current_number.next('li')
                } else {
                    var to = $(images[0])
                    var to_number = $(numbers[0])
                }
            } else {
                if(current.prev('div.slide').size()) {
                    var to = current.prev('div.slide')
                } else {
                    var to = $(images[images.size() - 1])
                }
            }
            
            if(jQuery.browser.msie) {
                current.removeAttr('current').hide()
                current_number.removeAttr('current').removeClass('current')
            } else {
                current.removeAttr('current').fadeOut(chatc.hero.fade)
                current_number.removeAttr('current').removeClass('current')
            }

            if(chatc.hero.useCaptions) {
                chatc.hero.container.find('#caption-holder').fadeOut(chatc.hero.fade / 2, function(){
                    chatc.hero.container.find('#caption-holder').text(to.find('img').size() ? to.find('img').attr('alt') : to.attr('alt'))
                    chatc.hero.container.find('#caption-holder').fadeIn(chatc.hero.fade * 1.5)
                })
            }

            if(jQuery.browser.msie) {
                to.attr({current: 'current'}).show()
                to_number.attr({current: 'current'}).addClass('current')
            } else {
                to.attr({current: 'current'}).fadeIn(chatc.hero.fade)
                to_number.attr({current: 'current'}).addClass('current')
            }
        }

        $('ul#hero-numbers li').each(function(i){
            $(this).css('cursor', 'pointer').click(function() {
                clearInterval(chatc.hero.interval)
                var images = chatc.hero.container.children('div.slide')
                var current = chatc.hero.container.children('div[current]')
                var current_number = chatc.hero.container.find('ul#hero-numbers').children('li[current]')
                var numbers = chatc.hero.container.find('ul#hero-numbers').children('li')
                var to = $(images[i])
                var to_number = $(numbers[i])
                if(jQuery.browser.msie) {
                    current.removeAttr('current').hide()
                    current_number.removeAttr('current').removeClass('current')
                } else {
                    current.removeAttr('current').fadeOut(chatc.hero.fade)
                    current_number.removeAttr('current').removeClass('current')
                }
                if(jQuery.browser.msie) {
                    to.attr({current: 'current'}).show()
                    to_number.attr({current: 'current'}).addClass('current')
                    chatc.hero.interval = setInterval(function(){
                        chatc.hero.rotate('next')
                    }, chatc.hero.dur + chatc.hero.fade)
                } else {
                    to.attr({current: 'current'}).fadeIn(chatc.hero.fade)
                    to_number.attr({current: 'current'}).addClass('current')
                    chatc.hero.interval = setInterval(function(){
                        chatc.hero.rotate('next')
                    }, chatc.hero.dur + chatc.hero.fade)
                }
                chatc.hero.container.find('#caption-holder').fadeOut(chatc.hero.fade / 2, function(){
                    chatc.hero.container.find('#caption-holder').text(to.find('img').size() ? to.find('img').attr('alt') : to.attr('alt'))
                    chatc.hero.container.find('#caption-holder').fadeIn(chatc.hero.fade * 1.5)
                })
            })
        })
    }
    
    chatc.directory = function() {
        var container = $('#category-filters');
        if(!container.size()) return;
        var checkboxes = container.find('input[type=checkbox]');
        var selectAll = protos.input.clone().attr({'type': 'checkbox', 'id': 'js-select-all', 'name': 'categories', 'value': 'all'});
        var label = protos.label.clone().attr({'for': 'js-select-all'}).html(' Select All').prepend(selectAll);
        var li = protos.li.clone();
        li.append(label);
        checkboxes.eq(0).closest('ul').prepend(li);
        checkboxes.click(function() {
            if(checkboxes.size() == checkboxes.filter(':checked').size()) {
                selectAll.attr({'checked': 'checked'});
            } else {
                selectAll.removeAttr('checked');
            }
        });
        selectAll.click(function() {
            if(selectAll.is(':checked')) {
                checkboxes.attr({'checked': 'checked'});
            } else {
                checkboxes.removeAttr('checked');
            }
        });
        if(checkboxes.size() == checkboxes.filter(':checked').size()) {
            selectAll.attr({'checked': 'checked'});
        }
    }

    chatc.equalHeight = function(group) {
        var tallest = 0;
        group.each(function() {
            var thisHeight = $(this).height();
            if(thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        group.height(tallest);
    }
    
    
    chatc.messages = function() {
        var container = $('#messages');
        if( ! container.size() ) return;
        var messages = container.children('li');
        messages.each(function() {
            var message = $(this);
            var close = protos.close.clone();
            message.append(close);
            close.click(function(c) {
                c.preventDefault();
                message.fadeOut(500, function() {
                    if( ! container.children('li:visible').size() ) container.remove();
                });
            });
        });
    }
    
    chatc.application = function() {
        if( ! $('body').is('#application') ) return;
        var memberInput = $('input#id_number_of_members');
        var price = protos.span.clone().addClass('price');
        memberInput.after(price);
        var pricePer = parseInt(memberInput.attr('data-cost-first-five'), 10);
        var priceAdditional = parseInt(memberInput.attr('data-cost-additional'), 10);
        var updatePrice = function() {
            var num = parseInt(memberInput.val(), 10);
            var basePrice = num <= 5 ? num * pricePer : 5 * pricePer;
            var additionalPrice = num > 5 ? (num - 5) * priceAdditional : 0;
            var displayCost = basePrice + additionalPrice;
            if( typeof displayCost == 'number' && ! isNaN(num) && num > 0 ) {
                price.text( '$' + django.intcomma(displayCost) );
            } else if( num < 0 ) {
                price.text('Please enter a positive number');
            } else {
                price.text('Please enter a number');
            }
        }
        memberInput.keyup(function() {
            updatePrice();
        });
        updatePrice();
    }
    
    chatc.forms = function() {
        var is_primaries = $('input[type=checkbox][name$=is_primary]');
        is_primaries.click(function() {
            var checkbox = $(this);
            if ( checkbox.is(':checked') ) {
                is_primaries.filter(':not(#' + checkbox.attr('id') + ')').removeAttr('checked');
            }
        });
        
        if(!Modernizr.input.placeholder && !$.browser.mobile) {
            $('input[placeholder]').each(function() {
                var input = $(this);
                var placeholder = input.attr('placeholder');
                input.focus(function() {
                    input.removeClass('placeholder');
                    if( input.val() == placeholder ) input.val('');
                });
                input.blur(function() {
                    input.addClass('placeholder');
                    if( input.val() == '' ) input.val(placeholder);
                });
                if( input.val() == '' ) input.val(placeholder).addClass('placeholder');
                $(window).unload(function(){
                    if( input.val() == placeholder ) input.val('');
                });
            });
        }
        
        $('input[rel=date]').datepicker({ 'dateFormat': 'yy-mm-dd', 'gotoCurrent': true, 'showButtonPanel': true, 'defaultDate': '+30', 'yearRange': '-00:+01', 'maxDate': '+3m', 'constrainInput': true, 'buttonImage': $('link[rel=media-url]').attr('href') + 'images/calendar.png', 'buttonImageOnly': true, 'buttonText': 'Choose Date', 'showOn': 'both' });
    }
    
    chatc.lists = function() {
        $('#main ul, #main ol').each(function() {
            var list = $(this);
            if( ! list.parents('form').size() && ! list.is('.pagination') && ! list.parents('.featured-members').size() ) {
                list.addClass('scripted');
                list.find('li').each(function() {
                    var item = $(this);
                    item.html( '<span>' + item.html() + '</span>' );
                });
            }
        });
    }
    
    chatc.nav = function() {
        var links = $('nav a, .nav a, *[class*=nav] a, *[id*=nav] a');
        var url = window.location.pathname;
        links.filter('[href=' + url + ']').parent('li:not(.selected)').addClass('selected');
        links.filter(function(){ return url.indexOf($(this).attr('href')) == 0 && ! $(this).parents('li').is('.selected'); }).parents('li:not(.ancestor)').addClass('ancestor');
    }
    
    chatc.jobs = function() {
        var form = $('#sb .directory-filters');
        if( ! $('body').is('.jobs') && form.size() ) return;
        
        var groups = form.find('ol > li');
        groups.each(function(index) {
            var group = $(this);
            var checkboxes = group.find('input[type=checkbox]');
            var selectAll = protos.input.clone().attr({'type': 'checkbox', 'id': 'js-select-all-' + index, 'name': 'categories', 'value': 'all'});
            var label = protos.label.clone().attr({'for': 'js-select-all-' + index}).html(' Select All').prepend(selectAll);
            var li = protos.li.clone();
            li.append(label);
            checkboxes.eq(0).closest('ul').prepend(li);
            checkboxes.click(function() {
                if(checkboxes.size() == checkboxes.filter(':checked').size()) {
                    selectAll.attr({'checked': 'checked'});
                } else {
                    selectAll.removeAttr('checked');
                }
            });
            selectAll.click(function() {
                if(selectAll.is(':checked')) {
                    checkboxes.attr({'checked': 'checked'});
                } else {
                    checkboxes.removeAttr('checked');
                }
            });
            if(checkboxes.size() == checkboxes.filter(':checked').size()) {
                selectAll.attr({'checked': 'checked'});
            }
        });
    }

    function removeElement(array, keyword) {
        return $.grep(array, function (item, i) {
          return item.indexOf(keyword) > -1;
      }, true);
    }

    chatc.memberfilter = function() {
        if (! $('body.directory').size()) { return; }

        var hashes = location.search.substring(1);

        if ( hashes.length ) { 
            var marray = hashes.split('&')
            var nmarray = removeElement(marray, 'page=')
            hashes = nmarray.join('&')
            if (hashes.length > 0) { hashes = '&' + hashes }
        }

        $('ul.pagination li a:not(.disabled)').each(function() {
            var original_content = $(this).attr('href');
            var split_hash = hashes.split('=')
            $(this).attr('href', original_content + hashes);
        });
    }
    
    chatc.mobile = function() {
        if( ! $.browser.mobile ) return;

        var nav = function() {
            var container = $('#nav');
            var links = container.find('a');
            container.empty();
            var select = $('<select />');
            var option = $('<option />');
            container.append(select);
            select.append(
                option.clone().attr({'value': '/'}).text('Home')
            );
            links.each(function() {
                var link = $(this);
                var thisOption = option.clone().attr({'value': link.attr('href')}).text(link.text());
                if ( link.parent('li').is('.selected') || link.parent('li').is('.ancestor') ) {
                    thisOption.attr({'selected': 'selected'});
                }
                select.append(thisOption);
            });
            select.change(function() {
                window.location = select.val();
            });
        }
        nav();
        
        var tables = function() {
            $('td, th').each(function() {
                if( ! $.trim($(this).html()) || $.trim($(this).html()) == '&nbsp;' || $.trim($(this).html()) == '<br />&nbsp;') $(this).remove();
            });
        }
        tables();
        
        var calendars = function() {
            $('a[href$=.ics]').each(function() {
                $(this).attr({'href': 'webcal://' + window.location.host + $(this).attr('href')});
            });
        }
        calendars();
    }
})(jQuery);