var validForm = true;


// Show title tooltips
$(function() {
	addTooltip();
});

function addTooltip() {
	$('.titleTooltip').each(function(){
		var titleDiv = this;
		$(titleDiv).tooltip({ 
			position: "top right",
			opacity: 0.98,
			predelay: 800,
			delay:400,
			tip: "#tooltip",
			effect: "slide",
			offset: [240,10],
			onBeforeShow: function() {titleTooltipContent(titleDiv.id);}
		}).dynamic();
	});
	
	function titleTooltipContent(titleDivId) {
		$("#tooltip").html('Laddar…');
		$.ajax({
			method: "get",
			url: "titleTooltip.php",
			data: "titleid=" + titleDivId,
			beforeSend: function() { },
			complete: function() { },
			error: function() { $("#tooltip").html("error."); },
			success: function(result) { $("#tooltip").html(result); }
		});
	}
}



// Show form tooltips
$(function() {
	addFormTooltip();
});

function addFormTooltip() {
	$('.formTooltip').each(function(){
		var dom = this;
		$(dom).tooltip({ 
			position: "top right",
			opacity: 0.98,
			predelay: 800,
			delay: 1000,
			tip: "#tooltip",
			effect: "slide",
			offset: [20,20],
			onBeforeShow: function() {formTooltipContent(dom.dataset.url,dom.dataset.id);}
		}).dynamic();
	});
	
	function formTooltipContent(url,id) {
		$("#tooltip").html('Laddar…');
		$.ajax({
			method: "get",
			url: url+'.php',
			data: "id="+id,
			beforeSend: function() { },
			complete: function() { },
			error: function() { $("#tooltip").html("error."); },
			success: function(result) { $("#tooltip").html(result); }
		});
	}
	
	$("#tooltip form").live("submit",function(e) {
		e.preventDefault();
		var dom = this;
		$.ajax({
			method: "get",
			url: $(dom).attr("action"),
			data: $(dom).serialize(),
			beforeSend: function() { },
			complete: function() { },
			error: function() { $("#tooltip").html("error."); },
			success: function(result) { 
				//alert(result);
				if (result == "success") {
					$("#tooltip").html('<div class="formTooltipMessage">Sparat!</div>'); 
					$("#tooltip").slideUp(1500);
				} else {
					$("#tooltip").html('<div class="formTooltipMessage">error.</div>'); 
					$("#tooltip").slideUp(1500);
				}
			}
		});
	});
}






//Set titlescore on load
$(function() {
	if ($("#scoreStars").length) {
		showCurrentStars();
	}
});

//Scorestars on mouse over
$(function() {
	$("#scoreStars img").live("mouseover",function() {
		var dom = this;
		$("#scoreStars img").each(function(index) {
			if (parseInt(dom.dataset.score) >= (index+1)) {
				$(this).attr("src","img/star_3.png");
			} else {
				$(this).attr("src","img/star_2.png");
			}
		});
	});
});

//Scorereturn on mouse out
$(function() {
	$("#scoreStars img").live("mouseout",function() {
		showCurrentStars();
	});
});

//When clicking a star
$(function() {
	$("#scoreStars img").live("click",function() {
		setScore($("#titleid").val(),this.dataset.score);
	});
});

//Delete a score
$(function() {
	$("#scoreDelete").live("click",function() {
		if (confirm('Är du säker på att du vill radera ditt betyg?')) {
			setScore($("#titleid").val(),"x");
		}
	});
});

//Abort a title
$(function() {
	$("#scoreAborted").live("click",function() {
		setScore($("#titleid").val(),0);
	});
});

//Show stars
function showCurrentStars() {
	$("#scoreStars img").each(function() {
		if (currentScore == "x") {
			$(this).attr("src","img/star_1.png");
		} else if (currentScore == 0) {
			$(this).attr("src","img/star_0.png");
		} else if (parseInt(this.dataset.score) > currentScore) {
			$(this).attr("src","img/star_2.png");
		} else {
			$(this).attr("src","img/star_3.png");
		}
	});
	setScoreText();
}

