//var api_rvl_key = '3f36369cbbdb7df235e360cf7054731f'; //staging reveal app need to change
//var api_ap6_key = '4b1bf2bb4b81b084d20feae16b63c0e5'; //staging ap6 app need to change

//var api_rvl_key = '15b10c4ddaab72b3a431f7669d6b7f97'; //local app need to change
//var api_ap6_key = '15b10c4ddaab72b3a431f7669d6b7f97'; //local app need to change


var channel_path = "/xd_receiver.htm"; //local app need to change

$(function() {
	$("#fb_connect").click(connectFacebook);	
	$(".fb_connect_long button").click(connectFacebook);	
	
	$("#fb_dl_form").ajaxForm({
		dataType:  'json', 
		async: false,
        success:  processJson
	});
	
	$(".fb_download_now")
		.click(function() {
			$("#fb_dl_form").submit();
		})
		.find(".download_now")
		.unbind("click");
		
	$(".fb_download").jqm({
		modal: true				
	});
	
	$(".fb_download").jqmAddClose('.fb_download .close');	
	
	
	$("#fb_publish").click(callFBPublish);	
	
});	

$(window).load(function(){
	FB.init(fb_api_key,channel_path);
});

function connectFacebook(){
//	$("#fb_dl_form").submit();
	//alert($("#fbSubmit").text());
	//$("#fbSubmit").trigger('click');
	//$(".fb_download").jqmShow();
	//return;
	
	FB.ensureInit(function(){
	  FB.Connect.requireSession(function(){	
	  		FB.Facebook.get_sessionState().waitUntilReady(function(session){
				checkPermission();
			});	
	   });	  
  	});	
}

function checkPermission(){
	FB.Connect.showPermissionDialog(
    	"publish_stream",
	    showFbDownload);
}

function showFbDownload(perRetStr){
	if(perRetStr=="publish_stream"){
		FB.Connect.forceSessionRefresh(updateFacebookProfile)
	}else{
		$(".download_email_error").html( i18n.translate("You have to authorize publish stream to download"));
		$(".download_email_error").show();	
	}
}


function updateFacebookProfile(){
//	alert("up");
/*
	if($("input#product").attr("value") == 'reveal') {
		var uMsg=' is trying muvee Reveal.';		
		var attachment = {
						'name':'muvee Reveal - Free 15-day trial',
						'href':'http://www.muvee.com/en/products/reveal',
						'caption':"Thank you so much for dowinloading muvee Reveal",
						'description':"Create and share personalized, professional looking home movies in 3 steps. With automatic motion and face detection, your photos and video are synced to the beat of your favorite music. Post to Facebook, YouTube, burn it to DVD and more.",
						'media':[{'type':'image','src':'http://www.muvee.com/en/images/store/reveal_boxshot.jpg','href':'http://www.muvee.com'}]
						}; 
	}else{
		var uMsg=' is trying muvee autoProducer 6';		
		var attachment = {
						'name':'muvee autoProducer 6 - Free 21-day trial',
						'href':'http://www.muvee.com/en/products/ap6',
						'caption':"Thank you so much for dowinloading muvee autoProducer 6",
						'description':"Home movies without the fuss. Add your photos and video, select a style, and let it automatically create and sync a movie to the beat of your music.",
						'media':[{'type':'image','src':'http://www.muvee.com/en/images/store/reveal_boxshot.jpg','href':'http://www.muvee.com'}]
						}; 
	}
	
*/	
	
	FB.ensureInit(function(){					
		FB.Connect.streamPublish(fbUMsg,fbAttachment,null,null,null,afterFacebookUpdate,true);
	});	
	
}

function afterFacebookUpdate(id,exception){
	//alert(exception);
	if(!id){
		$(".download_email_error").html( i18n.translate("Unable to update your profile") );
		$(".download_email_error").show();
	}else{
		showDownload();
	}
	return;
}


function processFbJson(data) {		
//	alert(data.location);
	
	if(!($.browser.msie && jQuery.browser.version == '6.0')) {
		if ($.browser.msie) {
			window.open(data.location, 'Download', 'width=100,height=50,scrollbars=0,resizable=0,location=0')					
		} else {
			$("body").append('<iframe frameborder="0" scrolling="no" src="'+ data.location +'" width="1" height="1"></iframe>');
		}
	}
	//$("div.download_email_error").empty();
	$(".download_box").jqmHide();
	
	//successfully started the download
	pageTracker._trackEvent(/*category*/ 'SuccessfulDownload_' + $("input#product").attr("value"), /*action*/ location.pathname, /*label*/ 'scr_SuccessfulDownload');
	
}	
function validateFbDownload(formData, jqForm, options) {
	$(".download_email_error").html('<img src="/en/images/components/ajaxload/round.gif"/> <font>Downloading...</font>');
	if($.browser.msie && jQuery.browser.version == '6.0') {
		window.open($("#downurl").attr("value"),'Download','toolbar=0,location=no,directories=0,status=0,scrollbars=0,resizeable=0,width=1,height=1,top=0,left=0');
    	window.focus();				
	}
	return true;
}


function showDownload(){
	//$("#fb_dl_div").show();
	if ($.browser.msie) {
		//$("#download_form").hide();
		//$(".fb_download_msg").text("Click to start download process");
		//$("#fb_dl_div").show();
		/*
		var downloadThanksHTML = '<div class="download_thanks"><h1>Thank you for downloading.</h1>' + 
			'<p>Your download should begin shortly. ' +
			'If your download does not start ' + 
//			'automatically, please <a href="' + data.location + '">click here</a>.</p></div>';
			'automatically, please try again';
		*/
			
		var downloadThanksHTML = '<div class="download_thanks"><h1 class="hello">' + i18n.translate('Thank you for downloading') + '</h1>' + 
			'<p>' + i18n.translate('Your download should begin shortly. If your download does not start automatically, ') + 
			+ i18n.translate('please try again.') + '.</p></div>';			
			
		if($("input#product").attr("value") != '') {
			$("#download_form").html(
				downloadThanksHTML		
			);			
		}
		$(".fb_download").jqmShow();
	} else {
		$("#fb_dl_form").submit();
	}
	
}



function callFBPublish() {
	 FB.ensureInit(function () {
   		 	FB.Connect.streamPublish('', fbAttachment, null);
		
 	});
}


