
// array of carousel models_items
var models_items = new Array();

// browser flag
var is_ie6OrLower = false;

// button flags
var models_next_enabled;
var models_prev_enabled;
var safari_inited = false;

// sliding labels init flag
var models_sliding_labels_init = false;

// query string request flag
var model_query_string_request = false;

/**
 * This is the callback function which receives notification
 * right after initialisation of the carousel
 */
function model_carousel_initCallback(carousel, state) {
	
	/*if (state == 'init')
        display('Carousel initialised');
    else if (state == 'reset')
        display('Carousel reseted');*/
	
	// set the browser var	
	if (jQuery.browser.msie && parseInt(jQuery.browser.version) <= 6) is_ie6OrLower = true;
		
	// init items array
	var carousel_items = $('#model_carousel').children();
	for (var i = 0; i < carousel_items.length; i++) {
		var id = $('#model_carousel a').eq(i).attr('id');		
		var item = new CarouselItem(id, i, false, false);
		models_items.push(item);
	}
	
	// add controls dynamically
	$('.jcarousel-skin-models').after('<div id="models_control_list"><ul class="jcarousel-models-control"></ul></div>');
	for (var i = 0, j = 1; i < carousel_items.length; i++, j++) {
		$('.jcarousel-models-control').append('<li><a href="#" class="replaced">' + j + '</a></li>');
	}
	
	// add callbacks to the main buttons
	jQuery('.jcarousel-skin-models a').bind('click', function() {
														  
		// get the id
		var string_id = jQuery(this).attr('id');
		string_id = string_id.slice(6);
		var id = jQuery.jcarousel.intval(string_id);
														  
		// get the index
		var index =jQuery('.jcarousel-skin-models a').index(this);
		
		// set selected
		setModelSelected(index);
		
		// set backgrounds
		setModelBackgrounds();			
		
		// hide outlines on click
		this.blur();
		
		// set the content
		setModelContent(id);
		
		return false;
		
	});	
	
	// add callbacks to the mini control
	jQuery('.jcarousel-models-control a').bind('click', function() {
														  
		// get the id
		var index = $('.jcarousel-models-control a').index(this);
		
		// set selected
		setModelSelected(index);		
		
		// set backgrounds
		setModelBackgrounds();			
		
		// hide outlines on click
		this.blur();
		
		// scroll to clicked position
		carousel.scroll(index);
														  
		// get the id
		var string_id = models_items[index].id;
		string_id = string_id.slice(6);
		var id = jQuery.jcarousel.intval(string_id);
		
		// set the content
		setModelContent(id);
		
		return false;
		
	});
		
	// add titles to the mini control
	jQuery('.jcarousel-models-control a').attr('title', function() {	
		
		return $('.jcarousel-skin-models').find('a').eq($('.jcarousel-models-control a').index(this)).text()
		
	});
		
	// do rollovers here	
	$('#model_carousel a').hover(
      function () {
		$(this).parent().css('background-image', 'url(images/bg-model-on.gif)');
        $(this).css('background-position', 'left bottom');
      }, 
      function () {
        models_items[$('#model_carousel a').index(this)].selected ? $(this).parent().css('background-image', 'url(images/bg-model-on.gif)') : $(this).parent().css('background-image', 'url(images/bg-model-off.gif)');
        models_items[$('#model_carousel a').index(this)].selected ? $(this).css('background-position', 'left bottom') : $(this).css('background-position', 'left top');
      }
    );
	
	// show sliding labels
	showModelSlidingLabels(1);
	
};

function hideModelSlidingLabels() {
	
	$('.carousel_labels').css( { visibility: 'hidden' } );	
	
}


function showModelSlidingLabels(first) {
	
	$('.carousel_labels').css( { visibility: 'visible' } );	
	
	var item_width = 104;
	var offset = item_width * (first-1);
	var new_left = 70 - offset;
	
	var carousel_children = $('.jcarousel-skin-models ul').children();	
	
	// centre if necessary
	if (carousel_children.length < 8) {
		
		new_left = 485;		
		for (var i = 0; i < carousel_children.length; i++) {
			new_left -= item_width/2;
		}	
		
	}
	
	$('.carousel_labels').css( { left: new_left } );
	$('.carousel_labels').css( { clip: 'rect(0px ' + (820 + offset) + 'px 10px ' + offset + 'px)' } );
	
	// animate in
	if (!is_ie6OrLower) $('.carousel_labels').hide().fadeIn("fast");
	
}


// support functions
function setModelSelected(id) {
	
	for (var i = 0; i < models_items.length; i++) {
		models_items[i].selected = false;	
	}
	
	models_items[id].selected = true;	
	
}

function setModelStyle(id, expression, style, value) {	

	$(id).find(expression).css(style, value);
	
}


