/* 

MAD.js is an in-hosue e-commerce javascript library written by Dan Wellman 
copyright 2009 MAD Productions

version 1.2

*/
var MAD = {};
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 = {
		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");
				
			});
			
			_stopIt(e);
		} else {
		  
			//get actual clicked radio and its outer container
			trigger = (_browser.ie == true) ? e.srcElement : e.target,
			  clickedDiv = $(trigger).parent().parent(),
				fieldset = clickedDiv.parent().parent();
							
			//remove boldness and 'on' class from all labels
			fieldset.find("label").each(function() {
			  $(this).css("color", "#C1C8CF").parent().removeClass("existingOn").addClass("existingOff");
		  });
			
			//add boldness and 'on' class to label of radio that was clicked
			clickedDiv.addClass("existingOn").find("label").css("color", "#2B2E38");
																								 
			if (clickedDiv.attr("id") == "BillNew") {				
				
				//if 'diff' radio is selected show address
				($(slideEl).hasClass("open")) ? null : $(slideEl).slideDown("slow").addClass("open") ;
				
				
			} else {
				
				//if 'same' radio cliked hide address
				($(slideEl).hasClass("open")) ? $(slideEl).slideUp("slow").removeClass("open") : null;
								
			}
		}	
	};
	
	//function to handle changing 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;
		
	};
	
	
//	var _cardPayment = function(e) {
//		//$('.ccDetails').hide();
//		$('.paymentType1 .ccRight input').click(function() {
//			$('.ccDetails').slideDown('slow');
//		});
//		$('.paymentType2 .ccRight input').click(function() {
//			$('.ccDetails').slideUp('slow');
//		});				
//	};
	
	
	//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
	}
})();

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 posTop = ($(window).height() - $(id).height()) / 2 + $(window).scrollTop();
		if (posTop < 0) { posTop = 0; }
		$(id).css("top", posTop + "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.treepodia = (function() {
    var _acc;
    var _accID;
    var _skus = [];
    var _vids;
    var _product;

    var _init = function(account) {
        _accID = account;
        _getAccount();
    }

    var _getAccount = function() {
        if (_acc === undefined) {
            _acc = Treepodia.getAccount(_accID);
        }
    }

    var _showLB = function(Video, title, prodURL) {
        MAD.lightBox.show(".lbTreepodia");
        //$("#swfDiv").html('<embed height="351px" width="554px" flashvars="callback=_trpd_video_callback_0&amp;video=http://videos.treepodia.com/UA-OLG/' + Video + '-OnlineGolf1-olg1.d.flv&amp;auto-play=false&amp;backcolor=0xffffff&amp;frontcolor=0xCCCCCC&amp;lightcolor=0x557722&amp;allowfullscreen=false&amp;ShowLogo=1&amp;play_on_click=true&amp;init_mute=false" wmode="transparent" allowfullscreen="false" swliveconnect="true" allowscriptaccess="always" quality="high" bgcolor="ffffff" name="swfID_0" id="swfID_0" src="http://www.treepodia.com/video/treepodia_player.swf" type="application/x-shockwave-flash">');

        _getProductVideo(Video, function(videoController) {
            videoController.setAutoplay(true);
            videoController.setWidth(554);
            videoController.setHeight(351);
            videoController.setWmode('transparent');
            videoController.show('swfDiv');
        });

        $('.lbTreepodia').find('h3').html(title);

        if (prodURL.length > 0) {
            $('.lbTreepodia').find('a.btn_viewProductLarge').css("display", "block");
            $('.lbTreepodia').find('a.btn_viewProductLarge').attr('href', prodURL);
        }
        else {
            $('.lbTreepodia').find('a.btn_viewProductLarge').css("display", "none");
            $('.lbTreepodia').find('a.btn_viewProductLarge').attr('href', '');
        }

        $(".lbTreepodia a.btn_close").click(function() { MAD.treepodia.stopVideo(Video); });

        $(".overlay").click(function() {
            if (!$(".modal").is(":visible")) {
                $(".lightbox").hide();
                $(".expandedContent").hide();
                $(this).hide();
            }
            MAD.treepodia.stopVideo(Video);

            $(".overlay").click(function() {
                if (!$(".modal").is(":visible")) {
                    $(".lightbox").hide();
                    $(".expandedContent").hide();
                    $(this).hide();
                }
            });
        });
    }

    var _stopVideo = function(Video) {
        //_showLB(Video, title, '');
        _getProductVideo(Video, function(vc) {
            vc.setAutoplay(false);
            vc.setWidth(554);
            vc.setHeight(351);
            vc.setWmode('transparent');
            vc.show('swfDiv');
        });
    }

    var _playVideo = function(Video, title) {
        _showLB(Video, title, '');
    }

    var _getProduct = function(sku) {
        _product = Treepodia.getProduct(_accID, sku);
    }

    var _getProductVideo = function(sku, handler) {
        _getProduct(sku);
        _product.requestVideo(handler);
    }

    var _logAddBasket = function(sku) {
        //_product = Treepodia.getProduct(account, sku);
        if (_product === undefined) {
            _getProduct(sku);
        }
        _product.logAddToCart();
    }

    //return public methods
    return {
        init: _init,
        //        reinit: _reinit,
        //        reinitCustom: _reinitCustom,
        //        handleVideo: _handleVideo,
        //        showVideos: _showVideos,
        playVideo: _playVideo,
        //        hasVideo: _hasVideo,
        showLB: _showLB,
        stopVideo: _stopVideo,
        //        addSku: _addSku,
        //        skus: _skus,
        logAddBasket: _logAddBasket,
        getProductVideo: _getProductVideo
    }
})();
