/* var APP defined in index.php */

APP.DEG2RAD = Math.PI / 180;
APP.SECTIONS = {
    welcome : { position : 0, title : '', header_height : 350 },
    project : { position : 0, title : 'Work', header_height : 350 },
    about : { position : 1, title : 'Hello', header_height : 325  },
    experiments : { position : 2, title : 'Lab', header_height : 200  },
    blog : { position : 3, title : 'Blog', header_height : 120  },
    article : { position : 4, title : '', header_height : 60  }
}

APP.TRANSITION_TYPES = [ "", "-o-", "-ms-", "-moz-", "-webkit-" ];
APP.SECTIONS_ARRAY = [ 'welcome', 'about', 'experiments', 'blog' ];

//Defined in main.php
//APP.location = 'welcome';

APP.transitioning = false;

APP.featureIdx = 0;

APP.paper;

APP.stateObj = { foo: "bar" };

APP.initialLoad = true;

APP.paper = {};

APP.history;

APP.wedges_array = [];

APP.carouselInterval;
APP.welcomeCarousel = false;

/*------------------------------------------------------------------------------------
 ADDRESS CHANGE
 ------------------------------------------------------------------------------------*/

window.onpopstate = function(stackstate) {

    if( stackstate.state == null && APP.BROWSER_NAME == 'Chrome' && APP.initialLoad ){
        APP.initialLoad = false;
        return;
    }

    if( stackstate.state == null ){

        var initialUri = APP.requestURI.split( '/' )[ 1 ]
        var article_name = APP.requestURI.split( '/' )[ 2 ]
        if( initialUri && initialUri.length > 1 ){
            if( initialUri == 'experiments' && article_name.length > 1 ){
                mainNav_onClick( null, 'lab_work' );
            }else{
                mainNav_onClick( null, initialUri );
            }
        }else{
            mainNav_onClick( null, 'welcome' );
        }

    }else{

        mainNav_onClick( null, stackstate.state );
    }

    APP.initialLoad = false;
};

/*------------------------------------------------------------------------------------
 EVENT LISTENERS
 ------------------------------------------------------------------------------------*/

function featureNav_onClick( event, state ){

    APP.welcomeCarousel = false;
    clearInterval( APP.carouselInterval );

    event = event || window.event;
    var target = event.target || event.srcElement;

    switch( $( target ).attr( 'id' ) ){
        case 'feature_nav_arrow_left_inner' :
            APP.featureIdx--;
            break;
        case 'feature_nav_arrow_left' :
            APP.featureIdx--;
            break;
        case 'feature_nav_arrow_right_inner' :
            APP.featureIdx++;
            break;
        case 'feature_nav_arrow_right' :
            APP.featureIdx++;
            break;
    }

    featureCarousel( true );
}

function featureCarousel( force ){

    var totalFeatures = $( '.feature' ).length;

    if( !force && !APP.welcomeCarousel ) return;

    if( APP.featureIdx >= totalFeatures ){
        APP.featureIdx = 0;
    }else if( APP.featureIdx < 0 ){
        APP.featureIdx = totalFeatures - 1;
    }

    $( '#feature_drawer' ).css( { opacity : 0, filter : 'alpha(opacity = 0)' } );

    setTimeout( function(){
        $( '.feature' ).each( function( idx ) {

            console.log( this )
            if( idx == APP.featureIdx ){
                $( this ).css( { visibility : 'visible' } );

//                if( idx == 0 ){
//                    document.getElementById( 'feature_ident' ).contentWindow.resume();
//                }else{
//                    document.getElementById( 'feature_ident' ).contentWindow.pause();
//                }

            }else{
                $( this ).css( { visibility : 'hidden' } );
            }

            $( '#feature_drawer' ).css( { opacity : 1, filter : 'alpha(opacity = 100)' } );

        });

    }, 250 );
}

function mainNav_onMouseOver( event ){
    event = event || window.event;
    var target = event.target || event.srcElement;

    var margin_left = 10, margin_right = 20;

    return;

    $( '#main_navigation li' ).each( function( idx ) {

        $( this ).css( { 'margin-left' : margin_left, 'margin-right' : margin_right } );

        if( $( 'h2 a' , this ).html() == $( target ).html() ){
            margin_left = 20;
            margin_right = 10;
        }
    });

}

