/* PANGEA ORGANICS */
/* Functions
----------------------------------------------------------------------------- */


	$(window).load(function() {
		

/* FACEBOOK
----------------------------------------------------------------------------- */

	FB.init({
		
	    appId  : '188617611176688',
	    status : true, // check login status
	    cookie : true, // enable cookies to allow the server to access the session
	    xfbml  : true  // parse XFBML
	
	  });
		

/* ROTATE FEATURED PRESS BOX
----------------------------------------------------------------------------- */	

	rotate("Featured Press");


/* FEATURES BOX
----------------------------------------------------------------------------- */


	if (page == "index") {

		// Rotate Featured Banners
		rotate("Featured Banners");

		// Rotate Featured Products
		rotate("Featured Products");

		// Toggle Pangea TV
		$('a.pangeatv').click(function() {

			$('#featured_banners').addClass('hide');
			$('#pangea_tv_player').removeClass('hide');

			$('#featured_banners').tabs('rotate', null);

			if ($('#pangea_tv_player #video div.flash div').length > 0) {

				var player = $('#pangea_tv_player #video div.flash div').attr('id');
				eval(player)();

			}

			return false;

		});

		// Toggle Featured Banners
		$('a.banners').click(function() {

			$('#pangea_tv_player').addClass('hide');
			$('#featured_banners').removeClass('hide');

			$('#featured_banners').tabs('rotate', 5000);

			$('#pangea_tv_player #video div.flash div').empty();

			return false;

		});

	}


/* HIDE DISCOUNT CODE INPUT FIELDS
----------------------------------------------------------------------------- */

	
	if (page == "added") {
	
		$('#basket-sidebar tbody.discounts tr.code:last').addClass('last');
	
	}


/* JOSHUA'S BLOG COUNT
----------------------------------------------------------------------------- */
	
	if (page == "site") {
		
		$('#content div.widget-editorial ul.stories > li').each(function() {
			
			// Replacing hyphens with underscores for comments associated with legacy URLs
			var blogURL = $(this).children('h4').children('a').attr('href').replace(/-/g, '_');
						
			//$('<a class="fb-comments" href="' + blogURL + '"><fb:comments-count href=http://www.pangeaorganics.com' + blogURL + '></fb:comments-count>Comments. Add a Comment.</a>').insertAfter($(this).children('h4'));
			$('<iframe class="fb-comments" src="http://www.facebook.com/plugins/comments.php?href=http://www.pangeaorganics.com' + blogURL + '&permalink=1" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:130px; height:16px;" allowTransparency="true"></iframe>').insertAfter($(this).children('h4'));
									
		});
		
	}
	

/* ROTATE FEATURED BANNERS
----------------------------------------------------------------------------- */


	if (page == "login") {

		rotate("Featured Banners");

	}


/* REDEEM GIFT CERTIFICATES
----------------------------------------------------------------------------- */


	if (page == "cart" || section == "checkout") {

		$('input.lookup').cliqueForms();
	
	}
	
	if (section == "checkout") {
	
		$('div.summary table.order select').not('.replace').unbind('change');
		$('<ul class="actions"><li class="emphasis"><a class="action save" href="#">Save Changes</a></li></ul>').insertAfter('table.order');
		$('table.order + ul a').click(function() {
		
			$('#order').parent().submit();
			return false;
		
		});
	
	}
	
	
/* GIFT PAGE
----------------------------------------------------------------------------- */


	if (page == "gift") {
	
		// Unhide container
		$('div.corner').show();
		$('div.widget-item.display').show();
		
	}


/* ADD "BUY ANOTHER" BUTTON PATTERN
----------------------------------------------------------------------------- */

	if (page == "product") {

		//$('div.widget-alert.added').cliqueAlertWidget();

	}


/* PRESS PAGE
----------------------------------------------------------------------------- */


	if (page == "press") {

		// Add hover state
		$('div.widget-tag ul').hover(function() {

			$(this).addClass('hover');

		}, function() {

			$(this).removeClass('hover');

		});	
		
	}


/* FORMAT ITEM TOOLTIP
----------------------------------------------------------------------------- */


	$('div.widget-item.label ul.items li').each(function() {

		var link = $(this).find('a').attr('href');
		var tags = $(this).attr('class');

		// Add hover state
		$(this).hover(function() {
	
			$(this).addClass('hover');
	
		}, function() {
	
			$(this).removeClass('hover');
	
		});

		// Make entire item clickable
		$(this).click(function() {

			window.location = link;
		
		});
	
		// Add buy link + translucent background
		$(this).prepend('<a class="action buy" href="' + link + '">Buy Product</a><var></var>');

		// Prepend product type
		var productType = getProductType(tags);

		if (productType) {

			$(this).find('dl').prepend('<dt class="type">' + productType + '</dt>');

		}

		// Prepend skin type
		var skinType = getSkinType(tags);

		if (skinType) {

			$(this).find('dl dt:last').before('<dt class="skin">for ' + skinType + ' skin</dt>');

		}

	});


/* FUNCTION CALLS
----------------------------------------------------------------------------- */


	markup();
	dropDown();
	cufon();
	tabs();
	paging();
	readmore();
	ticker();
	if (page == "faq" ) faq();
	

/* END LOAD FUNCTION
----------------------------------------------------------------------------- */	


	});


