/*
========================================
            SLIDING LABELS
========================================
*/
$(function() {

    $('#topburrito').slidinglabels({

        /* these are all optional */
        className: 'form-slider',
        // the class you're wrapping the label & input with -> default = slider
        topPosition: '7px',
        // how far down you want each label to start
        leftPosition: '5px',
        // how far left you want each label to start
        axis: 'x',
        // can take 'x' or 'y' for slide direction
        speed: 'fast' // can take 'fast', 'slow', or a numeric value
    });

});



/*
========================================
                CUFON
========================================
*/





Cufon.set('fontFamily', 'Cambria');

Cufon.replace('.col h2');
Cufon.replace('#slogan');

Cufon.set('fontFamily', 'League Gothic');

Cufon.replace('.machine h1', {
	textShadow: '0px 1px 1px #aaa'

});
	
Cufon.replace('#navigation', {
    color: '#fff',
    hover: {
        color: '#A6CFDD'
    }

});

/*
========================================
              NIVOSLIDER
========================================
*/

$(window).load(function() {


    $('#slider').nivoSlider({
        effect: 'fade',
        // Specify sets like: 'fold,fade,sliceDown'
        slices: 1,
        // For slice animations
        boxCols: 8,
        // For box animations
        boxRows: 4,
        // For box animations
        animSpeed: 700,
        // Slide transition speed
        pauseTime: 10000,
        // How long each slide will show
        startSlide: 0,
        // Set starting Slide (0 index)
        directionNav: false,
        // Next & Prev navigation
        directionNavHide: false,
        // Only show on hover
        controlNav: true,
        // 1,2,3... navigation
        controlNavThumbs: false,
        // Use thumbnails for Control Nav
        controlNavThumbsFromRel: false,
        // Use image rel for thumbs
        controlNavThumbsSearch: '.jpg',
        // Replace this with...
        controlNavThumbsReplace: '_thumb.jpg',
        // ...this in thumb Image src
        keyboardNav: true,
        // Use left & right arrows
        pauseOnHover: true,
        // Stop animation while hovering
        manualAdvance: false,
        // Force manual transitions
        captionOpacity: 1,
        // Universal caption opacity
        prevText: 'Prev',
        // Prev directionNav text
        nextText: 'Next',
        // Next directionNav text
        beforeChange: function() {},
        // Triggers before a slide transition
        afterChange: function() {},
        // Triggers after a slide transition
        slideshowEnd: function() {},
        // Triggers after all slides have been shown
        lastSlide: function() {},
        // Triggers when last slide is shown
        afterLoad: function() {} // Triggers when slider has loaded
    });
});

/*
========================================
                ISOTOPE
========================================
*/

$(window).load(function() {

    $('.machine-burrito').isotope({
        itemSelector: '.machine',
        animationEngine: 'jquery',
        masonry: {
            columnWidth: 1
        }
    });


    $('#filters a').click(function() {
        var selector = $(this).attr('data-filter');
        $('.product-burrito').isotope({
            filter: selector
        });
        return false;
    });

    $(function() {


        var $container = $('.product-burrito');
        $container.isotope({
            itemSelector: '.item',
            filter: '*',
            animationEngine: 'best-available',
            masonry: {
                columnWidth: 1
            },
             animationOptions: {
     		 duration: 500,
    		 easing: 'easeInOutExpo',
    		 queue: false
 			 }
		            
        });

        $('.item').click(function() {
            var $this = $(this),
                tileStyle = $this.hasClass('big') ? {
                    width: 50,
                    height: 50
                } : {
                    width: 170,
                    height: 110
                };
            $this.toggleClass('big');
            $(".isotope-image", this).toggleClass("inception");
            jQuery('.caption', this).delay(500).slideToggle(200);
            $container.isotope('reLayout');

        });

    });


   $('#main').css({
        opacity: 0,
        visibility: 'visible'
    })
    .delay(200).animate({
        opacity: 1
    }, 500);




});



/*
========================================
            FILTER SELECTED
========================================
*/
$(document).ready(function() {


    $('#filters a').click(function() {

        $('#filters a').each(function() {
            $(this).removeClass('selected');
        });

        $(this).addClass('selected');
    });



});

$(document).ready(function() {
    $("#navigation a").currentPage({
        defaultClass: "current",
        indexPage: "index.php",
        anyPath: true
    });
});



/*
========================================
            FANCY SEARCH
========================================
*/

$(function() {
    $('#name').bind('keyup change', function(ev) {
        // pull in the new value
        var searchTerm = $(this).val();

        // remove any old highlighted terms
        $('#main').removeHighlight();

        // disable highlighting if empty
        if ( searchTerm ) {
            // highlight the new term
            
            $('#main').highlight( searchTerm );
        }
    });
});



/*
========================================
                 TWITTER
========================================
*/


