
$.ajaxSetup({
        url: CONST_SERVLET,
        timeout: 25000,
        global: false,
        type: "POST"
    }); 



if (window.top !== window.self) 
{
	document.write = "";
	window.top.location = window.self.location;
	setTimeout(function(){document.body.innerHTML='';},1);
	window.self.onload=function(evt){document.body.innerHTML='';};
}

function isBlank(a) {
    return a.replace(/\s+/g, "").length == 0
}
function formatNumber(c, a) {
    var b = "" + c;
    while (b.length < a) {
        b = "0" + b
    }
    return b
}
var trn = {
	onCall: false,
	infoBox: false,
	result: false,
	car:false,
	days:false,
	pickup:false,
	dropoff:false,
	totalRent:0,
	isClon:false,
	extras:[],
	cssIsValid: 'valid-field',
	cssInvalid: 'invalid-field',
	callScript: function(sc){
		$.getScript(CONST_SERVLET+sc);
	},
	getBookingParams: function(){
		
		var searchInfo = this.isClon? $('#frm-search-clon').serialize().replace(/-clon/ig, ""):$('#frm-search').serialize();
		searchInfo = searchInfo.replace(/cmd=Site%3A%3AsearchForCars/ig,'');
		
		var carInfo = '&car-id='+this.car.ID+'&car-type='+this.car.CarplusType+'&car-group='+this.car.CarplusGroup+'&car-rate='+this.totalRent;
		var client = '&'+$('#personal-details-form').serialize();
		var extras = '&extras=';
		var total	= 0;
		
		for(var i=0;i<this.extras.length;i++)
		{
			total = this.extras[i].perday? parseFloat(this.extras[i].total*this.extras[i].units*this.days):parseFloat(this.extras[i].total*this.extras[i].units);
			extras += this.extras[i].id+':'+this.extras[i].units+':'+total.toFixed(2)+':'+this.extras[i].cdwid+';';
			
		}
		extras = extras.substring(0,extras.length-1);
		
		return 'cmd=Site::ConfirmBooking'+carInfo+client+searchInfo+extras;
		
	},
	searchForCars: function(params,isClon)
	{
		if(this.onCall) return;
		trn.onCall = true;
		$('#cars').hide();
		$('#cars').tabs( 'destroy' );
		$('#cars').html('');
		
		var clon = isClon?'-clon':'';
		this.isClon = isClon;
		this.pickup 	= '#pickup'+clon;
		this.dropoff	= '#dropoff'+clon;
		
		this.loadInfoBox(
			'#loader-box',CONST_SEARCHING_H2,'<center><img src="images/ajax-loader-big.gif" align="absmiddle" hspace="5" /></center>');
		var infoFrom = 
		'<strong>'+CONST_PICKUP_LABEL+'</strong><br/>'+$(this.pickup+'  option:selected').text() +', '+$('#date-from'+clon).val()+CONST_AT_LABEL+  $('#hour-from'+clon).val() +':'+$('#min-from'+clon).val();
		var infoTo = 
		'<strong>'+CONST_DROPOFF_LABEL+'</strong><br/>'+$(this.dropoff+'  option:selected').text() +', '+$('#date-to'+clon).val()+CONST_AT_LABEL+  $('#hour-to'+clon).val() +':'+$('#min-to'+clon).val();
		
		$('#pickup-info').html(infoFrom);
		$('#dropoff-info').html(infoTo);
		
		this.call('#cars','<img src="images/ajax.gif" />',params,
			function (){
				trn.onCall = false;	
				show_results(trn.unloadInfoBox(),isClon);
			},function(){
				trn.onCall = false;
				new_again(trn.unloadInfoBox());
			});
	},
	updateDetailsByExtraSelect: function(id){
		if(!$('#extra-'+id).is(':checked')) {
			$('#extra-'+id).attr('checked',true);
		}
		this.updateDetailsByExtra(id);
	},
	updateDetailsByExtra: function(id){	
		if($('#extra-'+id).is(':checked'))
		{
			var data = $('#extra-'+id).val();
			var total = 0.00;
			data = data.split(';');
			total = data[2];
			units = 1;
			
			if(data[3]==1){units = $('#extra-select-'+id+' option:selected').val();}
	
			for(var i=0;i<this.extras.length;i++)
			{
				if(this.extras[i].id==id)
				{
					this.extras[i].total =total;
					this.extras[i].units = units;
					this.calculateTotal();
					return;
				}
			}
			var obj = {};
			obj.id = id;
			obj.perday = data[1]; // per day or rental?
			obj.total = parseFloat(total);
			obj.cdwid = data[4];
			obj.units = units;
			
			this.extras.push(obj);
			this.calculateTotal();
		}
		else{
			var tmp = [];
			for(var i=0;i<this.extras.length;i++)
			{
				if(this.extras[i].id==id){continue;}
				tmp.push(this.extras[i]);
			}
			this.extras = tmp;
			this.calculateTotal();
		}
	},
	calculateTotal: function(){
		
		$('#total-price-value').html('');
		$('#total-price-loader').show();
		this.totalRent = parseFloat(this.car.Rate);
		
		for(i=0;i<this.extras.length;i++)
		{
			this.totalRent += this.extras[i].perday? parseFloat(this.extras[i].total*this.extras[i].units*this.days):parseFloat(this.extras[i].total*this.extras[i].units);
		}
		$('#total-price-loader').hide();
		$('#total-price-value').html(this.totalRent.toFixed(2) + '&euro;');
	},
	updateDetails: function(div)
	{
		if(this.result) $(this.result).children(':eq(0)').css({'border':'','color':'#2E7DB2'});
		
		$(div).children(':eq(0)').css({'border':'3px solid','color':'#CC0000'});
		this.result = div;
		
		var data = $(div).attr('data');
		
		this.car = (eval("(" + data + ")"));
		
		$('#car_picture').attr('src',this.car.Picture);
		$('#car_name').html(this.car.CarBrand+' '+this.car.CarName);
		$('#car_spaces').html(this.car.Spaces);
		$('#car_bags').html(this.car.Bags);
		$('#car_aa').html(this.car.AA);
		$('#car_doors').html(this.car.Doors);
		$('#initial-rate').html(this.car.Rate);
		
		$('#details-franchise').html(this.car.Excess);
		
		
		if($('#scdw'))
		{
			var eid = $('#scdw').attr('rel');
			if(this.car.SCDW)
			{
				var scdwdata = eid+';1;'+this.car.SCDWRate+';0;'+this.car.SCDWId;	
				$('#extra-'+eid).val(scdwdata);
				$('#extra-rate-'+eid).html(this.car.SCDWRate);
				this.updateDetailsByExtra(eid);
				
				$('#scdw').css('display','');
			}
			else
			{
				$('#extra-'+eid).attr('checked',false);
				$('#scdw').css('display','none');
			}
			this.updateDetailsByExtra(eid);
		}

	
		this.calculateTotal();
		
		if(!$('#details').is(':visible'))
			$('#details').show();
	},
	call: function(div,loader,params,callbackOk,callbackKo)
	{	
		if($(div)) $(div).html(loader);
		
		$.ajaxq ("torrenova", {
			data: params,
			success: function(html)
			{
				if(div != null) $(div).html(html);
				if(typeof callbackOk=='function'){callbackOk();}
			},
			error: function(){
				if(div==null) return;
				$(div).html('<strong>error</strong>');;
				if(typeof callbackKo=='function'){callbackKo();}
			}
		});
	},
	loadInfoBox: function(div,title,info){
		$(div+'-info').html(info);
		$(div+'-title').html(title);
		
		this.infoBox = $(div).overlay({ 
			top: 272, 
			expose: { 	 
				color: '#000', 
				loadSpeed: 200, 		 
				opacity: 0.5 
			}, 
			closeOnClick: false, 
			api: true 
		});
		this.infoBox.load();
	},
	unloadInfoBox:function(){
		if(this.infoBox && this.infoBox.isOpened())
			this.infoBox.close();
	},
    resetForm: function (a) {
        $('#validation-error').hide();
		$('#validation-error-message').html('');
        $("#" + a + " :text").each(function () {
            var b = $(this);
            if (b.hasClass(trn.cssInvalid)) {
                b.removeClass(trn.cssInvalid)
            }
            if (b.hasClass(trn.cssIsValid)) {
                b.removeClass(trn.cssIsValid)
            }
            b.val("")
        })
    },
	validateField: function (b) {
        var c = b.val();
        var d = "";
        if (b.hasClass("email")) {
            var a = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;
            if (a.test(c)) {
                b.removeClass(this.cssInvalid).addClass(this.cssIsValid)
            } else {
                if (b.hasClass("required")) {
                    b.removeClass(this.cssIsValid).addClass(this.cssInvalid);
                    d = "<strong>" + b.attr("rel") + "</strong> " + CONST_EMAIL_NOT_CORRECT + "<br/>"
                } else {
                    if (b.hasClass("validate") && c.length > 0) {
                        b.removeClass(this.cssIsValid).addClass(this.cssInvalid);
                        d = "<strong>" + b.attr("rel") + "</strong> " + CONST_EMAIL_NOT_VALID + "<br/>"
                    } else {
                        b.removeClass(this.cssInvalid).addClass(this.cssIsValid)
                    }
                }
            }
        } else {
            if (c.length > 0) {
                b.removeClass(this.cssInvalid).addClass(this.cssIsValid)
            } else {
                if (b.hasClass("required")) {
                    b.addClass(this.cssInvalid);
                    d = CONST_YOUR_FORGOT + " <strong>" + b.attr("rel") + "</strong>.<br/>"
                } else {
                    if (b.hasClass("validate")) {
                        b.removeClass(this.cssInvalid).addClass(this.cssIsValid)
                    }
                }
            }
        }
        return d
    },
    validateForm: function (b,f) {
        var a = true;
        var c = "";
		
        $("#" + b.id + " :text:visible, #" + b.id + " textarea").each(function () {
            var d = $(this);
            c += trn.validateField(d)
        });
        $("#" + b.id + " :password:visible").each(function () {
            var d = $(this);
            c += trn.validateField(d)
        });
        if (c.length == 0) {
			if(f) $(f).hide();
			else
            $("#validation-error").hide()
        } else {
			if(f) $(f).html(c).show();
            else $("#validation-error-message").html(c).parent().parent().show();
            a = false
        }
        return a
    }
}
