//--------------------------------------------------------------------------------------------------------------------------------
// Location
//--------------------------------------------------------------------------------------------------------------------------------
function Location(locationId)
{
    this.locationId = locationId;
    this.id = null;
    this.name = null;
    this.type = null;
    this.sidetrack = null;
    this.harbour = null;
    this.longitude = null;
    this.latitude = null;
    
    this.observerObjects = new Array();
}

Location.prototype.registerObserver = function(object)
{
    this.observerObjects.push(object);
};

Location.prototype.resetObservers = function(object)
{
    this.observerObjects = new Array();
};

Location.prototype.unregisterObserver = function(object)
{
    this.observerObjects = this.observerObjects.filter(
        function(loopObject)
        {
            if(loopObject !== object)
            {
                return loopObject;
            }
        }
    );
};

Location.prototype.notifyObserver = function()
{
    var scope = this || window;
    var observerObjectsLength = this.observerObjects.length;
    
    for(var index = 0; index < observerObjectsLength; index++)
    {
        this.observerObjects[index].notify();
    }
};

Location.prototype.updateData = function(prefix)
{
    var locationValidation = new LocationValidation(prefix, this);
    locationValidation.validate();
    
    this.notifyObserver();
};

Location.prototype.updateDataWithCoordinates = function(prefix, latitude, longitude)
{
    var locationValidation = new LocationValidation(prefix, this);
    locationValidation.validate();
    
    this.latitude = latitude;
    this.longitude = longitude;
    
    this.notifyObserver();
};

Location.prototype.setCoordinates = function(latitude, longitude)
{
    this.latitude = latitude;
    this.longitude = longitude;
    
    this.notifyObserver();
};

Location.prototype.updateDataByParameters = function(id, name, type)
{
    this.id = id;
    this.name = name;
    this.type = type;
    this.sidetrack = null;
    this.harbour = null;
    this.longitude = null;
    this.latitude = null;
    
    this.notifyObserver();
};

Location.prototype.resetData = function()
{
    this.id = null;
    this.name = null;
    this.type = null;
    this.sidetrack = null;
    this.harbour = null;
    this.longitude = null;
    this.latitude = null;
    
    this.notifyObserver();
};

Location.prototype.setId = function(id)
{
    this.id = id;
};

Location.prototype.getId = function()
{
    return this.id;
};

Location.prototype.getLocationId = function()
{
    return this.locationId;
};

Location.prototype.setName = function(name)
{
    this.name = name;
};

Location.prototype.getName = function()
{
    return this.name;
};

Location.prototype.setType = function(type)
{
    this.type = type;
};

Location.prototype.getType = function()
{
    return this.type;
};

Location.prototype.setSidetrack = function(sidetrack)
{
    this.sidetrack = sidetrack;
};

Location.prototype.getSidetrack = function()
{
    return this.sidetrack;
};

Location.prototype.setHarbour = function(harbour)
{
    this.harbour = harbour;
};

Location.prototype.getHarbour = function()
{
    return this.harbour;
};

Location.prototype.setLongitude = function(longitude)
{
    this.longitude = longitude;
};

Location.prototype.getLongitude = function()
{
    return this.longitude;
};

Location.prototype.setLatitude = function(latitude)
{
    this.latitude = latitude;
};

Location.prototype.getLatitude = function()
{
    return this.latitude;
};

Location.prototype.getFieldList = function()
{
    return new Array("LocationId", "Id", "Name", "Type", "Sidetrack", "Harbour", "Longitude", "Latitude");
};

Location.prototype.getClassName = function()
{
    return "Location";
};

Location.prototype.updateDependencies = function(removedSection)
{
    var observerObjectsLength = this.observerObjects.length;
    for(var index = 0; index < observerObjectsLength; index++)
    {
        var section = this.observerObjects[index];
        
        if(section != null)
        {
            if(section.getId() != removedSection.getId())
            {
                section.updateLocation(removedSection.getTargetLocation());
            }
        }
    }
};
//--------------------------------------------------------------------------------------------------------------------------------
// MainFormular
//--------------------------------------------------------------------------------------------------------------------------------
function MainFormular()
{
    this.intermodalTransferType = null;
    this.cargoUnit = null;
    this.cargoWeight = null;
    this.cargoVolumeWeight = null;
    this.energyUnit = null;
}

MainFormular.prototype.setIntermodalTransferType = function(intermodalTransferType)
{
    this.intermodalTransferType = intermodalTransferType;
};

MainFormular.prototype.getIntermodalTransferType = function()
{
    return this.intermodalTransferType;
};

MainFormular.prototype.setCargoUnit = function(cargoUnit)
{
    this.cargoUnit = cargoUnit;
};

MainFormular.prototype.getCargoUnit = function()
{
    return this.cargoUnit;
};

MainFormular.prototype.setCargoWeight = function(cargoWeight)
{
    this.cargoWeight = cargoWeight;
};

MainFormular.prototype.getCargoWeight = function()
{
    return this.cargoWeight;
};

MainFormular.prototype.setCargoVolumeWeight = function(cargoVolumeWeight)
{
    this.cargoVolumeWeight = cargoVolumeWeight;
};

MainFormular.prototype.getCargoVolumeWeight = function()
{
    return this.cargoVolumeWeight;
};

MainFormular.prototype.setEnergyUnit = function(energyUnit)
{
    this.energyUnit = energyUnit;
};

MainFormular.prototype.getEnergyUnit = function()
{
    return this.energyUnit;
};
//--------------------------------------------------------------------------------------------------------------------------------
// MainFields
//--------------------------------------------------------------------------------------------------------------------------------
function MainFields()
{
    this.intermodalTransferType = "None";
    this.cargoUnit = "ton";
    this.cargoWeight = 100;
    this.cargoVolumeWeight = "Average";
}

MainFields.prototype.setIntermodalTransferType = function(intermodalTransferType)
{
    this.intermodalTransferType = intermodalTransferType;
};

MainFields.prototype.getIntermodalTransferType = function()
{
    return this.intermodalTransferType;
};

MainFields.prototype.setCargoUnit = function(cargoUnit)
{
    this.cargoUnit = cargoUnit;
};

MainFields.prototype.getCargoUnit = function()
{
    return this.cargoUnit;
};

MainFields.prototype.setCargoWeight = function(cargoWeight)
{
    this.cargoWeight = cargoWeight;
};

MainFields.prototype.getCargoWeight = function()
{
    return this.cargoWeight;
};

MainFields.prototype.setCargoVolumeWeight = function(cargoVolumeWeight)
{
    this.cargoVolumeWeight = cargoVolumeWeight;
};

MainFields.prototype.getCargoVolumeWeight = function()
{
    return this.cargoVolumeWeight;
};

MainFields.prototype.getFieldList = function()
{
    return new Array("IntermodalTransferType", "CargoUnit", "CargoWeight", "CargoVolumeWeight");
};

//--------------------------------------------------------------------------------------------------------------------------------
// Rail
//--------------------------------------------------------------------------------------------------------------------------------
function Rail()
{
    this.trainDriveClass = null;
    this.trainWeight = null;
    this.emptyRunFactor = null;
    this.loadFactor = null;
    this.ferryRouting = null;
}

Rail.prototype.setTrainWeight = function(trainWeight)
{
    this.trainWeight = trainWeight;
};

Rail.prototype.getTrainWeight = function()
{
    return this.trainWeight;
};

Rail.prototype.setTrainDriveClass = function(trainDriveClass)
{
    this.trainDriveClass = trainDriveClass;
};

Rail.prototype.getTrainDriveClass = function()
{
    return this.trainDriveClass;
};

Rail.prototype.setEmptyRunFactor = function(emptyRunFactor)
{
    this.emptyRunFactor = emptyRunFactor;
};

Rail.prototype.getEmptyRunFactor = function()
{
    return this.emptyRunFactor;
};

Rail.prototype.setLoadFactor = function(loadFactor)
{
    this.loadFactor = loadFactor;
};

Rail.prototype.getLoadFactor = function()
{
    return this.loadFactor;
};

Rail.prototype.setFerryRouting = function(ferryRouting)
{
    this.ferryRouting = ferryRouting;
};

Rail.prototype.getFerryRouting = function()
{
    return this.ferryRouting;
};

Rail.prototype.getFieldList = function()
{
    return new Array("ClassName","TrainDriveClass", "TrainWeight", "EmptyRunFactor", "FerryRouting", "LoadFactor");
};

Rail.prototype.getClassName = function()
{
    return "Rail";
};
//--------------------------------------------------------------------------------------------------------------------------------
// Sea
//--------------------------------------------------------------------------------------------------------------------------------
function Sea()
{
    this.vehicleId = null;
    this.vehicleName = null;
    this.speedUtilisation = null;
    this.vehicleType = null;
    this.loadFactor = null;
    this.loadFactorContainer = null;
}

Sea.prototype.setVehicleId = function(vehicleId)
{
    this.vehicleId = vehicleId;
};

Sea.prototype.getVehicleId = function()
{
    return this.vehicleId;
};

Sea.prototype.setVehicleName = function(vehicleName)
{
    this.vehicleName = vehicleName;
};

Sea.prototype.getVehicleName = function()
{
    return this.vehicleName;
};

Sea.prototype.setSpeedUtilisation = function(speedUtilisation)
{
    this.speedUtilisation = speedUtilisation;
};

Sea.prototype.getSpeedUtilisation = function()
{
    return this.speedUtilisation;
};

Sea.prototype.setVehicleType = function(vehicleType)
{
    this.vehicleType = vehicleType;
};

Sea.prototype.getVehicleType = function()
{
    return this.vehicleType;
};

Sea.prototype.setLoadFactor = function(loadFactor)
{
    this.loadFactor = loadFactor;
};

Sea.prototype.getLoadFactor = function()
{
    return this.loadFactor;
};

Sea.prototype.setLoadFactorContainer = function(loadFactorContainer)
{
    this.loadFactorContainer = loadFactorContainer;
};

Sea.prototype.getLoadFactorContainer = function()
{
    return this.loadFactorContainer;
};

Sea.prototype.getFieldList = function()
{
    return new Array("ClassName","VehicleId", "VehicleName", "SpeedUtilisation", "VehicleType", "LoadFactor", "LoadFactorContainer");
};

Sea.prototype.getClassName = function()
{
    return "Sea";
};
//--------------------------------------------------------------------------------------------------------------------------------
// Chain
//--------------------------------------------------------------------------------------------------------------------------------
function Chain()
{
    this.transportMode = null;
}

Chain.prototype.setTransportMode = function(transportMode)
{
    this.transportMode = transportMode;
};

Chain.prototype.getTransportMode = function()
{
    return this.transportMode;
};
//--------------------------------------------------------------------------------------------------------------------------------
// TransferPoints
//--------------------------------------------------------------------------------------------------------------------------------
function TransferPoints()
{
    this.sourceLocationId = null;
    this.sourceLocationName = null;
    this.sourceLocationType = null;
    this.targetLocationId = null;
    this.targetLocationName = null;
    this.targetLocationType = null;
}

TransferPoints.prototype.setSourceLocationId = function(sourceLocationId)
{
    this.sourceLocationId = sourceLocationId;
};

TransferPoints.prototype.getSourceLocationId = function()
{
    return this.sourceLocationId;
};

TransferPoints.prototype.setSourceLocationName = function(sourceLocationName)
{
    this.sourceLocationName = sourceLocationName;
};

TransferPoints.prototype.getSourceLocationName = function()
{
    return this.sourceLocationName;
};

TransferPoints.prototype.setTargetLocationId = function(targetLocationId)
{
    this.targetLocationId = targetLocationId;
};

TransferPoints.prototype.getTargetLocationId = function()
{
    return this.targetLocationId;
};

TransferPoints.prototype.setTargetLocationName = function(targetLocationName)
{
    this.targetLocationName = targetLocationName;
};

TransferPoints.prototype.getTargetLocationName = function()
{
    return this.targetLocationName;
};

TransferPoints.prototype.setSourceLocationType = function(sourceLocationType)
{
    this.sourceLocationType = sourceLothis.sourceLocationId = null;
    this.sourceLocationName = null;
    this.sourceLocationType = null;
    this.targetLocationId = null;
    this.targetLocationName = null;
    this.targetLocationType = null;cationType;
};

TransferPoints.prototype.getSourceLocationType = function()
{
    return this.sourceLocationType;
};

TransferPoints.prototype.setTargetLocationType = function(targetLocationType)
{
    this.targetLocationType = targetLocationType;
};

TransferPoints.prototype.getTargetLocationType = function()
{
    return this.targetLocationType;
};

TransferPoints.prototype.getFieldList = function()
{
    return new Array("SourceLocationId", "SourceLocationName", "SourceLocationType", "TargetLocationId", "TargetLocationName", "TargetLocationType");
};

//--------------------------------------------------------------------------------------------------------------------------------
// Road
//--------------------------------------------------------------------------------------------------------------------------------
function Road()
{
    this.emissionClass = null;
    this.lorryClass = null;
    this.emptyRunFactor = null;
    this.loadFactor = null;
    this.ferryRouting = null;
}

Road.prototype.setEmissionClass = function(emissionClass)
{
    this.emissionClass = emissionClass;
};

Road.prototype.getEmissionClass = function()
{
    return this.emissionClass;
};

Road.prototype.setLorryClass = function(lorryClass)
{
    this.lorryClass = lorryClass;
};

Road.prototype.getLorryClass = function()
{
    return this.lorryClass;
};

Road.prototype.setEmptyRunFactor = function(emptyRunFactor)
{
    this.emptyRunFactor = emptyRunFactor;
};

Road.prototype.getEmptyRunFactor = function()
{
    return this.emptyRunFactor;
};

Road.prototype.setLoadFactor = function(loadFactor)
{
    this.loadFactor = loadFactor;
};

Road.prototype.getLoadFactor = function()
{
    return this.loadFactor;
};

Road.prototype.setFerryRouting = function(ferryRouting)
{
    this.ferryRouting = ferryRouting;
};

Road.prototype.getFerryRouting = function()
{
    return this.ferryRouting;
};

Road.prototype.getFieldList = function()
{
    return new Array("ClassName","EmissionClass","LorryClass","EmptyRunFactor","LoadFactor","FerryRouting");
};

Road.prototype.getClassName = function()
{
    return "Road";
};
//--------------------------------------------------------------------------------------------------------------------------------
// Air
//--------------------------------------------------------------------------------------------------------------------------------
function Air()
{
    this.vehicleId = null;
    this.vehicleName = null;
    this.RFIFactor = null;
    this.bellyFreight = null;
    this.loadFactor = null;
    this.bellyFreightCB = null;
}

Air.prototype.setVehicleId = function(vehicleId)
{
    this.vehicleId = vehicleId;
};

Air.prototype.getVehicleId = function()
{
    return this.vehicleId;
};

Air.prototype.setVehicleName = function(vehicleName)
{
    this.vehicleName = vehicleName;
};

Air.prototype.getVehicleName = function()
{
    return this.vehicleName;
};

Air.prototype.setRFIFactor = function(RFIFactor)
{
    this.RFIFactor = RFIFactor;
};

Air.prototype.getRFIFactor = function()
{
    return this.RFIFactor;
};

Air.prototype.setBellyFreight = function(bellyFreight)
{
    this.bellyFreight = bellyFreight;
};

Air.prototype.getBellyFreight = function()
{
    return this.bellyFreight;
};

Air.prototype.setLoadFactor = function(loadFactor)
{
    this.loadFactor = loadFactor;
};

Air.prototype.getLoadFactor = function()
{
    return this.loadFactor;
};

Air.prototype.setBellyFreightCB = function(bellyFreightCB)
{
    this.bellyFreightCB = bellyFreightCB;
};

Air.prototype.getBellyFreightCB = function()
{
    return this.bellyFreightCB;
};

Air.prototype.getFieldList = function()
{
    
    return new Array("ClassName","VehicleId", "VehicleName", "RFIFactor", "BellyFreight", "LoadFactor", "BellyFreightCB");
};

Air.prototype.getClassName = function()
{
    return "Air";
};
//--------------------------------------------------------------------------------------------------------------------------------
// InlandWaterways
//--------------------------------------------------------------------------------------------------------------------------------
function InlandWaterways()
{
    this.vehicleId = null;
    this.vehicleName = null;
    this.speedUtilisation = null;
    this.type = null;
    this.loadFactor = null;
    this.loadFactorContainer = null;
}

InlandWaterways.prototype.setVehicleId = function(vehicleId)
{
    this.vehicleId = vehicleId;
};

InlandWaterways.prototype.getVehicleId = function()
{
    return this.vehicleId;
};

InlandWaterways.prototype.setVehicleName = function(vehicleName)
{
    this.vehicleName = vehicleName;
};

InlandWaterways.prototype.getVehicleName = function()
{
    return this.vehicleName;
};

InlandWaterways.prototype.setSpeedUtilisation = function(speedUtilisation)
{
    this.speedUtilisation = speedUtilisation;
};

InlandWaterways.prototype.getSpeedUtilisation = function()
{
    return this.speedUtilisation;
};

InlandWaterways.prototype.setType = function(type)
{
    this.type = type;
};

InlandWaterways.prototype.getType = function()
{
    return this.type;
};

InlandWaterways.prototype.setLoadFactor = function(loadFactor)
{
    this.loadFactor = loadFactor;
};

InlandWaterways.prototype.getLoadFactor = function()
{
    return this.loadFactor;
};

InlandWaterways.prototype.setLoadFactorContainer = function(loadFactorContainer)
{
    this.loadFactorContainer = loadFactorContainer;
};

InlandWaterways.prototype.getLoadFactorContainer = function()
{
    return this.loadFactorContainer;
};

InlandWaterways.prototype.getFieldList = function()
{
    return new Array("ClassName","VehicleId", "VehicleName", "SpeedUtilisation", "Type", "LoadFactor", "LoadFactorContainer");
};


InlandWaterways.prototype.getClassName = function()
{
    return "InlandWaterways";
};
//--------------------------------------------------------------------------------------------------------------------------------
// RoadValidation
//--------------------------------------------------------------------------------------------------------------------------------

function RoadValidation (prefix, object)
{
    this.prefix = prefix;
    this.road = object; 
}

RoadValidation.prototype.validate = function () 
{
    var emissionClass = new CommonInputValidation(this.prefix + "_emissionClass");
    this.road.setEmissionClass(emissionClass.getInputFieldName());
    
    var lorryClass = new CommonInputValidation(this.prefix + "_lorryClass");
    this.road.setLorryClass(lorryClass.getInputFieldName());
    
    var ferryRouting = new CommonInputValidation(this.prefix + "_ferryRouting");
    this.road.setFerryRouting(ferryRouting.getInputFieldName());
    
    var loadFactor = new CommonInputValidation(this.prefix + "_loadFactor");
    this.road.setLoadFactor(loadFactor.getInputFieldValue());
    var loadFactorValidator = new Validator(loadFactor.getInputField());
    var loadFactorValit = loadFactorValidator.standardCheck();
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.isNumber,"");
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.minValue,0);
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.maxValue,100);
    
    var emptyRunFactor = new CommonInputValidation(this.prefix + "_emptyRunFactor");
    this.road.setEmptyRunFactor(emptyRunFactor.getInputFieldValue());
    var emptyRunFactorValidator = new Validator(emptyRunFactor.getInputField());
    var emptyRunFactorValit = emptyRunFactorValidator.standardCheck();
    emptyRunFactorValit = emptyRunFactorValidator.validate(ValidatorTypes.isNumber,"");
    emptyRunFactorValit = emptyRunFactorValidator.validate(ValidatorTypes.minValue,0);
    emptyRunFactorValit = emptyRunFactorValidator.validate(ValidatorTypes.maxValue,100);
    
    var valid = true;
    
    if(!loadFactorValit
            || !emptyRunFactorValit
            || !new Validator(emissionClass.getInputField()).standardCheck()
            || !new Validator(lorryClass.getInputField()).standardCheck()
            || !new Validator(ferryRouting.getInputField()).standardCheck())
    {
        valid = false;
    }
    
    return valid;
};

RoadValidation.prototype.getRoad = function ()
{
    return this.road;
};//--------------------------------------------------------------------------------------------------------------------------------
// ChainValidation
//--------------------------------------------------------------------------------------------------------------------------------

function ChainValidation (prefix, object)
{
    this.prefix = prefix;
    this.chain = object; 
}

ChainValidation.prototype.validate = function () 
{
    var transportMode = new CommonInputValidation(this.prefix + "_transportMode");
    this.chain.setTransportMode(transportMode.getInputFieldName());
};

ChainValidation.prototype.getChain = function ()
{
    return this.chain;
};
//--------------------------------------------------------------------------------------------------------------------------------
// MainFieldsValidation
//--------------------------------------------------------------------------------------------------------------------------------
function MainFormularValidation (object)
{
    this.mainFormular = object; 
}

MainFormularValidation.prototype.validate = function () 
{ 
    var intermodalTransferType = new CommonInputValidation("intermodalTransferType");
    this.mainFormular.setIntermodalTransferType(intermodalTransferType.getInputFieldName());
    
    var cargoUnit = new CommonInputValidation("cargoUnit");
    this.mainFormular.setCargoUnit(cargoUnit.getInputFieldName());
    
    var cargoWeight = new CommonInputValidation("cargoWeight");
    this.mainFormular.setCargoWeight(cargoWeight.getInputFieldValue());
    var cargoWeightValidator = new Validator(cargoWeight.getInputField());
    var cargoWeightValit = cargoWeightValidator.standardCheck();
    cargoWeightValit = cargoWeightValidator.validate(ValidatorTypes.isNumber,"");
    
    var cargoVolumeWeight = new CommonInputValidation("cargoVolumeWeight");
    this.mainFormular.setCargoVolumeWeight(cargoVolumeWeight.getInputFieldName());
    
    var valid = true;
    if(!new Validator(intermodalTransferType.getInputField()).standardCheck()
            || !new Validator(cargoUnit.getInputField()).standardCheck()
            || !new Validator(cargoVolumeWeight.getInputField()).standardCheck()
            || !cargoWeightValit)
    {
        valid = false;
    }
    
    return valid;
};

MainFormularValidation.prototype.getMainFormular = function ()
{
    return this.mainFormular;
};
//--------------------------------------------------------------------------------------------------------------------------------
// MainFieldsValidation
//--------------------------------------------------------------------------------------------------------------------------------
function MainFieldsValidation (object)
{
    this.mainFields = object; 
}

MainFieldsValidation.prototype.validate = function () 
{ 
    var intermodalTransferType = new CommonInputValidation("intermodalTransferType");
    this.mainFields.setIntermodalTransferType(intermodalTransferType.getInputFieldName());
    
    var cargoUnit = new CommonInputValidation("cargoUnit");
    this.mainFields.setCargoUnit(cargoUnit.getInputFieldName());
    
    var cargoWeight = new CommonInputValidation("cargoWeight");
    this.mainFields.setCargoWeight(cargoWeight.getInputFieldValue());
    var cargoWeightValidator = new Validator(cargoWeight.getInputField());
    var cargoWeightValit = cargoWeightValidator.standardCheck();
    cargoWeightValit = cargoWeightValidator.validate(ValidatorTypes.isNumber,"");
    
    var cargoVolumeWeight = new CommonInputValidation("cargoVolumeWeight");
    this.mainFields.setCargoVolumeWeight(cargoVolumeWeight.getInputFieldName());
    
    var valid = true;
    if(!new Validator(intermodalTransferType.getInputField()).standardCheck()
            || !new Validator(cargoUnit.getInputField()).standardCheck()
            || !new Validator(cargoVolumeWeight.getInputField()).standardCheck()
            || !cargoWeightValit)
    {
        valid = false;
    }
    
    return valid;
};

MainFieldsValidation.prototype.getMainFields = function ()
{
    return this.mainFields;
};
//--------------------------------------------------------------------------------------------------------------------------------
// RailValidation
//--------------------------------------------------------------------------------------------------------------------------------

function RailValidation (prefix, object)
{
    this.prefix = prefix;
    this.rail = object; 
}

RailValidation.prototype.validate = function () 
{
    var trainDriveClass = new CommonInputValidation(this.prefix + "_trainDriveClass");
    this.rail.setTrainDriveClass(trainDriveClass.getInputFieldName());
    
    var trainWeight = new CommonInputValidation(this.prefix + "_trainWeight");
    this.rail.setTrainWeight(trainWeight.getInputFieldValue());
    var trainWeightValidator = new Validator(trainWeight.getInputField());
    var trainWeightValit = trainWeightValidator.standardCheck();
    trainWeightValit = trainWeightValidator.validate(ValidatorTypes.isInt,"");
    trainWeightValit = trainWeightValidator.validate(ValidatorTypes.minValue,1);
    
    var ferryRouting = new CommonInputValidation(this.prefix + "_ferryRouting");
    this.rail.setFerryRouting(ferryRouting.getInputFieldName());
    
    var loadFactor = new CommonInputValidation(this.prefix + "_loadFactor");
    this.rail.setLoadFactor(loadFactor.getInputFieldValue());
    var loadFactorValidator = new Validator(loadFactor.getInputField());
    var loadFactorValit = loadFactorValidator.standardCheck();
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.isNumber,"");
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.minValue,0);
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.maxValue,100);
    
    var emptyRunFactor = new CommonInputValidation(this.prefix + "_emptyRunFactor");
    this.rail.setEmptyRunFactor(emptyRunFactor.getInputFieldValue());
    var emptyRunFactorValidator = new Validator(emptyRunFactor.getInputField());
    var emptyRunFactorValit = emptyRunFactorValidator.standardCheck();
    emptyRunFactorValit = emptyRunFactorValidator.validate(ValidatorTypes.isNumber,"");
    emptyRunFactorValit = emptyRunFactorValidator.validate(ValidatorTypes.minValue,0);
    emptyRunFactorValit = emptyRunFactorValidator.validate(ValidatorTypes.maxValue,100);
    
    var valid = true;
    
    if(!loadFactorValit
            || !emptyRunFactorValit
            || !new Validator(trainDriveClass.getInputField()).standardCheck()
            || !trainWeightValit
            || !new Validator(ferryRouting.getInputField()).standardCheck())
    {
        valid = false;
    }
    
    return valid;
};

