/* Site Wide */

// Replace any swfObject instances. 
// The name of the swf needs to be in the element's rel attribute.
function swfObjectReplacement(){
	$$('.flashcontent').each(function(flashDiv, index){
		var so = new SWFObject(flashDiv.getAttribute('rel'), flashDiv.id, flashDiv.getAttribute('width'), flashDiv.getAttribute('height'), "9", "#ffffff");
		so.addParam("allowScriptAccess", "always");
		so.addVariable('xmlpath', 'flash/');
		// Adds flashVars by looking for input elements with rel="flashVar" that are within the swf div
		flashDiv.select('[rel="flashVar"]').each(function(v,i){
			so.addVariable(v.getAttribute('name'), v.value);
		}.bind(this));
		// Add flash params in the same fashion as above
		flashDiv.select('[rel="flashParam"]').each(function(v,i){
			so.addParam(v.getAttribute('name'), v.value);
		}.bind(this));
		so.write(flashDiv.id);		
	});
}

// Collapses elements when the DOM loads. 
// We keep them open by default for users who don't have JavaScript enabled.
function collapseCollapsibleLists(){
	$$('.collapsible_list .dt, .collapsible_list .dd').each(function(el,i){
		el.addClassName('collapsed');
		if(el.hasClassName('dt')){
			el.childElements().each(function(label, index){
				$(label).observe('click', toggleCollapsibleItem);
			});
		}
	});
}

// Open or close a collapsible element
function toggleCollapsibleItem(event){
	var label = event.element();
	var dt = $(label.reverseSelect('.dt'));
	var dd = dt.nextSiblings().find(function(el){return el.hasClassName('dd')});
	if(dt.hasClassName('collapsed')){
		dt.removeClassName('collapsed');
		if(dd) dd.removeClassName('collapsed');
	}else{
		dt.addClassName('collapsed');
		if(dd) dd.addClassName('collapsed');
	}
	if(Prototype.Browser.IE){
		// Fixes a collapse bug in IE. I don't ask questions.
		$$('.collapsible_list dt').each(function(e,i){
			e.style.position = 'absolute';
			e.style.position = 'relative';		
		});		
	}
}

// Converts <select> elements into a custom drop-down that can be styled
function convertSelectLists(){
	$$('select.stylized').each(function(select, index){		
		selectId = select.id || 'formSelect'+Math.floor(Math.random()*1000000);
		selectClass = select.className;
		var listMarkup = ['<div class="actionable_select_list '+selectClass+'"><input name="'+select.name+'" type="hidden" id="'+selectId+'"/><ul>'];
		$A(select.options).each(function(option, i){
			listMarkup.push('<li');
			if(option.selected) listMarkup.push(' class="selected"');
			listMarkup.push('><a href="#" onclick="customDropDownSelect(\''+selectId+'\',\''+option.value+'\',this.parentNode);return false;">'+option.innerHTML+'</a></li>');
		}.bind(this));		
		listMarkup.push('</ul></div>');
		select.insert({before: listMarkup.join('\n')});
		$(select.parentNode).removeChild(select);
		$(selectId).value = select.value;
	});
	convertActionableSelectLists();
}

// Called when a user selects an item in one of our custom select drop-downs
function customDropDownSelect(selectInputId, value, li){
	$(selectInputId).value = value;
	$(selectInputId).fire('select:changed', {select : $(selectInputId)});
	$(li.parentNode).childElements().each(function(e,i){e.removeClassName('selected')});
	$(li.parentNode.parentNode).addClassName('collapsed_select_list');
	$(li).addClassName('selected');
}

// Converts UL lists with class="actionable_select_list" into custom drop downs.
// Good for drop down elements that have a collection of links, and preserves 
// non-javascript compatability.
function convertActionableSelectLists(){
	$$('.actionable_select_list').each(function(listContainer, index){		
		if(listContainer.select('.actionable_select_drop').length == 0){
			toggleActionableSelectList(listContainer);
			listContainer.insert({top : '<a class="actionable_select_drop" onclick="toggleActionableSelectList(this.parentNode)">&nbsp;</a>'});
		}
	});
}

