// {{{ MAIN CONTROLLER INSTRUCTIONS
$( document ).ready( function(){
   // Display the submenu
   $( '#menu li.has_sub a' ).click( show_sub );
   $( '#menu li.no_sub a' ).click( close_sub );
   $( '#submenu .single_sub ul li.has_sub_sub a' ).click( function(){ $(this).parent().find( 'ul').toggle( 'fast' ); return false; } ); 
   $( '#submenu .single_sub ul li.no_sub_sub a' ).click( function(){ $(this).parent().parent().find( '.has_sub_sub ul').hide( 'fast' ); return false; } ); 
   // Closes submenu
   $( '#sub_close' ).click( close_sub );
   // Displays pages with JQuery Address
    $.address.change( function(event) {  
        console.log( event );
        load_url( event.value );
        return false;
    });  
    // Sets JQuery address
    $( 'body' ).delegate( 'a.reveal_page', 'click', set_jq_add );
    $( 'body' ).delegate( '#submit_contact_form', 'click', submit_contact_form );
    // {{{ Music Player
    var playItem = 0;
    var myPlayList = [];
    var music_mp3 = $( '#background_song' ).html();
    var music_ogg = $( '#background_song_ogg' ).html();
    // Get Info
        myPlayList.push({ 
            name        : 'Background Music',
            mp3         : '/music_files/' + music_mp3,
            ogg         : '/music_files/' + music_ogg
        });

    // Local copy of jQuery selectors, for performance.
    var jpPlayTime = $("#jplayer_play_time");
    var jpTotalTime = $("#jplayer_total_time");

    $("#jquery_jplayer").jPlayer({
        swfPath : '/application/views/themes/default/library/swf',
        ready: function() {
            playListInit(true); // Parameter is a boolean for autoplay.
        },
        oggSupport : true
    })
    .jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
        jpPlayTime.text($.jPlayer.convertTime(playedTime));
        jpTotalTime.text($.jPlayer.convertTime(totalTime));
    })
    .jPlayer("onSoundComplete", function() {
        playListNext();
    });

    $("#jplayer_previous").click( function() {
        playListPrev();
        $(this).blur();
        return false;
    });

    $("#jplayer_next").click( function() {
        playListNext();
        $(this).blur();
        return false;
    });

    function displayPlayList() {
        $("#jplayer_playlist ul").empty();
        for (i=0; i < myPlayList.length; i++) {
            var listItem = (i == myPlayList.length-1) ? "<li class='jplayer_playlist_item_last'>" : "<li>";
            listItem += "<a href='#' id='jplayer_playlist_item_"+i+"' tabindex='1'>"+ myPlayList[i].name +"</a></li>";
            $("#jplayer_playlist ul").append(listItem);
            $("#jplayer_playlist_item_"+i).data( "index", i ).click( function() {
                var index = $(this).data("index");
                if (playItem != index) {
                    playListChange( index );
                } else {
                    $("#jquery_jplayer").jPlayer("play");
                }
                $(this).blur();
                return false;
            });
        }
    }

    function playListInit( autoplay ) 
    {
        if( autoplay ) 
        {
            playListChange( playItem );
        } 
        else 
        {
            playListConfig( playItem );
        }
    }

    function playListConfig( index ) {
        $("#jplayer_playlist_item_"+playItem).removeClass("jplayer_playlist_current").parent().removeClass("jplayer_playlist_current");
        $("#jplayer_playlist_item_"+index).addClass("jplayer_playlist_current").parent().addClass("jplayer_playlist_current");
        playItem = index;
        $("#jquery_jplayer").jPlayer("setFile", myPlayList[playItem].mp3, myPlayList[playItem].ogg);
    }

    function playListChange( index ) {
        playListConfig( index );
        $("#jquery_jplayer").jPlayer("play");
    }

    function playListNext() {
        var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
        playListChange( index );
    }

    function playListPrev() {
        var index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1;
        playListChange( index );
    }
    // End Music Player }}}
});
// }}}
// {{{ submit_contact_form()
var submit_contact_form = function()
{
    var obj = {};
    var url = '/contact/submit';
    obj.input_name = $( '#input_name' ).val();
    obj.input_email = $( '#input_email' ).val();
    obj.input_phone = $( '#input_phone' ).val();
    obj.input_message = $( '#input_message' ).val();
    obj.ajax = '1';
    //console.log( obj );
    $.ajax({
        url         : url,
        data        : obj,
        type        : 'POST',
        success     : function( data ) {
            $( '#contact_result' ).html( data );
        }
    });
    return false;
}
// }}}
// {{{ var set_jq_add = function()
var set_jq_add = function()
{
    $.address.value( $(this).attr( 'href' ) );  
    return false;
}
// }}}
// {{{ var load_url = function( url )
var load_url = function( url )
{
    console.log( 'loadURL: ' + url );
    url = ( url != '/' ) ? url : '/pages';
    var base = getBaseURL();
    var obj = {};
    $( '.chiTip' ).hide();
    $( '#loading' ).animate({ opacity : 1 }, 500, 'swing' );
    $( '#wrapper' ).animate({ opacity : 0 }, 500, 'swing', function(){ 
        $.ajax({
            url         : url,
            success     : function( data ) {
                var response = json_parse( data );
                if( response.success == true )
                {
                    // PUT NEW HTML IN WRAPPER
                    $( '#wrapper' ).html( response.view );
                    $( '.chiTip' ).hide();
                    // ACTIVATE VIDEO PLAYER
                    if( response.has_video == true ) 
                    {
                        activate_video( response.videos[0], response.playlist_id ); 
                        $('#jquery_jplayer').jPlayer('stop');
                    }
                    $( 'a[title]' ).chiToolTip();
                    // REPLACE FONTS
                    Cufon.replace( 'h1, .cufon_league', { fontFamily : 'LeagueGothic' } );
                    if( $('#menu_bool').html() == 'true' )
                    {
                        $('.content_block').attr( 'style', 'margin-left:-100px;' );
                    }
                    // FADE IN
                    $( '.chiTip' ).hide();
                    $( '#wrapper' ).animate({ opacity : 1 }, 1000, 'swing' );
                    $( '#loading' ).animate({ opacity : 0 }, 500, 'swing' );
                }
            }
        });
    });
    return false;
}
// }}}
// {{{ var activate_video = function( video )
var activate_video = function( video, playlist_id )
{
    var base = getBaseURL();
    var poster_url = base + '/index.php?admin/resize_img/' + encodeURIComponent( 'videos/images/' + video.pic ) + '/width/640';
    /*var poster_url = base +'/videos/images/' + video.pic;*/
    $("#video_player").H5Video({
        playlist : playlist_id,
        events : {
            pause : function()
            {
                writeMessage("Paused video");
            },

            play : function()
            {
                writeMessage("Playing video");
            },

            end : function()
            {
                writeMessage("End of video");
            }
        },
        animationDuration : 350,
        source : {
            "video/mp4"  : base + '/videos/' + video.h264,
            /* "video/ogg"  : base + '/videos/' + video.ogg */
            /* "video/webm" : base + '/videos/' + video.webm*/
        },
        loop : false,			
        preload: true,
        autoPlay : false,			
        poster : poster_url,			
        supportMessage : "This browser cannot playback HTML5 videos. We encourage you to upgrade your internet browser to one of the following modern browsers:"
    });				
}
// }}}
// {{{ var show_page = function()
var show_page = function() 
{
    var page = $( this ).attr( 'page' );
    var title = $( this ).attr( 'title' );
    var type = $( this ).attr( 'type' );
    var base_url = $( '#base_url' ).html();
    var body_bool = $( '#body_bool' ).html();
    $( '#wrapper' ).animate({ opacity : 0 }, 500, 'swing', function(){ 
      $.ajax({
        url: base_url + page + '/' + title,
        success: function( data ) {
          $( '#wrapper' ).html( data );
          $( '#wrapper' ).animate({ opacity : 1 }, 1000, 'swing' );
          if( type == 'video' )
          { 
          }
        }
      });
    });
    return false;
}
// }}}
// {{{ var show_sub = function()
var show_sub = function() 
{
   var next_sub = $( this ).attr( 'sub' ); 
   var has_sub = $( this ).parent().attr( 'has_sub' ); 
   var sub_bool = $( '#menu_bool' ).html();
   if( sub_bool == 'false' )
   {
      $( '#menu_info' ).html( next_sub );
      $('.content_block').animate({ marginLeft: -100 }, 600, 'swing', function(){ });
      $('#submenu').animate({
         width: 250,
        opacity: 1
      }, 600, 'swing', function(){
         $( '#menu_bool' ).html( 'true' );
         $( '#' + next_sub ).fadeIn( 'slow' );
         $( '#submenu' ).css( 'borderRight', '1px solid #0f132d' );
         $( '#' + next_sub ).animate({ opacity : 100 }, 600, 'swing' );
      });
   }
   else if( sub_bool == 'true' )
   {
      var current_sub = $( '#menu_info' ).html();
      $('#' + current_sub ).animate({
         opacity : 0
      }, 600, 'swing', function(){
         $( '#' + current_sub ).css( 'display', 'none' );
         $( '#menu_info' ).html( next_sub );
         $( '#' + next_sub ).fadeIn( 'slow' );
         $( '#' + next_sub ).animate({ opacity : 100 }, 600, 'swing' );
      });
   }
   return false; 
}
// }}}
// {{{ var close_sub = function()
var close_sub = function() 
{
   var current_sub = $( '#menu_info' ).html();
   $('.content_block').animate({ marginLeft: -200 }, 600, 'swing', function(){ });
   $('#submenu #' + current_sub ).animate({
      opacity : 0
   }, 600, 'swing', function(){
      $( '#submenu #' + current_sub ).css( 'display', 'none' );
      $( '#menu_bool' ).html( 'false' );
      $('#submenu').animate({ width: 0 }, 600, 'swing', function() { 
         $( '#submenu' ).css( 'borderRight', '0px' );
      });
   });
   return false; 
}
// }}}

