// STARTS JS WHEN DOM IS READY 
// ---------------------------
$(document).ready(function(){
				   
	path = currentPage.substring(1).split('/');

	pageTitle = $(document).attr('title');

	body = $(document.body);

	// FIX IE6 CHECKBOXES & RADIOS 
	// ---------------------------

	if($.browser.msie && parseInt($.browser.version)==6){
		$(':checkbox, :radio').css({border: 'none', background: 'none'});
	}

	// CHECK USERNAME FOR REGISTRATION
	// -------------------------------

	if(path[1] == 'register'){
		
		$('#usernameAvailabilityIndicator').addClass('notChecked');
		$('.checkuserName').each(function(){
			oldUsername = $('#username').val();
			
			$(this).keyup(function(){
				newUsername = $('#username').val();
				if(newUsername.length == 0){
					$('#usernameAvailabilityIndicator').removeClass().addClass('notChecked');
				}else if(oldUsername != newUsername){
					var username = $('#username').val();
					var checkUserNameURL = contextPath+"/_common/_core/ajax-request/account/register/_actions/check-username.jsp";	
					$.ajax({
					  type: "GET",
					  url: checkUserNameURL,
					  data: "username="+username,
					  success : function(resp) {
							$('#usernameAvailabilityIndicator').removeClass().addClass(resp);
						},
					  error : function(resp) {
							$('#usernameAvailabilityIndicator').removeClass().addClass('notChecked');
						}
					}); //$.ajax
				}
				oldUsername = $('#username').val();
			}); //END $(this).keyup
		}); //END $('.checkuserName').each
			
		// TERMS AND CONDITIONS
		$('.showTermsAndConditionsLightBox').click(function(){
			$('#lightboxContent').css('height','366px');
			$('#lightboxContent').css('overflow','auto');
			$.showLightbox();
			return false;
		}); //END $('.showTermsAndConditionsLightBox').click
			
		$('.closewTermsAndConditionsLightBox').click(function(){
			$.hideLightbox();	
			return false;
		}); //END $('.showTermsAndConditionsLightBox').click
	
	} //END REGISTER IF


	// ACCEPT T&C FOR LOGIN
	// -------------------------------

	if(path[1] == 'login'){
			
		// TERMS AND CONDITIONS
		$('.showTermsAndConditionsLightBox').click(function(){
			$('#lightboxContent').css('height','366px');
			$('#lightboxContent').css('overflow','auto');
			$.showLightbox();
			return false;
		}); //END $('.showTermsAndConditionsLightBox').click
			
		$('.closewTermsAndConditionsLightBox').click(function(){
			$.hideLightbox();	
			return false;
		}); //END $('.showTermsAndConditionsLightBox').click
	
	} //END REGISTER IF


	if(path[1] == 'orders'){
		// FINANCE TERMS AND CONDITIONS
		$('#showFinanceTerms').click(function(){
			$('#lightboxContent').css('height','366px');
			$('#lightboxContent').css('overflow','auto');
			$.showLightbox();
			return false;
		}); //END $('.showTermsAndConditionsLightBox').click
			
		$('.closewTermsAndConditionsLightBox').click(function(){
			$.hideLightbox();	
			return false;
		}); //END $('#showFinanceTerms').click

		// SHOW CCV HELP
		$('#showCCVHelp').click(function(){
			$('#lightboxContentCCV').css('height','366px');
			$('#lightboxContentCCV').css('overflow','auto');
			$.showLightboxCCV();
			return false;
		}); //END $('.showTermsAndConditionsLightBox').click
			
		$('.closewCCVLightBox').click(function(){
			$.hideLightboxCCV();	
			return false;
		}); //END $('#showFinanceTerms').click
	}

	// CONFIRM ACTION 
	// -----------------------
	
	$('.confirmAction').click(function(){
		tooltip.restoreTitle('',this);
		var confResponse = confirm($(this).attr('title'));
		if (confResponse==true) {
			return;
		} else {
			return false;
		}
	}); //END $('.confirmAction').click

	$('.clearDefault').each(function(){
		$(this).focus(function(){
			if($(this).val()==this.defaultValue){
				$(this).val('');
			}
		});//END $(this).focus
		$(this).blur(function() {
			if($(this).val()==''){
				$(this).val(this.defaultValue);
			}
		});//END $(this).blur
	});//END $('.clearDefault').each


	// REGISTER BUTTON (LOGIN PAGE)
	// -----------------------
	
	if(path[1] == 'login'){
		$('.registerButton').click(function(){
			location.href = contextPath+"/account/register/";
			return false;
		});
	}

	// COLLEAGUE PERMISSION LIMITS
	// -----------------------
	
	if(path[1] == 'colleagues' && path[2] == 'update-permissions.jsp'){
		$('.permission-limit').click(function(){
			id = '#'+$(this).attr('id').replace('limit-', '');
			if(!!($(this).attr('checked'))){
				$(id).attr('readonly',false);
				!!$(id).attr('origValue')?$(id).val($(id).attr('origValue')):'';
				$(id).attr('origValue','');
			}else{
				$(id).attr('readonly',true);
				$(id).attr('origValue',$(id).val());
				$(id).val('');
			}
		});
	}

	// QUOTE FILTER
	// -----------------------
	/* // the following code isn't required as these parameters can be derived from the quote status parameter 
	if(path[1] == 'quotes' && (path[2] == 'index.jsp' || path[2] == 'filter.jsp')){
		$('#quote-filter').submit(function(el){
			if(!($('#showNotExpired').attr('checked')) && !($('#showExpired').attr('checked'))){
				alert("You must choose to show expired and/or not expired quotes.");
				
				return false;
			}
		});
	}
	*/
	
	// MINIMUM ORDER QUANTITY
	// -----------------------
	
	if(pageTitle.indexOf(specialsSectionTitle) > -1 || path[0] == 'basket'){
		$('.minOrderQty').blur(function(){
			$(':submit',this.form).attr('disabled','disabled');
			
			var id = $(this).attr('id').replace('id_','');
			var minimumOrderQty = parseInt($('#minimumOrderQty_'+id).val());
			var val = parseInt($(this).val());
			if(val < minimumOrderQty){
				alert("Minimum order quantity for this product is " + minimumOrderQty);
				$(this).val(minimumOrderQty);
			}
			$(':submit',this.form).attr('disabled','');
		});
	}

	// ADD TO FAVOURITE/BASKET
	// -----------------------
	
	if(path[0] == 'catalogue' && (path[1] == 'list.jsp' || path[1] == 'search.jsp')){
		$('#addToFavourite').click(function(){
			$(':text',this.form).each(function(){
				if($(this).attr('name').indexOf('itemQty') > -1){
					$(this).hide();
				}
			});
		});
		$('#addToBasket').attr('checked',true);
		$('#addToBasket').click(function(){
			$(':text',this.form).each(function(){
				if($(this).attr('name').indexOf('itemQty') > -1){
					$(this).show();
				}
			});
		});
	}

	// TABLE SORTER
	// -----------------------

	if(currentPage.indexOf('webmanager')==-1){

		$.tablesorter.addParser({
			id: "isellDate",
			is: function(s) {
				d=s.toLowerCase().replace('tba','01-Jan-1970');
				return /^\d\d[\/-][A-Za-z]{3}[\/-](\d{4}|\d{2})$/.test(d);
			},
			format: function(s) {
				//return $.tablesorter.formatFloat((s != "") ? new Date(s.replace(new RegExp(/-/g),"/")).getTime() : "0");
				
				d=s.toLowerCase().replace('tba','01-01-1990').split('-');
				month=d[1].replace('jan','01').replace('feb','02').replace('mar','03').replace('apr','04').replace('may','05').replace('jun','06').replace('jul','07').replace('aug','08').replace('sep','09').replace('oct','10').replace('nov','11').replace('dec','12');
				return new Date(month+'/'+d[0]+'/'+d[2]).getTime();
			},
			type: "isellDate"
		});

		$('.sortable').tablesorter();

		/*
		add overlay to say "sorting in progress. might need this for long lists
		$(".sortable").bind("sortStart",function() { 
	        $("#overlay").show(); 
	    }).bind("sortEnd",function() { 
	        $("#overlay").hide(); 
	    }); 
	    */
	
		$("> thead th",".sortable").each(function(){
			$(this).attr('title', 'Click to sort');
			$(this).mouseover(function(){
				$(this).addClass('hover');
			});
			$(this).mouseout(function(){
				$(this).removeClass('hover');
			});
		});
	
		if($("input.date")){
			$("input.date").attr('readonly','readonly').datepicker({buttonImageOnly: true, buttonText: '', buttonImage: contextPath+'/_common/_core/media/icons/calendar.gif', changeFirstDay: false, closeAtTop:false, dateFormat: 'yy-mm-dd', showOn: 'button'});
			
			$("img.datepicker_trigger").mouseover(function(){$(this).attr('src', contextPath+'/_common/_core/media/icons/calendar-hover.gif')});
			$("img.datepicker_trigger").mouseout(function(){$(this).attr('src', contextPath+'/_common/_core/media/icons/calendar.gif')});
		}
	
		$('.product-detail-image a').lightBox({imageLoading: contextPath+'/_common/_core/media/lightbox/lightbox-ico-loading.gif',
			imageBtnPrev: contextPath+'/_common/_core/media/lightbox/lightbox-btn-prev.gif',
			imageBtnNext: contextPath+'/_common/_core/media/lightbox/lightbox-btn-next.gif',
			imageBtnClose: contextPath+'/_common/_core/media/lightbox/lightbox-btn-close.gif',
			imageBlank: contextPath+'/_common/_core/media/lightbox/lightbox-blank.gif',
			containerResizeSpeed: 0
		});

	}

	// FUNCTIONS
	// ---------------
	
	function findPos(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft
			curtop = obj.offsetTop
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft
				curtop += obj.offsetTop
			}
		}
		return [curleft,curtop];
	}

	function pageScroll(){
		var scrollTop,scrollLeft;
		
		if(window.pageYOffset){
			scrollTop=window.pageYOffset;
			scrollLeft=window.pageXOffset;
		}else if(document.body.parentElement){
			scrollTop = document.body.parentElement.scrollTop;
			scrollLeft = document.body.parentElement.scrollLeft;
		}else{
			scrollTop = 0;
			scrollLeft = 0;
			window.scrollTo(0,0);
		}
		
		return new Array(scrollLeft,scrollTop);
	}

	$.extend( {
	showLightbox : function(){
		if($.browser.msie && parseInt($.browser.version)==6){
			$('#overlay,#lightbox').css('width',document.body.offsetWidth+'px');
			$('select').css('visibility','hidden');
		}
		$('#overlay,#lightbox').css('display','block');
		coords = pageScroll();
		
		$('#lightbox').css('top',coords[1]+75+'px');
	},
	hideLightbox : function(){
		$('#overlay,#lightbox').css('display','none');
		if($.browser.msie && parseInt($.browser.version)==6){
			$('select').css('visibility','visible');
		}
	},
	showLightboxCCV : function(){
		if($.browser.msie && parseInt($.browser.version)==6){
			$('#overlay,#lightboxCCV').css('width',document.body.offsetWidth+'px');
			$('select').css('visibility','hidden');
		}
		$('#overlay,#lightboxCCV').css('display','block');
		coords = pageScroll();
		
		$('#lightboxCCV').css('top',coords[1]+75+'px');
	},
	hideLightboxCCV : function(){
		$('#overlay,#lightboxCCV').css('display','none');
		if($.browser.msie && parseInt($.browser.version)==6){
			$('select').css('visibility','visible');
		}
	}
	});

	function mousePos(e,el){
		var mouseLeft,mouseTop;
		
		if(el){
			mouseLeft = (e.pageX-el.offsetLeft);
			mouseTop = (e.pageY-el.offsetTop);
		}else{
			mouseLeft = e.pageX;
			mouseTop = e.pageY;
		}
		
		return new Array(mouseLeft,mouseTop);
	}

	tooltip = {
		delay : '', //FOR FUTURE USE
		tags : ['a', 'input', 'select', 'textarea', 'span', 'img'],
		length : 0,
		el : '',
		titleEls : new Array(),
		titles : new Array(),
		initialize : function(){
			$(body).append('<div id="tooltip"></div>');
			$('#tooltip').hide();
			$(tooltip.tags).each(function(){
				$(this+'[title]').each(function(){
						$(this).mouseover(function(e){
							tooltip.showTooltip(e, this);
							tooltip.mousePosition(e);
							if($.browser.msie && parseInt($.browser.version)==6){
								if($('#tooltip').width()>300){
									$('#tooltip').css('width','300px');
								}
							}
						});
						$(this).mousemove(function(e){
							tooltip.mousePosition(e);
						});
						$(this).mouseout(function(e){
							tooltip.hideTooltip(e, this);
							if($.browser.msie && parseInt($.browser.version)==6){
								$('#tooltip').css('width','');
							}
						});
						tooltip.titleArray(this, tooltip.length);
						tooltip.length++;
					});
				});
		},
		titleArray : function(obj, len){
			tooltip.titles.push($.trim($(obj).attr('title')));
			tooltip.titleEls.push(obj);
		},
		showTooltip : function(e, obj){
			$(obj).attr('tip', $.trim($(obj).attr('title')));
			tooltip.el = obj;
			$(obj).attr('title','');
			$('#tooltip').show().html($(obj).attr('tip'));
		},
		hideTooltip : function(e, obj){
			$(obj).attr('title', $(obj).attr('tip'));
			tooltip.el = '';
			$(obj).attr('tip','');
			$('#tooltip').hide().html('');
			$('#tooltip').css('left','0px');
			$('#tooltip').css('top','0px');
		},
		restoreTooltip : function(obj){
			if(!obj){
				obj=tooltip.el;
			}
			$(obj).attr('tip', $.trim($(obj).attr('title')));
			$(obj).attr('title','');
		},
		restoreTitle : function(e, obj){
			if(displayToolTips){
				els = tooltip.titleEls;
				if(obj=='all'){
					$(els).each(function(i){
						$(this).attr('title', tooltip.titles[i]);
					});
				}else{
					$(obj).attr('title', tooltip.titles[$(els).index(obj)]);
				}
			}
			return false;
		},
		mousePosition : function(e){
			coords = mousePos(e);
			$('#tooltip').css('left',coords[0]+10+"px");
			$('#tooltip').css('top',coords[1]+15+"px");
		}
	}

	if(displayToolTips){
		tooltip.initialize();
	}

	$("#useForAll").each(function(){
		$(this).click(function(){
			if($(this).attr('checked')){
				if($('#addressType').hasClass('required')){
					$('#addressType').removeClass('required').addClass('required-disable').attr('disabled','disabled');
				}
			}else{
				if($('#addressType').hasClass('required-disable')){
					$('#addressType').removeClass('required-disable').addClass('required').removeAttr('disabled','disabled');
				}
			}
		});
		
		if($(this).attr('checked')){
			$(this).triggerHandler('click');
		}
	});

});//END $(document).ready