/* ----------------------------------------------------------------------------
Author: Sketchworks, Inc.
Description: Global PatTheRoc.com JavaScript functions
-------------------------------------------------------------------------------
jQuery is used in noConflict mode
-------------------------------------------------------------------------------
The library is namespaced into the PATROC object.
Mainly is built on Singleton and split in different *Managers* each for
every main functionality

Singleton structure
var myInstance = (function() {
  var privateVar = '';
  
  function privateMethod () {
    // ...
  }

  return { // public interface
    publicMethod1: function () {
      // all private members are accesible here
    },
    publicMethod2: function () {
    }
  };
}());

*/

//wrap code in a closure to allow use of $ (for variables that are objects)
(function ($) {
    
    //create PATROC namspace if not already defined
    window.PATROC = window.PATROC || {};
		
		//set DOM global vars
		var loading = false;
    
   		PATROC.Loader = (function () {
   		    var self = {};
   		    
   		    self.show = function () {
   		    	if (loading = true) {
   		       		$('body').append('<div class="loader"><img src="/images/loading-spinner.gif" alt="Loading" /></div>');
   		    	}
   		    
   		    }
   		    
   		    self.hide = function () {
   		        $('.loader').remove();
   		    }
   		return self;
   		} ());
   		
   		PATROC.MovesManager = (function () {
   		    var self = {};
   		    
   		    self.init = function() {
   		    	
				//hover effect on hotspots for moves
   		    	$('#moves-home a.hotspot').hover(function(){
   		    	         PATROC.AnimationManager.fadeTo($(this).next(),0.6,50,0);
   		    	},function(){
   		    	         PATROC.AnimationManager.fadeTo($(this).next(),1,50,0);
   		    	});

   		    }
   		    
   		    self.showMove = function(movename) {
   		    	//alert('show '+movename);
   		    	
   		    	var selectedDiv = '#move-'+ movename;
   		    	var views;
   		    	var selectedDiv;
   		    	var selectedIndex;
   		    	var prevIndex;
   		    	var movesPanelLoaded = false;
   		    	
   		    	loading = true;
	    		
	    		$modal = $('<div class="modal"></div>');
	    		$('#section-moves .content-main').append($modal);
	    		
	    		//build content
	    		$container = $('<div class="modal-content" id="moves-modal">' +
	    							'<a id="modal-arrow-left"></a>' +
	    							'<a id="modal-arrow-right"></a>' +
	    							'<a class="close sitebackbutton">Moves</a>' +
	    						'</div>');
	    		$('.modal').append($container);
	    		
	    		
	    		$.get('moves.php', function(data) {
	    		
	    			//append moves.php file to div
	    		  	$('.modal-content').append(data);
	    		  	setupViewPanel();  	
  	
	    		});
	    		
	    		function setupViewPanel() {
	    		
	    			//get all views
	    			views = $('#moves-modal .modal-view').map(function () {
	    			    return '#'+$(this).attr('id');
	    			});
	    				    
	    			
	    			selectedDiv = '#move-'+ movename;				
	    			selectedIndex = jQuery.inArray(selectedDiv, views);
	    			prevIndex = selectedIndex;
	    			loading = true;
	    			
	    			//fade in modal wrapper,show first view, and update the controls
	    			
	    			PATROC.AnimationManager.fadeTo('.modal',1,800,0,function() {
	    				loadView(selectedIndex);
	    				updateControls();
	    				movesPanelLoaded = true;
	    			});
			
	    		
	    		
   		    	}
   		    	
				function loadView(index) {
					
						function showView (index) {
							loading = true;
							//setTimeout('PATROC.Loader.show()', 1000);
							
							PATROC.AnimationManager.fadeTo(views[index],1,800,0,function(){
								updateControls();
								prevIndex = index;
								loading = false;
								//PATROC.Loader.hide();
							});						
						}
						
						if (prevIndex != selectedIndex) {
							PATROC.AnimationManager.fadeTo(views[prevIndex],0,500,0,function(){
								showView(index);
							});
						} else {
							showView(index);
						}
						
						loading = false;

					}
	    			
					
					//update controls
					function updateControls() {
					  $(selectedDiv+' .selected').removeClass('active');
					  $(selectedDiv).addClass('active');
					}
					
					//back/forward
					function back() {
						if (!loading) {
							selectedIndex = selectedIndex - 1;
							if (selectedIndex < 0) {
								selectedIndex = views.length - 1;
							}
							loadView(selectedIndex);
							//change url
							return false;
						}
					}
					
					function forward() {
						if (!loading) {	
							selectedIndex = selectedIndex + 1;
							if (selectedIndex >= views.length) {
								selectedIndex = 0;
							}
							//alert(selectedIndex);
							loadView(selectedIndex);						
							return false;
						}
					}
					
					//back/forward buttons
					$('#modal-arrow-left').bind('click',function(e){
						e.preventDefault();						
						back();				
					}); 
					
					$('#modal-arrow-right').bind('click',function(e){
						e.preventDefault();
						forward();
							
					});        		
					
					//close button
					$('#moves-modal .close').click(self.close);
   		    	
   		    }

		    //close modal
	        self.close = function () {
					
 				PATROC.AnimationManager.fadeTo($('.modal'), 0, 400, 0, function () {
 					
 				    $('.modal').remove();
 				    $('.modal-view').remove(); 				    

 				});
 				
 				PATROC.URLManager.goToURL('/moves/');
 				
 				return false;

	        }
    
   		    
   		    //reset function
   		    
   		    
   		    
   			return self;
   		} ());
   		
   		PATROC.BlogManager = (function () {
   		    var self = {};
			var startIndex;
			var maxCount;
   		    
   		    //init function
   		    self.init = function () {

				startIndex = 10;
				maxCount = 10;
	
   		    	//set #section-blog div to be the length of two browser widths
   		    	var browserWidth = $(window).width();
   		    	var panelWidth = browserWidth * 2;
   		    	
   		    	$('#section-blog').css('width',panelWidth+'px'); 
   		    	
   		    	//set each child div to be half of section-blog
   		    	$('#blog-home,#blog-article').css('width',browserWidth+'px')
   		    	
   		    	//move blog article 100% to the right
   		    	$('#blog-article').css('left',browserWidth+'px');


				//scroll event
				$('#blog-home').scroll(function() {
					
					//alert('hey');
					var curScroll = $(this)[0].scrollTop;
        			var maxScroll = $(this)[0].scrollHeight - $(this).height();
					
					//check if at bottom
					if( (curScroll == maxScroll) && loading == false ) {

						//set loading true
						loading = true;

						// add loading box
						//$('body').append('<div class="loading">Loading!!!!</div>');

						//scroll to bottom of div
						$(this)[0].scrollTop = maxScroll;

						// load more
						self.loadMoreArticles(startIndex, maxCount, function(){
							startIndex += maxCount;
						});
						
						

					}
  		    
				});	

   		    }
   		    
   		    self.showSocial = function (permalink, title){


				function showButtons() {
					$.get("wordpress/wp-content/themes/pattheroc/share.php",{'permalink':permalink,'title':title},
					function(data){
						$('.share-buttons').each(function(index) {
						    $(this).append(data);
		
						});
					});
				
				}
				
				//delay showing buttons to give page time to animate/load
				window.setTimeout(showButtons, 1500); 
				
   		    }
   		    
   		    self.showBlogArticle = function (slug) {
   		    
   		    	var showDiv = '#blog-content';
   		    	var postslug = slug;
   		    	
   		    	$(showDiv).empty();
   		    	
   		    	$.get('wordpress/'+postslug, function(data) {
    				   				
    				$(showDiv).html(data);
 
    				$(element).animate({
    						scrollTop: $('#blog-article').offset().top,
    						scrollLeft: $('#blog-article').offset().left
    					}, 800, function() {	
							
							//why is this firing twice?
							
							//get rid of default image links created by wordpress
							$('img[class*="wp-image"]').each(function(index) {
								$(this).parent().replaceWith($(this).parent().html());
							});
							
							//set all links to open in new window
							$('#blog-content .post a').attr('target', '_blank');
    					   
    				}); 

    	  		});
   		    	  		
   		    }
   		    
			self.loadMoreArticles = function (startIndex, maxCount, callback) {
					loading = true;

			   		$.get("/includes/post_loader.php",{'posts_per_page':maxCount,'offset':startIndex},
			   			function(data) {
							    $('#blog-listing').append(data);
								
					});

					//kill loading stuff
					loading = false;
					$('.loading').remove();
					
					callback();
					
					

	       	}

   			return self;
   		} ());
   		
   		
        PATROC.FormManager = (function () {
            var self = {};
            

            self.init = function () {
            
				// contact form
				var $contactForm = $('#contact-form');
				$contactForm.submit(function(e) {
					e.preventDefault();
				});
	            	
				$contactForm.validate({
					submitHandler: function(form) {
						var str = $contactForm.serializeArray();
						$contactForm.fadeOut('slow', function() {
							PATROC.Loader.show();
							$contactForm.load('/includes/do.contactform.php', str, function() {
								//hide loader
								PATROC.Loader.hide();
								$contactForm.fadeIn('slow');
							});
						});
					}
				});
				

            	// newsletter form validation     				
        		var $newsletterForm = $('#subscribe-form');
        		
        		$newsletterForm.submit(function(e) {
        		    e.preventDefault();
        		});
        		
        		$newsletterForm.validate({
        			submitHandler: function(form) {
        				var str = $newsletterForm.serializeArray();
        				$newsletterForm.fadeOut('slow', function() {
        					$newsletterForm.load('/includes/do.newsletter.php', str, function() {
        						$newsletterForm.fadeIn('slow');
        					});
        				});
        			}
        		});
        		
        		if(PATROC.DeviceManager.isIE()) {
					//make HTML5 placeholders work in non supportive browsers
					$("input[placeholder], textarea[placeholder]").each(function(){
						if($(this).val()==""){
						 // $(this).addClass('hasplaceholder');
						  $(this).val($(this).attr("placeholder"));
						  $(this).focus(function(){
						    if($(this).val()==$(this).attr("placeholder")) $(this).val("");
						   // $(this).removeClass('hasplaceholder');
						  });
						  $(this).blur(function(){
						    if($(this).val()==""){
						  // $(this).addClass('hasplaceholder');
						       $(this).val($(this).attr("placeholder"));
						    }
						   });
						}
					});
					
					$('form').submit(function(evt){
						$('input[placeholder]').each(function(){
							if($(this).attr("placeholder") == $(this).val()) {$(this).val('');}
						});
					});
        		}
			}
			
        	return self;
        } ());
        
        PATROC.VideoManager = (function () {
        	var self = {};        	
        	var startIndex = 1;
        	
        	self.loadVideos = function (startIndex, maxCount, callback) {
        		loading = true;        		
        		var items = [];
        				
        		$.getJSON('https://gdata.youtube.com/feeds/api/users/pattheroctv/uploads?v=2&alt=jsonc&v=2&max-results='+maxCount+'&start-index='+startIndex+'&callback=?',
        			function(data) {

        				$.each(data.data.items, function() {
							items.push({
							    title: this.title, 
							    id:  this.id,
							    thumbnail: this.thumbnail.hqDefault,
							    code: '<object>'+
							    '<param name="movie" value="http://www.youtube.com/v/'+this.id+'?version=3&rel=0&border=0&showinfo=0"></param>'+
							    '<param name="allowscriptaccess" value="always"></param>'+
							    '<param name="wmode" value="transparent"></param>'+
							    '<embed src="http://www.youtube.com/v/'+this.id+'?version=3&rel=0&border=0&showinfo=0" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" wmode="transparent"></embed>'+
							    '</object>'
							 });
        				});
        				
        			//console.log(items);
    				callback(items);
        		
        		});
        		
        		
        	
        	}
        	
        	self.showVideos = function () {
        	
        		var maxCount = 5;       		
        		self.loadVideos(startIndex,maxCount,function(data) {
          			var items = data;
        			$.each(items, function() { 
        				$('#video-listing').append( '<li><h2 class="video-title">'+this.title+'</h2>'+
        							'<div class="video-player">'+this.code+'</div></li>'
        				);
        			});
        			        			
        			startIndex += maxCount;

        			//kill loading stuff
        			loading = false;
        			$('.loading').remove();
        		});
        		
        	}
        	
        	self.showHomeVideos = function () {
        	
        		var maxCount = 1;
        		self.loadVideos(startIndex,maxCount,function(data) {
        			var items = data;
        			$.each(items, function() { 
        				$('#home-latest-video').append( '<h3 class="video-title"><a href="/videos/" class="internal">'+this.title+'</a></h3>'+
        							'<a href="/videos/" class="video-thumb internal"><img src="'+this.thumbnail+'"></a>'
        				);
        			});
        		});
        	}
        	

        	self.init = function () {
        	        	
				self.showHomeVideos();				
				self.showVideos();

        		//scroll event
        		$('#section-videos').scroll(function() {
        		
        			var curScroll = $(this)[0].scrollTop;
        			var maxScroll = $(this)[0].scrollHeight - $(this).height();
        			
        			//check if at bottom
        			if( (curScroll == maxScroll) && loading == false ) {
        				
        				//set loading true
        				loading = true;
        				
        				// add loading box
        				$('body').append('<div class="loading">Loading!!!!</div>');
        				
        				//scroll to bottom of div
        				$(this)[0].scrollTop = maxScroll;
        				
        				// load more
        				self.showVideos();
        			
        			}
        		
        		});
        	
        		
        		
        	}
        	        	
        	
        	return self;
        } ());
        
        PATROC.AnimationManager = (function () {
            var self = {};
            //jquery animations
            self.fadeTo = function (element, opacity, duration, delay, callback) {
                $(element).delay(delay).fadeTo(duration, opacity, function () {
                    // need to remove filter on IE. Also opacity style goes from 0 to 1 even if in ie is from 0 to 100
                    if (opacity === 0) {
                        $(this).hide().css({ 'opacity': '', 'filter': '' });
                    }
                    if (opacity === 1) {
                        $(this).show().css({ 'opacity': '', 'filter': '' });
                    }
                    if (typeof callback !== 'undefined') {
                        callback.call(this)
                    }
                });
            }
        return self;
        } ());
    
   
		
		PATROC.URLManager = (function () {
			var self = {};
			var	oldHash;
			
			self.goToURL = function (location, withTransition) {

				element = 'html, body';
				var location;
				var withTransition;
				
				if (!withTransition) {
					withTransition = true;
				}
				
				if (!location) {
					location = document.location.href;
				}
				
				location = location.replace(/^http:\/\/[^\/]+/, '').replace(/\/?#/, ''); //strip url
				
		   		if (location.match(/^\/?$/) ||
		   		    location.match(/^\/profile\b/i) ||
		   		    location.match(/^\/blog\b/i) ||
		   		    location.match(/^\/videos\b/i) ||
		   		    location.match(/^\/moves\b/i) ||
		   		    location.match(/^\/contact\b/i) ||
		   		    location.match(/^\/subscribe\b/i)) {	
		   		    	hash = location.replace(/^\/([a-z0-9\-\_]+)(\/[a-z0-9\-\_]+)?\/?/i, '#section-$1'); //convert to hash
		   		    	//alert(hash);
			 			if (!location.match(/^\/#.*$/)) {
			 				if(location.match(/^\/?$/)) {
			 					//specialize treatment for home page
			 					location = '/#/';
			 					hash = '#section-home';
			 				}
			 				
			 			// if doesn't have correct url structure, lets correct it
						location = location.replace(/^\/([a-z0-9\-\_]+\/?)([a-z0-9\-\_]+\/?)?([a-z0-9\-\_]+\/?)?$/i, '/#/$1$2$3');
						
						//if doesn't have last slash, add it
						if (!location.match(/\/$/i)) {
							location = location+'/';
						}
					}
					
					//if moves deep link is requested
					if (location.match(/\/moves\/[a-z]+\/?$/i)) {
					
						var movename = location.replace(/^\/#\/moves\/([a-z0-9\-\_]+)?\/?$/i, '$1');
						PATROC.MovesManager.showMove(movename);
						
					} 
					
					//if blog deep link is requested
					else if (location.match(/\/blog\/[a-z0-9\-\_]+\/?$/i)) {
						
						var post_slug = location.replace(/^\/#\/blog\/([a-z0-9\-\_]+)?\/?$/i, '$1');
						PATROC.BlogManager.showBlogArticle(post_slug);
						
					} else {
					
					//update GAnalytics with new hre
					_gaq.push(['_trackPageview', location]);		
					
					$(hash).css({'overflow-y':'auto'}); //show scrollbar
					
					if (withTransition && !PATROC.DeviceManager.isIE()) {
						
					//what to do if transition is set to true AND if the browser is NOT IE
					   $(element).animate({
					   			scrollTop: $(hash).offset().top,
					   			scrollLeft: $(hash).offset().left
					   		}, 800, function() {	

					   	}); 
					} else {
						
						
						if (oldHash && (oldHash != hash)) {
							
							$(hash).show();
												
							PATROC.AnimationManager.fadeTo(oldHash,0,800,0,function(){
							
								//PATROC.AnimationManager.fadeTo(hash,0,800,0);
								$(hash).css({'opacity':'0'}); //ie can't use hide() so must change opacity
								$(element).scrollTop($(hash).offset().top);
								$(element).scrollLeft($(hash).offset().left);
								
								
								PATROC.AnimationManager.fadeTo(hash,1,1000,0,function() {
									$(hash).css({'overflow-y':'auto'}); //show scrollbar
									$(oldHash).hide();
									oldHash = hash;
								});	
							
							});
							
						} else {
							
							$(hash).css({'opacity':'0'}); //ie can't use hide() so must change opacity
							$(element).scrollTop($(hash).offset().top);
							$(element).scrollLeft($(hash).offset().left);	
										
							PATROC.AnimationManager.fadeTo(hash,1,1500,0,function() {		
								oldHash = hash;
												
							});	
						}
						
						
						
						
					}
					
					
					
					//set nav link to active					
					var clicker = hash.replace(/^#[section]+[\-]([a-z]+)/, '#gn-$1');
					$('#global-nav li').each(function(index) {
					    $(this).removeClass('active');
					  });
					$(clicker).addClass('active');
					   
				   //reset page to clear modals if any open
				   //PATROC.PageManager.reset();
					   
		   		}
		   		
		   		}
		   		
		   		document.location.href = location;
	   			
			};
			
			self.init = function () {
			
				// add internal class to all internal links
				$('a:not([href^="http://"]), a[href*="pattheroc.com"]').addClass("internal");
			
				//bind click events to buttons
				$('a.internal').live('click', function (event) {
					event.preventDefault();
					var link = $(this).attr('href');   				
					//start transition
					PATROC.URLManager.goToURL(link, true);	
				});

				self.goToURL();
				
				//if URL in browser is changed manually / disable in IE to prevent duplicate fires
				/* might not need this, lets check in IE first 
				
				if (!PATROC.DeviceManager.isIE()) {
					window.onhashchange = function() {
					//alert(document.location.href);
						self.goToURL(false,true);
					}
				}*/
				
				//add site credits to bottom of every section
				
				//TURNED OFF BECAUSE IT WAS ADDING ADDITION BOTTOM PADDING TO VIDEOS PAGE
				
				/*
				$.each($('div[id^="section-"] .content-main'), function() {
					$(this).append('<div class="site-credits">Website Designed by <a href="http://www.sketchworkspro.com" title="Sketchworks - Interactive Marketing Agency">Sketchworks</a></div>');
				});*/
			};
			
			return self;
			
		}());
   
        
    PATROC.PageManager = (function () {
    	
    	Sliders = (function () {
    	    	var self = {};
    	
    	   		self.init = function () {
    	   			
    	   			
    	   			var $sliders = $('div[id$="-slider"]');
    	   			
    	   			//convert all text links to real URLS  
    	   			var textareas = $sliders.find('p.message');    	   			  	   			
    	   			var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; 
    	   			var tweetexp = /\@([a-z]+)/ig; 
    	   			
    	   			$.each(textareas,function(){
    	   				var text = $(this).text();
    	   				text = text.replace(exp,'<a href="$1" target="_blank">$1</a>');    	   			   	   			
    	   				text = text.replace(tweetexp,'<a href="http://twitter.com/$1" target="_blank">@$1</a>');
    	   				$(this).html(text);
    	   			});
    	   			
    	   			$sliders.each(function (i) {
    		   			      
    	   			      	var $slider = $(this);
    	   			      	var trigger = $slider.attr('id').replace(/-[slider]+$/,'');
    	   			      	var $trigger = $('#socialmedia-nav #sm-'+trigger+' a');
    	   			      	var height = $slider.height();
    	   			      	var startPos = - (height + 40);
    	   			      	var onDiv = false;
    	   			      	var onTrigger = false;
    	   			      	var sliderExists = false;
    	   			      	var timeoutID;
    	   			      	var inBrowserWindow = true;
    	   			      	
    	   			      	//prevent clicks on trigger
    	   			      	$trigger.click(function(event) {
    	   			      		event.preventDefault();
    	   			      	});
    	   			      	
    						
    						$trigger.hover(function(){
		    					onTrigger = true;
		    					slideUp();
    						},function(){
	    						onTrigger = false;	
	    						timeoutID = setTimeout(function(){
	    							slideDown();
	    						}, 400);
    						});

    						
    						$slider.hover(function(){
    							onDiv = true;
    						},function(){  				
    							onDiv = false;
    							slideDown();
    						});
    						
    						

    						function slideUp () {
    							
    							//close helper if open
    							PATROC.Helpers.close();
    							
    							sliderExists = true;
    							$slider.animate({
    									bottom: 30,
    								}, 500, function() {
    								    
    								  }); 
    							}
    						 	
    						function slideDown () { 
    										
    							//clearTimeout(timeoutID);
    							if (sliderExists && !onDiv) {
    								sliderExists = false;
    								$slider.animate({
    									bottom: startPos,
    								}, 500, function() {
    									
    								});   
    						}		
    	   			         			
    	   			     }
    	   			      
    	   			});
    	   			
    	   			//load initial helpers
    	   			PATROC.Helpers.showSliderHelper();
    	   		};
    	   		
    	   		
    	    	
    	    	return self;
    	    
    	    }()); 
    	
    	return {
    			init: function() {
					
					
 				    //initialize all managers	 	    		
    				PATROC.URLManager.init();
    				Sliders.init();
    				PATROC.FormManager.init();
    				PATROC.MovesManager.init();
    				PATROC.BlogManager.init();
    				PATROC.VideoManager.init();
    				
    				if(PATROC.DeviceManager.isIE()) {
	    				//apply boxes for IE
	    				$('.boxed').each(function() {
	    					$(this).append('<div class="boxright"></div>');
		    				$(this).prepend('<div class="boxleft"></div>');
		    			});
					}
    			
    			},
    	
    			reset: function() {
    				//if any modals are open close them
    				
    				PATROC.MovesManager.close();
    				
    			}
    		};
    
    }()); 
    
} (jQuery.noConflict()));