function mainNav_onMouseOut( event ){
    event = event || window.event;
    var target = event.target || event.srcElement;

    return;

    $( '#main_navigation li' ).each( function( idx ) {
        $( this ).css( { 'margin-left' : 30, 'margin-right' : 0 } );
    });
}

function mainNav_onClick( event, state ){

    if( APP.transitioning ) return;

    var target;
    var historyNav = false;

    if( event == null ){
        switch( state ){
            case 'welcome':
                document.title = 'Welcome › Digital Playground › Ugonna Nwosu';
                target = $( '#nav_welcome' )[ 0 ];
                break;
            case 'about':
                document.title = 'About Me › Ugonna Nwosu';
                target = $( '#nav_about' )[ 0 ];
                break;
            case 'experiments':
                document.title = 'Experiments › Ugonna Nwosu';
                target = $( '#nav_experiments' )[ 0 ];
                break;
            case 'lab_work':
                document.title = 'Experiments › Ugonna Nwosu';
                target = $( '#nav_experiments' )[ 0 ];
                break;
            case 'blog':
                document.title = 'Blog › Ugonna Nwosu';
                target = $( '#nav_blog' )[ 0 ];
                break;
            case 'article':
                document.title = APP.pageTile;
                //window.location.reload();
                break;
            default:
                window.location.reload();
                break;
        }

    }else{
        event = event || window.event;
        target = event.target || event.srcElement;
    }

    if( state != undefined ){
        historyNav = true;
    }

    //if( APP.transitioning ) return;

    // get the current location versus the new location //

//    document.getElementById( 'feature_ident' ).contentWindow.pause();

    var currID;
    var nextID;
    var curr;
    var next;
    var exitPos;
    var enterPos;
    var direction;
    var transition_duration, animation_name;
    var i = 0;

    curr = APP.location;

    if( APP.SECTIONS[ $( target ).html().toLowerCase() ].title == $( '#sub_1' ).html().toLowerCase()  ){
        currID = 1;
        nextID = 2;
        //curr = $( '#sub_1' ).html().toLowerCase();
        $( '#sub_2' ).html( APP.SECTIONS[ $( target ).html().toLowerCase() ].title );
    }else if ( APP.SECTIONS[ $( target ).html().toLowerCase() ].title == $( '#sub_2' ).html().toLowerCase() ){
        currID = 2;
        nextID = 1;
        //curr = $( '#sub_2' ).html().toLowerCase();;
        $( '#sub_1' ).html( APP.SECTIONS[ $( target ).html().toLowerCase() ].title );
    }else{

    }

    next = $( target ).html().toLowerCase();

    if( next == curr ) return;

    $( '#sub_1' ).html( APP.SECTIONS[ curr ].title );
    $( '#sub_2' ).html( APP.SECTIONS[ next ].title );

    $( '#sub_1' ).css( { opacity : 1, filter : 'alpha(opacity = 100)', left : 0 } );
    $( '#sub_2' ).css( { opacity : 0, filter : 'alpha(opacity = 0)', left : 25 } );

    for( i = 0; i < APP.TRANSITION_TYPES.length; i++ ){
        transition_duration = APP.TRANSITION_TYPES[ i ] + 'transition-duration';
        $( '#sub_1' ).css( transition_duration, '0s'  );
        $( '#sub_2' ).css( transition_duration, '0s'  );
    }

    setTimeout( function(){
        for( i = 0; i < APP.TRANSITION_TYPES.length; i++ ){
            transition_duration = APP.TRANSITION_TYPES[ i ] + 'transition-duration';
            $( '#sub_1' ).css( transition_duration, '.5s' );
            $( '#sub_2' ).css( transition_duration, '.5s' );
        }

        $( '#sub_1' ).css( { opacity : 0, filter : 'alpha(opacity = 0)', left : -25 } );
        $( '#sub_2' ).css( { opacity : 1, filter : 'alpha(opacity = 100)', left : 0 } );

        setTimeout( function(){
            transition_hideContents( APP.SECTIONS[ next ].header_height );
        }, 500 );

    }, 50 );

    $( '#main_navigation li a' ).each( function( idx ) {
        $( this ).attr( 'class', '' );
    });

    $( target ).attr( 'class', 'selected_nav' );

    APP.location = next;


    if( !historyNav ){
        switch( APP.location ){
            case 'welcome' :
                window.history.pushState( "welcome", "welcome", "/" );
                document.title = 'Welcome › Ugonna Nwosu’s Digital Playground';
                break;
            case 'about' :
                window.history.pushState( "about", "about", "/about/" );
                document.title = 'About › Ugonna Nwosu’s Digital Playground';
                break;
            case 'experiments' :
                window.history.pushState( "experiments", "experiments", "/experiments/" );
                document.title = 'Experiments › Ugonna Nwosu’s Digital Playground';
                break;
            case 'blog' :
                window.history.pushState( "blog", "blog", "/blog/" );
                document.title = 'Blog › Ugonna Nwosu’s Digital Playground';
                break;
        }
    }

    //init_reloadShareBox();

    APP.transitioning = true;
}

