/* 

MAD.js is an in-hosue e-commerce javascript library written by Dan Wellman 
copyright 2009 MAD Productions

version 1.2

*/
var MAD = {};
MAD.pages = {};

//Pages Init Functions
MAD.pages.all = (function() {

	//Add product to collection
    var _init = function() {
		_recentlyViewed();
		_tabbedCarousel();
		_labelPicker();
		_mergeNewsletter();
    }
	
	var _tabbedCarousel = function() {
		// HIDE CAROUSELS IF THEY DON'T CONTAIN ANY PRODUCTS
		if (!$('.tabbed-carousels .content-block .top-sellers li').length && !$('.tabbed-carousels .content-block .new-arrivals li').length ) {
			$('.tabbed-carousels').hide();	
		}
		else if (!$('.tabbed-carousels .content-block .new-arrivals li').length) {
			$(".tabbed-carousels .tabs .new-arrivals").removeClass('on').hide();
			$(".tabbed-carousels .tabs .top-sellers").addClass("on");
			$(".tabbed-carousels .content-block .top-sellers").css({left: '1px'});
			$(".tabbed-carousels .content-block .new-arrivals").css({left: '-9999px'});
		}
		else if (!$('.tabbed-carousels .content-block .top-sellers li').length) {
			$(".tabbed-carousels .tabs .top-sellers").removeClass('on').hide();
			$(".tabbed-carousels .tabs .new-arrivals").addClass("on");
			$(".tabbed-carousels .content-block .new-arrivals").css({left: '1px'});
			$(".tabbed-carousels .content-block .top-sellers").css({left: '-9999px'});
		}
		// SWITCH CAROUSEL ON CLICK
		$(".tabbed-carousels .tabs .new-arrivals").click(function() {
			$(".tabbed-carousels .content-block .new-arrivals").css({left: '1px'});
			$(".tabbed-carousels .content-block .top-sellers").css({left: '-9999px'});
			$(this).addClass("on");	
			$(".tabbed-carousels .tabs .top-sellers").removeClass("on");
			return false;
		});
		// SWITCH CAROUSEL ON CLICK
		$(".tabbed-carousels .tabs .top-sellers").click(function() {
			$(".tabbed-carousels .content-block .top-sellers").css({left: '1px'});
			$(".tabbed-carousels .content-block .new-arrivals").css({left: '-9999px'});
			$(this).addClass("on");	
			$(".tabbed-carousels .tabs .new-arrivals").removeClass("on");
			return false;
		});
	
	}

	var _recentlyViewed = function() {
		$("#header .recentlyViewed").hover(function() {
           	$("#header .recentlyViewed .rvContent").stop(true,true).slideDown("fast");
		}, function() {
			$("#header .recentlyViewed .rvContent").stop(true,true).slideUp("fast");
		});
    }
	
	var _labelPicker = function() {
		$(".brand-selection .allLabels").click(function() {
        	if ($(".brand-selection .allLabels:checked").length) {
				$(".brand-selection input[type=checkbox]").attr('checked', true);
			}
			else {
				$(".brand-selection input[type=checkbox]").attr('checked', false);
			}
		});
		$(".brand-selection span :checkbox").click(function() {
			if (this.checked) {
				this.checked = true;
			}
			else {
				this.checked = false;
				if ($(".brand-selection .allLabels:checked").length) {
					$(".brand-selection .allLabels").attr('checked', false);
				}
			}
											   
		});
    }
	var _mergeNewsletter = function(id) {
		// FIRE LIGHTBOX FROM DIFFERENT LOCATIONS
		$('.openNewsletterSignup').click(function() {
			MAD.lightBox.show('.lbNewsletter'); 
			$('.lbNewsletter input.email').val($(this).parent().find('input').val());
			return false;
    	});
	}


    return {
        init: _init,
		tabbedCarousel: _tabbedCarousel,
		recentlyViewed: _recentlyViewed,
		labelPicker: _labelPicker,
		mergeNewsletter: _mergeNewsletter
    }
})();

