var isLocal = ( (document.location.host).indexOf('local') != - 1 );
var isDev = ( (document.location.host).indexOf('gc.dev') != - 1 );
var deleteUrl = 'http://'+(document.location.host)+'/registration/deleteLayout.jhtml';

$(function(){	
	// login page
	$("#facebookLogin .fb_connect_button").click(function() {
		FwpConnect.connect('facebook', function() {
			window.location.href = returnUrl;
		});		
	});

	// profile page
	$("#fb_profile_info_container .fb_connect_button").click(function() {
		FwpConnect.connect('facebook', function() {
			document.location.reload();
		});		
	});
	
	$("#invite_friend_a").click(function() {
		FB_RequireFeatures(["XFBML"], function(){
			showInviteFriendsBox();
		});
	});
	
	$("#update_settings_btn").click(function() {
		saveFeedSettings($("#tag_chk").attr("checked"), $("#love_chk").attr("checked"), $("#save_chk").attr("checked"));
		$("#feed_settings_msg").empty();
		$("#feed_settings_msg").append("Your settings were updated.");
	});
	
	if(FwpConnect.networks.facebook.loggedIn) {
		// on registration page, dont display facebook div if the user is already logged in to FB
		if ($("#facebookLogin").length == 1) {
			$("#facebookLogin").css("display", "none");
		}
		else {
			// on edit profile page, display friends list
			var fields = 'name,pic_square,current_location,is_app_user'; 
			FbPublish.getFriends(function(friendsList) {
				FbPublish.getInfo(friendsList, fields, showFriendsBox);
			});
			
			// set current feed settings
			$("#tag_chk").attr("checked", checkFeedSettings("tag"));
			$("#love_chk").attr("checked", checkFeedSettings("love"));
			$("#save_chk").attr("checked", checkFeedSettings("createLayout"));
		}
	}
	
	// on registration page, URI-encode and attach the link to reset-password 
	if($("#resetPwdLink").length == 1) {
		$("#resetPwdLink a").attr("href", "/registration/resetPassword.jhtml?returnUrl="+encodeURIComponent(returnUrl));
	}
	
	$('#profileOptions #editProfile').click( function() {
		if (getCookie("usr_info")) {
			$('#profileOptions').fadeOut(100, function() { $('#changeProfileContainer').fadeIn(200); });
		}
		else {
			window.location.href = 'http://'+(document.location.host)+'/registration/login.jhtml';
		}
	});
	$('#profileOptions #changePassword').click( function() {
		if (getCookie("usr_info")) {
			$('#profileOptions').fadeOut(100, function() { $('#changePasswordContainer').fadeIn(200); });
		}
		else {
			window.location.href = 'http://'+(document.location.host)+'/registration/login.jhtml';
		}
	});
	$('.cancelBtn').click( function() {
		$('#changeProfileContainer, #changePasswordContainer').fadeOut(100,								
		function() { $('#profileOptions').fadeIn(400); });
	});
	$('div[id*="delete_"]').click( function() {
		var fid = (this.id).replace('delete_','');
		$.ajax({
			type: 'POST',
			data: {'fid':fid},
			url: deleteUrl,
			success: function(data) {
				window.location = document.location.href; 
			},
			error:function(xhr, err, e){ alert( "Error: " + err ); }
			//complete: function(e){ alert( e+' completed deletion' ); }
		});
	});
});

/**
 * Builds the friends details table with selectable cells and 
 * adds it to the friends chooser dialog  
 */
