var slide_timer     =     0;
var slide_delay     =  3000;        // starting value: 3 seconds
var slide_delta     =  1000;        // faster/slows changes by 1 seconds
var slide_delay_min =  1000;        // 1 second minimum delay
var slide_delay_max = 10000;        // 10 seconds maximum delay
var wall_models     = new Array('b', 'c', 'd');
var ceil_models     = new Array('a', 'b');
var wall_examples   = lookup_table( // R&V images that have wall examples
    '03 06 11 17 22 24 25 26 31 36 38 46 47 48 51 55 64 66 69 71 75 77 80 81 84 86 90 91 98'
);
var ceil_examples   = lookup_table( // same for ceiling examples
    '57 58 59'
);
var ceil4_examples   = lookup_table( // same for ceiling examples with 5 model
    '94 95 96'
);
var ceil5_examples   = lookup_table( // same for ceiling examples with 5 model
    '93 94 95 96'
);

// add .warm and .cold methods to jQuery

jQuery.fn.extend({
    // add 'warm' to class and remove from all siblings
    warm: function() {
        this.addClass('warm').siblings('.warm').removeClass('warm');
        return this;
    },
    // remove 'warm' class 
    cold: function() {
        this.removeClass('warm');
        return this;
    },
    bind_lightbox: function() {
        this.find('a[@rel="lightbox"]').click(function () {
            pause_slideshow();
            show_lightbox(this); 
            return false;
        });
    }
});


/* ------------------------------------------------------------------------ */
/* Slideshow                                                                */
/* ------------------------------------------------------------------------ */

function init_slideshow() {
    $('#rvslideshow ul.tabs li a').click( function() {
        $(this).parent('li').warm();
        var pane = this.getAttribute('rel');
        $('#' + pane).warm();
        $('#' + pane + '_info').warm();
        return false;
    });
    $('#rvslideshow ul.items li a').click( function() {
        $(this).parent('li').warm();
        var imgid = this.getAttribute('rel');
        $('#one_way   img').attr('src', '/images/rvimages/single/' + imgid + 'a.jpg');
        $('#two_way   img').attr('src', '/images/rvimages/single/' + imgid + 'b.jpg');
        $('#three_way img').attr('src', '/images/rvimages/single/' + imgid + 'c.jpg');
        $('#four_way  img').attr('src', '/images/rvimages/single/' + imgid + 'd.jpg');
        $('#rvslideshow div.pane a')
            .attr('href', '/images/rvimages/large/' + imgid + '.jpg')
            .attr('title', 'Relax &amp; View&reg; Image ' + imgid);
        // TODO: if this.class('wall_examples'), prop to a link
        return false;
    });
    $('#rvslideshow div.pane').each(function() { 
        $(this).bind_lightbox();   
    });

    start_slideshow();
}

function start_slideshow() {
    $('#rvslideshow').addClass('playing');
    $('#rvslideshow #status').text('Slideshow Running');
    slide_timer = window.setTimeout("next_tab()", slide_delay);
    return false;
}

function pause_slideshow() {
    $('#rvslideshow #status').text('Slideshow Paused');
    $('#rvslideshow').removeClass('playing');
    clearTimeout(slide_timer);
    return false;
}

function slideshow_faster() {
    if (slide_delay > slide_delay_min) {
        slide_delay = slide_delay - slide_delta;
    }
    return false;
}

function slideshow_slower() {
    if (slide_delay < slide_delay_max) {
        slide_delay = slide_delay + slide_delta;
    }
    return false;
}

function next_slide() {
    var items = $('#rvslideshow ul.items');
    var item  = items.find('li.warm')[0];
    do { item  = item.nextSibling }
    while (item && item.nodeType != 1);
    if (! item) {
        item = items.find('li:first')[0];
    }
    $(item).find('a').trigger('click');
}

function next_tab() {
    var tabs = $('#rvslideshow ul.tabs');
    var tab  = tabs.find('li.warm')[0];
    do { tab  = tab.nextSibling }
    while (tab && tab.nodeType != 1);
    if (! tab) {
        tab = tabs.find('li:first')[0];
        next_slide();
    }
    $(tab).find('a').trigger('click');
    slide_timer = window.setTimeout("next_tab()", slide_delay);
}