JQTWEET = {
     
    // Set twitter username, number of tweets & id/class to append tweets
    user: 'Ajohanco', //AjohanCo
    numTweets: 3,
    appendTo: '#jstwitter',
 
    // core function of jqtweet
    loadTweets: function() {
        $.ajax({
            url: 'http://api.twitter.com/1/statuses/user_timeline.json/',
            type: 'GET',
            dataType: 'jsonp',
            data: {
                screen_name: JQTWEET.user,
                include_rts: true,
                count: JQTWEET.numTweets,
                include_entities: true
            },
            success: function(data, textStatus, xhr) {
 
                 var html = '<div class="tweet">TWEET_TEXT<div class="time">AGO</div>';
         
                 // append tweets into page
                 for (var i = 0; i < data.length; i++) {
                    $(JQTWEET.appendTo).append(
                        html.replace('TWEET_TEXT', JQTWEET.ify.clean(data[i].text) )
                            .replace(/USER/g, data[i].user.screen_name)
                            .replace('AGO', JQTWEET.timeAgo(data[i].created_at) )
                            .replace(/ID/g, data[i].id_str)
                    );
                 }                  
            }   
 
        });
         
    }, 
     
         
    /**
      * relative time calculator FROM TWITTER
      * @param {string} twitter date string returned from Twitter API
      * @return {string} relative time like "2 minutes ago"
      */
    timeAgo: function(dateString) {
        var rightNow = new Date();
        var then = new Date(dateString);
         
        if ($.browser.msie) {
            // IE can't parse these crazy Ruby dates
            then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
        }
 
        var diff = rightNow - then;
 
        var second = 1000,
        minute = second * 60,
        hour = minute * 60,
        day = hour * 24,
        week = day * 7;
 
        if (isNaN(diff) || diff < 0) {
            return ""; // return blank string if unknown
        }
 
        if (diff < second * 2) {
            // within 2 seconds
            return "right now";
        }
 
        if (diff < minute) {
            return Math.floor(diff / second) + " seconds ago";
        }
 
        if (diff < minute * 2) {
            return "about 1 minute ago";
        }
 
        if (diff < hour) {
            return Math.floor(diff / minute) + " minutes ago";
        }
 
        if (diff < hour * 2) {
            return "about 1 hour ago";
        }
 
        if (diff < day) {
            return  Math.floor(diff / hour) + " hours ago";
        }
 
        if (diff > day && diff < day * 2) {
            return "yesterday";
        }
 
        if (diff < day * 365) {
            return Math.floor(diff / day) + " days ago";
        }
 
        else {
            return "over a year ago";
        }
    }, // timeAgo()
     
     
    /**
      * The Twitalinkahashifyer!
      * http://www.dustindiaz.com/basement/ify.html
      * Eg:
      * ify.clean('your tweet text');
      */
    ify:  {
      link: function(tweet) {
        return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) {
          var http = m2.match(/w/) ? 'http://' : '';
          return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
        });
      },
 
      at: function(tweet) {
        return tweet.replace(/\B[@?]([a-zA-Z0-9_]{1,20})/g, function(m, username) {
          return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' + username + '">@' + username + '</a>';
        });
      },
 
      list: function(tweet) {
        return tweet.replace(/\B[@?]([a-zA-Z0-9_]{1,20}\/\w+)/g, function(m, userlist) {
          return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/' + userlist + '">@' + userlist + '</a>';
        });
      },
 
      hash: function(tweet) {
        return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) {
          return before + '<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>';
        });
      },
 
      clean: function(tweet) {
        return this.hash(this.at(this.list(this.link(tweet))));
      }
    } // ify
 
     
};
 
 
 
 
// start jqtweet!
JQTWEET.loadTweets();



/*
========================================
              CONTACT FORM
========================================
*/


