
function getcookie(name) {
  var start = document.cookie.indexOf(name+"=");
  var len = start+name.length+1;
  if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
  if (start == -1) return null;
  var end = document.cookie.indexOf(";",len);
  if (end == -1) end = document.cookie.length;
  return unescape(document.cookie.substring(len,end).replace('+',' '));
}

function setcookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function in_array (element, array) {
	for (var i = 0; i < array.length; i++) {
		if (array[i] == element) {
			return true;
		}
	}
	return false;
}


function checklogin(){
  var username = getcookie('csbname');
  if(username != null && getcookie('csbsesh') != null){
    document.getElementById('fxhomeusername').appendChild(document.createTextNode(username));
  
    if(username.match(/^FXhomer[0-9]+$/)){
  		otherOptions = '&nbsp;| <a href="http://fxhome.com/account/username">Change Name</a>';
  	    document.getElementById('loggedInOptions').innerHTML = otherOptions;
  	}
    
    document.getElementById('loggedOut').style.display = 'none';
    document.getElementById('loggedIn').style.display = 'inline';
  }else{
    document.getElementById('loggedOut').style.display = 'inline';
    document.getElementById('loggedIn').style.display = 'none';
  }
}


function buttonClick(num){

	try{

	if('function' == (typeof replacedButtons[num].onclick)){
		replacedButtons[num].onclick();
	}

	// see if this is button submits a form
	if(replacedButtons[num].type == 'submit'){
		var parent = replacedButtons[num].parentNode;

		// find form
		while(parent != null){
			if(parent.nodeName == 'FORM'){
				
				//sometimes the form button has data that we need to pass
				if(replacedButtons[num].name){
					var hiddenData = document.createElement('input');
					hiddenData.type = 'hidden';
					hiddenData.name = replacedButtons[num].name;
					hiddenData.value = replacedButtons[num].value;
					parent.appendChild(hiddenData);
				}
			
				if(parent.onsubmit){
					if(!parent.onsubmit()){
						return;
					}
				}
				
				parent.submit();
				return;
			}
			parent = parent.parentNode;
		}
	}
	
	}catch(err){
		window.location.href = '/log-error?type=javascript&msg=' + escape('buttonClick('+num+') '+err.message + ' ['+window.location.href+']');
		return; 
	}
}

var replacedButtons = new Array();

function swappy() {

	if((window.altPrices !== undefined) && (window.userCurrencyCode !== undefined) && (window.userCurrencyCode != 'USD')){


		var spanTags = document.getElementsByTagName('span');
		var parts;
		var numChanged = 0;
		
		for (var i = (spanTags.length - 1); i >= 0; i--){
			
			parts = /^([a-z]+)price$/.exec(spanTags[i].className);

			if(parts){

				for(var j = 0; j < altPrices.length; j++){
					if(altPrices[j].id == ''+parts[1]+window.userCurrencyCode){
						while(spanTags[i].childNodes.length > 0) {
							spanTags[i].removeChild(spanTags[i].childNodes[0]);
						}
					    spanTags[i].appendChild(document.createTextNode(altPrices[j].price.replace('&pound;','�')));
						numChanged++;
						break;
					}
				}

				
			}

		}

	}


	if (navigator.appVersion.indexOf("MSIE")!=-1){
		temp=navigator.appVersion.split("MSIE");
		version=parseFloat(temp[1]);
		if(version < 6){
			// versions of IE less than 6.0 cant cope with button swapping
			return;
		}
	}


	var buttonHTML = '<a href="LINK" class="b bn"><span>LABEL</span></a>';
	var buttonHTMLWithClass = '<a href="LINK" class="b CLASS"><span>LABEL</span></a>';
	
	var buttonNum = 0;

	var inputTags = document.getElementsByTagName('input');

	//backwards loop because replaceChild() actually removes elements from the array (even though we dont use it anymore)
	for (var i = (inputTags.length - 1); i >= 0; i--){

		// we dont do submit buttons with name="submit" because they break the submit() function on the form
		if((inputTags[i].type == 'button') || ((inputTags[i].type == 'submit') && (inputTags[i].name != 'submit'))){

			var newButton = document.createElement('span');
			
			if(inputTags[i].className.length > 0){
				newButton.innerHTML = buttonHTMLWithClass.replace('LABEL',inputTags[i].value).replace('LINK','javascript:buttonClick('+buttonNum+');').replace('CLASS',inputTags[i].className);
			}else{
				newButton.innerHTML = buttonHTML.replace('LABEL',inputTags[i].value).replace('LINK','javascript:buttonClick('+buttonNum+');');
			}

			replacedButtons[buttonNum] = inputTags[i];
			buttonNum++;

			inputTags[i].style.display = 'none';

			inputTags[i].parentNode.insertBefore(newButton,inputTags[i]);
		}
		

	}


}

