var timerSpeed = 4000;

function imgItem(item, inGallery) {
    var snippet = '<img src="' + item.attr('href') + '" alt="' + item.text() + '" class="sample';
    if (inGallery) {
        snippet += ' cycle';
    }
    snippet += '" style="display:none"/>';

    return snippet;
};

function expandByURL(url) {
    var anchor = $('a[href="' + url +'"]', '#side .nav');
    $(anchor.parents('ul')[0]).slideDown();
    $(anchor.parents('li')[1]).find('.header').addClass('active');
    anchor.addClass('active');
    
}

function updateCounter(gallery, current, total) {
    $('#counter .gallery').text(gallery);
    $('#counter .current').text(current + 1);
    $('#counter .total').text(total + 1);
    $('#counter').fadeIn();
}

function drawSample(anchor, inGallery) {
    var featured = $('#featured').fadeOut('fast', function() {

    var display = jQuery('#samples');
	display.show()
	
    if (anchor.hasClass('gallery')) { // setup basic carousel
        var galleryName = anchor.attr('class').split(' ')[1]; // what gallery are we working with?
		
		anchor = $('a[href="' + anchor.attr('href') +'"]', '#side .nav');
		
        var list = $('.' + galleryName, '#side .nav');
        var length = list.length - 1; // 0-based indexes
        var index = list.index(anchor);
        var first = $(list[0]);
        var next = (index < length) ? (list.eq(index + 1)) : (first);

        updateCounter(first.text(), index, length);

        display.html(imgItem(anchor, true));
        $('#content .sample').click(function (e) {
            drawSample(next);
            e.preventDefault();
        });
    } else {
        anchor = $('a[href="' + anchor.attr('href') +'"]', '#side .nav');
        updateCounter(anchor.text(), 0, 0);
        display.html(imgItem(anchor));
    }

	jQuery('#content .sample').fadeIn();
	});
    return jQuery('#content .sample');
}

$(document).ready(function () {

	/* Handle left-hand nav */

    // hide all sub heading lists
    $('#side .nav li ul').hide();

    // add a click handler to the heading links
    $('#side .nav .header').click(function (e) {
        var header = $(this);
        // if the current sub heading list is already open		
        if (header.next('ul:visible').length) {
            // close the sub heading list
            header.next('ul:visible').slideUp();
            header.removeClass('active');
        } else {
            $('#side ul li a').removeClass('active');
            // close all open sub heading lists
            $('#side .nav li ul:visible').slideUp();
            // slide open the next list
            header.next('ul').slideToggle();
            header.addClass('active');
        }

        // return false to stop link following the href
        e.preventDefault();
    });

    $('#side .nav ul li a, #featured .image_reel a').live('click', function (e) {
        var anchor = $(this);
        var header = $(anchor.parents('li')[1]).find('.header');

        drawSample(anchor); // draw image
        // highlight nav
        $('#side .nav ul li a').removeClass('active');
        anchor.addClass('active');
        
        expandByURL(anchor.attr('href'));

        e.preventDefault();
    });

    /* Handle the form */

    var contact = $('#contact');
    var button = contact.find('button');
    var fields = contact.find('input[name!="sweetness"], textarea');

    function validateField(field) {
        var status = false;

        if (field.hasClass('email')) {
            reg = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
            if (!reg.test(field.val())) {
                status = true;
            }
        } else {
            var reg = /^$/
            if (reg.test(field.val())) {
                status = true;
            }
        }

        return status;
    }

    function errorDisplay(field) {
        var pos = field.position();
        var msg = field.next('.msg');
        var errorStatus = false;

        if (validateField(field)) {
            field.addClass('error');
            msg.css({
                'top': Math.round(pos.top - msg.height() / 1.4),
                'left': Math.round(pos.left + field.width() * .8)
            }).fadeIn('fast');
        } else {
            if (field.hasClass('error')) {
                msg.fadeOut('fast');
                field.removeClass('error');
            }
            errorStatus = true;
        }
        return errorStatus;
    }

    function checkForm() {
        var errorCount = 0;
        var checkStatus = false;

        // Cycle through each field, validate, show errors as needed
        $.each(fields, function () {
            if (!errorDisplay($(this))) {
                errorCount++;
            }
        });

        if (errorCount == 0) {
            checkStatus = true;
        }

        return checkStatus;
    }

    // Set up blur error checking
    $.each(fields, function () {
        var field = $(this);

        field.blur(function () {
            errorDisplay(field);
            if (contact.find('.error').length == 0) {
                button.text('Send');
            }
        })
    });

    contact.submit(function (e) {
        e.preventDefault();

        button.text('Sending...');
        var formStatus = checkForm();

        if (formStatus) {
            $.post('email.php', contact.serialize(), function (data) {
                if (data.trim() == 'true') {
                    contact.fadeOut('fast');
                    $('#success-msg').fadeIn('fast');
                } else {
                    checkForm();
                }
            });
        } else {
            button.text("Can't Send");
        }
    }); // end submit
	
	/* Handle Feature Display */
	$('#logo').click(function(e){
		$('#side .nav li ul:visible').slideUp();
		$('#side .nav .active').removeClass('active');
		$('#samples').fadeOut(function(){
			$('#featured').show();
		});
        $('#counter').fadeOut();
		e.preventDefault();
	});
	
    /* Featured Content */
    //Show the paging and activate its first link
    $(".paging").show();
    $(".paging a:first").addClass("active");

    //Get size of the image, how many images there are, then determin the size of the image reel.
    var imageWidth = $(".window").width();
    var imageSum = $(".image_reel img").size();
    var imageReelWidth = imageWidth * imageSum;

    //Adjust the image reel to its new size
    $(".image_reel").css({
        'width': imageReelWidth
    });

    //Paging  and Slider Function
    rotate = function () {
        var triggerID = $active.attr("rel") - 1; //Get number of times to slide
        var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide
        $(".paging a").removeClass('active'); //Remove all active class
        $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
        //Slider Animation
        $(".image_reel").animate({
            left: -image_reelPosition
        }, 500);

    };

    //Rotation  and Timing Event
    rotateSwitch = function () {
        play = setInterval(function () { //Set timer - this will repeat itself every 7 seconds
            $active = $('.paging a.active').next(); //Move to the next paging
            if ($active.length === 0) { //If paging reaches the end...
                $active = $('.paging a:first'); //go back to first
            }
            rotate(); //Trigger the paging and slider function
        }, timerSpeed); //Timer speed in milliseconds (7 seconds)
    };

    //rotateSwitch(); //Run function on launch
    //On Hover
    $(".image_reel a").hover(function () {
        clearInterval(play); //Stop the rotation
    }, function () {
        rotateSwitch(); //Resume rotation timer
    });

    //On Click
    $(".paging a").click(function () {
        $active = $(this); //Activate the clicked paging
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(); // Resume rotation timer
        return false; //Prevent browser jump to link anchor
    });

});
