
function changeTransportType(mode) {
	if (mode == "bike")
		cartModifyProduct(bikePid) ;
	else
		cartModifyProduct(carPid) ;
//	window.djlSpecial.djlQueue.add(this, this.cartModifyProduct, [2074]) ;
//	window.djlSpecial.djlQueue.add(this, this.getUpdatedOrderSummary) ;
//	window.djlSpecial.djlQueue.run() ;
}

function cartModifyProduct(product_id) {
	var postData = {
			'add' : true,
			'ajax' : true,
			'id_product' : product_id,
			'token' : static_token,
			'djl_ajax' : true,
			'djl_ajax_noredirect' : true
	};

	jQuery.post(baseDir + 'cart.php', postData, function(data) {
		window.setTimeout(function() {
			this.getUpdatedOrderSummary() ;
		}, 0) ;

	}, "html") ;

}

function getUpdatedOrderSummary() {
	var postData = {
			'ajax' : true,
			'token' : static_token,
			'step' : "2",
			'detailOnly' : true,
			'djl_ajax' : true,
			'djl_ajax_noredirect' : true
	};

	jQuery.post(baseDir + 'order.php', postData, function(data) {
		$('#order-detail-content').empty() ;
		$('#order-detail-content').append(data) ;
		window.setTimeout(function() {
			updateShippingInfoInProduct() ;
		}, 0) ;
	}, "html") ;

}
function updatePricesColors() {
	var selected = djlSpecial.initialCap($('[name=transpoMode]:checked').val()) ;
	$('[class~=djlTranspoModeBike],[class~=djlTranspoModeCar]').removeClass("djlSpecialRed") ;
	$('[class~=djlTranspoMode'+ selected + ']').addClass("djlSpecialRed") ;
}

function ajaxGetProduct(shortLink, longLink) {
	longLinkPath = jQuery.url.setUrl(longLink).attr("path").substr(baseUrl.length) ;
	if (!shortLink) shortLink = longLink ;
	$.post(shortLink + '&djl_content_only=1&djlspecial_ajax=1', function(data) {
		$('#center_column').html(data);
		window.document.title = "Dejala.fr, " + $('#center_column h2').html() ;
		try {
			pageTracker = _gat._getTracker("UA-5313478-3");
			pageTracker._trackPageview(longLinkPath) ;
		}
		catch(err) {} 
	});
	window.location.hash = longLinkPath ;
	djlSpecial.setButtonsOpacity() ;
}

function getExpressQuote() {
	var error = false ;
	if (($('input#djls_orig_city').val() == "") || ($('input#djls_orig_city').val() == "VILLE OU CP")) {
		error = true ;
		$('#djls_orig_city_input').addClass("validation_error") ;
	}
	if (($('input#djls_dest_city').val() == "") || ($('input#djls_dest_city').val() == "VILLE OU CP")) {
		error = true ;
		$('#djls_dest_city_input').addClass("validation_error") ;
	}
	
	if (error) return false ;

	$("form#expressQuoteForm input#cmd").get(0).value = "getQuote" ;
	jQuery.post(djlSpecialModuleUrl + "expressquote.php?djlspecial_ajax=1", $("#expressQuoteForm").serialize(), function(data) {
		if (data && !data.errors) {
			$.each(["orig", "dest"], function (idx, elt) {
				$('#djls_' + elt + '_city_input').removeClass("validation_error") ;
			});

			$("#template_course_idf_tarif_motorbike").html(djlSpecial.formatPrice(data.bike.p));
			$("#template_course_idf_tarif_car").html(djlSpecial.formatPrice(data.car.p));
			$("form#expressQuoteForm").data("quotes", data) ;
			djlSpecial.setPostCodesCookie() ;
			updatePricesColors() ;
			if (isExternal !== true) {
				window.setTimeout(function() {
					$('[name=transpoMode]:checked').focus() ;
					$('[name=transpoMode]:checked').click() ;
				}, 0) ;
			}
			else {
				$('a[title="Afficher"]').fadeTo(0, 0.2) ;
				$('a[title="Choisir Horaire"]').focus() ;
				$('a[title="Choisir Horaire"]').fadeTo(0, 1) ;
			}
		}
		else if (data.errors) {
			$.each(data.errors, function (idx, elt) {
				$('#djls_' + idx + '_city_input').addClass("validation_error") ;
			});
		}
		//$("form#orderProduct").show('fast');
	}, "json") ;
}