//Send score to be saved
function setScore(titleid,score) {
	$.ajax({
		method: "get",
		url: "setScore.php",
		data: "titleid=" + titleid + "&score=" + score,
		error: function() {$("#scoreText").html('error');},
		success: function(result) {
			if (result == "success") {
				currentScore = score;
				showCurrentStars();
			} else {
				$("#scoreText").html('error');
			}
		}
	});	
}

//Update score text
function setScoreText() {
	if (currentScore == 0) {
		$("#scoreText").html('<span class="likeALink" id="scoreDelete">Ta bort som Avslutad</a>');
	} else if (currentScore > 0) {
		$("#scoreText").html(currentScore + ' av 10 <span class="likeALink" id="scoreOptionsLink">Betygsalternativ</span> <span class="likeALink" id="scoreDelete">Radera betyg</span>');
	} else { //currentScore = x
		$("#scoreText").html('Ej betygsatt &nbsp; <span class="likeALink" id="scoreAborted">Avslutad</a>');
	}
}


// Show/Hide scoreoptions
$(function(){
	var wipeLink = $("#scoreOptionsLink"),
		wipeTarget = $("#scoreOptions"),
		wipeStatus = 0;
 
	//$(wipeLink).click(function(){
	$(wipeLink).live("click",function() {
		if (wipeStatus == 0) {
			wipeStatus = 1;			
			wipeTarget.css('opacity', 0)
  			.slideDown('slow')
  			.animate(
    			{ opacity: 1 },
    			{ queue: false, duration: 'slow' }
 		 	);
		} else {
			wipeStatus = 0;
			wipeTarget.css('opacity', 1)
  			.slideUp('slow')
  			.animate(
    			{ opacity: 0 },
    			{ queue: false, duration: 'slow' }
 		 	);
		}
	});
});

	

// Add date value to score options
$(function() {
	var scoreDateYMD = $("#scoreDateYMD"),
		scoreDateYM = $("#scoreDateYM"),
		scoreDateY = $("#scoreDateY"),
		scoreDate = $("#scoreDate"),
		d = new Date();
		
	$(scoreDateYMD).click(function() {
		$(scoreDate).val(d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).substr(-2,2) + '-' + ('0' + (d.getDate()+1)).substr(-2,2));
	});
	$(scoreDateYM).click(function() {
		$(scoreDate).val(d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).substr(-2,2));
	});
	$(scoreDateY).click(function() {
		$(scoreDate).val(d.getFullYear());
	});
});



// Blink target 
function myBlink (id) {
	$(id).animate({opacity: 0.25}, 50, function(){})
		.animate({opacity: 1.00}, 50, function(){})
		.animate({opacity: 0.25}, 50, function(){})
		.animate({opacity: 1.00}, 50, function(){})
		.animate({opacity: 0.25}, 50, function(){})
		.animate({opacity: 1.00}, 50, function(){})
		.animate({opacity: 0.25}, 50, function(){})
		.animate({opacity: 1.00}, 50, function(){})
		.animate({opacity: 0.25}, 50, function(){})
		.animate({opacity: 1.00}, 50, function(){});
}



// Scroll title pictures
$(function() {
	$("#titleImagesScrollRight").click(function(){
	  $("#titleImagesContentImages").animate({"left": "-=150px"}, "fast");
	});

	$("#titleImagesScrollLeft").click(function(){
	  $("#titleImagesContentImages").animate({"left": "+=150px"}, "fast");
	});
});




//Form validations
$(function() {
	//Tid och datum
	$.tools.validator.fn("[type=tdate]", "Fel format på datum", function(input, value) {
		if (!value) {
			return true;
		} else {
			return /^[1-2][0-9]{3}(-[0-9]{2}){0,2}$/.test(value);
		}
	});

	//Scoreoptions
	$("#scoreOptionsForm").validator({
			position: 'top left', 
			offset: [-8, -30],
			message: '<div><em/></div>' // em element is the arrow
		}).submit(function(e) {
		var form = $(this);
		
		if (!e.isDefaultPrevented()) {
			e.preventDefault();
			$.ajax({
				method: "get",
				url: "setScoreOptions.php?id=" + $("#titleid").val(),
				data: form.serialize(),
				success: function(result) {
					if(result == "success") {
						myBlink("#scoreOptions");
						$("#scoreOptionsLink").click();
					} else {
						console.log(result);
					}
				}
			});
		}
	});
});


