/* Author: 

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

	balloons('div[class|="col"] a img');
	
	//send external links to a new window
	$('a.external').click(function() {
		
		window.open($(this).attr('href'));
		return false;
		
	});
	
	//handles background images from clipping when scrolling and resizing
	size 		= $(window).width();
	container = $('.krd_container-flexible').outerWidth(true)
	if(container <= 1100 || size <= 1100) {
		$('.krd_container-flexible').css('overflow', 'hidden')
	}

	if(container <= 480) {
		
		$nav = $('.main-navigation');
		$main = $('.main');
		$main.append($nav);
		
	}
	
	$(window).resize(function() {
		size 		= $(window).width();
		container = $('div[class|="krd_container-flexible"]').outerWidth(true)
		if(container <= 1100 || size <= 1100) {
			$('div[class|="krd_container-flexible"]').css('overflow', 'hidden')
		}
		
		
	});
	
	//load single twitter feed
	if($('.default').length) {
		$('.lower .twitter-feed').twitterFeed(1, 'jaymcinerney');
	}
	
	if($('#media_kit')) {
		
		$('.square').delegate('a.large', 'mouseenter', function() {
			
			$(this).closest('.square').find('a.link').animate({
				opacity:'1.0'
			}, 'fast')
			
		})
		
		$('.square').delegate('a.large', 'mouseleave', function() {
			
			$(this).closest('.square').find('a.link').animate({
				opacity:'0.8'
			}, 'fast')
			
		})
		
	}
	
	if($('div.other').length) {
		
		//make equal heights
		var sqh = 0;
		$('.square').each(function(e) {
		
			thish = $(this).height();
			if( thish > sqh ) {
				
				sqh = thish;
				
			}
			
		});

		//set the heights;
		$('.square').css('min-height', sqh+'px');

	}

	
});

// Validate the form
(function($) {
	
	$.fn.krd_validate = function(a) {
		
		var form = this;
		var error_message = '';
		var status = false;
		var defaults = {};
		var $inputs = $(form+':input');
		var url = a.url;
		$inputs.not('button').after('<span class="error"></span>');
		$($inputs).each(function() {
			defaults[this.name] = $(this).val();
			$(this).focus(function() {
				
				if($(this).val() == defaults[this.name]) {
					$(this).val('')
				}
				
			});
			
			$(this).blur(function() {
				if($(this).val() == '') {
					$(this).val(defaults[this.name])
				}
			})
			
		})
		
		form.submit(function() {
		errors = [];
			$inputs.each(function() {
				
				if($(this).hasClass('required')) {
					status = required(this);
					if(!status) {
						errors[0] = this;
						$(this).next('.error').text('This field needs to be filled out');
					} else {
						$(this).next('.error').text('');
					}
				}
				
				if($(this).hasClass('email')) {
					status = email(this);
					if(!status) {
						errors[0] = this;
						$(this).next('.error').text('Your email is invalid');
					} else {
						$(this).next('.error').text('');
					}
					
				}
				
			});

			if(errors.length == 0) {
				params = $(form).serialize();
				//alert(params)
				$.ajax({
					url: url,
					data: params,
					type: 'post',
					success: function(r) {
						
						$(':input', $(form))
						 .not(':button, :submit, :reset, :hidden')
						 .val('')
						 .removeAttr('checked')
						 .removeAttr('selected');
						
						$(form).append('<span style="font-weight:bold; font-size: 120%" id="thank_you">Thank you</span>');
						$('#thank_you').fadeOut(4000)
						
					}
				})
				//return true;

			}
			return false;
		});
		
		
		
		required = function required(element) {

			if($(element).val() === '' || typeof $(element).val() == null || typeof $(element).val() === 'unidentified' || $(element).val() == defaults[element.name]) {
				error_message = 'Field '+element.name+' is required';
				return false;
			}
			
			return true;
		}
		
		
		email = function email(element) {
			
			pattern = /([aA-zZ0-9.-])+@[aA-zZ0-9-]+(.)[a-z]{3}/;
			regex = new RegExp(pattern);
			text = $(element).val();;
			
			if(!regex.test(text)) {
				
				error_message = 'Your email address is invalid';
				return false;
				
			}
			return true;
			
		}
		
		
	}
	
})(jQuery);


/*
	TwitterFeed jQuery Plugin
	Just read this method support 150 requests per hour.
*/
(function($) {
	
	$.fn.twitterFeed = function(num, account) {
		
		$box		= $(this);
		num_feed = (num === 'undefined' ? 10 : Number(num));
		feed = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name='+account+'&count='+num_feed+'&callback=?';
		result = $.getJSON(feed, function(data) {
			
			var wrapper = '<div class="tweets" style="display:none;"></div>';
			var title = '<strong>Latest Tweet</strong>';
			var items = '';
			tweet = '';
			$.each(data[0], function(i, e) {

				//alert(i)
				if( i === 'created_at') {
					
					created_at = '<small class="created_at">'+e+'</small>';
				}
				
				if( i == 'id_str') {
					
					href = 'https://twitter.com/#!/JayMcInerney/status/'+e;
					id_str = '<a href="'+href+'" class="id_str external">Status</a>';
					
				}
				
				if( i === 'text') {
					text = '<p class="twitter-text">'+e+'</p></div>';

				}
	
				
			});
			inner_text = created_at+text+id_str;
			$box.html(wrapper);
			$('.tweets').html(inner_text)
			$('.twitter-box, .tweets').fadeIn();
			
		})
		
	}
	
})(jQuery);