RailValidation.prototype.getRail = function ()
{
    return this.rail;
};

//--------------------------------------------------------------------------------------------------------------------------------
// AirValidation
//--------------------------------------------------------------------------------------------------------------------------------
function AirValidation (prefix, object)
{
    this.prefix = prefix;
    this.air = object; 
}

AirValidation.prototype.validate = function () 
{
    var vehicleId = new CommonInputValidation(this.prefix + "_vehicleId");
    this.air.setVehicleId(vehicleId.getInputFieldValue());
    
    var vehicleName = new CommonInputValidation(this.prefix + "_vehicleName");
    this.air.setVehicleName(vehicleName.getInputFieldValue());
    
    var rfiFactor = new CommonInputValidation(this.prefix + "_RFIFactor");
    this.air.setRFIFactor(rfiFactor.getInputFieldChecked());
    
    /*
     * check bellyFreight
     */
    var bellyFreightValit = true;
    var bellyFreightCB = new CommonInputValidation(this.prefix + "_bellyFreightCB");
    this.air.setBellyFreightCB(bellyFreightCB.getInputFieldChecked());
    if(this.air.getBellyFreightCB())
    {
        var bellyFreight = new CommonInputValidation(this.prefix + "_bellyFreight");
        this.air.setBellyFreight(bellyFreight.getInputFieldValue());
        var bellyFreightValidator = new Validator(bellyFreight.getInputField());
        bellyFreightValit = bellyFreightValidator.standardCheck();
        bellyFreightValit = bellyFreightValidator.validate(ValidatorTypes.isNumber,"");
        bellyFreightValit = bellyFreightValidator.validate(ValidatorTypes.minValue,0);
        bellyFreightValit = bellyFreightValidator.validate(ValidatorTypes.maxValue,100);
    }
    /*
     * check loadFactor
     */
    var loadFactor = new CommonInputValidation(this.prefix + "_loadFactor");
    this.air.setLoadFactor(loadFactor.getInputFieldValue());
    var loadFactorValidator = new Validator(loadFactor.getInputField());
    var loadFactorValit = loadFactorValidator.standardCheck();
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.isNumber,"");
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.minValue,0);
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.maxValue,100);
    
    var valid = true;
    if(!loadFactorValit
            || !bellyFreightValit
            || (!new Validator(vehicleId.getInputField()).standardCheck()))
    {
        valid = false;
    }
    
    return valid;
};

AirValidation.prototype.getAir = function()
{
    return this.air;
};
//--------------------------------------------------------------------------------------------------------------------------------
// TransferPointsValidation
//--------------------------------------------------------------------------------------------------------------------------------

function TransferPointsValidation (prefix, object)
{
    this.prefix = prefix;
    this.transferPoints = object; 
}

TransferPointsValidation.prototype.validate = function () 
{
    var sourceLocationId = new CommonInputValidation(this.prefix + "_sourceLocationId");
    this.transferPoints.setSourceLocationId(sourceLocationId.getInputFieldValue());
    
    var sourceLocationName = new CommonInputValidation(this.prefix + "_sourceLocationName");
    this.transferPoints.setSourceLocationName(sourceLocationName.getInputFieldValue());
    
    var sourceLocationType = new CommonInputValidation(this.prefix + "_sourceLocationType");
    this.transferPoints.setSourceLocationType(sourceLocationType.getInputFieldValue());
    
    var targetLocationId = new CommonInputValidation(this.prefix + "_targetLocationId");
    this.transferPoints.setTargetLocationId(targetLocationId.getInputFieldValue());
    
    var targetLocationName = new CommonInputValidation(this.prefix + "_targetLocationName");
    this.transferPoints.setTargetLocationName(targetLocationName.getInputFieldValue());
    
    var targetLocationType = new CommonInputValidation(this.prefix + "_targetLocationType");
    this.transferPoints.setTargetLocationType(targetLocationType.getInputFieldValue());
    
    var valid = true;
    if(!new Validator(sourceLocationId.getInputField()).standardCheck()
            && !new Validator(sourceLocationName.getInputField()).standardCheck()
            && !new Validator(targetLocationId.getInputField()).standardCheck()
            && !new Validator(targetLocationName.getInputField()).standardCheck())
    {
        valid = false;
    }
    
    return valid;
};

TransferPointsValidation.prototype.getTransferPoints = function ()
{
    return this.transferPoints;
};
//--------------------------------------------------------------------------------------------------------------------------------
// LocationValidation
//--------------------------------------------------------------------------------------------------------------------------------
function LocationValidation (prefix, object)
{
    this.prefix = prefix;
    this.location = object; 
}

LocationValidation.prototype.validate = function () 
{ 
    var id = new CommonInputValidation(this.prefix + "_id");
    this.location.setId(id.getInputFieldValue());
    
    var name = new CommonInputValidation(this.prefix + "_name");
    this.location.setName(name.getInputFieldName());
    
    var type = new CommonInputValidation(this.prefix + "_type");
    this.location.setType(type.getInputFieldName());
    
    var sidetrack = new CommonInputValidation(this.prefix + "_sidetrack");
    this.location.setSidetrack(sidetrack.getInputFieldChecked());
    
    var harbour = new CommonInputValidation(this.prefix + "_harbour");
    this.location.setHarbour(harbour.getInputFieldChecked());
    
    var longitude = new CommonInputValidation(this.prefix + "_longitude");
    this.location.setLongitude(longitude.getInputFieldValue());
    
    var latitude = new CommonInputValidation(this.prefix + "_latitude");
    this.location.setLatitude(latitude.getInputFieldValue());
    
    var valid = true;
    if(document.getElementById(this.prefix + "_show").style.display == "none")
    {
        valid = false;
        document.getElementById(this.prefix + "_name").style.backgroundColor = "#FFB2B2";
    }
    
    if(!new Validator(id.getInputField()).standardCheck()
            || (!new Validator(name.getInputField()).standardCheck()
                && !new Validator(type.getInputField()).standardCheck())
            || !new Validator(longitude.getInputField()).standardCheck()
            || !new Validator(latitude.getInputField()).standardCheck())
    {
        valid = false;
    }
    
    return valid;
};

LocationValidation.prototype.getLocation = function ()
{
    return this.location;
};

//--------------------------------------------------------------------------------------------------------------------------------
// InlandWaterwaysValidation
//--------------------------------------------------------------------------------------------------------------------------------

function InlandWaterwaysValidation (prefix, object)
{
    this.prefix = prefix;
    this.inlandWaterways = object; 
}

InlandWaterwaysValidation.prototype.validate = function () 
{ 
    var vehicleId = new CommonInputValidation(this.prefix + "_vehicleId");
    this.inlandWaterways.setVehicleId(vehicleId.getInputFieldValue());
    
    var vehicleName = new CommonInputValidation(this.prefix + "_vehicleName");
    this.inlandWaterways.setVehicleName(vehicleName.getInputFieldValue());
    
    var type = new CommonInputValidation(this.prefix + "_type");
    this.inlandWaterways.setType(type.getInputFieldName());
    
    /*
     * check loadFactor
     */
    var loadFactor = new CommonInputValidation(this.prefix + "_loadFactor");
    this.inlandWaterways.setLoadFactor(loadFactor.getInputFieldValue());
    var loadFactorValidator = new Validator(loadFactor.getInputField());
    var loadFactorValit = loadFactorValidator.standardCheck();
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.isNumber,"");
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.minValue,0);
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.maxValue,100);
    
    /*
     * check speedUtilisation
     */
    var speedUtilisation = new CommonInputValidation(this.prefix + "_speedUtilisation");
    this.inlandWaterways.setSpeedUtilisation(speedUtilisation.getInputFieldValue());
    var speedUtilisationValidator = new Validator(speedUtilisation.getInputField());
    var speedUtilisationValit = speedUtilisationValidator.standardCheck();
    speedUtilisationValit = speedUtilisationValidator.validate(ValidatorTypes.isNumber,"");
    speedUtilisationValit = speedUtilisationValidator.validate(ValidatorTypes.minValue,0);
    speedUtilisationValit = speedUtilisationValidator.validate(ValidatorTypes.maxValue,30);
    
    /*
     * check loadFactorContainer
     */
    var loadFactorContainer = new CommonInputValidation(this.prefix + "_loadFactorContainer");
    this.inlandWaterways.setSpeedUtilisation(loadFactorContainer.getInputFieldValue());
    var loadFactorContainerValidator = new Validator(loadFactorContainer.getInputField());
    var loadFactorContainerValit = loadFactorContainerValidator.standardCheck();
    loadFactorContainerValit = loadFactorContainerValidator.validate(ValidatorTypes.isNumber,"");
    loadFactorContainerValit = loadFactorContainerValidator.validate(ValidatorTypes.minValue,0);
    loadFactorContainerValit = loadFactorContainerValidator.validate(ValidatorTypes.maxValue,30);
    
    var valid = true;
    if(!loadFactorValit
            || !speedUtilisationValit
            || !loadFactorContainerValit
            || !new Validator(vehicleId.getInputField()).standardCheck()
            || !new Validator(vehicleName.getInputField()).standardCheck()
            || !new Validator(type.getInputField()).standardCheck())
    {
        valid = false;
    }
    
    return valid;
};

InlandWaterwaysValidation.prototype.getInlandWaterways = function()
{
    return this.inlandWaterways;
};//--------------------------------------------------------------------------------------------------------------------------------
// SeaValidation
//--------------------------------------------------------------------------------------------------------------------------------

function SeaValidation (prefix, object)
{
    this.prefix = prefix;
    this.sea = object; 
}

SeaValidation.prototype.validate = function () 
{ 
    var vehicleId = new CommonInputValidation(this.prefix + "_vehicleId");
    this.sea.setVehicleId(vehicleId.getInputFieldValue());
    
    var vehicleName = new CommonInputValidation(this.prefix + "_vehicleName");
    this.sea.setVehicleName(vehicleName.getInputFieldValue());
    
    var vehicleType = new CommonInputValidation(this.prefix + "_vehicleType");
    this.sea.setVehicleType(vehicleType.getInputFieldName());
    
    /*
     * check loadFactor
     */
    var loadFactor = new CommonInputValidation(this.prefix + "_loadFactor");
    this.sea.setLoadFactor(loadFactor.getInputFieldValue());
    var loadFactorValidator = new Validator(loadFactor.getInputField());
    var loadFactorValit = loadFactorValidator.standardCheck();
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.isNumber,"");
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.minValue,0);
    loadFactorValit = loadFactorValidator.validate(ValidatorTypes.maxValue,100);
    
    /*
     * check speedUtilisation
     */
    var speedUtilisation = new CommonInputValidation(this.prefix + "_speedUtilisation");
    this.sea.setSpeedUtilisation(speedUtilisation.getInputFieldValue());
    var speedUtilisationValidator = new Validator(speedUtilisation.getInputField());
    var speedUtilisationValit = speedUtilisationValidator.standardCheck();
    speedUtilisationValit = speedUtilisationValidator.validate(ValidatorTypes.isNumber,"");
    speedUtilisationValit = speedUtilisationValidator.validate(ValidatorTypes.minValue,0);
    speedUtilisationValit = speedUtilisationValidator.validate(ValidatorTypes.maxValue,30);
    
    /*
     * check loadFactorContainer
     */
    var loadFactorContainer = new CommonInputValidation(this.prefix + "_loadFactorContainer");
    this.sea.setLoadFactorContainer(loadFactorContainer.getInputFieldValue());
    var loadFactorContainerValidator = new Validator(loadFactorContainer.getInputField());
    var loadFactorContainerValit = loadFactorContainerValidator.standardCheck();
    loadFactorContainerValit = loadFactorContainerValidator.validate(ValidatorTypes.isNumber,"");
    loadFactorContainerValit = loadFactorContainerValidator.validate(ValidatorTypes.minValue,0);
    loadFactorContainerValit = loadFactorContainerValidator.validate(ValidatorTypes.maxValue,30);
    
    var valid = true;
    if(!loadFactorValit
            || !speedUtilisationValit
            || !loadFactorContainerValit
            || (this.sea.getVehicleId() == null
                && this.sea.getVehicleName() == null)
            || this.sea.getVehicleType() == null)
    {
        valid = false;
    }
    
    return valid;
};

SeaValidation.prototype.getSea = function()
{
    return this.sea;
};//--------------------------------------------------------------------------------------------------------------------------------
// CommonInputValidation
//--------------------------------------------------------------------------------------------------------------------------------
function CommonInputValidation(inputFieldId)
{
    this.field = document.getElementById(inputFieldId);
}

CommonInputValidation.prototype.getInputField = function()
{
    var inputField = null;
    if(this.field != null)
    {
        inputField = this.field;
    }
    
    return inputField;
};

CommonInputValidation.prototype.getInputFieldType = function()
{
    var type = null;
    if(this.field != null)
    {
        type = this.field.type;
    }
    
    return type;
};

CommonInputValidation.prototype.getInputFieldName = function()
{
    var name = null;
    if(this.field != null)
    {
        name = this.field.name;
    }
    
    return name;
};

CommonInputValidation.prototype.getInputFieldValue = function()
{
    var value = null;
    if(this.field != null)
    {
        var expressionFloat = /^\d+((\.|\,)?\d+)?$/;
        if(expressionFloat.test(this.field.value))
        {
            value = parseFloat(this.field.value);
        }
        else
        {
            value = this.field.value;
        }
    }
    return value;
};

CommonInputValidation.prototype.getInputFieldChecked = function()
{
    var value = false;
    if(this.field != null)
    {
        value = this.field.checked;
    }
    return value;
};// --------------------------------------------------------------------------------------------------------------------------------
// TransportChain
// --------------------------------------------------------------------------------------------------------------------------------
function TransportChain (id, originLocation, destinationLocation, transportMode)
{
    this.id = id;
    this.sectionList = new Array();
    this.sectionIndex = 0;
    this.transportMode = transportMode;
    
    this.init(originLocation, destinationLocation);
    this.transferpointsControl = new TransferpointsControl();
}

TransportChain.prototype.init = function(originLocation, destinationLocation)
{
    var transportChainView = new TransportChainView(this.id, this.id + 1, this.transportMode);
    transportChainView.createChainContent();
    
    var section = new Section(this.sectionIndex, "tc_" + this.id + "_sec_" + this.sectionIndex);
    section.setTransportMode(new Road());
    section.setSourceLocation(originLocation);
    originLocation.registerObserver(section);
    section.setTargetLocation(destinationLocation);
    destinationLocation.registerObserver(section);
    section.registerObserver(this);
    this.sectionList.push(section);
    this.sectionIndex++;
};

TransportChain.prototype.addSection = function(id)
{
    var newSection = null;
    for(var index = 0; index < this.sectionList.length; index++)
    {
        var section = this.sectionList[index];
        
        if(section != null)
        {
            if(section.getId() === id)
            {
                var newLocation = locationList.getNewLocation();
                newSection = new Section(this.sectionIndex, "tc_" + this.id + "_sec_" + this.sectionIndex);
            
                var updateTargetLocation = section.getTargetLocation();
            
                newSection.setTargetLocation(updateTargetLocation);
                updateTargetLocation.unregisterObserver(section);
                updateTargetLocation.registerObserver(newSection);
            
                section.setTargetLocation(newLocation);
                newLocation.registerObserver(section);
            
                newSection.setSourceLocation(newLocation);
                newLocation.registerObserver(newSection);
            
                newSection.registerObserver(this);
            
                this.calculateTransferPoints(section);
            
                /* create via view */
                var postSectionId = this.findPostSectionId(index);
                            
                var sectionView = new SectionView(this.id, newLocation.getLocationId(), this.sectionIndex, postSectionId);
                sectionView.update();
            
                var roadValidation = new RoadValidation("tc_" + this.id + "_sec_" + newSection.getId(), new Road());
                roadValidation.validate();
                newSection.setTransportMode(roadValidation.getRoad());
            
                this.sectionIndex++;
            }
        }
    }
    this.sectionList.push(newSection);
};

TransportChain.prototype.deleteSection = function(id)
{
    var newSectionList = new Array();
    for(var index = 0; index < this.sectionList.length; index++)
    {
        var section = this.sectionList[index];
        if(section == null)
        {
            newSectionList.push(null);
        }
        else
        {
            if(section.getId() == id)
            {
                var removedLocation = section.getSourceLocation();
                removedLocation.unregisterObserver(section);
                section.getTargetLocation().unregisterObserver(section);
                removedLocation.updateDependencies(section);
                section = null;
            }
            newSectionList.push(section);
        }
    }
    this.sectionList = newSectionList;
    
    var sectionView = new SectionView(this.id, null, id, null);
    sectionView.deleteSectionView();
};

TransportChain.prototype.getSectionList = function()
{
    return this.sectionList;
};

TransportChain.prototype.getId = function()
{
    return this.id;
};

TransportChain.prototype.notify = function(section)
{
    if(section.getTransportMode() instanceof Road)
    {
        var mainFieldsValidation = new MainFieldsValidation(new MainFields());
        mainFieldsValidation.validate();
        new TransportModeView(this.id, section.getId(), "Road", mainFieldsValidation.getMainFields().getCargoUnit()).update();
    }
    this.calculateTransferPoints(section);
};

TransportChain.prototype.findPostSectionId = function(SectionIndex)
{
    var postSectionId = null;
    
    for(var index = SectionIndex+1; index < this.sectionList.length; index++)
    {
        var section = this.sectionList[parseInt(index)+1];
        if(section != null)
        {
            postSectionId = section.getId();
        }
    }
    return postSectionId;
};

TransportChain.prototype.calculateTransferPoints = function(section)
{
    section.setSourceTransferpoint(locationList.getNewLocation());
    section.setTargetTransferpoint(locationList.getNewLocation());
    
    this.transferpointsControl.setSourceTransferpoint(section.getSourceTransferpoint());
    this.transferpointsControl.setTargetTransferpoint(section.getTargetTransferpoint());
    
    this.transferpointsControl.calculate(section, this.id);
};
// --------------------------------------------------------------------------------------------------------------------------------
// LocationList
// --------------------------------------------------------------------------------------------------------------------------------
function LocationList ()
{
    this.list = new Array();
    this.list.push(new Location(0));
    this.list.push(new Location(1));
    this.locationIndex = 2;
}

LocationList.prototype.getNewLocation = function()
{
    var newLocation = new Location(this.locationIndex);
    this.locationIndex++;
    this.list.push(newLocation);
    return newLocation;
};

LocationList.prototype.reset = function()
{
    var newList = new Array();
    newList.push(this.list[0]);
    newList.push(this.list[1]);
    this.list[0].resetObservers();
    this.list[1].resetObservers();
    this.list = newList;
    this.locationIndex = 2;
};

LocationList.prototype.searchLocation = function(id)
{
    var returnLocation = null;
    for(var index = 0; index < this.list.length; index++)
    {
        var location = this.list[index];
        if(location.getLocationId() == id)
        {
            returnLocation = location;
            break;
        }
    }
    return returnLocation;
};

LocationList.prototype.removeLocation = function(id)
{
    var newList = new Array();
    for(var index = 0; index < this.list.length; index++)
    {
        var location = this.list[index];
        if(location.getLocationId() != id
                && location.getLocationId() <= 1)
        {
            newList.push(location);
        }
        else
        {
            location = null;
        }
    }
    this.list = newList;
};

LocationList.prototype.updateLocationList = function()
{
    for(var index = 0; index < this.list.length; index++)
    {
        if(document.getElementById("location_" + index + "_location")
                && this.list[index].getId() == null && this.list[index].getType() != "Coordinates")
        {
            resultControl.setInfoMessage("<br><br><b>Ortsangaben wurden automatisch vervollst&auml;ndigt. <br>Bitte klicken Sie noch einmal auf den \"Berechnen\" Button.</b>");
            new LocationItemControl().findLocationByName(this.list[index].getLocationId());
            this.list[index].updateData("location_" + this.list[index].getLocationId());
        }
    }
};
// --------------------------------------------------------------------------------------------------------------------------------
// Section
// --------------------------------------------------------------------------------------------------------------------------------
function Section (id, prefix)
{
    this.id = id;
    this.sourceLocation = null;
    this.targetLocation = null;
    this.transportMode = null;
    this.sourceTransferpoint = null;
    this.targetTransferpoint = null;
    this.valid = null;
    this.sectionPrefix = prefix;
    this.chainName = null;
    
    this.observerObjects = new Array();
}

Section.prototype.changeTransportMode = function(transportModeType, transportChainId, cargoUnit)
{
    var transportModeView = new TransportModeView(transportChainId, this.id, transportModeType, cargoUnit);
    transportModeView.update();
    
    if(transportModeType == "Road")
    {
        var roadValidation = new RoadValidation(this.sectionPrefix, new Road());
        roadValidation.validate();
        this.transportMode = roadValidation.getRoad();
    }
    else if(transportModeType == "Rail")
    {
        var railValidation = new RailValidation(this.sectionPrefix, new Rail());
        railValidation.validate();
        this.transportMode = railValidation.getRail();
    }
    else if(transportModeType == "Air")
    {
        var airValidation = new AirValidation(this.sectionPrefix, new Air());
        airValidation.validate();
        this.transportMode = airValidation.getAir();
    }
    else if(transportModeType == "Sea")
    {
        var seaValidation = new SeaValidation(this.sectionPrefix, new Sea());
        seaValidation.validate();
        this.transportMode = seaValidation.getSea();
    }
    else if(transportModeType == "InlandWaterways")
    {
        var inlandWaterwaysValidation = new InlandWaterwaysValidation(this.sectionPrefix, new InlandWaterways());
        inlandWaterwaysValidation.validate();
        this.transportMode = inlandWaterwaysValidation.getInlandWaterways();
    }
    
    this.notifyObserver();
};

Section.prototype.updateTransportMode = function()
{
    this.validateTransportMode();
    this.notifyObserver();
};

Section.prototype.validateTransportMode = function()
{
    if(this.transportMode instanceof Road)
    {
        var roadValidation = new RoadValidation(this.sectionPrefix, this.transportMode);
        roadValidation.validate();
        this.transportMode = roadValidation.getRoad();
    }
    else if(this.transportMode instanceof Rail)
    {
        var railValidation = new RailValidation(this.sectionPrefix, this.transportMode);
        railValidation.validate();
        this.transportMode = railValidation.getRail();
    }
    else if(this.transportMode instanceof Air)
    {
        var airValidation = new AirValidation(this.sectionPrefix, this.transportMode);
        airValidation.validate();
        this.transportMode = airValidation.getAir();
    }
    else if(this.transportMode instanceof Sea)
    {
        var seaValidation = new SeaValidation(this.sectionPrefix, this.transportMode);
        seaValidation.validate();
        this.transportMode = seaValidation.getSea();
    }
    else if(this.transportMode instanceof InlandWaterways)
    {
        var inlandWaterwaysValidation = new InlandWaterwaysValidation(this.sectionPrefix, this.transportMode);
        inlandWaterwaysValidation.validate();
        this.transportMode = inlandWaterwaysValidation.getInlandWaterways();
    }
};

Section.prototype.validate = function()
{
    if(document.getElementById(this.sectionPrefix + "_name") != null)
    {
        this.setChainName(document.getElementById(this.sectionPrefix + "_name").value);
    }
};

Section.prototype.getId = function()
{
    return this.id;
};

Section.prototype.getChainName = function()
{
    return this.chainName;
};

Section.prototype.setChainName = function(chainName)
{
    this.chainName = chainName;
};

Section.prototype.getTransportMode = function()
{
    return this.transportMode;
};

Section.prototype.setTransportMode = function(transportMode)
{
    this.transportMode = transportMode;
};

Section.prototype.getSourceLocation = function()
{
    return this.sourceLocation;
};

Section.prototype.setSourceLocation = function(sourceLocation)
{
    this.sourceLocation = sourceLocation;
};

Section.prototype.getTargetLocation = function()
{
    return this.targetLocation;
};

Section.prototype.setTargetLocation = function(targetLocation)
{
    this.targetLocation = targetLocation;
};

Section.prototype.getSourceTransferpoint = function()
{
    return this.sourceTransferpoint;
};

Section.prototype.setSourceTransferpoint = function(sourceTransferpoint)
{
    this.sourceTransferpoint = sourceTransferpoint;
};

Section.prototype.getTargetTransferpoint = function()
{
    return this.targetTransferpoint;
};

Section.prototype.setTargetTransferpoint = function(targetTransferpoint)
{
    this.targetTransferpoint = targetTransferpoint;
};


Section.prototype.notify = function()
{
    // Transferpunkte berechnen
    this.notifyObserver();
    
    this.validate();
};

Section.prototype.getFieldList = function()
{
    this.validateTransportMode();
    return new Array("Id","ChainName","SourceLocation","TargetLocation","TransportMode","SectionPrefix","SourceTransferpoint","TargetTransferpoint");
};

Section.prototype.getSectionPrefix = function()
{
    return this.sectionPrefix;
};

Section.prototype.registerObserver = function(object)
{
    this.observerObjects.push(object);
};

Section.prototype.unregisterObserver = function(object)
{
    this.observerObjects = this.observerObjects.filter(
        function(loopObject)
        {
            if(loopObject !== object)
            {
                return loopObject;
            }
        }
    );
};

Section.prototype.notifyObserver = function()
{
    var scope = this || window;
    var observerObjectsLength = this.observerObjects.length;
    
    for(var index = 0; index < observerObjectsLength; index++)
    {
        this.observerObjects[index].notify(this);
    }
};

Section.prototype.updateLocation = function(newTargetLocation)
{
    this.getTargetLocation().unregisterObserver(this);
    this.setTargetLocation(newTargetLocation);
    this.getTargetLocation().registerObserver(this);
    this.notify();
};
// --------------------------------------------------------------------------------------------------------------------------------
// MainFieldsControl
// --------------------------------------------------------------------------------------------------------------------------------
function MainFieldsControl()
{
    
}

