$('body').removeClass('nojs') //Remove nojs class (to target none javascript handling)
		 .addClass('js');
$(document).ready(function() {
		
		/* GF2 Competiotion entry page validation and picture selection */
		var lastselectedid = null;

		$("#prizes li label span").bind("click", function(element) {
        	
			//clear last selected element, reset it
			if (lastselectedid != null) {
				var selectedhref = $('img', '#'+lastselectedid).attr("src");
				$('img', '#'+lastselectedid).attr('src', $('#'+lastselectedid).attr('rel'));
				$('#'+lastselectedid).attr('rel',selectedhref );
				
			}
			
			var selectedhref = $(this).attr("rel");
			var originalhref = $('img', this).attr('src')
			$('img', this).attr("src", selectedhref);
			$(this).attr('rel', originalhref);
			$(this).parent().parent().find('input').attr('checked', true);
		
			//set lastselected id as current selection
			lastselectedid = $(this).attr('id');
        	return false;

        });
        
        $('form').submit(function() {
        	
        	var error = false;
        	var errors = '';
        	var checked = false;
        	var terms_checked = false;
        	
        	if (document.forms[0].title.value == 0){
        		error = true;
        		errors = errors + '<li>Please enter a title.</li>'
        	}
        	if (document.forms[0].fname.value == 0){
        		error = true;
        		errors = errors + '<li>Please enter a first name.</li>'
        	}
        	if (document.forms[0].lname.value == 0){
        		error = true;
        		errors = errors + '<li>Please enter a last name.</li>'
        	}
        	if (document.forms[0].add1.value == 0){
        		error = true;
        		errors = errors + '<li>Please enter the first line of your address.</li>'
        	}
        	if (document.forms[0].postcode.value == 0){
        		error = true;
        		errors = errors + '<li>Please enter a postcode.</li>'
        	}
        	if (document.forms[0].country.value == 0){
        		error = true;
        		errors = errors + '<li>Please select your country.</li>'
        	}
        	if (document.forms[0].terms.checked == 0){
        		error = true;
        		errors = errors + '<li>Please accept the terms and conditions to continue.</li>'
        	}
        	
        	
        	
        	for (var i=0; i<11; i++) {
        		if (document.forms[0].prize[i].checked)
        			checked = true;
        	}
        	
        	if (!checked) {
        		error = true;
        		errors = errors + '<li>Please select which photo you would like a chance to win.</li>'
        	}
        
        	
        	//Validate the email
        	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
        	if (document.forms[0].email.value == 0){
        		error = true;
        		errors = errors + '<li>Please enter an email.</li>'
        	} else if (emailPattern.test(document.forms[0].email.value)=== false){
        		error = true;
        		errors = errors + '<li>Please enter a valid email address.</li>'
        	}
        	
        	//Check the comment
        	if (document.forms[0].comment.value.length > 200){
        		error = true;
        		errors = errors + '<li>Your comment is too long, please shorten it.</li>'
        	}
        	
        	if (error == true){
        		$('#error').html('<span><h1>The following information still needs to be completed:</h1><ul>' + errors + '</ul></span>');
        		scroll(0,400);
        		return false;
        	} else {
        		return true;
        	}

        	
        });
	
	
	// Delete confirmation
	jQuery("a[rel=delete]").click(function(){
		return confirm("This will be permanently removed from the website.\n\nAre you sure you want to delete?");
	});

	/*
	 * Background image slideshow, based on script by Marco Kuiper
	 */
	if (!$('body').hasClass('home')&&!$('body').hasClass('gf2')&&!$('body').hasClass('g3')) {
		// Speed of the automatic slideshow
		var slideshowSpeed = 6000, numberOfPhotos = 4, activeContainer = 1, currentImg = Math.floor(Math.random() * 4);
		
		preloadArray = new Array();
		for(var i=1;i<=numberOfPhotos;i++){
			preloadArray.push(templateDir + "/images/headers/header"+i+".jpg");
		}
		 
		jQuery.preloadImages = function() {
			var a = (typeof arguments[0] == 'object')? arguments[0] : arguments;
			for(var i = a.length -1; i > 0; i--) {
				jQuery("<img>").attr("src", a[i]);
			}
		}
		$.preloadImages(preloadArray);
		
		var navigate = function(){
			// Check if no animation is running. If it is, prevent the action
			// Check which current image we need to show
			currentImg++;
			if (currentImg == numberOfPhotos + 1) 
				currentImg = 1;
			
			// Check which container we need to use
			var currentContainer = activeContainer;
			activeContainer = (activeContainer == 1) ? 2 : 1;
			showImage('header' + currentImg + '.jpg', currentContainer, activeContainer);
		};
		
		var showImage = function(photoObject, currentContainer, activeContainer){
			// Set the background image of the new active container
			$("#headerimg" + activeContainer).css({
				"background-image": "url(" + templateDir + "/images/headers/" + photoObject + ")",
				"display": "block",
				"z-index": 1
			});
			
			// Fade out the current container
			// and display the header text when animation is complete
			$("#headerimg" + currentContainer).fadeOut().css({
				"z-index": 2
			});
		};
		
		// We should statically set the first image
		navigate();
		
		$('#headerimg1').css({
			"background-image": "none"
		});
		
		// Start playing the animation
		interval = setInterval(function(){
			navigate();
		}, slideshowSpeed);
	}
	/** END - Background image slideshow **/
	
	
	/*
	 * Frequently Asked Questions
	 */
	
	$(".faq-question-answer").each (function() {
		$(this).css("height", $(this).height());
	});
	
	$(".faq-subgroup-container").hide();
	$(".faq-group h2")
		.wrapInner("<a href='#non'></a>")
		.addClass('js-enabled')
		.click(function(){
			jQuery(this).toggleClass("opened")
			jQuery(this).next(".faq-subgroup-container").slideToggle({ duration: 1000, easing: 'easeOutQuint'});
			return false;
		})
		.eq( 0).click();
	$(".faq-question-container").hide();
	$(".faq-subgroup h3")
		.wrapInner("<a href='#non'></a>")
		.addClass('js-enabled')
		.click(function(){
			jQuery(this).toggleClass("opened")
			jQuery(this).next(".faq-question-container").slideToggle({ duration: 1000, easing: 'easeOutQuint'});
			return false;
		})
		.eq( 0).click();	
	/** END - Frequently Asked Questions **/
	
	/*
	 * Product Listing Page (Copied from FAQ)
	 */
	
	$(".product-question-answer").each (function() {
		$(this).css("height", $(this).height());
	});
	
	$(".product-subgroup-container").hide();
	$(".product-group h2")
		.wrapInner("<a href='#non'></a>")
		.addClass('js-enabled')
		.click(function(){
			jQuery(this).toggleClass("opened")
			jQuery(this).next(".product-subgroup-container").slideToggle({ duration: 1000, easing: 'easeOutQuint'});
			return false;
		})
		.eq( 0).click();
	$(".product-question-container").hide();
	$(".product-subgroup h3")
		.wrapInner("<a href='#non'></a>")
		.addClass('js-enabled')
		.click(function(){
			jQuery(this).toggleClass("opened")
			jQuery(this).next(".product-question-container").slideToggle({ duration: 1000, easing: 'easeOutQuint'});
			return false;
		})
		.eq( 0).click();	
	/** END - Products listing page **/
	
	/*
	 * Firmware Listing Page (Copied from FAQ)
	 */
	
	$(".firmware-question-answer").each (function() {
		$(this).css("height", $(this).height());
	});
	
	$(".firmware-subgroup-container").hide();
	$(".firmware-group h2")
		.wrapInner("<a href='#non'></a>")
		.addClass('js-enabled')
		.click(function(){
			jQuery(this).toggleClass("opened")
			jQuery(this).next(".firmware-subgroup-container").slideToggle({ duration: 1000, easing: 'easeOutQuint'});
			return false;
		})
		.eq( 0).click();
	$(".firmware-question-container").hide();
	$(".firmware-subgroup h3")
		.wrapInner("<a href='#non'></a>")
		.addClass('js-enabled')
		.click(function(){
			jQuery(this).toggleClass("opened")
			jQuery(this).next(".firmware-question-container").slideToggle({ duration: 1000, easing: 'easeOutQuint'});
			return false;
		})
		.eq( 0).click();	
	/** END - Firmware listing page **/
	
	/*
	 * Tips and Tricks
	 */
	$("#listing-tips .listing-tip div").each (function() {
		$(this).css("height", $(this).height());
	});
	$("#listing-tips .listing-tip").each (function() {
		$(this).css("height", $(this).height());
	});
	$("#listing-tips .listing-tip").hide();
	$("#listing-tips .listing-item h2")
		.wrapInner("<a href='#non'></a>")
		.addClass('js-enabled')
		.click(function(){
			jQuery(this).toggleClass("opened")
			jQuery(this).next(".listing-tip").slideToggle({ duration: 1000, easing: 'easeOutQuint'});
			return false;
		});
	if (window.location.hash) {
		var item = $("#" + window.location.hash.substr(1));
		if (0 < item.length) item.click();
	} else {
		$("#listing-tips .listing-item:first h2").click();
	}
	/** END - Tips and Tricks **/
	
	/*
	 * Gallery Media Info Table
	 */
	$(".widget-content").each (function() {
		$(this).css("height", $(this).height());
	});
	
	/*
	 * Gallery Search 
	 */
	var mediaDDL = $(".gallery-search-form .search-media");
	
	if ("camera" != mediaDDL.val()) {
		mediaDDL.append("<option value=\"camera\">Lumix G</option>");
	}

	mediaDDL.change(function(){
		if ("camera" == $(this).val()){
			$(".gallery-search-form .search-camera").show();
			$(".gallery-search-form .search-term").val("").hide();
		} else {
			$(".gallery-search-form .search-camera").val("").hide();
			$(".gallery-search-form .search-term").show();
		}
	}).change();
	/** END - Gallery Search **/
	
	/**Ts and Cs**/
	$(".tsandcs-trigger").css({'display':'block'});
	$(".tsandcs-expanded").css({'display':'none'});
	
	$(".tsandcs-trigger a")
		.addClass('js-enabled')
		.click(function(){
			jQuery(this).toggleClass("opened")
			jQuery(this).parent().next(".tsandcs-expanded").toggle();
			return false;
		});
	/**End Ts and Cs**/

	/**Media List Widget**/
	$('.media-list li').hover(function(){
		$(this).siblings().stop().fadeTo('500','0.7');
	},function(){
		$(this).siblings().stop().fadeTo('500','1');
	});
	
	
	/* Products Page - Image Picker */
	 $("#image-picker .option a")
        .click(function() { 
            var src = $(this).attr("rel");
            $("#image-picker .image img").attr("src", src);
            $("#image-picker .image a").attr("href", src);
            
            return false;
        });
        
	


	/* End of Product Page - Image Picker */	

	/*GF2 Campaign Site*/
	if ($('#showcase-gallery').length) {
		
		$('#showcase-gallery').galleria({
            width:950,
            height:570,
            autoplay: 7000,
            showCounter: false,
            thumbnails: false,
            queue: false,
            debug: false,
            imageCrop: false,
            transition: 'slide',
            transitionInitial: 'fade',
            easing: 'easeOutQuad',
            transitionSpeed: 1000,
            extend: function(options) {
                var gallery = this; // "this" is the gallery instance
                var fullScreen = false;

                $('.caption a').click(function(){
        			gallery.$('galleria-info-close,info-text').slideToggle();
        			gallery.$('galleria-info-link').slideToggle();
        			if($(this).hasClass('on')){
        				$(this).removeClass('on');
        			}else{
        				$(this).addClass('on');
        			}
		        });
		        
		        $('.gallery-fullscreen a').click(function(){
		        	gallery.toggleFullscreen();
		        	fullScreen = true;
		   		});
		   		$('.closeFullScreen').live('click',function(){
		   			gallery.toggleFullscreen();
		       		
		   		});
		   		 $('.showcase-next a').click(function(){
		       		gallery.next();
		   		});
		   		 $('.showcase-prev a').click(function(){
		       		gallery.prev();
		   		});
		   		$('.gallery-other a').click(function(){
		       		$('#showcase-gallery-overlay').fadeToggle();
		       		if($(this).hasClass('on')){
        				$(this).removeClass('on');
        				gallery.play();
        			}else{
        				$(this).addClass('on');
        				gallery.pause();
        			}
		       		
		   		});
		   		gallery.$('images').bind('dblclick doubletap',function(){
		   			gallery.toggleFullscreen();	
	   			}).addSwipeEvents().bind('swipe',function(evt,touch){
	   				var event = touch.eventType;
	   				if(event=='swipeleft'){
	   					gallery.next();
	   				}
	   				if(event=='swiperight'){
	   					gallery.prev();
	   				}
   				});
		   		gallery.bind("fullscreen_enter", function(e) {
		   			$('body').append('<a href="javascript:void(0)" class="closeFullScreen">X</a>');
	   				$('head').append('<meta id="viewport" name="viewport" content="width=device-width; initial-scale=1.0; user-scalable:no;">');
	   				$('body').scrollLeft(0);
	   				$('body').scrollRight(0);
	   				fullScreen = true;
	   			});
	   			gallery.bind("fullscreen_exit", function(e) {
	   				$('viewport').remove();
	   				$('.closeFullScreen').remove();
	   				gallery.attachKeyboard({
			            left: gallery.prev,
			            right: gallery.next,
						70: function() {
					        gallery.toggleFullscreen();
					    }
					    
			    	});
	   				
		       		fullScreen = false;
   				});
	   			gallery.bind("idle_enter", function(e) {
	   				gallery.play(7000);
	   				$('a.closeFullScreen').css('opacity','0');
   				});
   				gallery.bind("idle_exit", function(e) {
	   				gallery.pause();
	   				$('a.closeFullScreen').css('opacity','0.5');
	   				
   				});
				
   				gallery.attachKeyboard({
			            left: gallery.prev,
			            right: gallery.next
			    });
   				
	   				
	   			setTimeout("$('.caption a').click()",200);
	   					
            }
        });
       
        
        
       
	}	
	
    //Video navigation carousel
    if($('#showcase-video-nav').length && $('.vzaar_media_player').length){
    	
    		
    	function switchVideo(videoId){
    		var mediaplayer = $('.vzaar_media_player');
    		mediaplayer.fadeTo('fast',0.1,function(){
    				mediaplayer.html('<object id="video" width="942" height="529" type="application/x-shockwave-flash" data="http://view.vzaar.com/'+videoId+'.flashplayer"><param name="movie" value="http://view.vzaar.com/'+videoId+'.flashplayer"><param name="allowScriptAccess" value="always"><param name="allowFullScreen" value="true"><param name="wmode" value="transparent"><param name="flashvars" value="autoplay=true&border=none"><embed src="http://view.vzaar.com/'+videoId+'.flashplayer" type="application/x-shockwave-flash" wmode="transparent" width="942" height="529" allowScriptAccess="always" allowFullScreen="true" flashvars="autoplay=true&border=none"></embed><video width="942" height="529" src="http://view.vzaar.com/'+videoId+'.mobile" poster="http://view.vzaar.com/'+videoId+'.image" controls onclick="this.play();"></video></object>');
    				mediaplayer.fadeTo('fast',1);
				});
    	}
    	
    	var hashIndex = 1;
    	
    	
    		
	    
	    function updateVideo(e){
	    	var hash = e.value;
	    	if(hash.length>0){
		    	var elem = $('a[href=#'+hash+']');
		    	var videoId = elem.attr('rel');
				hashIndex = elem.parent().index(); 
				
		    	if(videoId != undefined ){
					switchVideo(videoId);
				}
				_gaq.push(['_trackEvent', 'Lumix G3 Videos', 'Play', hash]);
			}else{
				$.address.value('doc-will-cooper-mitchell');
			}	
			
	    }
	    function initCarousel(e){
	    	var hash = e.value;
	    	if(hash.length>0){
		    	var elem = $('a[href=#'+hash+']');
		    	var videoId = elem.attr('rel');
				hashIndex = elem.parent().index(); 
			}
	    	
			jQuery('#showcase-video-nav').jcarousel({
        	wrap: 'circular',
        	start: hashIndex+1,
        	size: 10,
        	visible: 3
    		});
	    }
		$.address.init(function(){
    		$('#showcase-video-nav a').address();
		}).change(updateVideo).init(initCarousel).history(true);
		
    	
    }
        
        
        
        
        $('#showcase-container #pagination a').click(function() {
        	var pageid = $(this).attr("rel");
        	$('#showcase-container .tab-content').slideUp();
        	
        	$('#page'+pageid).delay(400).slideDown();
        	
        	return false;
        });
        

	
});
