/**
 * @author Alexandre Magno
 * @desc Center a element with jQuery
 * @version 1.0
 * @example
 * $("element").center({
 *
 * 		vertical: true,
 *      horizontal: true
 *
 * });
 * @obs With no arguments, the default is above
 * @license free
 * @param bool vertical, bool horizontal
 * @contribution Paulo Radichi
 *
 */
jQuery.fn.center = function(params) {
	var options = {
		vertical: true,
		horizontal: true
	}
	op = jQuery.extend(options, params);

	return this.each(function(){
		var $self = jQuery(this);
		var width = $self.width();
		var height = $self.height();
		var paddingTop = parseInt($self.css("padding-top"));
		var paddingBottom = parseInt($self.css("padding-bottom"));
		var borderTop = parseInt($self.css("border-top-width"));
		var borderBottom = parseInt($self.css("border-bottom-width"));
		var mediaBorder = (borderTop+borderBottom)/2;
		var mediaPadding = (paddingTop+paddingBottom)/2;
		var positionType = $self.parent().css("position");
		var halfWidth = (width/2)*(-1);
		var halfHeight = ((height/2)*(-1))-mediaPadding-mediaBorder;
		var cssProp = {
			position: 'absolute'
		};

		if(op.vertical) {
			cssProp.height = height;
			cssProp.top = '50%';
			cssProp.marginTop = halfHeight;
		}
		if(op.horizontal) {
			cssProp.width = width;
			cssProp.left = '50%';
			cssProp.marginLeft = halfWidth;
		}
		if(positionType == 'static') {
			$self.parent().css("position","relative");
		}
		$self.css(cssProp);
   });
};

function urlencode (str) {
	str = escape(str);
	return str.replace(/[*+\/@]|%20/g,
	function (s) {
		switch (s) {
			case "*": s = "%2A"; break;
			case "+": s = "%2B"; break;
			case "/": s = "%2F"; break;
			case "@": s = "%40"; break;
			case "%20": s = "+"; break;
		}
			return s;
		}
	);
}

$(document).ready(function() {
	
	/*----------------------------------------------------------------------
  		COOKIES
	----------------------------------------------------------------------*/
	setCookie = function(name, value, expires, path) {
		var cookie = name + '=' + value;
		if (expires) {
			cookie += '; expires=' + expires.toGMTString();
	    }
		if (path) {
			cookie += '; path=' + path;
	    }
	    document.cookie = cookie;
	};

	getCookie = function(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 (0 == c.indexOf(nameEQ)) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		return null;
	};

	unsetCookie = function(name) {
		var date = new Date();
		date.setTime(date.getTime() - 1);
		setCookie(name, '', date);
	};
	
	
	/*---------------------------------------------------------------------- 
  		MEGA MENU
	----------------------------------------------------------------------*/
	$(['balls','bags','accessories','shoes','the-pros','products','parts','lane-maintenance','service-and-support','bowling-investment','modernization']).each(function(i){
		var nav = this;
		
		$("#nav li."+ nav +" a").hover(function(){
			var li = $(this).parent();
			
			$('#nav > li.on').mouseleave();
			li.addClass('on');
			
			var $anchor = $(this);
			var $megamenuContainer = $('.mm-'+ nav);
			
			if ($megamenuContainer.size() == 1) {
				if(li.find(".mega-inner").size()) {
				
					li.addClass("mm");
					$megamenuContainer.show();
					
				}
			} else {
				var loading = null;
				
				var $megamenuContent = $('<div class="mega-menu mm-'+nav+'"><div class="content"></div></div>');
				
				$anchor.after($megamenuContent);
				
				loading = $.get('/megamenu/'+ nav +'/', function(data) {
				
					var $data = $(data);
					var size = $data.find(".list").size();
					var w = (size*215)+15;

					if(size == 4) {
						
						if(i != 0) {
							$megamenuContent.width(w).css({'margin-left': '-'+ (w/2) +'px', 'left': '50%'});
						} else {
							$megamenuContent.width(w).css({'left': '0'});
						}
						
					} else if(size == 1 || size == 2) {
						
						if(i != 0) {
							$megamenuContent.width(w).css({'margin-left': '-20px','left': '0'});
							$megamenuContent.parents("li."+ nav).css({'position': 'relative'});  // IE7 FIX
						} else {
							$megamenuContent.width(w).css({'left': '0'});
						}
						
					} else {
						
						if(i == 3) {
							$megamenuContent.width(w).css({'right': '0'});
			 			} else if(i == 0) {
							$megamenuContent.width(w).css({'left': '0'});
						} else {
							$megamenuContent.width(w).css({'margin-left': '-20px','left': '0'});
							$megamenuContent.parents("li."+ nav).css({'position': 'relative'}); // IE7 FIX
						}
						
					}
					
					$megamenuContent.children(".content").html(data);
					
					if(li.hasClass("on")) {
						if(li.find(".mega-inner").size()) {
							$megamenuContent.show();
							li.addClass("mm");
						}
					}

				});
				
			}
			
			li.mouseleave(function(){
				
				$('.mm-' + nav).hide();
				li.removeClass("mm");
				
			});
			
		}, function(){
			
			$(this).parent().removeClass("on");
			
		});
	});

});

