function doPositionFixed() {
	// Checks for IE6
	var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
	if(IE6) {
		// Fix height of semi transparent mask (leave yes/no box)
		$("div#popup_mask").css("height", $(window).height() + "px");
		// Add scroll event to make sure popup and mask stay in centre of screen
		$(window).scroll(function() {
			$("div#popup_mask").css("top", $(window).scrollTop() + "px");
			
		});
	} else {
		// Make position fixed for newer browsers
		$('.fixed').css('position','fixed');	
	}		
}
function customConfirm(yes_callback, no_callback, message) {
	var no_callback=no_callback ? no_callback : null;
	// Get target of link
	var target=$(this).attr('href');
	var message=message ? message : 'Are you sure you want to do this?';
	var popup='<div id="popup_mask" class="fixed"></div><div id="popup" class="fixed"><div id="popup_inner"><h3>'+message+'</h3><div class="popup_buttons"><button class="small_button" id="popup_yes">Yes</button> <button class="small_button" id="popup_no">No</button></div></div></div>';
	$('body').append(popup);
	// Call our function to replace headings etc with nicer font		
	startFLIR();
	// Call our function to emulate position fixed for any popups etc
	doPositionFixed();
	// Add href attribute to yes button
	$('#popup_yes').click(function() {
		$('#popup_mask, #popup').remove();
		if(yes_callback) {
			yes_callback();
		}
	});
	// Add href attribute to no button
	$('#popup_no').click(function() {
		$('#popup_mask, #popup').remove();
		if(no_callback) {
			no_callback();
		}
	});
}
function startFLIR() {
	
	//Helvetica Neue
	//HelveticaNeue LT 55 Roman
	
	Cufon.set('fontFamily', 'HelveticaNeue LT 55 Roman');
	Cufon.replace('h2.admin_jump, p.white, a.small_box, #popup h3');	
	
	Cufon.set('fontFamily', 'Helvetica Neue');
	Cufon.replace('h2, h3:not(.no_replace), button, .button, .carrier_rating, .button_title, .index_btn');
	
	
	
	var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
	/*
	if(!IE6) {
		// Init FLIR
		FLIR.init( { path: 'https://sslrelay.com/cargo-solv.com/facelift-1.2/' } );
		// Alex 02/04/09 - We now use jquery selectors for better accuracy & speed
		$('h1, h2, h3, button, .button, .carrier_rating, .button_title, .index_btn').not('#popup h3, h2.admin_jump').each(function() {
			FLIR.replace($(this), new FLIRStyle({cFont:'h_neue'}));			  
		});
		$('h2.admin_jump, p.white, a.small_box, #popup h3').each(function() {
			FLIR.replace($(this), new FLIRStyle({cFont:'h_55', mode:'wrap'}));			  
		});
		/*
		FLIR.replace( [ 'h1' ] , new FLIRStyle({ cFont:'h_neue'}) );
		FLIR.replace( [ 'h2.admin_jump' ] , new FLIRStyle({ cFont:'h_55'}) );
		FLIR.replace( [ 'h2' ] , new FLIRStyle({ cFont:'h_neue'}) );
		FLIR.replace( [ 'h3' ] , new FLIRStyle({ cFont:'h_neue', mode:'wrap'}) );
		FLIR.replace( [ 'p.white' ] , new FLIRStyle({ cFont:'h_55', mode:'wrap'}) );
		FLIR.replace( [ 'a.small_box' ] , new FLIRStyle({ cFont:'h_55', mode:'wrap'}) );
		//FLIR.replace( [ 'li' ] , new FLIRStyle({ cFont:'h_55'}) );
		FLIR.replace( [ '#freight_users li' ] , new FLIRStyle({ cFont:'h_55'}) );
		FLIR.replace( [ 'button' ] , new FLIRStyle({ cFont:'h_neue'}) );
		FLIR.replace( [ 'a.button' ] , new FLIRStyle({ cFont:'h_neue'}) );
		*/
	/*}*/
}
/**
 * Validates a single postcode object by retrieving the default postcode for the spcified country and checking for a valid
 * distance between the 2 points
 *
 * @param		object		postcode		Postcode object to check with 2 properties ('postcode' and 'country')
 * @param		function	callback		Callback function with single boolean argument whether postcode was valid
 */