function transition_hideContents( headerHeight ){
    $( '#main_content' ).css( { opacity : 0, filter : 'alpha(opacity = 0)' } );

    $( '#intro_container' ).css( { opacity : 0, filter : 'alpha(opacity = 0)' } );

    $( '#feature_container' ).css( { opacity : 0, filter : 'alpha(opacity = 0)' } );

    setTimeout( function(){

        $( '#intro_container' ).css( { visibility : 'hidden' } );

        $( '#home_intro' ).css( { visibility : 'hidden' } );
        $( '#about_intro' ).css( { visibility : 'hidden' } );
        $( '#experiments_intro' ).css( { visibility : 'hidden' } );
        $( '#blog_intro' ).css( { visibility : 'hidden' } );

        transition_removeContents( headerHeight );

    }, 250 );
}

function transition_removeContents( headerHeight ){
    $( '#main_content' ).empty();

    setTimeout( function(){

        $( 'header' ).css( { height : headerHeight } );
        $( '#header_wrapper' ).css( { height : headerHeight } );
        $( '#feature_container' ).css( { height : headerHeight } );

        switch( APP.location ){
            case 'welcome' :
                init_loadHome_mainContents();
                break;
            case 'about' :
                init_loadAbout_mainContents();
                break;
            case 'experiments' :
                init_loadExperiments_mainContents();
                break;
            case 'blog' :
                init_loadBlog_mainContents();
                break;
        }

    }, 50 );

}

function transition_moveHeader(){

}

function transition_loadContents(){

}

function transition_displayContents(){

}

function arc_onMouseOver( arc ){
    arc.animate( { fill : '#333' }, 100 );
}

function arc_onMouseOut( arc, fill ){
    arc.animate( { fill : fill }, 100 );
}

function arc_onMouseUp( arc, text ){
    text = text.replace(/ /g,'');
    window.location = "?tag=" + text;
}

/*------------------------------------------------------------------------------------
 INITIALIZE
 ------------------------------------------------------------------------------------*/

function init()
{
    setup();
    setupEventListeners();
}

/*------------------------------------------------------------------------------------
 SETUP
 ------------------------------------------------------------------------------------*/

function setup(){

    switch( APP.initLocation ){
        case 'blog':
            populateBlog();
            break;
    }

//    APP.history = window.History; // Note: We are using a capital H instead of a lower h
    // Bind to StateChange Event

    console.log( APP.request_uri )

    APP.carouselInterval = setInterval( function(){ intervalFeatureCarousel(); }, 8000 );
}

/*------------------------------------------------------------------------------------
 SETUP EVENT LISTENERS
 ------------------------------------------------------------------------------------*/