$.fn.input = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			$(this).val("");
			$(this).addClass("focus");
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
			$(this).removeClass("focus");
		}
	});
};

$(document).ready(function() {
	
	/*----------------------------------------------------------------------    
  		MISC SCRIPTS
	----------------------------------------------------------------------*/
	$("#banner.transparent img").center();
	$("img.center").center();
	
	$("a[href*=.pdf]").click(function(){
		window.open(this.href);
		return false;
	});
	
	$("#header input[type='text']").input();
	$("#related-list").hide();
	$("#information-docs").hide();
	$(".pro-tip").hide();
	
	$("#might-also-like").click(function(){
		$("#related-list").slideToggle();
		return false;
	});
	$("#more-information").click(function(){
		$("#information-docs").slideToggle();
		return false;
	});
	$("#pro-tips").click(function(){
		$(".pro-tip").slideToggle();
		return false;
	});
	
	$("#subnav li a.slide").click(function(e){
		e.preventDefault();
		$ul = $(this).parent().children('ul');
		if($ul.hasClass("closed")) {
			$ul.slideToggle();
		}
	});
	
	$("#footer ul li:last-child, #subnav li:last-child, .breadcrumb li:last, #related-list li:last").addClass("last");
	
	if($.browser.msie) {
		var showWarning = getCookie('ieWarning');

		if(showWarning == "show"){
			$('<div id="browser-warning"><h2><span>You are viewing our site with an outdated browser! <a href="http://www.getfirefox.com/">Click here</a> to download a new browser and properly view our site.</span></h2></div>').insertBefore('#wrapper');
		}
	}
	
	/*----------------------------------------------------------------------    
  		HOMEPAGE SLIDESHOW
	----------------------------------------------------------------------*/
	if ($.browser.msie) {
	    if($('#slideshow').length != 0) {
		    $('#slideshow .slides').cycle({
				speed:  0, 
				timeout: 7000,
				next: '.counter .next',
				prev: '.counter .previous',
				pager:  '.counter ul',
				cleartypeNoBg: true,
		      	pagerAnchorBuilder: function(idx, img){ 
		        	return '<li><a href="#">' + (+idx+1) + '</a></li>';
				}
			});
		}
	} else {
		if($('#slideshow').length != 0) {
		    $('#slideshow .slides').cycle({
				fx: 'fade',
				speed:  700, 
				timeout: 7000,
				next: '.counter .next',
				prev: '.counter .previous',
				pager:  '.counter ul',
		      	pagerAnchorBuilder: function(idx, img){ 
		        	return '<li><a href="#">' + (+idx+1) + '</a></li>';
				}
			});
		}
	}

	
	if($('#banner .slides').length != 0) {
	    var $banner = $('#banner .slides').cycle({
			fx: 'fade',
			speed:  400, 
			timeout: 0
		});
		
		var color = $("#color-id").text();
		
		$("#colors li").each(function(i){
			$(this).click(function(){
				$banner.cycle(i);
				color = $("a",this).attr("title");
				$("#color-id").text(color);
				return false;
			});
		});
		
		$("#colors li").hover(function(){
			$("#color-id").text($("a",this).attr("title"));
		},function(){
			$("#color-id").text(color);
		});
	}
	
	
	/*----------------------------------------------------------------------    
  		FILTERS/SELECT BOXES
	----------------------------------------------------------------------*/
	$("#filter .styled").change(function(){
		if($(this).attr("id") == "height" && $(":selected",this).val() == "6-foot") {
			document.getElementById('lanes').selectedIndex = 0;
			$("#selectl").text($("#lanes option:first").text());
		}
		if($(this).attr("id") == "hook-potential") {
			document.getElementById('breakpoint-shape').selectedIndex = 0;
			$("#selectb").text($("#breakpoint-shape option:first").text());
			document.getElementById('alphabetical').selectedIndex = 0;
			$("#selecta").text($("#alphabetical option:selected").text());
		}
		if($(this).attr("id") == "breakpoint-shape") {
			document.getElementById('hook-potential').selectedIndex = 0;
			$("#selecth").text($("#hook-potential option:first").text());
			document.getElementById('alphabetical').selectedIndex = 0;
			$("#selecta").text($("#alphabetical option:first").text());
		}
		if($(this).attr("id") == "alphabetical") {
			document.getElementById('hook-potential').selectedIndex = 0;
			$("#selecth").text($("#hook-potential option:first").text());
			document.getElementById('breakpoint-shape').selectedIndex = 0;
			$("#selectb").text($("#breakpoint-shape option:first").text());
		}
			
		this.form.submit();
	});
	
	$("#select-ball,#select-contact, #select-category").change(function(){
		 var val = $(this).val();
		if(val != "")
			window.location = val;
	});
		
		
	/*----------------------------------------------------------------------    
  		PRO NEWS SCROLLER
	----------------------------------------------------------------------*/
	if($('#pro-news').length != 0) {
		$("#pro-news").liScroll({travelocity: 0.05}); 
	}
	
	
	/*----------------------------------------------------------------------    
  		PHOTO GALLERY/VIDEO SLIDESHOW
	----------------------------------------------------------------------*/
	$(".gallery ul li a, .gallery-sm ul li a").click(function(e){
		e.preventDefault();
		var urlrel = $(this).attr('rel');
		$("#"+ urlrel +" a").colorbox({open: true, rel: urlrel, current: "{current} of {total}", href: function(){ return $(this).attr('src'); }}); 
	});

	$("#watch-video-sm, .watch-video a, #videos li a").click(function(e){
		e.preventDefault();
		var width = ($(this).attr('data-width')) ? parseInt($(this).attr('data-width'))+10 : '650';
		var height = ($(this).attr('data-height')) ? parseInt($(this).attr('data-height'))+30 : '510';
		$(this).colorbox({iframe: true, innerWidth: width, innerHeight: height}); 
	});
	
	$(".watch-video a.auto").each(function(){ 
		var width = ($(this).attr('data-width')) ? parseInt($(this).attr('data-width'))+10 : '650';
		var height = ($(this).attr('data-height')) ? parseInt($(this).attr('data-height'))+30 : '510';
		$(this).colorbox({open: true, iframe: true, innerWidth: width, innerHeight: height}); 
	});
	
	$(".cbox").colorbox();
	
	$(".small-cbox").colorbox({initialWidth: 200, initialHeight: 200});
	
	$(".cbox-vid").click(function(e){
		e.preventDefault();
		var width = ($(this).attr('data-width')) ? parseInt($(this).attr('data-width'))+10 : '650';
		var height = ($(this).attr('data-height')) ? parseInt($(this).attr('data-height'))+30 : '510';
		$(this).colorbox({iframe: true, innerWidth: width, innerHeight: height});
	});

	$(".gallery-item a").click(function(e){
		e.preventDefault();
		var urlrel = $(this).attr('rel');
		$("#"+ urlrel +" a").colorbox({open: true, rel: urlrel, current: "{current} of {total}", href: function(){ return $(this).attr('src'); }}); 
	});
	
	$("#locate-rep").click(function(){
		$("#continent").val($("#locate-country option:selected").attr("data-continent"));
	});
	
	
	/*----------------------------------------------------------------------    
  		TRANSLATION
	----------------------------------------------------------------------*/
	Translation = function() {
		var lang        = null;
        var that        = this;

        this.setLang    = function(lang) {
			that.lang = lang;
            setCookie('lang', lang, null, '/');
        };

        this.getLang    = function() {
			if (that.lang == null) {
				var lang = getCookie('lang');
				if (null == lang) {
                    that.setLang('en');
				} else {
					that.setLang(lang);
				}
            }

            return that.lang;
		};

		this.translate  = function(content) {
			if (!$('#footer .gBranding').length) {
				var gBranding   = $.translate().getBranding();
				var gText       = 'Translation services ' + gBranding.text();
				var gImage      = gBranding.find('img');
				gBranding       = $('<p class="gBranding">' + gText + '</p>');

				gImage.appendTo(gBranding);
				gBranding.prependTo('#footer');
			}


			$(content).translate('en', that.getLang(), {
				rebind: false,
				fromOriginal: true,
				async: false,
				limit: 1000,
				complete: function() {
					$('html').attr('xml:lang', that.getLang());
					$('html').attr('lang', that.getLang());
				}
			});
		};
	};

    $.translate().ready(function() {
        translation = new Translation();
		var lang = translation.getLang();
        if (lang != $('html').attr('lang') && lang != '') {
            translation.translate($('#wrapper-inner'));
        }
    });
});