function showFriendsBox(friendsList) {
	$("#friends_list_container").empty();
	
	// get only the friends who use this app (Superfetti)
	var fList = new Array();
	for (var k=0; k<friendsList.length; k++) {
		if (friendsList[k].is_app_user) {
			fList.push(friendsList[k]);
		}
	}
		
	var tableToInsert = "";
	
	if(!fList || fList.length == 0) {
		tableToInsert = "<br/><a href=\"#\" class=\"no_wf_friends_txt\">" +
						"You have no Webfetti Friends. Invite some now!</a>";
		$("#friends_list_container").append(tableToInsert);
		$(".no_wf_friends_txt").click(function() {
			FB_RequireFeatures(["XFBML"], function(){
				showInviteFriendsBox();
			});
		});
	}
	else {
    	getFriendsDiv(fList);
		/*tableToInsert = "<table cellspacing=\"5px\">";
		if (fList.length > 1) {
			for (var i=0; i<fList.length; i+=2) {
				tableToInsert += "<tr>" + getFriendsDiv(new Array(fList[i], fList[i+1])) + "</tr>";		
			}
		}
		else {
			tableToInsert += "<tr>" + getFriendsDiv(new Array(fList[0])) + "</tr>";
		}
		tableToInsert += "</table>";*/
		$("#friends_list_container").append(tableToInsert);
		
		// mouse-over, mouse-out and onclick color changes for the cells with friends' pics and names.
		// rgb(x,x,x) comparison for FF and hex color comparison for IE   
		$(".friends_block_td").mouseover(function() {
			if($(this).css("background-color") == "rgb(255, 255, 255)" || $(this).css("background-color") == "transparent" || 
					$(this).css("background-color") == "#ffffff") {
				$(this).css("background-color", "#E7EBF5");
			}
		});
		$(".friends_block_td").mouseout(function() {
			if($(this).css("background-color") == "rgb(231, 235, 245)" || $(this).css("background-color") == "#e7ebf5") {
				$(this).css("background-color", "#FFFFFF");			
			}
		});
		$(".friends_block_td").click(function () {
			if ($(this).css("background-color") == "rgb(231, 235, 245)" || $(this).css("background-color") == "transparent" || 
					$(this).css("background-color") == "#e7ebf5") {
				$(this).css("background-color", "#3B5998");
				$(this).css("color", "#FFFFFF");
				$(this).find("#location_span").css("color", "#FFFFFF");
			}
			else {
				$(this).css("background-color", "#E7EBF5");
				$(this).css("color", "#222222");
				$(this).find("#location_span").css("color", "#666666");
			}
		});
	}
}

/**
 * Iterates over friends list and extracts name, small pic and location info
 * to build selectable cells for friends chooser dialog
 */