/* ------------------------------------------------------------------------ */
/* Gallery                                                                  */
/* ------------------------------------------------------------------------ */

function init_gallery() {
    var loaded = { };

    // initalise lightbox and bind onclick handlers to each image
    $('#thumbnails div.pane').each(function() { 
        $(this).bind_lightbox();
    });
    
    $('#gallery ul.tabs li a').click(function() {
        $(this).parent('li').addClass('warm').siblings('.warm').removeClass('warm');

        // the rel attribute tells us which pane to activate
        var rel  = this.getAttribute('rel');
        var pane = $(rel);
        pane.addClass('warm').siblings('.warm').removeClass('warm');
    
        if (! loaded[rel]) {
            // the href attribute (minus the _small, _medium or _large) suffix 
            // has the pane content suitable for loading via AJAX
            var href = this.getAttribute('href').replace(/_(small|medium|large)/, '');

            // alert('loading ' + rel + ' with ' + href);
            pane.load(href, undefined, function() { 
                // bind lightbox handlers to each new image loaded
                $(this).bind_lightbox();
            });
            loaded[rel] = href;
        }
        return false;
    });
}



/* ------------------------------------------------------------------------ */
/* Lightbox                                                                 */
/* ------------------------------------------------------------------------ */

function hide_lightbox() {
	$('#lightbox').hide();
	$('#overlay').hide();
	$('select').show();
	document.onkeypress = '';
}

function show_lightbox(link) {
    var adjust_up   = 20;
    var page_size   = compute_page_size();
    var page_scroll = compute_page_scroll();

	var overlay  = $('#overlay');
	var lightbox = $('#lightbox');
    var loading  = overlay.find('#loading');
	var image    = lightbox.find('#image');
	var wall_ex  = lightbox.find('#wall_examples');
	var ceil_ex  = lightbox.find('#ceiling_examples');
	var ceil5_ex = lightbox.find('#ceiling5_examples');

	// display overlay over whole page
	overlay.css({
	    height: page_size[1] + 'px'
	});
	overlay.show();
	
	// center loading image
	loading.css({
		top:  (page_scroll[1] + (page_size[3] - loading.height()) / 2) + 'px',
	    left: ((page_size[0] - loading.width()) / 2) + 'px'
	});
	loading.show();
	    
    // set title
	lightbox.find('#title').html(link.getAttribute('title'));

    var match = link.href.match(/(\d+)\.(jpg|png|gif)$/);
    if (! match) throw "Cannot determine image number from link";
    var imgno = match[1];
    
    if (wall_examples[imgno]) {
        show_examples(lightbox, 'wall', imgno, link, wall_models);
        ceil_ex.hide();
        ceil5_ex.hide();
        adjust_up += 80;   // move lightbox further up screen

        // update src attributes of example images to show wall panels
/*        wall_ex.find('span.image_id').html(imgno);
        var url = link.href.replace('large', 'single/small');
        var models = new Array('b', 'c', 'd');
        for (var i in models) {
            var m = models[i];
            wall_ex.find('#wall_example_' + m).attr('src', url.replace(/(\.jpg)$/, m + "$1"));
        }
        wall_ex.show();
        ceil_ex.hide();
        adjust_up += 80;   // move lightbox further up screen
*/
    }
    else if (ceil_examples[imgno]) {
        ceil_ex.find('span.image_id').html(imgno);
        var url = link.href.replace('large', 'single/small');
        var models = new Array('a', 'b');
        for (var i in models) {
            var m = models[i];
            ceil_ex.find('#ceiling_example_' + m).attr('src', url.replace(/(\.jpg)$/, m + "$1"));
        }
        wall_ex.hide();
        ceil_ex.show();
        ceil5_ex.hide();
        adjust_up += 80;   // move lightbox further up screen
    }
    else if (ceil5_examples[imgno]) {
        ceil5_ex.find('span.image_id').html(imgno);
        var url = link.href.replace('large', 'single/small');
        var models = new Array('a', 'b', 'c', 'd', 'e');
        for (var i in models) {
            var m = models[i];
            ceil5_ex.find('#ceiling5_example_' + m).attr('src', url.replace(/(\.jpg)$/, m + "$1"));
        }
        if (ceil4_examples[imgno]) {
            ceil5_ex.find('#ceil5_ex_e').hide();
        }
        else {
            ceil5_ex.find('#ceil5_ex_e').show();
        }
        wall_ex.hide();
        ceil_ex.hide();
        ceil5_ex.show();
        adjust_up += 80;   // move lightbox further up screen
    }
    else {
        wall_ex.hide();
        ceil_ex.hide();
        ceil5_ex.hide();
    }

	// preload image and define onload() handler to display it
	var preload = new Image();

	preload.onload = function() {
	    // set original image src to this image
	    image.attr('src', this.src);

        // What a surprise!  We have to hack around limitations in IE
		if ($.browser.msie) {
		    // pause between loading the image and displaying to prevent
		    // the previous image from displaying 
			pause(250);  // ugly hack
		    // hide select boxes that will display through the image 
	        $('select').hide();
		} 

		// center lightbox and make sure that the top and left values are not negative
		// and the image placed outside the viewport
		var box_top  = page_scroll[1] + ((page_size[3] - this.height) / 2) - adjust_up;
		var box_left = ((page_size[0] - this.width) / 2) - 20;
        box_top  = box_top  < 0 ? 0 : box_top; 
        box_left = box_left < 0 ? 0 : box_left;

/*        alert("Window: " + page_size[0] + 'x' + page_size[1] + "\n" +
              "Page: " + page_size[2] + 'x' + page_size[3] + "\n" +
              "Image: " + preload.width + 'x' + preload.height + "\n" +
              "Box: @" + box_left + ',' + box_top);
*/

        // make caption same width as image
        lightbox.find('.caption').css('width', this.width + 'px');
		
		// move lightbox to middle of screen and display
		lightbox.css({
		    top:  box_top  + "px",
		    left: box_left + "px"
	    });
	    lightbox.show();
	
		// After image is loaded, update the overlay height as the new image might have
		// increased the overall page height.
		page_size = compute_page_size();
	    overlay.css({
	        height: page_size[1] + 'px'
	    });

        // hide loading image
        loading.hide();

		// Check for 'x' keypress
        document.onkeypress = key_listener('x', hide_lightbox);

		return false;
	}

	preload.src = link.href;
}