MAD.lightBox = (function() {

    var _init = function() {
        $(".overlay").click(function() {
        if (!$(".modal").is(":visible")) {
			$(".lightbox").hide();
			$(".expandedContent").hide();
			$(this).hide();
        }
        });

        $(".lightbox .btn_close").attr("href", "javascript:MAD.lightBox.hide();");
    }

    var _show = function(id) {
		var topPos = (($(window).height() - $(id).height()) / 2 + $(window).scrollTop());
		if (topPos < 0) {
			topPos = 10;	
		}
        $(id).css("top", topPos + "px");
        $(id).css("left", ($(window).width() - $(id).width()) / 2 + $(window).scrollLeft() + "px");
        $('.overlay').show();
        $(id).show();
        return false;
    }

    var _hide = function() {
        $(".lightbox").hide();
        $(".overlay").hide();
        //return false;
    }

    //return public methods
    return {
        init: _init,
        show: _show,
        hide: _hide
    }
})();

MAD.core = (function() {
	
	//do a little browser test
  var _browser = {
		ie:(window.ActiveXObject) ? true : false
	};
	
	//specify card image paths
	var _cardImgs = {
		delta:"url(/common/img/icons/delta.gif) no-repeat",
		electron:"url(/common/img/icons/electron.gif) no-repeat",
		maestro:"url(/common/img/icons/maestro.gif) no-repeat",
		mastercard:"url(/common/img/icons/mastercard.gif) no-repeat",
		solo:"url(/common/img/icons/solo.gif) no-repeat",
	  visa:"url(/common/img/icons/visa.gif) no-repeat"
	};
	
	//specify popup sizes
	var _popSizes = {
	//	sizes:"500:417",
		delivery:"500:417",
		emailFriend:"488:510",
		forgottenPassword:"500:360",
		product:"620:700",
		securityCode:"500:417",
		terms:"620:600"
	};
	
	//jquery getElsByClass wrapper function	
	var _getElementsByClass = function(className) {
		return $("." + className);
	};
	
	//attach events crossbrowser
	var _xAttachEvent = function(el, evt, handler, args) {
				
		//is 1st arg a string or array?
		if (typeof(el) == "string") {
			
			//work out if id or classname
			if (el.indexOf(".") == -1) {
			
				//make array of single element to attach event listener to
				var theEl = [];
				theEl.push(document.getElementById(el));
			} else {
				
				//get elements to attach event to
				var theEl = _getElementsByClass(el.substr(1));
			}
			
			if (theEl.length == 0) {
			
			  //if array empty do nothing
			  return false
			
			} else { 
			  for (var x = 0; x < theEl.length; x++) {
					
					//attach event listener to elements and pass args
					(_browser.ie == true) ? theEl[x].attachEvent("on" + evt, function(e) { handler(e, args) }) : theEl[x].addEventListener(evt, function(e) { handler(e, args) }, false);
				}
			}	
		
		} else if (typeof(el) == "object") {
			
			//attach event to each element in array
			for (var x = 0; x < el.length; x++) {
				
				//determine whether class name or id
				if (el[x].indexOf(".") == -1) {
				
			  	var theEl = document.getElementById(el[x]);
					(_browser.ie == true) ? theEl.attachEvent("on" + evt, handler) : theEl.addEventListener(evt, handler, false); 				
				} else {
					
					var theEl = _getElementsByClass(el[x].substr(1));
					for (var y = 0; y < theEl.length; y++) {
						(_browser.ie == true) ? theEl[y].attachEvent("on" + evt, handler) : theEl[y].addEventListener(evt, handler, false); 
					};
				}
			}
		}
	};
	
	//stop events cross-browser
	function _stopIt(e) {
		
		//stop the event
		(_browser.ie == true) ? stopIEevent() : stopFFevent() ;
		
		function stopIEevent() {
			window.event.returnValue = false;
			window.event.cancelBubble = true;
		}
		
		function stopFFevent() {
			
			e.preventDefault();
			e.stopPropagation();
			return false;
		}	
	};
	
	//slide things
	var _jSlide = function(e, args) {
				
		//get the id of the el to slide using handlerArgs obj
		var slideEl = (args.id != null) ? document.getElementById(args.id) : null ;
		
		//get trigger el
		var trigger = (args.linkID == null) ? (_browser.ie == true) ? e.srcElement.tagName.toLowerCase() : e.target.tagName.toLowerCase() : document.getElementById(args.linkID) ;
		
		if (trigger != "input") {
			
			//slide toggle the el
			$(slideEl).slideToggle("slow", function() {
							
				//change open link to close link
				($(trigger).children("strong").text().indexOf("Expand") != -1) ? $(trigger).children("strong").text("Collapse Basket") : $(trigger).children("strong").text("Expand Basket") ;
				
				//change class names on link
				($(trigger).hasClass("expand") == true) ? $(trigger).addClass("collapse").removeClass("expand") : $(trigger).addClass("expand").removeClass("collapse");
				
				//add selected class to link if you want to
				//trigger = (_browser.ie == true) ? e.srcElement : e.target;
//				
//				if ($(trigger).hasClass("selected") && args.applySelectedClass == true ) {
//					$(trigger).removeClass("selected").parent().removeClass("buttonSelected");
//				} else {
//					(args.applySelectedClass == true) ? $(trigger).addClass("selected").parent().addClass("buttonSelected") : null ;
//				}
			});
		} else {
		
			//remove boldness from all labels
			$(trigger).parent().children().css({ color:"#C1C8CF" });
			
			//get actual clicked radio
			trigger = (_browser.ie == true) ? e.srcElement : e.target ;
			
			//add boldness to label of radio that was clicked
			$(trigger).parent().next().css({ color:"#2B2E38" });
			
			if ($(trigger).hasClass("same")) {
				//if 'same' radio is selected and address already closed do nothing else shut address
				($(slideEl).hasClass("closed")) ? null : $(slideEl).slideUp("slow").removeClass("open").addClass("closed") ;
			} else {
				//if 'diff' radio is selected and address already open do nothing, else open address
				($(slideEl).hasClass("open")) ? null : $(slideEl).slideDown("slow").removeClass("closed").addClass("open") ;
			}
		}	
		
		_stopIt(e);
	};
	
	//function to handle chaning credit card logo in checkout
	var _changeCard = function(e, args) {
				
		//get the id of the select box el from config obj
		var selectEl = (args.id != null) ? document.getElementById(args.id) : null ;
		
		//get the id of the span to hold the card image
		var imgEl = (args.imgId != null) ? document.getElementById(args.imgId) : null ;
		
		//get the selected card (jumping through hoops for IE)
		var cardIndex = selectEl.selectedIndex;
		var cardChoice = selectEl[cardIndex].text.toLowerCase();
		
		//remove image if first option selected
		(cardIndex == 0) ? imgEl.style.background = "none" : null ;
		
		//get path to image
		var imgPath = _cardImgs[cardChoice];
				
		//set bg image of span
		imgEl.style.background = imgPath;
		
	};
	
	//open popup method
	var _openPopup = function(e, args) {
				
		//remove target (target set in mark-up to make popups usable if JS switched off)
		(_browser.ie == true) ? e.srcElement.setAttribute("target", "") : e.target.setAttribute("target", "") ;
	  
		var theLink = "";
		
		//is popup link wrapped round an image?
		if (_browser.ie == true) {
			theLink = (e.srcElement.tagName.toLowerCase() == "img" || e.srcElement.tagName.toLowerCase() == "strong") ? e.srcElement.parentNode : e.srcElement ;
		} else {
			theLink = (e.target.tagName.toLowerCase() == "img" || e.target.tagName.toLowerCase() == "strong") ? e.target.parentNode : e.target;
		}
		
		//get popup URL
		var href = theLink.href;
		
		//get popup filename
		if (!args || args.popupName == "undefined" || args.popupName == null) {
			
			//work through string and count / characters
			var slashCount = 0;
			if (href.indexOf("/") != -1) {
				for (var x = 0; x < href.length; x++) {
					(href.charAt(x) == "/") ? slashCount++ : null ;
				}
			}
			
			var popName = href.split("/", slashCount + 1);
			var thePopup = popName[popName.length -1].split(".")[0];
					
		} else {
				
			var thePopup = args.popupName;
			
		}
		
		//get dimensions from popSizes object
		width = _popSizes[thePopup].split(":")[0];
		height = _popSizes[thePopup].split(":")[1];
		
		//open the popup
		window.open(href, null, 'scrollbars=yes,status=no,width='+width+',height='+height);
		
		//stop the event
		_stopIt(e);
		
	};
	
	//close popup
	var _closePopup = function(e) {
		window.close();
	};
	
	var _setFaqHeadingOn = function(e) {

		//get the faq that was clicked
		if (_browser.ie == true) {
			var faqNumber = e.srcElement.href.split("#")[1];
		} else {
			var faqNumber = e.target.href.split("#")[1];
		}
		
		//add on class to faq answer
		$("#" + faqNumber).addClass("faqHeaderOn");
		
	};
	
	var _setFaqHeadingOff = function(e) {
		
		//remove faq on class
		$(".faqHeaderOn").removeClass("faqHeaderOn");
		
	};
	
	var _printPage = function(e) {
		window.print();
	};
	
	//remove default word in inputs
	var _inputClear = function(e, args) {
		
		//get the input
		var theInput = (_browser.ie == true) ? e.srcElement : e.target;
		
		//remove default word
		(theInput.value == args.displayWord) ? theInput.value = "" : null ;
	};
	
	var _inputFill = function(e, args) {
		
		//get the input
		var theInput = (_browser.ie == true) ? e.srcElement : e.target;
		
		//add the default word back on blur
		(theInput.value == "") ? theInput.value = args.displayWord : null ;
		
	};
	
	//fix open/closed address boxes on post-back pages
	var _closeAddress = function() {
		$(".genericAddress").slideUp(700);
		$(".slideParentSame").children("div").addClass("existingOn").removeClass("existingOff");
		$(".slideParentDiff").children("div").addClass("existingOff").removeClass("existingOn");
	};
	
	var _openAddress = function() {
		$(".genericAddress").slideDown(700);
		$(".slideParentSame").children("div").addClass("existingOff").removeClass("existingOn");
		$(".slideParentDiff").children("div").addClass("existingOn").removeClass("existingOff");
	};
	
	//change product image when thumbnail rolled over
	var _imageOver = function(e) { 
		var hook = (_browser.ie == true) ? e.srcElement : e.target;
		if (hook.className == "nail n1") { $(".t1").css("zIndex","3"); $(".main .openImgPopup img").css("zIndex", "-1") } ; 
		if (hook.className == "nail n2") { $(".t2").css("zIndex","3"); $(".main .openImgPopup img").css("zIndex", "-1") } ;
		if (hook.className == "nail n3") { $(".t3").css("zIndex","3"); $(".main .openImgPopup img").css("zIndex", "-1") } ;
	};
	
	//change it back
	var _imageOut = function(e) {
		var hook = (_browser.ie == true) ? e.srcElement : e.target;
		if (hook.className == "nail n1") { $(".t1").css("zIndex","1"); $(".main .openImgPopup img").css("zIndex", "2") } ;
		if (hook.className == "nail n2") { $(".t2").css("zIndex","1"); $(".main .openImgPopup img").css("zIndex", "2") } ;
		if (hook.className == "nail n3") { $(".t3").css("zIndex","1"); $(".main .openImgPopup img").css("zIndex", "2") } ;
	};

  //emulate hover on li in IE6 with class
	var _on = function(which) { 
		$(which).addClass("ieHover");
	}
	
	//remove class
  var _off = function(which) { 
		$(which).removeClass("ieHover");
	}
	
		//return public methods
	return {
		xAttachEvent: _xAttachEvent,
		changeCard: _changeCard,
		openPopup: _openPopup,
		closePopup: _closePopup,
		jSlide: _jSlide,
		setFaqHeadingOn: _setFaqHeadingOn,
		setFaqHeadingOff: _setFaqHeadingOff,
		inputClear: _inputClear,
		inputFill: _inputFill,
		printPage: _printPage,
		closeAddress: _closeAddress,
		openAddress: _openAddress,
		imageOver: _imageOver,
		imageOut: _imageOut,
		on: _on,
		off: _off
	}
})();