function getFriendsDiv(fList) {
  //alert('getFriendsDiv ' + fList);
	//var tds = "";
  $(fList).each(function(i,friend){
    var city = (friend.current_location != null && friend.current_location.city != undefined) ? getTruncatedLoc(friend.current_location.city) : "Undisclosed";
    var url = (friend.pic_square != null && friend.pic_square.length > 0) ? friend.pic_square : "http://static.ak.fbcdn.net/pics/q_silhouette.gif";
    $("#friends_list_container").append(
      "<div id=\""+friend.uid+"\" class=\"friends_block_div\">" +
        "<div class=\"friend_pic_square\" style=\"background-image: url("+url+");\"></div>" +
        getTruncatedName(friend.name) + "<br/>" +
        "<span id=\"location_span\" class=\"friend_location\">" + city + "</span>" +
      "</div>")
    .find("#"+friend.uid)
    .hover(function(){
      if($(this).css("border")=="1px solid mediumvioletred")
        $(this).css("border","1px solid gray");
      else
        $(this).css("border","1px solid black");
    },       function(){
      if($(this).css("border")=="1px solid gray")
        $(this).css("border","1px solid mediumvioletred");
      else
        $(this).css("border","1px solid white"); //ie6 doesn't support transparent borders
    }).click(function(){
      urchinTracker("/clicks/views/friendslist/"+friend.uid);
//      if($(this).css("border")=="1px solid gray")
//        $(this).css("border","1px solid black");
//      else
//        $(this).css("border","1px solid gray");
      var fdiv = this;
      $.get("http://"+document.location.host+"/webfetti/getNetworkFriendInfo.jhtml",
      // commenting because following line throws an access restricted error in FB's JS api
      //$.get(unescape(document.location.search).match(/returnUrl=(http:\/\/.*\.com(\/webfetti)?)\//)[1]+"/getNetworkFriendInfo.jhtml",
      {externalUid:friend.uid,network:"Facebook"},
			function (data){
        $("#fbInfoModal .friends_block_div").html($(fdiv).html());
        var memberSinceDt = data.memberSince;
        if (data.memberSince != null) {
        	$("#fbInfoModal .friends_info_div #joindate").text(memberSinceDt);
        }
        var loved = 0;
        if (data.itemsLoved != null && data.itemsLoved != -1) { // if ratings were available
        	loved = Number(data.itemsLoved).commas();
        	$("#fbInfoModal .friends_info_div #itemsloved").text("Items Loved: "+loved);
        }
        var tagged = 0;
        if (data.itemsTagged != null && data.itemsTagged != -1) {
        	tagged = Number(data.itemsTagged).commas();
        	$("#fbInfoModal .friends_info_div #itemstagged").text("Items Tagged: "+tagged);
        }
        
        $("#fbInfoModal #fbfirstname").text($.grep(friend.name.match(/(\w*)/g),function(a){return a!="";})[0]);
        $("#fbInfoModal #fbcustomstuff").empty();
        if(data.layouts!=null&&data.layouts.length>0)
          $(data.layouts).each(function(i,layout){
            $("#fbInfoModal #fbcustomstuff").append(
              "<a href='"+unescape(document.location.search).match(/returnUrl=(http:\/\/.*\.com(\/webfetti)?)\//)[1]+"/MySpace/Layouts/Layout-Editor.jhtml?refPath="+layout.path+"custom-"+layout.name+"' style='float:left;width:114px;height:86px;margin:0 4px 4px 0;'>" +
                (layout.preview.indexOf("custom_layout_placeholder") == -1 ? "<img src='http://ak.imgfarm.com/images/mfc/uploads/webfetti"+layout.preview+"' alt='"+layout.altText+"' title='"+layout.altText+"' height='86' width='114'/>" : 
                 "<img src='http://ak.webfetti.com/v2/layout_tn.jpg' height='86px' width='114px'/>") +
                 //"<div class='thumbnail_fInfo_modal'></div>") +
              "</a>"
		        );
          });
        $("#fbInfoModal").dialog("open");
        //if(data.itemsTagged==0)
        //  phrasersOnStun(0,"#fbInfoModal .friends_info_div #itemstagged",2000,["0","Hey","You!","","Yeah, you!","...","Poorab!","I'm talking to you.","Are you there?","Ah, forget it!","0"]);
      }, "json");
  });
  });
  $("#fbInfoModal").dialog({
    autoOpen:false,
    draggable:true,
    resizable:false,
    dialogClass:"wf_fb_modal",
    overlay:{opacity:0,background:"black"},
    modal:true,
    position:"center",
    height:"auto",
    width:413
  }).show();
  $(".wf_fb_modal .ui-resizable-handle").hide();
  if($.browser.msie)
    $(".wf_fb_modal .ui-dialog-titlebar").hide();
  $("#fbInfoModal .fb_dialog_cancel_button, #fbInfoModal .ok").click(function() {
    $("#fbInfoModal").dialog("close");
  });
}

/**
 * Friend invite box builder
 */
function showInviteFriendsBox() {
	var url = document.location.href;
	if (url.charAt(url.length-1) == '#') {
		url = url.substring(0, url.length-1);
	}
	var content = "Check out all the cool Graphics and Glitter Superfetti has to offer!";
	var labelText = "Get Superfetti!";
	var inviteText = "Invite your friends to Superfetti";
	var actionText = "Select the friends you want to invite.";
	var apiKey = FwpConnect.networks.facebook.apiKey;
	var type = "Superfetti";
	
	FbPublish.inviteFriends(type, url, content, apiKey, labelText, actionText, inviteText);
}

// retrieves a cookie from document.cookie
function getCookie(name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var ii = 0;
	while (ii < clen) {
		var jj = ii + alen;
		if (document.cookie.substring(ii, jj) == arg) {
			return getCookieVal (jj);
		}
		ii = document.cookie.indexOf(" ", ii) + 1;
		if (ii == 0) break;
	}
}

function getCookieVal(offset){
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) { 
		endstr = document.cookie.length; 
	}
	return unescape(document.cookie.substring(offset, endstr));
}

