/**/
$(function() {
    $('.recommendations .holder')
        // list of .holders
        .each(function() {
            // JUL-2288 - time stamp to prevent IE cache on reload - Kai
            var url = this.getAttribute('url') +'&t='+ (new Date().getTime());
            var holder = this;
            $(this).load( url, function(){
                $(holder).addClass( 'loaded' );
                app.connectWithUser.init(holder);
            });
        })
        .find('a.dismissBtn').live('click', function(){
            // JUL-2288 - remove trailing / in discard uri which IE includes
            var $holder = $(this).closest('.holder');
            var readyToReload = false;
            var newRecs = '';
            // request newRecommendations, wait for fade out to show them
            $.get($holder.attr('url'), {'discard':this.href.replace(/\/$/,'')}, function(data){
                // JUL-2796, reconnect connectWithUser ... todo: make connectWithUser use delegate
                if ( readyToReload ) { $holder.html(data); app.connectWithUser.init($holder[0]); }
                else { newRecs = data; }
            });
            $(this).closest('li')
                .fadeOut('slow', function(){ 
                    if ( newRecs ) { $holder.html(newRecs); app.connectWithUser.init($holder[0]); }
                    else { readyToReload = true; }
                });
            return false;
        });
});
/**/


        $(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() {
    $('#spotActivity').tabs();
    $('#spotMembers').tabs();

    $('#tools .accordion:first').accordion()
        .find('input[type=text]').click(function(){ this.select() });

    app.connectWithUser.init('#main');

    function concatStr(el) {
        if ( $(el).length == 0 ) return '';
        var lst = $(el).html().split(/\s*,\s*/);
        var str = '';
        $.each(lst, function(i){ 
            var joiner = ( i == (lst.length -2) ) ? ' and ' : ', ';
            if ( i == 0 || i == (lst.length -1)) joiner = ' ';
            str += this + joiner;
        });
        return $.trim(str) + '.';
    }
    $('#memberPerms').html(concatStr('#memberPerms'));

    $('#tagsAccordion').accordion({alwaysOpen: false, autoHeight: false});
});


        /**/
        $(function(){
            var reportOptions = {
                title: 'Report This',
                width: 400,
                buttons: {
                    'Send': function() { $('form', this).trigger('submit') },
                    'Cancel': function() {
                        $(this).dialog('close');
                        return false;
                    }
                }
            }

            $('#reportIt').click(function() {
                content.modal('#report', reportOptions);
                changeValidator();
                return false;
            });
            $('a.report-button').live('click', function() {
                var url = this.href;
                $.extend(reportOptions, { 
                   callback: function(){ 
                       $('#reportUrl').val(url);
                       $('#reportReturnUrl').val(location.href);
                   }
                });
                content.modal('#report', reportOptions);
                changeValidator();
                return false;
            });
            function changeValidator() {
                if ( $('#reportForm select').val() && $.trim($('#description').val()) ) {
                    $('#report button.lg:first').removeClass('disabled');
                } else {
                    $('#report button.lg:first').addClass('disabled');
                }
            }
            $('#reportForm select').change(changeValidator);
            $('#description').keyup(changeValidator);

            $('#reportForm').submit(function() {
                if ( $('#report select').val() == '' ) {
                    content.info("Please select a reason");
                    return false;
                } else if ( !$.trim($('#description').val()) ) {
                    content.info("Please enter a message");
                    return false;
                }
                else {
                    $('#report').dialog('close');
                    return true; // submit the form
                }
            });
        });
        /**/
    

$(function(){
    var leaveOptions = {
        title: 'Leave',
        width: 300,
        buttons: {
            'Yes': function() { $('form', this).trigger('submit') },
            'Cancel': function() { $(this).dialog('close'); return false; }
        }
    }

    $('#leave').click(function(){
        content.modal('#leaveDialog', leaveOptions);
        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;
    });
});


/**/
var dialogOpen = dialogOpen || {};
dialogOpen.joinSpot = function( btn ) {
    var joinOptions = {
        width: 400,
        destroy: true,
        buttons: { 'OK': function() { $('form', this).trigger('submit'); return false; } },
        callback: function(id) {
            $('span.spot-label', id).html(joinOptions.title);
            content.disableOnSubmit($('button:first', id));
            // if( joinOptions.action.indexOf(document.location.href) == -1) - too complex
            // new approch - if ?ajax in query string use ajax, otherwise post form normally
            if( /[\?|&]ajax\b/.test(joinOptions.action) )
                $('form', id)
                    .unbind('submit')
                    .bind('submit', function(){
                        var self = this;
                        // the unbind above requires us to rebind the button disable
                        // targetting the unbind the correct submit handler is not working - Kai
                        content.disableButton($('button:first', self));
                        $(this).ajaxSubmit({
                            success: function(data) {
                                $(self).parents('div.ui-dialog-content:first').dialog('close');
                                // Determin where to go after ajax post
                                // url before # is followed if it exists
                                if( joinOptions.next && (joinOptions.next.indexOf(document.location.href) == -1) ) {
                                    document.location.href = joinOptions.next;
                                }
                                else {
                                    //$(joinOptions.caller).remove(); - not doing this because we can't replocate on explore page
                                    setTimeout(function(){content.info('You are now a member of '+ joinOptions.title)}, 100);
                                }
                            }
                        });
                        return false;
                    });
        }
    }

    var action = (btn.href) ? btn.hash.substring(1) : '';
    var href = btn.href;
    if (action) {
        if( /\?ajax/.test(href) ) {
            action = $.addParameter('ajax', action); // add ajax to action to signal ajax response
            href = href.substring(0, href.indexOf('?')); // remove ?ajax and other parameters from next page url
            joinOptions.next = href;
        }
        joinOptions.caller = btn;
        joinOptions.action = $('form', '#subscription-dialog')[0].action = action; 
        joinOptions.title = $.entify(btn.title);
    }
    content.modal('#subscription-dialog', joinOptions);
    return false;
}
$(function(){
    $('a.joinSpotBtn').live('click', function(){ return dialogOpen.joinSpot(this) });
});
/**/


$(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;
});
/**/