function setModelBackgrounds() {
										
		// set the control list backgrounds		
		$('#models_control_list a').css('background-image', 'url(images/a-item-hidden.gif)')
							.filter(function () {	
                 				return models_items[$('#models_control_list a').index(this)].visible;
        					})
            				.css('background-image', 'url(images/a-item-visible.gif)')
							.filter(function () {		  	
                 				return models_items[$('#models_control_list a').index(this)].selected;
        					})
            				.css('background-image', 'url(images/a-item-on.gif)');
							
		
							
		// set the item backgrounds
		$('#model_carousel a').css('background-position', 'left top')
							.filter(function () {								
                 				return models_items[$('#model_carousel a').index(this)].selected;
        					})
            				.css('background-position', 'left bottom');								
					
		// set the item parent backgrounds			
		$('#model_carousel a').parent().css('background-image', 'url(images/bg-model-off.gif)');
		$('#model_carousel a').filter(function () {								
                 				return models_items[$('#model_carousel a').index(this)].selected;
        					})
            				.parent().css('background-image', 'url(images/bg-model-on.gif)');				
	
}

function setModelContent(id) {
	
	// set content
	$('#model_container').html($('#model_content_holder_' + (id)).html()).find('.keyword').tooltip({
		track: true,
		delay: 500
	});
	
	// animate in
	if (!is_ie6OrLower) $('#model_container').hide().fadeIn("slow");
	
}


/**
 * This is the callback function which receives notification
 * about the state of the next button.
 */
function model_carousel_buttonNextCallback(carousel, button, enabled) {
    //display('Next button is now ' + (enabled ? 'enabled' : 'disabled'));
	models_next_enabled = enabled;	
		
	// safari bug catching
	if (!jQuery.browser.safari) return;
	
	// set flag first time if safari - always false;
	if (!safari_inited) {
		safari_inited = true;
		return;
	}
	
	// centre
	centreModelCarousel();	
	
	// set deep link
	setModelDeepLink(carousel);
	
	
};

/**
 * This is the callback function which receives notification
 * about the state of the prev button.
 */
function model_carousel_buttonPrevCallback(carousel, button, enabled) {
    //display('Prev button is now ' + (enabled ? 'enabled' : 'disabled'));
	models_prev_enabled = enabled;
	
	// show the carousel
	$('#model_carousel_holder').css( { visibility: 'visible' } );	
	
	initModelSlidingLabels();	
		
	// safari bug catching
	if (jQuery.browser.safari) return;
	
	// centre
	centreModelCarousel();
	
	// set deep link
	setModelDeepLink(carousel);	
																			   
};


function centreModelCarousel() {
	
	var item_width = 104;
	
	// remove buttons if both disabled
	if (!models_next_enabled && !models_prev_enabled) {
		
		var width = 0;		
		var carousel_children = $('.jcarousel-skin-models ul').children();
		for (var i = 0; i < carousel_children.length; i++) {
			width += item_width;
		}	
		
		// centre the carousel
		$('.jcarousel-skin-models .jcarousel-next-horizontal').css( { visibility: 'hidden' } );
		$('.jcarousel-skin-models .jcarousel-prev-horizontal').css( { visibility: 'hidden' } );	
		$('.jcarousel-skin-models .jcarousel-clip-horizontal').css( { width: width } );	
		$('.jcarousel-skin-models .jcarousel-container-horizontal').css( { width: width } );
		
	}
	
}

function setModelDeepLink(carousel) {
	
	if (model_query_string_request) return;
	
	// set visibilty	
	for (var i = carousel.first-1; i < carousel.last; i++) {				
		models_items[i].visible = true;
		var item = $('#models_control_list').find('a').eq(i);
		$(item).css( { backgroundImage: models_items[i].selected ? 'url(images/a-item-on.gif)' : 'url(images/a-item-visible.gif)' } );
	}
	
	// set scroll if in query string
	var model_no = $.jqURL.get('model');
	if (!isNaN(model_no)) {	
	
		// get the item object
		var requested_item;
		for (var i = 0; i < models_items.length; i++) {	
			var item = models_items[i];
			if (item.id == 'model_' + model_no) {
				requested_item = item;
				break;
			}
		}
		
		if (!requested_item) return;
		
		// set selected
		setModelSelected(item.index);	
		
		// scroll to clicked position
		carousel.scroll(item.index);		
		
		// set backgrounds
		setModelBackgrounds();		
		
		// set the content
		setModelContent(item.model_no);
		
	}	
	
	else {
		
		// set selected
		setModelSelected(0);	
		
		// scroll to clicked position
		carousel.scroll(0);		
		
		// set backgrounds
		setModelBackgrounds();	
		
		// get the id
		var string_id = models_items[0].id.slice(6);
		var id = jQuery.jcarousel.intval(string_id);
		
		// set the content
		setModelContent(id);
		
	}
		
	
	model_query_string_request = true;

}

function initModelSlidingLabels() {
	
	if (models_sliding_labels_init) return;
	
	$('.carousel_labels').css( { visibility: 'visible' } );
	
	var item_width = 104;
	
	// set sliding labels width
	for (var i = 1; i <= 3; i++) {
		setModelFamilyLabelWidth(i, item_width);
	}
	
	models_sliding_labels_init = true;
	
}


