var now 		= new Date();
var day 		= now.getDay();
var monthday 	= now.getDate();
var month 		= now.getMonth();
var year 		= now.getYear();
year			+= ( year < 1000 )? 1900: 0;
var hr 			= now.getHours();
var min			= now.getMinutes();
var sec			= now.getSeconds();
hr				= ( hr < 10 )? '0'+hr.toString(): '';
min				= ( min < 10 )? '0'+min.toString(): '';
sec				= ( sec < 10 )? '0'+sec.toString(): '';

//onSale = false;  // TESTING 

var monthname = new Array();
monthname[0] = "Jan";
monthname[1] = "Feb";
monthname[2] = "Mar";
monthname[3] = "Apr";
monthname[4] = "May";
monthname[5] = "Jun";
monthname[6] = "Jul";
monthname[7] = "Aug";
monthname[8] = "Sep";
monthname[9] = "Oct";
monthname[10] = "Nov";
monthname[11] = "Dec";

var dayname = new Array();
dayname[0] = "Sun";
dayname[1] = "Mon";
dayname[2] = "Tue";
dayname[3] = "Wed";
dayname[4] = "Thu";
dayname[5] = "Fri";
dayname[6] = "Sat";

var timerID = setTimeout("",0);
defaultStatus="";

var endPromotion	= new Date();
endPromotion.setFullYear(2004);
endPromotion.setMonth(0);
endPromotion.setDate(10);
endPromotion.setHours(0);
endPromotion.setMinutes(0);
endPromotion.setSeconds(0);
var onPromo = ( endPromotion.getTime() - now.getTime() > 0 )? true: false;

var discountFactor	= ( onPromo )? 0.10: 0;
var SaleCufflinkPrice = 20;

var bb = '<form action="" name="frmBasket" id="frmBasket"><a href="/basket.php">Item(s) in Basket</a>:<input type="text" id="items" name="items" size="1" /></form>';

var txtBasket = '<form action="" name="frmBasket" id="frmBasket"><a href="/basket.php"><img src="/images/pics/view_basket.gif" /></a> Items:<input type="text" id="items" name="items" size="2" /> Total: £<input type="text" id="inpTotal" name="inpTotal" size="8" /></form>';

// version for Sale - red top //
//var txtBasket = '<form action="" name="frmBasket" id="frmBasket"><a href="/basket.php"><img src="/images/pics/view_basket_sale.gif" /></a> Items:<input type="text" id="items" name="items" size="2" /> Total: £<input type="text" id="inpTotal" name="inpTotal" size="8" /></form>';

function showDate() {
	document.write('<span class=date>&nbsp\;&nbsp\;&nbsp\;&nbsp\;&nbsp\;'+dayname[day]+' '+monthday+' '+monthname[month]+' '+year+'&nbsp\;&nbsp\;&nbsp\;&nbsp\;</span><br>');
}

function twoDecimalPlaces(value) {
	value.toString().indexOf('.',0)<0?value=value+'.00':value
	value.toString().indexOf('.',0)==value.toString().length-2?value=value+'0':value
	return value;
}

function convertor() {
	window.open('convertor.html?cost='+document.frmList.TaxFree.value,'convertor','scrollbars=yes,resizable=yes,width=900,height=490');
}

function convert100() {
	window.open('/convertor.html?cost=100','convertor','scrollbars=yes,resizable=yes,width=600,height=450');
}

function Status(text) {
	clearTimeout(timerID);
	defaultStatus=text;
	timerID=setTimeout("defaultStatus=''",5000);
}
	
