var dom = document.getElementById ?	true:false;
var ie  = document.all ? true:false;
var safari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
var opera = (navigator.userAgent.toLowerCase().indexOf('opera')!=-1);
var classSpecifier = (ie && !opera) ? 'className' : 'class';
if(ie)
	classSpecifier = (navigator.appVersion.indexOf("MSIE 8")>=0) ? "class" : classSpecifier;
var currentCharCount = 0;
var MaxCharCount = 0;
var prevText;
var cardPreviewText = 'Click on the above image to return to the gallery of card designs';


<!--
// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var reqMajorVer = 8;
// Minor version of Flash required
var reqMinorVer = 0;
// Minor version of Flash required
var reqRevision = 0;
// -----------------------------------------------------------------------------
// -->

// apply image rollovers/rolloffs to links within specified element
// #[container] UL LI A IMG
function initialiseIDRollovers(container){
	if(container){
		var aDivs = container.getElementsByTagName("a");
		for (i=0; i<aDivs.length;i++){
		    if(ie){
			    aDivs[i].onmouseover = imgIDRollOn;
			    aDivs[i].onmouseout = imgIDRollOut;
		    }
		    else
		    {
                aDivs[i].addEventListener('mouseover',imgIDRollOn,false);
                aDivs[i].addEventListener('mouseout',imgIDRollOut,false);
		    }
		}
	}
}

function imgIDRollOn(e){
	imgIDRollover(e,1);
}

function imgIDRollOut(e){
	imgIDRollover(e,0);
}

function imgIDRollover(e,state){
	var nodeObject = eventTrigger(e);
	var suffix = (state) ? '_on' : '_off';
	var currentNode = nodeObject;
	var currentTag = currentNode.tagName;
	while(currentTag != 'LI'){
		currentNode = currentNode.parentNode;
		currentTag = currentNode.tagName;
	}
	var currentID = currentNode.getAttribute('id');
	var imgCollection = currentNode.getElementsByTagName('img');
	var currentClass = (imgCollection[0].getAttribute(classSpecifier)) ? imgCollection[0].getAttribute(classSpecifier) : '';
	if(currentClass != 'on'){
		imgCollection[0].src = '../img/btn/' + currentID + suffix + '.gif';
	}
}

// apply image rollovers/rolloffs to links of a specified CSS class within specified container element
// #[container] * INPUT.button
// <INPUT type="image" class="button [imagename]" />
function initialiseInputRollovers(container){
	var classRegEx = new RegExp(/button/);
	if(container){
		var aDivs = container.getElementsByTagName('input');
		for (i=0; i<aDivs.length;i++){
			var nodeClass = (aDivs[i].getAttribute(classSpecifier)) ? aDivs[i].getAttribute(classSpecifier) : '';
			if(nodeClass.match(classRegEx)){
				aDivs[i].onmouseover = imgInputRollOn;
				aDivs[i].onmouseout = imgInputRollOut;
			}
		}
	}
}

// apply image rollovers/rolloffs to links of a specified CSS class within specified container element
// #[container] * A.button
// <A class="button [imagename]" ><img /></a>
function initialiseALinkRollovers(container){
	var classRegEx = new RegExp(/button/);
	if(container){
		var aDivs = container.getElementsByTagName('a');
		for (i=0; i<aDivs.length;i++){
			var linkImages = aDivs[i].getElementsByTagName('img');
			if(linkImages.length != 0){
				var imgNode = linkImages[0];
				var nodeClass = (imgNode.getAttribute(classSpecifier)) ? imgNode.getAttribute(classSpecifier) : '';
				if(nodeClass.match(classRegEx)){
					aDivs[i].onmouseover = imgInputRollOn;
					aDivs[i].onmouseout = imgInputRollOut;
				}
			}
		}
	}
}

function imgInputRollOn(e){
	imgInputRollover(e,1);
}

function imgInputRollOut(e){
	imgInputRollover(e,0);
}

function imgInputRollover(e,state){
	var nodeObject = eventTrigger(e);
	var suffix = (state) ? '_on' : '_off';
	
	var nodeClasses = nodeObject.getAttribute(classSpecifier);
	var classCollection = nodeClasses.split(' ');
	for(var n = 0;n < classCollection.length;n++){
		if(classCollection[n] != 'button'){
			nodeObject.src = '../img/btn/' + classCollection[n] + suffix + '.gif';
		}
	}
}

function initialiseIntroRollovers(container){
	if(container){
		var aDivs = container.getElementsByTagName("a");
		for (i=0; i<aDivs.length;i++){
			aDivs[i].onmouseover = imgIntroRollOn;
			aDivs[i].onmouseout = imgIntroRollOut;
		}
	}
}

