/* 0.0 JAVASCRIPT LEGEND
--------------------------------------------------

VW Owner Perks
Created: 02.04.08
Author: Jeremy Fields

1.0 jQUERY FUNCTIONS
	1.0.1 PRELOAD IMAGES
	1.0.2 TOGGLE LABEL VALUES IN FORM FIELDS
    1.0.3 FUNCTION CALLED FROM THE WIDGET WHEN IT FINISHES LOADING
2.0 jQUERY
	2.1 GLOBAL ACTIONS
	2.2 PAGE ACTIONS FOR PERKS-INDEX
	2.3 PAGE ACTIONS FOR PERKS-SPONSORS
		2.3.1 HANDLE ROLLOVERS
	2.4 PAGE ACTIONS FOR PERKS-ITEM
	2.5 PAGE ACTIONS FOR PERKS-CHECKOUT
		2.5.1 SHOW AND HIDE SECURITY CODE POPUP DIV
		2.5.2 TOGGLE BILLING ADDRESS
		2.5.3 VALIDATE AND SUBMIT CHECKOUT FORM DATA
	2.6 PAGE ACTIONS FOR PERKS-HISTORY
	2.7 PAGE ACTIONS FOR PERKS-FAQ
3.0 Cross browser image loader
4.0 METADATA PLUGIN

--------------------------------------------------
*/

