(function ( $ ) {
    if( location.hash ){
        var host = location.host,
            hashRoute = location.hash.replace( '#', '' );
        if( hashRoute ) {
            location.href = 'http://' + host + hashRoute;
        }
    }

    /*** Global methods ***/

    var fbShare = function( message, title, url, image, onShare ) {
        var description,
            name,
            nickMapping,
            nickReplacer;

        if ( onShare ) {
            onShare = function( onShare ) {
                return function( resp ) {
                    resp && resp.post_id && onShare();
                };
            }( onShare );
        }

        // Run Twitter handle replacement again with global name mappings
        nickMapping = {
            klout: 'Klout'
        };
        nickReplacer = function( twHandle, nick ) {
            return nickMapping[nick.toLowerCase()];
        };
        message = message.replace( /@([A-Za-z0-9_]+)/g, nickReplacer );

        if ( title ) {
            name = title;
            description = message;
        } else {
            name = message;
            description = 'Klout is the standard for influence.';
        }

        FB.ui( {
            description : description,
            link   : url,
            method : 'feed',
            name   : name,
            picture : image
        }, onShare );
    };

    function liShare( message, url ) {
        var left = ( $( window ).width() - 575 ) / 2,
            top  = ( $( window ).height() - 400 ) / 2,
            opts = 'status=1' +
                   ',width=575' +
                   ',height=400' +
                   ',top=' + top +
                   ',left=' + left,
            shareWindow = open( 'about:blank', 'li_share', opts ),
            queryString = 'url=' + encodeURIComponent( url ).replace( /%2F/g, '/' ) +
                          '&title=' + encodeURIComponent( 'Klout' ) +
                          '&summary=' + encodeURIComponent( message ) +
                          '&source=Klout';

        url = 'http://www.linkedin.com/shareArticle?mini=true&' + queryString;
        open( url, 'li_share', opts );
    }

    var twShare = function ( message, url, el, f ) {
        var onTweet,
            queryString = 'url=' + encodeURIComponent( url ) +
                          '&text=' + encodeURIComponent( message ) +
                          '&related=klout';

        url = 'http://twitter.com/intent/tweet?' + queryString;

        if ( f ) {
            onTweet = function ( e ) {
                f();
                el.unbind( 'tweet', onTweet );
                e.stopImmediatePropagation();
            };
            el.bind( 'tweet', onTweet );
        }

        el.attr( 'href', url );
    };

    var hookupTw = function () {
        if ( twttr ) {
            twttr.events.bind( 'tweet', function ( e ) {
                $( e.target ).trigger( 'tweet' );
            } );
        }
        else {
            setTimeout( hookupTw, 1000 );
        }
    };
    hookupTw();

    var log = amphetamine.log = function() {
        if ( typeof console == 'undefined' ) {
            return;
        }
        Function.prototype.apply.call( console.log, console, arguments );
    };

    var mp = amphetamine.mp = new function () {
        var objs = {},
            MixpanelDev = function ( token ) {
                this.token = token;

                this.track = function ( metric, obj, fn ) {
                    amphetamine.log( "--- Mixpanel tracked '" + metric + "' for " + this.token, obj );
                    if ( typeof fn === 'function' ) fn();
                };
            };

        this.jsonp_callback = $.noop;

        this.get = function ( type ) {
            if ( typeof objs[ type ] === 'undefined' ) {
                var token = ( amphetamine.config.mixpanel && amphetamine.config.mixpanel[ type ] ) || 0;
                objs[ type ] = amphetamine.config.dev ? new MixpanelDev( type ) : new MixpanelLib( token, 'amphetamine.mp' );
            }

            return objs[ type ];
        };
    }();


    /*** Event listeners ***/
    $( '#amphetamine-modal .close-modal' ).live( 'click', function() {
        $( '#amphetamine-modal' ).empty().hide();
    } );

    $( 'body' ).delegate( '.viral-link', 'click', function ( e ) {
        var el = $( this ),
            event,
            image = amphetamine.config.staticServer + 'images/stroke-flag.png',
            isFb = el.hasClass( 'fb' ),
            isTw = el.hasClass( 'tw' ),
            metaProperties,
            name,
            title = false,
            properties = {},
            property,
            route,
            url,
            viralMessage,
            viralUnit = el.closest( '.viral-unit' );

        // Get default required viral properties
        event = viralUnit.find( 'input[name=viralEvent]' ).val();
        route = viralUnit.find( 'input[name=viralRoute]' ).val();
        viralMessage = isTw ? viralUnit.find( 'input[name=viralMessageTw]' ).val() : viralUnit.find( 'input[name=viralMessage]' ).val();

        // See if we have any optional image and title properties for FB virals
        image = viralUnit.find( 'input[name=viralImage]' );
        image = ( isFb && image.length ) ? image.val() : ( amphetamine.config.staticServer + 'images/stroke-flag.png' );
        title = viralUnit.find( 'input[name=viralTitle]' );
        title = ( isFb && title.length ) ? title.val() : false;

        // Add any additional properties that were specified by the viralMeta* fields
        metaProperties = viralUnit.find( 'input[name^="viralMeta"]' );

        for ( var i = 0; i < metaProperties.length; i++ ) {
           property = metaProperties[i].name.replace( 'viralMeta', '' ).toLowerCase();
           properties[property] = metaProperties[i].value;
        }

        // Figure out remaining logic and then fire away!
        properties.network = isFb ? 'fb' : isTw ? 'tw' : 'li';
        url = amphetamine.config.host + route + ( route.indexOf( '?' ) > -1 ? '&' : '?' ) + 'n=' + properties.network + '&v=' + event;

        amphetamine.mp.get( 'viralSend' ).track( event, properties );

        if ( isFb ) {
           fbShare( viralMessage, title, url, image, function () {
               amphetamine.mp.get( 'viralSubmit' ).track( event, properties );
           } );
        }
        else if ( isTw ) {
           twShare( viralMessage, url, el, function () {
               amphetamine.mp.get( 'viralSubmit' ).track( event, properties );
           } );
        }
        else {
           liShare( viralMessage, url );
        }
    } );

    $( '#submit-optout' ).live( 'click', function() {
        var reason = $('#deactivate-account-form .radio-button[name=deactivate-reason]'),
            signature = $.trim( $( '#opt-out-signature' ).val() );

        if ( signature.length == 0 ) {
            $( '.error' ).html( 'A signature is required' ).show();
        }
        else if ( reason.serializeArray().length == 0 ) {
            $( '.error' ).html( 'A reason is required' ).show();
        } else {
            xhr = $.ajax({
                    url     : '/api/unregOptout/submitForm',
                    type    : 'POST',
                    data    : {
                        reasonCode : $( 'input:radio[name=deactivate-reason]:checked').val(),
                        description : $( '#deactivate-reason-text' ).val()
                    },
                    success : function( data ) {
                        location.href = '/corp/optoutconfirm';
                    },
                    error : function( data ) {
                        $( '.error' ).html( 'There was an error opting out. Please try again or contact support@klout.com' ).show();
                    },
                    complete : function( data ) {
                        xhr = null;
                    }
                });
        }
    });

    $( document ).on( 'keyup', function( e ){
        if( e.keyCode == 27 ) {
            $( '#amphetamine-modal' ).empty().hide();
        }
    });

    $( '#logo-notif' ).on( 'mouseenter', function( e ){
        $( '#header-glow' ).animate( { opacity: 1 }, 200 );
    }).live( 'mouseleave', function( e ) {
        $( '#header-glow' ).animate( { opacity: 0 }, 200 );
    });

    $( '#logo' ).on( 'click', function( e ){
        var page;
        if( location.href.indexOf( '/home' ) > -1 ){
            page = 'home_unlogged';
        } else if( location.href.indexOf( '/understand' ) > -1 ){
            page = 'understanding_klout_unlogged';
        } else if( location.href.indexOf( '/topic/' ) > -1 ) {
            page = 'topic_public';
        } else if( location.href.indexOf( '/list/' ) > -1 ) {
            page = 'list_public';
        } else {
            page = 'profile_public';
        }
        amphetamine.mp.get( 'click' ).track( 'header_logo', { page : page } );
    });
} )( jQuery );