function validatePostcode(postcode, callback) {
		//alert('in validatePostcode');//
	// String containing postcode we want to check
	//var from=postcode.postcode + ' ' + postcode.country;
	

	
	// dg 090910 - check if this postcode/country combination is in geocodes table - if yes geocodes will be used
		// create object to pass thru ajax to geocodes.php
		var postArray={
			postcode 		: postcode.postcode,
			country 		: postcode.country

		};
		
		//
		// dg 091031 - countries can now be set not to use Google Maps - as results are not consistant
		// - so before perfoming Google distance check below check if country is set to use google distance
		// - if not - do different check against default postcode prefixes
		
		// check if country is set to use google distance		
		$.post('/ajax/use_google_distance.php', postArray, function(google_distance) {
												 
				
		//
		//alert(google_distance);// either yes or no	
		
		if(google_distance=="yes"){//country can calculate distances on Google
			$.post('/ajax/geocodes.php', postArray, function(response) {
					var from=response;// set from string to be response - geocodes.php will return either postcode/country or latitude and longitude
				//alert('in'+from);//
				//alert(from);//ok
				// String containing our default location to check against (we use the same postcode twice)
				var to=from;//response;
				// Check whether browser is compatible
				if (GBrowserIsCompatible()) {
					var dir = new GDirections();
					GEvent.addListener(dir,"error", function() {
						//alert(postcode.index);//##									 
						callback(false, postcode.index);
					});
					GEvent.addListener(dir,"load", function() {
						callback(true, postcode.index);
					});
					// Load directions
					dir.load(from + " to " + to);
				} else {
					callback(false, postcode.index);	
				}	
				
			});
		}else{// country does not use google for distance - so check postcode against postcode prefixes - cannot continue if no zones will be found
			$.post('/ajax/check_existing_prefixes.php', postArray, function(response) {// will return true or false if valid postcode
				//alert(response);//
				
				if(response){
					callback(true, postcode.index);
				}else{
					callback(false, postcode.index);
				}
				
			});
		}
	});	//$.post('/ajax/use_google_distance.php', postArray, function(google_distance)	
		
}
function validatePostcodes(postcodes, callback) {
	
	var noResponses=0;
	// Array to hold responses for each postcode we check
	var errors=[];
	// Loop through each of our postcode objects
	for(var i in postcodes) {
		var postcode={
			'postcode'	:	postcodes[i].postcode,
			'country'	:	postcodes[i].country,
			'index'		:	i
		};
		// Call our function to check this postcode
		validatePostcode(postcode, function(response, index) {
			// Update our variable storing the number of responses we hae recieved
			noResponses++;
			// console.log('Recieved response about postcode '+response+' ('+noResponses+'/'+postcodes.length+')');
			// Update our array of errors if the postcode was invalid
			if(!response) {
				// console.log('Invalid postcode added to array');
				errors[errors.length]=index;
			}
			// Check whether this is our last postcode to check
			if(noResponses==postcodes.length) {
				// console.log('Last postcode to check');
				// Check whether there were any errors
				if(errors.length) {
					// console.log('Errors detected');
					// Use our callback with comma separated keys of the invalid postcodes passed to this function originially
					callback(errors.join(','));
				} else {
					// console.log('No errors');
					// Use our callback with our success trigger
					callback('success');	
				}
			}
		});
	}
}


function console_debug(message){
	// dg 100114 - use console.log to print any debugging info
	// - but doesnt work in IE - so test if console available before using...
		try {
			console;
		} catch(e) {
			console = {
				log:      function() {},
				debug:    function() {},
				info:     function() {},
				warn:     function() {},
				error:    function() {},
				trace:    function() {},
				dir:      function() {}
			};
		}
		
		console.log(message);
}