function setupEventListeners()
{

    $( '#main_navigation li a' ).mouseover( function( event ){
        mainNav_onMouseOver( event );
    });

    $( '#main_navigation li a' ).mouseout( function( event ){
        mainNav_onMouseOut( event );
    });

    $( '#main_navigation li a' ).click( function( event ){
        mainNav_onClick( event );
        return false;
    });

    /* Grid Item */

    $( 'a.grid_item' ).click( function( event ){
        gridItem_onClick( event );
    });

    /*  */
    $( '.feature_nav_arrow' ).click( function( event ){
        featureNav_onClick( event );
    });

//    APP.history.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
//        var State = History.getState(); // Note: We are using History.getState() instead of event.state
//        History.log(State.data, State.title, State.url);
//    });
}


function intervalFeatureCarousel(){
    if( APP.request_uri == '/' ){
        APP.featureIdx++;
        featureCarousel( true );
    }
}

/*------------------------------------------------------------------------------------
 HOME METHODS
 ------------------------------------------------------------------------------------*/

function init_loadHome_mainContents(){
    $( '.ajax_loader' ).css( { opacity : 1 } );
    setTimeout( loadHome_mainContents, 1100 );
    console.log( 'init load' );
}

function loadHome_mainContents(){
    console.log( 'loading contents' );
    $.ajax({
        url : "/php/views/welcome.php",
        error: loadHome_mainContents_onError,
        success : loadHome_mainContents_onSuccess
    });
}

function loadHome_mainContents_onError( data ){
    console.log( 'failed' )
    console.log( "ERROR LOADING : ", data );

    APP.transitioning = false;
}

function loadHome_mainContents_onSuccess( data ){
    console.log( 'contents loaded' )
    $( '.ajax_loader' ).css( { opacity : 0 } );
    $( '#main_content' ).html( data );
    setTimeout( function(){
        $( '#main_content' ).css( { opacity : 1, filter : 'alpha(opacity = 100)' } );
        $( '#feature_container' ).css( { 'pointer-events' : 'all', display : 'block', visibility : 'visible', opacity : 1, filter : 'alpha(opacity = 100)', 'pointer-events' : 'all' } );
        $( '#intro_container' ).css( { visibility : 'hidden', opacity : 0, filter : 'alpha(opacity = 0)', 'pointer-events' : 'none' } );

        APP.featureIdx = 0;

        $( '.feature' ).each( function( idx ) {
            $( this ).css( { visibility : 'hidden' } );

            if( idx == APP.featureIdx ){
                $( this ).css( { visibility : 'visible' } );
            }
        });

    }, 50 );

    APP.transitioning = false;
}

/*------------------------------------------------------------------------------------
 PROJECT
 ------------------------------------------------------------------------------------*/


/*------------------------------------------------------------------------------------
 ABOUT METHODS
 ------------------------------------------------------------------------------------*/

/* AJAX */

function init_loadAbout_mainContents(){
    $( '.ajax_loader' ).css( { opacity : 1 } );
    setTimeout( loadAbout_mainContents, 1100 );
}

function loadAbout_mainContents(){
    
    $.ajax({
        url : "/php/views/about.php",
        error: loadAbout_mainContents_onError,
        success : loadAbout_mainContents_onSuccess
    });
}

function loadAbout_mainContents_onError( data )
{
    console.log( 'failed' )
    console.log( "ERROR LOADING : ", data );

    APP.transitioning = false;
}

function loadAbout_mainContents_onSuccess( data ){
    $( '.ajax_loader' ).css( { opacity : 0 } );
    $( '#main_content' ).html( data );
    setTimeout( function(){
        $( '#main_content' ).css( { opacity : 1, filter : 'alpha(opacity = 100)' } );
        $( '#feature_container' ).css( { 'pointer-events' : 'none', display : 'none', visibility : 'hidden', 'pointer-events' : 'none' } );
        $( '#intro_container' ).css( { visibility : 'visible', opacity : 1, filter : 'alpha(opacity = 100)', 'pointer-events' : 'all' } );
        $( '#about_intro' ).css( { visibility : 'visible' } );
    }, 50 );

    APP.transitioning = false;
}



/*------------------------------------------------------------------------------------
 EXPERIMENTS METHODS
 ------------------------------------------------------------------------------------*/

/* AJAX */

function init_loadExperiments_mainContents(){
    $( '.ajax_loader' ).css( { opacity : 1 } );
    setTimeout( loadExperiments_mainContents, 1100 );
}

