// 12-11-08
var doubleclick = function(from)
{
	var template = doubleclick.map[from];
	jQuery(document.body).append(template.replace(/\{\$rnd\}/, (Math.random() * 10000000000000).toString()));
};
doubleclick.map =
{
	'landing':  '<iframe src="http://fls.doubleclick.net/activityi;src=1649153;type=kf_com;cat=mdifldg;ord=1;num={$rnd}?" width="1" height="1" frameborder="0"></iframe>',
	'download':	'<img src="http://ad.doubleclick.net/activity;src=1649153;type=kf_com;cat=mdifapp;ord={$rnd}?" width="1" height="1" border="0" alt="">',
	'appstore':	'<img src="http://ad.doubleclick.net/activity;src=1649153;type=kf_com;cat=mdifapp;ord={$rnd}?" width="1" height="1" border="0" alt="">',
	'comments':	'<img src="http://ad.doubleclick.net/activity;src=1649153;type=kf_com;cat=mdifsnd;ord={$rnd}?" width="1" height="1" border="0" alt="">'
};

var cmetrics = function(from)
{
	var params = cmetrics.map[from];
	if (!params) { return; }
	//alert('coremetrics: ' + params.type);
	
	switch (params.type)
	{
		case ('category'):
		{
			cmCreatePageviewTag(params.data.PageID, params.data.CategoryID, null, null);
			break;
		}
		case ('event'):
		{
			cmCreateConversionEventTag(params.data.EventID, params.data.ActionType, params.data.EventCategoryID, params.data.Points);
			break;
		}
		case ('element'):
		{
			cmCreatePageElementTag(params.data.ElementID, params.data.ElementCategory); //, params.PageID, params.PageCategoryID
			break;
		}
	}
};

cmetrics.map =
{
	'landing':	{ type: 'category',	data: { PageID: 'LandingPageiPhoneMicrosite',	CategoryID: 'LandingPageiPhoneMicrosite' } },
	'photos':	{ type: 'category',	data: { PageID: 'PhotosiPhoneMicrosite',		CategoryID: 'PhotosiPhoneMicrosite' } },
	'faqs':		{ type: 'category',	data: { PageID: 'FAQiPhoneMicrosite',			CategoryID: 'FAQiPhoneMicrosite' } },
	
	'download':	{ type: 'event',	data: { EventID: 'DownloadNowiPhoneMicrosite',					ActionType: '2', EventCategoryID: 'iPhoneMicrosite', Points: '0' } },
	'appstore':	{ type: 'event',	data: { EventID: 'ExittoAppStoreiPhoneMicrosite',				ActionType: '2', EventCategoryID: 'iPhoneMicrosite', Points: '0' } },
	'comments':	{ type: 'event',	data: { EventID: 'SendCommentsiPhoneMicrosite',					ActionType: '2', EventCategoryID: 'iPhoneMicrosite', Points: '0' } },
	
	'video-1':	{ type: 'event',	data: { PageID: 'VideosiPhoneMicrosite-7000_Recipes',			ActionType: '2', EventCategoryID: 'iPhone Microsite Videos', Points: '0' } },
	'video-2':	{ type: 'event',	data: { PageID: 'VideosiPhoneMicrosite-ShoppingList',			ActionType: '2', EventCategoryID: 'iPhone Microsite Videos', Points: '0' } },
	'video-3':	{ type: 'event',	data: { PageID: 'VideosiPhoneMicrosite-RecipeBox',				ActionType: '2', EventCategoryID: 'iPhone Microsite Videos', Points: '0' } },
	'video-4':	{ type: 'event',	data: { PageID: 'VideosiPhoneMicrosite-CookingInspirations',	ActionType: '2', EventCategoryID: 'iPhone Microsite Videos', Points: '0' } }
};


