dojo.require("dojo.parser");
dojo.require("dojo.hash");
// dojo.require("dojo.window");
dojo.require("dojox.image.Gallery");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.fx");
dojo.require("dojo.NodeList-fx");
dojo.require("dojox.av.FLVideo");
dojo.require("dojox.av.widget.Player");
dojo.require("dojox.av.widget.PlayButton");
dojo.require("dojox.av.widget.VolumeButton");
dojo.require("dojox.av.widget.ProgressSlider");
dojo.require("dojox.av.widget.Status");

var SECTION_PREFIX = "section_";
var SEC_LINK_PREFIX = "link_";

//// utilities

// given section name ('home', 'gallery', etc), return its DOM id
// separate in order to avoid browser jumping to elements on the page when we set the has value
var idFromSection = function(sec){
    return SECTION_PREFIX+sec;
};
// similar to idFromSection, but for link ids ('link_gallery', etc)
var linkidFromSection = function(sec){
    return SEC_LINK_PREFIX+sec;
};

// given section node DOM id ('section_home', 'section_gallery', etc), return its official section name
var sectionFromId = function(id){
    return id.substring(SECTION_PREFIX.length);
};
// similar to sectionFromId, but for link ids ('link_gallery', etc)
var linkFromId = function(id){
    return id.substring(SEC_LINK_PREFIX.length);
};

//// event hook(s)

// event method for noting that we've changed section 'c' to 'current'
// connected methods can check the globally available 'section'
var section;
var sectionChange = function(c){
    section = c;
};

//// specific page component implementations

/// sections

// change main page contents to a specific section
var changeSection = function(tosection){
    var newlink = dojo.byId(linkidFromSection(tosection));
    
    // noop if already here
    if (dojo.hasClass(newlink, "current")) {
        return;
    }

    // turn off current link highlight
    dojo.query("a.navlink.current").forEach(function(node, index, arr){
        dojo.removeClass(node, "current");
    });
    // turn on selected link highlight
    dojo.addClass(newlink, "current");

    // set up animation chain
    var animchain = [];
    // hide current text
    dojo.query(".contenttext.current").forEach(function(node, index, arr){
        animchain.push(dojo.fadeOut({
            node: node,
            duration: 300,
            beforeBegin: function(){
              dojo.removeClass(node, "current");
            },
            onEnd: function(){
              dojo.addClass(node, "hidden");
            }
        }));
    });
    // show text refd by link
    var node = dojo.byId(idFromSection(tosection));
    animchain.push(dojo.fadeIn({
        node: node,
        duration: 500,
        beforeBegin: function(){
          dojo.addClass(node, "current");
          dojo.removeClass(node, "hidden");
        },
        onEnd: function(){
          sectionChange(tosection);
          dojo.hash(tosection);
        }
    }));
    // run animation
    dojo.fx.chain(animchain).play();
};
// handle click on a section link to change the contents of the page cutely
var navClick = function(evt){
    evt.preventDefault();
    changeSection(linkFromId(evt.target.id));  // chop off "link_" prefix, using rest of id as section
};

/// slogan on "home" section
// event hook on section change
var sloganHandle = function(evt){
    var lowerpart = dojo.byId("lowerpart");
    var slogan = dojo.byId("mmm-banner");
    if (section=="home") {
      dojo.addClass(lowerpart, "withimage");
      dojo.removeClass(slogan, "hidden");
    } else {
      dojo.removeClass(lowerpart, "withimage");
      dojo.addClass(slogan, "hidden");
    }
};

/// gallery
var galleryloaded = false;  // which gallery is current

// change the current selected gallery to a specified one
var setGallery = function(gallerypath){
    var newgal = dojo.byId("gal-cat-"+gallerypath);
    if (dojo.hasClass(newgal, "current")) {
      return;  // short-circuit if we're already there
    }

    var gallery = dijit.byId('gallerydijit');
    var itemNameMap = {imageThumbAttr: "thumb", imageLargeAttr: "large"};
    var request = {query: {}, count: 20};
    var imageItemStore = new dojo.data.ItemFileReadStore({url:"resources/gallery/"+ gallerypath +"/images.json"});
    gallery.setDataStore(imageItemStore, request, itemNameMap);

    // turn off current gallery highlight
    dojo.query(".gallerycategory").forEach(function(node, index, arr){
        dojo.removeClass(node, "current");
    });
    // turn on selected gallery highlight
    dojo.addClass(newgal, "current");

    galleryloaded = gallerypath;
};
// handle click on a gallery link to call setGallery
var handleGalleryClick = function(evt){
    var gallery;
    if (dojo.hasClass(evt.target, "retail")) {
        gallery = "retail";
    } else if (dojo.hasClass(evt.target, "fleet")) {
        gallery = "fleet";
    } else if (dojo.hasClass(evt.target, "archi")) {
        gallery = "archi";
    }
    setGallery(gallery);
};
// event hook: load gallery only when we change into its section
var loadGallery = function(){
    if (section=="gallery") {
        if (!galleryloaded) {
            // instantiate
            new dojox.image.Gallery({ imageHeight:"600", imageWidth:"800" }, "gallerydijit");
        }
        var whichgallery = "retail";  // default
        var querygallery = dojo.queryToObject(window.location.search.substring(1)).gallery;  // looking for ?gallery=archi
        if (querygallery) { whichgallery = querygallery; }
        
        if (galleryloaded != whichgallery) {
            setGallery(whichgallery);
        } 
    }
};