//Tabs
$(function() {
	$("ul.tabs").tabs("div.pane > div", {effect: 'ajax'});
});

function refreshTab(index) {
	var api = $("ul.tabs").data("tabs");
	var pane = api.getPanes();
	pane.load(api.getTabs().eq(index).attr("href"));
}



//Change shelf list options
$(function() {
	$("#shelfListOptions").change(function() {
		dom = this;
		value = dom.value;
		$.ajax({
			method: "get",
			url: "setSessions.php",
			data: "slo=" + value,
			success: function(result) {
				if (result == "1") {
					window.location.reload();
				}
			}
		});
	});
});





//Shelf playing now
$(function() {
	$("#shelfList input[name=playing_now]").live("click",function() {
		checkbox = $(this);
		$.ajax({
			method: "get",
			url: "shelfPlayingNow.php",
			data: "shelfid=" + $(this).closest("tr").attr("id") + "&val=" + $(checkbox).is(":checked"),
			success: function(result) {
				if (result == "success") {
					myBlink($(checkbox).closest("td"));
				}
			}
		});
	});
});


//Shelf process
$(function() {
	$("#shelfList select[name=process]").live("change",function() {
		select = $(this);
		$.ajax({
			method: "get",
			url: "shelfProcess.php",
			data: "shelfid=" + $(this).closest("tr").attr("id") + "&val=" + $(select).val(),
			success: function(result) {
				console.log(result);
				if (result == "success") {
					myBlink($(select).closest("td"));
				}
			}
		});
	});
});


//Add to shelf
$(function() {
	$("#addToShelf").live("change",function() {
		id = $("#titleid").val();
		select = $(this);
		console.log(id);
		console.log($(select).val());
		$.ajax({
			method: "get",
			url: "addToShelf.php",
			data: "titleid=" + id + "&platform=" + $(select).val(),
			success: function(result) {
				if (result == "success") {
					fillTitleShelfContent(id,1);
					$(select).val("");
				}
			}
		});
	});
});


//Shelf delete
$(function() {
	$(".deleteFromShelf").live("click",function() {
		dom = $(this);
		id = ($(dom).attr("id")) ? $(dom).attr("id") : $(dom).closest("tr").attr("id");
		if(confirm("Är du säker på att du vill ta bort " + $(dom).attr("title") + " från din samling?\n\nHar du sålt titeln kan du istället fylla i priset du fick under Alternativ så spars det under fliken Sålda.")) {
			$.ajax({
				method: "get",
				url: "deleteFromShelf.php",
				data: "shelfid=" + id,
				success: function(result) {
					if (result == "success") {
						fillTitleShelfContent(id,1);
						if($(dom).attr("id")) {
							myBlink($(dom));
							$(dom).fadeOut('slow');
						} else {
							myBlink($(dom).closest("tr"));
							$(dom).closest("tr").fadeOut('slow');
						}
					}
				}
			});
		}
	});
});


// Fill title shelf content with content
function fillTitleShelfContent(titleid,blink) {
	$("#titleShelfContent").load("titleShelfContent.php?titleid=" + titleid, function() {
		if(blink == 1) {
			myBlink($(this));
		}
	});
}



//Shelf options
$(function() {
	$(".shelfOptions").live("click",function() {
		dom = $(this);
		$id = $(dom).closest("tr").attr("id");
		$.ajax({
			method: "get",
			url: "shelfOptions.php",
			data: "shelfid=" + $id,
			error: function() {alert('Kommer snart…');},
			success: function(result) {
				if (result == "success") {
					
				}
			}
		});
	});
});



