addEvent(window, 'load', init);

function init() {
	matchColumns();
	initRollovers();
	resizeRelatedProductsFlash();
}

function showBrowseCollection() {
	if ($('browseCollection')) {
		Element.show($('browseCollection'));
	}
}

function hideBrowseCollection() {
	if ($('browseCollection')) {
		Element.hide($('browseCollection'));
	}
}

function showSubNavComfort() {
	if ($('subnavComfort')) {
		Element.show($('subnavComfort'));
	}
}

function hideSubNavComfort() {
	if ($('subnavComfort')) {
		Element.hide($('subnavComfort'));
	}
}

function showSubNavStyle() {
	if ($('subnavStyle')) {
		Element.show($('subnavStyle'));
	}
}

function hideSubNavStyle() {
	if ($('subnavStyle')) {
		Element.hide($('subnavStyle'));
	}
}
function showSubNavSport() {
	if ($('subnavSport')) {
		Element.show($('subnavSport'));
	}
}

function hideSubNavSport() {
	if ($('subnavSport')) {
		Element.hide($('subnavSport'));
	}
}

function showZoom(url) {
	openPop(url, false);
}

function showMoreViews(url) {
	openPop(url, false);
}

function switchMoreView(e, url) {
	if ($('others')) {
		var a = $('others').getElementsByTagName('a');
		for (var i = 0; i < a.length; i++) {
			Element.removeClassName(a[i], 'selected');
		}
		Element.addClassName(e, 'selected');
		$('more-views-image').src = url;
	}
}

function forgotPassword(url) {
	openPop(url, false);
}

function doForgotPassword(f) {
	var myAjax = new Ajax.Updater('pop', f.action, { method: 'post', parameters: Form.serialize(f) });
}

function sendToAFriend(url) {
	openPop(url, false);
}

function doSendToAFriend(f,divId) {
	divId = divId || 'pop';
	var myAjax = new Ajax.Updater(divId, f.action, { method: 'post', parameters: Form.serialize(f), onComplete: function(request) {
		sendTrackingEvent('event2');
	}});
}
// ----------- MJK08_0115 added url to link
function addToShoppingList(url, style) {
	openPop(url, 'style='+style);
}
// function addToShoppingList(style) {
//      openPop('/shopping_list/add?style=' + style);
// }

function deleteFromShoppingList(style) {
	var myAjax = new Ajax.Request('/shopping_list/delete', { method: 'post', parameters: 'style='+style, onComplete: function(request) {
		var ps = document.getElementsByClassName('product_summary');
		if (ps.length == 1) {
			$('shopping_list').innerHTML = '<p>Your shopping list is empty.</p>';
		} else {
			Element.remove('product_summary_'+style);
		}
		
		sendTrackingEvent('scRemove');
	}});
}

function sendShoppingList(url) {
	openPop(url + '/send', false);
}

function doSendShoppingList(f) {
	var myAjax = new Ajax.Updater('pop', f.action, { method: 'post', parameters: Form.serialize(f), onComplete: function(request) {
		sendTrackingEvent('event2');
	}});
}

function sendStyleComparison(styles) {
	openPop('/products/compare/send', 'styles='+styles);
}

function doSendStyleComparison(f) {
	var myAjax = new Ajax.Updater('pop', f.action, { method: 'post', parameters: Form.serialize(f), onComplete: function(request) {
		sendTrackingEvent('event2');
	}});
}

function checkCharCount(e, max_chars) {
	var str = e.value;
	if (str.length > max_chars) {
		e.value = str.substring(0, max_chars);
	}
}
function validateCompare(f) {
	var chk = f.elements['styles[]'];
	var sel = 0;

	if (typeof chk.length != 'undefined') {
		for (var i = 0; i < chk.length; i++) {
			if (chk[i].checked) {
				sel++;
			}
		}
	} else if (chk.checked) {
		sel = 1;
	}

	if (sel < 2) {
		alert('Please select at least 2 styles and click compare.');
		return false;
	} else if (sel > 5) {
		alert('To compare bras, select up to 5 styles and click compare.');
		return false;
	}

	return true;
}

function validateStory(f) {
	var form_valid = false;
	var myAjax = new Ajax.Request('/stories/validate', { method: 'post', parameters: Form.serialize(f), asynchronous: false, onComplete: function(request) {
		if (request.responseText == "success") {
			form_valid = true;
		} else {
			alert(request.responseText);
			form_valid = false;
		}
	}});
	return form_valid;
}

