#include "CMainWindow.h"

struct SMouseState MouseState;

CMainWindow::CMainWindow(bool f, bool m, bool s, bool a, bool v, bool fsaa, video::E_DRIVER_TYPE d,core::stringw strRes)
: fullscreen(f), music(m), shadows(s), additive(a), vsync(v), aa(fsaa),
 driverType(d), device(0),resolutionStr(strRes)
{
    contexte=new CGameContext();
    SelectedNode=0;
}

void CMainWindow::setCurrentMap(core::stringc m) {
    currentmap=m;
    contexte->SetSelectedMap(currentmap);
}

CMainWindow::~CMainWindow()
{
    if(device!=0) {
        delete device;
        device=0;
    }

    if(contexte!=0) {
        delete contexte;
        contexte=0;
    }

    if(mountain!=0) {
        delete mountain;
        mountain=0;
    }

}

void CMainWindow::run()
{
    //printf("---Windows RUN \n");
    //printf("resolutionStr = %s \n",resolutionStr);
    //printf("fullscreen = %i \n",fullscreen);
    if(resolutionStr=="640x480") {
        resolution.Width=640;
        resolution.Height=480;
        printf("found 640x480 \n");
    }
    if(resolutionStr=="800x600") {
        resolution.Width=800;
        resolution.Height=600;
        printf("found 800x600 \n");
    }
    if(resolutionStr=="1024x768") {
        resolution.Width=1024;
        resolution.Height=768;
        printf("found 1024x768 \n");
    }
    if(resolutionStr=="1280x960") {
        resolution.Width=1280;
        resolution.Height=960;
        printf("found 1280x960 \n");
    }


    SIrrlichtCreationParameters params;
	params.DriverType=driverType;
	params.WindowSize=resolution;
	params.Bits=32;
	params.Fullscreen=fullscreen;
	//params.Fullscreen=false;
	params.Stencilbuffer=shadows;
	params.Vsync=vsync;
	params.AntiAlias=aa;
	params.EventReceiver=this;



	device = createDeviceEx(params);
	if (!device)
		return;

    app.Device=device;

    video::IVideoDriver* driver = device->getVideoDriver();
	scene::ISceneManager* smgr = device->getSceneManager();
	gui::IGUIEnvironment* guienv = device->getGUIEnvironment();

	device->setWindowCaption(L"My 3D Ski Resort");

    app.Driver=driver;
    app.Gui=guienv;
    app.ShouldQuit=false;
    app.gameAction=SAppContext::ACTION_NONE;
    app.textExplic="";

    //receiver=new CMyEventReceiver(app);
    //app.Device->setEventReceiver(receiver);
	/*
	Now we'll create a camera, and give it a collision response animator
	that's built from the mesh nodes in the scene we just loaded.
	*/
	//scene::ICameraSceneNode * camera = smgr->addCameraSceneNodeFPS(0, 50.f, 0.1f);
	/*scene::ICameraSceneNode * camera = smgr->addCameraSceneNodeMaya(0, 50.f, 0.1f);
    camera->setPosition(vector3df(6000,500,5000));
    camera->setTarget(vector3df(6000,500,5000));
    camera->setFarValue(15000);*/

	CDynamicCamera* camera = new CDynamicCamera(device,smgr->getRootSceneNode(),smgr,-1,100.0f,3.0f,1.0f);
	camera->setTranslateSpeed(2);//speed of cam movement
    camera->setRotationSpeed(20);//speed of cam rotation
    camera->setPosition(vector3df(6000,500,5000));
    camera->setFarValue(8000);


    mountain = new CMountain(contexte->GetSelectedMap());
    mountain->driver=driver;
    mountain->smgr=smgr;
    mountain->device=device;
    mountain->LoadMountain();
    camera->setTarget(mountain->arrStations[0]->GetPosition());

    scene::ISceneNodeAnimator * anim;
    anim = smgr -> createCollisionResponseAnimator (mountain->selector,camera,core::vector3df (30 , 50 , 30),core::vector3df(0,-10,0),core::vector3df(0,30 ,0));
    camera -> addAnimator(anim);

    printf("Camera %f",camera->getFarValue());
	/*
	That's it. Draw everything and finish as usual.
	*/

	arrow = smgr->addAnimatedMeshSceneNode(smgr->addArrowMesh("arrow", video::SColor(255, 255, 0, 0), video::SColor(255, 0, 255, 0)), NULL);
    arrow->setMaterialFlag(video::EMF_LIGHTING, false);
    arrow->setScale(core::vector3df(20,20,20));
    arrow->setRotation(core::vector3df(0,0,180));

	int lastFPS = -1;


    /*char c[24];
    char c2[24];*/

     // set new Skin
	gui::IGUISkin* newskin = guienv->createSkin(gui::EGST_BURNING_SKIN);
	guienv->setSkin(newskin);
	newskin->drop();

	// load font
	gui::IGUIFont* font = guienv->getFont("media/fonthaettenschweiler.bmp");
	if (font)
		guienv->getSkin()->setFont(font);

    gui::IGUIStaticText* txt;
    txt = guienv->addStaticText(L"",core::rect<s32>(190,10,600,40), false, true, 0, -1, false);
    txt->setOverrideColor(video::SColor(255,150,100,60));

    /*gui::IGUIStaticText* txt2;
    txt2 = guienv->addStaticText(L"Coordonnees camera",core::rect<s32>(10,90,600,120), false, true, 0, -1, false);
    txt2->setOverrideColor(video::SColor(255,150,100,60));*/


	// add button

	app.construtionButton = guienv->addButton(core::rect<int>(5,5,80,40), 0, SAppContext::GUI_ID_CONSTRUCTION_BUTTON, L"Construire");
	app.rechercheButton = guienv->addButton(core::rect<int>(90,5,180,40), 0, SAppContext::GUI_ID_BUTTON_RECHERCHE, L"Rechercher");
    //app.menuButton = guienv->addButton(core::rect<int>(960,5,1019,40), 0, SAppContext::GUI_ID_BUTTON_MENU, L"Menu");
    app.menuButton = guienv->addButton(core::rect<int>(resolution.Width-64,5,resolution.Width-5,40), 0, SAppContext::GUI_ID_BUTTON_MENU, L"Menu");

    u32 then = device->getTimer()->getTime();

	while(device->run() && !app.ShouldQuit) {

            // Work out a frame delta time.
            const u32 now = device->getTimer()->getTime();
            const f32 frameDeltaTime = (f32)(now - then) * 0.001f; // convert time in seconds
            then = now;

            driver->beginScene(true, true, video::SColor(0,200,200,200));
            //driver->draw3DLine(core::vector3df(6231.712891,390.519562,5039.063477),core::vector3df(5501.529785,623.897705,4901.688965), video::SColor(255, 0, 0, 0));

            for(int i=0;i<mountain->arrRemontees.size();i++) {
                if(mountain->arrRemontees[i]) {
                     mountain->arrRemontees[i]->RedrawCable();
                     //mountain->arrRemontees[i]->UpdateTroncons();
                     mountain->arrRemontees[i]->AnimateRm(camera->getAbsolutePosition(),frameDeltaTime);
                }
            }

            smgr->drawAll();
            guienv->drawAll();
            driver->endScene();

            int fps = driver->getFPS();

            if (lastFPS != fps)
            {
                core::stringw str = L"My 3D Ski Resort - v0.0.1 [";
                str += driver->getName();
                str += "] FPS:";
                str += fps;

                device->setWindowCaption(str.c_str());
                lastFPS = fps;
            }

            /*core::vector3df cameraPosition=camera->getAbsolutePosition ();
            sprintf(c2,"coordonnees camera : %f - %f - %f", cameraPosition.X, cameraPosition.Y, cameraPosition.Z);
            txt2->setText(core::stringw(c2).c_str());*/

            txt->setText(core::stringw(app.textExplic).c_str());

	}

	device->drop();
}