function show_examples(lightbox, type, imgno, link, models) {
    // fetch examples div for this type
    var examples = lightbox.find('#' + type + '_examples');    // e.g. #wall_examples
    
    // insert image number into example captions
    examples.find('span.image_id').html(imgno);
    
    // update src attributes of example images to show wall panels
    var url = link.href.replace('large', 'single/small');
    for (var i in models) {
        var m = models[i];
        examples.find('#' + type + '_example_' + m).attr('src', url.replace(/(\.jpg)$/, m + "$1"));
    }
    examples.show();
}


/* ------------------------------------------------------------------------ */
/* Utility functions                                                        */
/* ------------------------------------------------------------------------ */

// Convert text strings of numbers into hashes mapping each example number
// to 1, for quick testing to see if an image has wall or ceiling examples.
// There's probably a more succint JS idiom to do this, but I don't know 
// what it is.  

function lookup_table(text) {
    var numbers = text.split(/\s+/); 
    var hash = { };
    for (var k in numbers) {
        hash[numbers[k]] = 1;
    }
    return hash;
}


// based on code from Quirksmode.org via Lightbox JS

function compute_page_scroll() {
	var yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}
	return new Array('', yScroll);
}


// based on code from Quirksmode.org via Lightbox JS
// Edit for Firefox by pHaez

function compute_page_size() {
	var xScroll, yScroll;
	var windowWidth, windowHeight;
	var pageWidth, pageHeight;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	return new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
}


// generate a simple keypress event handler function that watches for
// a key (k) to be pressed and then calls a delegate function (f)

function key_listener(k, f) {
    return function(e) {
	    if (e == null) { // ie
		    keycode = event.keyCode;
	    } 
	    else { // mozilla
		    keycode = e.which;
	    }
	    key = String.fromCharCode(keycode).toLowerCase();
	    if (key == 'x') { 
	        f(); 
	    }
	};
}


//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//

function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

