/**
 * jQuery Popunder plugin
 * Copyright (c) 2011 DomainHoldings
 * Written by Jerod Venema
 * Usage:
 *   // creates a pop-under for the specified url(s), triggering them as the user interacts
 *   $.popunder([{ // the first parameter can be an array or a single object
 *				url: 'popunder.html?1',
 *				features: { width: 150 } // add any window requirements here
 *			},{
 *				url: 'popunder.html?2',
 *				features: { width: 350 }
 *			}], { 
 *              perSession: true  // if true (default), popups are once per browser session; false and they're once per page load
 *          });
 *
 *	 // resets any cookies and restarts the current page cycle of urls
 *   $.popunder('reset');
 */
(function( $ ) {
	var cookiePrefix = 'popunder_';
	var index = 0;
	var windows = [];
	var setIndex = 0;
	
	$.popunder = function(args, options) {
		if(args == 'reset'){
			$.each(args, function(arg){
				var cookieName = cookiePrefix + arg.url;
				$.cookie(cookieName, null);
			});
			index = 0;
			lastSet = 0;
			return;
		}else if(args == 'setUrl'){
			var url = arguments[1];
			var windowIndex = setIndex;
			if(arguments.length >= 3){
				windowIndex = arguments[2];
			}else{
				setIndex++;
			}
			windows[windowIndex].location = url;
			return;
		}else{
			if(!$.isArray(args)){
				args = [args];
			}
			this.args = $.map(args, function(arg){
				return $.extend(true, {
					url: 'http://www.google.com',
					features: {
						width: 800,
						height: 510,
						scrollbars: 1,
						resizeable: 1,
						toolbar: 1,
						location: 1,
						menubar: 1, 
						status: 1,
						directories: 0
					}
				}, arg || {});
			});
			options = $.extend({
				perSession: true
			}, options || {});
			
			$(document).bind('click', function(){
				// always no more than once per page load
				while(index < args.length){
					var current = args[index];
					if(!current){
						// no more entries, bail out
						break;
					}
					
					// if we've already loaded this once in this session, and we're using sessions, move on to the next url
					var cookieName = cookiePrefix + current.url;
					if(options.perSession && $.cookie(cookieName)){
						index++;
						continue;
					}
					
					// ok, we have a valid popunder to run; build the url
					var featuresProp = [];
					for(var prop in current.features){
						featuresProp.push(prop + '=' + current.features[prop]);
					}
					
					// open it
					var pop = window.open(current.url,'',featuresProp.join(','));
					pop.blur();
					windows.push(pop);
					window.focus();
					index++;
					
					// if we're setting things per-session, save a cookie for this url
					if(options.perSession){
						$.cookie(cookieName, '1');
					}
					
					break;
				}
			});
		}
	};
	
})( jQuery );
