// Check to see if the function Exists
jQuery.fn.exists = function(){
	return jQuery(this).length > 0;
}

var gallery;
var is_autoplay;
var window_name;
var animations = [];
var currentAnimationIndex = 0;


jQuery.fn.aPosition = function() {
	thisLeft = this.offset().left;
	thisTop = this.offset().top;
	thisParent = this.parent();
	parentLeft = thisParent.offset().left;
	parentTop = thisParent.offset().top;
	return {
		left: thisLeft-parentLeft,
		top: thisTop-parentTop
	}
} 

$(document).ready(function(){
	
	//set in collections/index.tpl.,.
	var is_collections = (window_name == "collections");
	
	// Set Auto play
	is_autoplay = true;
	
	// If the page is collections then...
	if(is_collections) {
		// If cookie is set - play the intro animation
		if(readCookie("animated_collections") == null) {
			init_gallery_load();
			
			// Create cookie so not to repeate animation
			createCookie("animated_collections", "1", 1);
			
			// Set Auto play
			is_autoplay = false;	
		} 
	}
	
	//set in designers/index.tpl.,.
	var is_designers = (window_name == "designers");

	// If the page is designers then...
	if(is_designers) {
		// If cookie is set - play the intro animation
		if(readCookie("animated_designers") == null) {
			init_designer_load();
			
			// Create cookie so not to repeate animation
			createCookie("animated_designers", "1", 1);
			
			// Set Auto play
			is_autoplay = false;	
		} 
	}

	/* 
		PAGINATION 
		Used in store/catalogue.tpl, store/category.tpl and press/index.tpl
	*/
	if ($("#thumbView").exists()) {
		$("#thumbView").easySlider({ lazyPaging : 'store_pages' });
	}
	
	/*
		COLLECTION GALLERY
		Used in collections/index.tpl and collections/view.tpl 
	*/
	if ($("#col_gallery_thumbs").exists()) {
		$('#col_gallery_content').css('display', 'block');
	

		$("#col_gallery_content").hover(function(){
			fadeCaption(true);
		},function(){
			fadeCaption(false);
		});
		
		// Initialize Advanced Galleriffic Gallery
		gallerific();
	}
	
	/*
		PRESS GALLERY
		Used in press/index.tpl and press/view.tpl 
	*/
	if ($("#press_gallery_thumbs").exists()) {
		$('#press_gallery_content').css('display', 'block');
	
		// Initialize Advanced Galleriffic Gallery
		gallerific();
	}
	
	/*
		FANCY BOX
		Used in press/view.tpl and store/view.tpl
	*/
		$("a#single_image").fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': true });
		$("a.fancybox_item").fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': true });
		$("a#slide_fancybox").fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': true });
		
	/*
		FANCY BOX - iFrame
		Used to display the contact form in a iFrame
	*/
	if ($("a.iframe").exists()) {
		$("a.iframe").fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'frameWidth': 550, 'frameHeight': 270, 'overlayShow': true });
	}
	
	/*
		TEXT INPUT
		Display text in a form input, and remove it upon click
	*/
	if ($("#VariationQuantity").exists()) {
		$('#VariationQuantity').val('Quantity');
		
		$('#VariationQuantity').focus(function() {
			if ($('#VariationQuantity').val() == 'Quantity') {
				$('#VariationQuantity').val('');
			}
		});
		
		$('#VariationQuantity').blur(function() {
			if ($('#VariationQuantity').val() == '') {
				$('#VariationQuantity').val('Quantity');
			}
		});
	}
	
	/*
		GALLERY NAVIGATION
		Fade arrows in / out on mouse over
	*/
	$("#controls #nav-prev").hover(
		function(){
			slideGalleryNav(true, "nav-prev")
		},
		function(){
			slideGalleryNav(false, "nav-prev")
		}
	); 
	
	$("#controls #nav-next").hover(
		function(){
			slideGalleryNav(true, "nav-next")
		},
		function(){
			slideGalleryNav(false, "nav-next")
		}
	); 	
	
});