function loadExperiments_mainContents(){
    $.ajax({
        url : "/php/views/experiments.php",
        error: loadExperiments_mainContents_onError,
        success : loadExperiments_mainContents_onSuccess
    });
}

function loadExperiments_mainContents_onError( data ){
    console.log( 'failed' )
    console.log( "ERROR LOADING : ", data );

    APP.transitioning = false;
}

function loadExperiments_mainContents_onSuccess( data ){
    $( '.ajax_loader' ).css( { opacity : 0 } );
    $( '#main_content' ).html( data );
    setTimeout( function(){
        $( '#main_content' ).css( { opacity : 1, filter : 'alpha(opacity = 100)' } );
        $( '#feature_container' ).css( { 'pointer-events' : 'none', display : 'none', visibility : 'hidden' } );
        $( '#intro_container' ).css( { visibility : 'visible', opacity : 1, filter : 'alpha(opacity = 100)' } );
        $( '#experiments_intro' ).css( { visibility : 'visible' } );
    }, 50 );

    APP.transitioning = false;
}



/*------------------------------------------------------------------------------------
 BLOG METHODS
 ------------------------------------------------------------------------------------*/

function blog_tagPie( tags ){
    APP.paper.tag_canvas = Raphael( "tag_canvas", 240, 240 );

    var tagsArray = [];

    for ( var prop in tags ) {
        var obj = {};
        obj.title = prop;
        obj.value = tags[ prop ];
        tagsArray.push( obj );
    }


//    var tagsArray = [   { title : 'html5', value : 2 },
//        { title : 'css3', value : 1 },
//        { title : 'javascript', value : 5 },
//        { title : 'actionscript', value : 3 } ];

    var arrColours = [  "#0DE10B", "#0DE5FC", "#F8DD00", "#E16D0B", "#F52274",
        "#0BB809", "#06717C", "#786B00", "#612F05", "#751037",
        "#0FF80C", "#09ACBC", "#B8A400", "#A14E08", "#B51956",
        "#033903", "#03383D", "#393300", "#EE730C", "#36071A",
        "#0DDE0B", "#0BD0E2", "#DEC600", "#C7600A", "#DB1C69"
    ];

    tagsArray.sort( sort_valueDescending );

    var i = 0;
    var j = 0;
    var totalTagsAmount = 0;
    var pCent;
    var startAngle = 0;
    var endAngle = 0;
    var angOffset = 0;
    var params;
    var arc;
    var fill;
    var textColour;
    var fontSize;

    var maxTags = 6;

    for( var i = 0; i < tagsArray.length; i++ ){
        totalTagsAmount += tagsArray[ i ].value;
        if( i >= maxTags - 1  ){
            break;
        }
    }

    for( i = 0; i < tagsArray.length; i++ ){

        if( i < maxTags ){

            startAngle = endAngle;
            pCent = tagsArray[ i ].value / totalTagsAmount;
            endAngle = startAngle + ( pCent * 360 );

            if( i == 0  ){
                angOffset = ( 180 - endAngle ) * -.5;
                startAngle -= angOffset;
                endAngle -= angOffset;
                fill = '#F52276';
                textColour = "#ffffff";
            }else{
                fill = '#dddddd';
                textColour = "#666666";
            }

            params = {  canvas : APP.paper.tag_canvas,
                canvasName : "tag_canvas",
                startAngle : startAngle,
                endAngle : endAngle,
                radius : 100,
                innerRadius : 0,
                centerX : 120,
                centerY : 120,
                color : fill,
                alpha : 1,
                text : tagsArray[ i ].title }

            arc = drawWedge(    params.canvas,
                params.canvasName,
                params.centerX,
                params.centerY,
                params.radius,
                params.innerRadius,
                params.startAngle,
                params.endAngle,
                params.color,
                params.alpha,
                params.text );

            wedge = { params : params, arc : arc, tween : {} };

            APP.wedges_array.push( wedge );

            if( i == 0 ){
                params.radius = 50;
            }else{
                params.radius = 60;
            }

            var halfAng = ( params.endAngle - params.startAngle ) * .5;
            halfAng = -( halfAng + params.startAngle );
            var x1 = params.centerX + params.radius * Math.cos( halfAng * APP.DEG2RAD );
            var y1 = params.centerY + params.radius * Math.sin( halfAng * APP.DEG2RAD );

            fontSize = 10;

            if( i == 0 ){
                halfAng = 0
                //fontSize = 20;
            }else if( -halfAng < 270 ){
                halfAng += 180;
            }

            var t = params.canvas.text( x1,y1, tagsArray[ i ].title ).attr( { fill : textColour, transform : "r" + halfAng, 'font-family' : "Helvetica", 'font-size' : fontSize, 'font-weight' : 'bold', stroke : 'none', cursor:'pointer' } );

        }
    }

    tagsArray.sort( sort_alphabetAscending );

    for( i = 0; i < tagsArray.length; i++ ){
        $( '#sidebar_tags h2 ul' ).append( '<li><a href="/blog/?tag=' + trim( tagsArray[ i ].title ) + '">' + tagsArray[ i ].title + '</a></li>' );
    }

}


