(function() {
    function toggle( item ) {
        if ( item.is('.selected') ) {
            item.removeClass('selected')
                .next()
                .animate({height: "hide"}, {
                duration: 200,
                easing: 'easeinout'
            });
        } else {
            item.addClass('selected')
                .next()
                .animate({height: "show"}, {
                duration: 200,
                easing: 'easeinout'
            });
        }
    }

    jQuery.fn.toggleSection = function() {
        $(this).each(function() {
            var item = $(this);
            var next = item.next();

            if ( $("p.loading", next).length ) {
                if ( !$.data(this, "loading") ) {
                    $.data(this, "loading", true);
                    next.load( item.attr('source') );
                }
            }
            toggle(item);
        })
        return this;
    };
})();

$(function() {
    app.connectWithUser.init('#main');
    app.messageUser.init('#main');
// alert('dynamic length: ' + $('.searchFacetValues li.dynamic span').length);
//     $('.searchFacetValues li.dynamic span').click(function() {
//         this.parentNode.parentNode.removeChild(this.parentNode);
//     });

    // search facets section disclose
    $("#searchFacets h3")
        .not('.selected')
        .next()
        .css('display', 'none')
        .end()
        .end()
        .click(function() {
        $(this).toggleSection();
    })
        .find('.title')
        .click(function() {
        $(this).parent().trigger('click');
        return false;
    });

});


$(function(){
    /* change behavior for filter select pulldowns */
    $('#selectView, #selectSort').change(function(){ location.href = this.value });
});
$(function(){
    $('#whatsThis').click(function(){
        var options = {
            // default title
            title: 'Whats This',
            width: 640,
            buttons: { 'OK': function() { $(this).dialog('close') } },
            callback: function(firstLoad) {
                initDialog(firstLoad, '#whatsThisWin');
            }
        }
        content.modalAjax('#whatsThisWin', options);
        return false;
    });
});


$(function(){
    function initDialog(firstLoad, id) {
        var baseName = $(id).attr('id');
        if (firstLoad) {
            $('.'+ baseName +'Icons a', id).click(function(){
                window.open(this.href);
                $(id).dialog('close');
                return false;
            });
        }
    }
    $('#trackBookmark').click(function(){
        var options = {
            title: 'Track this page via social bookmark',
            buttons: { 'OK': function() { $(this).dialog('close'); }},
            callback: function(firstLoad) {
                initDialog(firstLoad, '#bookmark');
            }
        }
        content.modalAjax('#bookmark', options);
        return false;
    });
});