// Slide the menu Open and Close
function slideGalleryNav(open, side) {

	if(side == "nav-prev"){
		$("#controls #" + side + " a").animate({ 
			left: (open ? "0" : "-24px")
		}, 500, 'swing');
	} else if (side == "nav-next") {
		$("#controls #" + side + " a").animate({ 
			right: (open ? "0" : "-24px")
		}, 500, 'swing');
	}
}


function display_img(thumb_src, full_src, target, index) {
	$('.altimg').attr({
		"class" : "altimg"
	});
	$('#alt_img_' + index).attr({
		"class" : "altimg active"
	});
	$('#' + target + ' > div > a').attr({
		"href" : full_src
	});
	$('#' + target + ' > div > a > img').attr({
		"src" : thumb_src
	});
	$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
}


function ucc_submit() {
	if ($('#uccTo').val() != '') {
		$('#ucc_form').submit();
	}
}


function ucc_toggle() {
	$('#uccTo').val('');
	$('#uccToDiv').toggle('fast');
}

function executeNextAnimation() {
	if(currentAnimationIndex < animations.length) {
		//alert(currentAnimationIndex);
		var animation = animations[currentAnimationIndex];
		animation(executeNextAnimation);
		currentAnimationIndex++;
	}
}

function init_gallery_load() {
	
	// Set CSS before we can start the animation
	prepareGalleryAnimations();

	// Show the body
	displayAnimationBody();

	// Slide in main gallery image
	var content_width = $("#content_wrap").width();
	var content_position_left = $("#main_wrap").aPosition().left;
	var content_off_screen = 0 - (content_width + content_position_left);
	
	// Position Elements off screen
	$("#content_wrap").css("margin-left", content_off_screen + "px");
	$("#menu_wrap").css("margin-left", content_off_screen + "px")
		
	// pre load first image,
	// on image load...
	$('<img />')
    .attr('src', first_image_src)
    .load(function(){        

		animations = [fadeBanner, slideContentWrap, slideMonogram, resetGalleryCSS, slideMenuOpen, slideMenuClose, resetGalleryNav, startAutoPlay];
		executeNextAnimation();

    });
	
}

// Set CSS so we can animate 
function prepareGalleryAnimations(){
	// Hide the banner
	$("#banner h1").css('display', 'none');
	// Hide the menu slider
	$("#slider").css('display', 'none');
	// Hide the image count
	$(".image-count").css('display', 'none');
	// Remove overflow from content wrap to see animation
	$("#content_wrap").css('overflow', 'visible');
	// Hide Gallery Arrows
	// $("#controls").css('display', 'none');
}

// Reset the CSS on the monogram so we can use the menu
function resetGalleryCSS(onComplete) {
	$("#content_wrap").css('overflow', 'hidden');	
	$("#slider").css('display', 'block');
	window.setTimeout(function(){  onComplete() }, 10);
}

function init_designer_load() {

	// Set CSS before we can start the animation
	prepareDesignerAnimations();

	// Show the body
	displayAnimationBody();

	// Slide in main gallery image
	var content_width = $("#content_wrap").width();
	var content_position_left = $("#main_wrap").aPosition().left;
	var content_off_screen = 0 - (content_width + content_position_left);
	
	// Position Elements off screen
	$("#content_wrap").css("margin-left", content_off_screen + "px");
	$("#menu_wrap").css("margin-left", content_off_screen + "px")
		
	// pre load first image,
	// on image load...
	$('<img />')
    .attr('src', first_image_src)
    .load(function(){        

		animations = [slideContentWrap, slideMonogram, resetDesignerCSS, fadeControls, startAutoPlay];
		executeNextAnimation();

    });
	
}

// Set CSS so we can animate 
function prepareDesignerAnimations(){
	// Hide the menu slider
	$("#slider").css('display', 'none');
	// Remove overflow from content wrap to see animation
	$("#content_wrap").css('overflow', 'visible');
	// Hide Gallery Arrows
	//$("#controls").css('display', 'none');
}