window.getVideoPlayer = function()
{
	var swf = null;
	var swfName = 'KraftPlayer';
	
	/*
	window.document[movieName]      // (on Mozilla browsers such as Netscape)
	window[movieName]               // (on Internet Explorer as of ver 5)
	document.embeds[movieName]      // Mozilla Netscape, Firefox or Opera
	*/
	if (window.document[swfName])
	{
		swf = window.document[swfName] || null;
	}
	else if (document.embeds && document.embeds[swfName])
	{
		swf = document.embeds[swfName] || null;
	}
	else
	{
		swf = window[swfName] || null;
	}
	
	return swf;
}
window.playVideo = function(videoNum)
{
	stopVideo.stopFlag = false;
	playVideo.videoNum = videoNum;
	_playVideo();
};
playVideo.pathToVideoPlayerSWF = '/SiteCollectionImages/KraftPlayer.swf';
playVideo.videoNum = 0;
window._playVideo = function()
{
	var swf = getVideoPlayer();
	
	// If the swf isn't loaded fully yet, try again in 55ms
	if (!swf || !swf.setVideo)
	{
		window.setTimeout('window._playVideo()', 10);
		return;
	}
	
	// Set the video in the swf to be played
	swf.setVideo(playVideo.videoNum);
	
	// Call coremetrics for tracking of the specific video
	cmetrics('video-' + playVideo.videoNum);
};

window.stopVideo = function()
{
	stopVideo.stopFlag = true;
	_stopVideo();
};
stopVideo.stopFlag = false;

window._stopVideo = function()
{
	if (!stopVideo.stopFlag) { return; }
	
	var swf = getVideoPlayer();
	if (!swf || !swf.stopVideo)
	{
		window.setTimeout('window._stopVideo()', 10);
		return;
	}
	
	stopVideo.stopFlag = false;
	swf.stopVideo();
};