// sets a cookie
function setCookie(name,value,expires,path,domain,secure,escapeVal){
	document.cookie = name + "=" + ( (escapeVal) ? escape( value ) : value )+
	( ( expires ) ? ";expires=" + expires.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	";domain=.webfetti.com" +
	( ( secure ) ? ";secure" : "" );
}

if(!Number.prototype.commas) {
  Number.prototype.commas = function() {
    var nStr = this + "";
    var x = nStr.split(".");
    var x1 = x[0];
    var x2 = x.length > 1 ? "." + x[1] : "";
    var rgx = /(\d+)(\d{3})/;
    while(rgx.test(x1)) {
      x1 = x1.replace(rgx,"$1" + "," + "$2");
    }
    return x1 + x2;
  };
}

var phrasersOnStun = function(i,commands,b,c){
	if(b!=null && c!=null){
		var target = commands;
		commands = [];
		$(c).each(function(i,phrase){
			commands.push({phrase:phrase,target:target,delay:b});
		});
	}
	var cur=commands[i++];
	$(cur.target).text(cur.phrase);
	if(i<commands.length)
		setTimeout(function(){
			phrasersOnStun(i,commands);
		},cur.delay);
};

function AprilFoolsDay(){
  var gagCount = 1;
  switch(Math.floor(Math.random()*(gagCount-1))){
    case 0: // pick a random phraser
      var sets = [
        [ {phrase:" Hey! ",target:"#toolbar_content a:eq(0)",delay:2500},
          {phrase:" What ",target:"#toolbar_content a:eq(0)",delay:0},
          {phrase:" are you doi",target:"#toolbar_content a:eq(1)",delay:0},
          {phrase:"ng here? ",target:"#toolbar_content a:eq(2)",delay:2000},
          {phrase:"You're",target:"#toolbar_content a:eq(0)",delay:0},
          {phrase:" not supposed ",target:"#toolbar_content a:eq(1)",delay:0},
          {phrase:" to be ",target:"#toolbar_content a:eq(2)",delay:0},
          {phrase:" here now ",target:"#toolbar_content a:eq(3)",delay:2000},
          {phrase:" Shhh! ",target:"#toolbar_content a:eq(0)",delay:0},
          {phrase:" Generators ",target:"#toolbar_content a:eq(1)",delay:0},
          {phrase:" Layouts ",target:"#toolbar_content a:eq(2)",delay:0},
          {phrase:" Glitter ",target:"#toolbar_content a:eq(3)",delay:1000},
          {phrase:" Your ",target:"#toolbar_content a:eq(0)",delay:0},
          {phrase:" Boss is ",target:"#toolbar_content a:eq(1)",delay:0},
          {phrase:" Coming! ",target:"#toolbar_content a:eq(2)",delay:1500},
          {phrase:" Home ",target:"#toolbar_content a:eq(0)",delay:0},
          {phrase:" Generators ",target:"#toolbar_content a:eq(1)",delay:0},
          {phrase:" Layouts ",target:"#toolbar_content a:eq(2)",delay:0},
          {phrase:" Glitter ",target:"#toolbar_content a:eq(3)",delay:10000},
          {phrase:" I'll ",target:"#toolbar_content a:eq(0)",delay:0},
          {phrase:" be back! ",target:"#toolbar_content a:eq(1)",delay:3000},
          {phrase:" Home ",target:"#toolbar_content a:eq(0)",delay:0},
          {phrase:" Generators ",target:"#toolbar_content a:eq(1)",delay:0},
        ]
      ];
      phrasersOnStun(0,sets[Math.floor(Math.random()*(sets.length-1))]);
      break;
    //case 1: // maybe a zwinky walking around the bottom of the window, sticking it's head up from time to time?
  }

}