
(function($){
	$(document).ready(function(){

    $('#datacontent').mousemove(function(e){
       var x = e.pageX - this.offsetLeft;
       var halfway = $(this).width() / 2;
       $(this).hover(function(){
         //nothing here, let css hover control movement
       },
       function(){
         if(x < halfway){
           $(this).removeClass('tiltRight').addClass('tiltLeft');
         }
         if(x >= halfway){
           $(this).removeClass('tiltLeft').addClass('tiltRight');
         }         
       });
    });

    $.fn.logoAnimation = function(){
        return this.each(function(){

            // initial state
            var canvas = $('#logo_animation'),
                width = canvas.width(),
                height = canvas.height(),
                c,
                strokeGradient,
                lines = 80,
                length = 0,
                stopLength = 0,
                direction = 1,
                animating;

            var easing = function (t, b, c, d) {
                return -c * ((t=t/d-1)*t*t*t - 1) + b; // easeOutQuart
            };

            var animate = function(e){
                var t = 0;
                clearInterval(animating);
                animating = setInterval(function(){
                    clearCanvas();
                    if (e.type=='mouseover') {
                        length = length>=1 ? 1 : easing(t,0,1,width/2);
                        stopLength = length;
                    } else {
                        length = easing(t,stopLength,-1,width*stopLength);
                        if (length<=0.1) {
                            length = 0;
                            clearInterval(animating);
                            return;
                        }
                    }
                    if (length>0) {
                        c.save();
                        c.scale(length,length);
                        c.rotate(t*2*Math.PI/360);
                        drawLoop();
                        c.restore();
                    }
                    t++;
                },36.67);
            }

            var drawLoop = function(){
                c.save();
                c.drawImage(preCanvas,-width/2,-height/2);
                c.restore();
            }

            var clearCanvas = function(){
                c.save();
                c.setTransform(1, 0, 0, 1, 0, 0);
                c.clearRect(0, 0, width, height);
                c.restore();
            }

            if (canvas.get(0).getContext) {
                c = canvas.get(0).getContext('2d');
                c.translate(width/2,height/2);

                // pre-render the image
                var preCanvas = document.createElement('canvas');
                var preContext = preCanvas.getContext('2d');
                preCanvas.width = width;
                preCanvas.height = height;
                preContext.translate(width/2,height/2);
                strokeGradient = preContext.createRadialGradient(0,0,0,0,0,width/2);
                strokeGradient.addColorStop(0,'rgba(159,0,3,0)');
                strokeGradient.addColorStop(0.75,'rgba(159,0,3,1)');
                strokeGradient.addColorStop(1,'rgba(159,0,3,0)');
                preContext.strokeStyle = strokeGradient;
                for (i=0;i<lines;i++) {
                    preContext.beginPath();
                    preContext.moveTo(0,0);
                    preContext.lineTo(0,-height/2);
                    preContext.closePath();
                    preContext.stroke();
                    preContext.rotate(2*Math.PI/lines);
                }

                // bind to logo
                $(this).children('a').on('mouseover mouseout',animate);
            }

        });
    }

	  
    $('#avatar').logoAnimation();
        
		//external links to open in a new window
    $('a[rel="external"]').attr('target', '_blank').addClass('external');

		//navigation behavior & functionality
	  $('nav').each(function (){
		  var $links = $(this).find('a');
		  var panelIds = $links.map(function(){ 
		    return this.hash; 
		  }).get().join(",");
		  
		  var $panels = $(panelIds);
		  var $panelwrapper = $panels.filter(':first').parent();
		  var delay = 500;
		  var heightOffset = 40; // we could add margin-top + margin-bottom + padding-top + padding-bottom of $panelwrapper
			$panels.hide();
 	    $links.hover(
				function (){
		      if ($(this).is('.selected')) {
		        return false;
		      }
		      $(this).stop().animate({color:"#FFFFFF"}, 500);   
				 },
  			 function(){
		       if ($(this).is('.selected')) {
		        return false;
		       }
		       $(this).stop().animate({color:"#DDDDDD"}, 500);
			  });

				$links.click(function () {   
					var link = this, 
		      $link = $(this);
		      // ignore if already visible
		      if ($link.is('.selected')) {
		        return false;
		      }

					$links.parent().find("span").hide();
		      $links.removeClass('selected').css({"color":"#DDDDDD"});
		      $link.addClass('selected').css({"color": "#FFFFFF"});
					var menuBulletOffset = ($link.parent().width() / 2) - 9; //9pixels is the width of the bullet
					$link.parent().find("span").css("left", menuBulletOffset + "px"); //.css("top", 19 + "px");
					$link.parent().find("span").show();
					
					
		      document.title = 'Larry A. Ball • Web Developer • East Peoria, Illinois • ' + $link.text();

		      if ($.support.opacity) {
		        $panels.stop().animate({opacity: 0 }, delay);
		      }

		      $panelwrapper.stop().animate({height:0}, delay, function(){
		        var height = $panels.hide().filter(link.hash).css('opacity', 1).show().height() + heightOffset;

		        $panelwrapper.animate({
		          height: height
		        }, delay);
		      });
  				if($link.text() == "Blog"){
            window.location = "http://blog.larryaball.net";
  				}

		    });
				
		    $links.filter(window.location.hash ? '[hash=' + window.location.hash + ']' : ':first').click();
        switch (window.location.hash){
          case "#about":
            $('a[href=#about]').click();
            break;
          case "#portfolio":
            $('a[href=#portfolio]').click();
            break;
          case "#contact":
            $('a[href=#contact]').click();
            break;
          case "#social":
            $('a[href=#social]').click();
            break;
          case "#blog":
            $('a[href=#blog]').click();
            break;
        }
		});

    
		//last.fm Music Listening To Page
    // var _config={
    //  username:'redhedded1',
    //  count:8,
    //  period:'3month',
    //  //period: topalbums, recenttracks, 7day, 3month, 6month, 12month, overall, lovedtracks
    //  defaultthumb:'http://cdn.last.fm/flatness/catalogue/noimage/2/default_album_large.png'
    // };
    // lastFmRecords.init(_config);
		
		//animate vinyl
    // $('#lastfmrecords a').append("<span></span>");
    // $('#lastfmrecords a').hover(
    //  function(){
    //    $(this).children("span").stop(true, true).animate({"left": "95px"}, 500);
    //  },
    //  function(){
    //    $(this).children("span").stop(true, true).animate({"left": "38px"}, 500);       
    //  }
    // );
		
//FORM validation
//setup error classes
		$.fn.errorStyle = function() {
		  this.replaceWith(function(i,html){
		      var StyledError = "<div class=\"ui-state-error ui-corner-all\">";
		      StyledError += "<p><span class=\"ui-icon ui-icon-alert\">";
		      StyledError += "</span><span class='errorMsg'>";
		      StyledError += html;
		      StyledError += "</span>";
		      StyledError += "</p></div>";
		      return StyledError;
		   });
		};
		//validation object
		var validateElement = {
			isValid:function(element){
				var isValid = true;
				var $element = $(element);
				var name = $element.attr('name');
				var value = $element.val();
				var id = $element.attr('id');
				var error = "#" + id + "_error";
				// <input> uses type attribute as written in tag
				// <textarea> has intrinsic type of 'textarea'
				// <select> has intrinsic type of 'select-one' or 'select-multiple' 
				// <checkbox> has intrinsic type of 'checkbox'
				var type = $element[0].type.toLowerCase();
				switch(type){
					case 'text':
						if(name == "contactName" ){
						 	isValid = value.length == 0 || value == "Your Name" ? false : true;
						}
						if(name == "contactEmail"){
						 	var pattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
						 	isValid = pattern.test(value);
						}
						break;
					case 'textarea':
						isValid = value.length == 0 || value == "Message" ? false : true;
				} //end switch
				if(!isValid){
					// var errorMsg = $(error).errorStyle();									
					$(error).errorStyle();	
				}
				return isValid;
			} //end isValid method
		}; //end validateElement Object

		//FORM EVENTS OBJECT
		var contact = {
			initEventHandlers: function(){
				//FORM Submit
				$('#submit').bind('click', function(event){
					var valid = true;
					$('#form-message').css({"color":"#444444", "font-family":"Museo700"}).empty().html("<img src='img/bullet.png' alt='' /> All fields are required");
					$('#contactForm input[type=text], #contactForm textarea').each(function(){
						if(!validateElement.isValid($(this))){
							$(this).next('div').css({"visibility":"visible"});							
							valid = false;
						}
					});
					if(!valid){
						event.preventDefault();
						return false;
					}else{
						$('.ui-state-error .ui-corner-all').css({"visibility":"hidden"});
						$('#loader').show();
						// setTimeout('contact.ContactFormSubmit()',500);							
						contact.ContactFormSubmit();
					}
				});
				//FORM behaviors
				$('#contactName').bind('blur', function(){
						if($(this).val() == ""){
							$(this).val("Your Name");
						}
						if(!validateElement.isValid($(this))){
							$(this).next('div').css({"visibility":"visible"});							
						}
				});
				$('#contactName').bind('focus', function(){
						if($(this).val() == "Your Name"){
							$(this).val("");
						}
				});
				$('#contactEmail').bind('blur', function(){
					if($(this).val() == ""){
						$(this).val("Your Email");
					}
					if(!validateElement.isValid($(this))){
						$(this).next('div').css({"visibility":"visible"});							
					}
				});
				$('#contactEmail').bind('focus', function(){
					if($(this).val() == "Your Email"){
						$(this).val("");
					}
				});
				$('#contactMessage').bind('blur', function(){
					if($(this).val() == ""){
						$(this).val("Message");
					}
					if(!validateElement.isValid($(this))){
						$(this).next('div').css({"visibility":"visible"});							
					}
				});
				$('#contactMessage').bind('focus', function(){
					if($(this).val() == "Message"){
						$(this).val("");
					}
				});
				$('#contactForm input[type=text], #contactForm textarea').bind('keydown', function(event){ 
					var keyCode = event.which;
					var excludedKeyCodes = ",9,13,37,38,39,40,";
					var excluded = (excludedKeyCodes.indexOf(',' + keyCode + ',') > -1);
					if (keyCode == 13){  
						$(this).next('div').css({"visibility":"hidden"});
						$('#submit').click();
						return false;
					}
					if(!excluded){
						$(this).next('div').css({"visibility":"hidden"});
					}
				});
			},
			ContactFormSubmit: function(){
				$.ajax({
					   type: 'POST',
					   url: 'scripts/contact.php',
					   dataType: 'json',
					   data	: $('#contactForm').serialize(),
					   success: function(data,textStatus){
									  //hide the ajax loader
									  $('#loader').hide();
									  if(data.result == '1'){
									      //show success message
										  $('#form-message').hide().css({"color":"#960003", "font-family":"Museo700"}).empty().html("<span class='envelope'><img src='img/envelope.png' alt='message sent' /></span> " + data.message).fadeIn("slow");
										  //reset all form fields
									  }else{
											if(data.result == '-1'){
										  	$('#form-message').hide().css({"color":"#960003", "font-family":"Museo700"}).empty().html(data.message).fadeIn("slow");
						 					}
										}
						 },
					   error: function(data,textStatus){
					  	$('#loader').hide();
							$('#form-message').hide().css({"color":"#960003", "font-family":"Museo700"}).empty().html("There was a problem sending your message: " + textStatus).fadeIn("slow");
						 }
				});
			}  
		};
		contact.initEventHandlers();
				
		//call jQuerified tooltip for alt desc on images within links - vtip.js
		vtip();
			
	});
})(jQuery);