$(document).ready(function() {
	// Do our image replacement
	startFLIR();

	// Banner ads
	$('.banner_ad').click(function() {
		// First get the encoded href attribute of the ad so we can pass it to our script
		var target=encodeURIComponent($(this).attr('href'));
		// Now get the impression id so we can check which impressions were clicked on
		var impression=$(this).attr('id').substring(11);
		// Create our new URL via our redirector (which saves the clickthrough)
		var url='/banners/index.php?i='+impression+'&t='+target;
		// Now check whether we need to open the link in a new window
		if($(this).attr('target')=='_blank') {
			// Open URL in a new window
			window.open(url);
		} else {
			// Redirect within the same window to our URL
			window.location=url;
		}
		// Return false to avoid the href attribute being actioned
		return false;
	});
	// Tooltips
	/*$('.tt_label').hover(function() {
		$(this).siblings('.tt_content').show();
	},
	function() {
		$(this).siblings('.tt_content').hide();
	});
	*/
	// Tooltips - dg  090416 - use existing jTip elements
	$('.jTip').hover(function() {
		$(this).siblings('.jTip_content').css('display','block');
		$('.jTip').not($(this)).parent('.jTip_container').css('position', 'static');
	},
	function() {
		$(this).siblings('.jTip_content').hide();
		$('.jTip_container').css('position', 'relative');
	});
	// AK - Since hiding the tooltips is buggy, hide them whenever w are over input/select boxes to be sure
	$('input, select').hover(function() {
		$('.jTip_content').hide();								  
	});
	// Add focus class for input fields
	$('.form_text, .form_textarea').focus(function() {
		$(this).addClass('form_focus');															  
	});
	// remove focus class from input fields onblur
	$('.form_text, .form_textarea').blur(function() {
		$(this).removeClass('form_focus');															  
	});
	// Custom warning popup box for links with class 'warn_link'
	$('.warn_link').click(function() {
		// Get target of link
		var linkTarget=$(this).attr('href');
		customConfirm(
			function() {
				window.location=linkTarget;
			},
			function() {
				return false;
			},
			'Are you sure you want to do this?'
		);
		return false;
	});
	
	// Pop-up flash videos
	
	var prettyPhotoConfig = {callback:function(){$('#index_flash').show()}};
	var freightUserVideoData = {
		"href"	:	"/flash/freight-users.html?iframe=true&width=632&height=382",
		"title"	:	"Freight User Video Tutorial"
	}
	var freightProviderVideoData = {
		"href"	:	"/flash/freight-providers.html?iframe=true&width=632&height=382",
		"title"	:	"Freight Providers Video Tutorial"
	}
	
	$('.open_freight_users').attr(freightUserVideoData).click(function(){$('#index_flash').hide()}).prettyPhoto(prettyPhotoConfig);
	$('.open_freight_providers').attr(freightProviderVideoData).click(function(){$('#index_flash').hide()}).prettyPhoto(prettyPhotoConfig);	

	// Force our old filters markup into the standard collapsable content markup
	$('form.quote_filters').children().not('h3').wrapAll('<div class="collapsable_content"></div>');
	$('form.quote_filters h3').addClass('collapsable_title');
	
	// Hide all collapsable content initially
	$('.collapsable_content').hide();
	// Add hover class to all clickable titles incase they aren't anchors
	$('.collapsable_title').hover(function() {
		$(this).addClass('link');
	}, function() {
		$(this).removeClass('link');		
	});
	$('.collapsable_title').click(function() {
		$(this).toggleClass('collapsable_down');
		if($(this).siblings('.collapsable_content:visible').length) {
			$(this).siblings('.collapsable_content').slideUp('fast');
		} else {
			$(this).siblings('.collapsable_content').slideDown('fast');	
		}
	});
	
	// Check for firebug
	if (window.console && console.firebug) {
		if(!$.cookie('hide_firebug_warning')) {
			$('#header_inner').prepend('<div class="firebug_warning_wrapper">We noticed that you have firebug installed. Sometimes this can cause problems with our our quote engine.<br />You may wish to disable it from the Tools > Add Ons > Firebug menu. <a href="#" class="hide_firebug_warning">Don\'t show this again</a></div>');
			$('.hide_firebug_warning').click(function() {
				// Set cookie to not show message again
				var config = { path: '/', expires: 10 };
				// Set cookie for 2 weeks
				$.cookie('hide_firebug_warning', '1', config);
				// Hide the warning
				$('.firebug_warning_wrapper').slideUp('fast', function() {
					$(this).remove();													   
				});
				return false;
			});
		}
	}

	// Functions to run whenever an ajax request completes
	$(document).ajaxStop(function() {
		// Call our function to replace headings etc with nicer font		
		startFLIR();
		// Call our function to emulate position fixed for any popups etc
		doPositionFixed();
	});
	
	// Pretty bad but no time to make a nice class :( TF 100522
									
	$("#tabs_index").children("div").hide();
	$("#tabs_index ul li:first a").addClass("selected");
	$("#tabs_index div:first").show();
	$("#tabs_index ul li a").click(function()
	{
		var div = $(this).attr("href");
		$("#tabs_index ul li a.selected").removeClass("selected");
		$(this).addClass("selected");
		$("#tabs_index").children("div").hide();
		$(div).show();
		return false;
	});
});