function addtoBasket(form,paramProdCode) {
	var df = document.forms[ form ];		
	var prodCode		= df.product[ df.product.selectedIndex ].value;
	var prodQuantity 	= df.quantity[ df.quantity.selectedIndex ].value;
	var selSize 		= df.size.selectedIndex;
	var prodSize 		= df.size[ df.size.selectedIndex ].value;
	var prodSizeText	= df.size[ df.size.selectedIndex ].text;
	var available		= 0;

    if( !prodCode  || prodCode=="" ) {
		alert( "Please select from the list of colours or fabrics.\n\nThank you!" );
		df.elements[ 'product' ].focus();
		return;
	}
    prodType			= prod[ prodCode ][ 0 ];
    prodSubtype			= prod[ prodCode ][ 1 ];
    prodDescription		= prod[ prodCode ][ 2 ];
    prodCategory		= prod[ prodCode ][ 6 ];
    prodPrice			= ( onSale )? prod[ prodCode ][ 4 ] : ( prod[ prodCode ][ 5 ] == 1 )? prod[ prodCode ][ 4 ] : prod[ prodCode ][ 3 ];
   // prodPrice			= ( WebsiteDiscount != 0 )? prod[ prodCode ][ 3 ]  * (100 - WebsiteDiscount)/100 : prod[ prodCode ][ 3 ];

    //prodPrice			= ( prod[ prodCode ][ 5 ] == 1 )? prod[ prodCode ][ 4 ] : prod[ prodCode ][ 3 ];
    //prodPrice			= ( onPromo && ( prodCategory == 'Cufflink') )? SaleCufflinkPrice : prod[ prodCode ][ 3 ];
    //totalShirts 		= checkShirts();
    //prodPrice			= prod[ prodCode ][ 4 ];
    totalShirts 		= 0;
    totalShirts			+= ( prodCategory == 'Shirt' )? prodQuantity : 0;
    
    if ( prodCategory == 'Shirt' )	{
		if ( avail[prodCode][selSize-1] == "" ) {  // amended 18 Jul 2010 to correct error when using Back button or on page Refresh
			alert ( "I'm sorry - this style [ " + prodDescription + " ] is not currently available in size: " + prodSize );
			return;
		}
	}
	
	//alert ( 'COOKIE: ' + getCookieData('TheBasket') )
	
	if ( ! prodQuantity ) {
		alert( "Please select a quantity.\n\nThank you!" );
		df.elements[ 'quantity' ].focus();
		return;
    }
    if ( prodSize=="" ) {
		alert( "Please select a size.\n\nThank you!" );
		df.elements[ 'size' ].focus();
		return;
    }
    
	
    
var msg = '';
	msg += ( onPromo && ( totalShirts >= 2 ) && (prodCategory == 'Shirt') )? 'PLEASE NOTE THAT A 10% SALE DISCOUNT OF £'+twoDecimalPlaces( prodQuantity * prodPrice * discountFactor )+'\nWILL BE DEDUCTED AND SHOWN IN YOUR SHOPPING BASKET\n\n': '';
	msg += 'YOUR SELECTION:\n\n';
	msg += 'CODE: '+prodCode+'\n';
	msg += 'PRODUCT: '+prodType
	msg += ( ! prodSubtype )? '\n' : ' '+prodSubtype+'\n' ;
	msg += 'STYLE: '+prodDescription+'\n';
	msg += ( onPromo && ( totalShirts >= 2 ) && (prodCategory == 'Shirt') )? 'PROMOTIONAL PRICE: £'+twoDecimalPlaces( prodPrice * ( 1 - discountFactor ) )+'\n': 'PRICE: £'+prodPrice+'\n';
	msg += ( prodSize!="" ) ? 'SIZE: '+prodSizeText+'\n' : "";
	msg += 'QUANTITY: '+prodQuantity+'\n';
	msg += ( onPromo && ( totalShirts >= 2 ) && (prodCategory == 'Shirt') )? 'DISCOUNTED COST: £'+twoDecimalPlaces( prodQuantity * prodPrice * ( 1 - discountFactor ) )+'\n': 'COST: £'+twoDecimalPlaces( prodQuantity * prodPrice )+'\n';
	msg += '\nAdd this to your order?';

	if( confirm( msg ) ) {
		var payload = '#' + prodCode + '|' + prodSize + '|' + prodQuantity;
		var currentBasketContents = getCookieData('TheBasket');
		document.cookie = "TheBasket="+currentBasketContents+escape(payload)+";path=/";
		if( confirm( 'View shopping basket now?' ) ) {
			relocate( '/basket.php' );
		}
	}
	inBasket(checkItems());
	totBasket(checkTotal());
}