/* =============================================================================
 AJAX
 ========================================================================== */

function init_loadBlog_mainContents(){
    $( '.ajax_loader' ).css( { opacity : 1 } );
    setTimeout( loadBlog_mainContents, 1100 );
}

function loadBlog_mainContents(){
    $.ajax({
        url : "/php/views/blog.php",
        error: loadBlog_mainContents_onError,
        success : loadBlog_mainContents_onSuccess,
    });
}

function loadBlog_mainContents_onError( data ){
    console.log( 'failed' )
    console.log( "ERROR LOADING : ", data );

    APP.transitioning = false;
}

function loadBlog_mainContents_onSuccess( data ){
    $( '.ajax_loader' ).css( { opacity : 0 } );

    // populate //
    $( '#main_content' ).html( data );
    setTimeout( function(){
        $( '#main_content' ).css( { opacity : 1 } );
        $( '#feature_container' ).css( { 'pointer-events' : 'none', display : 'none', visibility : 'hidden' } );
        $( '#intro_container' ).css( { visibility : 'visible', opacity : 1, filter : 'alpha(opacity = 100)' } );
        $( '#blog_intro' ).css( { visibility : 'visible' } );
        populateBlog();
    }, 50 );

    APP.transitioning = false;
}

/*

 */

function init_loadTwitter(){
    $( '.ajax_loader' ).css( { opacity : 1 } );
    setTimeout( function(){ loadTwitter() }, 50 );
}

function loadTwitter(){
    $.ajax({
        url : "/php/model/get_twitter.php",
        error: loadTwitter_onError,
        success : loadTwitter_onSuccess
    });
}

function loadTwitter_onError( data ){
    console.log( data );
}

function loadTwitter_onSuccess( data ){
    $( '.ajax_loader' ).css( { opacity : 0 } );
    $( '#sidebar_twitter_text' ).html( parseTweetText( data[ 0 ].text ) );
}

/*

 */

function init_loadTagsCategories(){
    $( '.ajax_loader' ).css( { opacity : 1 } );
    setTimeout( function(){ loadTagsCategories(); }, 50 )
}

function loadTagsCategories(){
    $.ajax({
        url : "/php/model/get_tags_categories.php",
        error: loadTagsCategories_onError,
        success : loadTagsCategories_onSuccess
    });
}

function loadTagsCategories_onError( data ){

}

function loadTagsCategories_onSuccess( data ){
    $( '.ajax_loader' ).css( { opacity : 0 } );
    var categoriesArray = [];
    var categories = data.categories
    $( '#sidebar_categories h1 ul' ).empty();

    for ( var prop in categories ) {
        var obj = {};
        obj.title = prop;
        obj.value = categories[ prop ];
        categoriesArray.push( obj );
    }

    for( var i = 0; i < categoriesArray.length; i++ ){
        $( '#sidebar_categories h1 ul' ).append( '<li><a href="/blog/?category=' + categoriesArray[ i ].title + '">' + categoriesArray[ i ].title.toUpperCase() + '</a></li>' );
    }

    $( '#sidebar_categories h1 ul' ).append( '<div style="clear:both;"></div>' );

    blog_tagPie( data.tags );
}

