var showShippingAddressPopupOnLoad = false;
var showLoginOnLoad = false;
var submitLoginForm = false;
var bannerManuallyChanged = false;
var selectedTrackingCountry = false;

var shipToCountry = 'GB';

var currentQuoteRowId = -1;
var currentQuoteRowButton;

var currentPricingTableDestinationId = 1;

function checkFormField( fieldId, isError ) {
	var field = document.getElementById( fieldId );
	if ( isError ) {
		$(field).addClass('formInputError');
	} else {
		$(field).removeClass('formInputError');
	}
}

function logout() {
	document.getElementById('logout_form').submit();
}

function trim(str) {
   return str.replace(/^\s*|\s*$/g,"");
}

function correctPNGBackground( divId, imgURL ) // correctly handle PNG transparency in Win IE 5.5 , 6 & 7.
{
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
		var div = document.getElementById( divId );
		div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+imgURL+"', sizingMethod='image')";
		div.style.background = '';
	}    
}

function initLogin() {
	document.getElementById('loginPopup').style.display = '';
	loginBox = 
			new YAHOO.widget.Panel("loginPopup",  
											{
											  width:"282px",
											  height:"196px",
											  fixedcenter:true, 
											  close:false, 
											  draggable:false, 
											  modal:true,
											  visible:false,
											  underlay:"none",
											  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5} 
											} 
										);

	loginBox.render(document.body);
	if( showLoginOnLoad )
		loginBox.show();
}
function hideLogin() {
	if( typeof loginBox != "undefined" ) {
		loginBox.hide();
	}
	submitLoginForm = false;
}
function showLogin( message ) {
	if ( typeof message != 'undefined' ) {
		document.getElementById('loginPopupText').innerHTML = message;
	}
	if( typeof loginBox != "undefined" ) {
		loginBox.show();
	} else {
		showLoginOnLoad = true;
	}
}

function onPopupSubmit() {
	// if we are submitting to form
	if( submitLoginForm ){
		// ensure we have username and password
		var validate = new validateForm();
		validate.checkText( 'popupUsername', 'Username' );
		validate.checkText( 'popupPassword', 'Password' );
		if( validate.numberOfErrors() > 0 ) {
			validate.displayErrors();
			// we have errors
			submitLoginForm = false;
		}
	}
	return submitLoginForm;
}


function checkLogin() {
	var validate = new validateForm();
	
	if( document.getElementById( 'clientLogin_username' ).value == 'Username' ){
		validate.addCustomError( 'Username' );
	} else {
		validate.checkText( 'clientLogin_username', 'Username' );
	}
	
	validate.checkText( 'clientLogin_password', 'Password' );
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
}

function openWindow( url, width, height ) {
	window.open( url, 'popupWindow','menubar=0,resizable=1,scrollbars=1,width='+ width +',height=' + height);
}


function inputBoxFocus( input, defaultText, passwordField ) {
	if( typeof( passwordField ) != 'undefined' ) {
		document.getElementById( passwordField ).style.display = '';
		document.getElementById( passwordField+'_text' ).style.display = 'none';
		document.getElementById( passwordField ).focus();
	} else {
		if( input.value == defaultText ) {
			input.value = '';
		}
	}
}

function inputBoxBlur( input, defaultText, passwordField ) {
	if( input.value == '' ) {
		if( typeof( passwordField ) != 'undefined' ) {
			document.getElementById( passwordField ).style.display = 'none';
			document.getElementById( passwordField+'_text' ).style.display = '';
		} else {
			input.value = defaultText;
		}
	}
}

function removeNonNumeric( val ) {
	return val.replace( /[^0-9]/g, '' );
}
function removeNonDecimal( val ) {
	return val.replace( /[^0-9\.]/g, '' );
}

function checkWhole( units, input, quoteRow ) {
	var isDocument = false;
	if(quoteRow == 'qq') {
		if(document.getElementById('qq_document')) {
			if(document.getElementById('qq_document').checked) {
				isDocument = true;
			}
		}
	} else {
		if(document.getElementById('cmsServicesShipping_document_' + quoteRow)) {
			if(document.getElementById('cmsServicesShipping_document_' + quoteRow).value == '1') {
				isDocument = true;
			}
		}
	}
	if(isDocument && units.toLowerCase() == 'kg') {
		var numericValue = removeNonDecimal( input.value );
	}
	else {
		var numericValue = removeNonNumeric( input.value );
	}
	if ( input.value != numericValue ) {
		input.value = numericValue;
		alert('Please only enter a whole number (ie 5.3' + units + ' would be 6' + units + ')');
	}
}

function mouseOverNavItem( navId ) {
	document.getElementById('navLink_' + navId).className = 'navLinkOn';
}
function mouseOutNavItem( navId ) {
	document.getElementById('navLink_' + navId).className = 'navLink';
}