function inBasket(quant) {
	if (document.frmBasket.items) {
		document.frmBasket.items.value = quant;
	}
}

function totBasket(quant) {
	if (document.frmBasket.inpTotal) {
		document.frmBasket.inpTotal.value = twoDecimalPlaces(quant);
	}
}
function checkItems() {
	var numItems 	= 0;
	TheBasket   	= getCookieData('TheBasket').split('#');
	for (var i = 1; i <= TheBasket.length-1; i++) {
		var detail	= TheBasket[i].split('|');
		numItems	+= parseInt(detail[2]);
	}
	return numItems;	
}

/* WORK IN PROGRESS */

function checkTotal() {
	var numTotal 	= 0;
	TheBasket   	= getCookieData('TheBasket').split('#');
	for (var i = 1; i <= TheBasket.length-1; i++) {
		var detail	= TheBasket[i].split('|');
		quantity	= parseInt(detail[2]);		
		code		= detail[0];
		priceType	= (onSale)? 4: ( prod[ code ][ 5 ] == 1 )? 4 :3;
		price		= parseFloat( prod[ code ][ priceType ] );
		numTotal	+= eval( quantity * price );
	}
	return numTotal;	
}
/*************************************************************************/

function checkShirts() {
	var numShirts 	= 0;
	TheBasket   	= getCookieData('TheBasket').split('#');
	for (var i = 1; i <= TheBasket.length-1; i++) {
		var detail	= TheBasket[i].split('|');
		numShirts	+= ( prod[ detail[0] ][ 6 ] == 'Shirt' )? parseInt(detail[2]) : 0;
	}
	return numShirts;
}

function getCookieData(label) {
	var labelLen = label.length;
	var cLen = document.cookie.length;
	var i = 0;
	var cEnd;
	while (i < cLen) {
		var j = i + labelLen;
		if (document.cookie.substring(i,j) == label) {
			cEnd = document.cookie.indexOf(";",j);
			if (cEnd == -1) {
				cEnd = document.cookie.length;
			}
			return unescape(document.cookie.substring(j+1,cEnd));
		}
		i++;
	}
	return "";
}

/* old function 
function setCookie(name, value, expires) {
	document.cookie = name + "=" + escape(value) + "; path=/" +
	((expires == null) ? "" : "; expires=" + expires.toGMTString());
}

*/

function setCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function delCookie(name) {
	document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT" +  "; path=/";
}

function checkCookie() {
	alert( 'Cookie contains: '+unescape(document.cookie) );
}

function relocate(page) {
	window.location.href=page;
}

