/**
 * @TODO: 
 * - documentation
 * - remove global vars: $element 120, $foldout 94, elementData 167
 */
/**
 * @jslint: 2008-10-31
 */
audi_ngw.namespace(audi_ngw, 'gallery');

// width of the thumbnails for the gallery
audi_ngw.gallery.imageWidth = 93;
audi_ngw.gallery.separator = ' | ';



// update the status-field for the active gallery
audi_ngw.gallery.update = function(){
	var itemsCount = jQuery('.audi_gallery_active .audi_gallery_items a').size();
	var thisItemsPosition = itemsCount - jQuery('.audi_gallery_active .audi_gallery_items a.active').parent().nextAll().size();
		
	jQuery('.audi_gallery_active .audi_gallery_slider_status').text(thisItemsPosition + audi_ngw.gallery.separator + itemsCount);
};


// update the fullscreen button for the gallery
audi_ngw.gallery.fullscreen = function(){

	var $fullscreen = jQuery('#audi_gallery_fullscreen');
	if (0 === $fullscreen.size()) {
		return;
	}
	
	
	var attribute = {};
	attribute.width = $fullscreen.width();
	attribute.height = $fullscreen.height();
	attribute.version = audi_ngw.flash.sNeededFlashVersion;

	
	// create the list of images for the fullscreen-mode
	if( 'undefined' == typeof(audi_ngw.gallery.images) ) {
		audi_ngw.gallery.images = '';
		jQuery('.audi_gallery_active .audi_gallery_items a').each(function(){
			audi_ngw.gallery.images = audi_ngw.gallery.images + jQuery(this).metadata().fullscreen + ',';
		});
	}

	var tmp = []; 
	tmp.search = jQuery('.audi_gallery_active .audi_gallery_items a.active').metadata().fullscreen;
	tmp.pos = audi_ngw.gallery.images.indexOf(tmp.search);

	tmp.newEnd = audi_ngw.gallery.images.substr(0, tmp.pos);
	tmp.newBegin = audi_ngw.gallery.images.substr(tmp.pos);
	
	audi_ngw.gallery.images = tmp.newBegin + tmp.newEnd;

	
	var data = $fullscreen.metadata();
	data.images = audi_ngw.gallery.images;
	data.xmldata = jQuery('#audi_gallery_fullscreen').metadata().xmldata;

	var params = {};
	params.allowScriptAccess = 'always';
	params.allowFullScreen = 'true';
	params.scale = 'noscale';
	params.menu = 'false';
	data.parent_id = 'audi_gallery_fullscreen';
	
	swfobject.embedSWF(jQuery('#audi_gallery_fullscreen').metadata().swf, data.parent_id, attribute.width, attribute.height, attribute.version, "expressInstall.swf", data, params);
	
	if( jQuery('#audi_modal_overlay').css('display') !== 'block' ) {
		jQuery('#audi_gallery_fullscreen').show();
	} else {
		jQuery('#audi_gallery_fullscreen').hide();
	}
};


// change the active gallery (for foldout)
audi_ngw.gallery.changeActive = function($element){

	// the given element needs to be a gallery
	if( true !== $element.hasClass('audi_gallery') ) {
		return false;
	}
	
	// we need to delete the fullscreen-images-list
	if( 'undefined' !== typeof(audi_ngw.gallery.images) ) {
		delete(audi_ngw.gallery.images);
	}
		
	// remove the class from the current active gallery
	jQuery('.audi_gallery_active').removeClass('audi_gallery_active');
	
	// set the class for the given element
	$element.addClass('audi_gallery_active');
	
	$foldout = $element.parent().find('> a');
	if( false === $foldout.hasClass('open') ) {
		$foldout.click();
	}
	// if there is not exactly one active link, set the first link to active
	var $activeElement = $element.find('a.active');
	if( 1 !== $activeElement.size() ) {
		$activeElement.removeClass('active');
		$element.find('a:first').addClass('active');
		$activeElement = $element.find('a.active');
	}


	// trigger a click on the active element
	$activeElement.click();
	
	// update the status field
	audi_ngw.gallery.update();
	
	
	// set the hover-effect for the thumbnails for ie6
	jQuery('.audi_gallery_active .audi_gallery_items a').hover(
		function(){
			jQuery(this).addClass('hover');
		},
		function(){
			jQuery(this).removeClass('hover');
		}
	);
	
};