var FXModals = {
	PREFS_COOKIE_NAME: 'csb_modals_shown',
	
	modalsToHide: [],

	modals: [],

	init: function(event) {
		if (window.modals && window.modals.length > 0) {
			FXModals.modals = window.modals;
		}
		FXModals.loadHiddenModals();
		FXModals.showNextModal();
	},

	showNextModal: function() {
		for (var i = 0; i < FXModals.modals.length; i++) {
			if (in_array(FXModals.modals[i].id, FXModals.modalsToHide)) {
				continue;
			}


			var modalHTML = '<div id="'+FXModals.modals[i].id+'" class="modal">';
			modalHTML += '<div class="headerStart"><div class="headerEnd"></div></div>';
			modalHTML += '<div class="pTitleStart"><div class="pTitleEnd"><div class="padTnRmBnLs">';
			modalHTML += '<p class="alignCenter">'+FXModals.modals[i].message+'</p>';
			modalHTML += '<p class="alignCenter">';
			modalHTML += '<a class="b bTopic" href="javascript:FXModals.modalAccepted('+FXModals.modals[i].id+');"><span>Yes</span></a> ';
			modalHTML += '<a class="b bTopic" href="javascript:FXModals.modalDenied('+FXModals.modals[i].id+');"><span>No</span></a>';
			modalHTML += '</p></div></div></div>';
			modalHTML += '</div>';

			document.getElementById('modals').innerHTML = modalHTML;
		}
	},

	modalAccepted: function(id) {
		for (var i = 0; i < FXModals.modals.length; i++) {
			var currModal = FXModals.modals[i];
			if (currModal.id == id) {
				FXModals.hideModal(currModal.id);
				window.location = currModal.url;
			}
		}
	},

	modalDenied: function(id) {
		for (var i = 0; i < FXModals.modals.length; i++) {
			var currModal = FXModals.modals[i];
			if (currModal.id == id) {
				FXModals.hideModal(currModal.id);
				FXModals.showNextModal();
			}
		}
	},

	hideModal: function(id) {
		// add to hidden list
		if (!in_array(id, FXModals.modalsToHide)) {
			FXModals.modalsToHide.push(id);
			FXModals.saveHiddenModals();
		}

		// remove from the page
		document.getElementById('modals').innerHTML = '';
	},

	loadHiddenModals: function() {
		if (FXModals.modalsToHide.length < 1) {
			var cookie = getcookie(FXModals.PREFS_COOKIE_NAME);

			if (cookie != null && cookie != '') {
				FXModals.modalsToHide = cookie.split(',');
			}
		}
	},

	saveHiddenModals: function()
	{
		setcookie(FXModals.PREFS_COOKIE_NAME, FXModals.modalsToHide.join(','), 31536000);
	}
}

jQuery(document).ready(function() {
	// hides the overlay when the darkened bg is clicked
	jQuery('.overlay .bg').click(function() {
		jQuery(this).parent().hide();
		return false;
	});

	// hides the overlay when the close button is clicked
	jQuery('.overlay .close').click(function() {
		jQuery(this).parent().parent().hide();
		return false;
	});

	// displays the overlay when an activating button is clicked
	jQuery('a.overlayActivator[rel]').click(function() {
		jQuery(jQuery(this).attr('rel')).show();
		return false;
	});

	// when the page loads if the overlay is specified in the url show it
	if (window.location.search) {
		var qs = window.location.search.substring(1);
		var qsitems = qs.split("&");
		for (i=0; i<qsitems.length; i++) {
			var item = qsitems[i].split('=');
			if (item[0] == 'showoverlay') {
				jQuery('#'+item[1]).show();
			}
		}
	}


});
		
// init anything we need once the content is loaded
window.onload = function initialize()
{
	FXModals.init();
	swappy();
}


// animations for the new product page tabs
jQuery(document).ready(function() {
	jQuery('.product-nav li, .product-sidebar-btn, #tell-friend-btn, #tell-santa-btn').not('.selected').hover(
		function productTabOver() {
			jQuery(this).stop().animate({textIndent:5}, 100, 'linear');
		},
		function productTabOut() {
			jQuery(this).stop().animate({textIndent:0}, 100, 'linear');
		}
	);
});



