
var SubPublic = {};
SubPublic.Templates  = Class.create({
	initialize: function() {
		
	},
	getSelectBox: function(selectId, JSONObject, defaultValue){
		var defaultOption = "";
		if(defaultValue)
			defaultOption = '<option value="-1">'+ defaultValue +'</option>';
		var opt = new Template('<option value="#{userId}">#{userName}</option>');
		return '<select id="'+selectId +'">' + defaultOption + opt.evaluate(JSONObject) +'</select>';
	}
});

SubPublic.replaceHTML = Class.create({
	initialize: function(url, fillDiv) {
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport){
				$(fillDiv).update(transport.responseText);
			}
		});
	}
});
SubPublic.replaceHTMLCallback = Class.create({
	initialize: function(url, fillDiv, callBack, callBackParam) {
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport){
				$(fillDiv).update(transport.responseText);
				callBack.call(this, callBackParam);
			}
		});
	}
});

SubPublic.GetSkater = function(userInfo){
	if(userInfo.userUrlName != ""){
		return userInfo.userUrlName;
	}else{
		return userInfo.userId;
	}
}
SubPublic.setFavorite = function(infoStr, categoryId, mediaId){
	Dialogs.confirm(infoStr, SubPublic.callSetFavorite, [categoryId, mediaId]);
}
SubPublic.callSetFavorite = function(params){
	new Ajax.Request("/users/setfollowed", {
		method: 'post',
		parameters: {category:params[0], media:params[1]},
		onSuccess: function(transport){
			var response = transport.responseText.evalJSON();
			Dialogs.alert(response.msg);
		}
	});
}
SubPublic.directSetFavorite = function(mediaType, mediaId, callBack){
	new Ajax.Request("/users/setfollowed", {
		method: 'post',
		parameters: {category:mediaType, media:mediaId},
		onSuccess: function(transport){
			var response = transport.responseText.evalJSON();
			
			if(response.type == "success"){
				if(typeof(callBack) != "undefined"){
					callBack.call(this, response.msg);
				}
			}else{
				Dialogs.alert(response.msg);
			}
		}
	});
}
SubPublic.directUnSetFavorite = function(mediaType, mediaId, callBack){
	new Ajax.Request("/users/removefollowedmedia", {
		method: 'post',
		parameters: {media:mediaType, mediaid:mediaId},
		onSuccess: function(transport){
			var response = transport.responseText.evalJSON();
			if(response.type == "success"){
				if(typeof(callBack) != "undefined"){
					callBack.call(this, response.msg);
				}
			}else{
				Dialogs.alert(response.msg);
			}
		}
	});
}
SubPublic.addForumCategory = function(formRef, callBack){
	if($(formRef).elements["name"].value == ""){
		Dialogs.alert("Head text missing");
	}else if($(formRef).elements["desc"].value == ""){
		Dialogs.alert("Body text missing");
	}else{
		$(formRef).request({
			onSuccess: function(transport){
				if(transport.responseText){
					var response = transport.responseText.evalJSON(true);
					if(response.type == "success"){
						// reset
						callBack.call(this, response.msg);
						$(formRef).replace("");
						
					}else{
						Dialogs.alert(response.msg);
					}
				}else{
					Dialogs.alert("Something f**ked up, try again later!");
				}
			},
			onFailure: function(){ 
				Dialogs.alert('Something f**ked up, try again later!'); 
			}
		});
	}
}
SubPublic.startDeleteMessage = function(idArr){
	Dialogs.confirm('Really remove this message?', SubPublic.deleteMessage, idArr);
}

SubPublic.deleteMessage = function(idArr){
	new Ajax.Request("/comments/deletemessage", {
		method: 'post',
		parameters: {id:idArr[0], media:idArr[1], mediaid:idArr[2]},
		onSuccess: function(transport){
			if(transport.responseText){
				var response = transport.responseText.evalJSON(true);
				if(response.type == "success"){
					if(response.msg == 15){ // hidden
						$('commentUser_'+ idArr[0]).update('');
						$('commentText_'+ idArr[0]).update('Removed');
					}else if(response.msg == 20){ // deleted
						$('comment_'+ idArr[0]).remove();
					}
				}else{
					Dialogs.alert(response.msg);
				}
			}
		}
	});
}

SubPublic.replyForum = function(formRef, callBack, callParam, clearForm){
	$(formRef).request({
		onSuccess: function(transport){
			if(transport.responseText){
				var response = transport.responseText.evalJSON(true);
				if(response.type == "success"){
					// reset
					if(callBack)
						callBack.call(this, callParam, response.msg);
					if(clearForm)
						$(formRef).reset();
				}else{
					Dialogs.alert(response.msg);
				}
			}else{
				Dialogs.alert("Something f**ked up, try again later!");
			}
		},
		onFailure: function(){ 
			Dialogs.alert('Something f**ked up, try again later!'); 
		}
	});
}