function goToCheckout() {
	if ( document.getElementById('quoteTableCheckoutButton') && ( !creditInBasket ) ) {
		// we are on a page with the quote table, validate the form
		prebookShipments();
	} else {
		// no quote table, just proceed to the checkout
		document.location = '/checkout';
	}
}

/**
The keepSessionAlive function runs every 10 minutes to 
ensure that our session does not time out, allowing the 
user to keep items in their basket for as long as required
**/
function keepSessionAlive() {
	
	var sUrl = "/keepsessionalive.php";
	
	var handleSuccess = function( result ){
	}
	
	var handleFailure = function(o) {
	}
	
	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
}

setInterval( 'keepSessionAlive()', 600000 );

function changePricingTableDestination( num ) {
	document.getElementById('pricingStructureTabContent_' + currentPricingTableDestinationId ).style.display = 'none';
	document.getElementById('pricingStructureTab_' + currentPricingTableDestinationId ).className = 'pricingStructureTab';
	currentPricingTableDestinationId = num;
	document.getElementById('pricingStructureTabContent_' + currentPricingTableDestinationId ).style.display = 'block';
	document.getElementById('pricingStructureTab_' + currentPricingTableDestinationId ).className = 'pricingStructureTab pricingStructureTabOn';
}

var currentBannerItem = 1;
var numberOfBanners = 2;

function viewNextBanner( dir ) {
	if ( dir == '+' ) {
		var nextBannerItem = currentBannerItem + 1;
		if ( nextBannerItem > numberOfBanners ) {
			nextBannerItem = 1;
		}
	} else {
		var nextBannerItem = currentBannerItem - 1;
		if ( nextBannerItem == 0 ) {
			nextBannerItem = numberOfBanners;
		}
	}
	var animImgIn = new YAHOO.util.Anim( 'slideyBannerImage' + nextBannerItem, { opacity: { to: 1 } }, 0.5, YAHOO.util.Easing.easeOut );
	var animTextIn = new YAHOO.util.Anim( 'sliderBannerText' + nextBannerItem, { opacity: { to: 1 } }, 0.5, YAHOO.util.Easing.easeOut );
	var animImgOut = new YAHOO.util.Anim( 'slideyBannerImage' + currentBannerItem, { opacity: { to: 0 } }, 0.5, YAHOO.util.Easing.easeIn );
	var animTextOut = new YAHOO.util.Anim( 'sliderBannerText' + currentBannerItem, { opacity: { to: 0 } }, 0.5, YAHOO.util.Easing.easeOut );
	animImgIn.animate();
	animTextIn.animate();
	animImgOut.animate();
	animTextOut.animate();
	currentBannerItem = nextBannerItem;
}

function initBanner() {
	viewNextBanner('+');
}

function showConverter() {
	openWindow( '/converter', 460, 140 );
}

function validateTrackingInline() {
	var validator = new validateForm();
	validator.checkText( 'trackingNumberInline', 'Tracking Number', '- Enter Tracking Number' );
	if( validator.numberOfErrors() > 0 ) {
		validator.displayErrors();
		return false;
	} else {
		if ( ( document.getElementById('trackingNumberInline').value.toUpperCase().substring( 0, 3 ) == 'JJD' ) && ( !selectedTrackingCountry ) ) {
			// this is a dhl european shipment, show the country drop-down as we need that info too
			$('#trackingNumberInline').hide();
			$('#trackingButtonInline').hide();
			$('#trackingCountryInline').show();
			$('#trackingButtonInlineDisabled').show();
			return false;
		} else {
			return true;
		}
	}
}

function changeTrackingCountryInline( countryCode ) {
	if ( countryCode != '' ) {
		selectedTrackingCountry = true;
		$('#trackingButtonInlineDisabled').hide();
		$('#trackingButtonInline').show();
	} else {
		selectedTrackingCountry = false;
		$('#trackingButtonInlineDisabled').show();
		$('#trackingButtonInline').hide();
	}
}

function validateDHLEuroTracking() {
	var validator = new validateForm();
	validator.checkText( 'trackingNumberDHLEuro', 'Tracking Number', 'JJD' );
	validator.checkSelect( 'trackingCountryDHLEuro', '', 'Country' );
	if( validator.numberOfErrors() > 0 ) {
		validator.displayErrors();
		return false;
	} else {
		return true;
	}
}

function showUnitDropDown( name, el ) {
	$('#' + name + 'DropDown').show();
}
function hideUnitDropDown( name ) {
	$('#' + name + 'DropDown').hide();
}