// Reset the CSS on the monogram so we can use the menu
function resetDesignerCSS(onComplete) {
	$("#content_wrap").css('overflow', 'hidden');	
	$("#slider").css('display', 'block');
	window.setTimeout(function(){  onComplete() }, 10);
}

// Display the body class
function displayAnimationBody(){
	$("body.animation_class").css('visibility', 'visible');
}

// Fade in Banner
function fadeBanner(onComplete){
	$("#banner h1").fadeIn(1000, onComplete);	
}

// Slide the content_wrap from off screen (left) to position
function slideContentWrap(onComplete){
	$("#content_wrap").animate({ 
		marginLeft: 0
	}, 1500, 'swing', onComplete);
}

// Slide the Monogram from off screen into postion 
function slideMonogram(onComplete){
	$("#menu_wrap").animate({ 
		marginLeft: 0
	}, 1000, 'swing', onComplete);
}

// Slide the menu Open and Close
function slideMenu(open, onComplete) {
	$("#slider").animate({ 
		marginLeft: (open ? "56px" : "-130px")
	}, 500, 'swing', onComplete);
}

// Slide the menu Open
function slideMenuOpen(onComplete) {
	slideMenu(true, onComplete);
}

// Slide the menu Close
function slideMenuClose(onComplete) {
	window.setTimeout(function(){  slideMenu(false, onComplete); }, 1500);
}

// Fade in Gallery controls
function fadeControls(onComplete){
	//$("#controls").fadeIn(500, onComplete);	
}

// Fade in Gallery Image Count
function fadeImageCount(onComplete){
	$(".image-count").fadeIn(500, onComplete);	
}

// Reset both Gallery controls and Image Count
function resetGalleryNav(onComplete){
//	alert('reset gal nav');
	fadeControls();
	fadeImageCount();
	window.setTimeout(function(){  
		onComplete();
	}, 10);
}

// Start Auto Play on the gallery
function startAutoPlay(onComplete) {
	
	window.setTimeout(function(){  
		gallery.play();
		onComplete();
	}, 10);
}

// Gallerific
function gallerific(){
	gallery = $('.gallery').galleriffic({
		delay:                     4000,
		numThumbs:                 10,
		preloadAhead:              10,
		enableTopPager:            false,
		enableBottomPager:         false,
		maxPagesToShow:            7,
		imageContainerSel:         '#slideshow',
		controlsContainerSel:      '#controls',
		captionContainerSel:       '#caption',
		loadingContainerSel:       '#loading',
		renderSSControls:          false,
		renderNavControls:         true,
		playLinkText:              'Play Slideshow',
		pauseLinkText:             'Pause Slideshow',
		prevLinkText:              'Previous Photo',
		nextLinkText:              'Next Photo',
		nextPageLinkText:          'Next &rsaquo;',
		prevPageLinkText:          '&lsaquo; Prev',
		enableHistory:             false,
		autoStart:                 is_autoplay,
		syncTransitions:           true,
		defaultTransitionDuration: 1000,
		onSlideChange:             function(prevIndex, nextIndex) {
			// Update the photo index display
			$('div.image-count').html('Image '+ (nextIndex+1) +' / '+ this.data.length);
		},
		onPageTransitionOut:       function(callback) {
			this.fadeTo('fast', 0.0, callback);
		},
		onPageTransitionIn:        function() {
			this.fadeTo('fast', 1.0);
		}
	});	
}

// Fade in Caption on Gallery
function fadeCaption(fadeIn){
	if(fadeIn){
		$("#col_gallery .content span.caption").fadeIn(500);
	} else {
		$("#col_gallery .content span.caption").fadeOut(500);
	}
}

// Create a cookie once the animation has been played
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=/";
}

// Check to see if a cokoie has been set
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;
}

// Destroy the cookie after x days
function eraseCookie(name) {
	createCookie(name,"",-1);
}