// Displays the options in a custom select drop-down and hides any that might already be open.
function toggleActionableSelectList(listContainer){
	if(listContainer.hasClassName('collapsed_select_list')){
		$$('.actionable_select_list').each(function(list, i){ list.addClassName('collapsed_select_list')});
		listContainer.removeClassName('collapsed_select_list');
	}else{
		listContainer.addClassName('collapsed_select_list');
	}	
}

// Makes the help tooltips more robust
function addHelpTooltips(){
	// Add the tooltip DOM node
	if(! $('tooltip')) document.body.innerHTML += '<span id="tooltip" style="display:none"><span id="tooltip_copy">&nbsp;</span><span id="tooltip_pointer">&nbsp;</span></span>';
	$$('.tool_question').each(function(el,i){
		// Move the title to the tooltip attribute so it doesnt appear when the mouse it over the button
		var tooltipText = el.getAttribute('title');
		el.setAttribute('title', '');
		el.observe('mouseover', function(event){
			var position = el.cumulativeOffset();
			var tooltip = $('tooltip');
			$('tooltip_copy').innerHTML = tooltipText;
			tooltip.style.top = position.top-(tooltip.getHeight()+15)+'px';
			tooltip.style.left = position.left-(tooltip.getWidth()/2)+'px';
			tooltip.show();
		}.bind(this));
		el.observe('mouseout', function(event){ $('tooltip').hide();});
	})
}

/* Page Specific */

// Redeem

// Stores the value of the currenly selected redeemable location
var selectedVendor;

// Highlights the logo of the currently selected redeemable location
function observeRedeemableRadios(){
	$$('#select_a_vendor [type="radio"]').each(function(radio, index){
		observeVendorRadio(radio);
	});
}

// Listen for clicks on the vendor logos, and update the background images to reflect their select state
function observeVendorRadio(radio){
	radio.style.display = 'none';
	if(radio.checked) selectedVendor = radio;

	// If the browser is IE, click the radio button when the label is clicked.
	// Other browsers do this by default.
	if(Prototype.Browser.IE){
		$(radio.parentNode).observe('click', function(){ radio.click() }.bind(this))
	}
	
	$(radio).observe('click', function(e){
		// Update the selection
		if(radio.checked){				
			if(selectedVendor && selectedVendor != radio){
				img = $(selectedVendor.parentNode).select('.vendor_logo')[0];
				if(img) img.removeClassName('selected');
			}
			selectedVendor = radio;
			img = $(selectedVendor.parentNode).select('.vendor_logo')[0];
			if(img) img.addClassName('selected');
			// The name of the location is stored in the radio's "title" attribute
			var locationName = radio.getAttribute('title');
			if(locationName){
				$('redemption_card_type').innerHTML = locationName
				$('selected_location_type').show();
			}
		}else{
			img = $(selectedVendor.parentNode).select('.vendor_logo')[0];
			if(img) img.removeClassName('selected');
			selectedVendor = null;
			$('selected_location_type').hide()
		}
	}.bind(this));
}

// Hides the redemption methods that are toggled by the select list
function hideRedemptionMethods(){
	$$('.redemption_method').each(function(el,i){
		el.hide();
	});
	observeRedemptionMethod();
}

// Toggles the selected redemption method
function observeRedemptionMethod(){
	$$('.redemption_method').each(function(e,i){e.hide()});
	if(!!$('redemption_method').value) $("redeem_"+$('redemption_method').value).show();
}

// My Account

$NUM_DEFAULT_CARDS = 4;