$(function(){

    //set global variables and cache DOM elements for reuse later
    var form = $('.col').find('form'),
        formElements = form.find('input[type!="submit"],textarea'),
        formSubmitButton = form.find('[type="submit"]'),
        errorNotice = $('#errors'),
        successNotice = $('#success'),
        loading = $('#loading'),
        errorMessages = {
            
            required: ' is a required field',
            email: 'You have not entered a valid email address for the field',
            minlength: ' must be greater than '
        }
    
    //feature detection + polyfills
    formElements.each(function(){

        //if HTML5 input placeholder attribute is not supported
        if(!Modernizr.input.placeholder){
            var placeholderText = this.getAttribute('placeholder');
            if(placeholderText){
                $(this)
                    .addClass('placeholder-text')
                    .val(placeholderText)
                    .bind('focus',function(){
                        if(this.value == placeholderText){
                            $(this)
                                .val('')
                                .removeClass('placeholder-text');
                        }
                    })
                    .bind('blur',function(){
                        if(this.value == ''){
                            $(this)
                                .val(placeholderText)
                                .addClass('placeholder-text');
                        }
                    });
            }
        }
        
        //if HTML5 input autofocus attribute is not supported
        if(!Modernizr.input.autofocus){
            if(this.getAttribute('autofocus')) this.focus();
        }
        
    });
    
    //to ensure compatibility with HTML5 forms, we have to validate the form on submit button click event rather than form submit event. 
    //An invalid html5 form element will not trigger a form submit.
    formSubmitButton.bind('click',function(){
        var formok = true,
            errors = [];
            
        formElements.each(function(){
            var name = this.name,
                nameUC = name.ucfirst(),
                value = this.value,
                placeholderText = this.getAttribute('placeholder'),
                type = this.getAttribute('type'), //get type old school way
                isRequired = this.getAttribute('required'),
                minLength = this.getAttribute('data-minlength');
            
            //if HTML5 formfields are supported         
            if( (this.validity) && !this.validity.valid ){
                formok = false;
                
                console.log(this.validity);
                
                //if there is a value missing
                if(this.validity.valueMissing){
                    errors.push(nameUC + errorMessages.required);   
                }
                //if this is an email input and it is not valid
                else if(this.validity.typeMismatch && type == 'email'){
                    errors.push(errorMessages.email + nameUC);
                }
                
                this.focus(); //safari does not focus element an invalid element
                return false;
            }
            
            //if this is a required element
            if(isRequired){ 
                //if HTML5 input required attribute is not supported
                if(!Modernizr.input.required){
                    if(value == placeholderText){
                        this.focus();
                        formok = false;
                        errors.push(nameUC + errorMessages.required);
                        return false;
                    }
                }
            }

            //if HTML5 input email input is not supported
            if(type == 'email'){    
                if(!Modernizr.inputtypes.email){ 
                    var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
                    if( !emailRegEx.test(value) ){  
                        this.focus();
                        formok = false;
                        errors.push(errorMessages.email + nameUC);
                        return false;
                    }
                }
            }
            
            //check minimum lengths
            if(minLength){
                if( value.length < parseInt(minLength) ){
                    this.focus();
                    formok = false;
                    errors.push(nameUC + errorMessages.minlength + minLength + ' characters');
                    return false;
                }
            }
        });
        
        //if form is not valid
        if(!formok){
            
            //animate required field notice
            $('#req-field-desc')
                .stop()
                .animate({
                    marginLeft: '+=' + 5
                },150,function(){
                    $(this).animate({
                        marginLeft: '-=' + 5
                    },150);
                });
            
            //show error message 
            showNotice('error',errors);
            
        }
        //if form is valid
        else {
            loading.show();
            $.ajax({
                url: form.attr('action'),
                type: form.attr('method'),
                data: form.serialize(),
                success: function(){
                    showNotice('success');
                    form.get(0).reset();
                    loading.hide();
                }
            });
        }
        
        return false; //this stops submission off the form and also stops browsers showing default error messages
        
    });

    //other misc functions
    function showNotice(type,data)
    {
        if(type == 'error'){
            successNotice.fadeOut('slow');
            errorNotice.find("li[id!='info']").remove();
            for(x in data){
                errorNotice.append('<li>'+data[x]+'</li>'); 
            }
            errorNotice.fadeIn('slow');
        }
        else {
            errorNotice.fadeOut('slow')
            successNotice.show();   
        }
    }
    
    String.prototype.ucfirst = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }
    
});

$('.tooltip-e').tipsy({gravity: 'e', fade: true, delayOut: 1000, opacity:0.8});
$('.tooltip').tipsy({gravity: 'w', fade: true, delayOut: 1000, opacity:0.8});
$('.tooltipdelay').tipsy({gravity: 'w', fade: true, delayIn:200, delayOut: 3500, opacity:0.8});
$('.tooltipdelay-e').tipsy({gravity: 'se', fade: true, delayIn:200, delayOut: 4500, opacity:0.8});

function UpdateTableHeaders() {
    $("#main").each(function() {

        var el = $(this),
            offset = el.offset(),
            scrollTop = $(window).scrollTop(),
            floatingHeader = $(".floatingHeader", this);

            if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
                floatingHeader.css({
                    "visibility": "visible"

                });
                
            } else {
                floatingHeader.css({
                    "visibility": "hidden",
                    "position": "fixed"
                });
            }
    });
}

// DOM Ready
$(function() {

    var clonedRow;

    $("#main").each(function() {
        clonedHeaderRow = $("#filterbox", this);
        clonedHeaderRow.before(clonedHeaderRow.clone()).css("width", clonedHeaderRow.width())
        
        .addClass("floatingHeader");
    });
            

    $(window).scroll(UpdateTableHeaders).trigger("scroll");

});




$('.trigger').hover(function() {
    $(this).next('.employee').fadeIn()
},function() {
    $('.employee').hide()
    $(this).dequeue();
    
});




