var img_path = '/wp/wp-content/themes/psps/img/';

$(window).ready(function() {
	$('.home .boxes .ribbon-box').gridify(4, '.content');
});

$(document).ready(function() {
    $('#search-form label').label_as_input();
	$('ul li:first-child').addClass('first');
    $('ul li:last-child').addClass('last');
    $('.cols .col:last-child').addClass('last');
	$('.address-box:last-child, tbody tr:last-child').addClass('last');

	$('.product-features tr:odd').addClass('odd');
	
	$('#job-form label').label_as_input();
	$('#contest-form label').label_as_input();
	
	$('#quote-form .field-text:odd').after('<div style="clear:both;"></div>');

	$("ul.sf-menu").superfish({dropShadows : true}).find('ul').bgIframe({opacity:false});
	$('ul.sf-menu > li, ul.sf-menu > li > a').addClass('level-1');
	$('ul.sf-menu li a').hover(function() {
		$(this).addClass('sfHover');
	},
	function() {
		$(this).removeClass('sfHover');
	});

	$('#subnav .menu > li, #subnav .menu > li > a').addClass('level-1');

	$('footer .menu-item').not(':last').after('<li class="sep">|</li>');

	$('.directory .contact a, #content.location .employee .email, #getPsNews').click(function() {
		PSPS.AjaxPopup(this, function() {
			PSPS.Contact.init();
		});
		return false;
	});

	$.blockUI.defaults.css = {};
	$.blockUI.defaults.overlayCSS = {
		'backgroundColor' : '#fff',
		'opacity' : 0.8
	};

	PSPS.Features.init();
	PSPS.MovieCovers.init();
	PSPS.Products.init();
	PSPS.Directory.init();
	PSPS.Carousel.init();
	PSPS.Location.init();
	PSPS.Contact.init();
	PSPS.HumanCheck();
	PSPS.History.init();
});

