// Set hash function for pages
var glamHash = {
	currentHash: window.location.hash,
	pageChange: function(theHash){
		for (var i=0; i<hashArray.length; i++) {
			if(hashArray[i].replace(/#/,'') == theHash){
				groovyDeck.goTo((i+1));
			}
		};
	},
	checkHash: function(){
		if(window.location.hash != glamHash.currentHash){
	        glamHash.currentHash = window.location.hash;
	        glamHash.pageChange(glamHash.currentHash.substr(1, glamHash.currentHash.length));
	    }
	},
	set: function(new_hash){
		glamHash.currentHash = new_hash;
		window.location.hash = new_hash;
	},
	init: function(){
		if (window.location.pathname == '/') {
			hashCheck = setInterval("glamHash.checkHash()", 50);
		}
	}	
};

var slideEvents = {
	slideTo: function(slide){
		for (var i=0; i<hashArray.length; i++) {
			if(hashArray[i].replace(/#/,'') == slide){
				groovyDeck.goTo((i+1));
			}
		};
	},
	init: function(){
		if($('.slidedeck dt').length){
			$('.slidedeck dt').click(function(e){
				e.preventDefault();
				if($(this).hasClass('slide1')){
					if($(this).hasClass('active')){						
						glamHash.set('#home');
					}
				}else if($(this).hasClass('slide2')){
					if($(this).hasClass('active')){
						glamHash.set('#our-work');
					}
				}else if($(this).hasClass('slide3')){
					if($(this).hasClass('active')){
						glamHash.set('#meet-the-directors');
					}
				}else if($(this).hasClass('slide4')){
					if($(this).hasClass('active')){
						glamHash.set('#green-production');
					}
				}else if($(this).hasClass('slide5')){
					if($(this).hasClass('active')){
						glamHash.set('#our-ethics');
					}
				}else if($(this).hasClass('slide6')){
					if($(this).hasClass('active')){
						glamHash.set('#get-in-contact');
						$('#binder').addClass('adjusted');
					}
				}
				expandList.closeAll();
				return false;
			});
		}
		if($('a.slideLink').length){
			$('a.slideLink').click(function(){
				slide = this.href.replace(/#/,'');
				slideEvents.slideTo(slide);
				expandList.closeAll();
			});
		}
	}	
}; 
 
var videoThumb = {
	init: function(){
		if($('.videoThumb').length){
			$('a.videoThumb').mouseenter(function(){
				$(this).find('img.playBtn').stop().css({
					opacity: 0,
					display: 'block'
				}).animate({
					opacity: 1
				},150);
			});
			$('a.videoThumb').mouseleave(function(){
				$(this).find('img.playBtn').stop().animate({
					opacity: 0
				},150);
			});
		}
		if($('.videoBlock').length){
			$('.videoBlock .videoMeta h4, .videoBlock .videoMeta .watchVideo').mouseenter(function(){
				$(this).parents('.videoBlock').find('img.playBtn').stop().css({
					opacity: 0,
					display: 'block'
				}).animate({
					opacity: 1
				},150);
			});
			$('.videoBlock .videoMeta h4, .videoBlock .videoMeta .watchVideo').mouseleave(function(){
				$(this).parents('.videoBlock').find('img.playBtn').stop().animate({
					opacity: 0
				},150);
			});
		}
		if($('.featuredVideo h4 a').length){
			$('.featuredVideo h4 a').mouseenter(function(){
				$(this).parents('.featuredVideo').find('img.playBtn').stop().css({
					opacity: 0,
					display: 'block'
				}).animate({
					opacity: 1
				},150);
			});
			$('.featuredVideo h4 a').mouseleave(function(){
				$(this).parents('.featuredVideo').find('img.playBtn').stop().animate({
					opacity: 0
				},150);
			});        
		}
        if($('#featured_directors .director').length){
			$('.director .name').mouseenter(function(){
				$(this).parents('.director').find('img.playBtn').stop().css({
					opacity: 0,
					display: 'block'
				}).animate({
					opacity: 1
				},150);
			});
			$('.director .name').mouseleave(function(){
				$(this).parents('.director').find('img.playBtn').stop().animate({
					opacity: 0
				},150);
			});
		}
		if($('#view_reel_link').length){
			var hrefVal = $('a#demo_reel').attr('href');
			$('#view_reel_link').attr('href',hrefVal);
		}
	}
};

var fancyBox = {
	init: function(){
		if($('.fancybox').length){
			$('.fancybox').fancybox({
				hideOnContentClick: false,
				centerOnScroll: true,
				overlayOpacity: 0.85,
				overlayColor: '#000',
				titleShow: false,
				speedIn: 500,
				speedOut: 300
			});
		}
	}
};
var expandList = {
	href: '',
	closeAll: function(){
		$('#glam_clients, #glam_directors').slideUp(function(){
			$('.toggleSymbol').html('[+]');
			$('#glam_directors, #glam_clients').removeClass('opened');
		});
	},
	expand: function(link){
		$(link).find('.toggleSymbol').html('[-]');
		$(expandList.href).slideDown(function(){
			$(expandList.href).addClass('opened');
			$.scrollTo(expandList.href,500,{offset:{top:-20}});
		});				
	},
	collapse: function(link){
		$(link).find('.toggleSymbol').html('[+]');
		$(expandList.href).slideUp(function(){
			$(expandList.href).removeClass('opened');
		});
	},
	init: function(){
		if($('.expandList').length){
			$('.expandList').click(function(e){
				e.preventDefault();
				expandList.href = '#'+this.href.replace(/.+#/,'');
				if($(expandList.href).hasClass('opened')){
					expandList.collapse(this);
				}else{
					expandList.expand(this);
				}
				return false;
			});	
		}
	}
};

function currentCheck (deck){
	if(deck.current != 6){
		if($('#binder').hasClass('adjusted')) $('#binder').removeClass('adjusted');
	}
};

var homeFeatures = {
	previous: '',
	current: '',
	filter: function(filterLink, filterResult){
		homeFeatures.previous = homeFeatures.current;
		homeFeatures.current = filterResult;
		
		$('.slide1 a.filter').removeClass('active');
		filterLink.addClass('active');
		Cufon.refresh('.slide1 .preview h3');
		
		$('#'+homeFeatures.previous).fadeOut('fast',function(){
			$('#'+homeFeatures.current).fadeIn('fast',function(){
				if(homeFeatures.current == "testimonials"){
					$('.testimonialContainer').cycle('resume');
				}else{
					$('.testimonialContainer').cycle('pause');
				}
			});
		});		
	},
	testimonials: function(){
		if ($('.testimonialContainer').length) {
			// Initiate cycler
			$('.testimonialContainer').cycle({
				speed: 1000,
				timeout: 5000,
				pager: '.testimonialNav',
			});
			$('.testimonialNav a').html('&bull;');
			$('.testimonialContainer').cycle('pause');
		}
	},
	init: function(){
		if($('.slide1 a.filter').length){
			homeFeatures.current = $('.slide1 .result:visible').attr('id');
			$('.slide1 a.filter').click(function(e){
				e.preventDefault();
				var filterHref = this.href.replace(/.+#/,'');
				homeFeatures.filter($(this),filterHref);
			});
		}
		homeFeatures.testimonials();
	}
};
 var Contact = { 	
 	init: function(){
		if($('#form_contact').length){
            $('#form_contact li#hidden_fields').append('<input type="hidden" name="cerberus" value="1" id="cerberus" />');
			window.validateForms['form_contact'] = new FormValidator('form_contact',{name: 'Name Required', email: 'Email Address Required',phone: 'Phone Number Required'});
		}
        if ( $('input:hidden[name=cerberus]').val() == '1' ) {
            $('#form_contact').submit(function(s){	
    			s.preventDefault();
    			return false;
    		});
    		$('#form_contact input#input_submit').click(function(e){
    			if(window.validateForms['form_contact'].validate()){
    				var success;
    				e.preventDefault();
    				var parameters = $('#form_contact').serialize();
                    $.ajax({
    					url: '/wp-content/themes/glam_v2/lib/contact_processor.php',
    					data: parameters,
                        dataType: 'json',
                        type: 'POST',
    					complete: function(response){
    						if(response){
                            var responseJSON = $.parseJSON(response.responseText);
    							$('#contact_success').fadeIn('fast',function(){
    								$('#contact_success').animate({
    									opacity: 1.0
    								}, 3000, function(){
    									$('#contact_success').fadeOut('slow');
    								});
    							});
    						}else{
    							$('#contact_fail').fadeIn('fast',function(){
    								$('#contact_fail').animate({
    									opacity: 1.0
    								}, 3000, function(){
    									$('#contact_fail').fadeOut('slow');
    								});
    							});
    						}						
    					}
    				});		
    				return false;
    			}
    		});
        }				
	}
 }

var Comments = { 	
	init: function(){
		if($('#commentform').length){
			window.validateForms['commentform'] = new FormValidator('commentform',{name: 'Name Required', email: 'Email Address Required'});
		}
	}
};

var ScrollPane = {
	init: function(){
		if($('#client_videos').length){
			$('#client_videos').jScrollPane({
				showArrows: true,
				scrollbarWidth: 12,
				scrollbarMargin: 0,
				dragMaxHeight:159
			});
		}
	}
};

var MetaLinks = {
	init: function(){
		$('#sidebar_meta ul a').attr('target','_blank');
	}
};

var ImageLoader = {
    imagePath: 'http://glam.dtelepathy.com/wp-content/themes/glam_v2/images/slidedeck/',
    //imagePath: 'http://www.groovylikeamovie.localhost/wp-content/themes/glam_v2/images/slidedeck/',
    check: function(l,c,s){
        if(l == c){            
            for (var i = 2; i < s; i++) {
            	$('.slidedeck dt.slide'+i).css({
                    backgroundColor: 'transparent',
                    backgroundImage: 'url('+ImageLoader.imagePath+'glam_spines_'+i+'.png)',
                    backgroundRepeat: 'no-repeat'
                });
                $('.slidedeck dt.slide'+i+' .spineCap').css({
                    backgroundColor: 'transparent',
                    backgroundImage: 'url('+ImageLoader.imagePath+'glam_spine_caps_'+i+'.png)',
                    backgroundRepeat: 'no-repeat'
                });
            };
            $('.slidedeck dt:not(.slide1)').fadeIn(1000,function(){
                $('.slidedeck dd:not(.slide1)').show();
            });
        }
    },
    init: function(){
        var imageSpineArray = [];
        var imageCapArray = [];
        var loaded = [];
            
        var spineCount = ($('.slidedeck dt').length);
        var index = 0;
        
        for (var i = 2; i < (spineCount+1); i++) {
        	index = i;
            imageSpineArray[index] = $(new Image());
            imageSpineArray[index].attr("src",ImageLoader.imagePath+'glam_spines_'+index+'.png').load(function(){
                loaded.push('loaded');
                ImageLoader.check(loaded.length,((spineCount-1)*2),(spineCount+1));               
            });
            imageCapArray[index] = $(new Image());
            imageCapArray[index].attr("src",ImageLoader.imagePath+'glam_spine_caps_'+index+'.png').load(function(){
                loaded.push('loaded');
                ImageLoader.check(loaded.length,((spineCount-1)*2),(spineCount+1));               
            });            
        };
    }
};
 
var SlideLoad = {
    init: function(slide){
        ScrollPane.init();
        if(slide == 1){
            $('.slidedeck dt:not(.slide1), .slidedeck dd:not(.slide1)').hide();
        }        
    }
}

 $(document).ready(function(){
 	window.validateForms = {};
	fancyBox.init();
 	videoThumb.init();
	slideEvents.init();
	expandList.init();
	glamHash.init();
	homeFeatures.init();
	Contact.init();
	Comments.init();
    //ScrollPane.init();
	MetaLinks.init();
    ImageLoader.init();
	DOMUtilities.init();
 });
  
/**
 * DOM Utilies Object for handling basic DOM actions
 * @author					Dave Shepard
 * @version					1.0
 * @required libraries:		JQuery 1.3.2 or later
 * 
 * Usage:
 *     $(document).ready(function(){
 *     		DOMUtilities.init();
 *     });
 *     
 * Can be initialized via the init(); method to apply to entire <body> or
 * a scope can be passed to limit the initialization to the child elements
 * of a particular element. Individual methods can als be called and passed
 * a scope.
 */
var DOMUtilities = {
	targetBlank: function(locality){
		// XHTML 1.0 Strict work around for external links
		$(locality+' a[rel*="external"]').attr("target","_blank");
	},
	inputAutoClear: function(locality){
		$(locality+' input.clearField').focus(function(){
			if(this.defaultValue == this.value) this.value='';
		}).blur(function(){
			if(this.value == '') this.value = this.defaultValue;
		});
	},
	imgRollover: function(locality){
		// Image roll-over setup
		$(locality+' img.rollOver, '+locality+' input[type="image"].rollOver')
			.mouseover(function(){
				if (this.src.indexOf("_i.") != -1) {
					this.src = this.src.replace("_i.", "_o.");
				}
			}).mouseout(function(){
				if (this.src.indexOf("_o.") != -1) {
					this.src = this.src.replace("_o.", "_i.");
				}
				if(this.src.indexOf("_a.")) {
					this.src = this.src.replace("_a.","_i.");
				}
			}).filter("input").mousedown(function(){
				this.src = this.src.replace("_o.","_a.");
			}).mouseup(function(){
				this.src = this.src.replace("_a.","_i.");
			});
	},
	init: function(locality){
		if(locality == null) {
			locality = "body";
		}
		this.targetBlank(locality);
		this.inputAutoClear(locality);
		this.imgRollover(locality);
	}
}
