YUI({
	base: '/includes/js/yui_3.4.1/build/',
	loadOptional: false,
	/* filter raw == not minified */
	//filter: 'raw',
	combine: true, 
	comboBase: '/inc/loader?',
	root: '/includes/js/yui_3.4.1/build/',
	groups: {
		masi: {
			base: '/build/',
			modules: {
				'controller': {
					requires: ['widget', 'history']
				},
				'basic-search': {
					requires: ['widget', 'substitute', 'io-base', 'json', 'datasource', 'autocomplete', 'autocomplete-filters', 'autocomplete-highlighters']
				},				
				'search-results': {
					requires: ['widget', 'substitute', 'io-base', 'json', 'pagination','anim']
				},				
				'pagination': {
					requires: ['base', 'node', 'event-delegate']
				},			
				'enlarge-preview': {
					requires: ['widget', 'substitute', 'io', 'json']
				},			
				'passthrough': {
					requires: ['io-base', 'io-form', 'dump', 'io-upload-iframe']
				},
				'ma-carousel': {
					requires: ['anim', 'widget']
				},
				'login': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'cookie']
				},
				'panel-slider': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'anim']
				},
				'library-panel': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'anim']
				},
				'library-content-panel': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'anim']
				},
				'cart-panel': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'anim']
				},
				'search-panel': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'anim']
				},
				'keyword': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'io-base', 'json']
				},
				'results-size': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'io-base', 'json']
				},
				'search-filter': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'io-base', 'json']
				},
				'my-account': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'io-base', 'json']
				},
				'ml-folder': {
					requires: ['event-key', 'widget', 'node', 'substitute', 'io-base', 'json']
				}
			}
		}
	}
}).use('event', 'search-results', 'node', 'results-size', 'login', 'panel-slider', 'anim', 'controller', 'library-panel', 'library-content-panel', 'cart-panel', 'search-panel', 'basic-search', 'io-base', 'json', 'keyword', 'passthrough', 'io-form', 'search-filter', 'my-account', 'node-event-simulate', 'ml-folder', 'io-upload-iframe', 'ma-carousel', 'enlarge-preview', function(Y) {
	function init() {
		
		//var loadPage = function() {
			if (Y.UA.ie < 7 && Y.UA.ie != 0) {
				window.location.href = "/browser.shtml";
			}

			/* Not sure if we really need this.
			if (Y.one('.art_template_home')) {
				var myCarousel = new Y.maCarousel({
					srcNode: '#carouselWrapper',
					nextNodeId: '#carouselNext',
					prevNodeId: '#carouselPrev',
					itemWidth: 205,
					increment: 830
				});

				myCarousel.render();
			}
			*/

			/*Not sure if we really need this.
			if (Y.one('.template_spotlight_home')) {
				var myCarousel = new Y.maCarousel({
					srcNode: '#carouselWrapper',
					nextNodeId: '#carouselNext',
					prevNodeId: '#carouselPrev',
					itemWidth: 205,
					increment: 830
				});

				myCarousel.render();
			}
			*/

			//Change the title tag
			if (Y.one('.current_page')) {
				var currentPage = Y.one('.current_page');

				switch (currentPage.get('innerHTML')) {
				case 'Newspaper (Niche)':
					document.title = 'Creative Outlet | Images, Spec Ads, Editorial Content, Design Tips & Sales Ideas for Newspapers';
					break;
				case 'Login':
					document.title = 'Creative Outlet | Login to Your Account';
					break;
				case 'Account Registration':
					document.title = 'Creative Outlet | Create Your Free Account';
					break;
				case 'Forgot Password':
					document.title = 'Creative Outlet | Forgot Password';
					break;
				case 'Creative Outlet Blog':
					document.title = 'Creative Outlet | Blog';
					break;
				case "We'll Create It":
					document.title = 'Creative Outlet | Custom Art Created Just For You';
					break;
				case 'Frequently Asked Questions':
					document.title = 'Creative Outlet | Support & FAQs';
					break;
				case 'Search Pages':
					document.title = 'Creative Outlet | Search';
					break;
				}
			}

			////////////////////////////////////////////////////////////
			// If this is the product page
			////////////////////////////////////////////////////////////
			if (Y.one('div.products')) {
				//shows product headers if appropriate
				if (Y.one('#subscribed-head')) {
					Y.one('#subscribed-head').removeClass('hide');
					if (Y.one('#nonsubscribed-head')) {
						Y.one('#nonsubscribed-head').removeClass('hide');
					}
					if (Y.one('#nonsubscribed-head-desc')) {
						Y.one('#nonsubscribed-head-desc').removeClass('hide');
					}
				}
				var myProductNode = Y.one('div.products');
				var myProducts = myProductNode.all('.product-link');
				myProducts.each(function(n, index) {
					n.on('click', function(e) {
						e.preventDefault();
						Y.fire('displayProductSearch', {
							base_id: n.getAttribute('base_id'),
							product_name: n.getAttribute('title')
						});
					});
				});
			}

			////////////////////////////////////////////////////////////
			// Handle search filter toggles
			////////////////////////////////////////////////////////////
			Y.on('autocomplete:toggleSearchFilter', _toggleSearchFilter);
			Y.on('searchResults:toggleSearchFilter', _toggleSearchFilter);
			Y.on('resultsSize:toggleSearchFilter', _toggleSearchFilter);
			Y.on('searchPanel:toggleSearchFilter', _toggleSearchFilter);
			Y.on('keyword:toggleSearchFilter', _toggleSearchFilter);
			Y.on('toggleSearchFilter', _toggleSearchFilter);

			function _toggleSearchFilter(e) {
				var overlayNode = '<div style="margin-top: 95px; margin-left: 275px; position: absolute !important;z-index: 800;"><div id="processing-overlay" class="" style="z-index: 801"><div class="search-overlay-container" style="z-index: 801"><h4 style="color: #000; margin-left: 20px;">Just a moment, we\'re preparing your results.</h4><br><img src="/img/ajax-loader.gif"></div></div>';

				if (Y.one('#noResults')) {
					if (!Y.one('#noResults').hasClass('dnone')) {
						Y.one('#noResults').toggleClass('dnone');
					}
				}
								
				var searchFilter = Y.one('#search-filter');
				var searchOverlay = Y.one('#processing-overlay');
				
				if (searchFilter) {
					searchFilter.toggleClass('dnone');
					searchOverlay.toggleClass('dnone');
				} else {
					Y.one('#content').set('innerHTML', overlayNode);
				}
				
				//if( !Y.one('#content').hasClass('home') ) {
					Y.one('#processing-overlay').set('innerHTML', '');
					
					var spinner = new Spinner({
					  lines: 10, // The number of lines to draw
					  length: 30, // The length of each line
					  width: 5, // The line thickness
					  radius: 20, // The radius of the inner circle
					  color: '#99CC00', // #rbg or #rrggbb
					  speed: 2, // Rounds per second
					  trail: 60, // Afterglow percentage
					  shadow: false // Whether to render a shadow
					}).spin( Y.one('#processing-overlay') ); // Place in DOM node called
				//}
			}
			
			//init widgets
			new Y.Controller().render();
			new Y.SearchResults().render();
			new Y.EnlargePreview().render();
			
			//////////////////////////////////////////////////
			// Initiate the login widget
			//////////////////////////////////////////////////
			var loginBox = new Y.Login({
				boundingBox: "#loginContent",
				contentBox: "#loginWidget",
				loginBox: "#loggedIn",
				loggedOutBox: "#loggedOut"
			});
			loginBox.set("tabIndex", null);

			//////////////////////////////////////////////////
			// Initiate the panels
			//////////////////////////////////////////////////
			var librarySlider = new Y.LibraryPanel({
				contentBox: "#libraryContent"
			});
			librarySlider.render();

			var libraryContentSlider = new Y.LibraryContentPanel({
				contentBox: "#expandedContent",
				rWidth: '670px',
				rLeft: -938,
				showDuration: 0.15,
				hideDuration: 0.3,
				hideEasing: Y.Easing.easeNone
			});
			libraryContentSlider.render();

			var myCartPanel = new Y.CartPanel({
				contentBox: "#cartContent"
			});
			myCartPanel.render();

			var mySearchPanel = new Y.SearchPanel({
				contentBox: "#searchContent"
			});
			mySearchPanel.render();

			var myBasicSearch = new Y.BasicSearch();
			myBasicSearch.render();
			
			

			////////////////////////////////////////////////////////////
			// Handle clicking off of something
			////////////////////////////////////////////////////////////		
			Y.one('document').delegate("click", function(e) {
				
				/*
				if (Y.one('#searchInput').contains(e.target) == false) {
					Y.fire('autocomplete:hideSuggest');
				}

				if (!e.target.hasAttribute('clickPanel')) {
					// Check to see if there is a current active tool panel
					if (Y.one('.tools .active')) {
						var activeNode = Y.one('.tools .active');
						var placeHolderNode = Y.one('#searchPopup');

						var xy = activeNode.getXY();

						if (activeNode.hasClass('active')) {
							var popUpNode = Y.one('.currentActiveResultsPopUp');
							placeHolderNode.swap(popUpNode);
							popUpNode.toggleClass('hidden');

							(popUpNode.hasClass('pnl_mod_addnote')) && (popUpNode.remove());
							(!popUpNode.hasClass('pnl_mod_addnote')) && (popUpNode.removeClass('currentActiveResultsPopUp'));

							activeNode.toggleClass('active');
						}

					} else if (Y.one('.enlargedLeftHeaderTools .active')) {
						var activeNode = Y.one('.enlargedLeftHeaderTools .active');
						var popUpNode = activeNode.one('.image-sizes');
						popUpNode.addClass('hidden');
						activeNode.removeClass('active');
					}
				}
				*/

				//check if a product search was clicked on
				var subCounter = 0;
				if (Y.one('.subscribed')) {
					Y.all('.subscribed').each(function(node) {
						if (node.contains(e.target)) {
							subCounter++;
						}
					});
				}

				var nonSubCounter = 0;
				if (Y.one('.non-subscribed')) {
					Y.all('.non-subscribed').each(function(node) {
						if (node.contains(e.target)) {
							nonSubCounter++;
						}
					});
				}
				
				//hide the panels when you click off of them
				if (Y.one('#toolsLinks').contains(e.target) == false && subCounter <= 0 && nonSubCounter <= 0) {
					//close advanced search
					if (Y.one('#searchPanel').contains(e.target) == false) {
						mySearchPanel._hidePanel();
					}

					//close library
					if (Y.one('#libraryExpandedPanel').contains(e.target) == false && Y.one('#libraryPanel').contains(e.target) == false && Y.one('.currentActiveResultsPopUp')) {
						if (Y.one('.currentActiveResultsPopUp').contains(e.target) == false) {
							libraryContentSlider._hidePanel();
							librarySlider._hidePanel();
						}
					}

					if (Y.one('#libraryExpandedPanel').contains(e.target) == false && Y.one('#libraryPanel').contains(e.target) == false && !Y.one('.currentActiveResultsPopUp')) {
						libraryContentSlider._hidePanel();
						librarySlider._hidePanel();
					}

					//close cart
					if (Y.one('#cartContent').contains(e.target) == false) {
						myCartPanel._hidePanel();
					}
				}

			}, 'body');

			//////////////////////////////////////////////////
			// Render the login control
			//////////////////////////////////////////////////
			Y.on('available', loginBox.render(), 'loggedIn', this);

			Y.all('.tabview').each(function() {
				this.delegate('click', toggleTabs, '.tabview-tabs a');
			});

			if (Y.one('.random-image')) {
				
				var numChildren = Y.all('.random-image .random');
				var randNum = Math.floor(Math.random() * (numChildren.size() + 1));
				randNum = (randNum < numChildren.size() - 1) ? randNum : randNum - 1;
				var randImg = numChildren.item(randNum);

				var visible = Y.one('#homeImg');
				visible.set('src', randImg.getAttribute('src'));
				visible.set('alt', randImg.getAttribute('alt'));

				Y.one('#homeImgWrapper').removeClass("hide");

			}

			if (Y.one('#industry-select')) {
				Y.one('#industry-select').on('change', toggleIndustryInput);
			}

			if (Y.one('.current_page')) {
				testNicheSubscriber();
			}

			if (Y.one('#no_results')) {
				testSearchResults();
			}

			if (Y.one('.tabview')) {
				handleTabHash();
			}

			/* for old style urls
			var myHash = window.location.hash;
			if (myHash.match('search_terms')) {
				var mySearchTerms = window.location.hash.split('=');
				Y.one('#searchInput').set('value', mySearchTerms[1]);

				//loops over the url params, starting with the 2nd one
				for (var i = 2; i < mySearchTerms.length; i++) {
					if (mySearchTerms[i]) {
						//if it's a filter param
						if (mySearchTerms[i].indexOf("filter") != -1) {
							setSearchFilters(mySearchTerms[i]);
						}
						//if it's an exclude param
						if (mySearchTerms[i].indexOf("exclude") != -1) {
							setExcludeSearchFilters(mySearchTerms[i]);
						}
						//if it's an exact match param
						if (mySearchTerms[i].indexOf("exact") != -1) {
							setExactMatch();
						}
					}
				}

				myAutoComplete._submitSearch();
			}
			*/

		//};

		/*
		//TODO: Major bottleneck.  This has to complete a whole request before the rest of the JS is initiated. 
		var authRequest = new Y.RequestPassthrough({
			uri: '/login',
			cfg: {
				method: 'POST'
			},
			callback: loadPage
		});

		authRequest.startRequest();
		*/
	}

	// end init //////////////////////////////////////////////////////////////////////////////////////////////
	//used when search filter is set via the url
	/*
	function setSearchFilters(filters) {
		filters = filters.replace('filter:', '');
		var currentFilters = Y.one('#searchInputFilters').get('value');
		if (currentFilters) {
			currentFilters = currentFilters + ",";
		}
		Y.one('#searchInputFilters').set('value', currentFilters + filters);
	}

	function setExcludeSearchFilters(keywords) {
		keywords = keywords.replace('exclude:', '');
		Y.one('#exempt_keywords_raw1').set('value', keywords);
	}

	//used when exact match is set via the url
	function setExactMatch() {
		Y.one('#s_intersect1').set('value', 1);
		if (Y.one('#s_intersect')) {
			Y.Node.getDOMNode(Y.one('#s_intersect')).checked = true;
		}
	}
	*/


	function toggleTabs(e) {
		e.preventDefault();

		var tabview = e.container,
			tabs = tabview.all('.tabview-tabs li'),
			contents = tabview.all('.tabview-content > *'),
			tab = e.currentTarget.get('parentNode');

		//tabs			
		Y.all('.tabview-tabs li').each(function(node) {
			node.removeClass('tabview-active');
			node.addClass('tabview-hidden');
		});
		this.get('parentNode').removeClass('tabview-hidden').addClass('tabview-active');

		//content
		Y.all('.tabview-content > div').each(function(node) {
			node.removeClass('tabview-active');
			node.addClass('tabview-hidden');
		});

		var contentDivId = this.get('href').split('#')[1];
		Y.one('#' + contentDivId).removeClass('tabview-hidden');
	}

	//Handles the display of the "Other Industry" input on the registration page.
	function toggleIndustryInput(e) {
		if (e.target.get('value') == "Other") {
			if (Y.one('#other-industry-item').hasClass("hide")) {
				Y.one('#other-industry-item').removeClass("hide");
			}
		} else {
			if (Y.one('#other-industry-item').hasClass("hide") == false) {
				Y.one('#other-industry-item').addClass("hide");
			}
		}
	}

	//Handles the unique content for niche subscriber
	function testNicheSubscriber() {
		if (Y.one('.current_page').get('innerHTML') == "Newspaper (Niche)") {
			Y.one('#nav .create').removeClass("hide");
			if (Y.one('.btn-special')) {
				Y.one('.btn-special').on('click', function(e) {
					e.preventDefault();
					Y.fire('displayProductSearch', {
						base_id: e.target.getAttribute('base_id'),
						product_name: e.target.getAttribute('title')
					});
				});
			}
			if (Y.one('.btn-fun')) {
				Y.one('.btn-fun').on('click', function(e) {
					e.preventDefault();
					Y.fire('displayProductSearch', {
						base_id: e.target.getAttribute('base_id'),
						product_name: e.target.getAttribute('title')
					});
				});
			}
		}
	}

	function testSearchResults() {
		if (Y.one('#total-results').get('innerHTML') == '0') {
			Y.one('#results').addClass('hide');
			Y.one('#no_results').removeClass('hide');
		} else {
			Y.one('#no_results').addClass('hide');
			Y.one('#results').removeClass('hide');
		}
	}

	function handleTabHash() {
		var urlTab = window.location;

		var tabs = Y.all('.tabview-tabs a');
		tabs.each(function(n, index, nl) {
			if (n.get('href') == urlTab) {

				n.simulate("click");
			}
		})
	};

	Y.on("domready", init);
});