function imgIntroRollOn(e){
	imgIntroRollover(e,1);
}

function imgIntroRollOut(e){
	imgIntroRollover(e,0);
}

function imgIntroRollover(e,state){
	var nodeObject = eventTrigger(e);
	var suffix = (state) ? 'on' : 'off';
	nodeObject.setAttribute(classSpecifier,suffix);
}

// card previews
// #cardGallery img.cardThumbnail
function initialiseCardPreview(){
	var container = document.getElementById('cardGallery');
	if(container){
		var classRegEx = new RegExp(/cardThumbnail/);
		var aDivs = container.getElementsByTagName('img');
		for (i=0; i<aDivs.length;i++){
			var nodeClass = (aDivs[i].getAttribute(classSpecifier)) ? aDivs[i].getAttribute(classSpecifier) : '';
			if(nodeClass.match(classRegEx)){
				aDivs[i].onclick = showCardPreview;
			}
		}
	}
}

function showCardPreview(e){
	if(!document.getElementById('cardPreview')){
		var nodeObject = eventTrigger(e);
		var nodeClasses = nodeObject.getAttribute(classSpecifier);
		var previewRegEx = new RegExp(/design(\d{1,2})/);
		var matchCollection = previewRegEx.exec(nodeClasses);
		var previewID = parseInt(matchCollection[1],10);
		var altTag = nodeObject.getAttribute('alt');
		
		var thumbnailContainer = document.getElementById('cardGallery');
		thumbnailContainer.style.display = 'none';
		var masterContainer = thumbnailContainer.parentNode;
		
		var previewNode = document.createElement('div');
		previewNode = masterContainer.appendChild(previewNode);
		previewNode.setAttribute('id', 'cardPreview');	
	
		var previewLinkNode = document.createElement('a');
		previewLinkNode = previewNode.appendChild(previewLinkNode);
		previewLinkNode.setAttribute('href', '#');	
		previewLinkNode.onclick = hideCardPreview;
		
		var previewImgNode = document.createElement('img');
		previewImgNode = previewLinkNode.appendChild(previewImgNode);
		previewImgNode.setAttribute('src', imagesFull[previewID]);	
		previewImgNode.setAttribute('width', '362');	
		previewImgNode.setAttribute('height', '362');	
		previewImgNode.setAttribute('alt',altTag);	
	
    	AddElement(previewNode,'p',cardPreviewText,classSpecifier + ':cardPreviewInfo')
    	/*
    	var infoNode = document.createElement('p');
		infoNode = previewNode.appendChild(infoNode);
	    text_node = document.createTextNode(cardPreviewText);
		infoNode.appendChild(text_node);
		*/
    	
		previewNode.style.display = 'block';
	}
	return false;
}

function hideCardPreview(e){
	var previewContainer = document.getElementById('cardPreview');
	previewContainer.style.display = 'none';
	var masterContainer = previewContainer.parentNode;
	var throwawayNode = masterContainer.removeChild(previewContainer);
	
	var thumbnailContainer = document.getElementById('cardGallery');
	thumbnailContainer.style.display = 'block';
	return false;
}

/* used for textarea in shopping basket - add card page */ 
function initialiseCharCount(MaxNumberOfCharacters){
	if(document.getElementById('addCard')){

	    var charLimitNode = document.getElementById('charLimit');
	    charLimitNode.style.display = 'none';
	    var charCountNode = document.getElementById('charCount');
	    charCountNode.style.display = 'block';

		MaxCharCount = MaxNumberOfCharacters;
		var textareaNode = getTextArea('addCard','wordCount');
		currentCharCount = textareaNode.value.length;
		remainingCharacters = MaxCharCount - currentCharCount;
		displayCharCount(remainingCharacters);
		textareaNode.onkeyup = updateCharCount;
		// updateCharCount();
		// StripLinebreaks();
	}
}

function updateCharCount(){
	var textareaNode = getTextArea('addCard','wordCount');
	//StripLinebreaks(textareaNode);
	currentCharCount = textareaNode.value.length;	
	remainingCharacters = MaxCharCount - currentCharCount;
	if(remainingCharacters >= 0){
		prevText = textareaNode.value;
		displayCharCount(remainingCharacters);
	}else{
		textareaNode.value = prevText;
		$("#charCount").hide();
		$("#charCount").fadeIn("slow");
	}
}

// only works in firefox
// IE 6 and 7 fail ro replace linebreaks and inserting value back into textarea forces cursor to end of entered text
function StripLinebreaks(textareaNode){
    var linebreakRegEx = new RegExp(/\n[\r]*/);
	// var textareaNode = getTextArea('addCard','wordCount');
	var textAreaValue = textareaNode.value;
	if(textAreaValue.match(linebreakRegEx)){
	    textareaNode.value = textAreaValue.replace(linebreakRegEx, '');
	}
}