SubPublic.reloadForum = function(url, scrollToId){
	if(scrollToId == "0"){
		new SubPublic.replaceHTMLCallback(url, 'messages');
	}else{
		new SubPublic.replaceHTMLCallback(url, 'messages', SubPublic.scrollToElement, 'comment_'+ scrollToId);
	}
	//setTimeout('SubPublic.scrollToElement("comment_'+ scrollToId +'")', 1);
}
SubPublic.scrollToElement = function(id){
	if($(id)){
		SubPublic.scrollTo(id);
		Effect.SlideDown(id);
	}
}
SubPublic.scrollTo = function(id) {
    var pos = $(id).cumulativeOffset();
    var posX = pos[0] - document.viewport.getWidth() / 2;
    var posY = pos[1] - document.viewport.getHeight() / 2;
    
    window.scrollTo(posX, posY);
    
 }
SubPublic.updateRating = function(id, userVote, updateDiv){
	new Ajax.Request("/tricks/rating?id=" + id + "&difficultyvote=" + userVote, {
		method: 'post',
		parameters: {},
		onSuccess: function(transport){
			$(updateDiv).update(transport.responseText);
		},
		onFailure: function(){ 
			Dialogs.alert("Could not register the vote"); 
		}
	});
}

SubPublic.updateKlick = function(id){
	new Ajax.Request("/verticalbar/updateklicks?id=" + id, {
		method: 'post',
		parameters: {},
		onSuccess: function(transport){
			$(updateDiv).update(transport.responseText);
		},
		onFailure: function(){ 
			Dialogs.alert(""); 
		}
	});
}

SubPublic.updateShow = function(id){
	new Ajax.Request("/verticalbar/updateshow?id=" + id, {
		method: 'post',
		parameters: {},
		onSuccess: function(transport){
			$(updateDiv).update(transport.responseText);
		},
		onFailure: function(){ 
			Dialogs.alert(""); 
		}
	});
}
	
SubPublic.getGnargleNews = function(newsLimit, updateDiv, gnargleId){
	new Ajax.Request("/gnargles/listnews", {
		method: 'post',
		parameters: {limit:newsLimit, id:gnargleId},
		onSuccess: function(transport){
			$(updateDiv).update(transport.responseText);
		},
		onFailure: function(){ 
			Dialogs.alert("Could not register the vote"); 
		}
	});
}	

SubPublic.getNotifications = function(type, offset, limit, insertBeforeDiv){
	
	// 1 -> feed stories
	if(type == 1) {
		var url = "/home/listnotifications";
	}
	// 0 -> personal notifications
	else if(type == 0) {
		var url = "/home/listpersonalnotifications";
	}
	
	var notificationOffset = offset + limit;
	
	new Ajax.Request(url, {
		method: 'post',
		parameters: {offset : notificationOffset},
		onSuccess: function(transport){
			$(insertBeforeDiv).insert({'before' : transport.responseText})			
			if(transport.responseText != "") {
				if(type == 1) //feed stories
					$('more_notifications_link').update('<a class="addLink" style="padding-top:5px; padding-bottom:3px;" onclick="SubPublic.getNotifications(' + 1 + ', ' + notificationOffset + ', ' + limit + ', \'end_of_notifications\');return false;" href="#">+ More Notifications </a>');
				else if(type == 0) //personal notifications
					$('more_personal_notifications_link').update('<a class="addLink" style="padding-top:5px; padding-bottom:3px;" onclick="SubPublic.getNotifications(' + 0 + ', ' + notificationOffset + ', ' + limit + ', \'end_of_personal_notifications\');return false;" href="#">+ More Notifications </a>');
			}
			else {
				if(type == 1) //feed stories
					$('more_notifications_link').update('There are no more notifications.');
				else if(type == 0) //personal notifications
					$('more_personal_notifications_link').update('There are no more personal notifications.');
				
			}	
		},
		onFailure: function(){ 
			Dialogs.alert("Could not get more notifications"); 
		}
	});
}

SubPublic.notLoggedIn = function(msg){
	Dialogs.confirmUrl(msg + '<br /><br />Please <a href="/users/login">Login</a> or <a href="/join">Sign up</a> for an account.<br />I takes about 34 seconds.', "/join", "Sign Up");
}

SubPublic.startDeleteNote = function(type, typeId, noteId){
	url = "/" + type + "/" + typeId + "/news/remove?noteid=" + noteId;
	Dialogs.confirm('Really remove this note?', SubPublic.deleteNote, url);
}