/*
1.0 jQUERY FUNCTIONS
--------------------------------------------------*/
// 1.0.1 PRELOAD IMAGES
jQuery.preloadImages = function() {
	for(var i = 0; i<arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
}

// 1.0.2 TOGGLE LABEL VALUES IN FORM FIELDS
jQuery.fn.toggleVal = function() {
	this.each(function() {
		jQuery(this).focus(function() {
			// clear value if current value is the default
			if(jQuery(this).val() == this.defaultValue) { jQuery(this).val(""); }
		}).blur(function() {
			// restore to the default value if current value is empty
			if(jQuery(this).val() == "") { jQuery(this).val(this.defaultValue); }
		});
	});
}

// 1.0.3 FUNCTION CALLED FROM THE WIDGET WHEN IT FINISHES LOADING
/*var checkLogin = false;
function onWidgetReady() {
	if (checkLogin) {
		jQuery('#ajax-loader-login').hide();
		util.getNode("swf_shell").promptOPLogin("",rrdAutologin);
	}
}*/

/*
2.0 jQUERY
--------------------------------------------------*/
jQuery(document).ready (function() {
	
	/*
	2.1 GLOBAL ACTIONS
	--------------------------------------------------*/
	// PRELOAD IMAGES
	jQuery.preloadImages("images/a-item-next-over.gif", "images/a-item-previous-over.gif");
	
	// OPEN WIDGET FOR LOGIN
    /*jQuery('.widgetLogin').click(function() {
	    checkLogin = true;
	    try {
		    util.getNode("swf_shell").promptOPLogin("",rrdAutologin);
	    } catch(err) {
		    jQuery('#ajax-loader-login').show();
	    }
    	
	    return false;
    });*/
	
	// SUBMIT BUTTON ROLLOVER ACTIONS
	jQuery(':image').each(function() {
		
		var str = jQuery(this).attr("src");
		var strSpl = str.split(".");
		
		var normal = str;
		var hover = strSpl[0]+"-hover."+strSpl[1];
		var click = strSpl[0]+"-click."+strSpl[1];
		
		jQuery.preloadImages(hover,click);
		
		jQuery(this).css('outline','none');
		
		jQuery(this).hover(
			function(){ jQuery(this).attr("src",hover); },
			function(){ jQuery(this).attr("src",normal); }
		).mousedown(function(){
			jQuery(this).attr("src",click);
		}).mouseup(function(){
			jQuery(this).attr("src",hover);
		});
		
	});
	
	/*
	2.2 PAGE ACTIONS FOR PERKS-INDEX
	--------------------------------------------------*/
	if ( jQuery('body').is('#perks-index') ) {
		
		// FIX PNGs
		jQuery('img[@src$=.png]').ifixpng();
		
		// HOVER EFFECT FOR item-detail
		jQuery('#perks-index #content-sub li').hover(
			function(){ jQuery(this).addClass('li-hover'); },
			function(){ jQuery(this).removeClass('li-hover'); }
		);
		// CLICK FOR item-detail li
		jQuery('#perks-index #content-sub li').click(function() {
			window.location = jQuery(this).children('p').children('a').attr('href');
		});
			
		// UI BLOCK
		jQuery('#UIBlock-container').css({
			position:'absolute',
			top:'135px',
			left:'0px',
			width:'750px',
			height:'400px',
			zIndex:'3000'
		});
		jQuery('#UIBlock-background').css({
			position:'absolute',
			width:'750px',
			height:'400px',
			background:'#fff',
			opacity:'0.5',
			top:'-10px',
			left:'0px',
			zIndex:'3001'
		});
		jQuery('#UIBlock-content').css({
			zIndex:'3002',
			top:'30px',
			left:'100px',
			position:'absolute'
		});
		
		// PRELOAD CONTAINER IMAGE BEFORE SHOWING DIV
		if (jQuery.browser.msie) {
			var loader = new ImageLoader('images/PageHeaders/popup-firsttime.png');
			//set event handler
			loader.loadEvent = function(url, image) {
				// HOME PAGE SCROLLER
				jQuery('#sponsorCarousel').jcarousel({
					scroll: 7
				});
			
				jQuery('#popup-firsttime').css('top','0px');
			}
			loader.load();
		} else {
		    /*
			$('#popup-firsttime-background img').load(function() {
				// HOME PAGE SCROLLER
				jQuery('#sponsorCarousel').jcarousel({
					scroll: 7
				});
				jQuery('#popup-firsttime').css('top','0px');
			});
			*/
			
			var loader = new ImageLoader('images/PageHeaders/popup-firsttime.png');
			loader.loadEvent = function(url, image) {
			    jQuery('#sponsorCarousel').jcarousel({
					scroll: 7
				});
				jQuery('#popup-firsttime').css('top','0px');
		    }
		    loader.load();
		    
		}
		
		// UNBLOCK UI
		jQuery('#a-popup-close a,#a-check-out-the-perks a').click(function() {
			
			jQuery('#popup-firsttime').css('top','1000px');
			jQuery('#UIBlock-container').hide();
			
			return false;
		});
		
		// INITIATE SCROLL PANE
		jQuery('.scroll-pane').jScrollPane({scrollbarWidth: 9, unregisterAtYLimit: true, scrollbarMargin: 10});
		
	}
	
	/*
	2.3 PAGE ACTIONS FOR PERKS-SPONSORS
	--------------------------------------------------*/
	if (jQuery('body').is('#perks-sponsors')) {
		
		// INITIATE SCROLL PANE
		jQuery('.scroll-pane').jScrollPane({scrollbarWidth: 9, unregisterAtYLimit: true, scrollbarMargin: 10});
		
		// PRELOAD IMAGES
		if (jQuery.browser.mozilla) {
			jQuery(".sponsor a img").each(function() {
				jQuery(this).load(function () {
					jQuery(this).css('top','0px');
				});
			});
		} else {
			jQuery(".sponsor a img").each(function() {
				jQuery(this).css('top','0px');
			});
		}
		
		// 2.3.1 HANDLE ROLLOVERS
		jQuery(".sponsor a").each(function() {
			var defaultState = jQuery(this).find('img').attr('src');
			var hoverState = jQuery(this).attr('rel');
			
			jQuery.preloadImages(hoverState);
			
			jQuery(this).hover(function() {
				jQuery(this).find('img').attr('src', hoverState);
			}, function() {
				jQuery(this).find('img').attr('src', defaultState);
			}).click(function() {
			    window.open( $(this).attr('href') );
			    return false;
		    });
		});
		
	}
	
	/*
	2.4 PAGE ACTIONS FOR PERKS-ITEM
	--------------------------------------------------*/
	if ( jQuery('body').is('#perks-item, #perks-confirmation') ) {
		
		// INITIATE SCROLL PANE
		jQuery('.scroll-pane').jScrollPane({scrollbarWidth: 9, unregisterAtYLimit: true, scrollbarMargin: 10});
		
	}
	if ( jQuery('body').is('#perks-item') && jQuery('div').is('.item-submit') ) {
		
		// FIX VERTICAL CENTERING OF SUBMIT BUTTON AND SPONSOR LOGO
		var submit = jQuery('.item-submit').height();
		var sponsor = jQuery('.item-sponsor').height();
		
		if ( submit > sponsor ) {
			var diff = Math.round((submit - sponsor)/2)-1;
			jQuery('.item-sponsor').css('padding-top',diff+"px");
		} else if ( submit < sponsor ) {
			var diff = Math.round((sponsor - submit)/2);
			jQuery('.item-submit').css('padding-top',diff+"px");
		}
		
	}
	
	/*
	2.5 PAGE ACTIONS FOR PERKS-CHECKOUT
	--------------------------------------------------*/
	if ( jQuery('body').is('#perks-checkout') ) {
		
		// FIX PNGs
		jQuery('img[@src$=.png]').ifixpng();
		
		// ADD IFRAME SHIM FOR IE 6 TO FIX Z-INDEX BUG WITH SELECT LISTS
		if (jQuery.browser.msie && jQuery.browser.version <= 6) {
			jQuery('#popup-securitycode-background').after('<iframe frameborder="0"></iframe>');
		}
		
		// 2.5.1 SHOW AND HIDE SECURITY CODE POPUP DIV
		jQuery('#securitycode').click(function() {
			var top = (jQuery(this).position().top + 220) - jQuery('#popup-securitycode').height();
			jQuery('#popup-securitycode').css('top',top+'px');
			
			return false;
		});
		jQuery('#a-popup-close a').click(function() {
			jQuery('#popup-securitycode').css('top','1000px');
			
			return false;
		});
		
		// 2.5.2 TOGGLE BILLING ADDRESS
		if (jQuery.boxModel) {
			var $defaultHeight = 585;
			var $expandedHeight = 713;
		} else {
			var $defaultHeight = 525;
			var $expandedHeight = 665;
		}

		if (jQuery('[name="billing"]:checked').val() == "yes") {
		    jQuery('#checkout-billing-address').hide();
		}
		else {
			jQuery('#site-content, #content-main, #site-wrapper').css('height',$expandedHeight+'px');
		}
		
		jQuery('#billing-no').click(function () {
			jQuery('#site-content, #content-main, #site-wrapper').css('height',$expandedHeight+'px');
			jQuery('#checkout-billing-address').fadeIn('fast',function() {
				jQuery("#checkout-billing-address [type='text']:first").focus();
			});
		});
		jQuery('#billing-yes').click(function () {
			jQuery('#checkout-billing-address').fadeOut('fast',function() {
				jQuery('#site-content, #content-main, #site-wrapper').css('height',$defaultHeight+'px');
			});
		});
		
		// TOGGLE VALUES IN FORM FIELDS 
		jQuery('.toggleDefault').toggleVal();
		
		// RESTRICT INPUT ON CERTAIN FORM FIELDS
		jQuery('.alpha').alpha({allow:"' -"});
		jQuery('.numeric').numeric({allow:".()- "});
		
		// 2.5.3 VALIDATE AND SUBMIT CHECKOUT FORM DATA
		jQuery('#aspnetForm').submit(function(e) {
			
			// SET BILLING ADDRESS REQUIREMENTS IF DIFFERENT FROM SHIPPING ADDRESS
			if (jQuery('[name="billing"]:checked').val() == "no") {
				jQuery('.billing-required').addClass('required');
			} else if (jQuery('[name="billing"]:checked').val() == "yes") {
				jQuery('.billing-required').removeClass('required');
			}
			
			// VALIDATE FORM, SUBMIT IF PASSED
			if( jQuery('#aspnetForm').validate({},'#205f92') ) {
				return true;
			}
			return false;
		});
		
	}
    
    /*
	2.6 PAGE ACTIONS FOR PERKS-HISTORY
	--------------------------------------------------*/
    if ( jQuery('body').is('#perks-history') ) {
    	jQuery('#order-history .history-summary:first td').css('border-top','none');
    	jQuery('.history-detail-link').append('<a class="history-trigger" href="#">Order Details</a>');
		jQuery('.history-detail').hide();
		jQuery('.scroll-pane').jScrollPane({scrollbarWidth: 9, unregisterAtYLimit: true});
    }
	jQuery('a.history-trigger').toggle ( 
		function() {
			jQuery(this).html('Hide Details');
			jQuery(this.parentNode.parentNode).next('.history-detail').fadeIn('fast');
			jQuery('.scroll-pane').jScrollPane({scrollbarWidth: 9, unregisterAtYLimit: true});
		},
		function() {
			jQuery(this).html('Order Details');
			jQuery(this.parentNode.parentNode).next('.history-detail').fadeOut('fast', function() {
				jQuery('.scroll-pane').jScrollPane({scrollbarWidth: 9, unregisterAtYLimit: true});
			});
		}
	);
	
	/*
	2.7 PAGE ACTIONS FOR PERKS-FAQ
	--------------------------------------------------*/
	if ( jQuery('body').is('#perks-faqs') ) {
		// INITIATE SCROLL PANE
		jQuery('.scroll-pane').jScrollPane({scrollbarWidth: 9, unregisterAtYLimit: true, scrollbarMargin: 10});
	}
	
});

/*
3.0 Cross browser image loader
--------------------------------------------------*/
function addListener(element, type, expression, bubbling) {
	bubbling = bubbling || false;
	if(window.addEventListener)	{ // Standard
		element.addEventListener(type, expression, bubbling);
		return true;
	} else if(window.attachEvent) { // IE
		element.attachEvent('on' + type, expression);
		return true;
	} else return false;
}

var ImageLoader = function(url){
	this.url = url;
	this.image = null;
	this.loadEvent = null;
};

ImageLoader.prototype = {
	load:function(){
		this.image = document.createElement('img');
		var url = this.url;
		var image = this.image;
		var loadEvent = this.loadEvent;
		addListener(this.image, 'load', function(e){
			if(loadEvent != null){
				loadEvent(url, image);
			}
		}, false);
		this.image.src = this.url;
	},
	getImage:function() {
		return this.image;
	}
};

/*
4.0 METADATA PLUGIN
--------------------------------------------------*/
(function($){$.extend({metadata:{defaults:{type:'class',name:'metadata',cre:/({.*})/,single:'metadata'},setType:function(type,name){this.defaults.type=type;this.defaults.name=name;},get:function(elem,opts){var settings=$.extend({},this.defaults,opts);if(!settings.single.length)settings.single='metadata';var data=$.data(elem,settings.single);if(data)return data;data="{}";if(settings.type=="class"){var m=settings.cre.exec(elem.className);if(m)data=m[1];}else if(settings.type=="elem"){if(!elem.getElementsByTagName)return;var e=elem.getElementsByTagName(settings.name);if(e.length)data=$.trim(e[0].innerHTML);}else if(elem.getAttribute!=undefined){var attr=elem.getAttribute(settings.name);if(attr)data=attr;}if(data.indexOf('{')<0)data="{"+data+"}";data=eval("("+data+")");$.data(elem,settings.single,data);return data;}}});$.fn.metadata=function(opts){return $.metadata.get(this[0],opts);};})(jQuery);