var userName = "Guest";
var gravatarlink = "";
var shareRot = false;

function showAchievement(title, achievement, image, callback) {
   var ahtml = "<b>"+title+"!</b>";
   ahtml = ahtml + "<img style='position: absolute;right:20px' src='/images/ac/"+image+"'/><br/><br/>";
   ahtml += achievement;

   jQuery("#achievement").html(ahtml);
   jQuery("#achievement").dialog({
      autoOpen: true,
      height: 250,
      width: 450,
      buttons: {
      	'Yay!': function() {
            jQuery(this).dialog('close');
      	}
      },
      close: function() {
         jQuery("#achievement").html();
         callback();
      }
	});
}

function phpDateToHTML(phpDate) {
   var minoffset = Math.floor(new Date().getTimezoneOffset());
   // YYYY-MM-DD HH:MM:SS
   var result = substr(phpDate,8,2)+"/"+substr(phpDate,5,2)+" "+substr(phpDate,11,2)+":"+substr(phpDate,14,2);
   return result;
}

function tweetMemeButton() {
    if (document.getElementById("tweetmeme")) {
        var iframeCode = "";
        iframeCode += "<iframe src=\"http://api.tweetmeme.com/button.js?url=" + escape(document.URL) + "&amp;style=normal&amp;source=RotR_News&amp;service=bit.ly\" scrolling=\"no\" frameborder=\"0\" width=\"50\" height=\"61\" >";
        jQuery("#tweetmeme").html(iframeCode);
    }
}

function clearHistory() {
   var ids = { task: 'clearHistory', name: userName};
	jQuery.ajax({
		type: "post",
		url: "/userTools.php",
		data: ids,
		success: function(result) {
		   welcomeUser("");
		}
	});
}

function checkNewAchievements(callback) {
   var ids = { task: 'newAchievements', name: userName};
	jQuery.ajax({
		type: "post",
		url: "/userTools.php",
		data: ids,
		success: function(result) {
         if (result!="none") {
            var achievements = result.split('#');
            for (x in achievements) {
              var infos = achievements[x].split('~');
              showAchievement(infos[0], infos[1], infos[2], callback);
            }
         }
		}
	});
}
function achievementUnlocked(aid, callback) {
   var ids = { task: 'achievement', name: userName, aid: aid};
	jQuery.ajax({
		type: "post",
		url: "/userTools.php",
		data: ids,
		success: function(result) {
         if (result!="none") {
            callback();
         }
		}
	});
}

(function(d){d.fn.kmi=function(b,c){if(c==undefined)c="38,38,40,40,37,39,37,39,66,65";return this.each(function(){var a=[];d(this).keydown(function(e){a.push(e.keyCode);if(a.toString().indexOf(c)>=0){d(this).unbind('keydown',arguments.callee);b(e)}},true)})}})(jQuery);

function openUser() {
   var cookieValue = jQuery.cookie("mh3User");
   var tempstr = cookieValue.split('#');
   userName = tempstr[0];
   var loginDate = tempstr[1];
   gravatarlink=tempstr[2];
   welcomeUser(loginDate);
}

function welcomeUser(lastLogin) {
   if (userName.toLowerCase() == "guest" || userName == "") {
      jQuery("#guestDialog").html("<span style='font-size:0.8em;'>Hello, Guest! Login to RotR's MH3 section to get access to your achievements and more stuff!</span>");
      jQuery("#returningDialog").html("");
      jQuery("#userDialog").dialog("open");
   } else {
      jQuery("#history").html("loading...");
      jQuery("#achievements").html("loading...");
      checkNewAchievements(function() {});
      var hroffset = Math.floor(new Date().getTimezoneOffset());

      var ids = { name: userName, task: 'history', loginDate: lastLogin, hroffset: hroffset };
   	jQuery.ajax({
   		type: "post",
   		url: "/userTools.php",
   		data: ids,
   		success: function(html) {
            jQuery("#history").html(html);
   		}
   	});
      var ids = { task: 'achievementList', name: userName};
   	jQuery.ajax({
   		type: "post",
   		url: "/userTools.php",
   		data: ids,
   		success: function(html) {
            jQuery("#achievements").html(html);
   		}
   	});

      jQuery("#guestDialog").html("");

      jQuery("#returningDialog").html("<img src='" + gravatarlink + "'/>" +
         "<span style='position: relative; top:-10px; left:10px;'>Hello, " + userName +
         ". Glad you're back!</span>");
      jQuery("#nickNameForm").hide();
      jQuery("#userDialog").dialog("option","buttons",
		   {
   			'Close': function() {
   				jQuery(this).dialog('close');
   			}
   		}
      ).dialog("open");
      checkUser();
   }
}