/* FUNCTION: FAQ Headline Expander
----------------------------------------------------------------------------- */

	function faq() {
		
		$('div.widget-editorial.browse ul.stories > li div.story').hide();
	
		$('div.widget-editorial.browse h4 a').toggle(function() {
			
			$(this).parent('h4').siblings('div.story').show();
			return false
			
		}, function() {
			
			$(this).parent('h4').siblings('div.story').hide();
			return false
			
		});
		
		
	}


/* FUNCTION: ENABLE PRODUCTS' DROPDOWN
----------------------------------------------------------------------------- */


	function dropDown() {

		// Animate
		$('#header li.products a').toggle(function() {

			$('#products').animate({ "height": "toggle" }, "medium", function() {

				$('#products').show();
				
			});
			
			$(this).parent('li').addClass('selected');

		}, function() {

			$('#products').animate({ "height": "toggle" }, "medium", function() {

				$('#products').hide();

			});
			
			$(this).parent('li').removeClass('selected');

		});

		// Add label to search text field
		if ($("#products div.widget-item.search #query").val() == "") {
	
			$("#products div.widget-item.search #query").val("Search Products").attr("title", "Search Products");
		
		}
	
		$("#products div.widget-item.search #query").click(function() {
		
			var label = $(this).attr("title");
			if (label == $(this).val()) {
			
				$(this).val("");
			
			}			
		
		});
		
		$("#products div.widget-item.search #query").blur(function() {
		
			var label = $(this).attr("title");
			if ($(this).val() == "") {
			
				$(this).val(label);
			
			}
			
		});

	}


/* FUNCTION: CUFON REPLACEMENTS
----------------------------------------------------------------------------- */


	function cufon() {

		var din_bold = [
		
			'#featured_products dt a',
			'div.widget-item.display div.details div h3',
			'div.widget-item.catalogue h3',
			'div.widget-tag.list li a',
			'div.widget-tag.display h3',
			'div.widget-item.label dt a',
			'div.widget-cart.modify h3',
			'div.widget-alert.added h3',
			'div.widget-alert.added h4',
			'div#boxes div h3',
			'body.section-legal div#content h3',
			'body.section-legal div#content h4',
			'div.widget-account.modify h3',
			'div.widget-account.modify:not(.addresses) h4',
			'#page-added div.widget-item.label h3',
			'#page-press div.widget-tag h3',
			'div#locations ul.options li a',
			'div#locations ul.options li strong',
			'body.section-news ul.tabs li',
			'body.section-ourpromise ul.tabs li',
			'div.widget-editorial h4:not(#page-wholesale div.widget-editorial div.story h4)',
			'div.widget-event h3',
			'div.widget-event a.date',
			'#plans h3',
			'#viewer p.lead',
			'div.widget-item.gift div.details h3',
			'div#sidebar div.pane h3',
			'body.section-ingredientglossary ul.tabs li',
			'a.faketab',
			'#ticker h3',
			'#page-wholesale div.widget-editorial div.story h3', 
			'div.widget-promotion h4', 
			'#page-promotions div.widget-editorial div.story ul li a'
			
		];
		
		var din_light = [
		
			'#featured_products dt em',
			'div.widget-item.display div.topic ul.tags li',
			'dt.type',
			'h2',
			'div.widget-item.gift div.topic h3'
		
		];

		Cufon.replace(din_bold, { fontFamily: 'DIN Bold', hover: true });
		Cufon.replace(din_light, { fontFamily: 'DIN Light', hover: true });
		
		$(din_bold.toString()).css('visibility', 'visible');
		$(din_light.toString()).css('visibility', 'visible');
				
	}


/* FUNCTION: LOADING INDICATOR
----------------------------------------------------------------------------- */


	function loading(event) {

		/*if (event == "start") {

			$('#loading').animate({
			left: '0px'
			}, 300);

		} else {

			$('#loading').animate({
			left: '-54px'
			}, 300);

		}*/

	}


