// ===================================================    
//*=== Activate JS-enabled class immediately  ===*
// ===================================================

$('html').removeClass('nojs').addClass('js');

// ===================================================    
//*=== Load custom fonts with Google WebFont loader ===*
// ===================================================

WebFont.load({
    custom: { families: ['LeagueGothicRegular'],
            urls: [ 'http://www.linesandwaves.com/c/fonts.css'] 
    }
});

$(document).ready(function() {
    
    // Determine if the device is a touch-enabled device
    var touchEnabled = ((navigator.userAgent.match(/Android/i)) || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
    
    // ===================================================    
    //*=== Overlay Form Labels ===*
    // ===================================================
    
    $('form label').overlabel();
    
    // ===================================================
    //*=== Build Slideshows ===*
    // ===================================================
        
    var slideWrap = $('#work .slides');
    var slideWidth = 614;
    
    slideWrap.each(function(){
        
        var curWrap = $(this);
        var slideBox = curWrap.find('ul');
        var slides = slideBox.find('li');
        var slideNum = slideBox.find('img').length;
        var totalWidth = slideNum * slideWidth;
        
        // Wrap the slides in an extra div for management's sake
        slideBox.wrap('<div class="wrap"></div>');
        
        // And position that div
        curWrap.find('.wrap').css({
            'position': 'relative',
            'overflow' : 'hidden'
        });

        // Position the slides
        slides.css('float', 'left');        

        // Set starting slide position (0,0) and make primary nav controls
        slideBox.css({
            'left': 0,
            'position': 'absolute',
            'top': 0,
            'width': totalWidth
        }).after('<a class="prev hidden_text" href="#">Previous</a><a class="next hidden_text" href="#">Next</a>');
        
        var prevLink = $(this).find('.prev');
        var nextLink = $(this).find('.next');      
        
        // Set the flags to determine when next/prev animations have finished
        var prevFlag = false;
        var nextFlag = false;
        
        // Hide the controls initially
        prevLink.hide();
        nextLink.hide();
        
        // Set the flags to determine whether prev/next should appear on hover
        var prevState = false;
        var nextState = true;
        
        // Bind the "next" control behavior      
        nextLink.click(function(e) {
            
            // If the animation is not already in progress, the flag is false
            if (nextFlag === false) {
                    
                // Once the animation begins, set the flag to true
                nextFlag = true;
                // Animate the slide action
                slideBox.animate({
                    'left' : (posCheck()-slideWidth)
                }, 1000, function(){
                    navCheck();
                    selectCheck();
                    navReveal();

                    // Animation done, reset flag to false
                    nextFlag = false;
                });  
            }
            
            return false;
        });
        
        // Bind the "prev" control behavior      
        prevLink.click(function(e) {
            
            // If the animation is not already in progress, the flag is false
            if (prevFlag === false) {

                // Once the animation begins, set the flag to true
                prevFlag = true;                
                // Animate the slide action
                slideBox.animate({
                    'left' : (posCheck()+slideWidth)
                }, 1000, function(){
                    navCheck();
                    selectCheck();
                    navReveal();
  
                    // Animation done, reset flag to false
                    prevFlag = false;
                });                
            }

            return false;
        });
        
        // Build the secondary nav items
        curWrap.append(function(){
            var secNav = '<ol>';
            for (var i=0; i < slideNum; i++) {
                secNav += '<li><a class="hidden_text" href="#" title="Go to slide #'+(i+1)+'">'+(i+1)+'</a></li>';
            }
            secNav += '</ol>';
            return secNav;
        });
        
        curWrap.find('ol a').click(function() {
            
            // Clear the secondary nav states
            curWrap.find('ol li').removeClass('selected');
            
            // If the nav item is not already selected, add the selected state
            if (!$(this).parent().hasClass('selected')) {
                $(this).parent().addClass('selected');
            }
            
            // Animate the slide action
            slideBox.animate({
                'left' : -(($(this).text()-1)*slideWidth)
            }, 1000, function(){
                navCheck();
            });
                        
            return false;
        });
        
        // Check the current slide position
        function posCheck() {
            var curPos = parseFloat(slideBox.css('left'));
            return curPos;
        }
        
        // Check the state of the primary nav controls and adjust accordingly
        function navCheck() {
            
            // Set prevState to false if on the first slide
            if (posCheck() === 0) {
                prevState = false;
            } else {
                prevState = true;
            }
            
            // Set nextState to false if on the last slide
            if (posCheck() == ((slideNum-1) * -slideWidth)) {
                nextState = false;
            } else {
                nextState = true;
            }
        }
        
        function selectCheck() {
            
            // Return the number of the secondary nav child
            var childNum = Math.abs((posCheck()/slideWidth))+1; 
            
            // Clear the state of each child
            curWrap.find('ol li').removeClass('selected');
            
            // Add the "selected" state to the matched child
            curWrap.find('ol li:nth-child('+childNum+')').addClass('selected');
        }
        
        function navReveal() {
            // If not on the first slide, fade in the "prev" control
            if (prevState === true) {
                prevLink.fadeIn('300');
            } else {
                prevLink.fadeOut('300');
            }
            
            // If not on the last slide, fade in the "next" control
            if (nextState === true) {
                nextLink.fadeIn('300');
            } else {
                nextLink.fadeOut('300');
            }
        }
                
        // Show the slideshows once they're done building
        curWrap.find('ul, ol').fadeIn(700);
        
        // Select the first slide
        curWrap.find('ol li:first-child').addClass('selected');
        
        // Reveal the prev/next controls on rollover
        curWrap.find('.wrap').hover(function(){
            navReveal();

        // If the slides will be linked to larger versions, then on slide click, pop out lightbox with enlarged image.
            
        }, function(){
            prevLink.fadeOut('300');
            nextLink.fadeOut('300');
        });
        
        // If the device has touch gestures enabled, use the swipe gesture to advance the slides instead of next/prev buttons
        if (touchEnabled) {
            prevLink.remove();
            nextLink.remove();
            slides.swipeEnable(slideBox);
        }
        
    });
    
    // ===================================================
    //*=== Build Chart for Last.fm Stats ===*
    // ===================================================
    
    var lfmTable = $('#lastfm_stats table');
    var lfmTopVal = 0;
    var lfmTotal = 0;
    
    // In pixels.  Make this a variable when you have time
    var lfmWidth = 460;
    
    // Get the top play count value
    lfmTable.find('tbody td:nth-child(2)').each(function(){
        var thisValue = parseFloat($(this).text());
        
        // Append the word "Plays" to each value, since we're hiding that header
        $(this).html(thisValue+' <span>plays</span>');
        
        // Find the highest value
        if (thisValue > lfmTopVal) {
            lfmTopVal = thisValue;
        }
        
        // Find the total plays
        lfmTotal += thisValue;
        
    });
    
    // Set the widths on each table row accordingly
    lfmTable.find('tbody td:last-child').each(function(){
       var thisCount = parseFloat($(this).prev().text());
       var thisWidth = Math.round((thisCount * lfmWidth)/lfmTopVal);
       var thisPercent = Math.round((thisCount/lfmTotal)*100);
       $(this).css('width', thisWidth).text(thisPercent);
    });
    
    // ===================================================    
    //*=== Build Canvas Chart for Reader Stats ===*
    // ===================================================
        
    var rTable = $('#reader_stats table');
    var tableData = {};
    tableData.xLabels = [];
    tableData.yValues = [];
    tableData.topValue = 0;
    tableData.bottomValue = 0;
    
    // In pixels.  Make this a variable when you have time
    var chartHeight = 65;
    var chartWidth = 155;
    
    // The line/fill colors and width
    var lineColor = '#333';
    var fillColor = '#333';
    var lineSize = 2;
    
    // Adjust the height value to account for the extra space needed by the stroke size
    var realHeight = chartHeight - lineSize;
    
    // Hide the table
    rTable.addClass('hidden');
    
    // Build the Labels on the x-Axis
    rTable.find('tbody span').each(function(){
        tableData.xLabels.push($(this).html());
    });
    
    // Get the Values for the y-Axis
    rTable.find('tbody td:last-child').each(function(){
        tableData.yValues.push($(this).html());
        var thisValue = parseFloat($(this).text());
        
        // Find the highest value
        if (thisValue > tableData.topValue) {
            tableData.topValue = thisValue;
        }
        
        // Find the lowest value
        if (thisValue < tableData.bottomValue) {
            tableData.bottomValue = thisValue;            
        }
    });
    
    // Define the total range
    var totalRange = tableData.topValue - tableData.bottomValue;
            
    // Create a new canvas element
    var canvas = $('<canvas></canvas>');
    
    // Give it a width and height
    canvas.attr({
        height: chartHeight,
        width: chartWidth 
    });
    
    // Insert into the DOM
    $('#reader_stats table').after(canvas);
    
    // check if the browser is IE by checking for the excanvas object
    if (typeof(G_vmlCanvasManager) != 'undefined') {
     G_vmlCanvasManager.initElement(canvas[0]);   
    }
    
    // The canvas context object is 2d
    var ctx = canvas[0].getContext('2d');
    
    // Reset the default coordinate start point to the bottom left corner
    ctx.translate(0, chartHeight);
    
    // define the horizontal distance between points on the graph
    var xIncrementAmt = chartWidth/(tableData.xLabels.length -1);
    
    // set the line width in pixels
    ctx.lineWidth = lineSize; 

    // Set the line color
    ctx.strokeStyle = lineColor;    

    // Define the first point on the y-Axis
    var firstPoint =  Math.round((tableData.yValues[0] * realHeight)/tableData.topValue);
   
    // Define incremented value
    var currentXvalue = 0;    
    
    // Begin to draw
    ctx.beginPath();
        
    // Move the pencil to the first data point
    ctx.moveTo(0, -firstPoint);
       
    for (var j=0; j < (tableData.yValues.length); j++) {

        // adjust the point height based on the scale of the map
        var point = Math.round((tableData.yValues[j] * realHeight)/tableData.topValue);

       // Loop through and plot each point
        ctx.lineTo(currentXvalue, -point);
        currentXvalue += xIncrementAmt;

       // Stroke the line
       ctx.stroke();
    }
    
    // Plot the bottom right and bottom left points after the rest of the lines are stroked
    ctx.lineTo(currentXvalue, 0);
    ctx.lineTo(0, 0);
    
    //Done, pick up the pencil
    ctx.closePath();

    // Set the fill color
    ctx.fillStyle = fillColor;
    
    // Set the fill opacity
    ctx.globalAlpha = '.5';
    
    // Fill the shape
    ctx.fill();

    // Build the x-Axis labels
    $(canvas).after('<ol id="weekday" class="group" style="width: '+chartWidth+'px;"></ol>');

    for (var i=0; i < tableData.xLabels.length; i++) {
        // Set the label widths in a percentage
        var labelWidth = 100/(tableData.xLabels.length-1);
        
        // If it's the first or last label, we want half of the normal percentage, so they will line up visually
        if (i === 0 || i == (tableData.xLabels.length)-1) {
            labelWidth = labelWidth/2;   
        }
        
        $('#weekday').append('<li style="text-align: center; width: '+labelWidth+'%">'+tableData.xLabels[i]+'</li>');
    }
    
    // Add a bit of CSS to help align the labels
    $('#weekday li:first-child').css('text-align', 'left');
    $('#weekday li:last-child').css('text-align', 'right');
    
	// ===================================================    
    //*=== Form Validation ===*
    // ===================================================
    
    var contactForm = $('#contact form');
    
    // Validates on blur and submit
    contactForm.validate({
       
        // Disable validation on keyup
        onkeyup: false,
       
        // Set the rules for each field name
        rules: {
            name: {
                required: true,
                minlength: 3
            },
            email: {
                required: true,
                email: true
            },
            comment: {
                required: true,
                minlength: 4
            }
        },
       
        // Set the error messages
        messages: {
            name: 'Please enter your name',
            email: 'Please enter a valid email address',
            comment: 'Your message must be longer than 4 characters'
        },
        
        errorClass: 'error',
        
        // Success behavior                
        success: function(label) {
            label.parent().removeClass('failed').addClass('checked');
            label.addClass('hidden_text valid').text('Valid Entry');
        },
        
        // Error behavior
        highlight: function(element, errorClass) {
            $(element).parent().removeClass('checked').addClass('failed');
        }
                
    });
    
    // On focus, remove any validation messages
    $('#contact input, #contact textarea').focus(function(){
        $(this).parent().removeClass('state failed checked');
        $(this).next().hide();
    });
    
    // ===================================================    
    //*=== Form Submission ===*
    // ===================================================
    
    // modify the form's 'action' attribute to prevent a page jump with JS.
    contactForm.attr('action','/');
    
    $('form button').click(function(){
        var mailCommenter = $('#name').val();
        var mailEmail = $('#email').val();
        var mailSubject = "linesandwaves.com: "+mailCommenter+" sent you a message";
        var mailMessage =  $('#comment').val();
        
        if ($('form div.checked').length == 3) {
            $(this).hide().after('<p id="submit_loader" class="hidden_text">Loading...</p>');
            $.post("../s/email/ajaxMail.php",
               {email: mailEmail, comment: mailMessage, name: mailCommenter },
                function(data){
               contactForm.before('<p id="form_success" style="display: none;">Thanks for your message!</p>');
               $('#form_success').slideDown(500);
               $('#submit_loader').hide().after('<p id="button_success">Nice one!</p>');
            });            
        }
        return false;
    });
    
    // ===================================================    
    //*=== Colorbox: Modal Overlay Effect ===*
    // ===================================================
    
    // The whole point of this roundabout method is to attach some nice transition effects that aren't otherwise possible with Colorbox
    $(".pop, .slides a[rel^='group']").click(function(){
        
        // Grab the attribute values for Colorbox
        var thisHref = $(this).attr('href');
        var thisTitle = $(this).attr('title');
        
        // On click, do a nice fade for the overlay, and then when it's done, call the Colorbox function
        $('#cboxOverlay').hide().fadeIn(400, function(){
            $.fn.colorbox({
                href: thisHref,
                title: thisTitle,
                onClose:function(){
                    $('#cboxOverlay').fadeOut(200);
                }
            });            
        }); 
        return false;
    });
    
});