function setModelFamilyLabelWidth(id, item_width) {
	
	var carousel_family_labels = $('#model_carousel li').filter(function () {
										return $(this).attr('familyindex') == id;
									});
	
	$('.carousel_labels #family_' + id + ' .left').css( { width: (item_width * carousel_family_labels.length) - 11 } );	
	$('.carousel_labels #family_' + id + ' .right').css( { width: (item_width * carousel_family_labels.length) - 11 } );	
	
}

/**
 * This is the callback function which receives notification
 * right after reloading of the carousel
 */
function model_carousel_reloadCallback(carousel) {
   // display('Carousel reloaded');
};

/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 */
function model_carousel_itemFirstInCallback(carousel, item, idx, state) {
   // display('Item #' + idx + ' is now the first item');
};

/**
 * This is the callback function which receives notification
 * when an item is no longer the first one in the visible range.
 */
function model_carousel_itemFirstOutCallback(carousel, item, idx, state) {
    //display('Item #' + idx + ' is no longer the first item');
};

/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 */
function model_carousel_itemLastInCallback(carousel, item, idx, state) {
    //display('Item #' + idx + ' is now the last item');
};

/**
 * This is the callback function which receives notification
 * when an item is no longer the first one in the visible range.
 */
function model_carousel_itemLastOutCallback(carousel, item, idx, state) {
    //display('Item #' + idx + ' is no longer the last item');
};

/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 * Triggered before animation.
 */
function model_carousel_itemVisibleInCallbackBeforeAnimation(carousel, item, idx, state) {
    // No animation on first load of the carousel
    if (state == 'init')
        return;
		
	// hide sliding labels
	hideModelSlidingLabels();

    //jQuery('img', item).fadeIn('slow');
};

/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 * Triggered after animation.
 */
function model_carousel_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {
   // display('Item #' + idx + ' is now visible');
	
	models_items[idx-1].visible = true;
	var item = $('#models_control_list').find('a').eq(idx-1);
	$(item).css( { backgroundImage: models_items[idx-1].selected ? 'url(images/a-item-on.gif)' : 'url(images/a-item-visible.gif)' } );
	
	// show sliding labels
	showModelSlidingLabels(carousel.first);	
	
};

/**
 * This is the callback function which receives notification
 * when an item is no longer the first one in the visible range.
 * Triggered before animation.
 */
function model_carousel_itemVisibleOutCallbackBeforeAnimation(carousel, item, idx, state) {
   // jQuery('img', item).fadeOut('slow');
		
	// hide sliding labels
	hideModelSlidingLabels();

};

/**
 * This is the callback function which receives notification
 * when an item is no longer the first one in the visible range.
 * Triggered after animation.
 */
function model_carousel_itemVisibleOutCallbackAfterAnimation(carousel, item, idx, state) {
    //display('Item #' + idx + ' is no longer visible');
		
	models_items[idx-1].visible = false;
	var item = $('#models_control_list').find('a').eq(idx-1);	
	$(item).css( { backgroundImage: models_items[idx-1].selected ? 'url(images/a-item-on.gif)' : 'url(images/a-item-hidden.gif)' } );
	
	// show sliding labels
	showModelSlidingLabels(carousel.first);
	
	
};

/**
 * Helper function for printing out debug messages.
 * Not needed for jCarousel.
 */
var row = 1;
function display(s) {
    // Log to Firebug (getfirebug.com) if available
    //if (window.console != undefined && typeof window.console.log == 'function')
      //  console.log(s);

    if (row >= 1000)
        var r = row;
    else if (row >= 100)
        var r = '&nbsp;' + row;
    else if (row >= 10)
        var r = '&nbsp;&nbsp;' + row;
    else
        var r = '&nbsp;&nbsp;&nbsp;' + row;

    jQuery('#display').html(jQuery('#display').html() + r + ': ' + s + '<br />').get(0).scrollTop += 10000;

    row++;
};

jQuery(document).ready(function() {
	
	// hide the carousel
	$('#model_carousel_holder').css( { display: 'block' } );	
	$('#model_carousel_holder').css( { visibility: 'hidden' } );	
	
    jQuery('#model_carousel').jcarousel({
		
		scroll: 1,

        initCallback:   model_carousel_initCallback,
        reloadCallback: model_carousel_reloadCallback,

        buttonNextCallback:   model_carousel_buttonNextCallback,
        buttonPrevCallback:   model_carousel_buttonPrevCallback,

        itemFirstInCallback:  model_carousel_itemFirstInCallback,
        itemFirstOutCallback: model_carousel_itemFirstOutCallback,
        itemLastInCallback:   model_carousel_itemLastInCallback,
        itemLastOutCallback:  model_carousel_itemLastOutCallback,
        itemVisibleInCallback: {
            onBeforeAnimation: model_carousel_itemVisibleInCallbackBeforeAnimation,
            onAfterAnimation:  model_carousel_itemVisibleInCallbackAfterAnimation
        },
        itemVisibleOutCallback: {
            onBeforeAnimation: model_carousel_itemVisibleOutCallbackBeforeAnimation,
            onAfterAnimation:  model_carousel_itemVisibleOutCallbackAfterAnimation
        }
		
    });
});