MainFieldsControl.prototype.update = function(cargoType)
{
    if(viewModeControl.getInputMode() == "extended")
    {
        var chainsLength = transportChainsControl.getTransportChainList().length;
        for(var chainIndex = 0; chainIndex < chainsLength; chainIndex++)
        {
            var tc = transportChainsControl.getTransportChainList()[chainIndex];
            if(tc != null)
            {
                var sectionLength = transportChainsControl.getTransportChainList()[chainIndex].getSectionList().length;
                for(var sectionIndex = 0; sectionIndex < sectionLength; sectionIndex++)
                {
                    var section = transportChainsControl.getTransportChainList()[chainIndex].getSectionList()[sectionIndex];
                    if(cargoType == "cargoVolumeWeight"
                            && (section.getTransportMode() instanceof Road
                            || section.getTransportMode() instanceof Rail))
                    {
                        this.updateVolumeWeights(section.getSectionPrefix(), section.getTransportMode());
                        section.validateTransportMode();
                    }
                    else if(cargoType == "cargoUnit"
                            && (section.getTransportMode() instanceof Sea
                                    || section.getTransportMode() instanceof InlandWaterways))
                    {
                        this.updateCargoUnits(section, transportChainsControl.getTransportChainList()[chainIndex].getId(), section.getSectionPrefix(), section.getTransportMode());
                    }
                }
            }
        }
    }
};

MainFieldsControl.prototype.updateCargoUnits = function(section, chainId, prefix, transportMode)
{
    var mainFieldsValidation = new MainFieldsValidation(new MainFields());
    mainFieldsValidation.validate();
    var mainFields = mainFieldsValidation.getMainFields();
    if(mainFields.getCargoUnit() == "teu")
    {
        // Anzeige des Feldes fuer release rausgenommen
        //document.getElementById("weight_tpTeu").style.display = "block";
    }
    else
    {
        document.getElementById("weight_tpTeu").style.display = "none";
    }
    
    if(transportMode instanceof Sea)
    {
        section.changeTransportMode("Sea", chainId, mainFields.getCargoUnit());
        //section.updateTransportMode();
    }
    if(transportMode instanceof InlandWaterways
        && mainFields.getCargoUnit() == "teu"
        && document.getElementById(prefix + "_loadFactorContainer_field") != null)
    {
        document.getElementById(prefix + "_loadFactorContainer_field").style.display = "block";
        document.getElementById("weight_tpTeu").style.display = "block";
    }
    else if(document.getElementById(prefix + "_loadFactorContainer_field") != null)
    {
        document.getElementById(prefix + "_loadFactorContainer_field").style.display = "none";
        document.getElementById("weight_tpTeu").style.display = "none";
    }
};

MainFieldsControl.prototype.updateVolumeWeights = function(prefix, transportMode)
{
    var cargoVolumeWeightInputValue = document.getElementById('cargoVolumeWeight').name;
    var loadFactorInput = document.getElementById(prefix + '_loadFactor');
    var emptyRunFactorInput = document.getElementById(prefix + '_emptyRunFactor');
    
    if("Heavy" == cargoVolumeWeightInputValue)
    {
        if(transportMode instanceof Road)
        {
            loadFactorInput.value = "100";
            emptyRunFactorInput.value = "60";
        }
        if(transportMode instanceof Rail)
        {
            loadFactorInput.value = "100";
            emptyRunFactorInput.value = "80";
        }
    }
    else if("Average" == cargoVolumeWeightInputValue)
    {
        if(transportMode instanceof Road)
        {
            loadFactorInput.value = "60";
            emptyRunFactorInput.value = "20";
        }
        if(transportMode instanceof Rail)
        {
            loadFactorInput.value = "60";
            emptyRunFactorInput.value = "50";
        }
    }
    else if("Light" == cargoVolumeWeightInputValue)
    {
        if(transportMode instanceof Road)
        {
            loadFactorInput.value = "30";
            emptyRunFactorInput.value = "10";
        }
        if(transportMode instanceof Rail)
        {
            loadFactorInput.value = "30";
            emptyRunFactorInput.value = "20";
        }
    }
};

// --------------------------------------------------------------------------------------------------------------------------------
// TransferpointsControl
// --------------------------------------------------------------------------------------------------------------------------------
function TransferpointsControl()
{
    this.jsonObject = null;
    this.sourceTransferpoint = null;
    this.targetTransferpoint = null;
}

TransferpointsControl.prototype.params = function ()
{
    var result = "";
    
    result += "&lang=" + fixedEncodeURIComponent(pageProperties.getLanguage());
    result += "&json=" + this.jsonObject;
    
    return result;
};

TransferpointsControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(pageProperties.getPath() + "/transferpoint.jsp");
    ajaxRequest.setData(this.params());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Xml);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

TransferpointsControl.prototype.responseCallback = function (response)
{
    var transferpoints = response.getElementsByTagName("transferpoints")[0].getElementsByTagName("transferpoint")[0];
    if(transferpoints != null)
    {
        var defaultVehicleId = null;
        
        var prefix = this.validateElement(transferpoints.getElementsByTagName("prefix")[0]);
        var transportMode = this.validateElement(transferpoints.getElementsByTagName("transportMode")[0]);
        var chainId = this.validateElement(transferpoints.getElementsByTagName("chainId")[0]);
        var sectionId = this.validateElement(transferpoints.getElementsByTagName("sectionId")[0]);
        var sourceDivId = prefix + "_tp_source";
        var sourceInputId = prefix + "_sourceLocation";
        var targetDivId = prefix + "_tp_target";
        var targetInputId = prefix + "_targetLocation";
        
        /*
         * remove transferpoint divs from a calculation before
         */
        if(document.getElementById(sourceDivId) != null)
        {
            document.getElementById(prefix + "_source_tp").removeChild(document.getElementById(sourceDivId));
        }
        if(document.getElementById(targetDivId) != null)
        {
            document.getElementById(prefix + "_target_tp").removeChild(document.getElementById(targetDivId));
        }
        
        var error = this.validateElement(transferpoints.getElementsByTagName("error")[0]);
        if(error != null)
        {
            var errorChild = this.createErrorChild(sourceDivId, error);
            document.getElementById(prefix + "_source_tp").appendChild(errorChild);
        }
        
        if(transferpoints.getElementsByTagName("defaultVehicleId")[0] != null)
        {
            defaultVehicleId = this.validateElement(transferpoints.getElementsByTagName("defaultVehicleId")[0]);
            var defaultVehicleName = this.validateElement(transferpoints.getElementsByTagName("defaultVehicleName")[0]);
            var defaultVehicleTransportType = this.validateElement(transferpoints.getElementsByTagName("defaultVehicleTransportType")[0]);
            var defaultVehicleLoadFactor = this.validateElement(transferpoints.getElementsByTagName("defaultVehicleLoadFactor")[0]);
            var sourceLocationId = this.validateElement(transferpoints.getElementsByTagName("sourceLocationId")[0]);
            var sourceLocation = this.validateElement(transferpoints.getElementsByTagName("sourceLocation")[0]);
            var sourceCountry = this.validateElement(transferpoints.getElementsByTagName("sourceLocationCountry")[0]);
            var sourceLocationType = this.validateElement(transferpoints.getElementsByTagName("sourceLocationType")[0]);
            var sourceLocationLatitude = this.validateElement(transferpoints.getElementsByTagName("sourceLocationLatitude")[0]);
            var sourceLocationLongitude = this.validateElement(transferpoints.getElementsByTagName("sourceLocationLongitude")[0]);
            var targetLocationId = this.validateElement(transferpoints.getElementsByTagName("targetLocationId")[0]);
            var targetLocation = this.validateElement(transferpoints.getElementsByTagName("targetLocation")[0]);
            var targetCountry = this.validateElement(transferpoints.getElementsByTagName("targetLocationCountry")[0]);
            var targetLocationType = this.validateElement(transferpoints.getElementsByTagName("targetLocationType")[0]);
            var targetLocationLatitude = this.validateElement(transferpoints.getElementsByTagName("targetLocationLatitude")[0]);
            var targetLocationLongitude = this.validateElement(transferpoints.getElementsByTagName("targetLocationLongitude")[0]);
            var title = this.validateElement(transferpoints.getElementsByTagName("title")[0]);
            
            var splitedPrefix = prefix.split("_");
            
            if(title.length > 0)
            {
                var sourceChild = this.createTransferpointChild(sourceDivId, sourceInputId, sourceLocationId, sourceLocation, sourceLocationType, title, null, sourceLocationLatitude, sourceLocationLongitude);
                document.getElementById(prefix + "_source_tp").appendChild(sourceChild);
                
                var targetChild = this.createTransferpointChild(targetDivId, targetInputId, targetLocationId, targetLocation, targetLocationType, title, null, targetLocationLatitude, targetLocationLongitude);
                document.getElementById(prefix + "_target_tp").appendChild(targetChild);
                
                
                if(document.getElementById(prefix + "_vehicleId") != null)
                {
                    document.getElementById(prefix + "_vehicleId").value = defaultVehicleId;
                    document.getElementById(prefix + "_vehicleName").value = decodeURIComponent(defaultVehicleName);
                    document.getElementById(prefix + "_vehicleName").style.color = "#000000";
                }
                
                var transportType = document.getElementById(prefix + "_vehicleType");
                var loadFactor = document.getElementById(prefix + "_loadFactor");
//                if(transportType != null)
//                {
//                    if(defaultVehicleTransportType != null)
//                    {
//                        transportType.value = defaultVehicleTransportType;
//                    }
//                    else
//                    {
//                        transportType.value = "";
//                    }
//                }
                if(loadFactor != null)
                {
                    if(defaultVehicleLoadFactor != null
                            && defaultVehicleLoadFactor != "")
                    {
                        loadFactor.value = defaultVehicleLoadFactor;
                    }
                }
            }
            
            var section = transportChainsControl.getTransportChainList()[chainId].getSectionList()[sectionId];
            var sourceTransferpoint = section.getSourceTransferpoint();
            var targetTransferpoint = section.getTargetTransferpoint();
            
            var sourceLocationTP = locationList.searchLocation(sourceTransferpoint.getLocationId());
            var targetLocationTP = locationList.searchLocation(targetTransferpoint.getLocationId());
            
            sourceLocationTP.updateDataByParameters(sourceLocationId, sourceLocation, sourceLocationType);
            targetLocationTP.updateDataByParameters(targetLocationId, targetLocation, targetLocationType);
            
            section.setSourceTransferpoint(sourceLocationTP);
            section.setTargetTransferpoint(targetLocationTP);
        }
        
        if(defaultVehicleId != null)
        {
            var vehiclesListControl = new VehiclesListControl(pageProperties.getPath() + "/vehicles_list.jsp", prefix, pageProperties.getLanguage(), transportMode, chainId, sectionId);
            vehiclesListControl.update();
        }
    }
};

TransferpointsControl.prototype.validateElement = function (element)
{
    if(element != null 
            && element.firstChild != null)
    {
        return element.firstChild.nodeValue;
    }
    else
    {
        return null;
    }
};

TransferpointsControl.prototype.createTransferpointChild = function (id, inputId, locationId, location, locationType, title, width, latitude, longitude)
{
    var child = document.createElement("div");
    child.id = id;
    child.style.cssFloat = "right";
    child.style.styleFloat = "right";
    child.style.border = "1px solid #777";
    child.style.backgroundColor = "#CAE2FF";
    child.style.marginTop = "2px";
    child.style.marginBottom = "2px";
    child.style.marginRight = "2px";
    child.style.width = "718px";
    child.innerHTML = "<input id=\""+ inputId +"Id\" type=\"hidden\" value=\"" + locationId + "\" />" +
                      "<input id=\""+ inputId +"Name\" type=\"hidden\" value=\"[" + locationType + "] " + location + "\" />" +
                      "<span style=\"font-weight: bold; padding-left: 38px;\">" + title + "</span>" +
                      "<span style=\"padding-left: 36px;\">[" + locationType + "] " + location + "" + 
                      "<img title=\"Google Maps\" style=\"cursor: pointer; margin-left:5px;\"" + 
                      "src=\"../" + pageProperties.getPath().replace("jspa", "", "i") + "images/flag.png\" width=\"12\" height=\"12\"" + 
                      "onclick=\"googleMapCoordinates.insertLocation('distance_point'," + latitude + ", " + longitude + ");googleMapCoordinates.showLocation('distance_point','" + latitude + " / " + longitude + "');\"/></span>";
    return child;
};

TransferpointsControl.prototype.createErrorChild = function (id, message, width)
{
    var child = document.createElement("div");
    child.id = id;
    child.style.cssFloat = "right";
    child.style.styleFloat = "right";
    child.style.border = "1px solid #777";
    child.style.backgroundColor = "#FFC0C0";
    child.style.marginTop = "2px";
    child.style.marginBottom = "2px";
    child.style.width = "718px";
    child.innerHTML = "<span style=\"font-weight: bold; padding-left: 38px;\">Error</span>" +
                      "<span style=\"padding-left: 36px;\">" + message + "</span>";
    return child;
};

TransferpointsControl.prototype.calculate = function (section, chainId)
{
    var jsonFormatter = new JsonFormatter();
    var mainFieldsValidation = new MainFieldsValidation(new MainFields());
    mainFieldsValidation.validate();
    
    this.jsonObject = "{\"ChainId\":" + chainId;
    this.jsonObject += ",\"MainFields\":" + jsonFormatter.format(mainFieldsValidation.getMainFields());
    this.jsonObject += ",\"Section\":" + jsonFormatter.format(section) + "}";
    this.postRequest();
};

TransferpointsControl.prototype.setSourceTransferpoint = function (sourceTransferpoint)
{
    this.sourceTransferpoint = sourceTransferpoint;
};

TransferpointsControl.prototype.getSourceTransferpoint = function ()
{
    return this.sourceTransferpoint;
};

TransferpointsControl.prototype.setTargetTransferpoint = function (targetTransferpoint)
{
    this.targetTransferpoint = targetTransferpoint;
};

TransferpointsControl.prototype.getTargetTransferpoint = function ()
{
    return this.targetTransferpoint;
};

// --------------------------------------------------------------------------------------------------------------------------------
// TransportChainsControl
// --------------------------------------------------------------------------------------------------------------------------------
function TransportChainsControl ()
{
    this.transportChainList = new Array(); //list of TransportChainObjects
    this.transportChainIndex = 0;
    this.transportChainCount = 0;
}

TransportChainsControl.prototype.init = function()
{
    locationList.updateLocationList();
    
    var mainFieldsValidation = new MainFieldsValidation(new MainFields());
    mainFieldsValidation.validate();
    var standardTransportModeArray = standardTransportModeControl.getTransportModeArray();
    if(standardTransportModeArray[0])
    {
        this.addTransportChain("Road");
        this.transportChainList[this.transportChainIndex-1].getSectionList()[0].changeTransportMode("Road",this.transportChainIndex-1 , mainFieldsValidation.getMainFields().getCargoUnit());
    }
    if(standardTransportModeArray[1])
    {
        this.addTransportChain("Rail");
        this.transportChainList[this.transportChainIndex-1].getSectionList()[0].changeTransportMode("Rail",this.transportChainIndex-1 , mainFieldsValidation.getMainFields().getCargoUnit());
    }
    if(standardTransportModeArray[2])
    {
        this.addTransportChain("Air");
        this.transportChainList[this.transportChainIndex-1].getSectionList()[0].changeTransportMode("Air",this.transportChainIndex-1 , mainFieldsValidation.getMainFields().getCargoUnit());
    }
    if(standardTransportModeArray[3])
    {
        this.addTransportChain("Sea");
        this.transportChainList[this.transportChainIndex-1].getSectionList()[0].changeTransportMode("Sea",this.transportChainIndex-1 , mainFieldsValidation.getMainFields().getCargoUnit());
    }
    if(standardTransportModeArray[4])
    {
        this.addTransportChain("InlandWaterways");
        this.transportChainList[this.transportChainIndex-1].getSectionList()[0].changeTransportMode("InlandWaterways",this.transportChainIndex-1 , mainFieldsValidation.getMainFields().getCargoUnit());
    }
};

TransportChainsControl.prototype.addTransportChain = function(transportMode)
{
    if(this.transportChainCount < 5)
    {
        var transportChain = new TransportChain(this.transportChainIndex, locationList.searchLocation(0), locationList.searchLocation(1), transportMode);
        this.transportChainList.push(transportChain);
        this.transportChainIndex++;
        this.transportChainCount++;
    }
};

TransportChainsControl.prototype.addTransportChainExt = function(transportMode)
{
    if(this.transportChainCount < 5)
    {
        var transportChain = new TransportChain(this.transportChainIndex, locationList.searchLocation(0), locationList.searchLocation(1), transportMode);
        this.transportChainList.push(transportChain);
        this.transportChainIndex++;
        this.transportChainCount++;
        var mainFieldsValidation = new MainFieldsValidation(new MainFields());
        mainFieldsValidation.validate();
        this.transportChainList[this.transportChainIndex-1].getSectionList()[0].changeTransportMode("Road",this.transportChainIndex-1 , mainFieldsValidation.getMainFields().getCargoUnit());
    }
};

TransportChainsControl.prototype.deleteTransportChain = function(id)
{
    var newTransportChainList = new Array();
    
    var count = 0;
    for(var chainIndex = 0; chainIndex < this.transportChainList.length; chainIndex++)
    {
        var transportChain = this.transportChainList[chainIndex];
        
        if(transportChain == null)
        {
            newTransportChainList.push(null);
        }
        else
        {
            if(transportChain.getId() === id)
            {
                var transportChainView = new TransportChainView(id, transportChain.getId() + 1);
                transportChainView.removeChainContent();
                newTransportChainList.push(null);
                for(var index = 0; index < transportChain.getSectionList().length; index++)
                {
                    var section = transportChain.getSectionList()[index];
                    transportChain.deleteSection(section.getId());
                }
            }
            else
            {
                newTransportChainList.push(transportChain);
                count++;
                var transportChainView = new TransportChainView(transportChain.getId(), transportChain.getId() + 1);
            }
        }
    }
    this.transportChainCount = count;
    this.transportChainList = newTransportChainList;
};

TransportChainsControl.prototype.getTransportChainList = function()
{
    return this.transportChainList;
};

TransportChainsControl.prototype.getTransportChainCount = function()
{
    return this.transportChainCount;
};

TransportChainsControl.prototype.reset = function()
{
    this.transportChainList = new Array();
    this.transportChainIndex = 0;
    this.transportChainCount = 0;
    locationList.reset();
};

TransportChainsControl.prototype.updateRoadClass = function (prefix, lorryClass)
{
    var listRoadEmission;
    if(lorryClass.indexOf("lbs") == -1)
    {
        listRoadEmission = listRoadEmissionsEU;
        document.getElementById(prefix + "_emissionClass").value = listRoadEmission["EuEuro3"];
    }
    else
    {
        listRoadEmission = listRoadEmissionsEPA;
        document.getElementById(prefix + "_emissionClass").value = listRoadEmission["UsEpa2004"];
    }
    
    setInputName(prefix + "_emissionClass", keyOfValue(listRoadEmissions, document.getElementById(prefix + "_emissionClass").value));
    
    var roadClassTable = "<table style=\"padding: 0px 4px; border-collapse:collapse; width: 100%;\">";
    
    for(var item in listRoadEmission) 
    {
        roadClassTable += "<tr onclick=\"layerControl.reset();popupControl.setPrefix('" + prefix + "_emissionClass'); popupControl.clickedItem('" + listRoadEmissions[item] + "');setInputName('" + prefix + "_emissionClass', keyOfValue(listRoadEmissions, document.getElementById('" + prefix + "_emissionClass').value));\"onmouseover=\"this.style.backgroundColor='#0095d5';this.style.color='#fff';\"onmouseout=\"this.style.backgroundColor='#fff'; this.style.color='#000';\"style=\"cursor: pointer;\">";
        roadClassTable += "<td style=\"font-size: 8pt; vertical-align:middle; padding-left:5px;\">";
    
        roadClassTable += listRoadEmission[item];
        roadClassTable += "</td></tr>";
    }
    roadClassTable += "</table>";
    document.getElementById(prefix + "_emissionClass_popupdiv").innerHTML = roadClassTable;
};// --------------------------------------------------------------------------------------------------------------------------------
// StandardTransportModeControl
// --------------------------------------------------------------------------------------------------------------------------------
function StandardTransportModeControl ()
{
    this.Road = true;
    this.Rail = true;
    this.Sea = false;
    this.Air = false;
    this.InlandWaterways = false;
}

StandardTransportModeControl.prototype.chooseTransportMode = function(mode)
{
    if(mode == "Road")
    {
        this.updateField(mode);
        this.Road = this.switchValue(this.Road);
    }
    if(mode == "Rail")
    {
        this.updateField(mode);
        this.Rail = this.switchValue(this.Rail);
    }
    if(mode == "Sea")
    {
        this.updateField(mode);
        this.Sea = this.switchValue(this.Sea);
    }
    if(mode == "Air")
    {
        this.updateField(mode);
        this.Air = this.switchValue(this.Air);
    }
    if(mode == "InlandWaterways")
    {
        this.updateField(mode);
        this.InlandWaterways = this.switchValue(this.InlandWaterways);
    }
};

StandardTransportModeControl.prototype.updateField = function(mode)
{
    var partialImageName = mode.toLowerCase();
    var imgPath = document.getElementById("tm_" + partialImageName + '_img').src;
    var index = imgPath.lastIndexOf('/');
    
    if(imgPath.indexOf("-hover") != -1)
    {
        document.getElementById("tm_" + partialImageName + '_img').src = imgPath.substring(0, index) + "/" + partialImageName + ".jpg";
    }
    else
    {
        document.getElementById("tm_" + partialImageName + '_img').src = imgPath.substring(0, index) + "/" + partialImageName + "-hover" + ".jpg";
    }
};

StandardTransportModeControl.prototype.switchValue = function(field)
{
    if(field)
    {
        return false;
    }
    else
    {
        return true;
    }
};

StandardTransportModeControl.prototype.prepareFormularFields = function()
{
    var jsonObject = null;
    var jsonFormatter = new JsonFormatter();
    var mainFieldsValidation = new MainFieldsValidation(new MainFields());
    var originLocation = locationList.searchLocation(0);
    var destinationLocation = locationList.searchLocation(1);
    mainFieldsValidation.validate();
    
    if((originLocation.getId() != null || originLocation.getLongitude() != null && originLocation.getLatitude() != null)
            && (destinationLocation.getId() != null || destinationLocation.getLongitude() != null && destinationLocation.getLatitude() != null))
    {
        jsonObject = "{\"ViewMode\":\"" + viewModeControl.getInputMode() + "\"";
        jsonObject += ",\"MainFields\":" + jsonFormatter.format(mainFieldsValidation.getMainFields());
        jsonObject += ",\"OriginLocation\":" + jsonFormatter.format(originLocation);
        jsonObject += ",\"DestinationLocation\":" + jsonFormatter.format(destinationLocation);
        jsonObject += ",\"Road\":" + this.Road;
        jsonObject += ",\"Rail\":" + this.Rail;
        jsonObject += ",\"Air\":" + this.Air;
        jsonObject += ",\"Sea\":" + this.Sea;
        jsonObject += ",\"InlandWaterways\":" + this.InlandWaterways + "}";
    }
    
    return jsonObject;
};

StandardTransportModeControl.prototype.getTransportModeArray = function()
{
    return new Array(this.Road, this.Rail, this.Air, this.Sea, this.InlandWaterways);
};

StandardTransportModeControl.prototype.reset = function()
{
    this.Road = true;
    this.Rail = true;
    this.Sea = false;
    this.Air = false;
    this.InlandWaterways = false;
};
// --------------------------------------------------------------------------------------------------------------------------------
// SectionView
// --------------------------------------------------------------------------------------------------------------------------------
function SectionView (transportChainId, locationId, sectionId, postSectionId)
{
    this.locationId = locationId;
    this.sectionId = sectionId;
    this.postSectionId = postSectionId;
    this.transportChainId = transportChainId;
    
    this.transportChainPrefix = "tc_" + transportChainId;
    this.sectionPrefix = "tc_" + transportChainId + "_sec_" + sectionId;
}

SectionView.prototype.init = function(prefix)
{
    this.prefix = prefix;
};

SectionView.prototype.params = function()
{
    var result = "";
    result += "&id=" + fixedEncodeURIComponent(this.transportChainId);
    result += "&sectionId=" + fixedEncodeURIComponent(this.sectionId);
    result += "&locationId=" + fixedEncodeURIComponent(this.locationId);
    result += "&lang=" + fixedEncodeURIComponent(pageProperties.getLanguage());
    result += "&transportChainPrefix=" + fixedEncodeURIComponent(this.transportChainPrefix + "_sec_" + (this.sectionId));
    
    return result;
};

SectionView.prototype.setParams = function(paramList)
{
    this.paramList = paramList; 
};

SectionView.prototype.getParams = function()
{
    return this.paramList; 
};

