/**
 * @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.galleryWidth = 706;
audi_ngw.gallery.separator = ' | ';
audi_ngw.gallery.orderLinkStdText = '';
audi_ngw.gallery.downloadLinkText = '';

// update the status-field for the active gallery
audi_ngw.gallery.update = function($scope){
	var itemsCount = jQuery('.audi_gallery_active .audi_gallery_items a', $scope).size();
	var thisItemsPosition = itemsCount - jQuery('.audi_gallery_active .audi_gallery_items a.active', $scope).parent().nextAll().size();
		
	jQuery('.audi_gallery_active .audi_gallery_slider_status', $scope).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();
	// special version for gallery-fullscreen
	attribute.version = '9.0.115.0';

	
	// 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;
	
	// exit if there's no fullscreen image 
	if (!tmp.search) { 
		jQuery('#audi_gallery_fullscreen').hide(); 
		return false;
	}	
	
	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.parent().metadata();
	data.images = audi_ngw.gallery.images;

	//data.xmldata = jQuery('#audi_gallery_fullscreen').parent().metadata().xmldata;

	var params = {};
	params.allowScriptAccess = 'always';
	params.allowFullScreen = 'true';
	params.scale = 'noscale';
	params.menu = 'false';
	params.wmode = 'opaque';
	data.parent_id = 'audi_gallery_fullscreen';
	
	audi_ngw.flash.embed(data.swf, data.parent_id, attribute.width, attribute.height, attribute.version, "", 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.trigger('click.simpleAccordion');
	}
	// 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');
		}
	);
	
};


// update the toolbox-elements for the clicked image
audi_ngw.gallery.updateToolbox = function($toolbox, elementData){

	// 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');
	$wallpaper.find('a').css('display', 'inline');
	var $wallpaperUl = $wallpaper.find('ul').empty();
	var i;

	// update the wallpaper-links
	$wallpaper.find('.open .close').click();
		
	$toolbox.find('li').hide().css('display', 'none');

	// update the wallpaper-element
	if( 'undefined' !== typeof(elementData.wallpaper) ) {

		for( 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('display', 'inline');
		audi_ngw.layer.statics.register(
			{	
				sIdContainer:			'#func_toolbox_wallpaper',
				sClassElement:			'.overlay',
				sClassClose:			'.close'

			}
		);

	} else {

		$wallpaper.hide();

	}


	// update the other toolbox-links
	if( 'undefined' !== typeof(elementData.toolbox) ) {
		for( 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).css('display', 'inline').parent().css('display', 'inline').find('span').text(elementData.toolbox[i].title);
		
			}

		}

	}
	
	
};

// 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();
	});

	// update the toolbox for the clicked image
	var $toolbox = jQuery('#audi_gallery_image').parent().find('.audi_gallery_toolbox .toolbox');
	audi_ngw.gallery.updateToolbox($toolbox, elementData);

	
	return false;
	
};


// handles click on a thumbnail in an video-gallery
audi_ngw.gallery.clickVideo = function($element, id){

	var elementData = $element.metadata();
	var $toolbox;

	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;
	
		audi_ngw.flash.embed(data.swf, id, attribute.width, attribute.height, attribute.version, "", 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_fullscreen, #audi_gallery_image').hide();
		jQuery('#audi_gallery_video').show().removeClass('audi_hide');
	
		// update the toolbox for the clicked image
		$toolbox = jQuery('#audi_gallery_video').parent().find('.audi_gallery_toolbox .toolbox');
		audi_ngw.gallery.updateToolbox($toolbox, elementData);

	} 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();
		
		// update the toolbox for the clicked image
		$toolbox = jQuery('#audi_gallery_mobile').parent().find('.audi_gallery_toolbox .toolbox');
		audi_ngw.gallery.updateToolbox($toolbox, elementData);
	}
	
	
	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';

		audi_ngw.flash.embed(data.swf, 'audi_gallery_mobilesound', attribute.width, attribute.height, attribute.version, "", 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);

	// update the toolbox for the clicked image
	var $toolbox = jQuery('#audi_gallery_mobile').parent().find('.audi_gallery_toolbox .toolbox');
	audi_ngw.gallery.updateToolbox($toolbox, elementData);
};


audi_ngw.gallery.updateOrderlink = function(data){

	var $orderlink = jQuery('#audi_gallery_orderlink'),
		$downloadLink = jQuery('#audi_gallery_downloadlink');
		
	if (($orderlink.length > 0) && (audi_ngw.gallery.orderLinkStdText === '')) {
		audi_ngw.gallery.orderLinkStdText = $orderlink.text();
	}
	if( data.orderlink ) {

		$downloadLink.hide();
		$orderlink.attr('href', data.orderlink).show();
		
		if (data.orderlinktext) {
			$orderlink.find('span').text(data.orderlinktext);
		} else {
			$orderlink.find('span').text(audi_ngw.gallery.orderLinkStdText);
		}
	} else if( data.downloadLink ) {
		
		$orderlink.hide();
		$downloadLink.attr('href', data.downloadLink).show();
		
		if (data.downloadLinkText) {
			$downloadLink.find('span').text(data.downloadLinkText);
		} else {
			$downloadLink.find('span').text(audi_ngw.gallery.downloadLinkText);
		}
		
		
	} else {

		$orderlink.attr('href', '#').hide();
		$downloadLink.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);
	
	// update the toolbox for the clicked image
	var $toolbox = jQuery('#audi_gallery_mobile').parent().find('.audi_gallery_toolbox .toolbox');
	audi_ngw.gallery.updateToolbox($toolbox, 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
 	var $scope = jQuery(data.sId);

	audi_ngw.gallery.initiate($scope);
	
	// trigger event 
	audi_ngw.event.trigger('ajaxSnippetPrepared');
};
 

audi_ngw.gallery.initiate = function($scope) {


	if (jQuery('div.audi_gallery', $scope).size() === 0) { return false; }

	jQuery('.audi_gallery_slider, .audi_gallery_slider_status', $scope).show();
		
	jQuery('div.audi_gallery', $scope).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 = audi_ngw.gallery.galleryWidth - 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
		if( 0 < slideWidth ) {
			
			jQuery('.audi_gallery_slider', this).show();
			
			var slider = jQuery('.audi_gallery_slider', this).slider({ 
				animate: true,
				min: 0, 
				max: slideWidth, 
				slide: function (ev, ui) {
					ul.css('left', '-' + ui.value + 'px');
				}
			});
		}

		// don't show the slider if there is not enough to slide
		if( (audi_ngw.gallery.galleryWidth-1) > ulWidth ) {
			jQuery('.audi_gallery_slider', this).hide();
		}
		
	});


	jQuery('#con_gallery_foldout > li > a', $scope).click(function(){
		audi_ngw.gallery.changeActive(jQuery(this).next());		
	});

	
	jQuery('.audi_gallery_items a', $scope).click(audi_ngw.gallery.click);

	

	if( 1 !== jQuery('.audi_gallery_active', $scope).size() ) {
		audi_ngw.gallery.changeActive(jQuery('.audi_gallery:first', $scope));
	} 

	
	
	audi_ngw.gallery.update($scope);


};

audi_ngw.gallery.prepare = function() {
	audi_ngw.event.bind('ajaxSnippetReady',audi_ngw.gallery.onAjaxSnippetReady);
};