/* FUNCTION: TESTIMONIES TICKER
----------------------------------------------------------------------------- */
	
	
	function ticker() {
		
		if ($('#ticker').length > 0) {
	
			$('#ticker').append('<ul class="pagination"><li><a class="action prev" id="prev" href="#">Previous</a></li><li><a class="action next" id="next" href="#">Next</a></li><li><a class="action browse" href="/testimonies">Read More Testimonies</a></li></ul>');

			$('#ticker > ul.leads').cycle({
			
			fx:      'fade',
			speed:    400,
			timeout:  20000,
			prev:	'#prev',
			next:	'#next'
			
			});
			
			$('#ticker').fadeIn();
		
		}
		
	}


/* FUNCTION: TABS
----------------------------------------------------------------------------- */


	function tabs() {

		// Javascript Tabs
		$('div.tabbed').not(".ajax, .static").tabs({

			fxSlide: false,

			click: function() {

			}, load: function() {

				cufon();

			}, show: function() {

				cufon();

			}

		});

		// AJAX Tabs
		$('div.tabbed.ajax').tabs({

			fxSlide: false,

			click: function() {

				loading('start');

			}, load: function() {

				cufon();
				loading('stop');

			}, show: function() {

				cufon();
				loading('stop');

			}

		});

	}
	
	
/* FUNCTION: PAGING FOR TABS
----------------------------------------------------------------------------- */ 


	function paging() {

		// Javascript Tabs
		$('div.tabbed:not(.ajax):not(.static) ul.paging a, div.tabbed:not(.ajax):not(.static) ul.pages a').each(function() {

			var panel = $(this).parents('div.ui-tabs-panel').attr('id'); 
			$(this).attr('href', $(this).attr('href') + '#' + panel); 

		});

		// AJAX Tabs
		$('div.tabbed.ajax ul.paging a, div.tabbed.ajax ul.pages a').livequery('click', function(event) {

			loading('start');

			$(this).parents('div.ui-tabs-panel').load($(this).attr('href'), function(data) {

				cufon();
				loading('stop');

			});

			return false;

		});

	}
	

/* FUNCTION: CHANGE PAGE COLOR
----------------------------------------------------------------------------- */


	function changePageColor(allTags) {

		var color;  // HEX color

		// Compares array for matching tag names
		for (var i = 0; i < HEXColors.length; i++) {

			var productTags = HEXColors[i][1].split(" ");

			for (var j = 0, k = 0; j < productTags.length; j++) {

				// If there's a matchtag, increase counter
				if (allTags.match(productTags[j])) {

					k++;

				}

				// If all classes are found in tag, set HEX color
				if (k == productTags.length) {

					color = HEXColors[i][2];

				}

			}

		}

		// If there is no match, default HEX color is used
		if (color == undefined) {

			color = "#eae4e1";

		}

		// Changes page color to matching HEX color
		if (page == "index") {

			$('div#header, div#corners, div.corner, #featured_banners, #pangea_tv_player, #featured_products a.back').animate({ backgroundColor: "#" + color }, 'slow');

		}

		if (page == "product") {

			$('div#header, div#corners, div.corner, div.widget-item.display').animate({ backgroundColor: "#" + color });

		}

		return true;

	}


/* FUNCTION: CHANGE PAGE COLOR AFTER CYCLE TRANSITION
----------------------------------------------------------------------------- */


	function afterTransition() {

		changePageColor($('#featured_products ul.items li:visible').attr('class'));

	}


/* FUNCTION: GET PRODUCT TYPE
----------------------------------------------------------------------------- */


	function getProductType(tags) {

		for (var i = 0; i < ProductTypes.length; i++) {

			// Find a matching product type tag
			if (tags.match(ProductTypes[i][2])) {

				return ProductTypes[i][1];  // Product type name

			}

		}

		return false;

	}


/* FUNCTION: GET SKIN TYPE
----------------------------------------------------------------------------- */


	function getSkinType(tags) {

		var matchedTypes = [];  // Array of matched skin types

		for (var i = 0; i < SkinTypes.length; i++) {

			// Find matching skin type tags
			if (tags.match(SkinTypes[i][1])) {

				matchedTypes.push(SkinTypes[i][0].toLowerCase());

			}

		}
		
		if (matchedTypes.length > 0) {
			
			var series = "";

			// Format matching skin types into a series
			for (i = 0; i < matchedTypes.length; i++) {

				if (i == 0) {
				
				series += matchedTypes[i];
				
				}
				
				else if (matchedTypes.length % i == 1 || i == matchedTypes.length - 1) {
				
				series += " & " + matchedTypes[i];
				
				}
				
				else {

				series += ", " + matchedTypes[i];
				
				}

			}

			return series;
		
		}
		
		return false;

	}