// handles the click on a thumbnail and passes them to the specialized functions
audi_ngw.gallery.click = function(){

	$element = jQuery(this);

	// remove the class "active" from the currect active thumbnail
	$element.parents('.audi_gallery_active').find('.active').removeClass('active');
	
	// add the class "active" to the clicked thumbnail
	$element.addClass('active');
	
	audi_ngw.gallery.update();
	
	var galleryType = jQuery('.audi_gallery_active').metadata().type;

	if( 'image' === galleryType ) {
		audi_ngw.gallery.clickImage($element);
	} else if( 'video' === galleryType ) {
		audi_ngw.gallery.clickVideo($element, 'audi_gallery_video');
	} else if( 'guided_tour' === galleryType ) {
		audi_ngw.gallery.clickVideo($element, 'audi_gallery_guided_tour');
	} else if( 'ringtone' === galleryType ) {
		audi_ngw.gallery.clickRingtone($element);
	} else if( 'mobileVideo' === galleryType ) {
		audi_ngw.gallery.clickVideo($element, 'audi_gallery_mobilevideo');
	} else if( 'mobileImage' === galleryType ) {
		audi_ngw.gallery.clickMobileImage($element);
	}
		
	return false;
};


// handles click on a thumbnail in an image-gallery
audi_ngw.gallery.clickImage = function($element){

	jQuery('#audi_gallery_fullscreen, #audi_gallery_video').hide();
	jQuery('#audi_gallery_image, .audi_gallery_toolbox').show().removeClass('audi_hide');
	

	elementData = $element.metadata();

	// get the jQuery-objects for the big image and the div
	var $imageDiv = jQuery('#audi_gallery_image');
	var $image = $imageDiv.find('img');

	// get the src for the clicked image (link)		
	var newImageSrc = elementData.big;

	// get the src for the old image		
	var oldImageSrc = $image.attr('src');
	
	// set the image to opacity=1
	//$image.css('opacity', '1');

	// set the new image as bg for the imageDiv
	$imageDiv.css('background-image', 'url(' + newImageSrc + ')');

	// animate the image to opacity=0 and set the src of the image to the new image
	$image.animate({'opacity': '0'}, 500, 'linear', function(){
		$image.attr('src', newImageSrc);	
		audi_ngw.gallery.fullscreen();
	});

	// find all the elements we need for the toolbox
	var $toolbox = jQuery('#audi_gallery_image').parent().find('.audi_gallery_toolbox .toolbox');
	var $wallpaper = $toolbox.find('.wallpaper');
	var $wallpaperUl = $wallpaper.find('ul').empty();

	// update the wallpaper-links
	$wallpaper.find('.open .close').click();
		
	$toolbox.find('li').css('visibility', 'hidden');

	// update the wallpaper-element
	if( 'undefined' !== typeof(elementData.wallpaper) ) {

		for (var i = 0; elementData.wallpaper[i]; i++) {

			$wallpaperUl.append('<li><a href="' + elementData.wallpaper[i].href + '" rel="wallpaper" target="_blank">' + elementData.wallpaper[i].title + '</a></li>');

		}

		$wallpaperUl.find('li:first').addClass('firstChild');
		$wallpaper.css('visibility', 'visible');
		audi_ngw.layer.statics.register(
			{	
				sIdContainer:			'#func_toolbox_wallpaper',
				sClassElement:			'.overlay',
				sClassClose:			'.close'

			}
		);

	} else {

		$wallpaper.css('visibility', 'hidden');

	}


	// update the other toolbox-links
	if( 'undefined' !== typeof(elementData.toolbox) ) {
		for (var i = 0; elementData.toolbox[i]; i++) {


			var $tmpElement = $toolbox.find('.' + elementData.toolbox[i].identifier);

			if( 1 == $tmpElement.size() ) {
				$tmpElement.find('a').attr('href', elementData.toolbox[i].href).parent().css('visibility', 'visible').find('span').text(elementData.toolbox[i].title);
			}

		}

	}
	
	audi_ngw.navigation.prepareLinks($toolbox);


	
	return false;
	
};


