var selectedLang = 'es';
var openedSection = false;
var menu1Template = new Template('<li><a href="about.php" >#{about}</a></li><li><a href="mission.php">#{mission}</a></li><li><a href="clients.php">#{clients}</a></li><li><a href="contact.php">#{contact}</a></li>');
var menu2Template = new Template('<li><a href="services.php" >#{services}</a></li><li><a href="products.php">#{products}</a></li>');
var menuLang = {
  es: {about:'La Empresa', mission:'Misión / Visión', clients:'Clientes', contact:'Contacto', services:'Servicios', products:'Productos'},
  en: {about:'About Us', mission:'Mission / Vision', clients:'Clients', contact:'Contact Us', services:'Services', products:'Products'}
};
var sloganLang = {es:'Informática Industrial', en:'Industrial Informatics'}


function alert(msg) {
  var body = $$('body')[0];

  body.insert(Builder.node('iframe', {id:'hideSelect'}));
  body.insert(Builder.node('div',{id:'alert'}, [
    Builder.node('input', {id:'alertOk', type:'button', value:'Ok'}).observe('click', function(event) {
      $('hideSelect').remove();
      $('alert').remove();
      $('overlay').remove();
    }),
    Builder.node('img', {src:'images/alert.png', alt:''}),
    Builder.node('div',{id:'alertContent'}, msg)
  ]));
  body.insert(Builder.node('div',{id:'overlay'}));
}

function getParameter(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if (results == null) {
    return results;
  } else {
    return results[1];
  }
}


function showIntro() {
  mainWidth = document.viewport.getWidth() * 0.6;
  mainHeight = document.viewport.getHeight() * 0.6;

  new Effect.Parallel([
    new Effect.Scale('main', 60, {
      sync:true,
      afterFinish:function() {$('main').setStyle({width:'60%'});}
    }),
    new Effect.Move('main', {sync:true, y: 90}),
    new Effect.Scale('logoIntro', 50, {sync:true}),
    new Effect.Move('logoIntro', {sync:true, x: parseInt(mainWidth*0.5), y: parseInt(mainHeight*0.5), queue:{position:'end', scope:'logo'}})
  ], {queue:{position:'end', scope:'scale'}});
  new Effect.Opacity('logoIntro', {from: 1.0, to: 0.3, duration: 0.5, queue:{position:'end', scope:'logo'}});

  $('bar').show();
  new Effect.Morph('bar', {style:'width:60%', queue:{position:'end', scope:'scale'}});
  new Effect.SlideDown('menu', {
    afterFinish:function() {
      //Configuracion de los links del menu
      setMenuLinks();
      setLangLinks();
    },
    queue:{position:'end', scope:'scale'}
  });
  new Effect.Parallel([
    new Effect.Appear('logoIndos', {
      sync:true,
      afterFinish:function() {
        //Fijo el ancho de las ventanas
        $('main').setStyle({width:$('main').getWidth()+'px'});
        $('bar').setStyle({width:$('bar').getWidth()+'px'});
        $('menu').setStyle({width:$('menu').getWidth()+'px'});
      }
    }),
    new Effect.Appear('foot', {sync:true}),
    new Effect.Appear('title', {sync:true}),
    
    // Innovar 2010
    new Effect.Appear('innovarDiv', {sync:true})
    //-------------
    
  ], {queue:{position:'end', scope:'scale'}});
}


function setMenuLinks() {
  $$('#menu1 a, #menu2 a').each(function(menuLink) {
    menuLink.observe('click', function(event) {
      closeSection();
      openSection(menuLink.innerHTML, menuLink.href);
      event.stop();
    });
  });
}


function setLangLinks() {
  $$('#langMenu a').each(function(menuLink) {
    menuLink.observe('click', function(event) {
      selectedLang = menuLink.rel;
      new Ajax.Request(menuLink.href, {parameters:{lang:selectedLang}});

      //Cierra la seccion abierta
      closeSection();

      //Oculta el menu y el slogan
      new Effect.Parallel([
        new Effect.SlideUp('menu', {
          sync:true,
          afterFinish:function() {
          	//Actualiza el menu
            $('menu1').update(menu1Template.evaluate(menuLang[selectedLang]));
            $('menu2').update(menu2Template.evaluate(menuLang[selectedLang]));
            setMenuLinks();
          }
        }),
        new Effect.Fade('slogan', {
          sync:true,
          afterFinish:function() {
            //Actualiza el slogan
            $('slogan').update(sloganLang[selectedLang])
          ;}
        })
      ], {queue:{position:'end', scope:'lang'}});

      //Muestra el menu y el slogan
      new Effect.Parallel([
        new Effect.SlideDown('menu', {sync:true}),
        new Effect.Appear('slogan', {sync:true})
      ], {queue:{position:'end', scope:'lang'}});

      event.stop();
    });
  });
}


function openSection(title, link) {
  new Ajax.Request(link, {
    onSuccess: function(transport) {
      new Effect.Morph('title', {
        style:'width:135px;',
        beforeSetup:function() {$('titleContent').update(title)},
        queue:{position:'end', scope:'section'}
      });
      new Effect.BlindDown('content', {
        beforeSetup:function() {$('content').update(transport.responseText)},
        queue:{position:'end', scope:'section'}
      });
      openedSection = true;
    }
  });
}


function closeSection() {
  if (openedSection) {
    new Effect.BlindUp('content', {queue:{position:'end', scope:'section'}});
    new Effect.Morph('title', {
      style:'width:0px;',
      afterFinish:function() {$('titleContent').update()},
      queue:{position:'end', scope:'section'}
    });
    openedSection = false;
  }
}


document.observe('dom:loaded', function() {
  $('main').setStyle({height:document.viewport.getHeight()+'px'});
  window.onresize = function(event) {
    $('main').setStyle({height:document.viewport.getHeight()+'px'});
  };

  //Carga del idioma
  $('slogan').update(sloganLang[selectedLang]);
  $('menu1').update(menu1Template.evaluate(menuLang[selectedLang]));
  $('menu2').update(menu2Template.evaluate(menuLang[selectedLang]));

  //Pre-carga de imagenes
  var imgSrcs = [
    'images/back.gif',
    'images/indos.jpg',
    'images/logo.jpg',
    'images/title.gif',
    'images/alert.png',

    // Innovar 2010
    'images/innovar.jpg'
    //-------------

  ];
  var loadedImgs = 0;
  imgSrcs.each(function(imgSrc, i) {
    var img = new Image();
    img.onload = function() {
      if (++loadedImgs == imgSrcs.size()) {
        //Todas las imagenes pre-cargadas.
        //$('logoIntro').observe('mouseover', function(event) {event.element().setOpacity(0.8);});
        //$('logoIntro').observe('mouseout', function(event) {event.element().setOpacity(1.0);});
        if (getParameter('skipIntro') == 1) {
          window.onresize = null;
          showIntro();
        } else {
          $('logoIntro').observe('click', function(event) {
            window.onresize = null;
            showIntro();
            event.stop();
            //event.element().stopObserving('mouseover');
            //event.element().stopObserving('mouseout');
            event.element().stopObserving('click').setStyle({cursor:'default'});
          }).setStyle({cursor:'pointer'});
        }
      }
    };
    img.src = imgSrc;
  });
});