function krd_3d(ele, o) {
	
	left_shadow = '<div class="left-shadow"></div>'
	bottom_shadow = '<div class="bottom-shadow"></div>';
	depth = (o.depth === 'undefined') ? '10' : o.depth;
	options = {
		
		
		depth: depth,
		side: ['lowerleft', 'topleft', 'topright', 'lowerright']
		
	}
	
	
	$(ele).each( function(i) {
		$(this).append(left_shadow).append(bottom_shadow);
		el_width = $(this).outerWidth(true) - (depth);
		el_height = $(this).outerHeight(true) - (depth);
		//console.log(el_width+' : '+el_height);
		$(this).find('.left-shadow')
				.css({
					
					width: depth+'px',
					height: el_height+'px'
					
		});
		
		$(this).find('.bottom-shadow')
				.css({

					width: el_width+'px',
					height: depth+'px'
					
		});
		
	})
	
}


function balloons(elements) {

	
	$(elements).live({
		
		mouseover: function(e) {
			
			$flag = $(this).find('.flag');
			f_width = $flag.outerWidth(true);
			f_height = $flag.outerHeight(true);
			new_pos = f_height +5;
			$('.arrow').remove();
			$flag
			.append('<div class="arrow"></div>')
			.css({
				display: 'block',
				top: '-'+new_pos+'px',
				left: '45%'
			});
			
			pos = $flag.offset();
			if(pos.top < 0 ) {
				$flag.css('top', '-150px')
			}
			
			
		},
		
		mouseleave: function() {
			
			$(this).find('.flag').css('display', 'none');
			
		}
		
	});
	
}