// handles click on a thumbnail in an video-gallery
audi_ngw.gallery.clickVideo = function($element, id){

	var elementData = $element.metadata();

	if( 1 !== jQuery('object#' + id).size() ) {
		
		$element = jQuery('#' + id);
		
		var attribute = {};
		attribute.width = $element.width();
		attribute.height = $element.height();
		attribute.version = audi_ngw.flash.sNeededFlashVersion;

		var params = {};
		params.allowScriptAccess = 'always';
		params.allowFullScreen = 'true';
		params.scale = 'noscale';
		params.menu = 'false';
		params.wmode = 'opaque';

		var data = $element.metadata();
		elementData.xmldata = data.xmldata;
		elementData.parent_id = id;
	
		swfobject.embedSWF(data.swf, id, attribute.width, attribute.height, attribute.version, "expressInstall.swf", elementData, params);
		audi_ngw.flash.pageLoaded(id);

	} else {

		audi_ngw.flash.pageLoaded(id);
		try{
			jQuery('#' + id)[0].playVideo(elementData.videoFile);
		} catch(e) {}
	}
	
	if( 'audi_gallery_video' == id ) {
		jQuery('#audi_gallery_fullscreen, #audi_gallery_image, .audi_gallery_toolbox').hide();
		jQuery('#audi_gallery_video').show().removeClass('audi_hide');

	} else if( 'audi_gallery_guided_tour' == id ) {
		
		var guidedTourData = elementData.guidedTour;
		var $container = jQuery('#audi_gallery_guided_tour').siblings('.audi_guided_tour');	
		
		$container.hide();
		$container.find('h4').text(guidedTourData.headline);
		var $ul = $container.find('ul').empty();
		

		for (var i = 0; guidedTourData.links[i]; i++) {
			$ul.append('<li><a href="' + guidedTourData.links[i].href + '" class="arrow">' + guidedTourData.links[i].title + '</a></li>');
		}
		
		
		
	} else {
		audi_ngw.gallery.updateOrderlink(elementData);
		
		jQuery('#audi_gallery_mobilesound, #audi_gallery_mobileimage').hide();
		jQuery('#audi_gallery_mobilevideo').show();
	}
	
	
	return false;
	
};


// handles click on a thumbnail in an sound-gallery
audi_ngw.gallery.clickRingtone = function($element){

	var elementData = $element.metadata();
	jQuery('#audi_gallery_mobilevideo').hide();
	jQuery('#audi_gallery_mobilesound, #audi_gallery_mobileimage').show();

	if( 1 !== jQuery('object#audi_gallery_mobilesound').size() ) {
		
		var attribute = {};
		attribute.width = $element.width();
		attribute.height = $element.height();
		attribute.version = audi_ngw.flash.sNeededFlashVersion;

		var data = jQuery('#audi_gallery_mobilesound').metadata();
		data.mp3file = elementData.mp3file;


		var params = {};
		params.allowScriptAccess = 'always';
		params.allowFullScreen = 'true';
		params.scale = 'noscale';
		params.menu = 'false';
		params.wmode = 'opaque';

		swfobject.embedSWF(data.swf, 'audi_gallery_mobilesound', attribute.width, attribute.height, attribute.version, "expressInstall.swf", data, params);
		 
	} else {
		try {
			jQuery('object#audi_gallery_mobilesound')[0].playMP3(elementData.mp3file);
		} catch(e) {}
		
		
	}
	
	var image = $element.parents('.audi_gallery').metadata().image;

	jQuery('#audi_gallery_mobileimage').css('background-image', 'url(' + image + ')');
	
	jQuery('#audi_gallery_mobile h3').html(elementData.headline);
	jQuery('#audi_gallery_mobile p').html(elementData.text);
	
	audi_ngw.gallery.updateOrderlink(elementData);
};