/**/
$(function(){
    $('ul.paging>li.direct>input').bind('change', function(){
        var limit = parseInt( $(this).attr('limit') );
        var max = (parseInt( $(this).parent().next('li').find('span.max').text() ) -1) * limit;
        var start = (parseInt( $(this).val() ) -1) * limit;
        var h = document.location.href;
        var p = 'start=' + ( (start > max) ? max : start < 0 ? 0 : start );
        document.location.href = (/start=/i.test(h)) ? h.replace(/start=([^&])+/i, p) : h + ((/\?/).test(h) ? '&' : '?') + p;
        this.select();
    }).bind('keypress', function(e){
        var keycode = e.which || 0;
        if (keycode == 13) { // 13 = Return Key
            $(this).trigger('change');
            return false;
        }
    }).click(function(){
        this.select();
    });
    // If the user manually typed in a URL that goes past the end, bounce them to the last page (FL-3292)
    var reqPg = parseInt($('ul.paging>li.direct>input:first').val());
    var maxPg = parseInt($('ul.paging>li>span.max:first').text());
    if( reqPg > maxPg ) {
        content.alert('Page out of bounds');
        setTimeout(function(){ $('ul.paging>li.direct>input').trigger('change') }, 5000);
    }
});
/**/


        $(function() {
            $('#main a.openRemoveFromThisSpot').live('click', function() {
                var options = {
                    title: 'Remove',
                    width: 350,
                    ajaxUrl: this.href,
                    ajaxCache: false,
                    buttons: {
                        'Remove': function() {
                            $('div.ui-dialog-buttonpane button', this).addClass('disabled');
                            $('form', this).trigger('submit');
                            return false;
                        },
                        'Cancel': function() {
                            $(this).dialog('close');
                            return false;
                        }
                    }
                }

                if ( $(this).hasClass('removeWithAjax') ) {
                    var $deleteItem = $(this).parents('li.blog-item:first');
                    $.extend(options, {
                        callback: function( id ) {
                            var dialogId = id;
                            $('form', dialogId).ajaxForm({
                                dataType: 'json',
                                success: function( data ) {
                                    $(dialogId).dialog('close');
                                    $deleteItem.fadeOut('normal', function() {
                                        $(this).remove();
                                    });
                                    if ( data.message ) {
                                        content.info(data.message);
                                    }
                                },
                                error: function() {
                                    $(dialogId).dialog('close');
                                    content.alert("Permission denied");
                                }
                            });
                        }
                    });
                }
                content.modalAjax('#removeFromThisSpot', options);
                return false;
            });

            $('a#bulk-remove').click(function() {
                var options = {
                    title: 'Remove',
                    width: 350,
                    ajaxUrl: this.href + '?' + $('ul.item-summary input:checkbox').serialize(),
                    ajaxCache: false,
                    buttons: {
                        'Remove': function() {
                            $('div.ui-dialog-buttonpane button', this).addClass('disabled');
                            $('form', this).triggerHandler('submit');
                            return false;
                        },
                        'Cancel': function() {
                            $(this).dialog('close');
                            return false;
                        }
                    },
                    callback: function( data ) {
                        var dialogId = this.id;
                        $('form', dialogId).ajaxForm({
                            dataType: 'json',
                            success: function( data ) {
                                $(dialogId).dialog('close');
                                $deleteItem.fadeOut('normal', function() {
                                    $(this).remove();
                                });
                                if ( !(data.message == '' || data.message == null ||
                                       data.message == 'undefined') ) {
                                    content.info(data.message);
                                }
                            },
                            error: function() {
                                $(dialogId).dialog('close');
                                content.alert("Permission denied");
                            }
                        });
                    }
                }

                var $deleteItem = $(this).parents('li.blog-item:first');
                content.modalAjax('#removeFromThisSpot', options);
                return false;
            });
        });
    

$(function(){
    $('#subscribeToDigest').click(function(){
        var postURI = $('#subscribeToDigest').attr("postURI");
        $.ajax({
            url: postURI,
            type: "POST",
            data: {'subscribe': $('#subscribeToDigest').attr('subscribe')},
            dataType: "json",
            success: function( data ) {
                if( data.error ) {
                    switch( data.error.code ) {
                        case "already-subscribed":
                            content.alert("You are already subscribed");
                            break;
                        case "not-subscribed":
                            content.alert("You are not subscribed");
                            break;
                        default:
                            content.alert("Oops, unable to subscribe");
                            break;
                    }
                } else {
                    if( data.added ) {
                        content.info("Added to Digest: " + data.spot );
                        $("#subscribeToDigest").attr("subscribe", "false");
                    } else {
                        content.info("Removed from Digest: " + data.spot );
                        $("#subscribeToDigest").attr("subscribe", "true");
                    }
                    updateSubscribeLabel();
                }
            },
            error: function() {
                try {
                    console.log("Unknown failure updating subscription");
                } catch ( ignored ) {
                }
            }
        });
    });
    updateSubscribeLabel();
});

function updateSubscribeLabel() {
    $("#subscribeToDigest[subscribe=true]").text("Email Subscription");
    $("#subscribeToDigest[subscribe=false]").text("Unsubscribe");
}