SMouseState & CMainWindow::GetMouseState()
{
    //printf("getMouseState\n");
    return MouseState;
}

bool CMainWindow::OnEvent(const SEvent& event)
{
    // Remember the mouse state
    if (event.EventType == irr::EET_MOUSE_INPUT_EVENT)
    {
        //printf("event.EventType ==EET_MOUSE_INPUT_EVENT\n");
        switch(event.MouseInput.Event)
        {
        case EMIE_LMOUSE_PRESSED_DOWN:
            MouseState.LeftButtonDown = true;

            //Si pas d'opération concrète en cours, le clic gauche sert à sélectionner des éléments sur la carte
            if(app.gameAction==SAppContext::ACTION_NONE) {
                // what a freakin hack
                //bool LMouseButtonDown   = 0;   // is the left mouse button down?
                //LMouseButtonDown = true;

                // check for a node being selected
                SelectedNode=mountain->getNodeByClick();


                // If we selected a node
                if(SelectedNode) {
                    // printf("node selected %s\n",SelectedNode->getName());
                     std::string typeNode=SelectedNode->getName();
                     printf("Type node %s\n",typeNode.c_str());

                     //typeNode=typeNode.c_str()->subString(0,5);
                     //if(strcmp(SelectedNode->getID().subString(0,5),"arbre")==0) {
                     typeNode=typeNode.substr(0,5);
                     char cstr[typeNode.size()+1];
                     strcpy(cstr,typeNode.c_str());

                     if(strcmp(cstr,"arbre")==0) {
                        printf("arbre clicked %s\n",SelectedNode->getName());
                        SelectedArbre=mountain->getArbreByID(SelectedNode->getName());
                        if(SelectedArbre) {
                            app.windowCutTree = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(100,170,250,238),true,L"Arbre",0,SAppContext::GUI_ID_WINDOW_TREE_CUT);
                            app.cutTreeButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,22,145,62), app.windowCutTree, SAppContext::GUI_ID_BOUTON_TREE_CUT, L"Couper l'arbre");
                        }

                     }

                     if(strcmp(cstr,"rmtkf")==0) {
                        printf("tkf clicked %s\n",SelectedNode->getName());
                        SelectedRM=mountain->getRemonteeByID(SelectedNode->getName());
                        if(SelectedRM && SelectedRM->proprietesOuvert==false) {
                            app.windowRMControl = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(100,170,400,410),true,L"Teleski fixe",0,SAppContext::GUI_ID_WINDOW_ETAT_RM);
                            app.windowRMControl->getCloseButton()->setVisible(false);
                            app.Device->getGUIEnvironment()->addStaticText(L"Nom du teleski:", rect<s32>(5,40,395,60), false,true,app.windowRMControl);
                            app.editBoxNameRM=app.Device->getGUIEnvironment()->addEditBox(core::stringw(SelectedRM->GetName().c_str()).c_str(),core::rect<int>(5,60,275,90), false,app.windowRMControl, SAppContext::GUI_ID_TEXT_NOM_RM);
                            app.marcheArretRMButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,100,145,120), app.windowRMControl, SAppContext::GUI_ID_BUTTON_MARCHE_RM, L"Marche / Arret");
                            app.Device->getGUIEnvironment()->addStaticText(L"Vitesse du teleski:", rect<s32>(5,140,155,160), false,true,app.windowRMControl);
                            app.labelVitesseRM=app.Device->getGUIEnvironment()->addStaticText(L"",rect<s32>(160, 140, 295, 160), false,true,app.windowRMControl);
                            app.scrollbarVitesseRM=app.Device->getGUIEnvironment()->addScrollBar(true,rect<s32>(5, 180, 295, 200), app.windowRMControl, SAppContext::GUI_ID_SCROLL_BAR_VITESSE_RM);
                            app.scrollbarVitesseRM->setMin(10);
                            app.scrollbarVitesseRM->setMax(100);
                            s32 scrollPosition=(s32)(SelectedRM->vitesse*100.0f/SelectedRM->vitesseMax);
                            printf("vitesse max %f\n",SelectedRM->vitesseMax);
                            //s32 scrollPosition=(s32)(SelectedRM->vitesse*100.0f/0.3f);
                            printf("scrollPosition %i\n",scrollPosition);
                            app.scrollbarVitesseRM->setPos(scrollPosition);
                            app.scrollbarVitesseRM->setSmallStep(1);
                            app.fermeRMControlButton= app.Device->getGUIEnvironment()->addButton(core::rect<int>(100,210,145,230), app.windowRMControl, SAppContext::GUI_ID_BUTTON_FERME_ETAT_RM, L"Fermer");
                            SelectedRM->proprietesOuvert=true;
                        }
                     }

                     if(strcmp(cstr,"tkdeb")==0) {
                        printf("tkd clicked %s\n",SelectedNode->getName());
                        SelectedRM=mountain->getRemonteeByID(SelectedNode->getName());
                        if(SelectedRM && SelectedRM->proprietesOuvert==false) {
                            app.windowRMControl = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(100,170,400,460),true,L"Teleski debrayable",0,SAppContext::GUI_ID_WINDOW_ETAT_RM);
                            app.windowRMControl->getCloseButton()->setVisible(false);
                            app.Device->getGUIEnvironment()->addStaticText(L"Nom du teleski:", rect<s32>(5,40,395,60), false,true,app.windowRMControl);
                            app.editBoxNameRM=app.Device->getGUIEnvironment()->addEditBox(core::stringw(SelectedRM->GetName().c_str()).c_str(),core::rect<int>(5,60,275,90), false,app.windowRMControl, SAppContext::GUI_ID_TEXT_NOM_RM);
                            app.marcheArretRMButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,100,145,120), app.windowRMControl, SAppContext::GUI_ID_BUTTON_MARCHE_RM, L"Marche / Arret");
                            app.Device->getGUIEnvironment()->addStaticText(L"Vitesse du teleski:", rect<s32>(5,140,155,160), false,true,app.windowRMControl);
                            app.labelVitesseRM=app.Device->getGUIEnvironment()->addStaticText(L"",rect<s32>(160, 140, 295, 160), false,true,app.windowRMControl);
                            app.scrollbarVitesseRM=app.Device->getGUIEnvironment()->addScrollBar(true,rect<s32>(5, 180, 295, 200), app.windowRMControl, SAppContext::GUI_ID_SCROLL_BAR_VITESSE_RM);
                            app.scrollbarVitesseRM->setMin(10);
                            app.scrollbarVitesseRM->setMax(100);
                            s32 scrollPosition=(s32)(SelectedRM->vitesse*100.0f/SelectedRM->vitesseMax);
                            printf("vitesse max %f\n",SelectedRM->vitesseMax);
                            //s32 scrollPosition=(s32)(SelectedRM->vitesse*100.0f/0.3f);
                            printf("scrollPosition %i\n",scrollPosition);
                            app.scrollbarVitesseRM->setPos(scrollPosition);
                            app.scrollbarVitesseRM->setSmallStep(1);
                            app.lauchPercheTkdButton= app.Device->getGUIEnvironment()->addButton(core::rect<int>(60,210,195,230), app.windowRMControl, SAppContext::GUI_ID_BUTTON_LAUNCHPERCHETKD, L"Faire partir une perche");
                            app.fermeRMControlButton= app.Device->getGUIEnvironment()->addButton(core::rect<int>(110,240,155,260), app.windowRMControl, SAppContext::GUI_ID_BUTTON_FERME_ETAT_RM, L"Fermer");
                            SelectedRM->proprietesOuvert=true;
                        }
                     }

                     if(strcmp(cstr,"tsf2p")==0) {
                        printf("tsf2p clicked %s\n",SelectedNode->getName());
                        SelectedRM=mountain->getRemonteeByID(SelectedNode->getName());
                        if(SelectedRM && SelectedRM->proprietesOuvert==false) {
                            app.windowRMControl = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(100,170,400,410),true,L"Telesiege siege fixe 2 pl",0,SAppContext::GUI_ID_WINDOW_ETAT_RM);
                            app.windowRMControl->getCloseButton()->setVisible(false);
                            app.Device->getGUIEnvironment()->addStaticText(L"Nom du telesiege:", rect<s32>(5,40,395,60), false,true,app.windowRMControl);
                            app.editBoxNameRM=app.Device->getGUIEnvironment()->addEditBox(core::stringw(SelectedRM->GetName().c_str()).c_str(),core::rect<int>(5,60,275,90), false,app.windowRMControl, SAppContext::GUI_ID_TEXT_NOM_RM);
                            app.marcheArretRMButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,100,145,120), app.windowRMControl, SAppContext::GUI_ID_BUTTON_MARCHE_RM, L"Marche / Arret");
                            app.Device->getGUIEnvironment()->addStaticText(L"Vitesse du telesiege:", rect<s32>(5,140,155,160), false,true,app.windowRMControl);
                            app.labelVitesseRM=app.Device->getGUIEnvironment()->addStaticText(L"",rect<s32>(160, 140, 295, 160), false,true,app.windowRMControl);
                            app.scrollbarVitesseRM=app.Device->getGUIEnvironment()->addScrollBar(true,rect<s32>(5, 180, 295, 200), app.windowRMControl, SAppContext::GUI_ID_SCROLL_BAR_VITESSE_RM);
                            app.scrollbarVitesseRM->setMin(10);
                            app.scrollbarVitesseRM->setMax(100);
                            s32 scrollPosition=(s32)(SelectedRM->vitesse*100.0f/SelectedRM->vitesseMax);
                            printf("vitesse max %f\n",SelectedRM->vitesseMax);
                            //s32 scrollPosition=(s32)(SelectedRM->vitesse*100.0f/0.3f);
                            printf("scrollPosition %i\n",scrollPosition);
                            app.scrollbarVitesseRM->setPos(scrollPosition);
                            app.scrollbarVitesseRM->setSmallStep(1);
                            app.fermeRMControlButton= app.Device->getGUIEnvironment()->addButton(core::rect<int>(100,210,145,230), app.windowRMControl, SAppContext::GUI_ID_BUTTON_FERME_ETAT_RM, L"Fermer");
                            SelectedRM->proprietesOuvert=true;
                        }
                     }
                     // Remember where the node and cursor were when it was clicked on
                        //position2di            initialCursorPosition;      // where mouse cursor started
                        //position2di            initialObjectPosition;      // where ray from camera to object intersected screen
                     //initialCursorPosition = device->getCursorControl()->getPosition();
                     //initialObjectPosition = CollMan->getScreenCoordinatesFrom3DPosition(SelectedNode->getAbsolutePosition(), camera);
                } else {
                   printf("no node selected\n");
                }
            }

            //Si on est en mode planter un arbre
            if(app.gameAction==SAppContext::ACTION_PLANT_TREES) {
                //trouve l'id max du tableau d'arbres
                u32 maxIdArbre=0;
                for(unsigned int i=0;i<mountain->arrArbres.size();i++) {
                    core::stringc strIdArbre=mountain->arrArbres[i]->GetID();
                    strIdArbre=strIdArbre.replace("arbre","");
                    u32 nbId=atoi(strIdArbre.c_str());
                    if(nbId>maxIdArbre) {
                        maxIdArbre=nbId;
                    }
                }

                maxIdArbre++;

                CArbre *ar=new CArbre(app.Device->getSceneManager(),app.Driver);
                ar->SetPosition(mountain->clickTerrainCoordinates());
                ar->DrawArbre();
                core::stringc arbreName="arbre";
                arbreName=arbreName + core::stringc(maxIdArbre);
                printf("numero arbre %s\n",core::stringc(maxIdArbre).c_str());


                ar->SetID(arbreName);

                printf("plant arbre %ls\n",ar->GetID().c_str());

                mountain->arrArbres.push_back(ar);
            }

            //Si on est en mode placer un depart pour TKFixe
            if(app.gameAction==SAppContext::ACTION_BUILD_TKF_DEPART) {
                CTKFixe *tkf=new CTKFixe(app.Device->getSceneManager(),app.Driver);
                tkf->SetPositionDepart(mountain->clickTerrainCoordinates());
                printf("clickTerrainCoordinates TKFDepart: %f %f %f \n",tkf->GetPositionDepart().X,tkf->GetPositionDepart().Y,tkf->GetPositionDepart().Z);
                tkf->DrawRemonteeDepart();
                core::stringc tkfID="rmtkf";
                tkfID + core::stringc(mountain->arrRemontees.size());
                tkf->SetID(tkfID);

                mountain->arrRemontees.push_back(tkf);
                app.currentRemontee=tkf;
                app.gameAction=SAppContext::ACTION_BUILD_TKF_ARRIVEE;
                app.textExplic="Placez la gare d arrivee";
                break;
            }

            //Si on est en mode placer la gare darrivee  pour TKFixe
            if(app.gameAction==SAppContext::ACTION_BUILD_TKF_ARRIVEE) {

                app.currentRemontee->SetPositionArrivee(mountain->clickTerrainCoordinates());
                printf("clickTerrainCoordinates TKFArrivee: %f %f %f \n",app.currentRemontee->GetPositionArrivee().X,app.currentRemontee->GetPositionArrivee().Y,app.currentRemontee->GetPositionArrivee().Z);
                app.currentRemontee->DrawRemonteeArrivee();

                app.gameAction=SAppContext::ACTION_BUILD_TKF_PYLONES;
                app.windowPylones = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(100,70,400,270),true,L"Ajout de pylones",0,SAppContext::GUI_ID_WINDOW_PYLONES);
                app.windowPylones->getCloseButton()->setVisible(false);
                app.newPyloneButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,20,145,60), app.windowPylones, SAppContext::GUI_ID_BUTTON_NOUVEAU_PYLONE, L"Ajouter pylone");
                app.terminePyloneButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(155,20,295,60), app.windowPylones, SAppContext::GUI_ID_BUTTON_TERMINER_PYLONE, L"Terminer remontee");
                app.killLastPyloneButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,120,205,140), app.windowPylones, SAppContext::GUI_ID_BUTTON_KILL_LAST_PYLONE, L"Supprimer dernier pylone");
                app.currentPylone=0;
                core::stringw nbPylones="Nombre de pylones : ";
                nbPylones+= core::stringw(app.currentRemontee->arrPylones.size());
                app.labelNbPylone=app.Device->getGUIEnvironment()->addStaticText(nbPylones.c_str(), rect<s32>(5,80,295,95), false,true,app.windowPylones);

                app.textExplic="Placez les pylones";
                break;
            }

            //Si on est en mode placer les pylones pour TKFixe
            if(app.gameAction==SAppContext::ACTION_BUILD_TKF_PYLONES) {
                break;
            }

            //Si on est en mode placer le départ pour TKDebrayable
            if(app.gameAction==SAppContext::ACTION_BUILD_TKD_DEPART) {
                CTKDebrayable *tkd=new CTKDebrayable(app.Device->getSceneManager(),app.Driver);
                tkd->SetPositionDepart(mountain->clickTerrainCoordinates());
                printf("clickTerrainCoordinates TSF2Depart: %f %f %f \n",tkd->GetPositionDepart().X,tkd->GetPositionDepart().Y,tkd->GetPositionDepart().Z);
                tkd->DrawRemonteeDepart();

                core::stringc tkdID="tkdeb";
                tkdID + core::stringc(mountain->arrRemontees.size());
                tkd->SetID(tkdID);

                mountain->arrRemontees.push_back(tkd);
                app.currentRemontee=tkd;
                app.gameAction=SAppContext::ACTION_BUILD_TKD_ARRIVEE;
                app.textExplic="Placez la gare d arrivee";
                break;
            }

            //Si on est en mode placer la gare darrivee  pour TKDeb
            if(app.gameAction==SAppContext::ACTION_BUILD_TKD_ARRIVEE) {
                app.currentRemontee->SetPositionArrivee(mountain->clickTerrainCoordinates());
                printf("clickTerrainCoordinates TKDArrivee: %f %f %f \n",app.currentRemontee->GetPositionArrivee().X,app.currentRemontee->GetPositionArrivee().Y,app.currentRemontee->GetPositionArrivee().Z);
                app.currentRemontee->DrawRemonteeArrivee();

                app.gameAction=SAppContext::ACTION_NONE;
                app.textExplic="";

                app.currentRemontee->UpdateTroncons();
                printf("update troncon at tkd arrivee build\n");
                app.currentRemontee->constructionFinie=true;
                app.currentRemontee->PlaceVehicules();
                app.currentRemontee->enMarche=true;
                //app.currentRemontee->PlaySoundMoteur(true);

                /*app.gameAction=SAppContext::ACTION_BUILD_TKD_PYLONES;
                app.windowPylones = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(100,70,400,270),true,L"Ajout de pylones",0,SAppContext::GUI_ID_WINDOW_PYLONES);
                app.windowPylones->getCloseButton()->setVisible(false);
                app.newPyloneButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,20,145,60), app.windowPylones, SAppContext::GUI_ID_BUTTON_NOUVEAU_PYLONE, L"Ajouter pylone");
                app.terminePyloneButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(155,20,295,60), app.windowPylones, SAppContext::GUI_ID_BUTTON_TERMINER_PYLONE, L"Terminer pylone");
                app.killLastPyloneButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,120,205,140), app.windowPylones, SAppContext::GUI_ID_BUTTON_KILL_LAST_PYLONE, L"Supprimer dernier pylone");
                app.currentPylone=0;
                core::stringw nbPylones="Nombre de pylones : ";
                nbPylones+= core::stringw(app.currentRemontee->arrPylones.size());
                app.labelNbPylone=app.Device->getGUIEnvironment()->addStaticText(nbPylones.c_str(), rect<s32>(5,80,295,95), false,true,app.windowPylones);

                app.textExplic="Placez les pylones";*/
                break;
            }

             //Si on est en mode placer le départ pour TSFixe2
            if(app.gameAction==SAppContext::ACTION_BUILD_TSF2_DEPART) {
                CTSFixe *tsf2=new CTSFixe(app.Device->getSceneManager(),app.Driver);
                tsf2->SetPositionDepart(mountain->clickTerrainCoordinates());
                printf("clickTerrainCoordinates TSF2Depart: %f %f %f \n",tsf2->GetPositionDepart().X,tsf2->GetPositionDepart().Y,tsf2->GetPositionDepart().Z);
                tsf2->DrawRemonteeDepart();

                core::stringc tsfID="tsf2p";
                tsfID + core::stringc(mountain->arrRemontees.size());
                tsf2->SetID(tsfID);

                mountain->arrRemontees.push_back(tsf2);
                app.currentRemontee=tsf2;
                app.gameAction=SAppContext::ACTION_BUILD_TSF2_ARRIVEE;
                app.textExplic="Placez la gare d arrivee";
                break;
            }

            //Si on est en mode placer la gare darrivee  pour TSFixe2
            if(app.gameAction==SAppContext::ACTION_BUILD_TSF2_ARRIVEE) {

                app.currentRemontee->SetPositionArrivee(mountain->clickTerrainCoordinates());
                printf("clickTerrainCoordinates TSF2Arrivee: %f %f %f \n",app.currentRemontee->GetPositionArrivee().X,app.currentRemontee->GetPositionArrivee().Y,app.currentRemontee->GetPositionArrivee().Z);
                app.currentRemontee->DrawRemonteeArrivee();

                app.gameAction=SAppContext::ACTION_BUILD_TSF2_PYLONES;
                app.windowPylones = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(100,70,400,270),true,L"Ajout de pylones",0,SAppContext::GUI_ID_WINDOW_PYLONES);
                app.windowPylones->getCloseButton()->setVisible(false);
                app.newPyloneButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,20,145,60), app.windowPylones, SAppContext::GUI_ID_BUTTON_NOUVEAU_PYLONE, L"Ajouter pylone");
                app.terminePyloneButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(155,20,295,60), app.windowPylones, SAppContext::GUI_ID_BUTTON_TERMINER_PYLONE, L"Terminer pylone");
                app.killLastPyloneButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,120,205,140), app.windowPylones, SAppContext::GUI_ID_BUTTON_KILL_LAST_PYLONE, L"Supprimer dernier pylone");
                app.currentPylone=0;
                core::stringw nbPylones="Nombre de pylones : ";
                nbPylones+= core::stringw(app.currentRemontee->arrPylones.size());
                app.labelNbPylone=app.Device->getGUIEnvironment()->addStaticText(nbPylones.c_str(), rect<s32>(5,80,295,95), false,true,app.windowPylones);

                app.textExplic="Placez les pylones";
                break;
            }


        case EMIE_LMOUSE_LEFT_UP:
            MouseState.LeftButtonDown = false;
            break;

        case EMIE_MOUSE_MOVED:
            MouseState.Position.X = event.MouseInput.X;
            MouseState.Position.Y = event.MouseInput.Y;
            break;

        default:
            // We won't use the wheel
            break;
        }
    }


    if (event.EventType == EET_GUI_EVENT)
	{
		s32 id = event.GUIEvent.Caller->getID();

		if (event.GUIEvent.EventType==EGET_COMBO_BOX_CHANGED)
        {
            if (id == SAppContext::GUI_ID_COMBO_TYPE_PYLONE)
            {
                printf("Type pylone changed\n");

                //Si TKF
                if(app.currentRemontee->typeRM==CRemontee::RM_TKF) {
                    core::vector3df rotation= app.currentPylone->getRotation();
                    core:vector3df position= app.currentPylone->getPosition();
                    app.currentPylone->ChangeTypePylone(app.comboboxTypePylone->getItemData(app.comboboxTypePylone->getSelected()),position,rotation);
                }

                //Si TSF2
                if(app.currentRemontee->typeRM==CRemontee::RM_TSF2) {
                    core::vector3df rotation2= app.currentPylone->getRotation();
                    core::vector3df position2= app.currentPylone->getPosition();
                    app.currentPylone->ChangeTypePylone(app.comboboxTypePylone->getItemData(app.comboboxTypePylone->getSelected()),position2,rotation2);
                }

            }
        }

        if (event.GUIEvent.EventType==EGET_SCROLL_BAR_CHANGED)
        {
            if (id == SAppContext::GUI_ID_SCROLL_BAR_VITESSE_RM)
            {
                if(SelectedRM) {
                    SelectedRM->vitesse=SelectedRM->vitesseMax*(f32)app.scrollbarVitesseRM->getPos()/100;
                    core::stringw lblVit="V = ";
                    f32 compteurVitesse=SelectedRM->vitesse;
                    lblVit+= core::stringw(compteurVitesse);
                    lblVit+=" m/s";
                    app.labelVitesseRM->setText(lblVit.c_str());
                    if(SelectedRM->GetSoundMoteur()) {
                        SelectedRM->GetSoundMoteur()->setPitchShift((f32)(app.scrollbarVitesseRM->getPos()/100.0f));
                    }

                }
            }
        }

		if (event.GUIEvent.EventType==EGET_SCROLL_BAR_CHANGED)
        {
            if (id == SAppContext::GUI_ID_SCROLL_BAR_NEW_PYLONE)
            {
                //printf("Scrollbar changed\n");
                //s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();
                //applique le changement de coordonnees au pylone
                //Selon le nb de pylones
                 core::vector3df posPylone;
                    if(app.currentRemontee->arrPylones.size()>1)
                    {

                        u32 indexlastPylone=app.currentRemontee->arrPylones.size()-2;
                        vector3df difference=app.currentRemontee->GetPositionArrivee()-app.currentRemontee->arrPylones[indexlastPylone]->getPosition();
                        //f32 pas=difference.getLength()/100;
                        //difference=difference.normalize();

                        //core::vector3df droite=core::vector3df(app.currentRemontee->GetPositionArrivee().X-app.currentRemontee->arrPylones[indexlastPylone]->getPosition().X,app.currentRemontee->GetPositionArrivee().Y-app.currentRemontee->arrPylones[indexlastPylone]->getPosition().Y,app.currentRemontee->GetPositionArrivee().Z-app.currentRemontee->arrPylones[indexlastPylone]->getPosition().Z);
                        core::vector3df vecPosPyl;
                        vecPosPyl.X=app.currentRemontee->arrPylones[indexlastPylone]->getPosition().X+difference.X*(f32)app.scrollbarNewPylone->getPos()/100;
                        vecPosPyl.Y=app.currentRemontee->arrPylones[indexlastPylone]->getPosition().Y+difference.Y*(f32)app.scrollbarNewPylone->getPos()/100;
                        vecPosPyl.Z=app.currentRemontee->arrPylones[indexlastPylone]->getPosition().Z+difference.Z*(f32)app.scrollbarNewPylone->getPos()/100;

                        vecPosPyl.Y=mountain->GetHeight(vecPosPyl,9000.0f);

                        posPylone=vecPosPyl;
                        //core::vector3df(app.currentRemontee->GetPositionDepart().X+droite.X*app.scrollbarNewPylone->getPos()/100,8000,app.currentRemontee->GetPositionDepart().Z+droite.Z*app.scrollbarNewPylone->getPos()/100);
                        //core::vector3df vecPosPyl=app.currentRemontee->arrPylones[indexlastPylone]->getPosition()+(f32)app.scrollbarNewPylone->getPos()*difference;
                        //posPylone=core::vector3df(vecPosPyl.X,mountain->GetHeight(vecPosPyl,9000.0f),vecPosPyl.Z);
                        //printf("2 pos=%f pas=%f difference %f %f %f\n",(f32)app.scrollbarNewPylone->getPos(),pas,difference.X,difference.Y,difference.Z);
                        //printf("2 pos=%f vecPosPyl %f %f %f\n",(f32)app.scrollbarNewPylone->getPos(),vecPosPyl.X,vecPosPyl.Y,vecPosPyl.Z);
                    } else {
                         vector3df difference=app.currentRemontee->GetPositionArrivee()-app.currentRemontee->GetPositionDepart();
                         //f32 pas=difference.getLength()/100;
                         //difference=difference.normalize();
                         core::vector3df vecPosPyl;
                         vecPosPyl.X=app.currentRemontee->GetPositionDepart().X+difference.X*(f32)app.scrollbarNewPylone->getPos()/100;
                         vecPosPyl.Y=app.currentRemontee->GetPositionDepart().Y+difference.Y*(f32)app.scrollbarNewPylone->getPos()/100;
                         vecPosPyl.Z=app.currentRemontee->GetPositionDepart().Z+difference.Z*(f32)app.scrollbarNewPylone->getPos()/100;

                         vecPosPyl.Y=mountain->GetHeight(vecPosPyl,9000.0f);

                         posPylone=vecPosPyl;
                         //core::vector3df vecPosPyl=app.currentRemontee->GetPositionDepart()+difference;
                         //posPylone=core::vector3df(vecPosPyl.X,mountain->GetHeight(vecPosPyl,2000.0f),vecPosPyl.Z);
                         //printf("1 pos=%f pas=%f difference %f %f %f\n",(f32)app.scrollbarNewPylone->getPos(),pas,difference.X,difference.Y,difference.Z);
                         //printf("1 pos=%f vecPosPyl %f %f %f\n",(f32)app.scrollbarNewPylone->getPos(),vecPosPyl.X,vecPosPyl.Y,vecPosPyl.Z);
                    }
                app.currentPylone->setPosition(posPylone);
                //Si c'est un TS, il faut rafraichir a chaque fois l'affichage du pylone pour gérer l'affichage support compression
                if(app.currentRemontee->typeRM==CRemontee::RM_TSF2) {
                    printf("scrollbar ->changeTypePylone TS \n");
                    app.currentPylone->ChangeTypePylone(app.currentPylone->GetType(),posPylone,app.currentRemontee->GetRotationRM());
                }

                app.currentRemontee->UpdateTroncons();

                //setSkinTransparency(pos, env->getSkin());
            }
        }

        //printf("onEvent\n");
		switch(id)
		{

		case SAppContext::GUI_ID_CONSTRUCTION_BUTTON: //Btn Construction
			if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
				//printf("New button clicked \n");

                app.windowConstruction = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(5,70,205,200),true,L"Choisir une construction",0,SAppContext::GUI_ID_WINDOW_CONSTRUCTION);
                app.newRMButton =  app.Device->getGUIEnvironment()->addButton(core::rect<s32>(5, 25, 195, 55),app.windowConstruction,SAppContext::GUI_ID_BUTTON_NOUVEAU_RM,L"Nouvelle remontee");
                app.newPisteButton =  app.Device->getGUIEnvironment()->addButton(core::rect<s32>(5, 60, 195, 90),app.windowConstruction,SAppContext::GUI_ID_BUTTON_NOUVELLE_PISTE,L"Nouvelle piste");
                app.newArbreButton =  app.Device->getGUIEnvironment()->addButton(core::rect<s32>(5, 95, 195, 125),app.windowConstruction,SAppContext::GUI_ID_BUTTON_ARBRES,L"Ajouter un arbre");

				//MenuDevice->closeDevice();
				//start = true;
			}
			break;

        case SAppContext::GUI_ID_BUTTON_NOUVEAU_RM: //Btn Construction
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
                app.windowTypeRm = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(210,70,415,200),true,L"Type de remontee",0,SAppContext::GUI_ID_WINDOW_TYPE_RM);
                app.tkfixeButton =  app.Device->getGUIEnvironment()->addButton(core::rect<s32>(5, 25, 195, 55),app.windowTypeRm,SAppContext::GUI_ID_BUTTON_TKFIXE,L"Teleski fixe");
                app.tkdebrayableButton =  app.Device->getGUIEnvironment()->addButton(core::rect<s32>(5, 60, 195, 90),app.windowTypeRm,SAppContext::GUI_ID_BUTTON_TKDEBRAYABLE,L"Teleski debrayable");
                app.ts2fixeButton =  app.Device->getGUIEnvironment()->addButton(core::rect<s32>(5, 95, 195, 125),app.windowTypeRm,SAppContext::GUI_ID_BUTTON_TS2FIXE,L"Telesiege 2p fixe");
                app.windowConstruction->remove();
			}
			break;

        case SAppContext::GUI_ID_BUTTON_TKFIXE: //Btn Construction TK Fixe
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
                app.windowTypeRm->remove();
                app.gameAction=SAppContext::ACTION_BUILD_TKF_DEPART;
                app.textExplic="Placez la gare de depart";
                printf("Place depart TK Fixe\n");
			}
			break;

        case SAppContext::GUI_ID_BUTTON_TKDEBRAYABLE: //Btn Construction TK Fixe
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
                app.windowTypeRm->remove();
                app.gameAction=SAppContext::ACTION_BUILD_TKD_DEPART;
                app.textExplic="Placez la gare de depart";
                printf("Place depart TK Debrayable\n");
			}
			break;

        case SAppContext::GUI_ID_BUTTON_TS2FIXE: //Btn Construction TK Fixe
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
                app.windowTypeRm->remove();
                app.gameAction=SAppContext::ACTION_BUILD_TSF2_DEPART;
                app.textExplic="Placez la gare de depart";
                printf("Place depart TSF2 Fixe\n");
			}
			break;

        case SAppContext::GUI_ID_BUTTON_ARBRES: //Btn plante arbre
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
                app.gameAction=SAppContext::ACTION_PLANT_TREES;
                app.windowStopTree = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(250,170,400,238),true,L"Plantation",0,SAppContext::GUI_ID_WINDOW_STOP_TREE);
                app.windowStopTree->getCloseButton()->setVisible(false);
                app.stopTreeButton = app.Device->getGUIEnvironment()->addButton(core::rect<int>(5,22,145,62), app.windowStopTree, SAppContext::GUI_ID_BOUTON_STOP_TREE, L"Stopper la plantation");
                printf("Plante arbre(s)\n");
			}
			break;

        //Si on clique sur couper l'arbre selectionné
         case SAppContext::GUI_ID_BOUTON_TREE_CUT: //Btn plante arbre
            if(event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) {
                if(SelectedArbre!=0 && SelectedArbre->GetID()!="") {
                    for(unsigned int i=0;i<mountain->arrArbres.size();i++) {
                        CArbre *tmpArbre=mountain->arrArbres[i];

                        printf("Compare %s and %s\n",tmpArbre->GetID().c_str(),SelectedArbre->GetID().c_str());
                        if(tmpArbre->GetID()==SelectedArbre->GetID()) {
                            printf("coupe arbre condition ok\n");
                            mountain->arrArbres.erase(i);
                            printf("nouvelle taille tableau  %i\n",mountain->arrArbres.size());
                            SelectedArbre->DropArbre();
                            printf("Drop arbre\n");
                            SelectedArbre=0;
                            break;
                        }
                    }
                    app.windowCutTree->remove();
                }
            }
            break;

        //Si on clique sur arrêter la plantation d'arbre
         case SAppContext::GUI_ID_BOUTON_STOP_TREE: //Btn plante arbre
            if(event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) {
                app.gameAction=SAppContext::ACTION_NONE;
                app.windowStopTree->remove();
            }
            break;

        case SAppContext::GUI_ID_BUTTON_MENU: //Btn Menu
			if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
				//printf("New button clicked \n");

                app.windowMenu = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(800,70,1000,200),true,L"Menu",0,SAppContext::GUI_ID_WINDOW_MENU);
                app.saveButton =  app.Device->getGUIEnvironment()->addButton(core::rect<s32>(5, 25, 195, 55),app.windowMenu,SAppContext::GUI_ID_BUTTON_SAVE,L"Sauvegarder");
                app.quitButton =  app.Device->getGUIEnvironment()->addButton(core::rect<s32>(5, 60, 195, 90),app.windowMenu,SAppContext::GUI_ID_BUTTON_QUIT,L"Quitter");
                //app.newArbreButton =  app.Device->getGUIEnvironment()->addButton(core::rect<s32>(5, 95, 195, 125),app.windowMenu ,SAppContext::GUI_ID_BUTTON_ARBRES,L"Ajouter un arbre");

				//MenuDevice->closeDevice();
				//start = true;
			}
			break;

        case SAppContext::GUI_ID_BUTTON_QUIT: //Btn plante arbre
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
                app.ShouldQuit=true;

			}
			break;

        case SAppContext::GUI_ID_BUTTON_TERMINER_PYLONE: //Btn terminer construction pylonerm
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
                app.gameAction=SAppContext::ACTION_NONE;
                app.textExplic="";

                app.currentRemontee->UpdateTroncons();
                app.currentRemontee->constructionFinie=true;
                app.currentRemontee->PlaceVehicules();
                app.currentRemontee->enMarche=true;
                app.currentRemontee->PlaySoundMoteur(true);
                app.windowPylones->remove();
			}
			break;

        case SAppContext::GUI_ID_BUTTON_NOUVEAU_PYLONE:
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
                app.windowNewPylone = app.Device->getGUIEnvironment()->addWindow(core::rect<s32>(450,70,850,270),true,L"Nouveau pylone",0,SAppContext::GUI_ID_WINDOW_NEW_PYLONE);
                app.Device->getGUIEnvironment()->addStaticText(L"Type de pylone:", rect<s32>(5,40,395,60), false,true,app.windowNewPylone);
                app.Device->getGUIEnvironment()->addStaticText(L"Place du pylone:", rect<s32>(5,100,395,120), false,true,app.windowNewPylone);
                app.comboboxTypePylone=app.Device->getGUIEnvironment()->addComboBox(core::rect<s32>(5, 70, 395, 90),app.windowNewPylone,SAppContext::GUI_ID_COMBO_TYPE_PYLONE);
                app.scrollbarNewPylone=app.Device->getGUIEnvironment()->addScrollBar(true,rect<s32>(5, 130, 395, 145), app.windowNewPylone, SAppContext::GUI_ID_SCROLL_BAR_NEW_PYLONE);
                app.comboboxTypePylone->clear();
                if(app.currentRemontee->typeRM==CRemontee::RM_TKF) {
                    app.comboboxTypePylone->addItem(L"Montee + descente",CPyloneRM::PYLONE_TKF_MONTEE_DESCENTE);
                    app.comboboxTypePylone->addItem(L"Montee seulement",CPyloneRM::PYLONE_TKF_MONTEE);
                }
                if(app.currentRemontee->typeRM==CRemontee::RM_TSF2) {
                    app.comboboxTypePylone->addItem(L"Taille moyenne",CPyloneRM::PYLONE_TSF_MONTEE_DESCENTE_MOYEN);
                    app.comboboxTypePylone->addItem(L"Taille basse",CPyloneRM::PYLONE_TSF_MONTEE_DESCENTE_BAS);
                    app.comboboxTypePylone->addItem(L"Taille grande",CPyloneRM::PYLONE_TSF_MONTEE_DESCENTE_HAUT);
                }

                app.scrollbarNewPylone->setMin(1);
                //app.scrollbarNewPylone->setMax(app.currentRemontee->GetPositionDepart().getDistanceFrom(app.currentRemontee->GetPositionArrivee())-10);
                app.scrollbarNewPylone->setMax(99);
                app.scrollbarNewPylone->setPos(5);
                app.scrollbarNewPylone->setSmallStep(1);
                app.validePyloneButton=app.Device->getGUIEnvironment()->addButton(core::rect<s32>(5, 160, 195, 180),app.windowNewPylone,SAppContext::GUI_ID_BUTTON_VALIDE_PYLONE,L"Valider");
                app.annulePyloneButton=app.Device->getGUIEnvironment()->addButton(core::rect<s32>(205, 160, 395, 180),app.windowNewPylone,SAppContext::GUI_ID_BUTTON_ANNULE_PYLONE,L"Annuler");
                if(app.currentRemontee->typeRM==CRemontee::RM_TKF) {
                    app.gameAction=SAppContext::ACTION_BUILD_TKF_NEW_PYLONE;
                }
                if(app.currentRemontee->typeRM==CRemontee::RM_TSF2) {
                    app.gameAction=SAppContext::ACTION_BUILD_TSF2_NEW_PYLONE;
                }
                if(app.currentRemontee->typeRM==CRemontee::RM_TKD) {
                    app.gameAction=SAppContext::ACTION_BUILD_TKD_NEW_PYLONE;
                }
                core::stringw lblExplic="Placez le pylone numero ";
                lblExplic+= core::stringw(app.currentRemontee->arrPylones.size());
                app.textExplic=lblExplic;

                core::vector3df posPylone;
                app.currentPylone=new CPyloneRM(app.Device->getSceneManager(),app.Driver);

                //Selon le nb de pylones
                if(app.currentRemontee->arrPylones.size()>1)
                {
                    u32 indexlastPylone=app.currentRemontee->arrPylones.size()-2;
                    vector3df difference=app.currentRemontee->GetPositionArrivee()-app.currentRemontee->arrPylones[indexlastPylone]->getPosition();
                    //f32 pas=difference.getLength()/100;
                    //difference=difference.normalize();

                    //core::vector3df droite=core::vector3df(app.currentRemontee->GetPositionArrivee().X-app.currentRemontee->arrPylones[indexlastPylone]->getPosition().X,app.currentRemontee->GetPositionArrivee().Y-app.currentRemontee->arrPylones[indexlastPylone]->getPosition().Y,app.currentRemontee->GetPositionArrivee().Z-app.currentRemontee->arrPylones[indexlastPylone]->getPosition().Z);
                    core::vector3df vecPosPyl;
                    vecPosPyl.X=app.currentRemontee->arrPylones[indexlastPylone]->getPosition().X+difference.X*(f32)app.scrollbarNewPylone->getPos()/100;
                    vecPosPyl.Y=app.currentRemontee->arrPylones[indexlastPylone]->getPosition().Y+difference.Y*(f32)app.scrollbarNewPylone->getPos()/100;
                    vecPosPyl.Z=app.currentRemontee->arrPylones[indexlastPylone]->getPosition().Z+difference.Z*(f32)app.scrollbarNewPylone->getPos()/100;

                    vecPosPyl.Y=mountain->GetHeight(vecPosPyl,9000.0f);

                    posPylone=vecPosPyl;

                    /*u32 indexlastPylone=app.currentRemontee->arrPylones.size()-1;

                    core::vector3df droite=core::vector3df(app.currentRemontee->GetPositionArrivee().X-app.currentRemontee->arrPylones[indexlastPylone]->getPosition().X,app.currentRemontee->GetPositionArrivee().Y-app.currentRemontee->arrPylones[indexlastPylone]->getPosition().Y,app.currentRemontee->GetPositionArrivee().Z-app.currentRemontee->arrPylones[indexlastPylone]->getPosition().Z);
                    core::vector3df vecPosPyl=core::vector3df(app.currentRemontee->GetPositionDepart().X+droite.X*app.scrollbarNewPylone->getPos()/100,2000,app.currentRemontee->GetPositionDepart().Z+droite.Z*app.scrollbarNewPylone->getPos()/100);
                    posPylone=core::vector3df(vecPosPyl.X,mountain->GetHeight(vecPosPyl,5000),vecPosPyl.Z);*/
                    //printf("Droite %f %f %f\n",droite.X,droite.Y,droite.Z);
                } else {
                    vector3df difference=app.currentRemontee->GetPositionArrivee()-app.currentRemontee->GetPositionDepart();
                    core::vector3df vecPosPyl;
                    vecPosPyl.X=app.currentRemontee->GetPositionDepart().X+difference.X*(f32)app.scrollbarNewPylone->getPos()/100;
                    vecPosPyl.Y=app.currentRemontee->GetPositionDepart().Y+difference.Y*(f32)app.scrollbarNewPylone->getPos()/100;
                    vecPosPyl.Z=app.currentRemontee->GetPositionDepart().Z+difference.Z*(f32)app.scrollbarNewPylone->getPos()/100;

                    vecPosPyl.Y=mountain->GetHeight(vecPosPyl,9000.0f);

                    posPylone=vecPosPyl;

                    /*core::vector3df droite=core::vector3df(app.currentRemontee->GetPositionArrivee().X-app.currentRemontee->GetPositionDepart().X,app.currentRemontee->GetPositionArrivee().Y-app.currentRemontee->GetPositionDepart().Y,app.currentRemontee->GetPositionArrivee().Z-app.currentRemontee->GetPositionDepart().Z);
                    core::vector3df vecPosPyl=core::vector3df(app.currentRemontee->GetPositionDepart().X+droite.X*app.scrollbarNewPylone->getPos()/100,2000,app.currentRemontee->GetPositionDepart().Z+droite.Z*app.scrollbarNewPylone->getPos()/100);
                    posPylone=core::vector3df(vecPosPyl.X,mountain->GetHeight(vecPosPyl,5000),vecPosPyl.Z);
                    //printf("Droite %f %f %f\n",droite.X,droite.Y,droite.Z);*/
                }


                //Creation de l'instance pylone en cours
                switch(app.currentRemontee->typeRM) {
                    case CRemontee::RM_TKF:
                        app.currentPylone->SetType(CPyloneRM::PYLONE_TKF_MONTEE_DESCENTE);
                        app.currentPylone->DrawPylone(posPylone,app.currentRemontee->GetRotationRM());

                        printf("Place pylone TKF %f %f %f\n",posPylone.X,posPylone.Y,posPylone.Z);
                    break;

                    case CRemontee::RM_TKD:

                    break;

                    case CRemontee::RM_TSF2:
                        app.currentPylone->SetType(CPyloneRM::PYLONE_TSF_MONTEE_DESCENTE_MOYEN);
                        app.currentPylone->DrawPylone(posPylone,app.currentRemontee->GetRotationRM());

                        printf("Place pylone TSF2 %f %f %f\n",posPylone.X,posPylone.Y,posPylone.Z);
                    break;
                }
                app.currentRemontee->arrPylones.push_back(app.currentPylone);
                //app.currentRemontee->UpdateTroncons();
                app.currentRemontee->RedrawCable();
			}
			break;

        //Bouton annule le pylone en cours de création
        case SAppContext::GUI_ID_BUTTON_ANNULE_PYLONE:
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
                //enleve le dernier pylone
                u32 indexlastPylone=app.currentRemontee->arrPylones.size()-1;
                app.currentRemontee->arrPylones[indexlastPylone]->DropPylone();
                app.currentRemontee->arrPylones.erase(indexlastPylone);
                app.currentRemontee->UpdateTroncons();

                printf("ANNULE_PYLONE app.currentRemontee->arrPylones.erase ok\n");
                //delete app.currentPylone;
                app.currentPylone=0;

                //app.currentRemontee->RedrawCable();
                app.windowNewPylone->remove();
                printf("ANNULE_PYLONE app.windowNewPylone->remove() ok\n");

                core::stringw nbPylones="Nombre de pylones : ";
                nbPylones+= core::stringw(app.currentRemontee->arrPylones.size());
                app.labelNbPylone->setText(nbPylones.c_str());
			}
			break;

		  //Bouton valider le nouveau pylone
         case SAppContext::GUI_ID_BUTTON_VALIDE_PYLONE:
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{

                app.currentPylone=0;

                core::stringw nbPylones="Nombre de pylones : ";
                nbPylones+= core::stringw(app.currentRemontee->arrPylones.size());
                app.labelNbPylone->setText(nbPylones.c_str());

                app.windowNewPylone->remove();

			}
			break;

		 //Bouton supprimer le dernier pylone
         case SAppContext::GUI_ID_BUTTON_KILL_LAST_PYLONE:
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{

                if(app.currentRemontee->arrPylones.size()>0)
                {
                    u32 indexlastPylone=app.currentRemontee->arrPylones.size()-1;
                    CPyloneRM *pylToKill=app.currentRemontee->arrPylones[indexlastPylone];
                    app.currentRemontee->arrPylones.erase(indexlastPylone);
                    pylToKill->DropPylone();

                    //delete pylToKill;

                    //printf("KILL_LAST_PYLONE erase ok\n");
                    core::stringw nbPylones="Nombre de pylones : ";
                    nbPylones+= core::stringw(app.currentRemontee->arrPylones.size());
                    app.labelNbPylone->setText(nbPylones.c_str());

                    app.currentRemontee->UpdateTroncons();
                    //printf("KILL_LAST_PYLONE UpdateTroncons nbpyl=%i ok\n",app.currentRemontee->arrPylones.size());
                    //app.currentRemontee->RedrawCable();
                }

			}
			break;

        //Si on est en mode placer un depart pour TKFixe
        case SAppContext::GUI_ID_BUTTON_MARCHE_RM:
            if(event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) {
                if(SelectedRM) {
                    SelectedRM->enMarche=!SelectedRM->enMarche;
                }
            }
            break;

        case SAppContext::GUI_ID_BUTTON_FERME_ETAT_RM:
        if(event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) {
                if(SelectedRM) {
                    //Sauvegarde le nom
                    SelectedRM->SetName(core::stringc(app.editBoxNameRM->getText()));

                    SelectedRM->proprietesOuvert=false;
                    app.windowRMControl->remove();
                }
            }
            break;

        case  SAppContext::GUI_ID_BUTTON_LAUNCHPERCHETKD:
        if(event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) {
             if(SelectedRM) {
                 dynamic_cast<CTKDebrayable*>(SelectedRM)->removePercheInGare();
            }
        }
        break;

        }




	}

    return false;
}