SectionView.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(pageProperties.getPath() + "/section.jsp");
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback(new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

SectionView.prototype.responseCallback = function (response)
{
    child = document.createElement("div");
    child.id = this.sectionPrefix;
    child.style.cssFloat = "left";
    child.style.styleFloat = "left";
    child.style.width = "754px";
    child.innerHTML = response;
    
    var transportChainPrefix = "tc_" + this.transportChainId + "_sec_0";
    
    if(this.postSectionId == null
            && document.getElementById(transportChainPrefix) != null)
    {
        document.getElementById(transportChainPrefix).appendChild(child);
    }
    else if(document.getElementById(transportChainPrefix) != null)
    {
        var postSectionPrefix = "tc_" + this.transportChainId + "_sec_" + this.postSectionId;
        document.getElementById(transportChainPrefix).insertBefore(child, document.getElementById(postSectionPrefix));
    }
};

SectionView.prototype.update = function ()
{
    this.setParams(this.params());
    this.postRequest();
};

SectionView.prototype.deleteSectionView = function ()
{
    var transportChainPrefix = "tc_" + this.transportChainId + "_sec_0";
    if(document.getElementById(transportChainPrefix) != null)
    {
        var child = document.getElementById(this.sectionPrefix);
        document.getElementById(transportChainPrefix).removeChild(child);
    }
};

// --------------------------------------------------------------------------------------------------------------------------------
// TransportModeView
// --------------------------------------------------------------------------------------------------------------------------------
function TransportModeView (chainId, sectionId, transportMode, cargoUnit)
{
    this.chainId = chainId;
    this.sectionId = parseInt(sectionId);
    
    this.prefix = "tc_" + this.chainId + "_sec_" + this.sectionId;
    
    this.selectedFormPrefix = this.prefix + "_selected_form";
    this.transportMode = transportMode;
    this.cargoUnit = cargoUnit;
}


/**
 * AjaxRequest
 */
TransportModeView.prototype.params = function()
{    
    var result = "";
    result += "&lang=" + fixedEncodeURIComponent(pageProperties.getLanguage());
    result += "&prefix=" + fixedEncodeURIComponent(this.prefix);
    result += "&transportMode=" + fixedEncodeURIComponent(this.transportMode);
    result += "&cargoUnit=" + fixedEncodeURIComponent(this.cargoUnit);
    result += "&chainId=" + this.chainId;
    result += "&sectionId=" + this.sectionId;
    
    var jsonFormatter = new JsonFormatter();
    result += "&json={\"Location\":" + jsonFormatter.format(transportChainsControl.getTransportChainList()[this.chainId].getSectionList()[this.sectionId].getSourceLocation()) + "}";
    
    return result;

};

TransportModeView.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(pageProperties.getPath() + "/transportmode.jsp");
    ajaxRequest.setData(this.params());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

TransportModeView.prototype.responseCallback = function (response)
{
    var imagePrefix = this.prefix + "_transporttype_img";
    if(document.getElementById(imagePrefix) != null)
    {
        var imgPath = document.getElementById(imagePrefix).src;
        var index = imgPath.lastIndexOf('/');
        document.getElementById(imagePrefix).src = imgPath.substring(0, index) + "/" + this.transportMode.toLowerCase() + "-small.gif";
        document.getElementById(this.prefix + "_transportMode").name = this.transportMode;
        document.getElementById(this.prefix + "_transportMode").value = listTransportModes[this.transportMode];
    }
    
    if(document.getElementById(this.selectedFormPrefix) != null)
    {
        document.getElementById(this.selectedFormPrefix).innerHTML = response;
    }
};

TransportModeView.prototype.update = function ()
{
    this.postRequest();
};
// --------------------------------------------------------------------------------------------------------------------------------
// TransportChainView
// --------------------------------------------------------------------------------------------------------------------------------
function TransportChainView (id, number, transportMode)
{
    this.prefix = "tc_";
    this.fullPrefix = "tc_" + id + "_sec_0";
    this.id = id;
    this.number = number;
    this.mainDiv = "tmtc";
    this.transportMode = transportMode;
}

TransportChainView.prototype.createChainContent = function()
{
    child = document.createElement("div");
    child.id = this.fullPrefix;
    child.style.cssFloat = "left";
    child.style.styleFloat = "left";
    child.style.lineHeight = "20px";
    child.style.width = "754px";
    document.getElementById(this.mainDiv).appendChild(child);
    this.postRequest();
    
    var separator = document.createElement("div");
    separator.id = this.fullPrefix + "_separator";
    separator.style.cssFloat = "left";
    separator.style.styleFloat = "left";
    separator.style.borderTop = "1px solid #777777";
    separator.style.marginTop = "0px";
    separator.style.marginBottom = "0px";
    separator.style.lineHeight = "0px";
    separator.style.width = "754px";
   
    document.getElementById(this.mainDiv).appendChild(separator);
};

TransportChainView.prototype.removeChainContent = function()
{
    var parentDiv = document.getElementById(this.mainDiv);
    var innerDiv = document.getElementById(this.fullPrefix);
    var innerSeperatorDiv = document.getElementById(this.fullPrefix + "_separator");
    parentDiv.removeChild(innerDiv);
    parentDiv.removeChild(innerSeperatorDiv);
};

TransportChainView.prototype.updateTransportChainNumber = function()
{
    if(document.getElementById("tc_" + this.id + "_sec_0_name") != null)
    {
        document.getElementById("tc_" + this.id + "_sec_0_name").innerHTML = this.number;
    }
};


/**
 * AjaxRequest
 */
TransportChainView.prototype.params = function()
{    
    var mainFieldsValidation = new MainFieldsValidation(new MainFields());
    mainFieldsValidation.validate();
    var mainFields = mainFieldsValidation.getMainFields();
    var result = "";
    result += "&prefix=" + fixedEncodeURIComponent(this.fullPrefix);
    result += "&lang=" + fixedEncodeURIComponent(pageProperties.getLanguage());
    result += "&chainId=" + fixedEncodeURIComponent(this.id);
    result += "&sectionId=" + 0;
    result += "&chainNumber=" + fixedEncodeURIComponent(this.number);
    result += "&transportMode=" + fixedEncodeURIComponent(this.transportMode);
    result += "&cargoUnit=" + mainFields.getCargoUnit();
    
    var jsonFormatter = new JsonFormatter();
    result += "&json={\"Location\":" + jsonFormatter.format(locationList.searchLocation(0)) + "}";
    
    return result;

};

TransportChainView.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(pageProperties.getPath() + "/transportchain.jsp");
    ajaxRequest.setData(this.params());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

TransportChainView.prototype.responseCallback = function (response)
{
    if(document.getElementById(this.fullPrefix) != null)
    {
        document.getElementById(this.fullPrefix).innerHTML = response;
    }
};

// --------------------------------------------------------------------------------------------------------------------------------
// JsonFormatter
// --------------------------------------------------------------------------------------------------------------------------------
function JsonFormatter ()
{
}

/**
 * @param object
 * @param fieldNameList - Array
 */
JsonFormatter.prototype.format = function (object)
{
    var jsonString = "{";
    var listLength = object.getFieldList().length;
    for(var index = 0; index < listLength; index++)
    {
        var value = eval("object.get" + object.getFieldList()[index] + "();");
        
        if(typeof value == "boolean")
        {
            jsonString += "\"" + object.getFieldList()[index] + "\":" + value;
        }
        else if(typeof value == "number")
        {
            jsonString += "\"" + object.getFieldList()[index] + "\":" + value;
        }
        else if(value instanceof Object)
        {
            var jsonFormatter = new JsonFormatter();
            jsonString += "\"" + object.getFieldList()[index] + "\":" + jsonFormatter .format(value);
        }
        else if(value == null)
        {
            jsonString += "\"" + object.getFieldList()[index] + "\":null";
        }
        else
        {
            jsonString += "\"" + object.getFieldList()[index] + "\":\"" + value + "\"";
        }

        if(index+1 != listLength)
        {
             jsonString += ",";
        }
    }
    
    jsonString += "}";
    
    return jsonString;
};
function RequestParameters()
{
    this.result = "";
}

RequestParameters.prototype.add = function(key, value)
{
    if (this.result.length > 0)
    {
        this.result = this.result + "&";
    }

    this.result = this.result
                + fixedEncodeURIComponent(key)
                + "="
                + fixedEncodeURIComponent(value);
};

RequestParameters.prototype.toString = function()
{
    return this.result;
};var ValidatorTypes = {
    minValue : 0,
    maxValue: 1,
    equal: 2,
    isNumber: 3,
    isNotEmpty: 4,
    color: 5,
    isInt: 6
};


/**
 * Constructor for a Validator object.
 */
function Validator(field)
{
    this.field = field;
    this.validation = true;
}

Validator.prototype.validate = function(type, value)
{
    if(this.validation == true
            && this.field != null)
    {
        switch (type) 
        {
        case ValidatorTypes.minValue:
            this.minValue(value);
        break;
        
        case ValidatorTypes.maxValue:
            this.maxValue(value);
        break;
        
        case ValidatorTypes.equal:
            this.equal(value);
        break;
        
        case ValidatorTypes.isNumber:
            this.isNumber();
        break;
        
        case ValidatorTypes.isNotEmpty:
            this.isNotEmpty();
        break;
        
        case ValidatorTypes.color:
            this.checkColor(value);
        break;
        
        case ValidatorTypes.isInt:
            this.isInt();
        break;
        }
        
        if(this.validation == true)
        {
            this.unmarkField();
        }
        else
        {
            this.markField();
        }
    }
    
    return this.validation;
    
};

Validator.prototype.markField = function()
{
    this.field.style.backgroundColor = "#FFB2B2";
};

Validator.prototype.unmarkField = function()
{
    if(this.field.disabled)
    {
        this.field.style.backgroundColor = "#eee";
    }
    else
    {
        this.field.style.backgroundColor = "#fff";
        this.field.style.color = "#000";
    }
};

Validator.prototype.standardCheck = function()
{
    
    if(this.validate(ValidatorTypes.isNotEmpty,"") == false)
    {
        return this.validation;
    }
    
    if(this.validate(ValidatorTypes.color,"#929292") == false)
    {
        return this.validation;
    }
    
    if(this.validate(ValidatorTypes.color,"rgb(146, 146, 146)") == false)
    {
        return this.validation;
    }
    
    return this.validation;
};

Validator.prototype.minValue = function(minValue)
{
    if(this.field.value < minValue)
    {
        this.validation = false;
    }
};

Validator.prototype.maxValue = function(maxValue)
{
    if(this.field.value > maxValue)
    {
        this.validation = false;
    }
};

Validator.prototype.equal = function(value)
{
    if(this.field.value == value)
    {
        this.validation = false;
    }
};

Validator.prototype.isNumber = function()
{
    var expression = /^\d*((\.|\,)?\d+)?$/;
    this.validation = expression.test(this.field.value);
};

Validator.prototype.isInt = function()
{
    var expression = /^\d*$/;
    this.validation = expression.test(this.field.value);
};

Validator.prototype.isNotEmpty = function()
{
    if(this.field.value == null)
    {
        this.validation = false;
    }
    else if(this.field.value.length == 0)
    {
        this.validation = false;
    }
};

Validator.prototype.checkColor = function(color)
{
    if(this.field.style.color == color)
    {
        this.validation = false;
    }
};


function toogleDisplay(elementId)
{
    if(document.getElementById(elementId).style.display == "block")
    {
        document.getElementById(elementId).style.display = "none";
    }
    else
    {
        document.getElementById(elementId).style.display = "block";
    }
}

function changeToogleImage(id, defaultImage, changeToImage)
{
    if(document.getElementById(id).src.search(defaultImage) != -1)
    {
        
        document.getElementById(id).src = document.getElementById(id).src.slice(0, -defaultImage.length) + changeToImage;
    }
    else
    {
        document.getElementById(id).src = document.getElementById(id).src.slice(0, -changeToImage.length) + defaultImage;
    }
}

function elementWidth(element)
{
    if (element.clientWidth)
    {
        // Gecko
        return element.clientWidth;
    }
    else
    {
        // Internet Explorer
        return element.offsetWidth;
    }
}

function elementHeight(element)
{
    if (element.clientHeight)
    {
        // Gecko
        return element.clientHeight;
    }
    else
    {
        // Internet Explorer
        return element.offsetHeight;
    }
}

function getSourceElementFromEvent(event)
{

    if (event.srcElement !== undefined)
    {
        // Internet Explorer
        return event.srcElement;
    }
    else if (event.originalTarget !== undefined)
    {
        // Gecko
        return event.originalTarget;
    }

    return undefined;  
}

function getMapKey(keyList, valueList, value)
{
    var splittedKeyList = keyList.split(",");
    var splittedValueList = valueList.split(",");
    
    for(var index = 0; splittedValueList.length; index++)
    {
        if(splittedValueList[index] == value)
        {
            return splittedKeyList[index];
        }
    }
}

function validateCheckboxEnableInputField(checked, inputField)
{
    if(checked)
    {
        inputField.disabled = false;
        inputField.style.backgroundColor = '#fff';
    }
    else
    {
        inputField.disabled = true;
        inputField.style.backgroundColor = '#eee';
    }
}


function setZIndex(id)
{
    if(document.getElementById(id).style.zIndex == 50)
    {
        document.getElementById(id).style.zIndex = 1;
    }
    else
    {
        document.getElementById(id).style.zIndex = 50;
    }
}

function setInputName(id, value)
{
    var field = document.getElementById(id);
    if(field != null)
    {
        document.getElementById(id).name = value;
    }
}

function setInputValue(id, value)
{
    var field = document.getElementById(id);
    if(field != null)
    {
        document.getElementById(id).value = value;
    }
}

function keyOfValue(arrayList, value)
{
    for(key in arrayList)
    {
        if(arrayList[key] == value)
        {
            return key;
        }
    }
};

function fixedEncodeURIComponent (str) 
{
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28')  
                                  .replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/\^/g, '%5e')
                                  .replace(/\`/g, '%60').replace(/\_/g, '%5f').replace(/\[/g, '%5b')
                                  .replace(/\]/g, '%5d').replace(/\[/g, '%5b').replace(/\~/g, '%7e');  
} 


//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
  var len = this.length;
  if (typeof fun != "function")
    throw new TypeError();

  var res = new Array();
  var thisp = arguments[1];
  for (var i = 0; i < len; i++)
  {
    if (i in this)
    {
      var val = this[i]; // in case fun mutates this
      if (fun.call(thisp, val, i, this))
        res.push(val);
    }
  }

  return res;
};
}
// --------------------------------------------------------------------------------------------------------------------------------
// PageProperties
// --------------------------------------------------------------------------------------------------------------------------------
function PageProperties (path, language)
{
    this.path = path;
    this.language = language;
}

PageProperties.prototype.getPath = function()
{
    return this.path;
};

PageProperties.prototype.getLanguage = function()
{
    return this.language;
};
// --------------------------------------------------------------------------------------------------------------------------------
// AjaxPopupControl
// --------------------------------------------------------------------------------------------------------------------------------
function AjaxPopupControl (requestPage)
{
    this.elementPrefix = null;
    this.popupDiv = null;
    this.loadingDivId = null;
    this.requestPage = requestPage;
    
    this.paramList = "";
    
    this.timerId = null;
    this.shown = false;
    
    this.switchButton = null;
}

AjaxPopupControl.prototype.init = function(elementPrefix,
        popupDivId,
        loadingDivId)
{
    this.elementPrefix = elementPrefix;
    this.popupDiv = popupDivId;
    this.loadingDivId = loadingDivId;
    this.switchButton = document.getElementById(elementPrefix + "_switch");
};

AjaxPopupControl.prototype.setParams = function(paramList)
{
    this.paramList = paramList; 
};

AjaxPopupControl.prototype.getParams = function()
{
    return this.paramList; 
};

AjaxPopupControl.prototype.clickedItem = function (value)
{
    this.hide();
    this.switchButton.src = this.switchButton.src.replace(/down.gif/, "up.gif");
    
    document.getElementById(this.elementPrefix + "_input").value = value;
};

AjaxPopupControl.prototype.restartTimer = function ()
{
    if (this.timerId != null)
    {
        window.clearTimeout(this.timerId);
    }
    var self = this;
    this.timerId = window.setTimeout(function() { self.trigger(); }, 300);
};

AjaxPopupControl.prototype.trigger = function ()
{
    this.timerId = null;
    this.postRequest();
};

AjaxPopupControl.prototype.toggleDisplay = function()
{
    if (this.shown)
    {
        this.hide();
    }
    else
    {
        this.postRequest();
    }
};

AjaxPopupControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(this.requestPage);
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

AjaxPopupControl.prototype.responseCallback = function (response)
{
    if(this.popupDiv == layerControl.getCurrentPopupID())
    {
        document.getElementById(this.popupDiv).innerHTML = response;
        document.getElementById(this.popupDiv).style.display = "block";
    
        if(this.loadingDivId != null)
        {
            document.getElementById(this.loadingDivId).style.display = "none";
        }    
    
        this.shown = true;
    }
    else
    {
        document.getElementById(this.popupDiv).style.display = "none";
        if(this.loadingDivId != null)
        {
            document.getElementById(this.loadingDivId).style.display = "none";
        }    
    }
};

AjaxPopupControl.prototype.hide = function ()
{
    document.getElementById(this.popupDiv).innerHTML = "";
    document.getElementById(this.popupDiv).style.display = "none";
    this.shown = false;
};

AjaxPopupControl.prototype.clickedPopupSwitch = function (listButton)
{
    if (this.shown)
    {
        this.hide();
        listButton.src = listButton.src.replace(/up.gif/, "down.gif");
    }
    else
    {
        if(this.loadingDivId != null)
        {
            document.getElementById(this.loadingDivId).style.display = "block";
        }    
        this.postRequest();
        listButton.src = listButton.src.replace(/down.gif/, "up.gif");
    }
};
var EnumRequestType = {
    Get  : 0,
    Head : 1,
    Post : 2,
    Xml  : 3
};

var EnumReadyState = {
    Uninitialized : 0, 
    Open          : 1,
    Sent          : 2,
    Receiving     : 3,
    Loaded        : 4
};

var EnumResponseType = {
    Text : 0,
    Xml  : 1
};

/**
 * Constructor for an AjaxRequest object.
 */
function AjaxRequest()
{
    this.xmlHttpRequest = this.createXmlHttpRequest();
    this.source = null;
    this.responseType = null;
    this.finishedCallback = null;
    this.receivingCallback = null;
    this.errorCallback = this.defaultErrorOutput;
    this.data = null;
    this.requestType = null;

    this.retryCount = 1;
    this.retryInterval = 2;
}

AjaxRequest.prototype.initXmlHttpRequest = function()
{
    if(this.source != null && this.data != null && this.responseType != null && this.requestType != null && this.finishedCallback != null)
    {
        var sessionIdString = null;
        if (globalAjaxRequestJSessionId == null)
        {
            sessionIdString = "";
        }
        else
        {
            sessionIdString = ";jsessionid=" + globalAjaxRequestJSessionId;
        }

        var bodyData = null;
        switch (this.requestType)
        {
        case EnumRequestType.Xml:
            this.xmlHttpRequest.open("POST", this.source + sessionIdString, true);
            bodyData = "xml=" + fixedEncodeURIComponent(this.data);
            this.xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            this.xmlHttpRequest.setRequestHeader('Content-length', bodyData.length);
            /* Force "Connection: close" for Mozilla browsers to work around
             * a bug where XMLHttpReqeuest sends an incorrect Content-length
             * header. See Mozilla Bugzilla #246651.
             */
            this.xmlHttpRequest.setRequestHeader('Connection', 'close');
            break;

        case EnumRequestType.Post:
            this.xmlHttpRequest.open("POST", this.source + sessionIdString, true);
            bodyData = this.data;
            this.xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            this.xmlHttpRequest.setRequestHeader('Content-length', this.data.length);
            /* Force "Connection: close" for Mozilla browsers to work around
             * a bug where XMLHttpReqeuest sends an incorrect Content-length
             * header. See Mozilla Bugzilla #246651.
             */
            this.xmlHttpRequest.setRequestHeader('Connection', 'close');
            break;

        case EnumRequestType.Head:
            bodyData = "";
            this.xmlHttpRequest.open("HEAD", this.source + sessionIdString, true);
            break;

        case EnumRequestType.Get:
            bodyData = "";
            this.xmlHttpRequest.open("GET", this.source + sessionIdString + "?" + this.data, true);
            break;
            }

        this.xmlHttpRequest.setRequestHeader('Cache-control', 'no-store');
        this.xmlHttpRequest.setRequestHeader('Expires', 0);
    
        this.registeredCallback = new RegisteredCallback(this, this.readystatechange);
        this.xmlHttpRequest.onreadystatechange = this.registeredCallback.getFunction();
        this.xmlHttpRequest.send(bodyData);
    }
    else
    {
        this.defaultErrorOutput();
        //this.errorCallback.run();
    }
};

/**
 * returns a new http request object for different browsers
 */
AjaxRequest.prototype.createXmlHttpRequest = function()
{
    // Internet Explorer: use ActiveX object
    if (window.ActiveXObject)
    {
        // Try different versions, start at the newest version
        for (var iVersionNumber = 5; iVersionNumber; iVersionNumber--)
        {
            try
            {
                if (iVersionNumber == 2)
                {
                    return new ActiveXObject( "Microsoft.XMLHTTP" );
                }
                else
                {
                    return new ActiveXObject( "Msxml2.XMLHTTP." + iVersionNumber + ".0" );
                    
                }
            }
            catch (excNotLoadable)
            {
            }
        }
        return null;
    }
    // other browsers
    else if (window.XMLHttpRequest)
    {
        try
        {
            return new XMLHttpRequest();
        }
        // loading of xmlhttp object failed
        catch( excNotLoadable )
        {
            return null;
        }
    }
    else
    {
        return null;
    }
};

AjaxRequest.prototype.response = function()
{
    return this.xmlHttpRequest.responseText;
};

AjaxRequest.prototype.readystatechange = function()
{
    //aktuellen Status pruefen
    switch (this.xmlHttpRequest.readyState)
    {
    case EnumReadyState.Uninitialized:
    case EnumReadyState.Open:
    case EnumReadyState.Sent:
        break;
    case EnumReadyState.Receiving:
        if(this.receivingCallback != null)
        {
            this.receivingCallback.run(this.xmlHttpRequest.responseText);
        }
        break;

    case EnumReadyState.Loaded:
        if (!this.xmlHttpRequest.addEventListener)
        {
            this.registeredCallback.unregister();
        }
        
        if (this.xmlHttpRequest.status == 200 ) // HTTP OK
        {
            switch (this.responseType)
            {
                case EnumResponseType.Text:
                    this.finishedCallback.run(this.xmlHttpRequest.responseText);
                    break;
                    
                case EnumResponseType.Xml:
                    this.finishedCallback.run(this.xmlHttpRequest.responseXML);
                    break;
           }
        }
        else
        {
            this.retryCount++;

            if (this.retryCount <= this.retryInterval)
            {
                var self = this;
                window.setTimeout(function() { self.initXmlHttpRequest(); }, 2000);
            }
            else
            {
                //alert("AJAX respone error (HTTP state " + this.xmlHttpRequest.status + ")\n" + this.xmlHttpRequest.statusText) ;
                this.defaultErrorOutput();
                //this.errorCallback.run();
                this.retryCount = 1;
            }
        }
    }
};

AjaxRequest.prototype.defaultErrorOutput = function()
{
    //alert("Es ist ein Problem mit der Seite aufgetreten.\nBitte laden Sie die Seite erneut!");
    document.getElementById("calculationLoading").style.display = "none";
    document.getElementById("inputFields").style.display = "block";
    document.getElementById("result").innerHTML = "<br><br><b>Es ist ein Problem mit der Seite aufgetreten.<br>Bitte pr&uuml;fen sie ihre Eingaben und versuchens sie es erneut.</b>";
};

AjaxRequest.prototype.setSource = function(source)
{
    this.source = source;
};

AjaxRequest.prototype.setData = function(data)
{
    this.data = data;
};

AjaxRequest.prototype.setRequestType = function(requestType)
{
    this.requestType = requestType;
};

AjaxRequest.prototype.setResponseType = function(responseType)
{
    this.responseType = responseType;
};

AjaxRequest.prototype.setFinishedCallback = function(finishedCallback)
{
    this.finishedCallback = finishedCallback;
};

AjaxRequest.prototype.setReceivingCallback = function(receivingCallback)
{
    this.receivingCallback = receivingCallback;
};

AjaxRequest.prototype.setErrorCallback = function(errorCallback)
{
    this.errorCallback = errorCallback;
};
// --------------------------------------------------------------------------------------------------------------------------------
// ChildNodesControl
// --------------------------------------------------------------------------------------------------------------------------------
function ChildNodesControl ()
{
    this.parentDivId = null;
    this.nodes = new Array();
}

ChildNodesControl.prototype.setParentDivId = function (parentDivId)
{
    this.parentDivId = parentDivId;
};

ChildNodesControl.prototype.delElement = function (elementId)
{
    if(document.getElementById(this.parentDivId).hasChildNodes())
    {
        var childNodesLength = document.getElementById(this.parentDivId).childNodes.length;
        
        for(var index = 0; index < childNodesLength; index++)
        {
            element = document.getElementById(this.parentDivId).childNodes[index];
            
            if(element.id == elementId)
            {
                parentElement = document.getElementById(this.parentDivId);
                parentElement.removeChild(element);
                break;
            }
        }
    }
};

ChildNodesControl.prototype.resizeElemets = function (classNameToCheck, resizeToPX)
{
    var nodesArray = new Array();
    for(var index = 0; index < document.getElementById(this.parentDivId).childNodes.length; index++)
    {
        element = document.getElementById(this.parentDivId).childNodes[index];
        if(element.className != null 
                && element.className.search(classNameToCheck) != -1)
        {
            nodesArray.push(element);
        }
    }
    
    var nodeElementWidth = resizeToPX / nodesArray.length;
    for(var index = 0; index < nodesArray.length; index++)
    {
        element = nodesArray[index];
        element.style.width = nodeElementWidth;
    }
};
var Compat = {

    addEventListener : function(element, eventname, eventFunction)
    {
        if (element.addEventListener)
        {
            element.addEventListener(eventname, eventFunction, false)
        }
        else if (element.attachEvent)
        {
            element.attachEvent('on' + eventname, eventFunction);
        }
    }

};function Callback(obj, func)
{
    this.obj = obj;
    this.func = func;
}

Callback.prototype.run = function()
{
    this.func.apply(this.obj, arguments);
};

var globalCallbackIds = { last : 0 };


function RegisteredCallback(obj, callback)
{
    this.obj = obj;
    this.callback = callback;
    
    globalCallbackIds.last++;
    this.callbackId = globalCallbackIds.last;
    globalCallbackIds['r' + this.callbackId] = this;

    this.callbackFunction = new Function("globalCallbackIds.r" + this.callbackId + ".run.apply(globalCallbackIds.r" + this.callbackId +", arguments);");
}

RegisteredCallback.prototype.getFunction = function()
{
    return this.callbackFunction;
};

RegisteredCallback.prototype.run = function()
{
    return this.callback.apply(this.obj, arguments);
};

RegisteredCallback.prototype.unregister = function()
{
    new Function("delete globalCallbackIds.r" + this.callbackId + ";")();
};
if (!document.ELEMENT_NODE) {
    document.ELEMENT_NODE = 1;
    document.ATTRIBUTE_NODE = 2;
    document.TEXT_NODE = 3;
    document.CDATA_SECTION_NODE = 4;
    document.ENTITY_REFERENCE_NODE = 5;
    document.ENTITY_NODE = 6;
    document.PROCESSING_INSTRUCTION_NODE = 7;
    document.COMMENT_NODE = 8;
    document.DOCUMENT_NODE = 9;
    document.DOCUMENT_TYPE_NODE = 10;
    document.DOCUMENT_FRAGMENT_NODE = 11;
    document.NOTATION_NODE = 12;
}

function customImportNode(node, allChildren) {
    switch (node.nodeType) {
        case document.ELEMENT_NODE:
            var newNode = document.createElement(node.nodeName);
            
            /* does the node have any attributes to add? */
            if (node.attributes && node.attributes.length > 0)
            {
                for (var i = 0; i < node.attributes.length; i++)
                {
                    newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i].nodeName));
                }
            }
            
            /* are we going after children too, and does the node have any? */
            if (allChildren && node.childNodes && node.childNodes.length > 0)
            {
                for (var i = 0; i < node.childNodes.length; i++)
                {
                    newNode.appendChild(customImportNode(node.childNodes[i], allChildren));
                }
            }
            return newNode;
            break;
        case document.TEXT_NODE:
        case document.CDATA_SECTION_NODE:
        case document.COMMENT_NODE:
            return document.createTextNode(node.nodeValue);
            break;
    }
}

function findElement(elementOrElementId)
{
    if (typeof elementOrElementId == "string")
    {
        return document.getElementById(elementOrElementId);
    }
    else
    {
        return elementOrElementId;        
    }
}
var loadHooks = new Array();

function registerLoadHook(hook)
{
    loadHooks.push(hook);
}

function runLoadHooks()
{
    for (var i = 0; i < loadHooks.length; i++)
    {
        loadHooks[i]();
    }
}// --------------------------------------------------------------------------------------------------------------------------------
// TransferpointControl
// --------------------------------------------------------------------------------------------------------------------------------
function TransferpointControl(requestPage,
                              language,
                              originPrefix,
                              destinationPrefix)
{
    this.requestPage = requestPage;
    this.language = language;
    this.numTransferponit = 0;
    this.originPrefix = originPrefix;
    this.destinationPrefix = destinationPrefix;
    this.mouseover = false;
    
    this.fromLocationPrefix = null;
    this.toLocationPrefix = null;
    this.transportModePrefix = null;
}

TransferpointControl.prototype.params = function ()
{
    var req = new RequestParameters();
    
    req.add("lang", fixedEncodeURIComponent(this.language));
    req.add("originPrefix", this.fromLocationPrefix);
    req.add("destinationPrefix", this.toLocationPrefix);
    req.add("transportModePrefix", this.transportModePrefix);
    
    return req.toString() + "&" + formularValidationControl.createParameterString();
};

TransferpointControl.prototype.setParams = function(paramList)
{
    this.paramList = paramList;
};

TransferpointControl.prototype.getParams = function()
{
    return this.paramList; 
};

TransferpointControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(this.requestPage);
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Xml);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

TransferpointControl.prototype.responseCallback = function (response)
{
    var transferpoints = response.getElementsByTagName("transferpoints")[0].getElementsByTagName("transferpoint");
    var tpLength = transferpoints.length;
    var prefix = null;
    var defaultVehicleId = null;
    
    for(var element = 0; element < tpLength; element++)
    {
        prefix = this.validateElement(transferpoints[element].getElementsByTagName("prefix")[0]);
        var sourceDivId = prefix + "_tp_source";
        var sourceInputId = prefix + "_sourceLocation";
        var targetDivId = prefix + "_tp_target";
        var targetInputId = prefix + "_targetLocation";
        
        /*
         * remove transferpoint divs from a calculation before
         */
        if(document.getElementById(sourceDivId) != null)
        {
            document.getElementById(prefix + "_source_tp").removeChild(document.getElementById(sourceDivId));
        }
        if(document.getElementById(targetDivId) != null)
        {
            document.getElementById(prefix + "_target_tp").removeChild(document.getElementById(targetDivId));
        }
        
        var error = this.validateElement(transferpoints[element].getElementsByTagName("error")[0]);
        if(error != "")
        {
            var errorChild = this.createErrorChild(sourceDivId, error);
            document.getElementById(prefix + "_source_tp").appendChild(errorChild);
        }
        
        if(transferpoints[element].getElementsByTagName("defaultVehicleId")[0] != null)
        {
            defaultVehicleId = this.validateElement(transferpoints[element].getElementsByTagName("defaultVehicleId")[0]);
            var defaultVehicleName = this.validateElement(transferpoints[element].getElementsByTagName("defaultVehicleName")[0]);
            var defaultVehicleTransportType = this.validateElement(transferpoints[element].getElementsByTagName("defaultVehicleTransportType")[0]);
            var defaultVehicleLoadFactor = this.validateElement(transferpoints[element].getElementsByTagName("defaultVehicleLoadFactor")[0]);
            var sourceLocationId = this.validateElement(transferpoints[element].getElementsByTagName("sourceLocationId")[0]);
            var sourceLocation = this.validateElement(transferpoints[element].getElementsByTagName("sourceLocation")[0]);
            var sourceCountry = this.validateElement(transferpoints[element].getElementsByTagName("sourceLocationCountry")[0]);
            var sourceLocationType = this.validateElement(transferpoints[element].getElementsByTagName("sourceLocationType")[0]);
            var targetLocationId = this.validateElement(transferpoints[element].getElementsByTagName("targetLocationId")[0]);
            var targetLocation = this.validateElement(transferpoints[element].getElementsByTagName("targetLocation")[0]);
            var targetCountry = this.validateElement(transferpoints[element].getElementsByTagName("targetLocationCountry")[0]);
            var targetLocationType = this.validateElement(transferpoints[element].getElementsByTagName("targetLocationType")[0]);
            var title = this.validateElement(transferpoints[element].getElementsByTagName("title")[0]);
            
            var splitedPrefix = prefix.split("_");
            
            if(title.length > 0)
            {
                var sourceChild = this.createTransferpointChild(sourceDivId, sourceInputId, sourceLocationId, sourceLocation, sourceLocationType, title);
                document.getElementById(prefix + "_source_tp").appendChild(sourceChild);
                
                var targetChild = this.createTransferpointChild(targetDivId, targetInputId, targetLocationId, targetLocation, targetLocationType, title);
                document.getElementById(prefix + "_target_tp").appendChild(targetChild);
                
                var object = formularValidationControl.getFormularFields()[prefix];
                if(object instanceof Air)
                {
                    var air = formularValidationControl.getFormularFields()[prefix];
                    air.setVehicleId(defaultVehicleId);
                    air.setVehicleName(defaultVehicleName);
                    
                    object = air;
                }
                else if(object instanceof Sea)
                {
                    var sea = formularValidationControl.getFormularFields()[prefix];
                    sea.setVehicleId(defaultVehicleId);
                    sea.setVehicleName(defaultVehicleName);
                    sea.setLoadFactor(defaultVehicleLoadFactor);
                    
                    object = sea;
                }
                else if(object instanceof InlandWaterways)
                {
                    var inlandWaterways = formularValidationControl.getFormularFields()[prefix];
                    inlandWaterways.setVehicleId(defaultVehicleId);
                    inlandWaterways.setVehicleName(defaultVehicleName);
                    inlandWaterways.setType(defaultVehicleTransportType);
                    
                    object = inlandWaterways;
                }
                
                formularValidationControl.getFormularFields()[prefix] = object;
                
                document.getElementById(prefix + "_vehicleId").value = defaultVehicleId;
                document.getElementById(prefix + "_vehicleName").value = decodeURIComponent(defaultVehicleName);
                document.getElementById(prefix + "_vehicleName").style.color = "#000000";
                
                var transportType = document.getElementById(prefix + "_vehicleType");
                var loadFactor = document.getElementById(prefix + "_loadFactor");
                if(transportType != null)
                {
                    if(defaultVehicleTransportType != null)
                    {
                        transportType.value = defaultVehicleTransportType;
                    }
                    else
                    {
                        transportType.value = "";
                    }
                }
                if(loadFactor != null)
                {
                    if(defaultVehicleLoadFactor != null
                            && defaultVehicleLoadFactor != "")
                    {
                        loadFactor.value = defaultVehicleLoadFactor;
                    }
                }
            }
        }
    }
    
    if(defaultVehicleId != null)
    {
        var vehiclesListControl = new VehiclesListControl(this.requestPage.replace("transferpoint.jsp", "vehicles_list.jsp", "i"), prefix, this.language, document.getElementById(prefix + "_transportMode").name, true);
        vehiclesListControl.update();
    }
};

TransferpointControl.prototype.validateElement = function (element)
{
    if(element != null 
            && element.firstChild != null)
    {
        return element.firstChild.nodeValue;
    }
    else
    {
        return "";
    }
};

TransferpointControl.prototype.createTransferpointChild = function (id, inputId, locationId, location, locationType, title, width)
{
    var child = document.createElement("div");
    child.id = id;
    child.style.cssFloat = "right";
    child.style.styleFloat = "right";
    child.style.border = "1px solid #777";
    child.style.backgroundColor = "#CAE2FF";
    child.style.marginTop = "2px";
    child.style.marginBottom = "2px";
    child.style.marginRight = "2px";
    child.style.width = "718px";
    child.innerHTML = "<input id=\""+ inputId +"Id\" type=\"hidden\" value=\"" + locationId + "\" />" +
                      "<input id=\""+ inputId +"Name\" type=\"hidden\" value=\"[" + locationType + "] " + location + "\" />" +
                      "<span style=\"font-weight: bold; padding-left: 38px;\">" + title + "</span>" +
                      "<span style=\"padding-left: 36px;\">[" + locationType + "] " + location + "</span>";
    return child;
};

TransferpointControl.prototype.createErrorChild = function (id, message, width)
{
    var child = document.createElement("div");
    child.id = id;
    child.style.cssFloat = "right";
    child.style.styleFloat = "right";
    child.style.border = "1px solid #777";
    child.style.backgroundColor = "#FFC0C0";
    child.style.marginTop = "2px";
    child.style.marginBottom = "2px";
    child.style.width = "718px";
    child.innerHTML = "<span style=\"font-weight: bold; padding-left: 38px;\">Error</span>" +
                      "<span style=\"padding-left: 36px;\">" + message + "</span>";
    return child;
};

TransferpointControl.prototype.calculateTransferpoints = function ()
{
    formularValidationControl.validate();
    
    if(viewModeControl.getInputMode() == "extended")
    {
        var originLocation = formularValidationControl.getFormularFields()[this.originPrefix];
        var destinationLocation = formularValidationControl.getFormularFields()[this.destinationPrefix];
        
        var prefixList = formularValidationControl.getPrefixList().split(",");
        var viaPrefixList = formularValidationControl.getViaPrefixList().split(",");
        
        for(var index in prefixList)
        {
            this.removeTransferpoints(prefixList[index]);
            this.fromLocationPrefix = this.originPrefix;
            var transportMode = formularValidationControl.getFormularFields()[prefixList[index] + "_transportMode"];
            this.transportModePrefix = prefixList[index];
            
            /*
             * check if a via location exist
             */
            var mainPrefix = prefixList[index];
            for(var viaIndex in viaPrefixList)
            {
                this.removeTransferpoints(viaPrefixList[viaIndex]);
                if(viaPrefixList[viaIndex].indexOf(mainPrefix) != -1)
                {
                    var viaPrefixElement = viaPrefixList[viaIndex];
                    var viaLocation = formularValidationControl.getFormularFields()[viaPrefixElement]["Location"];
                    this.toLocationPrefix = viaPrefixElement;
                    this.updateTransferpoints();
                        
                        /*
                         * set this viaPrefix as origin location prefix
                         * after request has been send
                         */
                    this.fromLocationPrefix = viaPrefixElement;
                    this.transportModePrefix = viaPrefixElement;
                }
            }
    
            this.toLocationPrefix = this.destinationPrefix;
            this.updateTransferpoints();
    
            this.fromLocationPrefix = null;
            this.toLocationPrefix = null;
            this.transportModePrefix = null;
        }
    }
};

TransferpointControl.prototype.updateTransferpoints = function ()
{
    if(this.fromLocationPrefix != null
            && this.toLocationPrefix != null
            && this.transportModePrefix != null)
    {
        this.setParams(this.params());
        this.postRequest();
    }
};

TransferpointControl.prototype.removeTransferpoints = function (divId)
{
    var sourceElement = document.getElementById(divId + "_tp_source");
    var targetElement = document.getElementById(divId + "_tp_target");
    if(sourceElement != null)
    {
        document.getElementById(divId + "_source_tp").removeChild(sourceElement);
    }
    if(targetElement != null)
    {
        document.getElementById(divId + "_target_tp").removeChild(targetElement);
    }
};

TransferpointControl.prototype.setMouseover = function ()
{
    this.mouseover = true;
};

TransferpointControl.prototype.setMouseout = function ()
{
    this.mouseover = false;
};// --------------------------------------------------------------------------------------------------------------------------------
// TabMenuControl
// --------------------------------------------------------------------------------------------------------------------------------
function TabMenuControl (tabIdsList, tabInfosList)
{
    this.tabIdsList = tabIdsList.split(";");
    this.tabInfosList = tabInfosList.replace(/'/g,"\\'");
    tabInfosList = tabInfosList.replace(/\u0027/g,"\\\u0027");
    this.tabInfosList = tabInfosList.split(";");
    this.currentInfo = "";
}

TabMenuControl.prototype.selectTabAndResultDiv = function(tabId, info)
{
    this.currentInfo = info;
    for(var index = 0; index < this.tabIdsList.length; index++)
    {
        this.resetTabStyle(this.tabIdsList[index], this.tabInfosList[index]);
        this.hide(this.tabIdsList[index].split("_")[0]);
    }
    
    this.setSelectedTabStyle(tabId);
    this.show(tabId.split("_")[0]);
};

TabMenuControl.prototype.resetTabStyle = function(id, info)
{
    if(document.getElementById(id) != null)
    {
        var element = document.getElementById(id);
        element.style.lineHeight = "18px";
        element.style.backgroundColor = "#eee";
        element.style.color = "#0F1448";
        element.style.paddingLeft = "15px";
        element.style.paddingRight = "15px";
        element.style.fontWeight = "bold";
        element.setAttribute("onmouseover", "this.style.background='#b1b1b1';getElementById('tabMenuInfo').innerHTML = '" + info +"';");
        element.setAttribute("onmouseout", "this.style.background='#eeeeee';getElementById('tabMenuInfo').innerHTML = '" + this.currentInfo.replace(/'/g,"\\'") + "';");
    }
};

TabMenuControl.prototype.setSelectedTabStyle = function(id)
{
    if(document.getElementById(id) != null)
    {
        var element = document.getElementById(id);
        element.style.lineHeight = "18px";
        element.style.backgroundColor = "#0F1448";
        element.style.color = "#eee";
        element.style.paddingLeft = "15px";
        element.style.paddingRight = "15px";
        element.style.fontWeight = "bold";
        element.setAttribute("onmouseover", "");
        element.setAttribute("onmouseout", "");
        document.getElementById("tabMenuInfo").innerHTML = this.currentInfo;
    }
};

TabMenuControl.prototype.hide = function(id)
{
    if(document.getElementById(id) != null)
    {
        document.getElementById(id).style.display = "none";
    }
};

TabMenuControl.prototype.show = function(id)
{
    if(document.getElementById(id) != null)
    {
        document.getElementById(id).style.display = "block";
    }
};

// --------------------------------------------------------------------------------------------------------------------------------
// TransferpointControl
// --------------------------------------------------------------------------------------------------------------------------------
function LocationItemControl()
{
    this.prefix = null;
    this.locationType = null;
    this.locationName = null;
    this.id = null;
}

LocationItemControl.prototype.params = function ()
{
    var result = "";
    result += "&lang=" + pageProperties.getLanguage();
    result += "&locationType=" + this.locationType;
    
    if(document.getElementById(this.prefix + "_uic") != null)
    {
         var country = document.getElementById(this.prefix + "_country");
         var uic = document.getElementById(this.prefix + "_uic");
         
         if(uic.value != "" && country.value != "")
         {
             result += "&country=" + document.getElementById(this.prefix + "_country").value;
             result += "&uic=" + document.getElementById(this.prefix + "_uic").value;
         }
         else 
         {
             if(country.value == "")
             {
                 result = "";
                 country.style.backgroundColor="#FFB2B2";
             }
         
             if(uic.value == "")
             {
                 result = "";
                 uic.style.backgroundColor="#FFB2B2";
             }
         }
    }
    if(document.getElementById(this.prefix + "_zip") != null)
    {
         var country = document.getElementById(this.prefix + "_country");
         var zip = document.getElementById(this.prefix + "_zip");
         
         if(zip.value != "" && country.value != "")
         {
             result += "&country=" + document.getElementById(this.prefix + "_country").value;
             result += "&zip=" + document.getElementById(this.prefix + "_zip").value;
         }
         else 
         {
             if(country.value == "")
             {
                 result = "";
                 country.style.backgroundColor="#FFB2B2";
             }
         
             if(zip.value == "")
             {
                 result = "";
                 zip.style.backgroundColor="#FFB2B2";
             }
         }
    }
    else if(document.getElementById(this.prefix + "_iata") != null)
    {
         result += "&iata=" + document.getElementById(this.prefix + "_iata").value;
    }
    else if(document.getElementById(this.prefix + "_unlocode") != null)
    {
         result += "&unlocode=" + document.getElementById(this.prefix + "_unlocode").value;
    }
    if(this.locationName != null)
    {
        result += "&locationName=" + fixedEncodeURIComponent(this.locationName);
    }
    
    return result;
};

LocationItemControl.prototype.setParams = function(paramList)
{
    this.paramList = paramList;
};

LocationItemControl.prototype.getParams = function()
{
    return this.paramList; 
};

LocationItemControl.prototype.postRequest = function ()
{
    if(this.getParams() != "")
    {
        var ajaxRequest = new AjaxRequest();
        ajaxRequest.setSource(pageProperties.getPath() + "/location_item.jsp");
        ajaxRequest.setData(this.getParams());
        ajaxRequest.setRequestType(EnumRequestType.Get);
        ajaxRequest.setResponseType(EnumResponseType.Xml);
        ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
        return ajaxRequest.initXmlHttpRequest();
    }
};

LocationItemControl.prototype.responseCallback = function (response)
{
    var location = response.getElementsByTagName("location")[0];
    
    if(location != null)
    {
        var error = location.getAttribute("error");
        if(error == null)
        {
            document.getElementById(this.prefix + "_name").value = "[" + location.getAttribute("countryName") + "] " + location.getAttribute("locationName");
            document.getElementById(this.prefix + "_name").name = location.getAttribute("locationName");
            document.getElementById(this.prefix + "_name").style.color="#000000";
            document.getElementById(this.prefix + "_id").value = location.getAttribute("identifier");
            locationChooserPopupControl.switchModus(this.prefix,"", this.locationType);
            
            var currentLocation = locationList.searchLocation(this.id);
            currentLocation.updateData(this.prefix);
            currentLocation.setCoordinates(location.getAttribute("latitude"),location.getAttribute("longitude"));
            googleMapCoordinates.insertLocation(this.prefix,location.getAttribute("latitude"),location.getAttribute("longitude"));
        }
        else
        {
            var elementName = document.getElementById(this.prefix + "_name");
            
            if(elementName != null)
            {
                locationList.searchLocation(this.id).resetData();
                elementName.value = error;
                elementName.style.color="#929292";
                elementName.style.backgroundColor="#FFB2B2";
            }
        }
    }
    else
    {
        locationList.searchLocation(this.id).resetData();
    }
};

LocationItemControl.prototype.findLocation = function (id, event, locationType)
{
    if(event.keyCode == 13 && id != null)
    {
        this.locationType = locationType;
        this.prefix = "location_" + id;
        this.id = id;
        this.setParams(this.params());
        this.postRequest();
    }
};

LocationItemControl.prototype.findLocationByName = function (id)
{
    if(id != null)
    {
        this.prefix = "location_" + id;
        this.locationType = document.getElementById(this.prefix + "_type").name;
        if(document.getElementById(this.prefix + "_name") != null)
        {
            this.locationName = document.getElementById(this.prefix + "_name").value;
        }
        this.id = id;
        this.setParams(this.params());
        this.postRequest();
    }
};
// --------------------------------------------------------------------------------------------------------------------------------
// ConfirmationControl
// --------------------------------------------------------------------------------------------------------------------------------
function ConfirmationControl ()
{
    this.confirmationText = "";
    this.id = "confirmation";
    this.confirmed = false;
    this.confirmationAction = null;
}

ConfirmationControl.prototype.verify = function(confirmed)
{
    this.confirmed = confirmed;
    this.hide();
    
    if(confirmed)
    {
        eval(this.confirmationAction);
    }
    document.getElementById("result").style.display = "block";
};

ConfirmationControl.prototype.show = function()
{
    document.getElementById("inputFields").style.display = "none";
    document.getElementById("result").style.display = "none";
    var confirmationDialog = document.getElementById(this.id);
    if(confirmationDialog != null)
    {
        confirmationDialog.style.display = "block";
        document.getElementById(this.id + "_text").innerHTML = this.confirmationText;
    }
};

ConfirmationControl.prototype.hide = function()
{
    document.getElementById("inputFields").style.display = "block";
    var confirmationDialog = document.getElementById(this.id);
    confirmationDialog.style.display = "none";
    document.getElementById(this.id + "_text").innerHTML = "";
};

ConfirmationControl.prototype.getConfirmed = function()
{
    return this.confirmed;
};

ConfirmationControl.prototype.setConfirmed = function(confirmed)
{
    this.confirmed = confirmed;
};

ConfirmationControl.prototype.setConfirmationText = function(confirmationText)
{
    this.confirmationText = confirmationText;
};

ConfirmationControl.prototype.setConfirmationAction = function(confirmationAction)
{
    this.confirmationAction = confirmationAction;
};/*
   Copyright 2007-2008 Nico Goeminne (nicogoeminne@gmail.com)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/ 
 
/*
 * Class GReverseGeocoder v1.0.6
 *
 * This class is used to obtain reverse geocodes (addresses) for user specified points.
 * It does not use any caching mechanisme and is limited to 10 000 request per day.
 * It uses both GDirections as GClientGeocoder. The default country is set to "Belguim".
 * The country could be set using the GReverseGeocoder.setBaseCountrybefore method 
 * before any reverse geocoding is attempted.
 *
 * All data is obtained by use of the Google Maps API only! 
 * Therefore Reverse Geocoding is only supported for those countries in which Google Maps
 * supports Geocoding (GClientGeocoder) and Driving Directions (GDirections).
 * As a result only street level results are returned. (No house numbers)
 */

 /* Change Log 5/01/08
  *
  * - Changed getStreet() function
  *     Now numbered roads are parsed correctly 
  * - Added the getPlacemarkProperty(placemark,propertyname) function
  *     The helper function is useful to investigate the resulting placemark.
  *     Since the placemark structure depends on the used data provider, the structure
  *     and property names may be different. This method searches the placemark for a certain
  *	property name. For example, if one needs the postal code:
  *
  *          GEvent.addListener(reversegeocoder, "load", 
  *            function(placemark) {
  *              var postalcodenumber = reversegeocoder.getPlacemarkProperty(placemark,"PostalCodeNumber");
  *              if (postalcodenumber != null) alert("Postal Code Number: " + postalcodenumber);
  *              else alert("Postal Code Number Unknown");
  *            }
  *          ); 
  *             
  */
 
 /* Change Log 18/11/07
  *
  * - Removed setBaseCountry() function
  *     The user of the script doesn't have to set the country anymore,
  *     instead the geocoder is provided by a bounding box (works in the 2.x api - fixed by google)
  * - Reported lng bug to google
  */
  
 
/*
 * Creates a new instance of a reversegeocoder.
 * Note that the reverseGeocode() method initiates a new query, 
 * which in turn triggers a "load" event once the query has finished loading.
 *
 * Additionally, the object contains thwo event listeners which you can intercept: 
 *  "load":  This event is triggered when the results of a reverse geocode query issued via 
 *           GReverseGeocoder.reverseGeocode() are available. Note that the reverseGeocode() method
 *           initiates a new query, which in turn triggers a "load" event once the query has finished
 *           loading. 
 *  "error": This event is triggered if a reverse geocode request results in an error. 
 *           Callers can use GReverseGeocoder.getStatus() to get more information about the error.
 *           In GReverseGeocoder v1.0 the getStatus() method proxies the GDirections.getStatus() behavior.
 */
function GReverseGeocoder(map) {
  // we don't actually need the map variable but to be sure the Google Map API
  // is loaded
  this.map=map;
  this.gdirections = new GDirections();
  this.geocoder = new GClientGeocoder();
  this.lastpoint=null;
  this.closestonroad=null;
  this.experimental=false;
  this.ad="";
  this.step=10;
  this.start=1;
  this.gdirectionsrefine = new GDirections();  
  GEvent.bind(this.gdirections, "error", this, this.handleError);
  GEvent.bind(this.gdirections, "load", this, this.processDirection);
  GEvent.bind(this.gdirectionsrefine, "error", this, this.handleError);
  GEvent.bind(this.gdirectionsrefine, "load", this, this.processDirectionRefine);
}

/*
 * This method issues a new reverse geocode query.
 * The parameter is a GLatLng point. 
 * If successful the Placemark object is passed to the user-specified 
 * listener. 
 *
 * E.g. var listener = GEvent.addListener(reversegeocoder,"load",
 *        function(placemark){
 *          alert("The reverse geocoded address is " + placemark.address);                               
 *        }
 *      );
 */
GReverseGeocoder.prototype.reverseGeocode = function(point){
  this.lastpoint = point;
  this.closestonroad = null;
  this.gdirections.clear();
  this.gdirections.loadFromWaypoints([point.toUrlValue(6),point.toUrlValue(6)],{getSteps: true, locale: "GB", getPolyline:true});
}

/*
 * Returns the status of the reverse geocode request.
 * In GReverseGeocoder v1.0 the getStatus() method proxies the GDirections.getStatus() behavior.
 * The returned object has the following form: {   code: 200   request: "directions" } 
 * The status code can take any of the values defined in GGeoStatusCode. (Since Google Map API 2.81)
 */
GReverseGeocoder.prototype.getStatus = function(){
  return this.gdirections.getStatus();
}


/*
 * Private implementation methods
 */

/*
 * This method is called when a GDirection error occurs,
 * or if the GReverseGeocoder does not find an address.
 */
GReverseGeocoder.prototype.handleError = function() {
  GEvent.trigger(this, "error");
}

/*
 * This method first gets the closest street using GDirections,
 * then tries to find addresses by combinating that street
 * with the supplied country using the GClientGeocoder. 
 * This can result in multiple addresses and is filtered 
 * by the GReverseGeocoder.getBestMatchingPlacemark() method.
 */
GReverseGeocoder.prototype.processDirection = function() {
  var source = this;
  // snap to road
  if ( this.gdirections.getPolyline() != null){
    this.closestonroad=this.gdirections.getPolyline().getVertex(0);;
  }
  
  var nrroutes = this.gdirections.getNumRoutes();
  if (nrroutes != 0) {
    var route = this.gdirections.getRoute(0);
    var nrsteps = route.getNumSteps();
    if (nrsteps != 0) {
      var step = route.getStep(0);
      var street = step.getDescriptionHtml();
      /* v102 */
      street = this.getStreet(street);
      var sw = new GLatLng(Number(this.lastpoint.lat()) - 0.01, Number(this.lastpoint.lng()) - 0.01);
      var ne = new GLatLng(Number(this.lastpoint.lat()) + 0.01, Number(this.lastpoint.lng()) + 0.01);
      var bounds = new GLatLngBounds(sw, ne);
      this.geocoder.setViewport(bounds);
      /* end change */
      this.geocoder.getLocations(street,
        function(response) {
          var placemark = source.getBestMatchingPlacemark(response);
          if (placemark != null) {
            if(source.experimental) {
            	source.ad = placemark.address;
            	source.step=10;
            	source.start=1;
            	source.houseNumberSearch();
            }
            else {
            	GEvent.trigger(source, "load", placemark);
            }
          }
          else{
            source.handleError();
          }
        }
      );
    }
  }  
}

/*
 * Finds the closest address towards the original point
 * form the resultset obtained by the GClientGeocoder request.
 * In GReverseGeocoder v1.0 an address is considered only if
 * it is within 1000m. If none of the addresses is in this range
 * the query will fail.
 */
 // TODO: the minimum Accuracy should be an optional parameter in
 // the GReverseGeocoder.
GReverseGeocoder.prototype.getBestMatchingPlacemark = function(response){
  if (!response || response.Status.code != 200) return null;
  var j = -1;
  var mindist = 1000000;
  for (var i = 0; i < response.Placemark.length; i++){
    var place = response.Placemark[i];
    var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    var temp = this.lastpoint.distanceFrom(point);
    if (temp < mindist) {
      j = i;
      mindist = temp;
    }
  }
  if(j < 0 ) return null;
  response.Placemark[j].RequestPoint = {
    "coordinates":[this.lastpoint.lng(),this.lastpoint.lat()]
  }
  response.Placemark[j].PointOnRoad = {
      "coordinates":[this.closestonroad.lng(),this.closestonroad.lat()]
  }
  response.Placemark[j].Distance=mindist;
  response.Placemark[j].DistanceOnRoad=this.closestonroad.distanceFrom(new GLatLng(response.Placemark[j].Point.coordinates[1], response.Placemark[j].Point.coordinates[0]));
  return response.Placemark[j];
}

   
 /*
 
 {	"id":"",
  	"address":"Binnenweg 41, 9050 Ledeberg, Gent, Belgium",
  	"AddressDetails":{
  		"Country":{
  			"CountryNameCode":"BE",
  			"AdministrativeArea":{
  				"AdministrativeAreaName":"Vlaams Gewest",
  				"SubAdministrativeArea":{
  					"SubAdministrativeAreaName":"Oost-Vlaanderen",
  					"Locality":{
  						"LocalityName":"Gent",
  						"DependentLocality":{
  							"DependentLocalityName":"Ledeberg",
  							"Thoroughfare":{
  								"ThoroughfareName":"Binnenweg 41"
  							},
  							"PostalCode":{
  								"PostalCodeNumber":"9050"
  							}
  						}
  					}
  				}
  			}
  		},
  		"Accuracy": 8
  	},
  	"Point":{
  		"coordinates":[3.739867,51.036155,0]
  	}
  }
 
 */

GReverseGeocoder.prototype.processDirectionRefine = function(){
  var nrgeocodes = this.gdirectionsrefine.getNumGeocodes();
  var j = -1;
  var mindist = 100;
  for (var i = 1; i < nrgeocodes; i++){
    var place = this.gdirectionsrefine.getGeocode(i);
    var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    if (place.AddressDetails.Accuracy == 8){
      var temp = this.lastpoint.distanceFrom(point);
      if (temp < mindist) {
        j = i;
        mindist = temp;
      }	
    }
  }
  if(j < 0 ) {
    if ( this.start + (24 * this.step) < 2000){
    	this.start = this.start + (25 * this.step);
    	this.houseNumberSearch();
    }
    else {
    	// house number above 2000 give up.
    	this.handleError();
    }	
  }
  else {
    if (this.step == 1){
        var placemark = this.gdirectionsrefine.getGeocode(j);
        placemark.RequestPoint = {
          "coordinates":[this.lastpoint.lng(),this.lastpoint.lat()]
        }
        placemark.PointOnRoad = {
          "coordinates":[this.closestonroad.lng(),this.closestonroad.lat()]
        }
               
        placemark.Distance=mindist;
        placemark.DistanceOnRoad=this.closestonroad.distanceFrom(new GLatLng(placemark.Point.coordinates[1], placemark.Point.coordinates[0]));
     	GEvent.trigger(this, "load", placemark);
    }
    else{
    	var place = this.gdirectionsrefine.getGeocode(j);
    	var nr = this.start + (j * this.step);
    	
    	
    	// var nr = place.address.split(",",1)[0].split(" ");
    	
    	
	/* belguim format is <street><nr> while the us format is <nr><street>*/ 
	//if ( ('' + Number(nr[nr.length-1])) == 'NaN') {
	//  nr =nr[0];
	//}
	//else {
	//  nr = nr[nr.length-1];
	//}
	this.start = nr - 10;
	this.step = 1;
	this.houseNumberSearch();
    }
  }
}

GReverseGeocoder.prototype.houseNumberSearch = function(){
  this.gdirectionsrefine.clear();
  
  
  this.gdirectionsrefine.loadFromWaypoints([
  	("" + (this.start + (0 * this.step))  + " ") + this.ad,
  	("" + (this.start + (1 * this.step))  + " ") + this.ad,
  	("" + (this.start + (2 * this.step))  + " ") + this.ad,
  	("" + (this.start + (3 * this.step))  + " ") + this.ad,
  	("" + (this.start + (4 * this.step))  + " ") + this.ad,
  	("" + (this.start + (5 * this.step))  + " ") + this.ad,
  	("" + (this.start + (6 * this.step))  + " ") + this.ad,
  	("" + (this.start + (7 * this.step))  + " ") + this.ad,
  	("" + (this.start + (8 * this.step))  + " ") + this.ad,
  	("" + (this.start + (9 * this.step))  + " ") + this.ad,
  	("" + (this.start + (10 * this.step))  + " ") + this.ad,
  	("" + (this.start + (11 * this.step))  + " ") + this.ad,
  	("" + (this.start + (12 * this.step))  + " ") + this.ad,
  	("" + (this.start + (13 * this.step))  + " ") + this.ad,
  	("" + (this.start + (14 * this.step))  + " ") + this.ad,
  	("" + (this.start + (15 * this.step))  + " ") + this.ad,
  	("" + (this.start + (16 * this.step))  + " ") + this.ad,
  	("" + (this.start + (17 * this.step))  + " ") + this.ad,
  	("" + (this.start + (18 * this.step))  + " ") + this.ad,
  	("" + (this.start + (19 * this.step))  + " ") + this.ad,
  	("" + (this.start + (20 * this.step))  + " ") + this.ad,
  	("" + (this.start + (21 * this.step))  + " ") + this.ad,
  	("" + (this.start + (22 * this.step))  + " ") + this.ad,
  	("" + (this.start + (23 * this.step))  + " ") + this.ad,
  	("" + (this.start + (24 * this.step))  + " ") + this.ad
  ],{getSteps: true, locale: "GB"});
}

/*
 * Cuts out the street form the GDirections result.  
 */
// The Google Map API team should consider to give back a 
// well defined stucture on the GStep.getDescriptionHtml()
// method rather than some arbitrary html
// or better, just provid us with a reverse geocoder
// Fixed Thanks to eugene at tsyrklevich.name
// Fixed Thanks to SC
GReverseGeocoder.prototype.getStreet = function(street){

  /* Modified by SC (02/03/08) because Google changed format */
  // extract Street from "Head <b>direction</b> on <b>Street</b> toward <b>Street2</b>"
  var str = street.split("</b>")[1];
  str =  str.substring(str.indexOf("<b>")+3);
  
  // is the street name specified as a road name + street name?
  // (e.g. "Abbey St/<wbr/>B202" or "A2205/<wbr/>Bermondsey St")
  if (str.indexOf("/<wbr/>") > 0) {
    // if so, extract the street name and drop the numeric road name
    strs = str.split("/<wbr/>");
  
    // we idenitfy numeric roads by checking if the 2nd character of the street name is a digit
    if (strs[0].charAt(1) >= "0" && strs[0].charAt(1) <= "9") {
      str = strs[1];
    }
    else {
      str = strs[0];
    }
  } 
  return str;
}

GReverseGeocoder.prototype.setExperimentalHouseNumber = function (setting){
  this.experimental = setting;
}

GReverseGeocoder.prototype.getPlacemarkProperty = function (placemark,propertyname){
  for (var property in placemark) {
    if((property == propertyname)) {
      return String(placemark[property]);
    } else if (typeof(placemark[property]) == 'object') {
      var r = this.getPlacemarkProperty(placemark[property], propertyname);
      if (r != null) return r;
    }
  }
  return null;
}// --------------------------------------------------------------------------------------------------------------------------------
// LocationControl
// --------------------------------------------------------------------------------------------------------------------------------
function LocationControl (
        mainWidth, 
        lableWidth,
        fieldWidth, 
        settingMarginLeft, 
        locationPadding,
        locationBorder)
{
    this.elementsId = new Array();
    this.mainWidth = mainWidth;
    this.lableWidth = lableWidth;
    this.fieldWidth = fieldWidth;
    this.settingMarginLeft = settingMarginLeft;
    this.locationPadding = locationPadding;
    this.locationBorder = locationBorder;
    this.locationArrowDownUp = 15;
}

LocationControl.prototype.addElementId = function(id)
{
    this.elementsId.push(id);
};

LocationControl.prototype.hideDelButton = function(id)
{
    document.getElementById(id + "_delbt").style.visibility = hidden;
};

LocationControl.prototype.getElementsId = function()
{
    return this.elementsId;
};

LocationControl.prototype.onClick = function(fieldName)
{
    var element = document.getElementById(fieldName);
    var color = element.style.color;
    var bgcolor = element.style.backgroundColor;
    
    if(color != "rgb(0,0,0)" && color != "rgb(0, 0, 0)")
    {
        element.style.color="rgb(0, 0, 0)";
        element.value="";
    }
};


// --------------------------------------------------------------------------------------------------------------------------------
// VehiclesListControl
// --------------------------------------------------------------------------------------------------------------------------------
function VehiclesListControl (requestPage, prefix, language, transportMode, chainId, sectionId)
{
    this.prefix = prefix;
    this.requestPage = requestPage;
    this.language = language;
    this.paramList = "";
    this.transportMode = transportMode;
    this.chainId = chainId;
    this.sectionId = sectionId;
}

VehiclesListControl.prototype.params = function ()
{
    var req = new RequestParameters();

    req.add("jsPrefix", this.prefix);
    req.add("lang", this.language);
    if(document.getElementById("cargoUnit") != null)
    {
        req.add("cargoUnit", document.getElementById("cargoUnit").name);
    }
    if(document.getElementById(this.prefix + "_vehicleType") != null)
    {
        req.add("transportType", fixedEncodeURIComponent(document.getElementById(this.prefix + "_vehicleType").name));
    }
    req.add("transportMode", this.transportMode);
    
    if("Air" == this.transportMode)
    {
        if(document.getElementById(this.prefix + '_bellyFreightCB').checked)
        {
            req.add("filter", "BellyFreight");
        }
        else
        {
            req.add("filter", "Freighter");
        }
    }
    req.add("chainId", this.chainId);
    req.add("sectionId", this.sectionId);

    return req.toString();
};

VehiclesListControl.prototype.setParams = function(paramList)
{
    this.paramList = paramList;
};

VehiclesListControl.prototype.getParams = function()
{
    return this.paramList; 
};

VehiclesListControl.prototype.responseCallback = function (response)
{
    document.getElementById(this.prefix + "_vehicle_resultlist").innerHTML = response;
};

VehiclesListControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(this.requestPage);
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

VehiclesListControl.prototype.update = function (response)
{
    this.setParams(this.params());
    this.postRequest();
};
// --------------------------------------------------------------------------------------------------------------------------------
// ComboBoxControl
// --------------------------------------------------------------------------------------------------------------------------------
function ComboBoxControl ()
{
    this.prefix = null;
    this.currentElementId = null;
    this.currentElement = null;
    this.resultDivId = null;
    this.switchButtonId = null;
    this.rowCount = null;
    this.currentTop = 0;
    this.updated = false;
}

ComboBoxControl.prototype.init = function(prefix, resultDivId, switchButtonId)
{
    this.prefix = prefix;
    this.resultDivId = resultDivId;
    this.switchButtonId = switchButtonId;
    document.onkeydown = this.onkeypress;

};

ComboBoxControl.prototype.onMouseover = function(elementId)
{
    if(!this.updated)
    {
        this.updateElements(elementId);
    }
    else
    {
        this.updated = false;
    }
};

ComboBoxControl.prototype.markElement = function(element)
{
    if(element != null)
    {
        element.style.backgroundColor = "#0095d5";
    }
};

ComboBoxControl.prototype.unmarkElement = function(element)
{
    if(element != null)
    {
        element.style.backgroundColor = "#fff";
    }
};

ComboBoxControl.prototype.onkeypress = function(e)
{
    var resultList = document.getElementById(comboBoxControl.getResultDivId());
    var element = document.getElementById(comboBoxControl.prefix + "_Element_" + comboBoxControl.currentElementId);
    if(resultList != null)
    {
        resultList.focus();
        if(comboBoxControl.getRowCount() == null)
        {
             comboBoxControl.setRowCount(resultList.getElementsByTagName("tr").length-1);
        }
    }
    
    e= window.event || e;
  
    e.cancelBubble=true;
   
    e= e.charCode || e.keyCode;
    
    // down
    if(e == 40)
    {
        var elementId = 0;
        if(comboBoxControl.getCurrentElementId() != null)
        {
            var elementId = comboBoxControl.getCurrentElementId()+1;
        }
        comboBoxControl.updateAndScroll(elementId);
    }
    
    // up
    else if(e == 38)
    {
        var elementId = 0;
        if(comboBoxControl.getCurrentElementId() != null)
        {
            var elementId = comboBoxControl.getCurrentElementId()-1;
        }
        comboBoxControl.updateAndScroll(elementId);
    }
    
    // page up
    else if(e == 33)
    {
        var elementId = 0;
        if(comboBoxControl.getCurrentElementId() != null)
        {
            var elementId = comboBoxControl.getCurrentElementId()-10;
            
            if(elementId < 0)
            {
                 elementId = 0;
            }
        }
        comboBoxControl.updateAndScroll(elementId);
    }
    
    // page down
    else if(e == 34)
    {
        var elementId = 0;
        if(comboBoxControl.getCurrentElementId() != null)
        {
            var elementId = comboBoxControl.getCurrentElementId()+10;
            
            if(elementId > comboBoxControl.getRowCount())
            {
                 elementId = comboBoxControl.getRowCount();
            }
        }
        comboBoxControl.updateAndScroll(elementId);
    }
    
    // home
    else if(e == 36)
    {
        var elementId = 0;
        comboBoxControl.updateAndScroll(elementId);
    }
    
    // end
    else if(e == 35)
    {
        var elementId = comboBoxControl.getRowCount();
        comboBoxControl.updateAndScroll(elementId);
    }
    
    // enter or tab
    else if(e == 13 || e == 9)
    {
        if(element != null)
        {
            var clickevent = element.getAttribute("onclick");
            
            if(clickevent != null)
            {
                // IE
                if(typeof clickevent == 'function')
                {
                     clickevent() ;
                }
                // Rest
                else
                {
                    eval(clickevent);
                }
            }
        comboBoxControl.clear();
        }
    }
    
    // escape
    else if(e == 13)
    {
        var switchElement = document.getElementById(comboBoxControl.getSwitchButtonId());
        if(switchElement != null)
        {
            var clickevent = switchElement.getAttribute("onclick");
            
            if(clickevent != null)
            {
                // IE
                if(typeof clickevent == 'function')
                {
                     clickevent() ;
                }
                // Rest
                else
                {
                    eval(clickevent);
                }
            }
        comboBoxControl.clear();
        }
    }
    return false; 
};

ComboBoxControl.prototype.setCurrentValues = function(elementId)
{
    this.currentElementId = parseInt(elementId);
    this.currentElement = document.getElementById(this.prefix + "_Element_" + this.currentElementId);
};

ComboBoxControl.prototype.updateElements = function(elementId)
{
    if(document.getElementById(this.prefix + "_Element_" + elementId) != null)
    {
        this.unmarkElement(this.currentElement);
    
        var offset = parseInt(0);
        if(this.currentElementId < parseInt(elementId))
        {
            for ( var i = this.currentElementId; i < parseInt(elementId); i++)
            {
                var element = document.getElementById(this.prefix + "_Element_" + i);
                if(element != null)
                {
                    offset += parseInt(elementHeight(element));
                }
            }
            this.currentTop += offset;
        }
        else if(this.currentElementId > parseInt(elementId))
        {
            for ( var i = parseInt(elementId); i < this.currentElementId; i++)
            {
                var element = document.getElementById(this.prefix + "_Element_" + i);
                if(element != null)
                {
                    offset += parseInt(elementHeight(element));
                }
            }
             this.currentTop -= offset;
        }
    this.setCurrentValues(parseInt(elementId));
    this.markElement(this.currentElement);
    }
};

ComboBoxControl.prototype.updateAndScroll = function(elementId)
{
    this.updated = true;
    comboBoxControl.updateElements(elementId);
    var resultList = document.getElementById(comboBoxControl.getResultDivId());
    
    if(resultList != null)
    {
        resultList.focus();
        resultList.scrollTop = this.currentTop;
    }
};

ComboBoxControl.prototype.getCurrentElementId = function()
{
    return this.currentElementId;
};

ComboBoxControl.prototype.getCurrentElement = function()
{
    return this.currentElement;
};

ComboBoxControl.prototype.getResultDivId = function()
{
    return this.resultDivId;
};

ComboBoxControl.prototype.getSwitchButtonId = function()
{
    return this.switchButtonId;
};

ComboBoxControl.prototype.getPrefix = function()
{
    return this.prefix;
};

ComboBoxControl.prototype.setRowCount = function(rowCount)
{
    this.rowCount = rowCount;
};

ComboBoxControl.prototype.setCurrentTop = function(top)
{
    this.currentTop = top;
};

ComboBoxControl.prototype.getRowCount = function()
{
    return this.rowCount;
};

ComboBoxControl.prototype.clear = function()
{
    this.prefix = null;
    this.currentElementId = null;
    this.currentElement = null;
    this.resultDiv = null;
    this.switchButton = null;
    this.rowCount = null;
    this.currentTop = 0;
    this.updated = false;
    document.onkeydown = "";
};// --------------------------------------------------------------------------------------------------------------------------------
// ResultDisplayControl
// --------------------------------------------------------------------------------------------------------------------------------
function ResultDisplayControl (requestPage,
                               language,
                               id)
{
    this.requestPage = requestPage;
    this.language = language;
    this.divId = id;
    
    this.paramList = null;
}

ResultDisplayControl.prototype.params = function ()
{
    var result = "";
    
    var splittedParamList = this.paramList.split('&');
    for(var element = 0; element < splittedParamList.length; element++)
    {
        if(splittedParamList[element] != null)
        {
            var splittedElement = splittedParamList[element].split('=');
            result += "&" + splittedElement[0] + "=" + escape(splittedElement[1]);
        }
    }
    result += "&lang=" + escape(this.language);
    
    var origin = locationList.searchLocation(0);
    var originName = origin.getName();
    if (originName == null || originName == "")
    {
        originName = origin.getLatitude().toString() + "/" + origin.getLongitude().toString();
    }
    result += "&originName=" + originName;
    result += "&originLatitude=" + origin.getLatitude().toString();
    result += "&originLongitude=" + origin.getLongitude().toString();
    
    var destination = locationList.searchLocation(1);
    var destinationName = destination.getName();
    if (destinationName == null || destinationName == "")
    {
    	destinationName = destination.getLatitude().toString() + "/" + destination.getLongitude().toString();
    }
    result += "&destinationName=" + destinationName;
    result += "&json=" + resultControl.getJsonObject();

    return result;
};

ResultDisplayControl.prototype.getSimpleParams = function ()
{
    var result = "";
    
    var splittedParamList = this.paramList.split('&');
    for(var element = 0; element < splittedParamList.length; element++)
    {
        if(splittedParamList[element] != null)
        {
            var splittedElement = splittedParamList[element].split('=');
            result += "&" + splittedElement[0] + "=" + escape(splittedElement[1]);
        }
    }
    result += "&lang=" + escape(this.language);
    
    var origin = locationList.searchLocation(0);
    var originName = origin.getName();
    if (originName == null || originName == "")
    {
        originName = origin.getLatitude().toString() + "/" + origin.getLongitude().toString();
    }
    result += "&originName=" + originName;
    
    var destination = locationList.searchLocation(1);
    var destinationName = destination.getName();
    if (destinationName == null || destinationName == "")
    {
        destinationName = destination.getLatitude().toString() + "/" + destination.getLongitude().toString();
    }
    result += "&destinationName=" + destinationName;

    return result;
};

ResultDisplayControl.prototype.setParams = function (paramList)
{
    this.paramList = paramList;
};

ResultDisplayControl.prototype.getParams = function()
{
    return this.params(); 
};

ResultDisplayControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(this.requestPage);
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

ResultDisplayControl.prototype.responseCallback = function (response)
{
    document.getElementById(this.divId).innerHTML = response;
};

ResultDisplayControl.prototype.update = function ()
{
    this.postRequest();
};

// --------------------------------------------------------------------------------------------------------------------------------
// ViewModeControl
// --------------------------------------------------------------------------------------------------------------------------------
function ViewModeControl (id)
{
    this.id = id;
    this.inputMode = "standard";
    this.newMode = "standard";
    
    this.responseCallbacks = new Array();
    this.callbackFunctions = new Array();
    
    this.popupControlPrefix = null;
    this.popupControlClickedItem = null;
}

ViewModeControl.prototype.init = function(popupControlPrefix,
                                          popupControlClickedItem)
{
    this.popupControlPrefix = popupControlPrefix;
    this.popupControlClickedItem = popupControlClickedItem;
};

ViewModeControl.prototype.switchMode = function(inputMode)
{
    if(this.inputMode != "standard"
        && this.inputMode != inputMode)
    {
        this.newMode = inputMode;
    }
    else if(this.inputMode != "extended"
        && !confirmationControl.getConfirmed())
    {
        this.newMode = inputMode;
        confirmationControl.setConfirmed(true);
    }
    else if(confirmationControl.getConfirmed())
    {
        this.newMode = inputMode;
    }
    else
    {
    	this.newMode = this.inputMode;
    }
};

ViewModeControl.prototype.params = function()
{
    var result = "";
    result += "&lang=" + fixedEncodeURIComponent(pageProperties.getLanguage());
    result += "&inputmode=" + fixedEncodeURIComponent(this.inputMode);
    
    return result;
};

ViewModeControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(pageProperties.getPath() + "/viewmode.jsp");
    ajaxRequest.setData(this.params());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

ViewModeControl.prototype.responseCallback = function (response)
{
    document.getElementById(this.id).innerHTML = response;
    
    transportChainsControl.reset();
    
    if(this.inputMode == 'standard')
    {
        standardTransportModeControl.reset();
    }
    else
    {
        this.inputMode = 'extended';
        transportChainsControl.init();
    }
};

ViewModeControl.prototype.update = function ()
{
    this.inputMode = this.newMode;
    if(this.inputMode != null
            && confirmationControl.getConfirmed())
    {
        layerControl.reset();
        resultControl.resetFields();
        if(this.popupControlPrefix != null
                && this.popupControlClickedItem != null)
        {
            popupControl.setPrefix(this.popupControlPrefix);
            popupControl.clickedItem(this.popupControlClickedItem);
            
            this.popupControlPrefix = null;
            this.popupControlClickedItem = null;
        }
        confirmationControl.setConfirmed(false);
        
        resultControl.clearResultDisplay();
        this.postRequest();
    }
};

ViewModeControl.prototype.getInputMode = function ()
{
    return this.inputMode;
};
// --------------------------------------------------------------------------------------------------------------------------------
// VehiclesChooserPopupControl
// --------------------------------------------------------------------------------------------------------------------------------
function VehiclesChooserPopupControl (ajaxPopupControl, language)
{
    this.elementPrefix = null;
    this.vehicleName = null;
    this.ajaxPopupControl = ajaxPopupControl;
    this.language = language;
    this.transportMode = null;
    this.mainPrefix = null;
    this.chainId = null;
    this.sectionId = null;
}

VehiclesChooserPopupControl.prototype.init = function(mainPrefix, elementPrefix, transportMode, chainId, sectionId)
{
    this.mainPrefix = mainPrefix;
    this.elementPrefix = elementPrefix;
    this.transportMode = transportMode;
    this.vehicleName = document.getElementById(this.elementPrefix + "_vehicleName");
    this.chainId = chainId;
    this.sectionId = sectionId;
};

VehiclesChooserPopupControl.prototype.params = function()
{
    var req = new RequestParameters();

    req.add("jsPrefix", this.mainPrefix);
    req.add("lang", this.language);
    if(document.getElementById("cargoUnit") != null)
    {
        req.add("cargoUnit", document.getElementById("cargoUnit").name);
    }
    if(document.getElementById(this.mainPrefix + "_vehicleType") != null)
    {
        req.add("transportType", fixedEncodeURIComponent(document.getElementById(this.mainPrefix + "_vehicleType").name));
    }
    req.add("transportMode", this.transportMode);
    
    if("Air" == this.transportMode)
    {
        if(document.getElementById(this.mainPrefix + '_bellyFreightCB').checked)
        {
            req.add("filter", "BellyFreight");
        }
        else
        {
            req.add("filter", "Freighter");
        }
    }
    req.add("chainId", this.chainId);
    req.add("sectionId", this.sectionId);

    return req.toString();
};

VehiclesChooserPopupControl.prototype.clickedItem = function (vehicleName)
{
    // Complete the input values
    this.vehicleName.value = vehicleName;

    // Hiding the popup
    this.ajaxPopupControl.hide();
    var switchButton = document.getElementById(this.elementPrefix + "_vehicle_switch");
    switchButton.src = switchButton.src.replace(/up.gif/, "down.gif");
};

VehiclesChooserPopupControl.prototype.keyPress = function (event)
{
    // Clear the input if a key is pressed 
    // input field, et vice versa.
    if (getSourceElementFromEvent(event).name == (this.vehicleName))
    {
        this.vehicleName.value = "";
    }
    
    if(this.vehicleName.value.search(/]/) != -1)
    {
        this.vehicleName.value = this.vehicleName.value.substr(5);
    }

    if(this.vehicleName.value.length >= 3 && event.keyCode == 13 || event.keyCode == 9)
    {
        layerControl.tooglePopupOnKeyup(this.mainPrefix,this.mainPrefix + "_selected_form",this.elementPrefix + "_vehicle_resultlist", "vehiclePopup-" + this.transportMode);
        var switchButton = document.getElementById(this.elementPrefix + "_vehicle_switch");
        switchButton.src = switchButton.src.replace(/down.gif/, "up.gif");
        document.getElementById(this.elementPrefix + "_vehicle_loading").style.display = "block";
        this.ajaxPopupControl.setParams(this.params());
        this.ajaxPopupControl.restartTimer();
    }
    
};

VehiclesChooserPopupControl.prototype.clickedPopupSwitch = function (listButton)
{   
    if (!this.ajaxPopupControl.shown)
    {
        document.getElementById(this.elementPrefix + "_vehicle_resultlist").style.display = "block";
        
        this.ajaxPopupControl.setParams(this.params());
    }
    
    this.ajaxPopupControl.clickedPopupSwitch(listButton);
};

VehiclesChooserPopupControl.prototype.addInputClickedCallback = function(callback)
{
    Compat.addEventListener(this.vehicleName, 'click', callback.getFunction());
    Compat.addEventListener(document.getElementById(this.elementPrefix + "_vehicle_switch"), 'click', callback.getFunction());
};

VehiclesChooserPopupControl.prototype.getVehicleName = function ()
{
    return this.vehicleName;
};// --------------------------------------------------------------------------------------------------------------------------------
// PopupControl
// --------------------------------------------------------------------------------------------------------------------------------
function PopupControl ()
{
    this.prefix = null;
    
    this.shown = false;
    
    this.callbackFunctions = new Array();
}

PopupControl.prototype.init = function ()
{
    this.input = document.getElementById(this.prefix);
    this.popupDiv = document.getElementById(this.prefix + "_popupdiv");
    this.switchButton = document.getElementById(this.prefix + "_switch");
};

PopupControl.prototype.clickedItem = function (value)
{
    this.init();
    this.hide();
    this.input.value = value;
};

PopupControl.prototype.toggleDisplay = function()
{
    this.init();
    if (this.shown)
    {
        this.hide();
    }
    else
    {
        this.show();
    }

    for (var callbackIndex = 0; callbackIndex < this.callbackFunctions.length; callbackIndex++)
    {
        this.callbackFunctions[callbackIndex].run();
    }
};

PopupControl.prototype.toogleToolTip = function (mainDivID,toolTipDivId,comboBoxID)
{
    this.init();
    
    if (this.shown)
    {
        this.hide();
        layerControl.toogleToolTip(mainDivID,toolTipDivId,comboBoxID);
    }
    else
    {
            this.show();
            toogleToolTip.toogleToolTip(mainDivID,toolTipDivId,comboBoxID);
    }  
    
    for (var callbackIndex = 0; callbackIndex < this.callbackFunctions.length; callbackIndex++)
    {
        this.callbackFunctions[callbackIndex].run();
    }
};

PopupControl.prototype.show = function ()
{
    this.popupDiv.style.display = "block";
    this.switchButton.src = this.switchButton.src.replace(/down.gif/, "up.gif");
    
    
    this.shown = true;
};

PopupControl.prototype.hide = function ()
{
    this.popupDiv.style.display = "none";
    this.switchButton.src = this.switchButton.src.replace(/up.gif/, "down.gif");
    
    this.shown = false;
};

PopupControl.prototype.addCallbackFunction = function (callback)
{
    this.callbackFunctions.push(callback);
};

PopupControl.prototype.getInput = function ()
{
    return this.input;
};

PopupControl.prototype.setPrefix = function (prefix)
{
    this.prefix = prefix;
};
// --------------------------------------------------------------------------------------------------------------------------------
// LocationChooserPopupControl
// --------------------------------------------------------------------------------------------------------------------------------
function LocationChooserPopupControl ()
{
    this.elementPrefix = null;
    this.locationInput = null;
    this.locationType = null;
    this.ajaxPopupControl = new AjaxPopupControl(pageProperties.getPath() + "/location_list.jsp");
    this.previousLength = 0;
    this.locationId = null;
}

LocationChooserPopupControl.prototype.init = function(prefix, locationType, locationName, locationId)
{
    this.elementPrefix = prefix;
    this.locationType = document.getElementById(locationType).name;
    this.locationInput = document.getElementById(locationName);
    this.locationId = locationId;
    
    this.ajaxPopupControl.init(prefix, prefix + "_resultlist", prefix + "_loading");
};

LocationChooserPopupControl.prototype.params = function()
{
    var req = new RequestParameters();

    req.add("jsPrefix", this.elementPrefix);
    req.add("lang", pageProperties.getLanguage());
    req.add("locationType", fixedEncodeURIComponent(this.locationType));
    req.add("searchParam", fixedEncodeURIComponent(this.locationInput.value));
    
    if(this.locationId != null)
    {
        req.add("locationId", this.locationId);
    }

    return req.toString();
};

LocationChooserPopupControl.prototype.clickedItem = function (locationValue)
{
    // Complete the input values
    this.locationInput.value = locationValue;

    // Hiding the popup
    this.ajaxPopupControl.hide();
    var switchButton = document.getElementById(this.elementPrefix + "_switch");
    switchButton.src = switchButton.src.replace(/up.gif/, "down.gif");
};

LocationChooserPopupControl.prototype.keyPress = function (event)
{
    // Clear the input if a key is pressed 
    // input field, et vice versa.
    if (getSourceElementFromEvent(event).name == (this.locationInput))
    {
        this.locationInput.value = "";
    }
    
    if(this.locationInput.value.search(/]/) != -1)
    {
        this.locationInput.value = this.locationInput.value.substr(this.locationInput.value.indexOf("]") + 2);
    }
    if(event.keyCode == 13 || event.keyCode == 40 || event.keyCode == 38)
    {
        this.locationInput.blur();
        layerControl.tooglePopupOnKeyup(this.elementPrefix,this.elementPrefix + "_location", this.elementPrefix + "_resultlist", "locationPopup");
        var switchButton = document.getElementById(this.elementPrefix + "_switch");
        switchButton.src = switchButton.src.replace(/down.gif/, "up.gif");
        document.getElementById(this.elementPrefix + "_loading").style.display = "block";
        document.getElementById(this.elementPrefix + "_location").style.zIndex = 50;
        this.ajaxPopupControl.setParams(this.params());
        this.ajaxPopupControl.restartTimer();
        comboBoxControl.init(this.elementPrefix,"location_list",this.elementPrefix + "_switch");
    }
};

LocationChooserPopupControl.prototype.clickedPopupSwitch = function (listButton)
{
    if (!this.ajaxPopupControl.shown)
    {
        document.getElementById(this.elementPrefix + "_resultlist").style.display = "block";
        comboBoxControl.init(this.elementPrefix,"location_list",this.elementPrefix + "_switch");
        
        this.ajaxPopupControl.setParams(this.params());
        
    }
    
    this.ajaxPopupControl.clickedPopupSwitch(listButton);
};

LocationChooserPopupControl.prototype.addInputClickedCallback = function(callback)
{
    Compat.addEventListener(this.locationInput, 'click', callback.getFunction());
    Compat.addEventListener(document.getElementById(this.elementPrefix + "_switch"), 'click', callback.getFunction());
};

LocationChooserPopupControl.prototype.getLocationInput = function ()
{
    return this.locationInput;
};

LocationChooserPopupControl.prototype.setLocationType = function (locationType)
{
    this.locationType = locationType;
};

LocationChooserPopupControl.prototype.setLocationId = function (field, fieldValue)
{
    document.getElementById(field).value = fieldValue;
};

LocationChooserPopupControl.prototype.switchModus = function (prefix, code, locationType)
{
    var name = document.getElementById(prefix + "_name");
    var editImg = document.getElementById(prefix + "_edit");
    var idField = document.getElementById(prefix + "_id");
    
    if(editImg.style.display == "none")
    {
        document.getElementById(prefix + "_show").style.display = "block";
    }
    else
    {
        document.getElementById(prefix + "_show").style.display = "none";
    }
    
    if(locationType == "Railway")
    {
        var country = document.getElementById(prefix + "_country");
        var uic = document.getElementById(prefix + "_uic");
        
        if(editImg.style.display == "none")
        {
            this.disableField(country);
            this.disableField(uic);
            this.disableField(name);
            this.switchEditImage(prefix);
            if(code != "")
            {
                country.value=code.split("-")[0];
                uic.value=code.split("-")[1];
            }
        }
        else
        {
            this.enableField(country);
            this.enableField(uic);
            this.enableField(name);
            this.switchEditImage(prefix);
            name.value = name.value.split("] ")[1];
            country.value = "";
            uic.value = "";
            idField.value = "";
        }
    }
    else if(locationType == "Airport")
    {
       
        var iata = document.getElementById(prefix + "_iata");
        
        if(editImg.style.display == "none")
        {
            this.disableField(iata);
            this.disableField(name);
            this.switchEditImage(prefix);
            
            if(code != "")
            {
                iata.value = code;
            }
        }
        else
        {
            this.enableField(iata);
            this.enableField(name);
            this.switchEditImage(prefix);
            name.value = name.value.split("] ")[1];
            iata.value = "";
            idField.value = "";
        }
    }
    else if(locationType == "Harbour")
    {
       
        var unlocode = document.getElementById(prefix + "_unlocode");
        
        if(editImg.style.display == "none")
        {
            this.disableField(unlocode);
            this.disableField(name);
            this.switchEditImage(prefix);
            
            if(code != "")
            {
                unlocode.value = code;
            }
        }
        else
        {
            this.enableField(unlocode);
            this.enableField(name);
            this.switchEditImage(prefix);
            name.value = name.value.split("] ")[1];
            unlocode.value = "";
            idField.value = "";
        }
    }
    else if(locationType == "ZIP")
    {
        var country = document.getElementById(prefix + "_country");
        var zip = document.getElementById(prefix + "_zip");
        
        if(editImg.style.display == "none")
        {
            this.disableField(country);
            this.disableField(zip);
            this.disableField(name);
            this.switchEditImage(prefix);
            if(code != "")
            {
                country.value=code.split("-")[0];
                zip.value=code.split("-")[1];
            }
        }
        else
        {
            this.enableField(country);
            this.enableField(zip);
            this.enableField(name);
            this.switchEditImage(prefix);
            name.value = name.value.split("] ")[1];
            country.value = "";
            zip.value = "";
            idField.value = "";
        }
    }
    else
    {
        if(editImg.style.display == "none")
        {
            this.disableField(name);
            this.switchEditImage(prefix);
        }
        else
        {
            this.enableField(name);
            this.switchEditImage(prefix);
            name.value = name.value.split("] ")[1];
            idField.value = "";
        }
    }
};


LocationChooserPopupControl.prototype.disableField = function (field)
{
    field.setAttribute("disabled","disabled");
    field.setAttribute("readOnly","readonly");
    field.style.backgroundColor = "#EEEEEE";
};

LocationChooserPopupControl.prototype.enableField = function (field)
{
    field.removeAttribute("disabled");
    field.removeAttribute('readOnly');
    field.style.backgroundColor = "#FFFFFF";
};

LocationChooserPopupControl.prototype.switchEditImage = function (prefix)
{
    var switchImg = document.getElementById(prefix + "_switch");
    var editImg = document.getElementById(prefix + "_edit");
    
    if(editImg.style.display == "none")
    {
        switchImg.style.display = "none";
        editImg.style.display = "block";
    }
    else
    {
        switchImg.style.display = "block";
        editImg.style.display = "none";
    }
};
// --------------------------------------------------------------------------------------------------------------------------------
// LocationTypeSwitchControl
// --------------------------------------------------------------------------------------------------------------------------------
function LocationTypeSwitchControl ()
{
    this.paramList = null;
    this.inputId = null;
    this.locationId = null;
    this.innerHtmlId = null;
    this.setInputValue = null;
    this.locationPrefix = null;
}

LocationTypeSwitchControl.prototype.init = function(inputId, innerHtmlId, locationId)
{
    this.inputId = inputId;
    this.innerHtmlId = innerHtmlId;
    this.locationId = locationId;
};

LocationTypeSwitchControl.prototype.params = function()
{
    var req = new RequestParameters();
    
    req.add("value", fixedEncodeURIComponent(document.getElementById(this.inputId).name));
    req.add("lang", pageProperties.getLanguage());
    req.add("innerHtmlId", this.innerHtmlId);
    req.add("locationId", this.locationId);

    return req.toString();
};

LocationTypeSwitchControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(pageProperties.getPath() + "/location_type_formswitch.jsp");
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

LocationTypeSwitchControl.prototype.responseCallback = function (response)
{
    document.getElementById(this.innerHtmlId).innerHTML = response;
    
    if(formularValidationControl.getFormularFields()[this.locationId + "_longitude"] != null)
    {
        document.getElementById(this.locationId + "_longitude").value = formularValidationControl.getFormularFields()[this.locationId + "_longitude"];
    }
    if(formularValidationControl.getFormularFields()[this.locationId + "_latitude"] != null)
    {
        document.getElementById(this.locationId + "_latitude").value = formularValidationControl.getFormularFields()[this.locationId + "_latitude"]; 
    }
    locationList.searchLocation(this.locationId).resetData();
};

LocationTypeSwitchControl.prototype.setParams = function(paramList)
{
    this.paramList = paramList; 
};

LocationTypeSwitchControl.prototype.getParams = function()
{
    return this.paramList; 
};

LocationTypeSwitchControl.prototype.update = function ()
{
    if(document.getElementById(this.locationId + "_id") != null)
    {
        document.getElementById(this.locationId + "_id").value = null;
    }
    
    if(document.getElementById(this.locationId + "_longitude") != null)
    {
        document.getElementById(this.locationId + "_longitude").value = null;
    }
    
    if(document.getElementById(this.locationId + "_latitude") != null)
    {
        document.getElementById(this.locationId + "_latitude").value = null;
    }
    
    if(this.inputId != null)
    {
        this.setParams(this.params());
        this.postRequest();
    }
};
//GoogleMapCoordinates
function GoogleMapCoordinates()
{
   this.coordinate_display = document.getElementById("coordinate_background");
   this.coordinate_map = document.getElementById("coordinate_map");
   this.latitudeField = document.getElementById("coordinate_latitude");
   this.longitudeField = document.getElementById("coordinate_longitude");
   this.searchField = document.getElementById("coordinate_search");
   this.resultLatitudeField = "";
   this.resultLongitudeField = "";
   this.locationLatitudeArray = new Array();
   this.locationLongitudeArray = new Array();
   this.logged = true;
   this.locationId = null;
}

GoogleMapCoordinates.prototype.open = function (locationId, latitudeField, longitudeField, info)
{
   this.locationId = locationId;
   this.latitudeField.value=latitudeField.value;
   this.longitudeField.value=longitudeField.value;
   this.resultLatitudeField = latitudeField;
   this.resultLongitudeField = longitudeField;
   this.logged = false;
   
   document.getElementById("coordinate_info").style.display = "block";
   document.getElementById("coordinate_info_text").innerHTML = info;
   document.getElementById("coordinate_confirm_button").style.display = "block";
   
   document.getElementById("coordinate_search_div").style.display = "block";
   this.latitudeField.removeAttribute("disabled");
   this.latitudeField.removeAttribute('readOnly');
   this.latitudeField.style.backgroundColor = "#FFFFFF";
   this.longitudeField.removeAttribute("disabled");
   this.longitudeField.removeAttribute('readOnly');
   this.longitudeField.style.backgroundColor = "#FFFFFF";
       
   this.coordinate_display.style.display="block";
   this.coordinate_display.style.zIndex=100;
   this.createMap();
};

GoogleMapCoordinates.prototype.createMap = function ()
{
    if (GBrowserIsCompatible())
    {
        window.scrollTo(0,0);
        this.resetFields();
        
        var map = new GMap(this.coordinate_map);
        
        map.setUIToDefault();
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        
        var longitude = this.longitudeField.value;
        var latitude = this.latitudeField.value;
        var zoom = 4;
        if((longitude == "" && latitude == "") || (longitude == "0" && latitude == "0"))
        {
            zoom = 13;
        }
        var point = new GPoint(new Number(longitude), new Number(latitude));
        var placemark = new GMarker(point);
        map.centerAndZoom(new GPoint(new Number(longitude),new Number(latitude)), zoom);
        map.addOverlay(placemark);
        
        if(!this.logged)
        {
            this.addReversegeocoder(map, placemark);
        }
      
    }
    else
    {
        alert("Sorry, the Google Maps API is not compatible with this browser");
    }
};

GoogleMapCoordinates.prototype.onEnterPress = function (event)
{
      if(event.keyCode == 13)
      {
          this.createMap();
      }
};

GoogleMapCoordinates.prototype.close = function ()
{
    this.resultLatitudeField.value=this.latitudeField.value;
    this.resultLongitudeField.value=this.longitudeField.value;
    this.coordinate_display.style.display="none";
    
    if(this.locationId != null)
    {
        locationList.searchLocation(this.locationId).updateData("location_" + this.locationId);
    }
};

GoogleMapCoordinates.prototype.addReversegeocoder = function (map, placemark)
{
    var reversegeocoder = new GReverseGeocoder(map);
    
    GEvent.addListener(map, "click", function(marker,point) {
        var Punkte = point.toString().slice(1,(point.toString().length-1)).split(",");
        document.getElementById("coordinate_latitude").value = Punkte[0];
        document.getElementById("coordinate_longitude").value = Punkte[1].slice(1,(point.toString().length-1));
        placemark.setLatLng(point); 
        placemark.show();
        reversegeocoder.reverseGeocode(point);
     }
  );
    
    GEvent.addListener(reversegeocoder, "load",
      function(placemark) {
          document.getElementById("coordinate_street").value = reversegeocoder.getPlacemarkProperty(placemark,"ThoroughfareName");
          var zipCode = reversegeocoder.getPlacemarkProperty(placemark,"CountryNameCode");
          var code = reversegeocoder.getPlacemarkProperty(placemark,"PostalCodeNumber");
          if(code != null)
          {
              zipCode += " - " + code;
          }
          document.getElementById("coordinate_zip").value = zipCode;
          document.getElementById("coordinate_name").value = reversegeocoder.getPlacemarkProperty(placemark,"LocalityName");
          document.getElementById("coordinate_area").value = reversegeocoder.getPlacemarkProperty(placemark,"AdministrativeAreaName");
          document.getElementById("coordinate_country").value = reversegeocoder.getPlacemarkProperty(placemark,"CountryName");
      }
    );
    
    GEvent.addListener(reversegeocoder, "error",
      function() {
         googleMapCoordinates.resetFields();
      }
    );
    
};

GoogleMapCoordinates.prototype.showLocation = function (prefix, info)
{
   this.latitudeField.value=this.locationLatitudeArray[prefix];
   this.longitudeField.value=this.locationLongitudeArray[prefix];
   
   document.getElementById("coordinate_info").style.display = "block";
   document.getElementById("coordinate_info_text").innerHTML = info;
   document.getElementById("coordinate_confirm_button").style.display = "none";
   this.coordinate_display.style.display="block";
   this.coordinate_display.style.zIndex=100;
   this.logged = true;
   
   document.getElementById("coordinate_search_div").style.display = "none";
   this.latitudeField.setAttribute("disabled","disabled");
   this.latitudeField.setAttribute("readOnly","readonly");
   this.latitudeField.style.backgroundColor = "#EEEEEE";
   this.longitudeField.setAttribute("disabled","disabled");
   this.longitudeField.setAttribute("readOnly","readonly");
   this.longitudeField.style.backgroundColor = "#EEEEEE";
   
   this.createMap();
};

GoogleMapCoordinates.prototype.resetFields = function ()
{
    document.getElementById("coordinate_street").value = "";
    document.getElementById("coordinate_zip").value = "";
    document.getElementById("coordinate_country").value = "";
    document.getElementById("coordinate_name").value = "";
    document.getElementById("coordinate_area").value = "";
};

GoogleMapCoordinates.prototype.insertLocation = function (prefix, latitude, longitude)
{
   this.locationLatitudeArray[prefix] = latitude;
   this.locationLongitudeArray[prefix] = longitude;
};

GoogleMapCoordinates.prototype.searchLocation = function ()
{
    var address = this.searchField.value;
    var geocoder = new GClientGeocoder();

    geocoder.getLatLng(
        address,
        function(point) {
             if (point) {
                   var Punkte = point.toString().slice(1,(point.toString().length-1)).split(",");
                   document.getElementById("coordinate_latitude").value = Punkte[0];
                   document.getElementById("coordinate_longitude").value = Punkte[1].trim();
                   googleMapCoordinates.createMap();
             }
        }
    );

};
// --------------------------------------------------------------------------------------------------------------------------------
// ResultControl
// --------------------------------------------------------------------------------------------------------------------------------
function ResultControl ()
{
    this.id = "result";
    this.mouseover = false;
    this.resultCount = 0;
    this.energyUnit = "MegaJoule";
    this.jsonObject = null;
    this.infoMessage = null;
}

ResultControl.prototype.params = function()
{
    var result = "";
    
    result += "&lang=" + fixedEncodeURIComponent(pageProperties.getLanguage());
    result += "&json=" + this.jsonObject;
    
    return result;
};

ResultControl.prototype.setParams = function(paramList)
{
    this.paramList = paramList; 
};

ResultControl.prototype.getParams = function()
{
    return this.paramList; 
};

ResultControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(pageProperties.getPath() + "/result.jsp");
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Post);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback(new Callback(this, this.responseCallback));
    ajaxRequest.setReceivingCallback(new Callback(this, this.receivingCallback));
    return ajaxRequest.initXmlHttpRequest();
};

ResultControl.prototype.receivingCallback = function (responseText)
{

    for ( var resultCount = 1; resultCount < 6; resultCount++)
    {
        if(responseText.search("result_" + resultCount) != -1)
        {
            document.getElementById("loading_" + resultCount).style.display = "block";
        }
    }
};

ResultControl.prototype.responseCallback = function (response)
{
    document.getElementById(this.id).innerHTML = response;
    
    document.getElementById("calculationLoading").style.display="none";
    document.getElementById("inputFields").style.display="block";
    
    for ( var int = 1; int < 6; int++)
    {
        document.getElementById("loading_" + int).style.display="none";
    }
    
};

ResultControl.prototype.update = function ()
{
    this.infoMessage = null;
    locationList.updateLocationList();
    
    if(this.infoMessage == null)
    {
        var mainFieldsValidation = new MainFieldsValidation(new MainFields());
        var mainFieldsValid = mainFieldsValidation.validate();
        
        if(viewModeControl.getInputMode() == "standard")
        {
            this.jsonObject = standardTransportModeControl.prepareFormularFields();
        }
        else
        {
            var jsonFormatter = new JsonFormatter();
            
            this.jsonObject = "{\"ViewMode\":\"" + viewModeControl.getInputMode() + "\"";
            this.jsonObject += ",\"MainFields\":" + jsonFormatter.format(mainFieldsValidation.getMainFields());
            this.jsonObject += ",\"TransportChainList\":[";
            var tcSplit = "";
            for(var index = 0; index < transportChainsControl.getTransportChainList().length; index++)
            {
                var transportChain = transportChainsControl.getTransportChainList()[index];
                if(transportChain != null)
                {
                    this.jsonObject += tcSplit + "[";
                    tcSplit = ",";
                    var sectionSplit = "";
                    for(var sectionIndex = 0; sectionIndex < transportChain.getSectionList().length; sectionIndex++)
                    {
                        var section = transportChain.getSectionList()[sectionIndex];
                        if(section != null)
                        {
                            this.jsonObject += sectionSplit + jsonFormatter.format(section);
                            sectionSplit = ",";
                        }
                    }
                    this.jsonObject += "]";
                }
            }
            this.jsonObject += "]}";
        }
        
        if(this.jsonObject != null && mainFieldsValid)
        {
            this.setParams(this.params());
            document.getElementById("calculationLoading").style.display="block";
            document.getElementById("inputFields").style.display="none";
            this.postRequest();
        }
    }
    else
    {
        document.getElementById("result").style.display="block";
        document.getElementById("result").innerHTML = this.infoMessage;
        this.infoMessage = null;
    }
};

ResultControl.prototype.clearResultDisplay = function ()
{
    document.getElementById(this.id).innerHTML = "";
};

ResultControl.prototype.clearAndUpdate = function ()
{
    if(this.mouseover)
    {
        this.clearResultDisplay();
        this.update();
    }
};

ResultControl.prototype.updateResult = function (energyUnit)
{
    var resultDifferentiation = new ResultDifferentiationControl(pageProperties.getPath() + "/result_differentiation.jsp", this.id, energyUnit);
    resultDifferentiation.update();
};

ResultControl.prototype.newCalculation = function ()
{
    if(this.mouseover)
    {
        window.location.reload();
    }
};

ResultControl.prototype.resetFields = function ()
{
    this.numOfTransportChains = 0;
};

ResultControl.prototype.setNumOfTransportChains = function (numOfTransportChains)
{
    this.numOfTransportChains = numOfTransportChains;
};

ResultControl.prototype.setMouseover = function ()
{
    this.mouseover = true;
};

ResultControl.prototype.setMouseout = function ()
{
    this.mouseover = false;
};

ResultControl.prototype.setEnergyUnit = function (energyUnit)
{
    this.energyUnit = energyUnit;
};

ResultControl.prototype.getJsonObject = function ()
{
    return this.jsonObject;
};

ResultControl.prototype.setInfoMessage = function (infoMessage)
{
    this.infoMessage = infoMessage;
};
function LayerControl()
{
    this.currentPopupID = null;
    this.currentMainDivID = null;
    this.currentPopupType = null;
    this.currentPrefix = null;
}

LayerControl.prototype.toolTipMouseover = function(mainDivID,toolTipDivId, comboBoxID)
{
    if(this.getCurrentPopupID() === null)
    {
       document.getElementById(mainDivID).style.zIndex = 51;
       
       if(document.getElementById(toolTipDivId) != null)
       {
          document.getElementById(toolTipDivId).style.display='block';
       }
    }
    else if(this.getCurrentMainDivID() == mainDivID && this.getCurrentPopupID() != comboBoxID)
    {
       document.getElementById(mainDivID).style.zIndex = 51;
       if(document.getElementById(toolTipDivId) != null)
       {
          document.getElementById(toolTipDivId).style.display='block';
          document.getElementById(toolTipDivId).style.zIndex = 70;
       }
    }
};

LayerControl.prototype.toolTipMouseout = function(mainDivID,toolTipDivId)
{
    if(this.getCurrentPopupID() === null)
    {
       document.getElementById(mainDivID).style.zIndex = 1;
       
       if(document.getElementById(toolTipDivId) != null) {
          document.getElementById(toolTipDivId).style.display='none';
       }
    }
    else 
    {
       if(document.getElementById(toolTipDivId) != null) {
          document.getElementById(toolTipDivId).style.display='none';
       }
    }
};

LayerControl.prototype.tooglePopupOnClick = function(prefix, mainDivID, comboBoxID, popupType)
{
    if(comboBoxID == this.getCurrentPopupID())
   {
         this.setCurrentMainDivID(null);
         this.setCurrentPopupID(null);
         this.setCurrentPopupType(null);
         this.setCurrentPrefix(null);
         document.getElementById(mainDivID).style.zIndex = 1;
         layerControlSwitch.toogleLayer(popupType, prefix);
   } 
   else
   {  
         if(comboBoxID != this.getCurrentPopupID() && this.getCurrentMainDivID() != null)
         {
             layerControlSwitch.toogleLayer(this.getCurrentPopupType(), this.getCurrentPrefix());
             document.getElementById(this.getCurrentMainDivID()).style.zIndex = 1;
         }
         this.setCurrentMainDivID(mainDivID);
         this.setCurrentPopupID(comboBoxID);
         this.setCurrentPrefix(prefix);
         this.setCurrentPopupType(popupType);
         layerControlSwitch.toogleLayer(popupType, prefix);
         document.getElementById(mainDivID).style.zIndex = 50;
   }
};

LayerControl.prototype.tooglePopupOnKeyup = function(prefix, mainDivID, comboBoxID, popupType)
{
     if(comboBoxID != this.getCurrentPopupID())
     {
         if(this.getCurrentPopupType() != null)
         { 
             layerControlSwitch.toogleLayer(this.getCurrentPopupType(), this.getCurrentPrefix());
             document.getElementById(this.getCurrentMainDivID()).style.zIndex = 1;
         }

         this.setCurrentMainDivID(mainDivID);
         this.setCurrentPopupID(comboBoxID);
         this.setCurrentPrefix(prefix);
         this.setCurrentPopupType(popupType);
         document.getElementById(mainDivID).style.zIndex = 50;
         }
};

LayerControl.prototype.reset = function()
{
    if(document.getElementById(this.getCurrentMainDivID()) != null)
    {
        document.getElementById(this.getCurrentMainDivID()).style.zIndex = 1;
    }
    this.currentPopupID = null;
    this.currentMainDivID = null;
    this.currentPopupType = null;
    this.currentPrefix = null;
};

LayerControl.prototype.resetAndClose = function()
{
    if(this.getCurrentPopupID() != null && this.getCurrentMainDivID() != null)
    {
        layerControlSwitch.toogleLayer(this.getCurrentPopupType(), this.getCurrentPrefix());
        document.getElementById(this.getCurrentMainDivID()).style.zIndex = 1;
    }
    this.currentPopupID = null;
    this.currentMainDivID = null;
    this.currentPopupType = null;
    this.currentPrefix = null;
};

LayerControl.prototype.setCurrentPopupID = function (div)
{
    this.currentPopupID = div;
};

LayerControl.prototype.getCurrentPopupID = function ()
{
    return this.currentPopupID;
};

LayerControl.prototype.setCurrentMainDivID = function (div)
{
    this.currentMainDivID = div;
};

LayerControl.prototype.getCurrentMainDivID = function ()
{
    return this.currentMainDivID;
};

LayerControl.prototype.setCurrentPrefix = function (prefix)
{
    this.currentPrefix = prefix;
};

LayerControl.prototype.getCurrentPrefix = function ()
{
    return this.currentPrefix;
};

LayerControl.prototype.setCurrentPopupType = function (type)
{
    this.currentPopupType = type;
};

LayerControl.prototype.getCurrentPopupType = function ()
{
    return this.currentPopupType;
};

LayerControl.prototype.setBlocked = function (blocked)
{
    this.blocked = blocked;
};

LayerControl.prototype.getCurrentPopupType = function ()
{
    return this.currentPopupType;
};
//
//GoogleMap
//
function GoogleMap(requestPage)
{
    this.requestPage = requestPage;
    this.calcIndex = null;
}

GoogleMap.prototype.init = function(calcIndex)
{
    this.calcIndex = calcIndex;

};

GoogleMap.prototype.setParams = function(paramList)
{
    this.paramList = paramList; 
};

GoogleMap.prototype.getParams = function()
{
    return this.paramList; 
};

GoogleMap.prototype.params = function()
{
    var result = "";
    result += "&calcIndex=" + fixedEncodeURIComponent(this.calcIndex);
    
    return result;
};


GoogleMap.prototype.postRequest = function () 	
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(this.requestPage);
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Xml);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

GoogleMap.prototype.responseCallback = function (response)
{
    if (GBrowserIsCompatible())
    {
        var mapParameters = response.getElementsByTagName("mapParameters")[0];
        
        this.coordinate_display = document.getElementById("coordinate_background");
        this.coordinate_map = document.getElementById("coordinate_map");
        this.latitudeField = document.getElementById("coordinate_latitude");
        this.longitudeField = document.getElementById("coordinate_longitude");
        this.searchField = document.getElementById("coordinate_search");
        this.infoDiv = document.getElementById("coordinate_info");

        document.getElementById("coordinate_info_text").innerHTML = mapParameters.getAttribute("info");
        document.getElementById("coordinate_confirm_button").style.display = "none";
        document.getElementById("coordinate_search_div").style.display = "none";
        
        this.coordinate_display.style.display="block";
        this.coordinate_display.style.zIndex=100;
        
        this.infoDiv.style.display="none";

        
        window.scrollTo(0,0);
        
        var map = new GMap2(document.getElementById("coordinate_map"));
    
        map.setUIToDefault();
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        
        var coordinateArrayJS = mapParameters.getAttribute("coordinates");
        var coordinates = coordinateArrayJS.split(" / ");
        var colorArrayJS = mapParameters.getAttribute("colors");
        var colors = colorArrayJS.split(" / ");
        var boundPoints = [];
        var pointCount = 0;

        for(var j = 0; j < coordinates.length; j++)
        {
            if (GBrowserIsCompatible())
            {
                var color = '#' + colors[j].charAt(6) + colors[j].charAt(7) + colors[j].charAt(4) + colors[j].charAt(5) + colors[j].charAt(2) + colors[j].charAt(3);
                var width = 5;
                var pts = [];
                var string = coordinates[j];
                var coordinate = string.split(" ");

                for(var i = 0; i < coordinate.length; i++)
                {
                    var coordinateSet = coordinate[i].split(",");
                    pts[i] = new GLatLng(Number(coordinateSet[1]),Number(coordinateSet[0]));
                    boundPoints[i+pointCount] = new GPoint(Number(coordinateSet[1]),Number(coordinateSet[0]));
                }

                pointCount = i + pointCount;
                map.addOverlay(new GPolyline(pts,color,width));
            }
      }
      var bounds = new GBounds(boundPoints);
      var centerPoint = bounds.mid();
      var zoomBound = new GLatLngBounds(new GLatLng(bounds.minX, bounds.minY), new GLatLng(bounds.maxX, bounds.maxY));

      map.setCenter(new GLatLng(centerPoint.x,centerPoint.y), map.getBoundsZoomLevel(zoomBound));
      map.addOverlay(new GPolyline(pts,color,width));
      
    }

    else
    {
        alert("Sorry, the Google Maps API is not compatible with this browser");
    }

};

GoogleMap.prototype.showMap = function ()
{
   this.setParams(this.params());
   this.postRequest();
};
// --------------------------------------------------------------------------------------------------------------------------------
// TransportChainSimpleControl
// --------------------------------------------------------------------------------------------------------------------------------
function TransportChainSimpleControl (language)
{
    this.prefix = null;
    this.language = language;
    
    this.selectedModes = new Array();
}

TransportChainSimpleControl.prototype.init = function(prefix)
{
    this.prefix = prefix;
};

TransportChainSimpleControl.prototype.updateSelection = function (value)
{
    var partialImageName = value.toLowerCase();
    var imgPath = document.getElementById(this.prefix + "_" + partialImageName + '_img').src;
    var index = imgPath.lastIndexOf('/');
    
    if(imgPath.indexOf("-hover") != -1)
    {
        document.getElementById(this.prefix + "_" + partialImageName + '_img').src = imgPath.substring(0, index) + "/" + partialImageName + ".gif";
        document.getElementById(value).value = "";
    }
    else
    {
        document.getElementById(this.prefix + "_" + partialImageName + '_img').src = imgPath.substring(0, index) + "/" + partialImageName + "-hover" + ".gif";
        document.getElementById(value).value = value;
    }
};

TransportChainSimpleControl.prototype.createExtendedSelectedChains = function ()
{
    for(var key in listTransportModes)
    {
        
        if(document.getElementById(key) != null 
                && document.getElementById(key).value != null
                && document.getElementById(key).value != "")
        {
            this.selectedModes.push(key);
        }
    }
    transportChainsControl.setSelectedModes(this.selectedModes);
    this.selectedModes = new Array();
};
// --------------------------------------------------------------------------------------------------------------------------------
// ResultDifferentiationControl
// --------------------------------------------------------------------------------------------------------------------------------
function ResultDifferentiationControl (requestPage,
                                       id, 
                                       energyUnit)
{
    this.id = id;
    this.requestPage = requestPage;
    this.energyUnit = energyUnit;
}

ResultDifferentiationControl.prototype.params = function()
{
    var result = "";
    
    if(document.getElementById("showDifferentiation") != null)
    {
        result = result += "&showDifferentiation=" + fixedEncodeURIComponent(document.getElementById("showDifferentiation").checked);
    }
    
    if(this.energyUnit != null)
    {
        result = result += "&energyUnit=" + fixedEncodeURIComponent(this.energyUnit);
    }
    
    return result;
};

ResultDifferentiationControl.prototype.setParams = function(paramList)
{
    this.paramList = paramList; 
};

ResultDifferentiationControl.prototype.getParams = function()
{
    return this.paramList; 
};

ResultDifferentiationControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(this.requestPage);
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

ResultDifferentiationControl.prototype.responseCallback = function (response)
{
    if(document.getElementById("result_error") != null)
    {
        document.getElementById(this.id).innerHTML = "<div id='result_error'>" + document.getElementById("result_error").innerHTML + "</div>" + response;
    }
    else
    {
        document.getElementById(this.id).innerHTML = response;
    }
    document.getElementById("calculationLoading").style.display="none";
    document.getElementById("inputFields").style.display="block";
    document.getElementById("energyUnit_" + this.energyUnit).checked = true;
};

ResultDifferentiationControl.prototype.update = function ()
{
    this.setParams(this.params());
    this.postRequest();
};
// --------------------------------------------------------------------------------------------------------------------------------
// TransportChainControl
// --------------------------------------------------------------------------------------------------------------------------------
function TransportChainControl (prefix,
                                requestPage,
                                language,
                                divId)
{
    this.elements = new Array();
    this.prefix = prefix;
    this.language = language;
    
    this.divId = divId;
    
    this.requestPage = requestPage;

    this.paramList = "";
    
    this.mouseover = false;
}

TransportChainControl.prototype.init = function(id, transportMode)
{
    this.numElement = id;
    this.transportMode = transportMode;
};

TransportChainControl.prototype.params = function()
{    
    var result = "";
    result += "&parentDivId=" + fixedEncodeURIComponent(this.prefix);
    result += "&lang=" + fixedEncodeURIComponent(this.language);
    result += "&tcid=" + fixedEncodeURIComponent(transportChainsControl.getInsertedChains()+1);
    result += "&chainNumber=" + fixedEncodeURIComponent(transportChainsControl.getChainNumber());
    
    return result;

};

TransportChainControl.prototype.setParams = function(paramList)
{
    this.paramList = paramList;
};

TransportChainControl.prototype.getParams = function()
{
    return this.paramList; 
};

TransportChainControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(this.requestPage);
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

TransportChainControl.prototype.responseCallback = function (response)
{   
    var childNumber = transportChainsControl.getInsertedChains() + 1;
    var childId = this.prefix + "_" + childNumber;
    child = document.createElement("div");
    child.id = childId;
    child.style.cssFloat = "left";
    child.style.styleFloat = "left";
    child.style.lineHeight = "20px";
    child.style.width = "754px";
    child.innerHTML = response;
    document.getElementById(this.divId).appendChild(child);
    
    var separator = document.createElement("div");
    separator.id = this.prefix + "_" + childNumber + "_separator";
    separator.style.cssFloat = "left";
    separator.style.styleFloat = "left";
    separator.style.borderTop = "1px solid #777777";
    separator.style.marginTop = "0px";
    separator.style.marginBottom = "0px";
    separator.style.lineHeight = "0px";
    separator.style.width = "754px";
   
    document.getElementById(this.divId).appendChild(separator);
    transportChainsControl.renumberChains();
    
    transportChainsControl.setInsertedChains(childNumber);
};

TransportChainControl.prototype.updateVolumeWeightValues = function ()
{
    if(viewModeControl.getInputMode() != 'standard')
    {
        var transportChainsMainDiv = document.getElementById(this.divId);
        var chains = transportChainsMainDiv.childNodes.length;
        for(var index = 0; index < chains; index++)
        {
            var prefixLength = this.prefix.length + 1;
            var element = transportChainsMainDiv.childNodes[index];
            if(element.id != null 
                    && element.id.indexOf("seperator") == -1
                    && element.id.substring(0, prefixLength) == this.prefix + "_")
            {
                this.setVolumeWeights(element.id);
                
                var vias = formularValidationControl.getViaPrefixList().split(",");
                if(formularValidationControl.getViaPrefixList().indexOf(element.id) != -1)
                {
                    for(var key in vias)
                    {
                        if(vias[key].indexOf(element.id) > -1)
                        {
                            this.setVolumeWeights(vias[key]);
                        }
                    }
                }
            }
        }
    }
};

TransportChainControl.prototype.setVolumeWeights = function (prefix)
{
    var cargoVolumeWeightInputValue = document.getElementById('cargoVolumeWeight').name;
    var loadFactorInput = document.getElementById(prefix + '_loadFactor');
    var emptyRunFactorInput = document.getElementById(prefix + '_emptyRunFactor');
    
    var transportModeInput = document.getElementById(prefix + '_transportMode');
    
    if(transportModeInput != null)
    {
        var enumTransportMode = transportModeInput.name;
        if("Heavy" == cargoVolumeWeightInputValue)
        {
            if("Road" == enumTransportMode)
            {
                loadFactorInput.value = "100";
                emptyRunFactorInput.value = "60";
            }
            if("Rail" == enumTransportMode)
            {
                loadFactorInput.value = "100";
                emptyRunFactorInput.value = "80";
            }
        }
        else if("Average" == cargoVolumeWeightInputValue)
        {
            if("Road" == enumTransportMode)
            {
                loadFactorInput.value = "60";
                emptyRunFactorInput.value = "20";
            }
            if("Rail" == enumTransportMode)
            {
                loadFactorInput.value = "60";
                emptyRunFactorInput.value = "50";
            }
        }
        else if("Light" == cargoVolumeWeightInputValue)
        {
            if("Road" ==  enumTransportMode)
            {
                loadFactorInput.value = "30";
                emptyRunFactorInput.value = "10";
            }
            if("Rail" == enumTransportMode)
            {
                loadFactorInput.value = "30";
                emptyRunFactorInput.value = "20";
            }
        }
    }
};

TransportChainControl.prototype.updateCargoUnits = function ()
{
    formularValidationControl.validate();
    
    var prefixList = formularValidationControl.getPrefixList().split(",");
    var viaPrefixList = formularValidationControl.getViaPrefixList().split(",");
    
    if(prefixList != null)
    {
        for(var index in prefixList)
        {
            var prefix = prefixList[index];
            this.updateCargoUnitsData(prefix);
        }
    }
    
    if(viaPrefixList != null)
    {
        for(var index in viaPrefixList)
        {
            var prefix = viaPrefixList[index];
            this.updateCargoUnitsData(prefix);
        }
    }
};

TransportChainControl.prototype.updateCargoUnitsData = function (prefix)
{
    if(formularValidationControl.getFormularFields()['MainFormular'].getCargoUnit() == "teu")
    {
        // Anzeige des Feldes fuer release rausgenommen
        //document.getElementById("weight_tpTeu").style.display = "block";
    }
    else
    {
        document.getElementById("weight_tpTeu").style.display = "none";
    }
    
    if(formularValidationControl.getFormularFields()[prefix + "_transportMode"] == "Sea")
    {
        var id = prefix.substring((prefix.length -1), prefix.length);
        var innerTransportModeControl = new TransportModeControl(this.requestPage.replace("transportchain.jsp", "transportmode.jsp", "i"), this.language);
        innerTransportModeControl.init(id, "Sea", prefix, prefix + "_selected_form");
        innerTransportModeControl.update();
    }
    if(formularValidationControl.getFormularFields()[prefix + "_transportMode"] == "InlandWaterways"
        && formularValidationControl.getFormularFields()['MainFormular'].getCargoUnit() == "teu"
        && document.getElementById(prefix + "_loadFactorContainer_field") != null)
    {
        document.getElementById(prefix + "_loadFactorContainer_field").style.display = "block";
        document.getElementById("weight_tpTeu").style.display = "block";
    }
    else if(document.getElementById(prefix + "_loadFactorContainer_field") != null)
    {
        document.getElementById(prefix + "_loadFactorContainer_field").style.display = "none";
        document.getElementById("weight_tpTeu").style.display = "none";
    }
};

TransportChainControl.prototype.updateTransportChains = function ()
{
    if(document.getElementById(this.divId) != null)
    {
        if(document.getElementById(this.divId).hasChildNodes())
        {
            for(var index = 0; index < document.getElementById(this.divId).childNodes.length; index++)
            {
                element = document.getElementById(this.divId).childNodes[index];
                if(document.getElementById(element.id + "_transportMode") != null)
                {
                    var enumKey = document.getElementById(element.id + "_transportMode").name;
                    var enumValue = document.getElementById(element.id + "_transportMode").value;
                    
                    if(enumKey == "Sea")
                    {
                        splittedElementId = element.id.split("_");
                        elementPrefix = splittedElementId[0] + "_" + splittedElementId[1];
                        formularValidationControl.validate();
                        transportModeControl.updateSelection(elementPrefix + '_transporttype_img', enumKey.toLowerCase() + '-small'); 
                        transportModeControl.init('0', enumKey, elementPrefix, elementPrefix + '_selected_form');
                        transportModeControl.update();
                    }
                }
            }
        }
    }
};

TransportChainControl.prototype.createChain = function ()
{
    if(this.mouseover)
    {
        if(transportChainsControl.getChainNumber() < 6)
        {  
            this.setParams(this.params());
            this.postRequest();
        }
    }
};

TransportChainControl.prototype.setMouseover = function ()
{
    this.mouseover = true;
};

TransportChainControl.prototype.setMouseout = function ()
{
    this.mouseover = false;
};

TransportChainControl.prototype.updateRoadClass = function (prefix, lorryClass)
{
    var listRoadEmission;
    if(lorryClass.indexOf("lbs") == -1)
    {
        listRoadEmission = listRoadEmissionsEU;
        document.getElementById(prefix + "_emissionClass").value = listRoadEmission["EuEuro3"];
    }
    else
    {
        listRoadEmission = listRoadEmissionsEPA;
        document.getElementById(prefix + "_emissionClass").value = listRoadEmission["UsEpa2004"];
    }
    
    setInputName(prefix + "_emissionClass", keyOfValue(listRoadEmissions, document.getElementById(prefix + "_emissionClass").value));
    
    var roadClassTable = "<table style=\"padding: 0px 4px; border-collapse:collapse; width: 100%;\">";
    
    for(var item in listRoadEmission) 
    {
        roadClassTable += "<tr onclick=\"layerControl.reset();popupControl.setPrefix('" + prefix + "_emissionClass'); popupControl.clickedItem('" + listRoadEmissions[item] + "');setInputName('" + prefix + "_emissionClass', keyOfValue(listRoadEmissions, document.getElementById('" + prefix + "_emissionClass').value));\"onmouseover=\"this.style.backgroundColor='#0095d5';this.style.color='#fff';\"onmouseout=\"this.style.backgroundColor='#fff'; this.style.color='#000';\"style=\"cursor: pointer;\">";
        roadClassTable += "<td style=\"font-size: 8pt; vertical-align:middle; padding-left:5px;\">";
    
        roadClassTable += listRoadEmission[item];
        roadClassTable += "</td></tr>";
    }
    roadClassTable += "</table>";
    document.getElementById(prefix + "_emissionClass_popupdiv").innerHTML = roadClassTable;
};// --------------------------------------------------------------------------------------------------------------------------------
// TransportModeControl
// --------------------------------------------------------------------------------------------------------------------------------
function TransportModeControl (requestPage,
                                language)
{
    this.transportModeType = null;
    this.transportModeId = null;
    this.prefix = null;
    this.requestPage = requestPage;
    this.language = language;
    this.replaceContentPrefix = null;
}

TransportModeControl.prototype.init = function(transportModeId,
                                                transportModeType,
                                                prefix,
                                                replaceContentPrefix)
{
    this.transportModeId = transportModeId;
    this.transportModeType = transportModeType;
    this.prefix = prefix;
    this.replaceContentPrefix = replaceContentPrefix;
};

TransportModeControl.prototype.params = function()
{
    var result = "";
    result += "&id=" + fixedEncodeURIComponent(this.transportModeId);
    result += "&transportMode=" + fixedEncodeURIComponent(this.transportModeType);
    result += "&lang=" + fixedEncodeURIComponent(this.language);
    result += "&prefix=" + fixedEncodeURIComponent(this.prefix);
    result += "&cargoUnit=" + fixedEncodeURIComponent(formularValidationControl.getFormularFields()['MainFormular'].getCargoUnit());
    
    return result;
};

TransportModeControl.prototype.setParams = function(paramList)
{
    this.paramList = paramList; 
};

TransportModeControl.prototype.getParams = function()
{
    return this.paramList; 
};

TransportModeControl.prototype.postRequest = function ()
{
    var ajaxRequest = new AjaxRequest();
    ajaxRequest.setSource(this.requestPage);
    ajaxRequest.setData(this.getParams());
    ajaxRequest.setRequestType(EnumRequestType.Get);
    ajaxRequest.setResponseType(EnumResponseType.Text);
    ajaxRequest.setFinishedCallback( new Callback(this, this.responseCallback));
    return ajaxRequest.initXmlHttpRequest();
};

TransportModeControl.prototype.responseCallback = function (response)
{
    document.getElementById(this.replaceContentPrefix).innerHTML = response;
    
    childNodesControl.setParentDivId(this.replaceContentPrefix);
    
    transferpointControl.removeTransferpoints(this.replaceContentPrefix.replace("_selected_form", ""));
    transferpointControl.calculateTransferpoints();
};

TransportModeControl.prototype.update = function ()
{
    this.setParams(this.params());
    this.postRequest();
};

TransportModeControl.prototype.updateSelection = function (id, value)
{
    if(document.getElementById(id) != null)
    {
        var imgPath = document.getElementById(id).src;
        var index = imgPath.lastIndexOf('/');
        document.getElementById(id).src = imgPath.substring(0, index) + "/" + value + ".gif";
    }
};

TransportModeControl.prototype.hoverSelection = function (id, value, color, fontWeight)
{
    var imgPath = document.getElementById(id + '_img').src;
    var index = imgPath.lastIndexOf('/');
    document.getElementById(id + '_img').src = imgPath.substring(0, index) + "/" + value + ".gif";
    document.getElementById(id + '_txt').style.color = color;
    document.getElementById(id + '_txt').style.fontWeight = fontWeight;
};

TransportModeControl.prototype.setTransportModeType = function (transportModeType)
{
    this.transportModeType = transportModeType;
};

TransportModeControl.prototype.setTransportModeId = function (transportModeId)
{
    this.transportModeId = transportModeId;
};