function populateBlog(){
    init_loadTwitter();
    init_loadTagsCategories();
}

/*------------------------------------------------------------------------------------
 SIDE BAR METHODS
 ------------------------------------------------------------------------------------*/

/*------------------------------------------------------------------------------------
 SIDE BAR METHODS
 ------------------------------------------------------------------------------------*/

function init_reloadShareBox(){
    $( '#share_box_container' ).empty();
    setTimeout( function(){
        reloadShareBox()
    }, 50 );
}

function reloadShareBox(){
    $.ajax({
        url : "/php/views/share_box.php",
        error: reloadShareBox_onError,
        success : reloadShareBox_onSuccess
    });
}

function reloadShareBox_onError( data ){

}

function reloadShareBox_onSuccess( data ){
    $( '#share_box_container' ).html( data );
}


/*------------------------------------------------------------------------------------
 UTILS
 ------------------------------------------------------------------------------------*/

function randomRange(min, max) {
    return ((Math.random()*(max-min)) + min);
}

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

function parseTweetText( str ){

    str = str.split( '\r' ).join( '\r ' );
    str = str.split( '\n' ).join( '\n ' );

    var arr = str.split( ' ' );
    var new_arr = [];

    var word;

    for( var i = 0; i < arr.length; i++ ){

        word = arr[ i ];

        if ( word.substr( 0, 7 )  == 'http://' ) {
            word = '<a href="' + word + '" target="_blank">' + word + '</a>';
        }

        if ( word.substr( 0, 8 )  == 'https://' ) {
            word = '<a href="' + word + '" target="_blank">' + word + '</a>';
        }

        if ( word.substr( 0, 1 )  == '#' ) {
            word = '<a href="http://search.twitter.com/search?q=%23' +  word.substr( 1 ) + '" target="_blank">' + word + '</a>';
        }

        if ( word.substr( 0, 1 )  == '@' ) {
            word = '<a href="http://twitter.com/' +  word.substr( 1 ) + '" target="_blank">' + word + '</a>';
        }

        new_arr.push( word );
    }

    str = new_arr.join( ' ' );
    return str;
}

function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}

/* =============================================================================
 ARRAY - SORT
 ========================================================================== */

function sort_alphabetAscending( a, b ){
    var titleA = a.title, titleB = b.title;
    if ( titleA < titleB)
        return -1;
    if ( titleA > titleB)
        return 1;
    return 0;
}

function sort_alphabetDescending( a, b ){
    var titleA = a.title, titleB = b.title;
    if ( titleA > titleB)
        return -1;
    if ( titleA < titleB)
        return 1;
    return 0;
}

function sort_valueAscending( a, b ){
    var valueA = a.value, valueB = b.value;
    if (valueA < valueB)
        return -1;
    if (valueA > valueB)
        return 1;
    return 0;
}

function sort_valueDescending( a, b ){
    var valueA = a.value, valueB = b.value;
    if (valueA > valueB)
        return -1;
    if (valueA < valueB)
        return 1;
    return 0;
}

/* =============================================================================
 RAPHAEL
 ========================================================================== */

/**
 *
 * @param raphaelCanvas
 * @param rapahelName
 * @param centerX
 * @param centerY
 * @param radius
 * @param innerRadius
 * @param startAngle
 * @param endAngle
 * @param fillColour
 */