// Hides any cards greater than the default number
function paginateMyCards(){
	var cardCollection = $$('ul#my_saved_cards li');
	var numPages = Math.ceil(cardCollection.length / $NUM_DEFAULT_CARDS * 1.0);
	if(cardCollection.length > $NUM_DEFAULT_CARDS){
		$('my_saved_cards_pagination').innerHTML = "Page:";
		for(var i=$NUM_DEFAULT_CARDS; i<cardCollection.length; i++){
			cardCollection[i].hide();
		}
		for(var i=0;i<numPages;i++){
			$('my_saved_cards_pagination').innerHTML += "<a href='#' onclick='paginateCards("+i+");return false;' class='pagination_link' id='pagination_link_"+i+"' title='Page "+(i+1)+"'>"+(i+1)+"</a>";
		}
		$('pagination_link_0').addClassName('current');
	}
}

// Only show $NUM_DEFAULT_CARDS at a time. The rest are revealed through pagination.
function paginateCards(pageNum){
	var cards = $$('ul#my_saved_cards li');
	cards.each(function(card,i){card.hide();});
	var startCard = (pageNum*$NUM_DEFAULT_CARDS);
	var endCard = startCard+$NUM_DEFAULT_CARDS;
	for(var i=startCard; i<endCard; i++){
		cards[i].show();
	}
	$$('.pagination_link').each(function(link,i){
		link.removeClassName('current');
	});
	$('pagination_link_'+pageNum).addClassName('current');	
}

// Make the entire Person header a link
function addLinksToPeopleHeaders(){
	$$('.column.roster li').each(function(summary, index){
		var link = summary.select('.link_to_person')[0];
		var header = summary.select('.people_header')[0];
		if(link && header){			
			header.addClassName('clickable');			
			header.observe('click', function(){
				location.href = link.href;
			}.bind(this));
		}
	});
}

// Make the entire Article header a link
function addLinksToArticleListItems(){	
	$$('#articles_list li').each(function(li, index){
		var link = li.select('.article_link')[0];
		if(link){			
			li.addClassName('clickable');			
			li.observe('click', function(){
				location.href = link.href;
			}.bind(this));
		}
	});	
}

// Safari doesn't take you to the top of the page with a blank anchor link (e.g. <a href="#">) 
// if there is a named anchor in the page. Wierd.
function observeJumpToTop(){
	$$('[href=#]').each(function(link,i){
		link.onclick = function(){
			scrollTo(0,0);
			return false;
		}
	});
}

/* Finally */

// Page specific DOM Loader methods
var domLoaders = {
	'redeem' : function(){
		hideRedemptionMethods();
		observeRedeemableRadios();
		document.observe('select:changed', function(event){
			if(event.element() == $('redemption_method')){ observeRedemptionMethod(); }
		});		
	},
	'add_a_card' : function(){
		observeRedeemableRadios();
	},
	'my_account' : function(){
		paginateMyCards();
	},
	'rewards_faqs' : function(){
		// Wrap this page in the faq class, so the pages inherit the same styles
		$(document.body).addClassName('faqs');
	},
	'people' : function(){
		addLinksToPeopleHeaders();
	},
	'articles' : function(){
		addLinksToArticleListItems();
	}
};

// Adds the name of the browser and OS as class names to the <body>
function addBrowserClass(){
	var className = "";
	if(navigator.userAgent.indexOf("Macintosh") == -1){
		className = "pc ";
	}else{
		className = "mac ";
	}
	className += Prototype.Browser.IE ? "IE" : Prototype.Browser.Opera ? "Opera" : Prototype.Browser.WebKit ? "WebKit" : Prototype.Browser.Gecko ? "Gecko" : "";
	$(document.body).addClassName(className);
}

// Called when the page loads
function domLoader(){
	// Visible
	
	Cufon.replace('h3');
	Cufon.replace('.clarendon');


	addBrowserClass();
	swfObjectReplacement();
	collapseCollapsibleLists();
	convertSelectLists();
	// For each class name in the body, check if there is a local domLoader for it
	// and execute if there is.
	document.body.className.split(' ').each(function(className,index){
		if(loader = domLoaders[className]){
			loader();
		}
	});
	// Invisible
	
	observeJumpToTop();
	$$('h1').each(function(h1,i){h1.observe('click', function(){location.href = 'index.aspx'})});	
}

document.observe('dom:loaded', domLoader);