/*----------------------------------------------------------------------    
	EQUALIZE HEIGHTS
----------------------------------------------------------------------*/
$(window).load(function() {
	var sidebar = $("#sidebar").height();
	var content =  $("#content").height()+290;

	if(sidebar > content) {
		$("#content").css("min-height", sidebar-322);
	}
});


/*----------------------------------------------------------------------    
	EMAIL SIGNUP
----------------------------------------------------------------------*/

$('#email-signup').submit(function(e){
	e.preventDefault();
	var emailAddress = $('#email-signup input').val();

	if(emailAddress != "" && emailAddress != "sign up for Brunswick emails" && emailAddress != "sign up for Brunswick emails "){
		var url = '/email-signup/_signup-form/?email=' + urlencode(emailAddress);
	} else {
		var url = '/email-signup/_signup-form/';
	}
	
	$(this).colorbox({
		href: url,
		open: true,
		iframe: true,
		innerWidth: 520,
		height: 610
	}, function(){
		$('#email-signup input').click(function(){
			return false;
		});
	});
});

$(".throbot").colorbox({
	iframe: true,
	innerWidth: 520,
	height: 400
});


/*----------------------------------------------------------------------    
	HIGH ROLLERS
----------------------------------------------------------------------*/

$("#entryform").validate({
	rules: {
		roller_month : {digits:true},
		roller_day : {digits:true},
		roller_year : {digits:true}
	},
	invalidHandler: function(e, validator) {
		var errors = validator.numberOfInvalids();
		if (errors) {
			var message = errors == 1
				? 'You missed 1 field. It has been highlighted below'
				: 'You missed some fields.  They have been highlighted below';
			$("div#error-msg").html(message);
			$("div#error-msg").show();
		} else {
			$("div#error-msg").hide();
		}
	},
	errorElement: "abbr",
	onkeyup: false,
	highlight: function(element, errorClass, validClass) {
		$(element).addClass(errorClass).removeClass(validClass);
		$(element).siblings('span').css('color','#b72126');
	},
	unhighlight: function(element, errorClass, validClass) {
		$(element).removeClass(errorClass).addClass(validClass);
		$(element).siblings('span').css('color','#ffffff');
	},
	submitHandler: function(form){
	$("#claims").val("");
	$(".claim").each(function(i){
		var n = i+1;

		var OrigOrderNo = $("#OrigOrderNo" + n).val();
		var RefCode = $("#RefCode" + n).val();
		var Qty = $("#Qty" + n).val();
		var PartNo = $("#PartNo" + n).val();
		var PartDesc = $("#PartDesc" + n).val();
		var Problem = $("#Problem" + n).val();

		if(Qty != "" && PartNo != "" && PartDesc != "" && Problem != "") {
			$("#claim" + n + "-merged").val(OrigOrderNo + "|" + RefCode + "|" + Qty + "|" + PartNo + "|" + PartDesc + "|" + Problem);
			
			var claims = $("#claims").val();
			if (claims != "") {
				$("#claims").val(claims + "\n<br>" + OrigOrderNo + "|" + RefCode + "|" + Qty + "|" + PartNo + "|" + PartDesc + "|" + Problem);
			}else {
				$("#claims").val(OrigOrderNo + "|" + RefCode + "|" + Qty + "|" + PartNo + "|" + PartDesc + "|" + Problem);
			}
		}
	});
		
		form.submit();
	}
});
 if(jQuery().filestyle) {
	$("#rollers input[type=file]").filestyle({ 
	     image: "http://system.brunswickbowling.com/assets/images/file-upload.png",
	     imageheight : 22,
	     imagewidth : 82,
	     width : 250
	});
 }
 
 $('#rollers form .date-val').keyup(function(){
 	var month = $('#roller-month').val();
 	var day = $('#roller-day').val();
 	var year = $('#roller-year').val();
 	$('#date-field').val(year + '-' + month + '-' + day + ' 00:00');
 });
 
 $('#rollers form .date-val').change(function(){
 	var month = $('#roller-month').val();
 	var day = $('#roller-day').val();
 	var year = $('#roller-year').val();
 	$('#date-field').val(year + '-' + month + '-' + day + ' 00:00');
 });
 
 $('#rollers form #roller-name').keyup(function(){
 	var name = $(this).val();
 	$('#entry-title').val(name);
 });
 
  $('#rollers form #roller-name').change(function(){
 	var name = $(this).val();
 	$('#entry-title').val(name);
 });