function validateSizeFinder(f) {
	var band_size = (f.elements['band_size'][f.elements['band_size'].selectedIndex].value != '') ? true : false;
	var cup_size  = (f.elements['cup_size'][f.elements['cup_size'].selectedIndex].value != '') ? true : false;
	if (!band_size && !cup_size) {
		alert('Please select a band and cup size from the size finder.')
		return false;
	} else if (!band_size && cup_size) {
		alert('Please select a band size from the size finder.');
		return false;
	}
	return true;
}

function activateField(e) {
	Element.addClassName(e, 'active');
	if (e.value == e.defaultValue) {
		e.value = '';
	}
}

function setInnerHtml(e, v) {
	if ($(e)) $(e).innerHTML = v;
}

function login(f) {
	var myAjax = new Ajax.Updater('loginForm', '/account/authorize', { method: 'post', parameters: Form.serialize(f), evalScripts: true });
}

function subscribeNewsletter(f) {
	var params = 'email=' + $('subscribe_email').value;
	var myAjax = new Ajax.Request(f.action, { method: 'get', parameters: params, onComplete: function(request) {
		alert(request.responseText.stripTags());
		if (request.responseText.match(/Thank you/)) {
			sendTrackingEvent('event3');
			$('subscribe_email').value = $('subscribe_email').defaultValue;
		}
	}});
}

function enterSweepstakes(f) {
	var myAjax = new Ajax.Updater('form-section', f.action, { method: 'post', parameters: Form.serialize(f), onComplete: function(request) {
		if (request.responseText.match(/Good Luck/)) {
			sendTrackingEvent('event5');
			f.reset();
		}
	}});
}

function calculateBraSize(f) {
	openPop(f.action, Form.serialize(f));
}

function openPop(url, params) {
	var myAjax = new Ajax.Updater('pop', url, { method: 'get', parameters: params, evalScripts: true,
		onComplete: function(request) {
			var box  = Element.getDimensions('pop');
			var size = getPageSize();

			$('pop').setStyle({
				top:  ((size[3] - box.height) / 2) + 'px',
				left: ((size[2] - box.width) / 2) + 'px'
			});

			Element.show('pop');
			
			sendTrackingEvent(myAjax.getHeader('X-Bestform-Event') || '');
		},
		onFailure: function(transport) {
			if (transport.status == 401) {
				document.location = '/login';
			}
		}
	});
}

function closePop() {
	Element.hide('pop');
}

function matchColumns(){
	 var divs,contDivs,maxHeight,divHeight,d;
	 divs=document.getElementsByTagName('div');
	 contDivs=[];
	 maxHeight=0;
	 for(var i=0;i<divs.length;i++){
		  if(/\bcolumn\b/.test(divs[i].className)){
				d=divs[i];
				contDivs[contDivs.length]=d;
				if(d.offsetHeight){
					 divHeight=d.offsetHeight;
				}
				else if(d.style.pixelHeight){
					 divHeight=d.style.pixelHeight;
				}
				maxHeight=Math.max(maxHeight,divHeight);
		  }
	 }
	 for(var i=0;i<contDivs.length;i++){
		  contDivs[i].style.height=maxHeight + "px";
	 }
}

function resizeRelatedProductsFlash() {
	if ($('product-view') && $('related-products-flash')) {
		$('related-products-flash').style.height = Element.getHeight('product-view') + 'px';
	}
}

/* Omniture event definitions:
 * event1 - Unused
 * event2 - Send to a Friend
 * event3 - Newsletter Subscription
 * event4 - Store Locator
 * event5 - Best in Life Sweepstakes
 * event6 - Best in Life Submission
 * event7 - Shopping List
 * event8 - New Account
 */
function sendTrackingEvent(event) {
	if (typeof(s) != "object") return;
	switch(event) {
		case 'event2':
			s.pageName = "Bestform Intimates: Send to a Friend";
			s.events = "event2";
			void(s.t());
			break;

		case 'event3':
			s.pageName = "Bestform Intimates: Newsletter Signup";
			s.events = "event3";
			void(s.t());
			break;

		case 'event5':
			s.pageName = "Best in Life Sweepstakes: Thank You";
			s.events = "event5";
			void(s.t());
			break;

		case 'scOpen': 
		case 'scOpen,scAdd':
		case 'scRemove':
			s.pageName = "Bestform Intimates: My Shopping List";
			s.events = event;
			void(s.t());
			break;
	}
}