/// case studies

// handle selection of a particular case study. if not open, open it. if open, close it.
var useCaseStudy = function(/* Node */casestudy){
    console.log(casestudy.id);
    if (dojo.hasClass(casestudy, "animating")) {
        console.log("multi-click short-circuit");
        return;
    }
    
    var selectedbody = dojo.query("#"+casestudy.id+" .body").pop();
    if (dojo.hasClass(selectedbody, "hidden")) {
        // click on closed case study; open this one
        var wipeInArgs = {
                    node: selectedbody,
                    duration: 400,
                    beforeBegin: function(n) {
                        dojo.addClass(casestudy, "animating");
                        dojo.removeClass(selectedbody, "hidden");
                    },
                    onEnd: function(n) {
                        dojo.removeClass(casestudy, "animating");
                    }
                };
        dojo.fx.wipeIn(wipeInArgs).play();

    } else {
        // click on expanded case study; close this one
        var wipeOutArgs = {
                    node: selectedbody,
                    duration: 400,
                    beforeBegin: function() {
                        dojo.addClass(casestudy, "animating");
                    },
                    onEnd: function() {
                        dojo.addClass(selectedbody, "hidden");
                        dojo.removeClass(casestudy, "animating");
                    }
                };
        dojo.fx.wipeOut(wipeOutArgs).play();
    }
    
};
// handle click on tab of a particular case study
var clickCaseStudy = function(/* Dojo Event */evt){
    var checknode = evt.target;
    var casestudy;
    while (checknode.parentNode && !casestudy) {
        if (checknode.className == "casestudy") { casestudy = checknode; }
        checknode = checknode.parentNode;
    }
    if (casestudy) { useCaseStudy(casestudy); }
};

/// video
// event hook: load gallery only when we change into its section
var videoloaded = false;
var loadVideo = function(){
    if (section=="video" && !videoloaded) {
//       var myVideo = new dojox.av.FLVideo({initialVolume:.1, mediaUrl:"resources/video/Foxmark.flv", autoPlay:false, isDebug:false}, "vidnode")
      videoloaded = true;
    }
};


//// initialization

// on page load, set initial state. At bottom to technically define all methods before use.
dojo.addOnLoad(function() {
  // wire up section-specific hooks
  dojo.connect("sectionChange", "loadGallery");
  dojo.connect("sectionChange", "sloganHandle");
  dojo.connect("sectionChange", "loadVideo");

  // set current section (has 'current' class) to either default (home) or hash value if we have one
  var sec = dojo.hash();
  if (sec.substring(0, SECTION_PREFIX.length)==SECTION_PREFIX) {  // click before load will set id as hash, so watch that
      sec = sectionFromId(sec);
      dojo.hash(sec, true);
      // TODO: scroll up; CDN doesn't like dojo.window
//       dojo.window.scrollIntoView(dojo.body());
      window.scroll(0,0);

  }
  var contenttext = dojo.byId(idFromSection(sec));
  if (!contenttext) {
      sec = "home";
      dojo.hash(sec, true);
      contenttext = dojo.byId(idFromSection(sec));
  }
  var seclink = dojo.byId(linkidFromSection(sec));
  if (contenttext) { dojo.addClass(contenttext, "current"); }   // current contenttext
  if (seclink) { dojo.addClass(seclink, "current"); }           // and link to it
  sectionChange(sec);   // notify change

  // set up hash change handler to deal with browser fwd/back
  dojo.subscribe("/dojo/hashchange", null, changeSection);

  // make section links do dynamic change
  dojo.query("a.navlink").forEach(function(node, index, arr){
      dojo.connect(node, "click", navClick);
  });
  // hide all non-current .contenttext sections
  dojo.query(".contenttext").forEach(function(node, index, arr){
      if (!dojo.hasClass(node, "current")) {
          dojo.addClass(node, "hidden");                    // remove from flow
          dojo.fadeOut({node: node, duration: 1}).play();   // hide visually, allow fadeIn
      }
  });

  // gallery hook-ups
  dojo.query(".gallerycategory .clickable").connect("click", "handleGalleryClick");
//   Nifty(".gallerycategory .background", "big");

  // case study hooks
  dojo.query(".casestudy .clickable").connect("click", "clickCaseStudy");

  // pre-collapse all case studies
  dojo.query(".casestudy .body").addClass("hidden").wipeOut({duration: 1}).play();   // hide visually, allow wipeIn
});

