$(document).ready(
	function(){
		//initialize Navigation
		$.initNavigation();
		//initialize Tabs
		$("div.tab").tabs();
		//initialize Form
		$.initForm();
		//initialize Galleriffic
		if ( $(".gallery").length > 0 )
		{
			$.initGalleriffic();
		}
		if ( $("a[rel^='prettyPhoto']").length > 0)
		{
			$.initPrettyphoto();
		}
		if ( $(".profilelink").length > 0)
		{
			$('.profilelink').popupWindow({ 
			centerBrowser:1,
			scrollbars:1,
			height:700, 
			width:700 
			}); 
		}
		if ( $("div .infotel").length > 0)
		{
			$("div .infotel").hover(
				function(){
					$("div .infoteldetail").fadeTo('slow', 1);
				},
			function(){
					$("div .infoteldetail").fadeTo('slow', 0);
				}
				);
		}
	}
);

$(window).load(
	function() {
		$('ul.open').show();
		$.initImageslider();
	}
);

$.extend({
	initNavigation:function(){
		$("#snb").hide();
		$("#gnb li a").click(
			function(){
				var gnb = $("#snb");
				if(gnb.css("display")=="none"){
				gnb.slideDown("fast");
				return false;
				}
			}
		);
		$("#gnb li a").hover(
			function(){
				$("#snb").slideDown("fast");
			}
		);
		$("#snb").hover("",
			function(){
				$("#snb").slideUp("fast");
			}
		);
		$('.parent li a').click(
			function(e){
			var targetElement = $(this).parent().children("ul.child");
				if(!targetElement[0]){
					return true;
				}else{
					targetElement.slideToggle("fast");
					return false;
				}
			}
		);
	},
	initForm:function(){
		//Depth Auto Change
		var mPid = $("select#mPid")
		mPid.change(function(){$("input#mDepth").prev('.i_label').css('visibility','hidden');$("input#mDepth").val(Number($("select#mPid option:selected").attr("rel"))+1);});
		//Question Anchor
		var q_anchor = $('a[rel="question"]');
		q_anchor.click(function(){var q = confirm(q_anchor.attr("title"));if(q){return true;}else{return false;}})
		// Help Toggle
		$('.item>.i_help').click(function(){
			$(this).parent('.item').find('.i_dsc').toggleClass('hide');
		});
		// Input Clear
		var i_text = $('.item>.i_label').next('.i_text');
		$('.item>.i_label').css('position','absolute');
		i_text
			.focus(function(){
				$(this).prev('.i_label').css('visibility','hidden');
			})
			.blur(function(){
				if($(this).val() == ''){
					$(this).prev('.i_label').css('visibility','visible');
				} else {
					$(this).prev('.i_label').css('visibility','hidden');
				}
			})
			.change(function(){
				if($(this).val() == ''){
					$(this).prev('.i_label').css('visibility','visible');
				} else {
					$(this).prev('.i_label').css('visibility','hidden');
				}
			})
			.blur();

	},
	initGalleriffic:function(){
		// Initially set opacity on thumbs and add
		// additional styling for hover effect on thumbs
		var onMouseOutOpacity = 0.67;
		$('ul.thumbs li').opacityrollover({
			mouseOutOpacity:   onMouseOutOpacity,
			mouseOverOpacity:  1.0,
			fadeSpeed:         'fast',
			exemptionSelector: '.selected'
		});


		var gallery = $('.gallery').galleriffic({
			delay:                     2500,
			numThumbs:                 200,
			preloadAhead:              10,
			enableTopPager:            false,
			enableBottomPager:         false,
			maxPagesToShow:            50,
			imageContainerSel:         '#slideshow',
			controlsContainerSel:      '#controls',
			captionContainerSel:       '#caption',
			loadingContainerSel:       '#loading',
			renderSSControls:          true,
			renderNavControls:         true,
			playLinkText:              '',
			pauseLinkText:             '',
			prevLinkText:              '',
			nextLinkText:              '',
			nextPageLinkText:          '',
			prevPageLinkText:          '',
			enableHistory:             false,
			autoStart:                 false,
			syncTransitions:           true,
			defaultTransitionDuration: 900,
			onSlideChange:             function(prevIndex, nextIndex) {
				// 'this' refers to the gallery, which is an extension of $('#thumbs')
				this.find('ul.thumbs').children()
					.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
					.eq(nextIndex).fadeTo('fast', 1.0);
			},
			onPageTransitionOut:       function(callback) {
				this.fadeTo('fast', 0.0, callback);
			},
			onPageTransitionIn:        function() {
				this.fadeTo('fast', 1.0);
			}
		});
	},
	initPrettyphoto:function(){
		$("a[rel^='prettyPhoto']").prettyPhoto({
			animation_speed: 'fast', /* fast/slow/normal */
			slideshow: 5000, /* false OR interval time in ms */
			autoplay_slideshow: false, /* true/false */
			opacity: 0.80, /* Value between 0 and 1 */
			show_title: true, /* true/false */
			allow_resize: true, /* Resize the photos bigger than viewport. true/false */
			default_width: 500,
			default_height: 344,
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'pp_default', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
			horizontal_padding: 20, /* The padding on each side of the picture */
			hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
			wmode: 'opaque', /* Set the flash wmode attribute */
			autoplay: true, /* Automatically start videos: True/False */
			modal: false, /* If set to true, only the close button will close the window */
			deeplinking: true, /* Allow prettyPhoto to update the url to enable deeplinking. */
			overlay_gallery: true, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
			keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
			changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
			callback: function(){}, /* Called when prettyPhoto is closed */
			ie6_fallback: false,
			markup: '<div class="pp_pic_holder"> \
						<div class="ppt">&nbsp;</div> \
						<div class="pp_top"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
						</div> \
						<div class="pp_content_container"> \
							<div class="pp_left"> \
							<div class="pp_right"> \
								<div class="pp_content"> \
									<div class="pp_loaderIcon"></div> \
									<div class="pp_fade"> \
										<a href="#" class="pp_expand" title="Expand the image">Expand</a> \
										<div class="pp_hoverContainer"> \
											<a class="pp_next" href="#">next</a> \
											<a class="pp_previous" href="#">previous</a> \
										</div> \
										<div id="pp_full_res"></div> \
										<div class="pp_details"> \
											<div class="pp_nav"> \
												<a href="#" class="pp_arrow_previous">Previous</a> \
												<p class="currentTextHolder">0/0</p> \
												<a href="#" class="pp_arrow_next">Next</a> \
											</div> \
											<p class="pp_description"></p> \
											 \
											<a class="pp_close" href="#">Close</a> \
										</div> \
									</div> \
								</div> \
							</div> \
							</div> \
						</div> \
						<div class="pp_bottom"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
						</div> \
					</div> \
					<div class="pp_overlay"></div>',
			gallery_markup: '<div class="pp_gallery"> \
								<a href="#" class="pp_arrow_previous">Previous</a> \
								<div> \
									<ul> \
										{gallery} \
									</ul> \
								</div> \
								<a href="#" class="pp_arrow_next">Next</a> \
							</div>',
			image_markup: '<img id="fullResImage" src="{path}" />',
			flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
			quicktime_markup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',
			iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',
			inline_markup: '<div class="pp_inline">{content}</div>',
			custom_markup: ''
		});
	},
	initPopupslider:function(psTarget){
		//Set Default State of each portfolio piece
		var ps = $('.popupSlider.'+psTarget);
		
		$Paging = $('.popupSlider.'+psTarget+' > .paging');
		$Window = $('.popupSlider.'+psTarget+' > .window');
		$Image_reel = $('.popupSlider.'+psTarget+' > .window > .image_reel');


		$Paging.show();
		$Paging.find("a:first").addClass("active");
		//Get size of images, how many there are, then determin the size of the image reel.
		var imageWidth = $Window.width();
		var imageSum = $Image_reel.find("img").size();
		var imageReelWidth = imageWidth * imageSum;
		//Adjust the image reel to its new size
		$Image_reel.css({'width' : imageReelWidth});
		//Paging + Slider Function
		$active = $Paging.find('a.active');
		rotate = function(){
			var triggerID = $active.attr("rel") - 1; //Get number of times to slide
			var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide
			$Paging.find("a").removeClass('active'); //Remove all active class
			$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
			//Slider Animation
			$Image_reel.animate({ 
				left: -image_reelPosition
			}, 1000 );
				$active = $Paging.find('a.active').next();
				if ( $active.length === 0) { //If paging reaches the end...
					$active = $Paging.find('a:first'); //go back to first
				}
		};
		//Rotation + Timing Event
		rotateSwitch = function(){		
			play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
				
				rotate(); //Trigger the paging and slider function
			}, 20000); //Timer speed in milliseconds (3 seconds)
		};
		rotateSwitch(); //Run function on launch
		//On Hover
		$Image_reel.find("a").hover(function() {
			clearInterval(play); //Stop the rotation
		}, function() {
			rotateSwitch(); //Resume rotation
		});	
		//On Click
		$Paging.find("a").click(function() {	
			$active = $(this); //Activate the clicked paging
			//Reset Timer
			clearInterval(play); //Stop the rotation
			rotate(); //Trigger rotation immediately
			rotateSwitch(); // Resume rotation
			return false; //Prevent browser jump to link anchor
		});	
	}
});