function JustSoPicWindow(imageName,imageWidth,imageHeight,alt,bgcolor,hugger) {
// by E Michael Brandt of ValleyWebDesigns.com - Please leave this comment intact.

	alt=alt+"  ** Click window to close **"
	if (bgcolor=="") {
		bgcolor="#FFFFFF";
	}
	var adj=0
	var w = screen.width;
	var h = screen.height;
	var byFactor=1;

    if(w<740){
      var lift=0.90;
    }
    if(w>=740 & w<835){
      var lift=0.91;
    }
    if(w>=835){
      var lift=0.93;
    }

	if (imageWidth>w){	
		byFactor = w / imageWidth;			
		imageWidth = w;
		imageHeight = imageHeight * byFactor;
	}
	if (imageHeight>h-adj){
		byFactor = h / imageHeight;
		imageWidth = (imageWidth * byFactor);
		imageHeight = h; 
	}
	   
	var scrWidth = w-adj;
	var scrHeight = (h*lift)-adj;

	if (imageHeight>scrHeight){
		imageHeight=imageHeight*lift;
		imageWidth=imageWidth*lift;
	}

	var posLeft=0
	var posTop=0
	
	if (hugger=="hug image") {
		posTop = (scrHeight-imageHeight)/2;
		posLeft = ((w-imageWidth)/2);
		scrHeight = imageHeight-adj;
		scrWidth = imageWidth-adj;
 	}
	
	imageHeight=imageHeight-adj;
	imageWidth=imageWidth-adj;

	newWindow = window.open("","newWindow","width="+scrWidth+",height="+scrHeight+",left="+posLeft+",top="+posTop);
	newWindow.document.open();
	newWindow.document.write('<html><title>'+alt+'</title><body leftmargin="0" topmargin="0" marginheight="0" marginwidth="0" bgcolor='+bgcolor+' onBlur="self.close()" onClick="self.close()">');  
	newWindow.document.write('<table width='+imageWidth+' border="0" cellspacing="0" cellpadding="0" align="center" height='+scrHeight+' ><tr><td>');
	newWindow.document.write('<img src='+imageName+' width='+imageWidth+' height='+imageHeight+' alt=\"Click\&nbsp\;screen\&nbsp\;to\&nbsp\;close.\" >'); 
	newWindow.document.write('</td></tr></table></body></html>');
	newWindow.document.close();
	newWindow.focus();
}

/* Marquee functions */
//Specify the marquee's width (in pixels)
var marqueewidth=680;
//Specify the marquee's height (in pixels, pertains only to NS)
var marqueeheight=15;
//Specify the marquee's scroll speed (larger is faster)
var speed=3;
//Specify the marquee contents
var marqueecontents1='<span class="marquee">' +

'WINTER SALE: 10% off all orders of two or more regular shirts!  ' +
'See WINTER SALE page for more special prices - 30% off! All items are subject to availability.' +

'</span>';

function showMarquee() {
	if ( onPromo ) {
		marqueeHTML = 	'';
		marqueeHTML += 	'<table width="748" border="0" cellspacing="0" cellpadding="0" align="center" bgcolor="#741226">' +
						'<tr> ' +
						'<td width="22" align="left" valign="top">&nbsp;</td>' +
						'<td align="left">';
		if (document.all) {
			marqueeHTML += '&nbsp;&nbsp;&nbsp;<marquee LOOP="-1" scrollAmount='+speed+' style="width:'+marqueewidth+'">'+marqueecontents1+'</marquee>';
		} else {
			marqueeHTML += 	'<ilayer width=' + marqueewidth + ' height=' + marqueeheight + ' name="cmarquee01" left="18">' +
							'<layer name="cmarquee02" class="marquee"></layer>' +
							'</ilayer>';
		}
		marqueeHTML +=	'</td>' +
						'<td width="22" align="right" valign="top">&nbsp;</td>' +
						'</tr>' +
						'</table>';
		document.write(marqueeHTML);
		window.onload=regenerate2;
	}
}

function regenerate(){
	window.location.reload();
}

function regenerate2(){
	inBasket(checkItems());
	if (document.layers){
		setTimeout("window.onresize=regenerate",680);
		intializemarquee();
	}
}

function intializemarquee(){
	document.cmarquee01.document.cmarquee02.document.write('<nobr>'+marqueecontents1+'</nobr>')
	document.cmarquee01.document.cmarquee02.document.close();
	thelength=document.cmarquee01.document.cmarquee02.document.width;
	scrollit();
}

