/*
 * GamesRadar JavaScript Libray
 * Most of the functions are based on JQUERY library
*/

/*
 * calculateAge()
 * calculates age between current system date and user dob
*/
function calculateAge(bDay){
	now = new Date()
	bD = bDay.value.split('/');
	if(bD.length==3){
		born = new Date(bD[2], bD[1]*1-1, bD[0]);
		years = Math.floor((now.getTime() - born.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
	}
}

function check_length_websites(getThis, maxLen){
	if(trim(getThis.value) != null) {
		if(getThis.value.length > maxLen) {
			getThis.value = getThis.value.substring(0, maxLen);
			alert('You entered too much text in the website(s) field. A maximum of 2000 characters is allowed.');
			return false;
		}
	}
}


/*
 * selectAllCkBoxTxt()
 * Select All/None checkboxes in the friends form by using SELECT ALL/NONE text link
*/
function selectAllCkBoxTxt(formName, chkBxName){
	if (document.forms[formName].chk_select_all.checked) {
		document.forms[formName].chk_select_all.checked = false;
	}
	else {
		document.forms[formName].chk_select_all.checked = true;
	}
	var checked_status = document.forms[formName].chk_select_all.checked;
	$("input[@class=" + chkBxName + "]").each(function(){
		this.checked = checked_status;
	});
}

/*
 * selectAllCkBox()
 * Select All/None checkboxes in the frinds form by using select all/none CHECK BOX
*/
function selectAllCkBox(formName, chkBxName){
	var checked_status = document.forms[formName].chk_select_all.checked;
	$("input[@class=" + chkBxName + "]").each(function(){
		this.checked = checked_status;
	});
}

/*
 * showPlatformForm()
 * Show edit/cancel text link on my platforms block
*/
function showPlatformForm(getThis){
	var e = $('.edit_platforms').find('span');
	if (e.text() == "(Edit)") {
		$('#my_platforms').hide();
		e.text('(Cancel)');
	} else if (e.text() == "(Cancel)") {
		$('#my_platforms').show();
		e.text('(Edit)');
	} else {
		$('#my_platforms').show();
		e.text('(Edit)');
	}
	$('#web_my_platforms_form').slideToggle(400);
}

/*
 * webform_platforms()
 * Hide/Show my platforms web form
*/
function webform_platforms(get_user_id){
	var e = $('.edit_platforms').find('span');
	e.text('(Edit)');
	$('#web_my_platforms_form').slideUp(200);
	var array_disp_platform = new Array();
	var chkbox_value = "";
	for (var i=0; i < document.platforms.platform.length; i++) {
		if (document.platforms.platform[i].checked) {
			chkbox_value = chkbox_value + document.platforms.platform[i].value + ",";
			array_disp_platform.push(document.platforms.platform[i].title);
		}
	}
	array_disp_platform_length = array_disp_platform.length;
	send_val = "";
	print_val = "";
	for (var j=0; j < array_disp_platform_length-1; j++) {
		send_val = array_disp_platform[j].replace(/ /gi, "") + "," + send_val;
		plink = (array_disp_platform[j].replace(/ /gi, "")).toLowerCase();
		if (plink == "gc"){
			print_val = print_val + "<a href=\"/" + plink + "\">GameCube</a>, ";
		}
		else if(plink == "dc"){
			print_val = print_val + "<a href=\"/" + plink + "/games\">" + "Dreamcast</a>, ";
		}
		else if((plink == "nes") || (plink == "snes") || (plink == "genesis") || (plink == "saturn") || (plink == "gameboy") || (plink == "n64") || (plink == "ps1") || (plink == "gba")){
			print_val = print_val + "<a href=\"/" + plink + "/games\">" + array_disp_platform[j] + "</a>, ";
		}
		else {
			print_val = print_val + "<a href=\"/" + plink + "\">" + array_disp_platform[j] + "</a>, ";
		}
	}
	send_val = send_val + array_disp_platform[j].replace(/ /gi, "");

	$.ajax({
			url: '/myplatforms.htj?user_id=' + get_user_id + '&selectedPlatforms=' + send_val.toLowerCase(),
			type: 'GET',
			timeout: 15000,
			error: function(e){
				alert('Your request cannot be processed at this time.\nPlease try again later.');
		},
		success: function(html){
			void(0);
		}
	});
	plink = (array_disp_platform[j].replace(/\b/, "")).toLowerCase();

	if(plink == "gc"){
		print_val = print_val + "<a href=\"/" + plink + "\">GameCube</a>";
	}
	else if(plink == "dc"){
		print_val = print_val + "<a href=\"/" + plink + "/games\">" + "Dreamcast</a>";
	}
	else if((plink == "nes") || (plink == "snes") || (plink == "genesis") || (plink == "saturn") || (plink == "gameboy") || (plink == "n64") || (plink == "ps1") || (plink == "gba")){
		print_val = print_val + "<a href=\"/" + plink + "/games\">" + array_disp_platform[j] + "</a>";
	}
	else{
		print_val = print_val + "<a href=\"/" + plink + "\">" + array_disp_platform[j] + "</a>";
	}
	$('#my_platforms').show();
	$('#my_platforms').html(print_val);
}

/*
 * SlideMyGames Menu
*/
var _USER2GAMES_LIST_UPDATED = false;
var _USER2GAMES_RELATIONSHIPS = new Array(7);
_USER2GAMES_RELATIONSHIPS[0] = "G_WANT";
_USER2GAMES_RELATIONSHIPS[1] = "G_PLAY";
_USER2GAMES_RELATIONSHIPS[2] = "G_BEAT";
_USER2GAMES_RELATIONSHIPS[3] = "G_DUST";
_USER2GAMES_RELATIONSHIPS[4] = "G_LOVE";
_USER2GAMES_RELATIONSHIPS[5] = "G_HATE";
_USER2GAMES_RELATIONSHIPS[6] = "G_TRACK";

function slideMyGamesMenu(getMenuId, userId, gameReleaseId, relativeType, page, returnHTMLContnet) {
	$(".slide_my_games").slideUp("normal");
	var jGetMenuId = "#" + getMenuId;

	if ($(jGetMenuId).is(":hidden")) {
		$.ajax({
			url: '/grAjaxGetUser2GameRelationship.htj?user_id='+userId+'&game_release_id='+gameReleaseId,
			type: 'GET',
			timeout: 15000,
			error: function(e){
					alert('Your request cannot be processed at this time.\nPlease try again later.');
			},
			success: function(html){
				$(jGetMenuId).html(html);

				_USER2GAMES_LIST_UPDATED = false;
				$(jGetMenuId).slideDown("normal");
				callSlideUpTimeoutFn(getMenuId, userId, gameReleaseId, relativeType, page, returnHTMLContnet);
			}
		});
	}
	else{
		$(jGetMenuId).slideUp("normal");
	}
}

function slideMyGamesSummaryMenu(getMenuId, userId, gameReleaseId) {
	$(".slide_my_games").slideUp("normal");
	var jGetMenuId = "#" + getMenuId;
	if ($(jGetMenuId).is(":hidden")) {
		$(jGetMenuId).slideDown("normal");
		callSlideUpTimeoutFn(getMenuId, userId, gameReleaseId, "", "", 0);
	}
	else{
		$(jGetMenuId).slideUp("normal");
	}
}

function callSlideUpTimeoutFn(getMenuId, userId, gameReleaseId, relativeType, page, returnHTMLContnet){
	var jGetMenuId = "#" + getMenuId;
	var mEnter = 0;
	var mLeave = 0;

    if (! page) page = 1;

	var getSlideMyGames = $(jGetMenuId).parent().find("div")[0];
	$(getSlideMyGames).bind("mouseenter",function(){
		mEnter = 1;
		mLeave = 0;
	}).bind("mouseleave",function(){
		mEnter = 0;
		mLeave = 1;
		setTimeout(function(){
			if (mEnter == 0){
				$(jGetMenuId).slideUp("normal");

				if (_USER2GAMES_LIST_UPDATED == true) {
					var getAjaxId = getMenuId.replace(/add_my_games/, "ajax_my_games");
					$("#"+getAjaxId).show();
					var activeRels = "";
					for (i=0;i<7;i++){
						var getSpan = $(jGetMenuId).children().find("span")[i];
						if ($(getSpan).hasClass("active")){
						if (activeRels.length > 0) activeRels += ",";
								activeRels += _USER2GAMES_RELATIONSHIPS[i];
							}
					}
					$(getSlideMyGames).unbind("mouseenter").unbind("mouseleave");
					$.ajax({
						url: '/profileGameUpdate.htj?user_id='+userId+'&game_release_id='+gameReleaseId+'&relationship_types='+activeRels+'&relationship_type='+relativeType+'&page='+page+'&returnHtml='+returnHTMLContnet,
						type: 'GET',
						timeout: 15000,
						error: function(e){
							$("#"+getAjaxId).hide();
							alert('Your request cannot be processed at this time.\nPlease try again later.');
						},
						success: function(html){
							$("#"+getAjaxId).hide();
							if (returnHTMLContnet > 0) {
								document.getElementById('user_game_relationship_list').innerHTML = html;
								// $("#user_game_relationship_list").html(html);
							}
						}
					});
				}
			}
		}, 800);
	});


}

function myGameSlideClick(thisObject, getSet){
	var jObject = $(thisObject);
	currentClassName = thisObject.className;
	if (getSet == 1) {
		removeMyGameSetOne(thisObject, currentClassName);
	} else if (getSet == 2) {
		removeMyGameSetTwo(thisObject, currentClassName);
	} else if (getSet == 0) {
		for (i=6;i<7;i++){
			var getSpan = $(thisObject).parent().children().find("span")[i];
			if (!($(getSpan).parents("li").hasClass(currentClassName))) {
				$(getSpan).removeClass("active")
			}
			else if (!($(getSpan).hasClass("remove_active"))){
				$(getSpan).addClass("active")
			}
		}
	}

	_USER2GAMES_LIST_UPDATED = true;

	jObject.find("span").removeClass("hover");
	// jObject.find("span").toggleClass("active");
	for (i=0;i<7;i++){
		var getSpan = $(thisObject).parent().children().find("span")[i];
		if ($(getSpan).hasClass("remove_active")) {
			jObject.find("span").removeClass("remove_active");
		}
	}

	var changeBtn = 0;
	for (i=0;i<7;i++){
		var getSpan = $(thisObject).parent().children().find("span")[i];
		if ($(getSpan).hasClass("active")){
			changeBtn = 1;
		}
	}

	var btnDiv = $(thisObject).parent().parent().parent().parent().find("div")[0];

	var jBtnDiv = $(btnDiv);
	if (changeBtn){
		jBtnDiv.removeClass("btn_add_my_games");
		jBtnDiv.addClass("btn_edit_my_games");
	}
	else{
		jBtnDiv.removeClass("btn_edit_my_games");
		jBtnDiv.addClass("btn_add_my_games");
	}
}

function removeMyGameSetOne(thisObject, getCurrent){
	for (i=0;i<4;i++){
		var getSpan = $(thisObject).parent().children().find("span")[i];
		if (!($(getSpan).parents("li").hasClass(getCurrent))) {
			$(getSpan).removeClass("active")
		}
		else if (!($(getSpan).hasClass("remove_active"))){
			$(getSpan).addClass("active")
		}
	}
}

function removeMyGameSetTwo(thisObject, getCurrent){
	for (i=4;i<6;i++){
		var getSpan = $(thisObject).parent().children().find("span")[i];
		if (!($(getSpan).parents("li").hasClass(getCurrent))) {
			$(getSpan).removeClass("active")
		}
		else if (!($(getSpan).hasClass("remove_active"))){
			$(getSpan).addClass("active")
		}
	}
}

function myGameSlideHover(thisObject){
	var jObject = $(thisObject);
	if (!(jObject.find("span").hasClass("active"))) {
		jObject.find("span").addClass("hover");
	}
	else{
		jObject.find("span").removeClass("active");
		jObject.find("span").addClass("remove_active");
	}
}

function myGameSlideOut(thisObject) {
	var jObject = $(thisObject);
	jObject.find("span").removeClass("hover");
	if (jObject.find("span").hasClass("remove_active")) {
		jObject.find("span").removeClass("remove_active")
		jObject.find("span").addClass("active")
	}
}

function slideMyPeopleMenu(getMenuId) {
		var jGetMenuId = "#" + getMenuId;
		$(jGetMenuId).slideToggle(400);
		callPeopleSlideUpTimeoutFn(getMenuId);
	}

	$(document).ready(function(){
	z = 1;
	$(".single_btn_section").mouseout(function(){
		z++;
		a = $(this).find("div").find("div");
		// $("#right_content").text(z);
	});

	$(".slide_my_people").mouseout(function(){
		$(this).animate({opacity: 1.0}, 500).slideUp();
	});
});

function callPeopleSlideUpTimeoutFn(getMenuId){
	var jGetMenuId = "#" + getMenuId;
	var mEnter = 0;
	var mLeave = 0;

	var getSlideMyPeople = $(jGetMenuId).parent().find("div")[0];
	var jSubDiv = "#" + getSlideMyPeople['id'];
	var jDiv = ".single_btn_section";
	$(jDiv).bind("mouseenter",function(){
		mEnter = 1;
		mLeave = 0;
	}).bind("mouseleave",function(){
		mEnter = 0;
		mLeave = 1;
		setTimeout(function(){
			if (mEnter == 0){
				$(jSubDiv).slideUp("normal");
				$(jDiv).unbind("mouseenter").unbind("mouseleave");
			}
		}, 800)
	});
}

function addUser2UserFollowing(getMenuId, targetId, reloadUrl, slideId, pageNum, userId, userName) {
	var getAjaxId = "ajax_my_people_" + slideId;
	$("#"+getAjaxId).show();
	$.ajax({
		url: '/grUser2UserAddFollowRelationship.htj?target_id='+targetId+'&reloadUrl='+reloadUrl+'&page='+pageNum+'&user_id='+userId+'&username='+userName+'&menu_id='+getMenuId,
		type: 'POST',
		timeout: 15000,
		error: function(e){
			$("#"+getAjaxId).hide();
			alert('Your request cannot be processed at this time.\nPlease try again later.');
		},
		success: function(html){
			try {
				$("#"+getAjaxId).hide();
				$("#" + getMenuId).html(html);
			} catch (err) {
				$("#"+getAjaxId).hide();
			}
		}
	});
}

function removeUser2UserFollowing(getMenuId, targetId, reloadUrl, slideId, pageNum, userId, userName) {
	var getAjaxId = "ajax_my_people_" + slideId;
	$("#"+getAjaxId).show();
	$.ajax({
		url: '/grUser2UserRemoveFollowRelationship.htj?target_id='+targetId+'&reloadUrl='+reloadUrl+'&page='+pageNum+'&user_id='+userId+'&username='+userName+'&menu_id='+getMenuId,
		type: 'POST',
		timeout: 15000,
		error: function(e){
			$("#"+getAjaxId).hide();
			alert('Your request cannot be processed at this time.\nPlease try again later.');
		},
		success: function(html){
			try {
				$("#"+getAjaxId).hide();
				$("#" + getMenuId).html(html);
			} catch (err) {
				$("#"+getAjaxId).hide();
			}
		}
	});
}

// SEARCH FRIENDS - RIGHT MODULE VALIDATION
function searchFriends(getThis){
	if (document.searchPeople.keywords.defaultValue == document.searchPeople.keywords.value){
		$("#search_friends_keyw").css("border-color","red");
		$("#right_search_error").html('<div class="ajax_failure_msg"><span>Please enter a valid email.</span></div>');
		return false;
	}
	else {
		$("#search_friends_keyw").css("border-color","#000");
		$("#right_search_error").html('');
		return true;
	}
}

function clearText(thefield){
	if(thefield.defaultValue == thefield.value) thefield.value = "";
}

function getText(thefield){
	if (thefield.value == "") thefield.value = "Enter username, name or email";
}

// INVITE FRIENDS - RIGHT MODULE VALIDATION
function inviteFriends() {
	var errorType = 0;
	var getToEmail 			= trim(document.inviteFriendsForm.toEmail.value);
	var getMessage 			= trim(document.inviteFriendsForm.message.value);
	var getInviteType 		= document.inviteFriendsForm.addFriendsType.value;
	var getSubject 			= document.inviteFriendsForm.subject.value;
	var getSenderEmail 		= document.inviteFriendsForm.fromEmail.value;
	var getSenderUsername 	= document.inviteFriendsForm.senderUsername.value;
	var getSenderFirstname 	= document.inviteFriendsForm.senderFirstname.value;
	var getSenderLastname 	= document.inviteFriendsForm.senderLastname.value;
	var getSenderUserId 	= document.inviteFriendsForm.senderUserId.value;

	var isComma = getToEmail.indexOf(",");
	var email_count = 1;
	if (getToEmail != "") {
		if(getToEmail == getSenderEmail){
			errorType = 1;
			$(".email_addresses").css("border-color","red");
			$("#right_invite_error").html('<div class="ajax_failure_msg"><span>Logged in user is not allowed to follow/friend self.</span></div>');
		}
		if (isComma == -1) {
			if (!(isValidEmail(getToEmail))) {
				errorType = 1;
				$(".email_addresses").css("border-color","red");
				$("#right_invite_error").html('<div class="ajax_failure_msg"><span>Please enter a valid email.</span></div>');
			}
		}
		else {
			var email = getToEmail.split(',');
			email_count = email.length;
			if (email.length > 11) {
				errorType = 2;
				$(".email_addresses").css("border-color","red");
				$("#right_invite_error").html('<div class="ajax_failure_msg"><span>Only upto 10 email addresses are allowed.</span></div>');
			}
			else {
				for (var i = 0; i < email.length; i++) {
					if (!(isValidEmail(email[i]))){
						errorType = 1;
					}
					if(email[i] == getSenderEmail){
						errorType = 1;
					}
				}
				if (errorType == 1){
					$(".email_addresses").css("border-color","red");
					$("#right_invite_error").html('<div class="ajax_failure_msg"><span>Atleast one or more email(s) is invalid.</span></div>');
				}
			}
		}
	}
	else {
		errorType = 1;
		$(".email_addresses").css("border-color","red");
		$("#right_invite_error").html('<div class="ajax_failure_msg"><span>Please enter atleast one email address.</span></div>');
	}
	if (errorType == 0) {
		$(".email_addresses").css("border-color","#000");
		$("#right_invite_error").html('');

		$.post("/grRightContentUserAddFriends.htj", {
				to_email: getToEmail,
				to_message: getMessage,
				invite_type: getInviteType,
				subject: getSubject,
				fromEmail: getSenderEmail,
				senderUsername: getSenderUsername,
				senderFirstname: getSenderFirstname,
				senderLastname: getSenderLastname,
				senderUserId: getSenderUserId
				},
				function(count){
					$("#ajax_people_updates").html('<div class="ajax_sucess_msg">' + count + ' invite(s) sent.</div>');
					document.inviteFriendsForm.toEmail.value = "";
					document.inviteFriendsForm.message.value = "";
				}
			);
	}
	return false;
}

// VALIDATE EMAIL STRING
function isValidEmail(str){
	str = str.replace(/ /g, "");
	var emailPattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!emailPattern.test(str)) {
		return false;
	}
	else {
		return true;
	}
}

// COMPLETE YOUR PROFILE CYP
function save_display_cyp(getVal){
	$.ajax({
		url: '/grSaveDisplayCYP.htj?cypvalue=' + getVal,
		type: 'GET',
		timeout: 15000,
		error: function(e){
			//alert('Your request cannot be processed at this time.\nPlease try again later.');
		},
		success: function(html){
			$("#complete_profile_block").css('display','none');
			void(0);
		}
	});
}

function blockUser(url, userId, userName) {
  var classX = '.block_user_' + userId;
  var time = new Date();
  url += '?' + time.getTime();

  $.ajax({
      url: url,
      type: 'GET',
      dataType: 'text',
      timeout: 15000,
      error: function(){
          alert('Your request cannot be processed at this time.\nPlease try again later.');
      },
      success: function(xml){
    	  $("#action_updates").text("");
          $(classX).html('<a href="javascript:unBlockUser(\''+userId+'\', \''+userName+'\')">Unblock User</a>');
          tb_remove();
      }
  });
}

function unBlockUser(userId, userName) {
  var classX = '.block_user_' + userId;
  var time = new Date();
  var url = '/profile/'+userName+'/people/unblock/'+userId + '?' + time.getTime();

  userName = userName.replace(' ', '+');
  var tb_url = '/profile/'+userName+'/people/block-thickbox/'+userId+'?&amp;height=130&amp;width=440&amp;modal=true';

  $.ajax({
      url: url,
      type: 'GET',
      dataType: 'text',
      timeout: 15000,
      error: function(){
          alert('Your request cannot be processed at this time.\nPlease try again later.');
      },
      success: function(xml){
    	  $("#action_updates").text("");
          $(classX).html('<a href="javascript:callThickBox(\''+tb_url+'\')">Block User</a>');
      }
  });
}

function checkTimeZone() {
   var dst;
   var rightNow = new Date();
   alert("Date ="+rightNow);
   var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
   var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
   var temp = date1.toGMTString();
   var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var temp = date2.toGMTString();
   var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
   var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);
   if (hoursDiffDaylightTime == hoursDiffStdTime) {
	   alert("Time zone is GMT " + hoursDiffStdTime + ".\nDaylight Saving Time is NOT observed here.");
	   return document.form1.getElementById("offset").value = "GMT "+hoursDiffStdTime;
   } else {
	   alert("Time zone is GMT " + hoursDiffDaylightTime + ".\nDaylight Saving Time is observed here.");
	   return document.form1.getElementById("offset").value = "GMT "+hoursDiffDaylightTime;
   }
}

