// jordans.js - ajax helpers for the slideshow and contact form

//console.log("jordans.js");

dojo.require('dojo.NodeList-traverse');

// IE7 hack, only show footer once images have loaded to 
// prevent footer collapsing on partial image loads
dojo.connect(window, "onload", function(){
    dojo.query('.footer.region').removeClass('closed');
});

dojo.addOnLoad( function(){
    dojo.query('#contact-form #select_department').connect( 'onchange', null, departmentSelect );
    dojo.query('#contact-form li.location').addClass('hidden');

    // detail view popups
    dojo.query('#detail_1, #detail_2, #sp_detail_1, #sp_detail_2').connect('onclick', detailPopup);
    dojo.query('.detail_pic').connect('onclick', detailPopup);
    dojo.query('#detail_popup').forEach( function(popup){
        dojo.connect(popup, 'onclick', detailClose);
        dojo.fadeOut({node:popup, duration:1}).play();
        dojo.removeClass(popup, 'closed');
    });
   
    // promo item popups
    dojo.query('.promo_list img.sidebar_image_box').connect('onclick', promoPopup);
    dojo.query('#promo_popup').forEach( function(popup){
        dojo.connect(popup, 'onclick', promoClose);
        dojo.fadeOut({node:popup, duration:1}).play();
        dojo.removeClass(popup, 'closed');
    });

    // recent project popup
    dojo.query('ul.resource-recent_project li img').connect('onclick', projectPopup);
    dojo.query('#popup-recent_project').forEach( function(popup){
        dojo.connect(popup, 'onclick', projectClose);
        dojo.fadeOut({node:popup, duration:1}).play();
        dojo.removeClass(popup, 'closed');
    });

    dojo.query('#home_main_region #main_content_image').forEach( function(node){
        var buffer = dojo.query('#home_main_region #main_content_image_buffer')[0];
        //document.slideshow = new jordans.SlideShow(node, buffer); 
        window.slideshow = new jordans.SlideShow(node, buffer); 
    });

});

function locationSelect(evt){
    //console.log("selectChange() evt: ", evt);    
    dojo.query('#contact-form li.department').removeClass('hidden');
    // get the list of locations_departments_assocs
    var locationId = evt.target.value;
    dojo.xhrGet( {
        url: '/content/locations_departments_assoc/list_json?location_id=' + locationId,
        handleAs: 'json',
        timeout: 5000,
        load: function(response, ioArgs){
            var deptSelect = dojo.query('#contact-form #select_department')[0];
            // destroy all current options in the department pulldown
            dojo.query('option', deptSelect).forEach( dojo.destroy );
            dojo.forEach( response, function(assoc){
                dojo.create('option', {value: assoc.id, innerHTML:assoc._repr }, deptSelect); 
            });
        }
    });
}

// new version for selecting dept first
function departmentSelect(evt){
    //console.log("deparmentSelect()");
    //console.log("selectChange() evt: ", evt);    
    dojo.query('#contact-form li.location').removeClass('hidden');
    // get the list of locations_departments_assocs
    var deptId = evt.target.value;
    dojo.xhrGet( {
        url: '/content/locations_departments_assoc/list_json?department_id=' + deptId,
        handleAs: 'json',
        timeout: 5000,
        load: function(response, ioArgs){
            var locationSelect = dojo.query('#contact-form #select_location')[0];
            // destroy all current options in the department pulldown
            dojo.query('option', locationSelect).forEach( dojo.destroy );
            dojo.forEach( response, function(assoc){
                dojo.create('option', {value: assoc.id, innerHTML:assoc._repr }, locationSelect); 
            });
        }
    });
}

function detailPopup(evt){
    //console.log("detailPopup");
    var sourceDetailContainer = dojo.query(evt.target).parents('div')[0];
    var captionEl = dojo.query('.caption', sourceDetailContainer);
    var caption = captionEl ? captionEl[0].innerHTML : '';
    var imgSrc = dojo.attr(evt.target, 'src');
    var popup = dojo.query('#detail_popup')[0];
    var popupImg = dojo.query('#detail_popup img')[0];
    dojo.attr(popupImg, 'src', imgSrc);
    var popupCaption = dojo.query('.caption', popup)[0];
    popupCaption.innerHTML = caption;
    dojo.fadeIn({node:popup, duration:200}).play();
    dojo.removeClass(popup, 'closed');
    dojo.stopEvent(evt);
}