// Main docment ready functionality
jQuery(document).ready(function()
{
	// Modal options
	var options = {};
	
	// Create FAQ Modal
	options.title = "<h2><strong>iFood Assistant</strong> Frequently Asked Questions</h2>";
	var faqModal = new JModal(jQuery('#modal-faqs'), options);
	jQuery('.application-faqs-link').click(function(evt)
	{
		evt.preventDefault();
		faqModal.show();
		cmetrics('faqs');
	});
	
	var videoMap =
	[
		{ idx: 1, title: '<h2><strong>7000 Recipes at your Fingertips</strong></h2>' },
		{ idx: 2, title: '<h2><strong>Smart Shopping List with Store Locator</strong></h2>' },
		{ idx: 3, title: '<h2><strong>Your very own Mobile Recipe Box</strong></h2>' },
		{ idx: 4, title: '<h2><strong>Delicious Inspiration, Anytime, Anywhere</strong></h2>' }
	];
	
	// Create Video Modal
	var videoModal = new JModal(jQuery('#modal-video-gallery'), { hideHandler: window.stopVideo, hideMove: true, title: "<h2><strong>iFood Assistant</strong> Your very own mobile Recipe Box</h2>" });
	jQuery('.playvideo').each(function(idx)
	{
		jQuery(this).click(function(evt)
		{
			evt.preventDefault();
			
			var video = videoMap[idx];
			
			jQuery('h2', videoModal.getContentElm().parent()).html(video.title);
			
			// Show the video player modal
			videoModal.show();
			
			// play specific video
			playVideo(video.idx);
		});
	});
	
	// Load video player
	var so = new SWFObject(playVideo.pathToVideoPlayerSWF, "KraftPlayer", "640", "385", "9.0.0", "#333333");
	so.addParam('wmode', 'window');
	so.addParam('quality', 'high');
	so.addParam('align', 'middle');
	so.addParam('allowNetworking', 'all');
	so.addParam('allowFullScreen', 'true');	
	so.addParam('allowScriptAccess', 'samedomain');
	so.addParam('name', 'KraftPlayer');
	
	so.write("video-gallery");
	
	// Create Photo Gallery Modal
	options.title = "<h2><strong>iFood Assistant</strong> Photo Gallery</h2>";
	options.closeHandler = function(modal) {};
	var galleryPhotosModal = new JModal(jQuery('#modal-photo-gallery'), options);
	jQuery('.photo-gallery-link').click(function(evt)
	{
		evt.preventDefault();
		carousel.jumpTo(0);
		galleryPhotosModal.show();
		cmetrics('photos');
	});
	var carousel = new Carousel(jQuery('.carousel'));
	
	/* BEGIN: Alt Landing */
	/*
	1) Over 7,000 recipes at your fingertips>Image 2>Recipe Overview
	2) Smart Shopping List with Store Locator>Image 9>Gallery_Shopping List
	3) Your very own mobile recipe box>Image 7>Recipe Box
	4) Delicious inspiration anywhere, anytime>Image 4>Simple Shortcuts
	*/
	var photoMap =
	{
		recipes: { idx: 1, title: '' },
		shoppinglist: { idx: 3, title: '' },
		recipebox: { idx: 7, title: '' },
		inspiration: { idx: 10, title: '' }
	};
	jQuery('.view-in-gallery').click(function(evt)
	{
		evt.preventDefault();
		var photo = map[jQuery(this).parent().attr('id')];
		var itemIdx = photoMap.idx;
		carousel.jumpTo(itemIdx);
		galleryPhotosModal.show();
		cmetrics('photos');
	});
	/* END */
	
	// Email form
	jQuery('.submit').click(function(evt)
	{
		evt.preventDefault();
		
		var errors = [];
		
		var emailElm = jQuery('#feedback-email');
		var fromEmail = emailElm.attr('value');
	
		if (!fromEmail || fromEmail === emailElm.get(0).defaultValue || !jQuery.regexpCommon('email').test(fromEmail))
		{
						errors.push('Please enter a valid email address.');
		}
		
		var commentsElm = jQuery('#feedback-comments');
		var comments = commentsElm.attr('value');
		if (!comments || comments === commentsElm.get(0).defaultValue)
		{
			errors.push('Please enter your comments.');
		}
		
		if (errors.length)
		{
			alert(errors.join('\n'));
			return;
		}
		
		// BEGIN: CHANGE ME
		var toEmail = 'FeedbackiPhone@kraftfoods.com'; 
		var serviceUrl = '/ws/RecipeWS.asmx?op=SendEmail'; 		
		// END: CHANGE ME
		
		cmetrics('comments');
		doubleclick('comments');
		
		var soapMessage = [];
		soapMessage[soapMessage.length] = '<?xml version="1.0" encoding="utf-8"?>';
		soapMessage[soapMessage.length] = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
		soapMessage[soapMessage.length] = '<soap:Body>';
		soapMessage[soapMessage.length] = '<SendEmail xmlns="http://www.kraftfoods.com/ws/">';
		soapMessage[soapMessage.length] = '<sMessageFrom>' + fromEmail + '</sMessageFrom>';
		soapMessage[soapMessage.length] = '<sMessageTo>' + toEmail + '</sMessageTo>';
		soapMessage[soapMessage.length] = '<sMessageSubject>iPhone Feedback</sMessageSubject>';
		soapMessage[soapMessage.length] = '<sMessageBody>' + comments + '</sMessageBody>';
		soapMessage[soapMessage.length] = '<bIsMessageTypeHTML>true</bIsMessageTypeHTML>';
		soapMessage[soapMessage.length] = '</SendEmail>';
		soapMessage[soapMessage.length] = '</soap:Body>';
		soapMessage[soapMessage.length] = '</soap:Envelope>';
		
		jQuery.ajax(
		{
			type: 'post',
			url: serviceUrl,
			data: soapMessage.join(''),
			processData: false,
			contentType: 'text/xml; charset=utf-8',
			dataType: 'xml',
			cache: false,
			// clearForm: true,
			complete: function(data, status)
			{
				if (status === 'success')
				{
					var match = /^.*\<SendEmailResult\>\<Status\>(.*)\<\/Status\>\<\/SendEmailResult\>.*$/.exec(data.responseText);
					if (!match || !match[1] || match[1] !== 'success') { alert("There was a problem submitting your data. Please try again."); return; }
					
					jQuery('#microsite-container #feedback').hide('fast');
					jQuery('#microsite-container #thankyou').show('fast');
				}
				else
				{
					alert("There was a problem submitting your data. Please try again.");
				}
			}
		});
	});
	jQuery('#thankyou a').click(function(evt){ evt.preventDefault(); jQuery(this).parent().hide('fast'); jQuery('#feedback').clearForm(); jQuery('#feedback').show('fast') })
	
	jQuery('a.appstore-external').click(function(evt)
	{
		//evt.preventDefault();
		if (!confirm('You are now leaving kraftfoods.com. To continue to iTunes, click OK.'))
		{
			evt.preventDefault();
			return;
		}
		var key = (jQuery(this).hasClass('download'))? 'download' : 'appstore';
		cmetrics(key);
		doubleclick(key);
	});

	/********************************
		COREMETRICS */
	cmSetProduction(); // Uncomment this line for production
	cmetrics('landing');
	doubleclick('landing');
});