    /**
    *
    *   global.js
    *
    *   This JS file include will hold all global functionality.
    *   Global is defined as appearing on more than one type of page.
    *
    */
	$(function() {
		
		var xp = 20;
		var yp = 70;
		var exp_cp = 60;
		var name_cp = 'sub_pop';
		var cp_val = readCookie(name_cp);
		var pop_timeout = 10000;
		
		if( typeof( window.innerWidth ) == 'number' ) {
		    //Non-IE
		    myWidth = window.innerWidth;
		    myHeight = window.innerHeight;
		  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		    //IE 6+ in 'standards compliant mode'
		    myWidth = document.documentElement.clientWidth;
		    myHeight = document.documentElement.clientHeight;
		  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		    //IE 4 compatible
		    myWidth = document.body.clientWidth;
		    myHeight = document.body.clientHeight;
		  }
	
		var width = myWidth;
		var left = (width / 2) - 275;

	    if (!cp_val) {
	        $("#sub_pop").css('display', 'block');
	        $("#sub_pop").css('left', left);
	        createCookie(name_cp,1,exp_cp); 
	    }
	    
	    $('#pop_click,#pop_close').click(function() {
			$('#sub_pop').hide();
		});

		function createCookie(name,value,days) {
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else var expires = "";
			document.cookie = name+"="+value+expires+"; path=/";
		}

		function readCookie(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		}
		
		$("#expand-small").mouseover(function() { 
			$("#expand-small").hide();
			$("#expand-big").show();
		});
		
		$("#expand-big").mouseout(function() {
			$("#expand-small").show();
			$("#expand-big").hide();
		});
			
	});
	
	/**
	*
	*    Mantle
	*
	*    Generates the Mantle Module Which Slides the Featured Content On Homepage
	*    Added By: Tito To (5/27/2009)
	*/
	function rotate() {

		//Get the first image
		var currentImg = ($('.contentdiv.show') ?  $('.contentdiv.show') : $('.contentdiv:first'));
		var currentNo = ($('.toc.selected') ?  $('.toc.selected') : $('.toc:first'));

		//Get next image, when it reaches the end, rotate it back to the first image
		var nextImg = ((currentImg.next().length && !currentImg.next().hasClass('pagination')) ? ((currentImg.next().hasClass('show')) ? $('.contentdiv:first') : currentImg.next()) : $('.contentdiv:first'));
		var nextNo = ((currentNo.next().length) ? ((currentNo.next().hasClass('selected')) ? $('.toc:first') : currentNo.next()) : $('.toc:first'));

		//Set the fade in effect for the next image, the show class has higher z-index
		nextImg.css({opacity: 0.0})
		.addClass('show')
		.animate({opacity: 1.0}, 700);
		nextNo.addClass('selected');

		//Hide the current image
		currentImg.animate({opacity: 0.0}, 700)
		.removeClass('show');
		currentNo.removeClass('selected');

	};

	function initMantle() {

		//Get the first image and display it (gets set to full opacity)
		$('.contentdiv:first').css({opacity: 1.0})
		.addClass('show');

		$('.indicators').css({opacity: 1.0})
		$('.toc:first').addClass('selected');

		var set = setInterval('rotate()',5000);	

		$('.toc').click(function(event) {
			//Clear out timer
			clearInterval(set);

	    var url = this.toString();
	    var delimiter = '#';
	    var id = url.split(delimiter);
	    id = parseInt(id[1]);

	    $('.contentdiv.show').css({opacity: 0.0})
			.removeClass('show');

			$('.contentdiv.content_'+id).css({opacity: 1.0})
			.addClass('show');

	    $('.toc.selected').removeClass('selected');

			$('.toc.content_'+id).addClass('selected');

			return false;
		});

	}

	/**
	*
	*   Toggles Tabs
	*
	*   This function will toggle through tabs or any other ID'd DOM elements, showing the selected
	*   tab.  It also has the option to change the tab CSS styles.
	*
	*   @param array options Options List (Example: ['MyVideos','FavoriteVideos','TaggedVideos'])
	*   @param string selected Selected Option (Example: 'TaggedVideos')
	*   @param string offClass Tab 'Off Class' CSS Classes To Set
	*   @param string onClass Tab 'On Class' CSS Classes To Set
	*   @return void
	*
	*/
	function toggle_tabs(options, selected, offClass, onClass) {
		if (options instanceof Array) {
	    	for (var i=0; i<options.length; i++) {
	            if (document.getElementById(options[i])) {
	                document.getElementById(options[i]).style.display = 'none';
	            }
	            if (typeof(offClass) != 'undefined') {
	                if (document.getElementById(options[i]+'Tab')) {
	                    document.getElementById(options[i]+'Tab').className = offClass;
	                }
	            }
	        }
		} else {
	        if (document.getElementById(options)) {
	            document.getElementById(options).style.display = 'none';
	        }
	        if (typeof(offClass) != 'undefined') {
	            if (document.getElementById(options+'Tab')) {
	                document.getElementById(options+'Tab').className = offClass;
	            }
	        }
		}
	    if (selected instanceof Array) {
	    	for (var i=0; i<selected.length; i++) {
		        if (document.getElementById(selected[i])) {
		            document.getElementById(selected[i]).style.display = 'inline';
		        }
		        if (typeof(onClass) != 'undefined') {
		            if (document.getElementById(selected[i]+'Tab')) {
		                document.getElementById(selected[i]+'Tab').className = onClass;
		            }
		        }
	    	}
	    } else {
	        if (document.getElementById(selected)) {
	            document.getElementById(selected).style.display = 'inline';
	        }
	        if (typeof(onClass) != 'undefined') {
	            if (document.getElementById(selected+'Tab')) {
	                document.getElementById(selected+'Tab').className = onClass;
	            }
	        }
	    }
	}
	
	/**
	*
	*   Select Tab
	*
	*   This function will toggle through tabs or any other ID'd DOM elements, showing the selected
	*   tab and hide the rest.
	*
	*   @param array options Options List (Example: ['MyVideos','FavoriteVideos','TaggedVideos'])
	*   @param string selected Selected Option (Example: 'TaggedVideos')
	*   @return void
	*
	*/
	function select_tab(options, selected) {
		if (options instanceof Array) {
	    	for (var i=0; i<options.length; i++) {
	            if (document.getElementById(options[i])) {
	                $('#'+options[i]).removeClass('on');
	                $('#'+selected).addClass('on');
	            }
	            
	        }
		}
	}
	
	/**
	*
	*   Display Full Size
	*
	*   This function will traverse the class="x" and display the full size of the first image
	*   
	*   @param class to find
	*   @return url of image source
	*
	*/
	function display_full_size() {
		var img = $('ul.filmstrip').find('li.current img').attr('src');
		window.open(img);
	}
	
	/****************************************
	 **
	 **    Photo Gallery
	 **
	 ****************************************/

	var Collection;
	var showAnchor = true;
	var firstImageID = '';
	var CollectionComponent = function()
	{
	 this.images = {};

	 // Loads Playlist
	 this.Load = function(playlist) {

	     // Loads Playlist
	     try {
	         this.images = $.parseJSON(playlist);
	     } catch (e) {
	    	 alert('Error parsing JSON');
	         return false;
	     }
	     
	     // Shows Initial Image
	     if (typeof(GetID('#')) != 'undefined' && GetID('#').length == 10) {
	         this.ShowImage(GetID('#'));
	     } else {
	    	 showAnchor = false;
	    	 firstImageID = this.images[0].id;
	    	 this.ShowImage(this.images[0].id);	 
	     }

	     //Keylistener for Left/Right arrows
	     $(document).bind('keydown', function(e) {
	         if (e.which == '37') {
	             Collection.ShowImage(Collection.prevID);
	         }
	         if (e.which == '39') {
	             Collection.ShowImage(Collection.nextID);
	         }
	     });
	     
	 	//var HashCheckInterval = setInterval(this.CheckForHash, 500);

	 };

	 // Show Image (Primary Function Call)
	 this.ShowImage = function(id) {

	     // Adds Anchor Tag With ID Of Current Image
		 if(showAnchor == true) {
			 document.location.href = "#"+id; 
		 } else {
			 showAnchor = true;
		 }

	     this.ShowLoader();

	     this.UpdatePhotoPaging(id); // <-- Updates Photo Paging, Per Image

	 };

	 // Shows Loader
	 this.ShowLoader = function() {
	     $('#imageLoaderGif').css('display','block');
	 }

	 // Hides Loader
	 this.HideLoader = function() {
	     $('#imageLoaderGif').css('display','none');
	     $('#featured-photo').css('display','block');
	 };

	 // Updates Featured Image and Image Pagination
	 this.UpdateFeatureImage = function(id,prevId,nextId) { 
		 var image = this.GetImage(id);
		 //if this is a video
		 //$('#selectedImage').html('<script src="http://player.ooyala.com/player.js?width=640&height=426&embedCode=9lZmkwMjpA3Y1PVjurNHZnim4UNhqleU&videoPcode=Y2eWc6BmWMypoBLDfce-LDGmx47n"></script>');
		if(image.desc.indexOf("<iframe") != -1 || image.desc.indexOf("<object") != -1) {
			 $('#selectedImage').css('padding-top', '26px');
			 $('#featured-photo').css('background-color', '#000');
			 $('#prevImage,#nextImage').html('');
			 $('#prevImage,#nextImage').addClass('video-detected');
			 this.HideLoader();
			 if(image.desc.indexOf("<iframe") != -1) {
				 $('#selectedImage').html(image.desc.slice(image.desc.indexOf("<iframe"), image.desc.indexOf("</iframe") + 9));
			 } else if(image.desc.indexOf("<object") != -1) {
				 $('#selectedImage').html(image.desc.slice(image.desc.indexOf("<object"), image.desc.indexOf("</object") + 10));
			 }
		 } else {
			 $('#selectedImage').css('padding-top', '0px');
			 $('#featured-photo').css('background-color', '#F2F2F2');
			 $('#selectedImage').html('<img style="vertical-align:middle;" src="'+image.link+'" alt="" onload="Collection.HideLoader();return false;"/>');
			 $('#prevImage').html('<a href="'+this.GetCollectionPath()+'#'+prevId+'" onclick="Collection.ShowImage(\''+prevId+'\');return false;"><img style="vertical-align:middle;" src="'+image_path+'/clear.gif" alt="" onload="Collection.HideLoader();return false;"/></a>');
			 $('#nextImage').html('<a href="'+this.GetCollectionPath()+'#'+nextId+'" onclick="Collection.ShowImage(\''+nextId+'\');return false;"><img style="vertical-align:middle;" src="'+image_path+'/clear.gif" alt="" onload="Collection.HideLoader();return false;"/></a>');
			 $('#prevImage,#nextImage').removeClass('video-detected');
		 }
	};

	 // Updates Photo Paging
	 this.UpdatePhotoPaging = function(id) { 

	     var currentPage = 0;
	     var totalPages = 0;

	     var currentNumber = 1;
	     var totalImages = 0;
	     var prevID = 0;
	     var nextID = 0;
	     var num = 0;

	     if ($('#GalleryView').length > 0) {
	         var noDisplayThumb = 8;
	     }

	     // Gets Total Image Count, Current Page
	     var first = 0;
	     var prev = 0;
	     var count = 0;
	     for (image in this.images) {
	    	 if (image == 'filter' || image == 'indexOf') continue;
	         count++;
	         if ((count % noDisplayThumb) == 1) {
	             totalPages++;
	         }
	         if (first == 0) {
	             first = this.images[image].id;
	         }
	         if (this.images[image].id == id) { // <-- Image Match Found
	             this.UpdateCaption(this.images[image].desc); // <-- Updates Caption, Per Image
	             this.UpdateDownloadLinks(this.images[image].link); // <-- Updates Download links, Per Image
	             currentNumber = count;
	             currentPage = totalPages;
	             prevID = prev; // <-- Sets Previous Image ID (Or 0 If Image Is First Image)

	         }
	         if (prev == id) { // <-- Sets Next Image ID (Based On Cycle/Rotation)
	             nextID = this.images[image].id;
	         }
	         prev = this.images[image].id;
	         totalImages++;
	     }

	     if (totalImages > 0) {
	         if (prevID == 0) { // <-- If PrevID Still Not Set, Use Last Image Found (As Image ID Was First Image)
	             prevID = prev;
	         }
	         if (nextID == 0) { // <-- If NextID Still Not Set, Use First Image Found (As Image ID Was Last Image)
	             nextID = first;
	         }
	     }

	     this.prevID = prevID;
	     this.nextID = nextID;

	     this.UpdateFeatureImage(id,prevID,nextID); // <-- Updates Feature Image

	     // Builds links pagination
	     var html = '';
	     html += '<a id="PrevImg" href="'+this.GetCollectionPath()+'#'+prevID+'" onclick="Collection.ShowImage(\''+prevID+'\');return false;">&lt; Previous</a>';
	     html += currentNumber+' of '+totalImages+' ';
	     html += '<a id="NextImg" href="'+this.GetCollectionPath()+'#'+nextID+'" onclick="Collection.ShowImage(\''+nextID+'\');return false;">Next &gt;</a>';
	     $('#paginationLinks').html(html);
	     
	     // Builds thumbs pagination
	     var html = '';
	     html += '<a href="'+this.GetCollectionPath()+'#'+prevID+'" onclick="Collection.ShowImage(\''+prevID+'\');return false;"><img src="'+arrow_prev_active+'" /></a>';
	     $('#previousPageImage').html(html);
	     var html = '';
	     html += '<a href="'+this.GetCollectionPath()+'#'+nextID+'" onclick="Collection.ShowImage(\''+nextID+'\');return false;"><img src="'+arrow_next_active+'" /></a>';
	     $('#nextPageImage').html(html);

	     // Builds Image Navigation
	     var html = '';
	     if (totalImages <= noDisplayThumb) {
	         num = totalImages;
	     } else {
	         num = (totalImages % noDisplayThumb == 0) ? noDisplayThumb : (totalImages % noDisplayThumb);

	     }

	     if (currentPage == totalPages) {
	         for (i=0; i<num; i++) {

	             var startImg = ((currentPage-1) * noDisplayThumb) + i;
	             var startImage = this.GetImage(this.images[startImg].id);

	             html += '<img src="'+startImage.thumb+'" width="100" height="75" border="0" onclick="Collection.ShowImage(\''+this.images[startImg].id+'\');return false;" id="img_'+this.images[startImg].id+'"';
	             if (this.images[startImg].id == id) {
	                 html += ' class="selected"';
	             } else {
	                 html += ' class="notSelected"';
	             }
	             html += ' />';
	         }

	     } else { 
	         for (i=0; i<noDisplayThumb; i++) {
	 
	             var startImg = ((currentPage-1) * noDisplayThumb) + i;
	             var startImage = this.GetImage(this.images[startImg].id);

	             html += '<img src="'+startImage.thumb+'" width="100" height="75" border="0" onclick="Collection.ShowImage(\''+this.images[startImg].id+'\');return false;" id="img_'+this.images[startImg].id+'"';
	             if (this.images[startImg].id == id) {
	                 html += ' class="selected"';
	             } else {
	                 html += ' class="notSelected"';
	             }
	             html += ' />';
	         }
	     }
	     $('#photoThumbs').html(html);
	     
	     if ($('.40th-anniversary').length > 0) {
	    	// Builds Previous Images Navigation Button for 40th Anniversary Prom Galleries
		     var ppImage = document.getElementById('previousPageImage');
		     if (currentPage == 1) {
		         $('#previousPageImage').attr('src',arrow_prev_inactive);
		         $('#previousPageImage').removeClass('cursoron');
		         $('#previousPageImage').addClass('cursoroff');
		         $('#previousPageImage').click(function() {});
		     } else {
		         var num1 = currentNumber - (currentNumber % noDisplayThumb + noDisplayThumb);
		         imageID2 = this.images[num1].id; // <-- Define Before Sending Into 'onclick' Definition
		         ppImage.src = arrow_prev_active;
		         ppImage.className = 'cursoron';
		         ppImage.title = '< Previous Page';
		         ppImage.onclick = function() {
		             Collection.ShowImage(imageID2);
		         }
		     }

		     // Builds Next Images Navigation Button for 40th Anniversary Prom Galleries
		     var npImage = document.getElementById('nextPageImage');
		     if (totalPages > 1 && currentPage != totalPages) {
		         var num2 = (currentPage * noDisplayThumb);
		         imageID = this.images[num2].id; // <-- Define Before Sending Into 'onclick' Definition
		         npImage.className = 'cursoron';
		         npImage.src = arrow_next_active;
		         npImage.title = 'Next Page >';
		         npImage.onclick = function() {
		             Collection.ShowImage(imageID);
		         }
		     } else {
		         $('#nextPageImage').attr('src',arrow_next_inactive);
		         $('#nextPageImage').removeClass('cursoron');
		         $('#nextPageImage').addClass('cursoroff');
		         $('#nextPageImages').click(function() {});
		     } 
	     }
      
	 };

	 // Updates Caption
	 this.UpdateCaption = function(caption) {
	     if (caption != '') {
	    	 $('#photo-description').css('display','block');
	    	 //if this is a video
	    	 if (caption.indexOf("<iframe") != -1) {
	    		 $('#imageDescription').html($.trim(caption.slice(caption.indexOf("</iframe>") + 9)));
	    	 } else  if (caption.indexOf("<object") != -1) {
	    		 $('#imageDescription').html($.trim(caption.slice(caption.indexOf("</object>") + 10)));
	    	 } else {
	    		 $('#imageDescription').html(caption);
	    	 }
	     } else {
	    	 $('#photo-description').css('display','none');
	     }
	 };
	 
	// Updates Download links
	 this.UpdateDownloadLinks = function(link) {
		 var html = '';
		 var images = link.split('/');
		 var lowResImage = 'http://images.grindtv.com/powdermag.com/40th-anniversary/' + images[images.length-1];
		 var highResImage =  'http://images.grindtv.com/powdermag.com/40th-anniversary/' + images[images.length-1].replace('l.jpg', 'h.jpg');
		 if ($('.40th-anniversary').length > 0) {
			 html += 'Download: <a href="' + lowResImage + '">Low Resolution</a> | ';
			 html += '<a href="' + highResImage + '">High Resolution</a>';
			 $('#imageDownload').html(html);
			 $('#photo-description').css('display','block')
		 }
	 };
	
	 // Gets Current Collection Path
	 this.GetCollectionPath = function() {
	     var url = window.location.href;
	     var delimiter = '#';
	     var segment = url.split(delimiter);
	     return segment[0];

	 };
	 
	 // Gets Current Collection Path for FB share
	 this.GetCollectionSharePath = function() {
	     var url = window.location.href;
	     var segment = url.split('?image=');
	     if (typeof(segment[1]) == 'undefined') {
	    	 var segment = segment[0].split('#');
	    	 return segment[0]+'?image=';
	     } else {
	    	 var image = segment[1].split('#');
	    	 return segment[0]+'?image='; 
	     }
	 };

	 // Gets Image Info
	 this.GetImage = function(id) {
		 var imgObj;
		 var i;
	     for(i in this.images) {
	    	 if (this.images[i].id == id) {
				 imgObj = this.images[i]; 
			 }
		 }
	     return imgObj;
	 };

	 /**
	 *
	 *   Check for image hash id and update featured photo accordingly
	 *   @return void
	 *
	 */
	 this.tempID;
	 this.CheckForHash = function() {
		 var currentID = GetID('#');
		if(typeof(currentID) != 'undefined') {
			if (currentID != this.tempID) {
				this.tempID = currentID ;
				Collection.UpdatePhotoPaging(this.tempID);
			}
		} 
		else if(this.tempID != firstImageID) 
		{ 
			this.tempID = firstImageID;
			Collection.UpdatePhotoPaging(this.tempID); 
		}
	};
	 
	} //end Collection

	/**
	*
	*   Retrieves Anchor Tag From URL As ID
	*   @return void
	*
	*/
	function GetID(delimiter){
		var url = window.location.href;
		var id = url.split(delimiter);
		if (id[1] != '') {
		    return id[1];
		} else {
		    return '';
		}
	}
	
	/**
	* GrindMedia Overlay Instantiation
	* - NOTE: Only First "gmOverlay()" Call Will Initialize 
	* @param string json JSON Overlay Definition
	* @return void
	*/
	var overlay;
	function gmOverlay(json) {
		if (!overlay) {
			var obj = jQuery.parseJSON(json);
			if (obj != null) {
				overlay = new OverlayComponent();
				$(document).ready(function() {
					overlay.video = obj.video;
					overlay.image = obj.image;
					overlay.link = obj.link;
					overlay.lifetime = obj.countdown;
					overlay.skiptime = obj.skip;
					overlay.init();
				});
			}
		}
	}

	/**
	* GrindMedia Overlay Instantiation
	* @param string json JSON Overlay Definition
	* @return void
	*/
	function gmOverlayCallback() {
		if (overlay != null) {
			if (arguments[0] == 'REMAINING')
				overlay.updateCountdown(arguments[1]);
			else if (arguments[0] == 'COMPLETE')
				overlay.hideOverlay();
			else if (arguments[0] == 'CLICK-THRU') {
				window.open(arguments[1]);
				overlay.hideOverlay();
			}
		}
	}

	/**
	* GrindMedia Photo Gallery Overlay Component
	*/
	var OverlayComponent = function() {

		this.image = '';
		this.video = '';
		this.link = '';
		this.duration = 0;
		this.lifetime = 0;
		this.skiptime = 0;

		this.init = function() {

			// Adjusts Overlay Height On Initialization
			this.adjustHeight();

			// Initializes Video Interstitial
			if (this.video) {
				var version = swfobject.getFlashPlayerVersion();
				if (version.major >= 10) {
					swfobject.embedSWF(
						'/wp-content/themes/surfermag.com/swf/interstitial.swf',
						'InterstitialOverlay',
						'950',
						'700',
						'10.0.0',
						'/wp-content/themes/surfermag.com/swf/swfobject-installer.swf',
						{video: this.video, link: this.link},
						{wmode: 'window'}
					);
					this.updateCountdown(0);
					$('#Interstitial').fadeIn();
					return;
				}
			}

			// Initializes Image Interstitial
			if (this.image) {
				var html = '<a href="' + this.link + '" onclick="window.open(this.href);return false;">';
					html += '<img src="' + this.image + '" />';
					html += '</a>';
				$('#InterstitialOverlay').html(html);
				$('#Interstitial').fadeIn();
				this.tick();
				return;
			}

		};

		// Artificial Image Countdown Ticker
		this.tick = function() {
			$(this).oneTime(1000, function(i) {
				this.updateCountdown(this.lifetime);
				if (--this.lifetime >= 0)
					this.tick();
				else
					this.hideOverlay();
			});
		};

		// Updates Advertisement Countdown
		this.updateCountdown = function(secs) {

			// Re-adjusts Overlay Height
			this.adjustHeight();

			// Updates Lifetime, Initializing Duration Where Applicable
			this.lifetime = secs;
			if (this.duration < this.lifetime)
				this.duration = this.lifetime;

			// Displays Close Button When Applicable
			if (this.lifetime == (this.duration - this.skiptime))
				this.showClose();

			// Displays Advertisement Countdown
			var html = 'This advertisement will close in ' + secs + ' seconds..';
			if (secs == 0)
				html = 'This advertisement will close in a moment..';
			$('#Interstitial .countdown').html(html);

		};
		
		this.adjustHeight = function() {
			if ($('#Interstitial .takeover').length > 0) {
				var height = $(document).height();
				var offset = $('#Interstitial .takeover').offset();
				$('#Interstitial .takeover').css('height', (height - offset.top));
			}
		};

		this.showClose = function() {
			$('#Interstitial .takeover').live('click', this.hideOverlay);
			$('#Interstitial .close').fadeIn();
		};

		this.hideOverlay = function() {
			this.lifetime = 0;
			$('#Interstitial .takeover').fadeOut(function() {
				$('#Interstitial .takeover').remove();
			});
		};

	}



	

	
	