function displayCharCount(numberOfCharacters){
	var charCountPara = document.getElementById('charCount');
	var spanCollection = charCountPara.getElementsByTagName('span');
	spanCollection[0].innerHTML = numberOfCharacters;
}

function getTextArea(teID,teClass){
	var addCardForm = document.getElementById(teID);
	var textareaCollection = addCardForm.getElementsByTagName('textarea');
	var index = 0;
	var textareaNode = textareaCollection[index];
	var textareaClass = textareaNode.getAttribute(classSpecifier);
	while(textareaClass != teClass){
		textareaNode = textareaCollection[index];
		textareaClass = textareaNode.getAttribute(classSpecifier);
		index++;
	}
	return textareaNode;
}

function introFlashDetection(flashVersion){
    if(document.getElementById('siteSelect'))
    {
//        if( tz_isFlash(flashVersion)){
//            document.getElementById('showFlash').style.display = 'block';        
//        }
//        else
//        {
//            document.getElementById('flashDownloadLink').style.display = 'block';        
//        }
        
        if(DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision))
        {
            document.getElementById('showFlash').style.display = 'block';        
        }
        else
        {
            document.getElementById('flashDownloadLink').style.display = 'block';        
        }
    }
}

function eventTrigger(e) {
    if (!e)
	{
        e = event;
	}
    return e.target || e.srcElement;
}

function giftsPopupImage(url) {
    /*
    need to add code to position popup over centre of browser window, requires
    browserLeft,browserTop = browser window top left coords
    browserWidth,browserHeight = dimensions of browser window
    popupWidth,popupHeight = dimensions of popup window

    algorithm:
     popupLeft = browserLeft + ((browserWidth - popupWidth) / 2)
     popupTop = browserTop + ((browserHeight - popupHeight) / 2)
    */
    
    // returns dimensions of screen *in which browser window resides on page load* for firefox
    // returns primary screen dimensions in IE6,7
    // does *not* return total dimensions of multi-monitor setups
    var screenWidth = window.screen.width;
    var screenHeight = window.screen.height;

    // only works in firefox (gecko HTML engine)  / safari browsers
    var browserWidth = window.innerWidth;
    var browserHeight = window.innerHeight;

    // returns 0 for both values
    var browserLeft = window.screen.left;
    var browserTop = window.screen.top;

    /*
    apparently it is not possible to find the top left screen co-ordinates of the browser window
    so the popup could be displayed in the centre of the current screen, but not over the centre of the browser window
    */ 
    
    var popupLeft = 100;
    var popupTop = 100;
    
    // gift list pages - 189 x 199 px image
    var popupWidth = 210;
    var popupHeight = 250;
    
    window.open(url,'productPicture','status=no,resizable=no,top='+popupTop+',width='+popupWidth+',height='+popupHeight+',left='+popupLeft+',scrollbars=no');
}

/* Tango Zebra flash version detection */
function tz_isFlash(tz_flashVerRequired){
	var tz_flashVersion = 0;
	if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)){
		function tz_activeXDetect(activeXname){
	    	try
	    	{
				var xObj = new ActiveXObject(activeXname);
      	        	return xObj;
  	    	}catch (e){
    	        return false;
  	    	}
        }
			
		for(i=1;i<10;i++){
	    	if(tz_activeXDetect('ShockwaveFlash.ShockwaveFlash.' + i)){
	        	tz_flashVersion = i;
	    	}
		}
	} else if(navigator.plugins && navigator.mimeTypes && navigator.mimeTypes['application/x-shockwave-flash'] && navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin)	{
		var tz_isVersion2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
		var tz_flashDescription = navigator.plugins["Shockwave Flash" + tz_isVersion2].description;
		tz_flashVersion = parseInt(tz_flashDescription.charAt(tz_flashDescription.indexOf(".") - 1));
    }
    return (tz_flashVersion>=tz_flashVerRequired)? true : false;
}

function deleteItemCheck(){
    return confirm("Are you sure?")
}

function initialiseDeleteConfirmation(container){
	var classRegEx = new RegExp(/deleteButton/);
	if(container){
		var aDivs = container.getElementsByTagName('input');
		for (i=0; i<aDivs.length;i++){
			var nodeClass = (aDivs[i].getAttribute(classSpecifier)) ? aDivs[i].getAttribute(classSpecifier) : '';
			if(nodeClass.match(classRegEx)){
			    /*
			    var nodeOnClick = aDivs[i].getAttribute('onclick');
				aDivs[i].onclick = 'deleteItemCheck()' + nodeOnClick ;
			    */
				aDivs[i].onclick = deleteItemCheck ;
			}
		}
	}
}