$(document).ready(function(){
	window.djlSpecial = {
		myMerge : function(first, second) {
			$.each(second, function(key, val){
				first[key] = val ;
			});
			return first ;
		},
		formatPrice : function(price) {
			var parts = parseFloat(price).toFixed(2).split(".") ;
			return "€ " + parts[0] + "<sup>" + (parts.length > 1 ? parts[1] : "00") + "</sup>" ;
		},
		initialCap : function(str) {
			return str.substr(0, 1).toUpperCase() + str.substr(1);
		},
		getRequestedCodes : function() {
			var ret = {} ;
			if ($("form#expressQuoteForm").data("quotes")) {
				var data = $("form#expressQuoteForm").data("quotes") ;
				ret['orig'] = data.orig.cp;
				ret['dest'] = data.dest.cp;
				ret['carpid'] = data.car.id;
				ret['bikepid'] = data.bike.id;
			}
			return ret ;
		},
		setButtonsOpacity : function () {
			var data = $("form#expressQuoteForm").data("quotes") ;
			var opacity = 1 ;
			if (data) {
				$.each([data[data.sel].sl, data[data.sel].ll], function(idx, elt) {
					if (elt == window.location.href.replace('#','')) opacity = 0.2 ;
				}) ;
			}
			$('a[title="Afficher"]').fadeTo(0, opacity) ;
		},
		setPostCodesCookie : function(erase) { // erase === true => erase. Else store
			if (erase === true) {
				$.cookie("djlRequestedPostCodes", null) ;
				$("form#expressQuoteForm").removeData("quotes") ;
			}
			else {
				var data = djlSpecial.myMerge({}, $("form#expressQuoteForm").data("quotes")) ;
				djlSpecial.myMerge(data, { "sel" : $('input[name="transpoMode"]:checked').val()}) ;
				$("form#expressQuoteForm").data("quotes", data) ;
				$.cookie("djlRequestedPostCodes", $.toJSON(data));
			}
		},
		djlQueue : {
			queue : [],
			pending : 0,
			add : function(context, func, args) {
				try {
					if (typeof context == "object" && typeof func === "function") {
						this.queue.push({ "context" : context, "func" : func, "args" : args }) ;
					}
					else {
						throw("Bad context and/or function") ;
					}
				} finally {};
			},
			reset : function() {
				this.queue = [] ;
				this.pending = 0 ;
				this.clearHandlers() ;
//				$("#djl_eo_loading").hide() ;
			},
			clearHandlers : function() {
				$(document).unbind("ajaxSuccess", this.successHandler) ;
				$(document).unbind("ajaxError", this.errorHandler) ;
				$(document).unbind("ajaxSend", this.sendHandler) ;
			},
			setHandlers : function() {
				this.clearHandlers() ;
				$(document).ajaxSuccess(this.successHandler) ;
				$(document).ajaxError(this.errorHandler) ;
				$(document).ajaxSend(this.sendHandler) ;
			},
			successHandler : function(e, xhr, settings) {
				window.djlSpecial.djlQueue.pending-- ;
				window.djlSpecial.djlQueue.run() ;
			},
			errorHandler : function(e, xhr, settings) {
				window.djlSpecial.djlQueue.reset();
			},
			sendHandler : function(e, jqxhr, settings) {
				settings.oldSuccess = settings.success ;
				var settingsRef = settings ; 
				settings.success = function(data, textStatus, jqXHR) {
					var retVal = settingsRef.oldSuccess(data, textStatus, jqXHR) ;
					if (retVal === false) {
						window.djlSpecial.djlQueue.reset() ;
					}
				} ;
			},
			run : function() {
				window.setTimeout(function() {
					window.djlSpecial.djlQueue.subrun() ;
				}, 0) ;
			},
			subrun : function() {
				if (!this.queue.length) {
					if (this.pending <= 0) {
						this.reset();
					}
					return ;
				}
				this.setHandlers() ;
				var next = this.queue.shift() ;
				var queue = this ;
				window.setTimeout(function() {
					var nbActiveAjaxRequests = $.active ;
					var retVal ;
					
					// Apparently, IE7 dislikes an undefined second arg to apply
					if (next.args) {
						retVal = next.func.apply(next.context, next.args) ;
					}
					else {
						retVal = next.func.apply(next.context) ;
					}
					// if function has not added a request to the queue and has not returned false, jump to next.
					if ($.active <= nbActiveAjaxRequests) {
						if (retVal === false) {
							queue.reset() ;
						}
						else {
							queue.run() ;
						}
					}
					else {
						queue.pending++ ;
					}
				}, 0) ;
			}
		}


	};

	$('a[title="Choisir Horaire"]').fadeTo(0, 0.2) ;

	$(['input#djls_orig_city', 'input#djls_dest_city']).each(function(idx, elt) {
		$(elt).bind('focus.myEvents', function() {
//			if (!$(this).data('initDone')) {
				$(this).val("");
				djlSpecial.setPostCodesCookie(true) ;
				$("#template_course_idf_tarif_motorbike").html("--") ;
				$("#template_course_idf_tarif_car").html("--") ;
//				$(this).data('initDone', true) ;
//			}
				djlSpecial.setButtonsOpacity() ;
//			$('a[title="Afficher"]').fadeTo(0, 1) ;
//			$('a[title="Choisir Horaire"]').fadeTo(0, 0.2) ;
		});

		$(elt).autocomplete({
			delay: 100,
			source: djlSpecialModuleUrl + "postcode-ajax-new.php",
			focus: function( event, ui ) {
			if (ui.item) $(event.target).val( ui.item.label );
			return false;
		},
		select: function( event, ui ) {
			window.setTimeout(function() {
				$(event.target).val( ui.item.label );
				$("form#expressQuoteForm").submit() ;
			}, 0) ;
			return false;
		}
		}) ;
//		$(elt).data( "autocomplete" )._resizeMenu = function() {
//		var ul = this.menu.element;
//		ul.width( Math.max(
//		ul.width( "" ).outerWidth(),
//		this.element.outerWidth()
//		) );
//		};
		$(elt).data( "autocomplete" )._search = function( value ) {
			this.element.addClass( "ui-autocomplete-loading" );
			this.source( { term: value, rnd: Math.random() }, this.response );
		};
		$(elt).data( "autocomplete" )._renderItem = function( ul, item ) {
			return $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append( "<a>" + accent_folded_hilite(item.label, this.element.val()) + "</a>" )
			.appendTo( ul );
		};
		$(elt).data( "autocomplete" )._renderMenu = function( ul, items ) {
			var self = this;
			if (items && items.length) {
				if (items[0].value == "none") {
					$( "<li></li>" )
					.append("\"" + this.element.val() + "\" " + items[0].label)
					.addClass("noAutocompleteValue")
					.appendTo( ul );
				}
				else {
					$.each( items, function( index, item ) {
						self._renderItem( ul, item );
					});
				}
			}
			else {
			}
		};
//		$(elt).data( "autocomplete" )._response = function( content ) {
//		this._suggest( content );
//		this._trigger( "open" );
//		this.element.removeClass( "ui-autocomplete-loading" );
//		} ;
	});
	
	$('input[name="transpoMode"]').val([$('input[name="transpoMode"]').val()]) ;

	if (cookie = $.cookie("djlRequestedPostCodes")) {
		var data = $.evalJSON(cookie) ;
		if (!data.bike || !data.car) {
			djlSpecial.setPostCodesCookie(true) ;
			return ;
		}
		$("form#expressQuoteForm").data("quotes", data) ;
		if (!data.sel) data.sel = "bike" ;

		$('input[name="transpoMode"]').val([data.sel]) ;
		
		$("#template_course_idf_tarif_motorbike").html(djlSpecial.formatPrice(data.bike.p)) ;
		$("#template_course_idf_tarif_car").html(djlSpecial.formatPrice(data.car.p)) ;
		$('input[name="djls_orig_city"]').val(data.orig.c + ' (' + data.orig.cp + ')') ;
		$('input[name="djls_dest_city"]').val(data.dest.c + ' (' + data.dest.cp + ')') ;

//		$('a[title="Choisir Horaire"]').fadeTo(0, 1) ;
//		$('a[title="Afficher"]').fadeTo(0, 0.2) ;
		updatePricesColors() ;
	}
	djlSpecial.setButtonsOpacity() ;

	$("form#expressQuoteForm").submit(function() {
		if (($('input#djls_orig_city').val() != "") && ($('input#djls_orig_city').val() != "VILLE OU CP")
				&& ($('input#djls_dest_city').val() != "") && ($('input#djls_dest_city').val() != "VILLE OU CP")) {
			getExpressQuote() ;
		}
		return false ;
	});

	$("form#orderProduct").submit(function() {
		$("form#expressQuoteForm input#cmd").get(0).value = "orderProduct" ;
		jQuery.post("{/literal}{$module_dir}{literal}expressquote.php?djlspecial_ajax=1", $("#expressQuoteForm").serialize(), function(data) {
			//$("#djl_loading").hide() ;
			djlSpecial.setPostCodesCookie() ;
			if (data.url && data.url != "") window.location = data.url ;
		}, "json") ;
		return false ;
	});

	$('input[name=transpoMode]').each(function(idx, elt) {
		$(elt).click(function(evt) {
			var data = $("form#expressQuoteForm").data("quotes") ;
			var which = $(elt).val() ;
			if (data) {
				longLink = jQuery.url.setUrl(data[which]['ll']).attr("path").substr(baseUrl.length) ;
				djlSpecial.setPostCodesCookie() ;
				updatePricesColors() ;
				if (isExternal !== true) {
					if (window.location.pathname == baseUrl) {
						ajaxGetProduct(data[which]['sl'], data[which]['ll']) ;
					}
					else {
						window.location.assign(baseUrl + '#' + longLink) ;
					}
				}
			}
		}) ;
	});

	$(document).ajaxSend(function(e, xhr, settings) {
		if (settings.url.indexOf('djlspecial_ajax') > 0) {
			$("#djl_loading").show() ;
		}
	});
	$(document).ajaxSuccess(function(e, xhr, settings) {
		if (settings.url.indexOf('djlspecial_ajax') > 0) {
			$("#djl_loading").hide() ;
		}
	});
	$(document).ajaxError(function(e, xhr, settings, exception) {
		if (settings.url.indexOf('djlspecial_ajax') > 0) {
			$("#djl_loading").hide() ;
		}
	});

	$('a[title="Afficher"]').click(function() {
		getExpressQuote() ;
	}) ;

	if (isExternal) {
		$('a[title="Choisir Horaire"]').click(function() {
			var data = $("form#expressQuoteForm").data("quotes") ;
			if (data) {
				window.open(data[data.sel].ll + refSite) ;
			}
		}) ;
	}
	if (window.location.hash) ajaxGetProduct(null, window.location.href.replace('#','')) ;
}) ;