function loginUser(password, email) {
   var ids = { task: 'login', name: userName, password: password, email: email};
   var now = new Date();
   var cdate =(expandDate(now.getMonth()+1,2)) + "/" +
      expandDate(now.getDate(),2) + "/" +
      now.getFullYear()+ " " +
      expandDate(now.getHours(),2) + ":" + expandDate(now.getMinutes(),2);

	jQuery.ajax({
		type: "post",
		url: "/userTools.php",
		data: ids,
		success: function(result) {
		   if (result=="fail") {
		      userName="Guest";
		      jQuery("#loginError").html("Your password does not match.");
		      welcomeUser(cdate);
		   } else {
		      jQuery("#loginError").html("");
		      gravatarlink=result;
		      saveUserCookie();
		      welcomeUser(cdate);
		   }
		},

	});
}

function expandDate(value, length) {
   var tempR = "00000" + value;
   return tempR.substr(tempR.length-length);
}

function saveUserCookie() {
   var now = new Date();
   var dateString = (expandDate(now.getMonth()+1,2)) + "/" +
      expandDate(now.getDate(),2) + "/" +
      now.getFullYear()+ " " +
      expandDate(now.getHours(),2) + ":" + expandDate(now.getMinutes(),2);
   cookieValue = userName + "#" + dateString + "#" + gravatarlink;
   jQuery.cookie("mh3User",cookieValue,{ path: '/', expires: 10});
}

function checkUser() {
   var cookieValue = jQuery.cookie("mh3User");
   if (cookieValue==null) {
      // cookie expired or null
      welcomeUser("");
   } else {
      var tempstr = cookieValue.split('#');
      userName = tempstr[0];
      gravatarlink = tempstr[2];

      jQuery("#userButtonI").html("<br/>" +
            "<div class='ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix'" +
            " unselectable='on' style='-moz-user-select: none;font-size:0.9em;margin-left:5px;margin-right:5px;padding-left:5px;'><p>" + "Hello  " + userName +
            "!<br />Click here to access your user status.</p></div>" );
      saveUserCookie();
      setTimeout(function(){jQuery("#userButton").effect('pulsate')},10000);
      setTimeout(function(){jQuery("#userButton").effect('pulsate')},30000);
      setTimeout(function(){jQuery("#userButton").effect('pulsate')},50000);
   }
}

function checkContest() {
   var cookieValue = jQuery.cookie("contest");
   if (cookieValue==null) {
      // cookie expired or null
      showContest();
      var now = new Date();
  		var dateString = (expandDate(now.getMonth()+1,2)) + "/" +
      expandDate(now.getDate(),2) + "/" +
      now.getFullYear()+ " " +
      expandDate(now.getHours(),2) + ":" + expandDate(now.getMinutes(),2);
   		cookieValue = userName + "#" + dateString + "#" + gravatarlink;
   		jQuery.cookie("contest",cookieValue,{ path: '/', expires: 5});
   }
}

function showContest() {
   var ahtml = "Get a chance to win shirts, buttons, posters, postcards, buzzers, and and and...";
    ahtml = ahtml + "<img width='400' height='300' src='http://www.reign-of-the-rathalos.com/wp-content/uploads/2010/04/Foto174.jpg'/>";
   ahtml = ahtml + "<br/><br/>Just send a picture of your original gamebox to the mail adress below for your chance on BIG prizes.<br/><br/>";
   ahtml += "Send to: <a href='mailto:mh3supporter@reign-of-the-rathalos.com'>mh3supporter@reign-of-the-rathalos.com</a><br/><br/>";

   jQuery("#supcon").html(ahtml);
   jQuery("#supcon").dialog({
      autoOpen: true,
      height: 550,
      width: 450,
      buttons: {
      	'GREAT Idea!': function() {
            jQuery(this).dialog('close');
      	}
      },
      close: function() {
         jQuery("#supcon").html();
      }
	});	  
}

