var MEDIA_GALLERY_REQUEST_URL = '/service/widgets/mediagalleries/item';

$(function(){
	if($('body').hasClass('media-gallery')){	
		mediaGallery.activateGalleryTabs();
		mediaGallery.activateThumbnails();
		mediaGallery.activateFirstItem();
		mediaGallery.activateItemDeepLinking();
	}else if($('body').hasClass('accessories')){
		mediaGallery.activateAccordion();
		mediaGallery.activateOverlays();
		mediaGallery.activateTabs();
		mediaGallery.activateThumbnails();
		mediaGallery.activateItemDeepLinking();
	}
});

var mediaGallery = {
	changeItemURL: function(sItemId){
		var sCurrentUrl = location.href;
		var aCurrentUrlHash = sCurrentUrl.split('#');		
		location.href = aCurrentUrlHash[0]+'#item-'+sItemId;	
	},	
	activateItemDeepLinking: function(){
		var sCurrentUrl = location.href;
		var aCurrentUrl = sCurrentUrl.split('#');

		function getUrlVars(sUrl){
			var vars = [];
			var hash = '';
			var hashes = sUrl.slice(sUrl.indexOf('?') + 1).split('&');
			for(var i = 0; i < hashes.length; i++){
				hash = hashes[i].split('=');
				vars.push(hash[0]);
				vars[hash[0]] = hash[1];
			}
			return vars;
		}		
		
		if((aCurrentUrl[1] != null) && (aCurrentUrl[1] != '')){
			var sSelectedItem = aCurrentUrl[1].replace("item-", "");
			oSelectedItem = $('#'+sSelectedItem).find('.item');
			if(oSelectedItem[0] != null){
				mediaGallery.openItem(oSelectedItem);	
			}
		}
	},		
	loadItem: function(oItem){
		var oGallery = oItem.parents('.gallery');
		var aItemId = oItem.attr('id').split('-');
				
		function displayLoading(oGallery){
			oGallery.find('.viewer').html('<div class="text-box"><img src="/static/global/images/toyota-loader.gif" width="100" height="100"></div>');
			$.scrollTo($('body'));
		}		
		function displayError(oGallery){
			oGallery.find('.viewer').html('<div class="text-box">Server error. Please try again.</div>');
			$.scrollTo($('body'));
		}	
		function selectItem(oGallery, oItem){
			$('.gallery .block .list .item').removeClass('current');
			oItem.addClass('current');
			mediaGallery.activateControls(oGallery, oItem);
			mediaGallery.changeItemURL(oItem.parents('.item-id').attr('id'));
		}	
		
		displayLoading(oGallery);
		selectItem(oGallery, oItem);
		
		$.ajax({
			type: "GET",
			url: MEDIA_GALLERY_REQUEST_URL+'/'+aItemId[0]+'/'+aItemId[3]+'.html',
			error: function(data, textStatus, errorThrown) {
				displayError(oGallery);
			},
			success: function(data){
				oGallery.find('.viewer').html(data);
				video.elementSearch();		
				videoPlayer.embedVideos();

				var section = $('.gallery .tabs li.current a').text();
				if(!section) {
					section = $('.gallery-header .tabs li.current a').text();
				}
				if(!section) {
					section = 'unspecified section';
				}
				
				var type = 'Image';
				if($('.gallery-header .tabs li.current a').text() == 'Videos') {
					type = 'Video';
				}
				
				/*TRACKING*/
				//tracking.event.activate('trackingevent', {EventClass: PAGE_ABBR, Action: "ViewImage", Vehicle: VEHICLE_ABBR, Image: oItem.attr('id'), Section: section, Type: type});
				
				if(PAGE_ABBR == 'Accessories') {
					var sItemHeader = $('.viewer:visible .figure-box h3').text().replace(/\s/g, '');
					var link = oGallery.find('.viewer .icon-links .toyota a').attr('href');
					oGallery.find('.viewer .icon-links .toyota a').attr('href', link + '?WT.ac=VH'+VEHICLE_CODE+'AccessoriesPRC'+sItemHeader);
					var elink = oGallery.find('.viewer .icon-links .icon-accessories a').attr('href');
					oGallery.find('.viewer .icon-links .icon-accessories a').attr('href', elink + '?WT.ac=VH_'+VEHICLE_CODE+'_Accessories_EBR_'+sItemHeader);
					var wlink = oGallery.find('.viewer .genuine a').attr('href');
					oGallery.find('.viewer .genuine a').attr('href', wlink + '?WT.ac=VH'+VEHICLE_CODE+'AccessoriesWCG'+sItemHeader);
				}
			}
		});												
	},
	loadFirstItem: function(oBlock){
		var oFirstItem = oBlock.find('.list .item').filter(":visible:first");
		if(oFirstItem[0] != null){
			mediaGallery.openItem(oFirstItem);	
		}else{
			return false;
		}
	},
	loadLastItem: function(oBlock){
		var oLastItem = oBlock.find('.list .item').filter(":visible:last");
		if(oLastItem[0] != null){
			mediaGallery.openItem(oLastItem);	
		}else{
			return false;
		}
	},
	activateFirstItem: function(){
		var oItem= $('.gallery .block .list .current').filter(":visible:first");
		mediaGallery.activateControls(oItem.parents('.gallery'), oItem);
	},	
	activateGalleryTabs: function(){
		$('.gallery-header ul.tabs li').click(function(){
			var oCurrentTab = $(this);
			var oCurrentGallery = $('#'+oCurrentTab.attr('id').replace('tab-', ''));

			mediaGallery.openGalleryTab(oCurrentTab);
			
			var oCurrentBlock = oCurrentGallery.find('.block').filter(':visible:first');
			if(oCurrentBlock[0] != null){
				mediaGallery.loadFirstItem(oCurrentBlock);
			}
			
			/*TRACKING*/
			var sTabTitle = oCurrentTab.find('a').text();
			switch(sTabTitle) {
			case 'Images':
				tracking.event.activate('trackingevent', {EventClass: "Gallery", Action: "ButtonClick", Vehicle: VEHICLE_ABBR + ' Gallery section', Type: 'Image'});
				break;
			case 'Videos':
			case 'Video':
				tracking.event.activate('trackingevent', {EventClass: "Gallery", Action: "ButtonClick", Vehicle: VEHICLE_ABBR + ' Gallery section', Type: 'Video'});
				break;
			default:
				tracking.event.activate('trackingevent', {EventClass: "Gallery", Action: "ButtonClick", Vehicle: VEHICLE_ABBR + ' Gallery section', Type: sTabTitle});
				break;
			}
			
			return false;
		}); 		
	},
	openGalleryTab: function(oCurrentTab){
			var oCurrentGallery = $('#'+oCurrentTab.attr('id').replace('tab-', ''));

			/* Selecting current tab */
			$('.gallery-header ul.tabs li').removeClass('current');
			oCurrentTab.addClass('current');
			
			/* Displaying current gallery */
			$('.gallery').hide();
			oCurrentGallery.show();		
	},	
	activateTabs : function(){
		$('.gallery ul.tabs li').click(function(){
			var oCurrentTab = $(this);
			var oCurrentBlock = $('#'+oCurrentTab.attr('id')+'-block');
			
			mediaGallery.openTab(oCurrentBlock);
			
			if(oCurrentBlock.find('.current')[0] == null){
				mediaGallery.loadFirstItem(oCurrentBlock);
			}	
			
			/*TRACKING*/
			var sCategory = oCurrentTab.find('a').text();
			if($('body').hasClass('accessories')) {		
				tracking.event.activate('trackingevent', {EventClass:"Accessories", Action:"Category", Vehicle: VEHICLE_CODE, Category: sCategory});
			}
			
			return false;
		}); 
	},
	openTab : function(oCurrentBlock){		
		var oCurrentTab = $('#'+oCurrentBlock.attr('id').replace('-block', ''));
		if(oCurrentTab[0] != null){
			/* Selecting current tab */
			$('.gallery ul.tabs li').removeClass('current');
			oCurrentTab.addClass('current');
		}		
					
		/* Displaying current block */
		$('.gallery .block').hide();
		oCurrentBlock.show();
	},
	activateControls: function(oGallery, oItem){
		var oControls = oGallery.find('.controls');
		oControls.show();
		oControls.find('.previous').unbind('click').click(function(){
			var oPreviousItem = oItem.parents('.item-id').prev();
			if(oPreviousItem[0] != null){
				mediaGallery.loadItem(oPreviousItem.find('.item'));
			}else{
				mediaGallery.loadLastItem(oItem.parents('.block'));
			}
		});
		oControls.find('.next').unbind('click').click(function(){
			var oNextItem = oItem.parents('.item-id').next();
			if(oNextItem[0] != null){
				mediaGallery.loadItem(oNextItem.find('.item'));
			}else{
				mediaGallery.loadFirstItem(oItem.parents('.block'));
			}
		});
	},
	activateThumbnails: function(){	
		$('.gallery .block .list .item .link').click(function(){
			mediaGallery.openItem($(this).parents('.item'));		
			return false;
		});
	},
	openItem: function(oItem){	
		mediaGallery.loadItem(oItem);
		if(oItem.parents('.gallery').filter(':visible')[0] == null){
			var sCurrentGalleryTab = 'tab-'+oItem.parents('.gallery').attr('id');
			mediaGallery.openGalleryTab($('#'+sCurrentGalleryTab));
		}
				
		if (oItem.parents('.block').filter(':visible')[0] == null) {
			var oCurrentBlock = oItem.parents('.block');
			mediaGallery.openTab(oCurrentBlock);
		}
	},	
	activateAccordion: function(){
		$('.gallery .viewer .accordion-box').accordion({
			header: 'h4',
			autoHeight: true,
			clearStyle: true
		});
		
		$('.gallery .viewer .accordion-box h4').click(function() {
			if(!$(this).hasClass('current')) {
				var title = $(this).text();
				/*TRACKING*/
				tracking.event.activate('trackingevent', {EventClass:"Accessories",Action:"Expand",Vehicle: VEHICLE_ABBR,Heading: title});
			}
			$('.gallery .viewer .accordion-box h4').removeClass('current');
			$(this).addClass('current');
		});
	},
	activateOverlays: function(){
		var sAction = 'not specified';
		function showBlock(oBlock, oCloseLink){
			var bLinkState = false;
			$('body').click(function(){
				if(bLinkState == true){
					bLinkState = false;
				}else{
					hideBlock(oBlock);
				}				
			});
			
			oBlock.find('.opened').show().click(function(){
				if(bLinkState != true){
					return false;
				}
			});			
			
			oCloseLink.addClass('close-link');
			oBlock.find('.opened a').click(function(){
				if($(this).hasClass('close-link')){
					hideBlock(oBlock);
					return false;
				}else{
					bLinkState = true;
					return true;
				}
			});
						
			/*tracking*/
			var sItemHeader = $('.viewer:visible .figure-box h3').text();
			tracking.event.activate('trackingevent', {EventClass: "Accessories", Action: sAction, Vehicle: vehicle, Item: sItemHeader});			
		}
		
		function hideBlock(oBlock){
			oBlock.find('.opened a').unbind('click');
			oBlock.find('.opened').hide().unbind('click');
			$('body').unbind('click');
		}	
		
		$('.gallery .info .applicability .closed a').live('click', function() {
			sAction = 'Applicability';
			var oApplicabilityBlock = $(this).parents('.applicability');
			showBlock(oApplicabilityBlock, oApplicabilityBlock.find('.opened a'));
			return false;
		});
		
		$('.gallery .figure-box .disclaimers .closed a').live('click', function() {
			sAction = 'Disclaimers';
			var oDisclaimersBlock = $(this).parents('.disclaimers');
			showBlock(oDisclaimersBlock, oDisclaimersBlock.find('.opened a.disclaimer-controls'));
			return false;
		});
	}
}