function moreActivityFeed(feedUrl, mainForm) {
	var activityType = document.forms[mainForm].elements["activityType"].value;
	var pageSize = document.forms[mainForm].elements["pageSize"].value;
	var nextRecordOffset = document.forms[mainForm].elements["nextRecordOffset"].value;
	var lastActivityFeedId = document.forms[mainForm].elements["lastActivityFeedId"].value;
	var lastGroupDate = document.forms[mainForm].elements["lastGroupDate"].value;
	var actionUrl = feedUrl + '?' + 'activityType=' + activityType + '&nextRecordOffset=' + nextRecordOffset + '&lastActivityFeedId=' + lastActivityFeedId + '&lastGroupDate=' + lastGroupDate;
	$.ajax({
		url: actionUrl,
	    type: 'POST',
	    dataType: 'text',
	    timeout: 15000,
	    error: function() {
	      alert('Your request cannot be processed at this time.\nPlease try again later.');
	    },
	    success: function(xml) {
	    	var getCurHtml = $("#activity_feed").html();
	    	$("#activity_feed").html(getCurHtml + xml);

	    	if ((xml != null) && (trim(xml) == '')) {
	    		try {
	    		  $("#activity_feed_footer").hide();
	    		} catch (err) {
	    		}
	    	} else {
	    		var offset = parseInt(nextRecordOffset);
	    		offset += parseInt(pageSize);
	    		document.forms[mainForm].elements["nextRecordOffset"].value = offset.toString();
	    	}
	    }
	});
}

function updateActivityFeedGroupDate(mainForm, groupDate) {
	document.forms[mainForm].elements["lastGroupDate"].value = groupDate;
}