
$(document).ready(function() {    
    var IMAGE_URL = $("#IMAGE_URL").val();
	var REFERRAL_URL = $("#REFERRAL_LINK").val();
	var ajaxCommons = new FDR.AJAXCommons();
    var fdrWindow        = $(window);
    var fdrBGWrapper = $("#bg-splash");
    var fdrBG            = $("#bg-splash img");
    var fdrAspectRatio      = parseInt(fdrBGWrapper.css('width').replace("px", "")) / parseInt(fdrBGWrapper.css("height").replace("px", ""));
    var lrwidget = $("#sign-up-wrapper");
	var arraySearch = new FDR.ArraySearch();
	var abTesting = new FDR.ABTesting();

    function resizeBg() {
            var wWidth = fdrWindow.width();
            var wHeight = fdrWindow.height();
			
			if ( (fdrWindow.width() / fdrWindow.height()) < fdrAspectRatio ) {
				fdrBG
                    .removeClass('bgwidth')
                    .addClass('bgheight');
            } else {
                fdrBG
                    .removeClass('bgheight')
                    .addClass('bgwidth');
            }
			

    };
	
	var finalFriendsList = [];
	var userName = "";
	$(".connect-to-fb").bind('click', function() {
		var action = $(this).attr('fbAction');

		/* Handle facebook connection */
		FB.login(function(response) {
	    	if (response.authResponse) {
				var myInfo = FB.api("/me", function(response) {
					if( response ) {
						userName = response.name;
						if (action == 'wall') {
							postToFeed(getPostToMyWallParams(userName, REFERRAL_URL));
						} else {
							var friendsResponse = FB.api("/me/friends", function(response) {
								if( response.data) {
									var friends = response.data;
									$(".invite-facebook .content .search").show();
									finalFriendsList = friends.sort(function(a, b){
										return a.name.localeCompare(b.name)
									});
									populateFacebookFriendSelect(finalFriendsList);
								}
							});
						}	
					}
				});
				
		    } else {
				$('#facebox .spinner img').hide();
		    }

		}, {});
		return false;
	});
	
	//Facebook friends search
	$(".invite-facebook .search input").bind("keyup", function() {
		if( finalFriendsList.length > 0 ) {
			var newList = [];
			var searchString = $(this).val();
			for( var i in finalFriendsList ) {
				var name = finalFriendsList[i].name.toLowerCase();
				if( name.indexOf(searchString) >= 0 ) {
					newList.push(finalFriendsList[i]);
				}
			}
			populateFacebookFriendSelect(newList);
		}
	});
	
	//Populates the friends selection widget
	function populateFacebookFriendSelect(friendsList) {
		$(".invite-facebook .friends").html("");
		for( var i in friendsList ) {
			var friend = friendsList[i];
			var friendHTML = "\
			<div class='friend' fbId='" + friend.id + "'  fbName='" + friend.name + "'>\
				<img width='50' height='50' src='https://graph.facebook.com/" + friend.id + "/picture'/>\
				<div class='name'>" + friend.name + "</div>\
			</div>";
			
			$(".invite-facebook .friends").append(friendHTML);
		}
		
		$(".invite-facebook .friends .friend").click(function() {
			postToFeed(getPostToMyFriendsWallParams($(this).attr('fbId'), $(this).attr('fbName'), REFERRAL_URL));
		});
	};
	
	//Params used to post to users wall
	function getPostToMyWallParams(userName, referralURL) {
		var referralURL = referralURL + "&utm_source=home&utm_medium=facebook&utm_campaign=invite-fbwall&utm_content=";
		var versions = [ 
						{name : 'Invitation and a $15 credit to Opus 32 from ' + userName,
										feedUserName : userName,
										link : referralURL + "necklace",
										picture : IMAGE_URL + 'fb/necklace.jpg',
										description : 'Opus32.com features exceptional luxury goods from artisans worldwide. Save up to 60% on craftsman leather, jewelry, watches, apparel, spirits and more. Launching Spring 2012.',
										properties : {'Accept your $15 credit' : { text: 'Join Opus 32 now.', href: referralURL + "necklace"}}},
						{name : 'Invitation and a $15 credit to Opus 32 from ' + userName,
										feedUserName : userName,
										link : referralURL + "stitch",
										picture : IMAGE_URL + 'fb/stitch.jpg',
										description : 'Opus32.com features exceptional luxury goods from artisans worldwide. Save up to 60% on craftsman leather, jewelry, watches, apparel, spirits and more. Launching Spring 2012.',
										properties : {'Accept your $15 credit' : { text: 'Join Opus 32 now.', href: referralURL + "stitch"}}}
						];
		
		return versions[abTesting.getRandomInt(0,versions.length-1)];
	}	
	
	//Params used to post to friends wall
	function getPostToMyFriendsWallParams(friendsId, friendsName, referralURL) {
		var referralURL = referralURL + "&utm_source=home&utm_medium=facebook&utm_campaign=invite-fbfriend&utm_content=";
		var versions = [ 
						{userId : friendsId,
							name :  'Invitation and a $15 credit to Opus 32 from ' + userName,
							feedUserName : friendsName,
							link : referralURL + "necklace",
							picture : IMAGE_URL + 'fb/necklace.jpg',
							properties : {'Accept your $15 credit' : { text: 'Join Opus 32 now.', href: referralURL + "necklace"}}},
						{userId : friendsId,
							name : 'Invitation and a $15 credit to Opus 32 from ' + userName,
							feedUserName : friendsName,
							link : referralURL + "stitch",
							picture : IMAGE_URL + 'fb/stitch.jpg',
							properties : {'Accept your $15 credit' : { text: 'Join Opus 32 now.', href: referralURL + "stitch"}}}
						];
		
		return versions[abTesting.getRandomInt(0,versions.length-1)];
	}
	
	//Common function to post to a facebook feed
	function postToFeed(params) {
		var params = params ? params : {};
		var userId = params.userId ? params.userId : "";
		var link = params.link ? params.link : REFERRAL_URL;
		var picture = params.picture ? params.picture : IMAGE_URL + 'beta/fb-watch.jpg';
		var name = params.name ? params.name : 'Become an exclusive Opus 32 member';
		var caption = params.caption ? params.caption : ' ';         
		var description = params.description ? params.description : 'Opus32.com features exceptional luxury goods from artisans worldwide. Save up to 60% on craftsman leather, jewelry, watches, apparel, spirits and more. Launching Spring 2012.';
		var properties = params.properties ? params.properties : {'Accept your $15 gift' : { text: 'Join Opus 32 now.', href: REFERRAL_URL}};
		var feedUserName = params.feedUserName ? params.feedUserName : '';
		
		// calling the API ...
		var obj = {
		  method: 'feed',
		  link: link,
		  picture: picture,
		  name: name,
		  caption : caption,
		  description: description,
		  properties : properties
		};
		
		if( userId ) {
			obj['to'] = userId;
		}
		
		FB.ui(obj, function(res){
			if( res ) {
				var fbInvite = feedUserName + "@fbwall";
				if( userId ) {
					fbInvite = userId + "@" + feedUserName;
				}
				ajaxCommons.callPOST("/fbInvite/", {'fbInfo' : fbInvite});
			}
			
		});
	
	};
		

    fdrWindow.resize(function() {
            resizeBg();
    }).trigger("resize");

	resizeBg();
	
	$("#referral-link").click(function() {
		$(this).focus();
		$(this).select();
	});
	
	new FDR.FDRInputTextClearer($("#email-address"));
	new FDR.FDRInputTextClearer($("#invite-emails"));
	new FDR.FDRInputTextClearer($(".search-box"));
	
	
	/* invite navigation */
	$(".navigation a.by-email").click(function() {
		$(".widget").hide();
		$(".navigation li a").removeClass("selected");
		$(this).addClass("selected");
		$(".invite-more-people").show();
		return false;
	});
	
	$(".navigation a.by-facebook").click(function() {
		$(".widget").hide();
		$(".navigation li a").removeClass("selected");
		$(this).addClass("selected");
		$(".invite-facebook").show();
		return false;
	});
	
	$(".connect-to-fb").bind("click", function() {
		$(".connect-to-fb").removeClass("selected");
		$(this).addClass("selected");
	});
});