var PSPS = {
	loading_img : img_path + 'popup/loading.gif',

	HumanCheck : function() {
		$('#what_human').attr('checked', 'checked');
		$('.field-what').hide();
	},

	Contact : {
		
		init : function() {
		
			$('#contact-form').submit(function() {
				var form = $(this);
				var post_data = form.serialize();
				$.post(form.attr('action') + '?ajax=1', post_data, function(data) {
					form.html(data);
					$('.error-msg, .error', form).hide().fadeIn();
					$('#contact-form .field-what').hide();
				});
				return false;
			});

			PSPS.HumanCheck();
		}
		
	},

	Location : {
		
		init : function() {
			if (!$('#content.location').get(0)) return;
			
			$('.tabs h4').attr('rel', 'reg');
			
			var ahc = $('.employee.ahc');
			if (ahc.size() > 0) {
				$('.tabs').append('<h4 class="ahc" rel="ahc">After Hours Contacts</h4>');
			}
			
			$('.tabs h4').click(function() {
				$('.tabs .current').removeClass('current');
				$(this).addClass('current');
				
				$('.employee').show().not('.' + $(this).attr('rel')).hide();
			});
			
			$('.tabs h4').eq(0).trigger('click');
		}
		
	},

	Popup : function(css) {
			
		$.blockUI({ message : '\
			<div class="viewer"><div class="loading"><img src="' + PSPS.loading_img + '" alt="" /></div></div>\
			<a href="#" class="close">X CLOSE</a>\
		'});

		if (css) $('.blockMsg').addClass(css);

		$('.blockMsg .close').click(function() {
			$.unblockUI();
			return false;
		});
		
		$('.blockOverlay').click(function() {
			$.unblockUI();
		});
		
		$('.blockMsg').center();
		
	},

	AjaxPopup : function(obj, callback) {
		PSPS.Popup();
		$.get($(obj).attr('href'), { ajax : true }, function(data) {
			$('.blockMsg .viewer').html('<div class="ajax-content">' + data + '</div>');
			$('.blockMsg').center();
			callback();
		});
	},
		
	YouTubePopup : function(url) {
		PSPS.Popup();
		var width = 640;
		var height = 385;
		var matches = url.match(/v=([^&]+)/);
		if (!matches) $('.blockMsg .viewer').html('Could not retrieve video.');
		url = 'http://www.youtube.com/v/' + matches[1] + '?fs=1&amp;hl=en_US&amp;autoplay=1';
		$('.blockMsg .viewer').html('<object width="' + width + '" height="' + height + '"><param name="movie" value="' + url +'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="' + url + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + width + '" height="' + height + '"></embed></object>');
		$('.blockMsg').center();
	},
	
	ImagePopup : function(image) {
		PSPS.Popup();
		var img = new Image();
		$(img).load(function() {
			$('.blockMsg .viewer')
				.css({
					width: img.width + 'px',
					height: img.height + 'px'
				})
				.html('<img src="' + image + '" />');
			$('.blockMsg').center();
		});
		img.src = image;		
	},

	Directory : {
		init : function() {
			if (!$('.directory').get(0)) return;
	
			$('.dir-filters .search label').label_as_input();
			
			$('.dir-filters select').change(function() {
				$(this).parents('form').submit();
			});
			
			$('.dir-filters input[type=submit]').hide();
		}
	},
	
	Gallery : {
		current : 0,
		
		popup : function() {
			PSPS.Gallery.current = 0;
			
			PSPS.Popup();

			$('.blockMsg .viewer').click(function() {
				$.unblockUI();
			});

			$('.blockMsg').append('\
				<div class="nav prev">&laquo;</div>\
				<div class="nav next">&raquo;</div>\
			');
			
			var item = $('.product-images .current').parents('li');
			var i = 0;
			$('.product-images li').each(function() {
				if (item.attr('id') == $(this).attr('id')) return false;
				i++;
			});
			
			PSPS.Gallery.show_item(i);
			
			$('.blockMsg .prev').click(function() {
				PSPS.Gallery.show_item(-1);
			});
	
			$('.blockMsg .next').click(function() {
				PSPS.Gallery.show_item(1);
			});
			
		},
		
		show_item : function(x) {
			var items = $('.product-images li a');
			var i = PSPS.Gallery.current + x;
			var item_count = items.size();
			if (i >= item_count)
				i = 0;
			if (i < 0)
				i = item_count - 1;
			
			var item = items.eq(i);

			var img = new Image();
			var url = item.attr('href');
			$(img).load(function() {
				$('.blockMsg .viewer')
					.css({
						width: img.width + 'px',
						height: img.height + 'px'
					})
					.html('<img src="' + url + '" />');
				$('.blockMsg').center();
			});
			img.src = url;		
			
			PSPS.Gallery.current = i;
		}
	
	},
	
	Products : {
		init : function() {
			if (!$('#content.products').get(0)) return;
			
			var div = $('.product-images');
			$('li:first-child', div).each(function() {
				div.prepend('<div class="thumb-bg"></div>');
				PSPS.Products.update_thumb($('a', this));
			});
			
			$('li a', div).click(function() {
				PSPS.Products.update_thumb($(this));
				return false;
			});
			
			$('.blinds .video a').click(function() {
				PSPS.YouTubePopup($(this).attr('href'));
				return false;
			});
		},
		
		update_thumb : function(elem) {
			$('.product-images .current').removeClass('current');
			elem.addClass('current');
			
			$('.product-images .thumb-bg').html('\
				<a href="' + elem.attr('href') + '" target="_blank" class="thumb"\
				style="background-image: url(' + elem.attr('rel') + ')"><span class="spyglass"></span></a>\
			');
			
			$('.product-images .thumb').click(function() {
				PSPS.Gallery.popup();
				return false;
			});
		}
	},

	Features : {
		current : 0,
		delay : 5000,
		delay_sticky : 15000,
		delay_clicked : 30000,
		clicked : false,
		timer : null,

		init : function() {
			if (!$('body.home').get(0)) return;
			
			var features = $('.features');
			features
				.wrapInner('<div class="articles"></div>')
				.prepend('<ul class="menu"></ul>')
				.wrapInner('<div class="frame"></div>');

			var menu = $('.menu', features);
			
			var i = 0;
			$('.title', features).each(function() {
				$(this).hide();
				menu.append('<li><a href="" rel="' + i + '">' + $(this).text() + '</a></li>');
				if ($(this).parent().hasClass('sticky')) {
					$('li:last', menu).hide().addClass('sticky');
				}
				i++;
			});
			
			$('li:first', menu).addClass('first current');
			$('li:last', menu).addClass('last');
			
			Cufon.replace('.home .features .menu a', { hover: true });
			
			$('a', menu).click(function() {
				var x = $('li', menu).index($(this).parent());
				PSPS.Features.clearTimer();
				PSPS.Features.clicked = true;
				PSPS.Features.show(x);
				return false;
			});
			
			PSPS.Features.setTimer();
		},
		
		next : function() {
			var x = PSPS.Features.current + 1;
			
			if (x >= $('.features .menu li').size())
				x = 0;
			
			PSPS.Features.show(x);
		},
		
		show : function(x) {
			PSPS.Features.current = x;

			$('.features .menu li.current').removeClass('current');
			$('.features .menu li').eq(x).addClass('current');
			$('.features article').fadeOut(500).eq(x).fadeIn(500);
			Cufon.refresh('.home .features .menu a');
			
			PSPS.Features.setTimer();
		},

		setTimer : function() {
			var delay = PSPS.Features.delay;
			if ($('.features .menu li.current.sticky').get(0)) {
				delay = PSPS.Features.delay_sticky;
			}
			else if (PSPS.Features.clicked) {
				delay = PSPS.Features.delay_clicked;
				PSPS.Features.clicked = false;
			}
			
			PSPS.Features.timer = window.setTimeout(PSPS.Features.next, delay);
		},
		
		clearTimer : function() {
			window.clearTimeout(PSPS.Features.timer);
		}		
	},

	Carousel : {
		delay : 3000,
		timer : null,
		viewable_items: 6,
		orig_size : 0,
		
		init: function() {
			PSPS.Carousel.orig_size = $('.carousel ul li').size();
			
			$('.carousel li').clone().appendTo('.carousel ul');

			var li_width = $('.carousel ul li').outerWidth();
			var li_num = $('.carousel ul li').size();
			
			if (li_num <= PSPS.Carousel.viewable_items) {
				return;
			}
			
			$('.carousel ul').css('width', (li_num * li_width) + 'px');

			$('.carousel')
				.append('<a href="#" class="nav prev"></a>')
				.append('<a href="#" class="nav next"></a>');

			
			$('.carousel .prev').click(function() {
				PSPS.Carousel.clearTimer();
				PSPS.Carousel.scroll(1);
				return false;
			});
			$('.carousel .next').click(function() {
				PSPS.Carousel.clearTimer();
				PSPS.Carousel.scroll(-1);
				return false;
			});
			
			PSPS.Carousel.setTimer();
		},
		
		scroll: function(direction) {
			var ul_width = $('.carousel ul').width();
			var li_width = $('.carousel ul li').outerWidth();
			var carousel_width = li_width * PSPS.Carousel.viewable_items;
			var current = $('.carousel ul').css('left');
			current = parseFloat(current.replace('px', ''));
			var dist = (direction * li_width) + current;

			if (dist > 0) {
				var left = -1 * PSPS.Carousel.orig_size * li_width;
				$('.carousel ul').css('left', left + 'px');
				dist = left + li_width;
			}
			
			if (ul_width - carousel_width < Math.abs(dist)) {
				var left = -1 * (PSPS.Carousel.orig_size - PSPS.Carousel.viewable_items) * li_width;
				$('.carousel ul').css('left', left + 'px');
				dist = left - li_width;
			}
			
			$('.carousel ul').animate({
				left: dist + 'px'
			});
			
			PSPS.Carousel.setTimer();
		},      

		next : function() {
			PSPS.Carousel.scroll(-1);
		},
		
		setTimer : function() {
			PSPS.Carousel.timer = window.setTimeout(PSPS.Carousel.next, PSPS.Carousel.delay);
		},
		
		clearTimer : function() {
			window.clearTimeout(PSPS.Carousel.timer);
		}	
	},

	History : {
		delay : 3000,
		timer : null,
		viewable_items: 5,
		orig_size : 0,
		current : 0,
		
		init: function() {
			$('#timeline').append('<div class="years"><div class="viewport"><ul>');
			
			$('#timeline li').each(function() {
				var li = $(this);
				$('img', this).eq(0).prependTo(this).wrap('<div class="year-img">');
				var title = $('h2', this).text();
				$('#timeline .years ul').append('<li><span></span>' + title + '</li>');
				
				$('#timeline .years li:last').click(function() {
					$('#timeline .content li').removeClass('current').hide();
					li.addClass('current').show();
					$('#timeline .years li').removeClass('current');
					$(this).addClass('current');
					Cufon.refresh('#timeline .years li');
					PSPS.History.center('.copy');
					PSPS.History.center('.year-img');
				});
			});
			
			$('#timeline .content li:first').addClass('current');
			$('#timeline .years li:first').addClass('current');
				
			PSPS.History.center('.copy');
			PSPS.History.center('.year-img');

			Cufon.replace('#timeline .years li');

			var li_width = $('#timeline .years li').outerWidth();
			var li_num = $('#timeline .years li').size();
			
			if (li_num <= PSPS.History.viewable_items) {
				return;
			}
			
			$('#timeline .years ul').css('width', (li_num * li_width) + 'px');

			$('#timeline .years')
				.append('<a href="#" class="nav prev disabled"></a>')
				.append('<a href="#" class="nav next"></a>');

			$('#timeline .prev').click(function() {
				PSPS.History.scroll(1);
				return false;
			});
			$('#timeline .next').click(function() {
				PSPS.History.scroll(-1);
				return false;
			});
		},
		
		center: function(selector) {
			var h = $('#timeline li').height();
			var mid = Math.floor(h / 2);
			var inner = $('#timeline .current ' + selector);
			var top = mid - (inner.outerHeight() / 2);
			inner.css('top', top + 'px');
		},
		
		scroll: function(direction) {
			var ul_width = $('#timeline .years ul').width();
			var li_width = $('#timeline .years li').outerWidth();
			var carousel_width = li_width * PSPS.History.viewable_items;
			current = PSPS.History.current;
			
			if (current == 0 && direction > 0) {
				return;
			}

			if (Math.abs(current) == ul_width - carousel_width && direction < 0) {
				return;
			}
			
			var dist = (direction * carousel_width) + current;

			if (dist == 0) {
				$('#timeline .prev').addClass('disabled');
			}
			else {
				$('#timeline .prev').removeClass('disabled');
			}
			
			if (Math.abs(dist) == ul_width - carousel_width) {
				$('#timeline .next').addClass('disabled');
			}
			else {
				$('#timeline .next').removeClass('disabled');
			}
			
			PSPS.History.current = dist;
			$('#timeline .years ul').animate({
				left: dist + 'px'
			});
		}
	},
				
    MovieCovers : {
        current : 0,
		delay : 3000,
		timer : null,

        init : function() {
            if (!$('#covers').get(0) || $('#covers li').size() == 1) return;
			
			$('#covers ul').after('\
                <div class="nav prev"></div>\
                <div class="nav next"></div>\
			');
            
            $('#covers .prev').click(function() {
				PSPS.MovieCovers.clearTimer();
                PSPS.MovieCovers.show_item(-1);
            });

            $('#covers .next').click(function() {
				PSPS.MovieCovers.clearTimer();
                PSPS.MovieCovers.show_item(1);
            });
			
			PSPS.MovieCovers.setTimer();
        },
        
        show_item : function(x) {
            var item_num = PSPS.MovieCovers.current + x;
			var covers = $('#covers li');
            var num_lis = covers.size();
            if (item_num >= num_lis)
                item_num = 0;
            if (item_num < 0)
                item_num = num_lis - 1;
            
            covers.eq(PSPS.MovieCovers.current).fadeOut();
			var li = covers.eq(item_num);
            
            var img = new Image();
            $(img).load(function() {
                li.fadeIn();
            });

			var bg = $('a', li).css('background-image');
			bg = bg.replace('url(', '');
			bg = bg.replace(')', '');
			bg = bg.replace(/"/g, '');

            img.src = bg;
            
            PSPS.MovieCovers.current = item_num;
			
			PSPS.MovieCovers.setTimer();
        },

		next : function() {
			PSPS.MovieCovers.show_item(1);
		},
		
		setTimer : function() {
			PSPS.MovieCovers.timer = window.setTimeout(PSPS.MovieCovers.next, PSPS.MovieCovers.delay);
		},
		
		clearTimer : function() {
			window.clearTimeout(PSPS.MovieCovers.timer);
		}	
    }

};


(function($){
    
 	$.fn.extend({ 
 		label_as_input: function() {
            
    		return this.each(function() {
                var input = $(this).siblings('input[type=text],textarea').eq(0);
                var txt = $(this).text();
                
                $(this).hide();
                
                var _focus = function() {
                    if (input.val() == txt) {
                        input.removeClass('dim');
                        input.val('');
                    }
                };
                
                var _blur = function() {
                    if (input.val() == '') {
                        input.addClass('dim');
                        input.val(txt);
                    }
                };
            
                input.focus(_focus);
                input.blur(_blur);
                
                _focus();
                _blur();
                
                input.parents('form').submit(_focus);
                
                return this;
    		});
    	}
	});

    $.fn.center = function() {
        // Always return each...
        return this.each(function() {
            var t = $(this);

            var leftMargin = t.width() / 2;
            var topMargin = t.height() / 2;

            if( typeof( window.pageYOffset ) == 'number' ) {
                // Netscape
                var scrollOffset = window.pageYOffset;
            } else if( document.body && document.body.scrollTop ) {
                // DOM
                var scrollOffset = document.body.scrollTop;
            } else if( document.documentElement && document.documentElement.scrollTop ) {
                // IE6 standards compliant mode
                var scrollOffset = document.documentElement.scrollTop;
            }
            else {
                var scrollOffset = 0;
            }

            var topOffset = ($(window).height() / 2) + scrollOffset - topMargin;
            var leftOffset = ($('body').width() / 2) - leftMargin;
            
            if (topOffset < 0)
                topOffset = 0;

            t.css({
                position: 'absolute',
                left: leftOffset + 'px',
                top: topOffset + 'px'
            });
        });
    };


    $.fn.gridify = function(per_row, selector) {
        var size = this.size();
        if (!per_row && size) {
            var container = this.parent();
            var item = this.eq(0);
            per_row = Math.floor(container.width() / item.width());
        }
        
        return this.each(function(i) {
            if ((i+1) % per_row == 0 || (per_row > size && (i+1) == size)) {
                $(this).addClass('row-last');
                
                var max_height = 0;
                var el = $(this);
                for (var x = 1; x <= per_row; x++) {
                    if (selector)
                        var h = $(selector, el).outerHeight();
                    else
                        var h = el.outerHeight();
                        
                    if (h > max_height)
                        max_height = h;
                    el = el.prev();
                }
                
                var el = $(this);
                for (var x = 1; x <= per_row; x++) {
                    if (selector)
                        var obj = $(selector, el);
                    else
                        var obj = el;

                    var diff = max_height - obj.outerHeight();
                    obj.height(diff + obj.height());
                    el = el.prev();
                }
                
            }
        });
    };
    
})(jQuery);