/* FUNCTION: ROTATIONS
----------------------------------------------------------------------------- */


	function rotate(object) {

		switch(object) {

			// Rotate Featured Press Box
			case "Featured Press":
	
				$.get('/feeds/banners', function(data) {
	
					// Load banners
					$(data).find('unit').each(function() {
	
						if ($(this).find('name').text() == "press_box") {
	
							var clippings = '<ul>';
	
							$(this).find('banner').each(function() {
	
								if ($(this).children('status').text() != "Retract Temporarily") {
	
									var title = $(this).children('description').text();
									var link = $(this).children('url').text();
									var image = $(this).children('image').text();
		
									clippings += '<li><h3><em>Featured In</em><br />' + title + '</h3><img src="' + image + '" /><a class="action circle" href="' + link + '">Go To Press</a></li>';
								
								}
	
							});
	
							clippings += '</ul>';
							
							$('div.box.press').append(clippings);
	
						}
	
						$('div.box.press ul').cycle({
			
							fx:      'fade',
							speed:    '5000'
	
						});
	
					});
	
				});
				
				break;

			// Rotate Featured Banners
			case "Featured Banners":
	
				$.get('/feeds/banners', function(data) {
	
					// Load banners
					$(data).find('unit').each(function() {
	
						if ($(this).find('name').text() == "features_box_banner") {
	
							var slideshow = '<div id="slideshow">';
							var tabs = '<ul class="tabs">';
							var bannerNumber = 1;
	
							$(this).find('banner').each(function() {
	
								if ($(this).children('status').text() != "Retract Temporarily") {
	
									var url = $(this).children('url').text();
									var image = $(this).children('image').text();
									var caption = $(this).children('description').text();
		
									tabs += '<li><a href="#banner' + bannerNumber + '">' + caption + '</a></li>';
		
									// Add corners mask
									if (page == "login") {
										slideshow += '<a id="banner' + bannerNumber + '" href="' + url + '"><div class="corners"></div><img src="' + image + '" alt="' + caption + '" /></a>';
									}
		
									else {
										slideshow += '<a id="banner' + bannerNumber + '" href="' + url + '"><img src="' + image + '" alt="' + caption + '" /></a>';
									}
		
									bannerNumber++;
							
								}
	
							});
	
							slideshow += '</div>';
							tabs += '</ul>';
	
							$(slideshow).appendTo('#featured_banners');
							$(tabs).appendTo('#featured_banners');
	
						}
	
					});
	
					$('#featured_banners').tabs({ fx: { opacity: 'toggle', duration: 'slow' } });
					$('#featured_banners').tabs('rotate', 5000);
	
				});
				
				break;
	
			// Rotate Featured Products
			case "Featured Products":
	
				$('#featured_products ul.pages, #featured_products ul.paging').remove();  // Clear out pagination from widget
	
				$('#featured_products').append('<ul class="actions paging"></ul>');
				$('<li><a id="featured_products_next" class="action next" href="#">Next</a></li>').prependTo('#featured_products ul.paging');
				$('<li><a id="featured_products_back" class="action back" href="#">Back</a></li>').prependTo('#featured_products ul.paging');
	
				$('#featured_products ul.items').cycle({
	
					fx:      'fade',
					speed:    'slow',
					timeout:  0,
					next:    '#featured_products_next',
					prev:    '#featured_products_back',
					after:   afterTransition  // Change page color upon load and transition of slideshow
	
				});
	
				break;	
					
			default:
				
		}
	}
	

/* FUNCTION: MOVE "READ MORE" LINK
----------------------------------------------------------------------------- */ 


	function readmore() {

		$('#ticker ul.leads > li').each(function() {

			var link = $(this).find('a.display').attr('href');
			$(this).find('ul.actions').remove();

			// IF LAST CHILD IS P.LEAD
			if ( $(this).find('div.story > *:last-child').hasClass('lead') ) {

				$(this).find('div.story p.lead:last').append('&nbsp;&nbsp;<a class="readmore" href="' + link + '">Read More...</a>');

			}

			// IF LAST CHILD IS ANOTHER ELEMENT
			else {

				$(this).find('div.story > *:last-child').after('<br /><a class="readmore" href="' + link + '">Read More...</a>');

			}

		});

	}


/* FUNCTION: TRUNCATE TEXT
----------------------------------------------------------------------------- */


	function truncate() {

		// DESCRIPTIONS OF TITLED BROWSE WIDGETS
		$('#ticker ul.leads li div.story').each(function() {

			if ($(this).text().length >= 240) {

				var text = $(this).text().slice(0,240);

				$(this).text(text);
				$(this).append('<var>&nbsp;&hellip;</var>');

			}

		});

	}