$('a.postToAnotherSpotDialog').live('click', function(e){
    e.stopPropagation();
    e.preventDefault();
    var options = {
        title: 'Share this item with another twine',
        // height: 400,
        width: 400,
        ajaxUrl: this.href,
        ajaxCache: false,
        buttons: { 'Share': function() { $('form', this).submit() } },
        callback: function(firstLoad) {
            /* omniture code to track share attempts */
            if ( typeof(s_account) !== 'undefined' ) {
                var s=s_gi(s_account);
                s.linkTrackVars='events';
                s.linkTrackEvents='event27';
                s.events='event27';
                s.tl(true,'o','share attempt');
            }
            /* omniture code end */
            if (firstLoad) {
                var id = this.id;
                var $dialog = $(id).parent();
                // select first option in dialog when only one exists - Kai
                var $opts = $('select[multiple] option:not([disabled])', id);
                if ( $opts.length === 1 ) $opts[0].selected = true;
                else $dialog.find('.ui-dialog-buttonpane button').addClass('ui-state-disabled');

                $('select.multi').change(function () {
                    $('select.multi option:selected:not([disabled])').each(function () {
                        $dialog.find('.ui-dialog-buttonpane button').removeClass('ui-state-disabled');
                    });
                });

                $('form', id).ajaxForm({
                    dataType: 'json',
                    beforeSubmit: function() {
                        if ( $dialog.find('.ui-dialog-buttonpane button:first').hasClass('ui-state-disabled') ){ return false; };
                        content.disableButton($dialog.find('.ui-dialog-buttonpane button:first'));
                    },
                    success: function(data) {
                        content.info(data.message);
                        $(id).dialog('close');
                    },
                    error: function(xhr, status, ex) {
                        // kill this error function when ie6+7 are working perfectly - kb
                        var msg = ""; 
                        msg += status + "\n"; 
                        msg += xhr.status + "\n\n"; 
                        msg += ex; 
                        debug('REPORT: ' + msg);
                        $(id).dialog('close');
                    }
                });
            }
        }
    }
    content.modalAjax('#postToAnotherSpot', options);
    return true;
});
$('a.withViaEmailDialog').live('click', function(e){
    e.stopPropagation();
    e.preventDefault();
    var options = {
        title: 'Share this item via Email',
        // height: 400,
        width: 400,
        ajaxUrl: this.href,
        ajaxCache: false,
        buttons: { 'Share': function() { $('form', this).submit() } },
        callback: function(firstLoad) {
            if (firstLoad) {
                /* omniture code to track share attempts */
                if ( typeof(s_account) !== 'undefined' ) {
                    var s=s_gi(s_account);
                    s.linkTrackVars='events';
                    s.linkTrackEvents='event27';
                    s.events='event27';
                    s.tl(true,'o','share attempt');
                }
                /* omniture code end */
                var id = this.id;
                var $dialog = $(id).parent();

                $('textarea:last', id).placeholder({blankSubmit: false});
                $dialog.find('.ui-dialog-buttonpane button:first').addClass('ui-state-disabled');
                $('.email-list textarea', id).blur(function(){
                    $dialog.find('.ui-dialog-buttonpane button:first')
                        [$(this).val()?'removeClass':'addClass']('ui-state-disabled');
                });
                $('form', id).ajaxForm({
                    dataType: 'json',
                    beforeSubmit: function(formArray, $form) {
                        // email validation pattern
                        var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i
                        var $emailField = $('.email-list textarea', id);
                        $emailField.parent().prev('div.oops').remove(); // clear previous message
                        if ( ! $emailField.val() ) { return false; }
                        // trim, remove trailing ',', split on space or ',' and normalize to ', '
                        $emailField.val($.trim($emailField.val()).replace(/\s*,$/,'').split(/\s*,\s*|\s+/).join(', '));
                        // update addresses element
                        $.grep(formArray, function(f){ return f.name == 'addresses' }).value = $emailField.val();
                        // check email address format
                        var invalid = $.grep($emailField.val().split(', '), function(addr){ 
                            return email.test(addr);
                        }, true);
                        if ( invalid.length ) {
                            $emailField.parent()
                                .before('<div class="oops" style="font-weight: bold; margin-bottom: 10px">Please fix these addresses: '+ invalid.join(', ') +'</div>');
                            return false;
                        }
                        content.disableButton($dialog.find('.ui-dialog-buttonpane button:first').removeClass('ui-state-disabled'));
                        return true;
                    },
                    success: function(data) {
                        content.info(data.message);
                        $(id).dialog('close');
                    }
                });
            }
        }
    }
    content.modalAjax('#withViaEmail', options);
    return false;
});
/**/
$('a.withService').live('click', function(){
    $.post(this.href, null, function(data){
        if ( data && data.redirect ) {
            document.location.href = data.redirect;
        }
        else if ( data && data.message ) {
            content.info(data.message);
        }
    },'json');
    return false;
});
/**/