function createUserCenter() {
   jQuery("#userDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 450,
		width: 450,
		modal: true,
		buttons: {
			'Login/Register': function() {
				userName = jQuery("#nickname").val();
				password = jQuery("#password").val();
				email= jQuery("#email").val();
				loginUser(password, email);
			   jQuery(this).dialog('close');
			},
			'Close': function() {
				jQuery(this).dialog('close');
				saveUserCookie();
			}
		},
		close: function() {
		   saveUserCookie();
	   }
	});
}

function initMenus() {
   var actPage = jQuery("#main").attr("rel");
   jQuery(".topMenu").each(function() {
      if (jQuery(this).attr("rel")!=actPage) {
         jQuery(this).bind('mouseover', function(){
               jQuery(this).stop().animate({top: -20},300,'easeOutBounce');
            });
         jQuery(this).bind('mouseout', function(){
               jQuery(this).stop().animate({top: 137},300,'easeInExpo');
            });
         jQuery(this).bind('click', function() {
               window.location = jQuery(this).attr("rel");
            });
      } else {
         var ids = { commentID: jQuery("#main").attr("class")};
         var obj = this;
      	jQuery.ajax({
      		type: "post",
      		url: "/commentTools.php",
      		data: ids,
      		success: function(result) {
               jQuery(obj).children(".topMenuBox").css("background-image","url(/images/menuBackground.png)");
               jQuery(obj).children(".topMenuBox").html("<br/>" +
                  "<div class='ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix'" +
                  " unselectable='on' style='-moz-user-select: none;margin-left:5px;margin-right:5px;'><p>" + result +
                  "</p></div>");
               jQuery(obj).stop().animate({top: -20},100,'easeOutBounce');
      		}
      	});

      }
   });
}

function startRotShare() {
   if (shareRot) return;
   shareRot = true;
 	var deg=0;
	var dif=-3;
	var arr = $('.btn');
	var len = arr.length;
	var centerX = $('#stage').width()/2 - 40;
	var centerY = $('#stage').height()/2 - 60;

	arr.css('position','absolute');
	setInterval(function(){
   	if(Math.abs(dif)<0.5) return false;
   	deg+=dif;
   	$.each(arr,function(i){
   		var eSin = Math.sin(((360/len)*i+deg)*Math.PI/180);
   		var eCos = Math.cos(((360/len)*i+deg)*Math.PI/180);

   		$(this).css({
   			top:centerY+25*eSin,
   			left:centerX+90*eCos,
   			opacity:0.8+eSin*0.2,
   			zIndex:Math.round(80+eSin*20)
   		});
   	})
	},40);
}

function initShare() {
   jQuery("#share .btn").css('display','none');
   jQuery("#share").live('mouseover', function(){
         jQuery("#share .btn").css('display','block');
         jQuery(this).stop().animate({top: -27},400,'easeOutBounce');

      });
   jQuery("#share").live('click', function(){
         jQuery(this).stop().animate({top: 137},500,'easeInExpo');
         jQuery("#share .btn").css('display','none');
      });
   startRotShare();
}

jQuery(document).ready(function(){
   jQuery('a[href^="http://"]').attr("target", "_blank");
   jQuery(".hideAndShow").fadeTo(1,"0.01");
   jQuery(window).kmi(function(){
      achievementUnlocked(1, function() {
         checkNewAchievements(function() {
            // todo something here?
        });
      });
	});
   createUserCenter();
   jQuery("body").mousemove(function(e){
      var backx = e.pageX - 250;
      var backy = e.pageY - 250;
      var backpos = backx+'px '+backy+'px';

     jQuery("body").css('background-position',backpos);
   });

   jQuery(".hideAndShow").hover(function() {
      jQuery(this).stop(true, true).fadeTo(1000,"1");
   },function() {
      jQuery(this).stop(true, true).fadeTo(500,"0.01");
   });

   initMenus();
   initShare();
   tweetMemeButton();
   checkUser();
   
   jQuery("#userButton").click(function() {openUser();})
   jQuery("#clearHistory").click(function() {
      clearHistory();
      });

});