function detailClose(evt){
    //console.log("detailClose for evt: ", evt);
    var popup = dojo.query('#detail_popup')[0];
    dojo.fadeOut({node:popup, duration:200}).play();
    setTimeout( function(){ 
        dojo.addClass(popup, 'closed');
    }, 200);
    dojo.stopEvent(evt);
}

function promoPopup(evt){
    //console.log("promoPopup for evt: ", evt);
    var imgSrc = dojo.attr(evt.target, 'src');
    var popup = dojo.query('#promo_popup')[0];
    var popupImg = dojo.query('#promo_popup img')[0];
    //dojo.attr(popup, 'style', 'top: 150px; left: 200px');
    dojo.attr(popupImg, 'src', imgSrc);
    dojo.fadeIn({node:popup, duration:200}).play();
    dojo.removeClass(popup, 'closed');
    dojo.stopEvent(evt);
}
function promoClose(evt){
    //console.log("promoClose for evt: ", evt);
    var popup = dojo.query('#promo_popup')[0];
    dojo.fadeOut({node:popup, duration:200}).play();
    setTimeout( function(){ 
        dojo.addClass(popup, 'closed');
    }, 200);
    dojo.stopEvent(evt);
}

function projectPopup(evt){
    //console.log("projectPopup for evt: ", evt);
    var imgSrc = dojo.attr(evt.target, 'fullsize');
    var popup = dojo.query('#popup-recent_project')[0];
    var popupImg = dojo.query('#popup-recent_project img')[0];
    //dojo.attr(popup, 'style', 'top: 150px; left: 200px');
    dojo.attr(popupImg, 'src', imgSrc);
    dojo.fadeIn({node:popup, duration:200}).play();
    dojo.removeClass(popup, 'closed');
    dojo.stopEvent(evt);
}
function projectClose(evt){
    //console.log("promoClose for evt: ", evt);
    var popup = dojo.query('#popup-recent_project')[0];
    dojo.fadeOut({node:popup, duration:200}).play();
    setTimeout( function(){ 
        dojo.addClass(popup, 'closed');
    }, 200);
    dojo.stopEvent(evt);
}


dojo.declare('jordans.SlideShow', null, {

    // list of image sources to rotate through
    imageList: Array(),

    // url for gettin image list as json objects
    imageUrl: '/content/slide/list_json',
    
    // use to keep track of current image index
    imageIndex: 0,
    
    // interval for slide swap
    fadeInterval: 5000,
    fadeInTime: 2500,
    fadeOutTime: 2500,
    fadeDelay: 700,

    constructor: function(node, buffer){
        //console.log("initing slideshow on :", node, " buffer: ", buffer);
        this.imageMain = node;
        this.imageBuffer = buffer;
        // get list of slideshow source images and save in an array to iterate through
        this.getImageList(); 
        //console.log('image list: '+this.imageList);
    },

    getImageList: function(){
        //console.log("getImageList()");
        var self = this;
        dojo.xhrGet({
            url: this.imageUrl,
            timeout: 5000,
            handleAs: 'json',
            load: function(response, ioArgs){ 
                //console.log("response: "+response)
                dojo.forEach(response, function(slide){
                    self.imageList.push( slide._repr );
                });
                self.startSlideShow();
            }   
        });
    },

    startSlideShow: function(){
        //console.log("startSlideShow() this: ", this);
        var self = this;
        setInterval( function(){
            self.swapSlide(self);
        }, self.fadeInterval );    
    },

    swapSlide: function(self){
        //console.log("swapSlide()");
        // either increment index or loop to beginning
        self.imageIndex = ( self.imageIndex < self.imageList.length - 1  ? self.imageIndex + 1 : 0 );
        var newFile = self.imageList[self.imageIndex];
        //console.log("newFile: ", newFile);

        // fade out the buffer
        dojo.fadeOut( {'node':self.imageBuffer, 'duration':1} ).play();
        // set it's source to the new file
        dojo.attr(self.imageBuffer, 'src', '/files/' + newFile);
        // fade out the main image 
        dojo.fadeOut( {'node':self.imageMain, 'duration':self.fadeOutTime} ).play();
        // fade in new one after the delay
        setTimeout( function(){
            dojo.fadeIn( {'node':self.imageBuffer, 'duration':self.fadeInTime} ).play();
        }, self.fadeDelay );
        
        // swap the node referrences for the next call
        setTimeout( function(){
            var temp = self.imageBuffer;
            self.imageBuffer = self.imageMain
            self.imageMain = temp;
        }, self.fadeInterval / 2 );
    }

});