function changeUnits( name, units ) {
	$('#units_' + name ).val( units );
	$('.customDropDownLabel_' + name ).html( '(' + units + ')' );
	hideUnitDropDown( name );
	for ( var i in shipmentDetails ) {
		updateStatus( i );
	}
}


/** exit popup stuff **/
var Page_Enter = new Date();
var TimeLimit = 20;
var Page_ShowPopOnExit = false;
var takingSurvey = false;
var surveyInt;
var surveyIsDone = false;
$(document).ready(function(){
	var cookieValue = getCookie("surveyIsDone");
	if( cookieValue == null ){
		surveyIsDone = false;
	}else{
		if( cookieValue == true ){
			surveyIsDone= true;
		}else{
			surveyIsDone = false;
		}
	}
});

function setCookie( name, value ) {
	document.cookie = name + '=' + value + ';path=/;';
}

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 ) );
}

function togglePopup( bool ) {
	setCookie( 'showPopOnExit', ( ( bool ) ? 'true' : 'false' ) );
	Page_ShowPopOnExit = bool;
}

function XBrowserAddHandlerPops( target, eventName, handlerName ) {
	if ( target.addEventListener ) {
		target.addEventListener(eventName, function(e){target[handlerName](e);}, false);
	} else if ( target.attachEvent ) {
		target.attachEvent("on" + eventName, function(e){target[handlerName](e);});
	} else {
		var originalHandler = target["on" + eventName];
		if ( originalHandler ) {
			target["on" + eventName] = function(e){originalHandler(e);target[handlerName](e);};
		} else {
			target["on" + eventName] = target[handlerName];
		}
	}
}

function internalLink( url ) {
	Page_ShowPopOnExit = false;
	if ( typeof url == 'string' ) {
		document.location = url;
	}
}


function startSurveyInterval() {
	surveyInt = setInterval( function() {
		checkSurveyReturn()
	}, 250 );
}

function checkSurveyReturn() {
	if ( takingSurvey && !surveyIsDone ) {
		togglePopup( false );
		Page_ShowPopOnExit = false;
		takingSurvey = false; // make sure we don't go back into this if
		clearInterval( surveyInt );
		document.location = '/survey/1';
	}
}
function surveyIsDone(){
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + 3650);
	var c_value= "true; expires="+exdate.toUTCString()+ ';path=/;';
	document.cookie="surveyIsDone=" + c_value;
}
function SiteExit() {
	var cookieVal = getCookie('showPopOnExit');
	if ( ( cookieVal === 'true' ) && ( Page_ShowPopOnExit == true ) ) {
		takingSurvey = true;
		startSurveyInterval();
		return "------------------------------------\n\nIf you would like to obtain a 5% discount on your next shipment (valid for 7 days), please click the 'Cancel' button below to stay on our site and take part in our survey.\n\n------------------------------------";
	}
}

function LinkConvert() {
	var href;
	var anchors = document.getElementsByTagName('a');
	var forms = document.getElementsByTagName('form');
	for(var y=0; y<anchors.length; y++) {
		href = anchors[y].href.toLowerCase();
		if (!(href.indexOf("http://")!=-1 && href.indexOf('ian')==-1 && href.indexOf('worldwide-parcelservices')==-1 && href.indexOf('mammoth')==-1)) {
			anchors[y].clickhandler = internalLink;
			XBrowserAddHandlerPops(anchors[y],"click","clickhandler");
		}
	}
	for(var y=0; y<forms.length; y++) {
		forms[y].submithandler = internalLink;
		XBrowserAddHandlerPops(forms[y],"submit","submithandler");
	}
}

$(document).ready( function() {
	XBrowserAddHandlerPops( window, 'load', 'LinkConvert' );
	window.onbeforeunload = SiteExit;
	Page_ShowPopOnExit = true;
} );
/** end exit popup stuff **/

function answerSurvey( done ) {
	if ( $('.surveyAnswers input:checked').length == 0 ) {
		alert( 'Please select your response.' );
		return false;
	} else {
		if(typeof done != "undefined" && done == true){
			surveyIsDone();
		}
		return true;
	}
}

function showAddOptions() {
	$('#addShipmentIcon').addClass('selectedBg');
	$('#addOptions').css('left',$('#addShipmentIcon').position().left);
	$('#addOptions').css('top',$('#addShipmentIcon').position().top - 45);
	$('#addOptions').show();
	$('#addOptions').mouseleave(function(){
		hideAddOptions();
	});
}
function hideAddOptions() {
	$('#addShipmentIcon').removeClass('selectedBg');
	$('#addOptions').hide();
}

function viewMoreNews() {
	$('#moreNews').slideDown(500);
}

YAHOO.util.Event.addListener( window, "load", initBanner );
YAHOO.util.Event.addListener( window, "load", initLogin );