//Placeholder compatibility
$(function() {
	$('[placeholder]').focus(function() {  
		var input = $(this);  
		if (input.val() == input.attr('placeholder')) {  
			input.val('');  
			input.removeClass('placeholder');  
		}  
	}).blur(function() {  
		var input = $(this);  
		if (input.val() == '') {  
			input.addClass('placeholder');  
			input.val(input.attr('placeholder'));  
		}  
	}).blur();
});



//Note delete
$(function() {
	$(".deleteNote").live("click",function() {
		dom = this;
		if(confirm("Är du säker på att du vill ta bort \"" + dom.dataset.title + "\" från din anteckningar?")) {
			myBlink(dom);
			window.location.href = "memberNotesDelete.php?noteid="+dom.dataset.id;
		}
	});
});



//Newsfeed delete
$(function() {
	$(".deleteFromNewsfeed").live("click",function() {
		dom = this;
		id = this.dataset.newsfeedid;
		if(confirm("Är du säker på att du vill ta bort denna rad?")) {
			$.ajax({
				method: "get",
				url: "deleteFromNewsfeed.php",
				data: "newsfeedid=" + id,
				success: function(result) {
					console.log(result);
					if (result == "success") {
						myBlink($(dom).closest("div"));
						$(dom).closest("div").fadeOut('slow');
					}
				}
			});
		}
	});
});



//Uppdatera att man är online och även visa nya gruppmeddelanden/forum

function statusUpdate() {
	$.ajax ({
		method: "get",
		url: "statusUpdate.php",
		success: function(result) {
			$("span[id^=menuGroup]").html("");
			document.title = 'Tjockapa';
			resultSplit = result.split('|');
			
			var newGroupMsg = 0;
			var newForumMsg = '';
			for (i = 0; i < resultSplit.length; i++) {
				resultSplitSplit = resultSplit[i].split(',');
				if (resultSplitSplit[0] == 'all') {
					if (resultSplitSplit[1] > 0) {
						newGroupMsg = resultSplitSplit[1];
						$("#menuGroups").html('(' + resultSplitSplit[1] + ')');
					}
				} else if (resultSplitSplit[0] == 'forum') {
					if (resultSplitSplit[1] == 1) {
						newForumMsg = "*";
						$("#menuForum").addClass("underline");
					} else {
						$("#menuForum").removeClass("underline");
					}
				} else {
					if ($("#menuGroup"+resultSplitSplit[0]).length > 0) {
						$("#menuGroup"+resultSplitSplit[0]).html(' (' + resultSplitSplit[1] + ')');
					}
				}
			}
			
			if (newGroupMsg || newForumMsg) {
				document.title = ((newGroupMsg>0)?'(' + newGroupMsg + ')':'') + newForumMsg + 'Tjockapa';
			
			}
		}
	});
}



//Visa online/aktiv-status i en grupp
var groupid;
function updateGroupMembers(groupid) {
	$.ajax ({
		method: "get",
		url: "groupMemberStats.php",
		data: "groupid=" + groupid,
		success: function(result) {
			$("#groupMembers").html(result);
		}
	});
}

//Räkna och begränsa fält
function countChar(val,max) {
	var len = val.value.length;
	if (len >= max) {
		val.value = val.value.substring(0, max);
	} else {
		$('#countChar').html(max - len);
	}
}


//Ändra intresse för en titel
$(function () {
	$(".changeChecklist").live("change",function() {
		dom = $(this);
		titleid = this.dataset.titleid;
		value = this.value
		$.ajax ({
			method: "get",
			url: "checklistSave.php",
			data: "titleid=" + titleid + "&value=" + value,
			success: function(result) {
				if (result) {
					myBlink(dom);
					if (value == 0 && $("#titleid").length == 0) {
						$(dom).closest("tr").fadeOut('slow');
					}
				}
			}
		});
	});
});

//Change checklist options
$(function() {
	$("#checklistOptions").change(function() {
		dom = this;
		value = dom.value;
		$.ajax({
			method: "get",
			url: "setSessions.php",
			data: "clo=" + value,
			success: function(result) {
				if (result == "1") {
					window.location.reload();
				}
			}
		});
	});
});



