$( document ).ready( function () {


    var url = window.location.href;
    $( '.sidebar-menu a' ).filter( function () {
        return this.href === url;
        //} ).closest( 'li' ).addClass( 'active' );
    } ).parents( '.sidebar-menu li' ).addClass( 'active' );

    function fixHeight() {
        var headerHeight = $( "header.main-header" ).outerHeight();
        $( "#frame" ).attr( "height", ( ( $( window ).height() - 0 ) - headerHeight ) + 'px' );
    }

    $( window ).resize( function () {
        fixHeight();
    } ).resize();


    function populate_visitors_price() {
        /**
         * Calculate visitors
         */
        // http://stackoverflow.com/a/3087027
        var visitors = 0;
        $( 'input[id^=campaign-items-][id$=-purchase]' ).each( function ( index, item ) {
            var val = $( item ).val();
            visitors += val * 1000;
        } );
        $( "#total-visitors" ).text( visitors );

        /**
         * Calculate price
         */
        var price = 0;
        $( 'input[id^=campaign-items-][id$=-advertiser-price]' ).each( function ( index, item ) {
            console.log( val );
            var val = $( item ).val();
            price += val * $( "#campaign-items-" + index + "-purchase" ).val();
            ;
        } );
        $( "#total-price" ).text( price );
    }

    populate_visitors_price();

    $( "#campaign-create" ).change( function () {
        populate_visitors_price();
    } );
} );



/**
 * Bootstrap 3: Keep selected tab on page refresh
 */
// store the currently selected tab in the localStorage
$( '#form-settings a[data-toggle="tab"]' ).on( "shown.bs.tab", function ( e ) {
    var id = $( e.target ).attr( "href" ).substr( 1 );
    localStorage.setItem( 'settings_selectedTab', id );
} );

// on load of the page: switch to the currently selected tab
var selectedTab = localStorage.getItem( 'settings_selectedTab' );

if ( $( '#form-settings' ).length && selectedTab !== null ) {
    $( '#form-settings a[data-toggle="tab"][href="#' + selectedTab + '"]' ).tab( 'show' );
} else {
    $( '#form-settings a[data-toggle="tab"]:first' ).tab( 'show' );
}



// http://stackoverflow.com/a/5766416
$( function () {
    var go_submit = $( '#go-submit' );
    function myFunction() {
        go_link = $( '#go-link' );
        go_link.addClass( 'go-link' );
    }

    ( function () {
        var time = 10000,
            delta = 1000,
            tid;

        tid = setInterval( function () {
            if ( window.blurred ) {
                return;
            }
            time -= delta;
            go_submit.text( 'Please Wait ' + ( time / 1000 ) + 's' );
            if ( time <= 0 ) {
                go_submit.text( 'Go!' ).removeAttr( "onclick" );
                ;
                clearInterval( tid );
                myFunction(); // time passed - do your work
            }
        }, delta );
    } )();

    window.onblur = function () {
        window.blurred = true;
    };
    window.onfocus = function () {
        window.blurred = false;
    };
} );


/**
 * Report invalid link
 */
$( "#go-link" ).one( "submit", function ( e ) {
    e.preventDefault();
    var goForm = $( this );

    if ( !goForm.hasClass( 'go-link' ) ) {
        return;
    }

    var submitButton = goForm.find( 'button' );

    $.ajax( {
        dataType: 'json', // The type of data that you're expecting back from the server.
        type: 'POST', // he HTTP method to use for the request
        url: goForm.attr( 'action' ),
        data: goForm.serialize(), // Data to be sent to the server.
        beforeSend: function ( xhr ) {
            //submitButton.attr( "disabled", "disabled" ).html( '<i class="fa fa-spinner fa-spin"></i>' );
            goForm.replaceWith( '<button class="btn btn-default" onclick="javascript: return false;">Redirecting...</button>' );
        },
        success: function ( result, status, xhr ) {
            //console.log( result );
            if ( result.url ) {
                //alert( result.message + ' - ' + result.url );
                window.location.href = result.url;
                //submitButton.text( 'Redirecting...' );
                //goForm.replaceWith( '<button class="btn btn-default" onclick="javascript: return false;">Redirecting...</button>' );
            } else {
                alert( result.message );
            }
        },
        error: function ( xhr, status, error ) {
            alert( "An error occured: " + xhr.status + " " + xhr.statusText );
        },
        complete: function ( xhr, status ) {

        }
    } );
} );

/**
 * Shorten
 */
$( "#shorten" ).on( "submit", function ( e ) {
    e.preventDefault();
    var shortenForm = $( this );
    var submitButton = shortenForm.find( 'button' );
    var submitButtoHTML = submitButton.html();

    $.ajax( {
        dataType: 'json', // The type of data that you're expecting back from the server.
        type: 'POST', // he HTTP method to use for the request
        url: shortenForm.attr( 'action' ),
        data: shortenForm.serialize(), // Data to be sent to the server.
        beforeSend: function ( xhr ) {
            submitButton.attr( "disabled", "disabled" ).html( '<i class="fa fa-spinner fa-spin"></i>' );
            $( '<div class="shorten loader"></div>' ).insertAfter( shortenForm );
        },
        success: function ( result, status, xhr ) {
            //console.log( result );
            if ( result.url ) {

                shortenForm.slideUp();
                var short_url_html = '<div class="form-group"><input class="form-control input-lg" value="' + result.url + '" readonly onfocus="javascript:this.select()" ></div>';
                $( ".shorten.add-link-result" ).html( short_url_html ).slideDown();

                //alert( result.message + ' - ' + result.url );
                //shortenForm.replaceWith( '<input class="form-control input-lg"  type="text" value="' + result.url + '" onfocus="javascript:this.select()" readonly>' );
                //shortenForm.find( 'input#url' ).val( result.url );
            } else {
                shortenForm.slideUp();
                var success_message = '<div class="form-group"><div class="alert alert-danger" role="alert">' + result.message + '</div></div>';
                $( ".shorten.add-link-result" ).html( success_message ).slideDown();
                //alert( result.message );
                //shortenForm.replaceWith( '<input class="form-control input-lg"  type="text" value="' + result.message + '" onfocus="javascript:this.select()" readonly>' );
                //shortenForm.find( 'input#url' ).val( result.message );
            }
        },
        error: function ( xhr, status, error ) {
            alert( "An error occured: " + xhr.status + " " + xhr.statusText );
        },
        complete: function ( xhr, status ) {
            $( '.shorten.loader' ).remove();
        }
    } );
} );