// custom jQuery plugin for the rotators
// example usage:  jQuery('#ads').fxRotator({elementSelector:'.ad', speed:100, duration:3000});
(function($) {
	// custom jquery plugin for the rotator
	$.fn.fxRotator = function(options) {
		// take the user passed options and override the defaults
		var opts = $.extend({}, $.fn.fxRotator.defaults, options);

		// process all the containers and return them keeping the jquery fluent interface
		return $(this).each(function() {

			var container = $(this);
			var items = $(opts.elementsSelector, container);
			var itemCount = items.length;
			var currItem = 0;

			// initially show just the first item
			items.hide().eq(currItem).show();

			// change the positioning of all of them to absolute so they sit in the same place and can be faded between
			container.css('position', 'relative');
			items.css('position', 'absolute');

			// if there is only one item just discard any further actions.
			if (itemCount < 2) {
				return;
			}

			// start the timer which periodically changes the items
			window.setInterval(function rotateItem() {
				// calculate the next item
				if (currItem >= (itemCount-1)) {
					currItem = 0;
				}
				else {
					currItem++;
				}

				// hide the currently shown item
				items.filter(':visible').fadeOut(opts.speed);
				
				// show the next item
				items.eq(currItem).fadeIn(opts.speed);
				
				// animate the height to the next one
				container.animate({
					'height': items.eq(currItem).height() + 'px'
				}, 250);
			}, opts.duration);

		});
	}

	// setup default options for rotators
	$.fn.fxRotator.defaults = {
		speed: 500, // half sec
		duration: 5000, // 5 secs
		elementsSelector: '.ad-rotator-item'
	}
})(jQuery);

// setup any rotators
jQuery(document).ready(function setupRotators() {
	jQuery('.ad-rotator-container').fxRotator({
		speed: 500,
		duration: 5000,
		elementsSelector: '.ad-rotator-item'
	});
});


/*
 * Turns links with the mediaPopup class into a overlay where the contents are
 * either a flash video player or image based on what the href of the link is.
 */
(function($) {

	$(document).ready(function() {
		var mediaLinks = $('a.mediaPopup');
		
		if (mediaLinks.length > 0) {
			$('<div class="overlay" id="mediaPopup" style="display:none;"><div class="box"><a class="close" href="?"><img height="30" width="30" title="close" alt="close" src="http://static.fxhome.com/images/white/overlay/close.png"/></a><div class="content"></div></div><div class="bg"></div></div>').appendTo('body');

			var $overlay = $('#mediaPopup');
			var $overlayContent = $overlay.find('div.content');
			var $overlayBox = $overlay.find('div.box');

			$overlay.find('.close, div.bg').click(function() {
				$overlayContent.empty();
				$overlay.hide();

				return false;
			});

			mediaLinks.click(function() {
				$link = $(this);
				var href = $link.attr('href');

				if (href.match(/\.(flv|f4v)$/i)) {
					// its a video
					$overlayContent.html('<div id="popupVideoPlayer" style="padding-bottom:20px;"><div class="padTsRmBnLm"><p class="alignCenter medium"><span class="alert">Adobe</span> Flash is required to play this embedded movie. <a href="http://www.macromedia.com/go/getflashplayer" class="minib">Get Flash now!</a></p></div></div>');
					$overlay.show();

					// now use swfobject to replace the video
					var swfobj = new SWFObject("/media-player.swf","player","600","360","9");
					swfobj.addParam("allowfullscreen","true");
					swfobj.addParam("wmode","opaque");
					swfobj.addVariable("autostart","true");
					swfobj.addVariable("file",href);
					swfobj.addVariable("displayheight","340");
					swfobj.addVariable("backcolor","0x212121");
					swfobj.addVariable("lightcolor","0x4b7dff");
					swfobj.addVariable("frontcolor","0xCCCCCC");
					swfobj.addVariable("bufferlength","5");
					swfobj.write("popupVideoPlayer");

					// resize the window appropriately
					$overlayBox.css({
						height: '360px',
						width: '600px',
						marginLeft: '-301px'
					});
					$overlayContent.css({
						height: 'auto',
						width: '600px',
						maxHeight: '400px'
					});
				}
				else if(href.match(/\.(gif|jpg|png)$/i)) {
					$overlayContent.html('<div class="padTsRmBsLm"><p class="alignCenter"><br/><img src="http://static.fxhome.com/images/ajax-loader.gif" width="16" height="16" alt="loading image" /></p></div>');
					
					var img = new Image();
					img.onload = function() {
						// its an image
						$overlayContent.html('<img src="'+href+'" alt="'+$link.text()+'" />');
						$overlayBox.css({
							height: img.height+'px',
							width: img.width+'px',
							marginLeft: '-'+((img.width / 2)+1)+'px'
						});
						$overlayContent.css({
							height: img.height+'px',
							width: img.width+'px',
							maxHeight: 'none'
						});
					}
					img.onerror = function () {
						$overlayContent.html('<div class="padTsRmBsLm"><p class="alignCenter hilight">Sorry... we could not find a bigger version of the image you clicked on.</p></div>');
						$overlayBox.css({
							height: 'auto',
							width: '600px',
							marginLeft: '-301px'
						});
						$overlayContent.css({
							height: 'auto',
							width: '600px',
							maxHeight: 'none'
						});
					}
					img.src = href;

					$overlay.show();
				}

				return false;
			});
		}
	});

})(jQuery);