SubPublic.deleteNote = function(url){
	
	//find id-nr
	var regexS = "[\\?&]noteid=([^&#]*)";
	var regex = new RegExp(regexS);
	var noteId = regex.exec(url);

	//get the url back without the remove part...
	var regexUrl = "remove([^&#]*)";
	var regex = new RegExp(regexUrl);
	regex.exec( url );
	var noteUrl = RegExp.leftContext;

	//remove the note
	new Ajax.Request(url, {
		method: 'post',
		onSuccess: function(transport){
			if(transport.responseText){
				var response = transport.responseText.evalJSON(true);
				if(response.type == "success"){
					
					//if i the notes view
					if($('noteNr_'+ noteId[1])) {
						$('noteNr_'+ noteId[1]).remove();
					}
					//if in single note view
					else if($$('.BigMid')) {
 						window.location=noteUrl;
					}
					
				}else{
					Dialogs.alert(response.msg);
				}
			}
		}
	});
}

SubPublic.onlyOneClick = function(disableId, feedbackId, offImg){
	if(disableId != null) {
		//give feedback...
		if(feedbackId != null) {
			var updateVar = '$(\''+feedbackId+'\').update(\'Already propped\').show(); setTimeout(\"$(\'rating_msg\').hide();\", 4000);return false;';
		}
		//... ordisable clicking
		else {
			var updateVar = "return false;";
		}
		$(disableId +"Img").src = offImg;
		//update link/buttons click event
		$(disableId).writeAttribute('onclick', updateVar);
	}
}

// Countdown for main competition
function checkTimeZone() {
   var rightNow = new Date();
   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);
   return hoursDiffDaylightTime;
}

var compFinishDate;
function startCountDown(pCompFinishDate){
	compFinishDate = pCompFinishDate;
	countDownComp();
}
function countDownComp(){
	var PDT = -7;
	var finishDate = new Date(compFinishDate);
	finishDate.setHours(19 - PDT + checkTimeZone());
	var currentDate = new Date();
	var timeDiff = finishDate.getTime() - currentDate.getTime();
	var days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
	var hours = Math.floor(timeDiff / (1000 * 60 * 60)) % 24;
	var minutes = Math.floor(timeDiff / (1000 * 60)) % 60;
	var seconds = Math.floor(timeDiff / (1000)) % 60;
	
	//$('datecounter').update(finishDate.getTime() +":"+ currentDate.getTime());
	if(timeDiff > 0){
		$('datecounter').update('<font style="font-size: 17px; color: #3BCEFF; font-weight: bold">'+ days +'</font><span class="tiny extraInfo">d</span> <font style="font-size: 17px; color: #3BCEFF; font-weight: bold">'+ hours +'</font><span class="tiny extraInfo">h</span> <font style="font-size: 17px; color: #3BCEFF; font-weight: bold">'+ minutes +'</font><span class="tiny extraInfo">m</span> <font style="font-size: 17px; color: #3BCEFF; font-weight: bold">'+ seconds +'</font><span class="tiny extraInfo">s</span>');
	}else{
		$('datecounter').update('');	
	}
	setTimeout('countDownComp()', 1000);
}


var Dialogs = {}; 

var mainInit = function(){
	Dialogs = new Dialog.Boxes();
	if($('loginemail') && $('loginpass')){
		Event.observe($('moremenulink'), 'mouseover', 	hideLoginForm.bindAsEventListener());
		Event.observe($('moremenulink'), 'mouseout', 	showLoginForm.bindAsEventListener());
	}
}
function hideLoginForm(){
	$('loginemail').hide();
	$('loginpass').hide();
}
function showLoginForm(){
	$('loginemail').show();
	$('loginpass').show();
}
function loginMark(){
	if($F('loginemail') == "E-mail adress"){
		$('loginemail').value = "";
	}else{
		$('loginemail').select();
	}
}
function loginBlur(){
	if($F('loginemail') == ""){
		$('loginemail').value = "E-mail adress";
	}
}
function passwordMark(){
	if($F('loginpass') == "tlnvtyds"){
		$('loginpass').value = "";
	}else{
		$('loginpass').select();
	}
}
function passwordBlur(){
	if($F('loginpass') == ""){
		$('loginpass').value = "tlnvtyds";
	}
}
function checkLoginReset(){
	if($F('loginemail') == "E-mail adress")
		$('loginemail').value = "";
	if($F('loginpass') == "tlnvtyds")
		$('loginpass').value = "";
}
function setSignUp(){
	checkLoginReset();
	if($F('loginemail') == "" && $F('loginpass') == ""){
		window.location = "/join";
	}else{
		$("loginform").action = "/join";
		$("loginform").submit();
	}
}