/*
	Finds paragraphs with a classname provided
	and shortens the display to 50 characters.
	A link is inserted to expand or collapse
	the paragrah
	
	Uses jQueryUI
*/
function truncate(elements, truncate_to) {
	
	this.element = elements;
	
	if( $(this.elements).is('p')) {
		
		//result = single(truncate_to);
		
	} else {
		
		if($(this.element+' p').length) {
			
			//result = collection(truncate_to)
			
		}
		
	}
	
	function collection(truncate_to) {
		
		blob = '';
		html = [];
		
		//$('<a href="javascript" class="more">(show more)</a>').insertAfter(this.element);
		
		$(this.element+' p').each( function(i) {
			
			blob += $(this).text();
			html[i] = $(this).html();
			
		});
		
		words = blob.split(" ");
		num_words = words.length;
		num_p = html.length;
		current = 0;
		if( num_words > truncate_to ) {
			
			for(i=0; i<num_p; i++) {
				
				p = html[i].split(" ");
				
				if(p.length < truncate_to) {
					
					current = p.length;

					
				} else {
					
					p_words = p.length;
					for(e = 0; e < p_words; e++) {
						
						current++;
						if( current == truncate_to ) {
							
							p[e] = p[e]+'<span class="marker"></span>';
							
						}
						
						
					}
					html[i] = '<p>'+p.join(" ")+'</p>';

					
				}
				
			}
			
		}
		
		$final = html.join("");
		$(this.element).html($final);
		$off = $('.marker').offset();

		
	}
	
	function single(truncate_to) {

		$this = $(this);
		text = $this.text();
		
		words = text.split(" ");
		p_length = words.length;
		/*
			test of paragraph has 50 words
		*/

		if(words.length >= truncate_to) {
			
			//get first 50 words
			intro = words.slice(0, (truncate_to - 1));
			the_rest = words.slice(truncate_to, p_length);
			
			/*
				It's not worth viewing unless there something substantial to view
			*/
			if(the_rest.length > 20) {

				intro_text = intro.join(" ");
				all_text = intro_text;
				rest_text = ' <span class="more_text">'+the_rest.join(" ")+'</span> <a href="javascript" class="more">(show more)</a>';
				all_text += rest_text;
				$this.html(all_text);

			}
			
		}
		
		
	}
	
	update = function() {
		
		
		
	}
	
	/*
		Handles the newly created 'more' link
	*/
	$('a.more').click(function() {

		$this = $(this);
		text = $this.text();
		
		if($this.closest('span.more_text').length) {
			
			$this.prev('span.more_text').toggle('blind', function() {
				if(text == '(show more)') {
					$this.text('(show less)');
				} else {
					$this.text('(show more)');
				}
			});
			
		} else {
			
			oh = $this.prev('.truncate').outerHeight();
			$this.prev('.truncate').css({ height: 'auto' });
			nh = $this.prev('.truncate').outerHeight();
			if($this.prev('.truncate').hasClass('full')) {
				$this.prev('.truncate')
					.animate({ height: oh})
					.addClass('excerpt')
					.removeClass('full')
			} else {
				$this.prev('.truncate')
					.animate({ height: nh})
					.addClass('full')
					.removeClass('excerpt')
			}
			
			
		}

		
		
		return false;
	});
	
}

//the navigation plugin
(function($) {
	
	settings = {
		cur_color: '',
		new_color: ''
	};
	
	
	methods = {
		
		init:function(e) {
			
			$(this).delegate('a', 'mouseenter', methods.over);
			$(this).delegate('a', 'mouseleave', methods.out);
			
		},
		
		over: function() {
			
			cur_color = $(this).closest('li').css('background-color');
			$(this).closest('li')
			.not('.youtube')
			.not('.twitter-menu')
			.not('.facebook')
			.stop()
			.animate({
				backgroundColor: $.Color({ alpha: 0.5 })
			})
			
		},
		out: function() {
			$(this).closest('li')
			.stop()
			.animate({
				backgroundColor: cur_color
			})
		}
	}
	
	$.fn.jay_nav = function( method ) {
		
		// Method calling logic
		    if ( methods[method] ) {
		      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		    } else if ( typeof method === 'object' || ! method ) {
		      return methods.init.apply( this, arguments );
		    } else {
		      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
		    }
		
	}
	
})(jQuery);

//displays the Media Kit drop menu
(function($) {
	
	$.fn.show_media = function(target) {
		
		list = target;
		//$(this).append('<div id="large_photo" />');
		$(this).live({
			
			click: function(e) {
				if(!$(e.target).hasClass('file_download')) {
					$(list).stop().slideToggle();
					
				} else {
					return true;
				}
				
				return false;
			}
		});
		
		//handles the image previews
		$(list+' a.file_download').live({
			
			mouseenter: function() {
				
				if($(this).closest('li').find('img').length) {
					$img = $(this).closest('li').find('img');
					$('#large_image').html($img);
				}
				
				
			},
			mouseleave: function() {
				$(this).append($img)
				$('#large_image').html('');
			}
		})

	}
	
})(jQuery);

$('.main-navigation').jay_nav();
$('#media_kit a').show_media('.file_download_list');