function pageLoaded()
{
    introFlashDetection(8);
    initialiseIntroRollovers(document.getElementById('siteSelect'));
	initialiseIDRollovers(document.getElementById('misc'));
	initialiseInputRollovers(document.getElementById('misc'));
	initialiseInputRollovers(document.getElementById('basketButtons'));
	initialiseInputRollovers(document.getElementById('giftList'));
	initialiseInputRollovers(document.getElementById('basketSummary'));
	initialiseInputRollovers(document.getElementById('tellAFriend'));
	// initialiseDeleteConfirmation(document.getElementById('basketSummary'))
	initialiseInputRollovers(document.getElementById('addCard'));
	initialiseInputRollovers(document.getElementById('deliveryAddress'));
	initialiseInputRollovers(document.getElementById('yourDetails'));
	initialiseInputRollovers(document.getElementById('orderConfirmation'));
	initialiseALinkRollovers(document.getElementById('orderConfirmation'));
	initialiseCardPreview();
	initialiseCharCount(380);
}

var eCardSelected;
var paperCardSelected;
var bothSelected;
var recommendsBlock;
var selectDesignEl;
var eCardSelectEl;	

function eCardOnSelect(){
	$(chooseCardMessageOnEl).css("display", "none");
	$(chooseCardMessageOffEl).css("display", "block");
	$(selectDesignEl).css("display", "none");
	$(recommendsBlock).css("display", "none");
	$(eCardSelectEl).css("visibility", "visible");
	$(noSelectDesignEl).css("display", "");
	$(occasionDetailsEl).css("display", "none");
	(eCardSelected).attr("checked", "checked");
}
function paperCardOnSelect(){
	$(chooseCardMessageOnEl).css("display", "block");
	$(chooseCardMessageOffEl).css("display", "none");
	$(eCardSelectEl).css("visibility", "hidden");
	$(selectDesignEl).css("display", "");
	$(recommendsBlock).css("display", "");
	$(noSelectDesignEl).css("display", "none");
	$(occasionDetailsEl).css("display", "block");
	(paperCardSelected).attr("checked", "checked");
}
function bothOnSelect(){
	$(chooseCardMessageOnEl).css("display", "block");
	$(chooseCardMessageOffEl).css("display", "none");
	$(eCardSelectEl).css("visibility", "visible");
	$(selectDesignEl).css("display", "");
	$(recommendsBlock).css("display", "");
	$(noSelectDesignEl).css("display", "none");
	$(occasionDetailsEl).css("display", "block");
	
	(bothSelected).attr("checked", "checked");
}

$(document).ready(function(){ 
	
	pageLoaded();

	//JJ
	eCardSelected = $(".eCardSelected");
	paperCardSelected = $(".paperCardSelected");
	bothSelected = $(".bothSelected");
	recommendsBlock = $("#recommendsBlock");
	
	selectDesignEl = $(".designSelectJs");
	noSelectDesignEl = $("#noDesignSelectJs");
	eCardSelectEl = $("#eCardSelectJs")
	occasionDetailsEl = $("#occasionDetails")
	
	chooseCardMessageOnEl = $("#chooseCardMessageOn");
	chooseCardMessageOffEl = $("#chooseCardMessageOff");
	
	if($(eCardSelected).size()>0 && $(eCardSelected).not(":checked")){
		$(eCardSelected).click(function(){
			eCardOnSelect();
		});
	}
	if($(paperCardSelected).size()>0 && $(paperCardSelected).not(":checked")){
		$(paperCardSelected).click(function(){
			paperCardOnSelect();
		});
	}
	if($(bothSelected).size()>0 && $(bothSelected).not(":checked")){
		$(bothSelected).click(function(){
			bothOnSelect();
		});
	}
	
	var whatsThisA = $("#whatsThis");
	var whatsThisPopup = $("#whatsThisPopup");
	if($(whatsThisA).size()>0){
		$(whatsThisA).attr("title", "");
		var txt = $(whatsThisA).text();
		$(whatsThisA).toggle(function(){
			$(whatsThisPopup).show().load("whatsthis.html");
			$(this).text("Close");
		},function(){
			$(whatsThisPopup).hide();
			$(this).text(txt);
		});
		return false;
	}
	
	var useGiftAidCheck = $(".useGiftAid");
	var addressForm = $(".billing4");
	if($(useGiftAidCheck).size()>0){
		$(useGiftAidCheck).click(function(){	
			if($(this).is(":checked")){
				$(addressForm).show();
			}else{
				$(addressForm).hide();
			}
		});
	}
	
});



// Flash Player Version Detection - Rev 1.6
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
			//alert("flashVer="+flashVer);
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}