//handles storing data in the DOM.
var siteData = {
    get: function(attribute) {
		return document.getElementById('data').getAttribute('data-'+attribute);
    },
    set: function(attribute, value) {		
		//document.getElementById('data').hasAttribute('data-'+attribute)
		if( hasAttribute(document.getElementById('data'), 'data-'+attribute) ) {
			document.getElementById('data').setAttribute('data-'+attribute, value);
		}
    },
	toJson: function() {
		var node = document.getElementById('data'),
			dataObj = {}; 	    
	    
	    /* Doesn't work in IE7 :-(
		for (var i=0, l = 10; i<=l; i++){
			var name = node.attributes.item(i).nodeName.replace('data-', ''),
				value = node.attributes.item(i).value;
				
			if( value.length > 0 
				&& name != 'id' 
				&& name != 'style' 
				&& name != 'initial_page_count_maximum' 
				&& name != 'assets_per_page'
			) {
				//convert to array
				if( name === 'filter_keyword_ids') {
					value = value.split(',');
				}
				dataObj[name] = value;
			}				
		}
		*/
		
		dataObj.exclude_keywords = node.getAttribute('data-exclude_keywords');
		dataObj.matched_keywords = node.getAttribute('data-matched_keywords');
		dataObj.exclude_keyword_string = node.getAttribute('data-exclude_keyword_string');
		dataObj.filter_keyword_ids = node.getAttribute('data-filter_keyword_ids');
		dataObj.keyword_match_type = node.getAttribute('data-keyword_match_type');
		dataObj.preview_size = node.getAttribute('data-preview_size');
		//dataObj.assets_per_page = node.getAttribute('data-assets_per_page'); //doesn't need to be in the url
	    //dataObj.initial_page_count_maximum = node.getAttribute('data-initial_page_count_maximum'); //doesn't need to be in the url
		dataObj.keyword_string = node.getAttribute('data-keyword_string');
		dataObj.rollover_preview = node.getAttribute('data-rollover_preview');
		
		return dataObj;
	}
};

//implement indexOf in IE
if(!Array.prototype.indexOf){
    Array.prototype.indexOf= function(what, i){
        i= i || 0;
        var L= this.length;
        while(i< L){
            if(this[i]=== what) return i;
            ++i;
        }
        return -1;
    }
}

//implement hasAttribute in IE
function hasAttribute(node,attr) {
    return node.hasAttribute ? node.hasAttribute(attr) : !!node.getAttribute(attr);
}
