// Onload When Document Ready
$j(document).ready(function() {
  $j('a[rel=external]').attr('target', '_blank');
  $j('.equalize').equalHeights('true');
  $j("img[src$=png],.pngfix").pngfix();
  //$j(document).stickyfooter();
  $j("#content_container li,.faq_item a").prepend("<div class=\"blueCap\"><img src=\"/images/structural/ltl.gif\"></div>");
  $j("#content_container li,.faq_item a").append("<div class=\"blueBase\"><img src=\"/images/structural/lbl.gif\"></div>");
  $j("ul#footernav li:not(:last)").append("<span class=\"spacer\">|</span>");
  $j('.photocap > img[title]').each(function(){$j(this).after("<p>"+this.title+"</p>").parent().css("width", $j(this).width());});
  $j('a.popup').live('click',function(){var data=$j(this).metadata();var name=(data.name==null)?'popup':data.name;w=screen.availWidth;h=screen.availHeight;var leftPos=(w-data.width)/2,topPos=(h-data.height)/2;window.open($j(this).attr('href'),name,'width='+data.width+',height='+data.height+',toolbar=no,menubar=no,status=no,scrollbars=yes,resizable=yes,top='+topPos+',left='+leftPos);return false;});
  
  if ($j('label.infield').length) {
    $j.getScript(
      '/javascript/jquery.infieldlabel.min.js',
      function() {
        $j('label.infield').inFieldLabels();
      }
    );
  }
  
  if ($j('a.tooltip').length) {
    $j.getScript(
      '/javascript/jquery.tipsy.js',
      function() {
        $j('a.tooltip').tipsy({gravity: 'w'});
      }
    );
  }
  
	$j("a.faqHeader").click(function() {
		$j(this).next().toggle();
		return false;
	}).next().hide();
	
	// Contact Us Form
	if ($j("#contactRequest").length > 0) {
		function wantsBrochure(){
			if($j("#conBrochure:checked").length == 0) return false;
			return true;
		}
		
		$j.getScript(
      '/javascript/jquery.validate.js',
      function() {
				$j('#contactRequest').validate({
					errorLabelContainer: "#contactErrors",
					wrapper: "li",
					rules: {
						conAddress1: {required: wantsBrochure},
						conCity: {required: wantsBrochure},
						conCountry: {required: wantsBrochure},
						conState: {required: wantsBrochure},
						conZip: {required: wantsBrochure}
					}
				});
      }
    );
		
		$j("#conBrochure").bind('change click keypress', function() {
      if (wantsBrochure()) $j("#option_fields").slideDown();
      else $j("#option_fields").slideUp();
    });
		$j("#conBrochure").change();
  }

	// Order Checkout Form
	if ($j("#reviewOrder").length > 0) {
		function checkCCNum() {
			var ccNum = $j('[name="ordCCNumber"]').val().toString();
			if(ccNum.length > 3){
				if(ccNum.match(/^4\d{12}(\d{3})?$/)) {
					return 'Visa';
				} else if(ccNum.match(/^5[1-5]\d{14}$/)) {
					return 'Mastercard';
				} else if(ccNum.match(/^6011\d{12}$/)) {
					return 'Discover';
				} else if(ccNum.match(/^3[47]\d{13}$/)) {
					return 'American Express';
				} else if(ccNum.match(/^3(0[0-5]|[68]\d)\d{11}$/)) {
					return 'Diners Club';
				} else if(ccNum.match(/^2(014|149)\d{11}$/)) {
					return 'enRoute';
				} else if(ccNum.match(/^(3\d{4}|2131|1800)\d{11}$/)) {
					return 'JCB';
				} else if(ccNum.match(/^56(10\d\d|022[1-5])\d{10}$/)) {
					return 'Bankcard';
				} else if(ccNum.match(/^49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\d{10}(\d{2,3})?$/) || ccNum.match(/^564182\d{10}(\d{2,3})?$/) || ccNum.match(/^6(3(33[0-4][0-9])|759[0-9]{2})\d{10}(\d{2,3})?$/)) {
					return 'Switch';
				} else if(ccNum.match(/^6(3(34[5-9][0-9])|767[0-9]{2})\d{10}(\d{2,3})?$/)) {
					return 'Solo';
				} else return 'Unknown';
			} else {
				return 'Unknown';
			}
		}
		
		function submitPayPal() {
			try { pageTracker._trackPageview('/order/PayPal'); } catch(err) { doit = true; }
			$j('[name="ordIsPayPal"]').val('1');
			$j('form[name="reviewOrder"]').submit();
		}
		
		function copyBillingInfo() {
			if($j('#same_as_billing:checked').length) {
				$j('#reviewOrder [name^="ordShip"]').each(function(){
					$j(this).val($j('#reviewOrder [name="ordBill' + $j(this).attr("name").substr(7) + '"]').val()).focus().blur();
				});
			} else {
				$j('#reviewOrder [name^="ordShip"]').each(function(){
					$j(this).val("").focus().blur();
				});
			}
			updateShipping();
		}
		
		function isCCOrder() {
			return ($j('[name="ordIsPayPal"]').val() == 0);
		}
		
		$j.getScript(
      '/javascript/jquery.validate.js',
      function() {
				$j('#reviewOrder').validate({
					errorPlacement: function(error, element) {
						var err = $j("#billingErrorContainer label[for='" + $j(element).attr('name') + "']");
						if(err.length == 1) {
							err.parent().replaceWith(error);
						} else error.appendTo("#billingErrorContainer");
						$j("#billingErrorContainer").prev("p").show().prev("img").show();
					},
					highlight: function( element, errorClass, validClass ) {
						$j(element).addClass(errorClass).removeClass(validClass);
					},
					unhighlight: function( element, errorClass, validClass ) {
						$j(element).removeClass(errorClass).addClass(validClass);
						$j("#billingErrorContainer label[for='" + $j(element).attr('name') + "']").parent().remove();
						if ($j("#billingErrorContainer li").length < 1) $j("#billingErrorContainer").prev("p").hide().prev("img").hide();
					},
					invalidHandler: function(){
						window.location.hash = '#topErrors';
					},
					wrapper: "li",
					rules: {
						ordCCNumber: {required: isCCOrder},
						ordCCCVV: {required: isCCOrder},
						ordCCExpiration_month: {required: isCCOrder},
						ordCCExpiration_year: {required: isCCOrder}
					}
				});
      }
    );
		
		$j('[name="ordIsPayPal"]').val('0');
		$j('#payPalSubmit').click(function(){submitPayPal(); return false;});
		$j('#same_as_billing').change(copyBillingInfo).click(function(){$j(this).trigger('change');});
		$j('select[name="ordShipCountry"]').change(function(){
			if($j('#same_as_billing:checked').length > 0) $j('select[name="ordBillCountry"]').val($j(this).val()).focus().blur();
			updateShipping();
		});
		$j('select[name="ordBillCountry"]').change(function(){
			if($j('#same_as_billing:checked').length > 0) $j('select[name="ordShipCountry"]').val($j(this).val()).focus().blur();
			updateShipping();
		});
		updateShipping();
		$j('[name="ordCCNumber"]').bind('keyup blur', function() {
			var ccType = $j('#ccImageList img[alt=' + checkCCNum() + ']');
			if(ccType.length > 0){
				ccType.css('opacity', '1').siblings().css('opacity', '0.2');
			} else {
				$j('#ccImageList img').css('opacity', '1');
			}
		});
	}
});