//Tobuy delete
$(function() {
	$(".deleteTobuy").live("click",function() {
		dom = this;
		if(confirm("Är du säker på att du vill ta bort \"" + dom.dataset.title + "\"?")) {
			$.ajax({
				method: "get",
				url: "tobuySave.php",
				data: "delete=" + dom.dataset.id,
				success: function(result) {
					if (result == "1") {
						myBlink(dom);
						$(dom).closest("tr").fadeOut('slow');
					}
				}
			});
		}
	});
});



//Menu
$(function() {
	var subMenuTimeout;	
	$(".showSubMenu").mouseenter(function() {
		clearTimeout(subMenuTimeout);
		$(".subMenu").css("display","none");
		$(this).children(".subMenu").css("display","inline");
	});
	$(".showSubMenu").mouseleave(function() {
		var dom = this;
		subMenuTimeout = setTimeout(function(){
			$(dom).children(".subMenu").css("display","none");
		}, 1000);
	});
	$(".subMenu").mouseenter(function() {
		clearTimeout(subMenuTimeout);
		$(this).children(".subMenu").css("display","inline");
	});
	$(".subMenu").mouseleave(function() {
		$(this).children(".subMenu").css("display","none");
	});
});



//Scroll menu along
$(function() {
	var el=$('#menu');
	var elpos=el.offset().top;
	$(window).scroll(function () {
    	var y=$(this).scrollTop();   	
    	if(y<elpos){el.css({'top':54,'position':'absolute'});}
    	else{el.css({'top':'0','position':'fixed','left':'50%','margin-left':'-472px'});}
	});
});
















//Ändra om en medlem är grupp-godkänd
function changeApproved(id,approved) {
	location.href = 'groupEditSave.php?id=' + id + '&approved=' + approved;
}





//Ändra lager-display
function switchDisplay(that) {
	thatLayer = document.getElementById(that).style;
	if (thatLayer.display == 'block') {
		thatLayer.display = 'none';
	} else {
		thatLayer.display = 'block';
	}
}


//Dölj ett objekt
function hideThis(that) {
	that.style.display='none';
}



//Förstorning utav titelbilder
function picPreview(pic) {
	picDiv = document.getElementById('picPreview');
	picDiv.style.display='block';
		
	var yScroll = 0;
	var yHeight = 0;
	if (window.innerHeight && window.scrollMaxY) {	
		yScroll = window.pageYOffset;
		yHeight = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){
		yScroll = document.body.scrollTop;
		yHeight = document.body.scrollHeight;
	} else { 
		yScroll = document.documentElement.scrollTop;
		yHeight = document.body.offsetHeight;
	}

	picDiv.style.height = (yHeight - yScroll - 35) + 'px';
	picDiv.style.paddingTop = (yScroll + 35) + 'px';
	picDiv.innerHTML = '<img src="' + pic + '" alt="Förhandstitt" />';
}

//Stänga förstorning av titelbilder
function picPreviewClose() {
	picDiv = document.getElementById('picPreview');
	picDiv.style.display='none';
}




function groupChatLinks() {
	window.open(document.getElementById('groupChatLinks').value);
	document.getElementById('groupChatLinks').value = '';
}


//Ajax-funktion för att trigga xml
function xmlHttpFunction() {
    var xmlHttp;
  
    try {
      // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
    }
  
    catch (e) {
      // Internet Explorer
      try {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    
      catch (e) {
        try {
          xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    
        catch (e) {
          alert("Your browser does not support AJAX!");
          xmlHttp = false;
        }
      }
    }
    
    return xmlHttp;
}








//Lägga till som vän
function addFriend(id) {

	xmlHttp = xmlHttpFunction();
	var saveStatus;
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			saveStatus = xmlHttp.responseText;
			if (saveStatus == 1) {
				document.getElementById('friends').innerHTML = 'Tillagd som vän';
			}
		}
	}
	xmlHttp.open("GET","friendSave.php?id="+id,true);
	xmlHttp.send(null);	
}








$(function (){
	statusUpdate();
	interval = setInterval('statusUpdate()', 60*1000);
	interval2 = setInterval('updateGroupMembers(' + groupid + ')', 60*1000);
});