audi_ngw.gallery.updateOrderlink = function(data){

	var $orderlink = jQuery('#audi_gallery_orderlink');
	
	if( data.orderlink ) {

		$orderlink.attr('href', data.orderlink).show();
		audi_ngw.navigation.prepareLinks(jQuery('#audi_gallery_orderlink').parent());

	} else {

		$orderlink.attr('href', '#').hide();

	}
	
};



// handles click on a thumbnail in an mobile image-gallery
audi_ngw.gallery.clickMobileImage = function($element){
	
	var elementData = $element.metadata();
	
	jQuery('#audi_gallery_mobilevideo, #audi_gallery_mobilesound').hide();
	jQuery('#audi_gallery_mobileimage').show();
	
	jQuery('#audi_gallery_mobileimage').css('background-image', 'url(' + elementData.image + ')');
	
	jQuery('#audi_gallery_mobile h3').html(elementData.headline);
	jQuery('#audi_gallery_mobile p').html(elementData.text);
	
	audi_ngw.gallery.updateOrderlink(elementData);
	
};

/**
 * Custom Event: wil be fired as soon as we injected the xhr-snippet 
 * @param {Object} event
 * @param {Object} data {sId: new HTML parent Id}
 */
audi_ngw.gallery.onAjaxSnippetReady = function(event,data){
 
	//audi_ngw.log("EVENT - ajaxSnippetPrepared: audi_ngw.gallery.onAjaxSnippetReady ",arguments);
	// execute funtions on new content
 
	audi_ngw.gallery.initiate();
	
	// trigger event 
	audi_ngw.event.trigger('ajaxSnippetPrepared');
};
 

audi_ngw.gallery.initiate = function() {


	if (jQuery('div.audi_gallery').size() === 0) { return false; }

	jQuery('.audi_gallery_slider, .audi_gallery_slider_status').show();
		
	jQuery('div.audi_gallery').each(function (){

	    var ul = jQuery('ul', this);
		jQuery(this).addClass('audi_gallery_js');	

		if( jQuery(this).hasClass('audi_gallery_small') ) {
			jQuery(this).addClass('audi_gallery_small_js');				
		}

		// calculate the width of the ul => number of images * width of images + margin of images
		var ulWidth = ul.children('li').size() * audi_ngw.gallery.imageWidth;
	
		// calculate the range we can scroll => width of the ul - calculdated width of the ul before
		var slideWidth = 706 - ulWidth; // changed to fixed width
		slideWidth = slideWidth * -1;
	
		// set the width of the ul to the calculated size to get all images in a real row
		ul.width(ulWidth);

	
		// activate the slider with some options
	    var slider = jQuery('.audi_gallery_slider', this).slider({ 
	      handle: '.audi_gallery_slider_handle',
	      min: 0, 
	      max: slideWidth, 
	      slide: function (ev, ui) {
			ul.css('left', '-' + ui.value + 'px');
	      }, 
	      stop: function (ev, ui) {
	        ul.animate({ 'left' : '-' + ui.value + 'px' }, 1500, 'linear');
	      }
	    });
 	});


	jQuery('#con_gallery_foldout > li > a').click(function(){
		audi_ngw.gallery.changeActive(jQuery(this).next());		
	});

	
	jQuery('.audi_gallery_items a').click(audi_ngw.gallery.click);

	

	if( 1 !== jQuery('.audi_gallery_active').size() ) {
		audi_ngw.gallery.changeActive(jQuery('.audi_gallery:first'));
	} 

	
	
	audi_ngw.gallery.update();


};

jQuery(document).ready(function(){
	audi_ngw.event.bind('ajaxSnippetReady',audi_ngw.gallery.onAjaxSnippetReady);

});

