var $ = jQuery.noConflict();

$(document).ready(function() {
    // Placeholders for browsers not supporting the placeholder attribute
    if (!Modernizr.input.placeholder){
        $('[placeholder]').focus(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
                input.removeClass('placeholder');
            }
        }).blur(function() {
            var input = $(this);
            if (input.val() == '' || input.val() == input.attr('placeholder')) {
                input.addClass('placeholder');
                input.val(input.attr('placeholder'));
            }
        }).blur();    
    }
    
    // Variables for transitions
    var homeTransition = ($('input[name=homeTransition]').val() != '' ? $('input[name=homeTransition]').val() : 'scrollLeft');
    var homeTime = Number($('input[name=homeTime]').val() != '' ? $('input[name=homeTime]').val() : 5000); 
    var productTransition = ($('input[name=productTransition]').val() != '' ? $('input[name=productTransition]').val() : 'fade'); 
    var productTime = Number($('input[name=productTime]').val() != '' ? $('input[name=productTime]').val() : 5000); 
    
    // Scroll to top
    $('a[href=#header-wrap]').bind('click', function(e) {
        e.preventDefault();
        $("html, body").animate({ scrollTop: 0 }, "slow");
        return false;
    });
    
    // Notifications
    if ($('.notification').length > 0) {
        $('.notification').slideDown(500, function() {
            var t = setTimeout(function(){$('.notification').slideUp(500)}, 3000);
        });
    }
    
    // Wrap first word of h1 with span for CSS colour
    $('h1').wrapStart(1);
    
    // Home Carousel
    if ($('#image-carousel').length > 0) {
        $('#image-carousel #images').cycle({
            fx: homeTransition,
            timeout: homeTime,
            pager: '#pager',
            after: function(currEle, nextEle, opts, flag) {
                $('a#mask-click').attr('href', ($('a.read-more', $(nextEle)).attr('href')));
            }
        });
        $('#mask-click').css('margin-top', '-420px');
    }
    
    // Question Selector
    if ($('#product-finder').length > 0) {
        $('#product-finder select').bind('change', function() {
            if ($(this).val() != '') {
                window.location.href = $(this).val();
            } 
        });        
    }
    
    // Review Carousel
    if ($('#comment').length > 0) {
        $('#comment').cycle({
            fx: productTransition,
            timeout: productTime,
            cleartype: true,
            cleartypeNoBg: true
        });
    }
    
    // Product Grid
    // Text changes colour when image hovered over too
    $('#products a img').hover(function() {
        // On state
        $('a', $(this).parent().parent().parent()).addClass('hover'); 
    }, function() {
        // Off state
        $('a', $(this).parent().parent().parent()).removeClass('hover');    
    });
    
    // Product Pager
    $('ul#product-thumbnails li a').bind('click', function(e) {
        e.preventDefault();
        $('a', $(this).parent().parent()).removeClass('selected');
        $('#product-image p a').attr('href', $(this).attr('rel'));
        $('#product-image p a img.wp-post-image').attr('src', $(this).attr('href'));
        $(this).addClass('selected');
    });
    $('#product-pager a').bind('click', function(e) {
        e.preventDefault();
        
        var action = $(this).attr('class');
        var totalImages = Number($('ul#product-thumbnails li').length);
        var currentImageClass = $('ul#product-thumbnails li a.selected').attr('class').split(' ')[0];
        var currentImageID = currentImageClass.split('-')[1];

        // Define next / previous image to display
        // Cannot use switch as may have IE specific classes on anchor element
        if (action.search('next') > -1) {
            var newImageID = (currentImageID == (totalImages-1)) ? 0 : (Number(currentImageID) + 1); 
        } else if (action.search('prev') > -1) {
            var newImageID = (currentImageID == 0) ? Number(totalImages-1) : (Number(currentImageID) - 1); 
        } else {
            return false;
        }

        var newImageURL = $('ul#product-thumbnails li a.image-'+newImageID).attr('href');
        var newImageLightboxURL = $('ul#product-thumbnails li a.image-'+newImageID).attr('rel');

        $('ul#product-thumbnails li a').removeClass('selected');
        $('#product-image p a').attr('href', newImageLightboxURL);
        $('#product-image p a img.wp-post-image').attr('src', newImageURL);
        $('ul#product-thumbnails li a.image-'+newImageID).addClass('selected');
    });
        
    // Image Map
    $('.room').hide(); // Hide articles
    $('.room a[href=#house]').hide(); // Hide Back to Top links
    $('#cleaning-tips area').click(function(e) {
        e.preventDefault(); 
        
        // Calculate size of overlay box.  We need left + top margin, and width + height of overlay box
        var title = $(this).attr('alt');
        var coords = $(this).attr('coords').split(','); 
        var marginLeft = Number($.trim(coords[0]));
        var marginTop = Number($.trim(coords[1])); 
        var width = Number($.trim(coords[2]) - marginLeft);
        var height = Number($.trim(coords[5]) - marginTop);

        // Update display to reflect clicked area of map
        $('.room').hide(); // Hide articles
        $('#room-'+$(this).attr('id')).show(); // Show article
        $('#house-map-highlight').css('margin-top', marginTop+'px');
        $('#house-map-highlight').css('margin-left', marginLeft+'px');
        $('#house-map-highlight').css('width', width+'px');
        $('#house-map-highlight').css('height', height+'px');
        $('#house-map-highlight').css('line-height', height+'px');
        if ($(this).attr('id') == 'study' || $(this).attr('id') == 'bathroom' || $(this).attr('id') == 'kids-bedroom') {
            $('#house-map-highlight').css('font-size', '1.2em'); // Smaller font for study or bathroom 
        } else {
            $('#house-map-highlight').css('font-size', '2.2em'); // Already defined in CSS, but need to reset as not on study or bathroom 
        }
        $('#house-map-highlight').html(title); // Set title
        $('#house-map-highlight').show(); 
    });
    
    // Youtube Flash fix for fixed header / iframes with flash content
    $('iframe').each(function() {
        var url = $(this).attr('src');
        $(this).attr('src', url+'?wmode=transparent');
    });
	
    // Lightbox
    if (typeof lbox_img_opts !== 'undefined') {
        $('a[rel=lightbox]').lightbox(lbox_img_opts);
    }
	
	//Ajax comment submission
    $("#commentform").submit(function (e) {
        e.preventDefault();

        //Check length of comment first
        if ($("#commentform textarea[name=comment]").val().length > 190) {
            alert("Sorry, your comment is too long, please keep it to 190 characters");
            return;
        }

        $.post($("#commentform").attr("action"), $("#commentform").serialize())
        .success(function () {
            $("#commentform").html('<p class="commentThanks">Thanks for your feedback honey, my worker bees will review and upload your comments as soon as possible. Eric x</p>');
        })
        .error(function () {
            alert("Error: please fill the required fields (name, email).");
        });
    });

    /*count review characters*/
    $("#commentform textarea[name=comment]").keyup(function () {
        var count = $(this).val().length;

        $("#char-count").html(count);

        if (count > 190) {
            $(this).addClass("review-too-long");
        } else {
            $(this).removeClass("review-too-long");
        }
    });
	
	//End of doc(ready)
});

$.fn.wrapStart = function (numWords) { 
    var node = this.contents().filter(function () { 
            return this.nodeType == 3 
        }).first(),
        text = node.text(),
        first = text.split(" ", numWords).join(" ");

    if (!node.length)
        return;

    node[0].nodeValue = text.slice(first.length);
    node.before('<span>' + first + '</span>');
};