function drawWedge( raphaelCanvas, rapahelName, centerX, centerY, radius, innerRadius, startAngle, endAngle, fillColour, fillAlpha, text ){
    var p;
    var cx = centerX;
    var cy = centerY;
    var r = radius;
    var ir = innerRadius;
    if( ir > r ){ ir = r; }
    if( ir < 0 ){ ir = 0; }
    var x1 = cx + r * Math.cos( -startAngle * APP.DEG2RAD ),
        x2 = cx + r * Math.cos( -endAngle * APP.DEG2RAD ),
        x3 = cx + ir * Math.cos( -endAngle * APP.DEG2RAD ),
        x4 = cx + ir * Math.cos( -startAngle * APP.DEG2RAD ),
        y1 = cy + r * Math.sin( -startAngle * APP.DEG2RAD ),
        y2 = cy + r * Math.sin( -endAngle * APP.DEG2RAD ),
        y3 = cy + ir * Math.sin( -endAngle * APP.DEG2RAD ),
        y4 = cy + ir * Math.sin( -startAngle * APP.DEG2RAD );
    var fill = fillColour;

    var path = [ "M", x1, y1, "L", x1, y1, "A", r, r, 0, + ( endAngle - startAngle > 180 ), 0, x2, y2, "L", x3, y3, "A", ir, ir, 1, + ( endAngle - startAngle > 180 ), 1, x4, y4, "z" ];

    p = raphaelCanvas.path(path).attr({ cx : cx, cy : cy, fill: fill, 'fill-opacity': fillAlpha, 'stroke' : '#fff', 'stroke-width' : 1 });
    //$( '#' + rapahelName + ' svg path' ).attr( { 'filter' : 'url(#f1)' }  );

    var halfAng = ( endAngle - startAngle ) * .5;
    halfAng = -( halfAng + startAngle );
    x1 = cx + ( r * .5 )  * Math.cos( halfAng * APP.DEG2RAD );
    y1 = cy + ( r * .5 ) * Math.sin( halfAng * APP.DEG2RAD );

    p.mouseover( function(){ arc_onMouseOver( p ) } );
    p.mouseout( function(){ arc_onMouseOut( p, fill ) } );
    p.mouseup( function(){ arc_onMouseUp( p, text ) } );

    return p;
}

function updateWedge( wedge ){

    var cx = wedge.params.centerX;
    var cy = wedge.params.centerY;
    var r = wedge.params.radius;
    var ir = wedge.params.innerRadius;

    var sa = wedge.params.startAngle % 350;
    var ea = wedge.params.endAngle % 360;

    if( wedge.params.endAngle > 359.99 ){
        ea = 359.99;
    }

    var x1 = cx + r * Math.cos( -sa * APP.DEG2RAD ),
        x2 = cx + r * Math.cos( -ea * APP.DEG2RAD ),
        x3 = cx + ir * Math.cos( -ea * APP.DEG2RAD ),
        x4 = cx + ir * Math.cos( -sa * APP.DEG2RAD ),
        y1 = cy + r * Math.sin( -sa * APP.DEG2RAD ),
        y2 = cy + r * Math.sin( -ea* APP.DEG2RAD ),
        y3 = cy + ir * Math.sin( -ea * APP.DEG2RAD ),
        y4 = cy + ir * Math.sin( -sa * APP.DEG2RAD );

    var path = [ "M", cx, cy, "L", x1, y1, "A", r, r, 0, + ( ea - sa > 180 ), 0, x2, y2, "L", x3, y3, "A", ir, ir, 0, + ( ea - sa > 180 ), 1, x4, y4, "z" ];

    wedge.arc.attr( 'path', path );
}

function drawCurve( raphaelCanvas, rapahelName, centerX, centerY, radius, innerRadius, startAngle, endAngle ){
    var p;
    var r = radius;
    var cx = centerX;
    var cy = centerY;
    var ir = innerRadius;
    var x1 = cx + r * Math.cos( -startAngle * APP.DEG2RAD ),
        x2 = cx + ir * Math.cos( -( startAngle - endAngle ) * APP.DEG2RAD ),
        x3 = cx + r * Math.cos( -endAngle * APP.DEG2RAD ),
        y1 = cx + r * Math.sin( -startAngle * APP.DEG2RAD ),
        y2 = cx + ir * Math.sin( -( startAngle - endAngle ) * APP.DEG2RAD ),
        y3 = cx + r * Math.sin( -endAngle * APP.DEG2RAD );

    var path = [ "M", x1, y1, "S", x2, y2, x3, y3 ];
    p = raphaelCanvas.path(path);

    return p;

}

/*------------------------------------------------------------------------------------
 INITIALIZATION
 ------------------------------------------------------------------------------------*/

$(document).ready(function() {
    init();
});