function scrollit(){
	var count = 1;
	if (document.cmarquee01.document.cmarquee02.left>=thelength*(-1)){
		document.cmarquee01.document.cmarquee02.left-=speed;
		setTimeout("scrollit()",100);
	} else {
		document.cmarquee01.document.cmarquee02.left=marqueewidth;
		scrollit();
	}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

/*  begin - product size search form functions - ADDED 10-02-2007 */

function outputHelperText( text ) {
	document.open();
	document.write( '<div id="helper" class="helperText" style="visibility: hidden;"><nobr>' + text + '</nobr></div>' );
	document.close();
}

function doFocusEvent( name ) {
	var nav = getNavigatorType();
	var s = getLayer( 'helper' );
	var e = document.getElementById( name );
	e.style.backgroundColor = "#eee";
	if (nav=="ns6" || nav=="ie4") {
		s.visibility = "visible";
	} else if (nav=="ns4") {
		s.visibility = "show";
	}
}

function doBlurEvent( name ) {
	var nav = getNavigatorType();
	var s = getLayer( 'helper' );
	var e = document.getElementById( name );
	e.style.backgroundColor = "#fff";
	if (nav=="ns6" || nav=="ie4") {
		s.visibility = "hidden";
	} else if (nav=="ns4") {
		s.visibility = "hide";
	}	
}
function getElement( name ) {
   var element;
   var f = document.forms[0];
   for ( var i = 0; i < f.elements.length; i++ ) {
      element = f.elements[i];
      if ( element.name == name )
         return element;
   }

   return element;
}
function getLayer( name ) {
   var nav = getNavigatorType();
   var s;
   if (nav == "ns6")
       s = document.getElementById( name ).style;
   else if(nav == "ie4")
       s = document.all[ name ].style;
   else if (nav == "ns4")
       s = document.layers[ name ];

   return s;
}
function getNavigatorType() {
   if(document.layers)
      return "ns4";
   if(document.all)
      return "ie4";
   if(navigator.appVersion.indexOf("5.") == 0 && navigator.appName.indexOf("Netscape")>=0) 
      return "ns6";
}
function setStyle(obj,style,value){
	getRef(obj).style[style]= value;
}

function getRef(obj){
	return (typeof obj == "string") ?
		 document.getElementById(obj) : obj;
}
/* Availability function */

function alterSizes(selProdIdx, selProd, typ ) {
	if ( (selProd == '6363 98001 00') || (selProd == '6363 99001 00') ) {
		return;
	}
	var optSizes = (typ == 1)? new Array('18 1/2','19','19 1/2','20'): new Array('14 1/2','15','15 1/2','40','16','16 1/2','17','17 1/2','18');
	var lenSize = 0;
	var j = 0;
	var newList = new Array();
	var frm = document.getElementById('frmProducts');
	frm.size.options[0].value = "";
	frm.size.options[0].text = "Available Collar Sizes";

	if ( selProd != "" ) {
		frm.size.options.length = optSizes.length+1;
		for ( var i=0; i<optSizes.length; ++i ) {
			$sold_out = ( avail[ selProd ][ i ] != 1 )? ' - SOLD OUT': '';
			//$sold_out =  '';
			frm.size.options[i+1].value = optSizes[i];
			if ( typ==0 && i==3 ) {
				frm.size.options[i+1].text = 'Size ' + optSizes[i] + $sold_out;
			} else {
				frm.size.options[i+1].text = optSizes[i] + ' inches' + $sold_out;
			}
			setStyle(frm.size.options[0],'color','#000')
		}
	} else {
		frm.size.options.length = optSizes.length+1;
		for ( var i=0; i<optSizes.length; ++i ) {
			frm.size.options[i+1].value = optSizes[i];
			if ( typ==0 && i==3 ) {
				frm.size.options[i+1].text = 'Size ' + optSizes[i];
			} else {
				frm.size.options[i+1].text = optSizes[i] + ' inches';
			}
		}	
	}
	frm.size.selectedIndex = 0;

}

/*  end - product size search form functions - ADDED 10-02-2007 */

/* product option set on swatch popup - ADDED 17/08/07 */
function selectProduct(code) {
	var frm = document.getElementById('frmProducts');
	var productIndex = 0;
	for ( var i = 0; i<frm.product.options.length; ++i ) {
		if ( frm.product.options[i].value == code ) {
			productIndex = i;
		}
	}
	frm.product.selectedIndex = productIndex;
	frm.quantity.selectedIndex = 1;
	frm.elements[ 'product' ].focus();
	frm.elements[ 'size' ].focus();
}

/*** dynamic swatch area - 01/11/08 ******/
function reveal( typeSwatch ) {
	var hUpper = document.getElementById('right_col_upper').scrollHeight;
	var hMiddle = document.getElementById('right_col_middle').scrollHeight;
	var hSwatches = document.getElementById( typeSwatch ).scrollHeight;
	var hCollars = ( ( document.getElementById( 'collars' )==null ) || ( typeof document.getElementById( 'collars' )=="undefined"  ) )?0:document.getElementById( 'collars' ).scrollHeight;
	document.getElementById( typeSwatch ).style.height = hSwatches + 'px';
	document.getElementById('right_col_lower').style.height = hSwatches + 1 + 'px';
	document.getElementById('container').style.height = hUpper + hMiddle + hSwatches + hCollars + 'px';
	document.getElementById('left_col').style.height = hUpper + hMiddle + hSwatches + hCollars + 'px';
	document.getElementById('container').style.borderBottom = "solid #666 1px";
	document.getElementById('left_col').style.borderRight = "solid #666 1px";
}
function reveal_sale( typeSwatch ) {
	var hUpper = document.getElementById('right_col_upper').scrollHeight;
	var hMiddle = document.getElementById('right_col_middle_sale').scrollHeight;
	var hSwatches = document.getElementById( typeSwatch ).scrollHeight;
	var hCollars = ( ( document.getElementById( 'collars' )==null ) || ( typeof document.getElementById( 'collars' )=="undefined"  ) )?0:document.getElementById( 'collars' ).scrollHeight;
	document.getElementById( typeSwatch ).style.height = hSwatches + 'px';
	document.getElementById('right_col_lower').style.height = hSwatches + 1 + 'px';
	document.getElementById('container').style.height = hUpper + hMiddle + hSwatches + hCollars + 'px';
	document.getElementById('left_col').style.height = hUpper + hMiddle + hSwatches + hCollars + 'px';
	document.getElementById('container').style.borderBottom = "solid #666 1px";
	document.getElementById('left_col').style.borderRight = "solid #666 1px";
}
function collapse( typeSwatch ) {
	var addCollars = ( ( document.getElementById( 'collars' )==null ) || ( typeof document.getElementById( 'collars' )=="undefined"  ) )?false:true;
	var hCollars = ( ( document.getElementById( 'collars' )==null ) || ( typeof document.getElementById( 'collars' )=="undefined"  ) )?0:document.getElementById( 'collars' ).scrollHeight;
	swatches_height = ( ( typeSwatch=='swatches' ) )? '160px':'175px' ;
	var rclh = ( addCollars )? hCollars + 180 + 'px': '161px';
	var ch = ( addCollars )? hCollars + 590 + 'px': '650px';
	//var ch = ( addCollars )? hCollars + 590 + 'px': '610px';  //****************non-sale setting
	right_col_lower_height = ( ( typeSwatch=='swatches' ) )? '160px' : rclh ;
	container_height = ( ( typeSwatch=='swatches' ) )? '650px' : ch ;
	//container_height = ( ( typeSwatch=='swatches' ) )? '610px' : ch ;  //****************non-sale setting
	document.getElementById( typeSwatch ).style.height = swatches_height;
	document.getElementById('right_col_lower').style.height = right_col_lower_height;
	document.getElementById('container').style.height = container_height;
	document.getElementById('left_col').style.height = container_height;
	document.getElementById('container').style.borderBottom = "solid #666 1px";
}
function calcTaxfree() {
	if (document.convertor.price.options[document.convertor.price.selectedIndex].text != "select price") {
	document.convertor.Amount.value = formatPrice(eval(document.convertor.price.options[document.convertor.price.selectedIndex].text * 40/47));
	} else {
	document.convertor.Amount.value = 0;
	}
}
