
$(document).ready(function(){
	if ($('#latestvideosanim').length) setInterval('FadeOut("#lastestvideosanim")', 8000);

	// MEMBER LOGIN FANCYBOX PLUGIN. less obtrusive.
	if ($.fancybox)
	$('#loginButton').fancybox({
		padding : 0,
		autoDimensions: false,
		height: 260,
		width: 360,
		titleShow : false,
		content : '<h2 class="fancybox-h2">Login</h2>'+
	'<form action="modules/public/login/login.php" method="post" onsubmit="resultCallLogin();return false;">'+
	'<span id="msgrequired" style="display:none;color:#c33;">Both email and password are required; Please fill them out.</span>' +
	'<p><span id="msgformat" style="display:none;color:#c33;">Probably you misspeled your email. Please check it out.</span></p>'+
	'<p><label style="width:60px;display:inline-block;">E-mail</label> <input type="text" id="logininput" name="logininput" autofocus/></p>' +
	'<p><label style="width:60px;display:inline-block;">Password</label> <input type="password" id="passwordinput" name="passwordinput" /></p>'+
	'<p><a href="registration.php">New User?</a> <a href="forgotpassword.php">Forgot Password?</a></p><p><input type="submit" value="Login" /></p></form>'
	});

});

function FadeOut(divid){
	$(divid).fadeOut(500);
	setTimeout('CallChangeLatest()', 500);
}

function CallChangeLatest(){
	document.getElementById("lastestvideosanim").style.display = "none";
	ChangeLatestVideo();
}

function FadeIn(divid){
	$(divid).fadeIn(500);
}

function ChangeLatestVideo(){
	$.ajax({
		type: 'POST',
		url: "modules/public/videos/changeLatestvideos.php",
		success: function(data){
			document.getElementById("lastestvideosanim").innerHTML = data;
			FadeIn('#lastestvideosanim');
		}
	});
}

function ValidateNewsletterForm(){
	var val = 0;
	var title = ValidateEmail("newsletterinput", "msgnewsletter");
	if (!title) {
		val = 1;
	}
	if (val == 1) {
		return false;
	} else {
		$.ajax({
			type: 'POST',
			url: "modules/public/newsletter/insert.php?mail=" + document.getElementById("newsletterinput").value,
			success: resultNewsletterForm
		});
	}
}

function resultNewsletterForm(){
	document.getElementById("msgnewsletter").innerHTML = "E-mail successfully saved.";
	document.getElementById("newsletterinput").value = "";
	setTimeout("HideSpan('msgnewsletter')", 5000);
}


function ValidateSearchForm(){

	if (document.getElementById("searchinput").value == "") {
		return false;
	} else {
		$.ajax({
			type: 'POST',
			url: "modules/public/search/search.php?word=" + document.getElementById("searchinput").value,
			success: resultSearchForm
		});
	}
	
}

function ValidateForgotPassword(){
	var val = 0;
	var title = ValidateEmail("forgotpassinput", "msgforgotpass");
	if (!title) {
		val = 1;
	}
	if (val == 1) {
		return false;
	} else {
		$.ajax({
			type: 'POST',
			url: "modules/public/registration/forgotpassword.php?mail=" + document.getElementById("forgotpassinput").value,
			success: function(data){
				if (data == 1) {
					document.getElementById("forgotpassinput").value = "";
					document.getElementById("msgforgotpass").innerHTML = "New password generated successfully. Please visit your e-mail.";
					setTimeout("HideSpan('msgforgotpass')", 5000);
				} else {
					document.getElementById("msgforgotpass").innerHTML = "It was not possible to generate another password. Try again later.";
					setTimeout("HideSpan('msgforgotpass')", 5000);
				}
			}
		});
	}
}

function resultSearchForm(){
	window.location = 'search.php';
}

function HideSpan(div){
	document.getElementById(div).innerHTML = "";
}

function ValidateEmail(idinput, msgid){
	if (document.getElementById(idinput).value == "") {
		document.getElementById(msgid).innerHTML = "Required Field";
		setTimeout("HideSpan('" + msgid + "')", 5000);
		return false;
	} else {
		if (validEmail(document.getElementById(idinput).value)) {
			document.getElementById(msgid).innerHTML = "";
			return true;
		} else {
			document.getElementById(msgid).innerHTML = "Invalid Format";
			setTimeout("HideSpan('" + msgid + "')", 5000);
			return false;
		}
	}
}

function validEmail(str){
	var at = "@"
	var dot = "."
	var lat = str.indexOf(at)
	var lstr = str.length
	var ldot = str.indexOf(dot)
	if (str.indexOf(at) == -1) {
		return false
	}
	if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
		return false
	}
	
	if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
		return false
	}
	if (str.indexOf(at, (lat + 1)) != -1) {
		return false
	}
	if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
		return false
	}
	if (str.indexOf(dot, (lat + 2)) == -1) {
		return false
	}
	if (str.indexOf(" ") != -1) {
		return false
	}
	return true
}


function CallVideoOnload(){
	flowplayer("a.player", "http://dev.iuz.pt/capview/images/flowplayer/flowplayer.swf", {
		clip: {
			autoPlay: false,
			autoBuffering: true
		}
	});
}

function CallLogin(){
	$.prompt('<h2 style="background: url(\'images/layout/login_title.jpg\') no-repeat; height:22px; display: block; text-indent:-9999px">Login</h2>'+
	'<form action="modules/public/login/login.php" method="post" onsubmit="resultCallLogin();return false;">'+
	'<span id="msgrequired" style="display:none;color:#c33;">Both email and password are required; Please fill them out.</span>' +
	'<p><span id="msgformat" style="display:none;color:#c33;">Probably you misspeled your email. Please check it out.</span></p>'+
	'<p><label style="width:60px;display:inline-block;">E-mail</label> <input type="text" id="logininput" name="logininput" /></p>' +
	'<p><label style="width:60px;display:inline-block;">Password</label> <input type="password" id="passwordinput" name="passwordinput" /></p>'+
	'<p><a href="registration.php">New User?</a> <a href="forgotpassword.php">Forgot Password?</a></p></form>', {
		submit: resultCallLogin,
		buttons: {
			Ok: true,
			Cancel: false
		}
	});
	$("#logininput").get(0).focus();
}

function fancyboxlogin() {
	if ($('#logininput').val() != '' && $('#passwordinput').val() != '') {
		$('#msgrequired:visible').slideUp(300);
	} else {
		$('#msgrequired:hidden').slideDown(300);
		return false;
	}
	if (validEmail($('#logininput').val())) {
		$('#msgformat:visible').slideUp(300);
	} else {
		$('#msgformat:hidden').slideDown(300);
		return false;
	}

	$("#msgrequired,#msgformat").hide();

	$.ajax({
		type: 'post',
		url: "modules/public/login/login.php?username=" + $('#logininput').val() + "&password=" + hex_md5($('#passwordinput').val()),
		success: function(data){
			if (data == "0") {
				window.location = "community";
			} else {
				$('#msgrequired').before('<p class="flash alert">Your username / password combination didn\'t match.</p>');
				$(".flash.alert").hide().slideDown(300);
				setTimeout(function() {
					$('.flash.alert').slideUp(300); setTimeout(function() {
						$('.flash.alert').remove();}, 300); },2000);
			}
		}
	});
}

function resultCallLogin(v, m, f){
	return fancyboxlogin();
	if (v != false) {
		if (f.logininput == "" || f.passwordinput == "") {
			document.getElementById("msgrequired").style.display = "";
			document.getElementById("msgformat").style.display = "none";
			return false;
		} else {
			var valmail = validEmail(f.logininput);
			if (valmail) {
				$.ajax({
					type: 'POST',
					url: "modules/public/login/login.php?username=" + f.logininput + "&password=" + hex_md5(f.passwordinput),
					success: function(data){
						if (data == "0") {
							window.location = "community";
						} else {
							$.prompt('<img src="images/layout/login_title.jpg" /><br/><span style="color:#FF0000;">Username/Password incorrect</span>' +
							'<span id="msgrequired" style="display:none;color:#FF0000;">Required Fields</span>' +
							'<span id="msgformat" style="display:none;color:#FF0000;">Invalid Format</span><table><tr>' +
							'<td width="90px">Username</td><td><input type="text" id="logininput" name="logininput" /></td></tr>' +
							'<tr><td>Password</td><td><input type="password" id="passwordinput" name="passwordinput" /></td></tr><tr><td></td><td><a href="registration.php">New User?</a> <a href="forgotpassword.php">Forgot Password?</a></td></tr></table>', {
								submit: resultCallLogin,
								buttons: {
									Ok: true,
									Cancel: false
								}
							});
						}
					}
				});
			} else {
				document.getElementById("msgrequired").style.display = "none";
				document.getElementById("msgformat").style.display = "";
				return false;
			}
		}
		
	}
}

function CallLogout(){
	window.location = 'modules/public/login/logout.php';
}

function CallRemoveNewsletter(iduser){
	$.ajax({
		type: 'POST',
		url: "modules/public/newsletter/unsubscribe.php?id=" + iduser,
		success: resultRemoveNewsletter
	});
}

function resultRemoveNewsletter(){
	history.go(0);
}

function ValidateText(idinput, idlabel){
	if (document.getElementById(idinput).value == "") {
		document.getElementById(idlabel).style.color = "#FF0000";
		return false;
	} else {
		document.getElementById(idlabel).style.color = "#666";
		return true;
	}
}


function CallGoogleMaps(urlparam, id){
	if (!id) {
		id = 0;
	}
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(37.4419, -122.1419), 13);
		GDownloadUrl("http://dev.iuz.pt/capview/modules/admin/modules/members/" + urlparam + "?&id=" + id, function(data){
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			
			function createMarker(point, index, name, job, institution){
			
				var marker = new GMarker(point);
				GEvent.addListener(marker, "click", function(){
					marker.openInfoWindowHtml("<b>" + name + "</b><br/>" + job + "<br/>" + institution + "<br/>");
				});
				return marker;
			}

			for (var i = 0; i < markers.length; i++) {
				var latlng = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
				map.addOverlay(createMarker(latlng, i, markers[i].getAttribute("name"), markers[i].getAttribute("job"), markers[i].getAttribute("institution")));
				
			}
			map.setUIToDefault();
		});
		
	}
}

function SearchDetect(val){

	if (val != 0) {
		if (val == "name") {
			document.getElementById("textsearch").style.display = "";
			document.getElementById("keywordssearch").style.display = "none";
		} else {
			document.getElementById("textsearch").style.display = "none";
			document.getElementById("keywordssearch").style.display = "";
		}
	} else {
		document.getElementById("searchbuttontd").style.display = "none";
		document.getElementById("textsearch").style.display = "none";
		document.getElementById("keywordssearch").style.display = "none";
	}
}

function UpdateGoogleMaps(){
	var val = document.getElementById("searchform").value;
	var word = document.getElementById("searchmemberinput").value;
	if (val == "name") {
		CallGoogleMaps("getMembersText.php?value=" + word);
	} else {
	
		var p = document.searchcommunity;
		var par = "";
		
		for (i = 0; i < p.elements.length; i++) {
			if (p.elements[i].type == "checkbox") {
				if (p.elements[i].checked == true) {
					par += "&arr[]=" + p.elements[i].value;
				}
			}
		}
		CallGoogleMaps("getMembersKeywords.php?" + par);
	}
}

function ShowOption(idtr, hidediv){
	if (hidediv == "optionRadioURL") {
		document.getElementById("urlinput").value = "";
	} else {
		document.getElementById("fileupload").value = "";
	}
	document.getElementById(hidediv).className = "hide";
	document.getElementById(idtr).className = "";
}

function ChangedUpload(){
	document.getElementById("changedupload").value = "1";
}

function ValidateVideosForm(){
	var val = 0;
	var title = ValidateText("titleinput", "titlelabel");
	if (!title) {
		val = 1;
	}
	var size = ValidateText("sizeinput", "sizelabel");
	if (!size) {
		val = 1;
	}
	var duration = ValidateText("durationinput", "durationlabel");
	if (!duration) {
		val = 1;
	}
	var year = ValidateText("yearinput", "yearlabel");
	if (!year) {
		val = 1;
	}
	if (document.getElementById("imageinput").value == "" && document.getElementById("imgname").value == "") {
		val = 1;
		document.getElementById("imagelabel").style.color = "#FF0000";
	} else {
		document.getElementById("imagelabel").style.color = "#666";
	}
	var pubup = ValidateText("publishupinput", "publishuplabel");
	if (!pubup) {
		val = 1;
	}
	var pubdown = ValidateText("publishdowninput", "publishdownlabel");
	if (!pubdown) {
		val = 1;
	}
	var classurl = document.getElementById("optionRadioURL").className;
	if (classurl != "hide") {
		var urlfile = ValidateText("urlinput", "documentlabel");
		if (!urlfile) {
			val = 1;
		}
	} else {
		if (document.getElementById("changedupload").value == "0") {
			var uploadfile = ValidateText("filename", "documentlabel");
			if (!uploadfile) {
				val = 1;
			}
		} else {
			var uploadfile = ValidateText("fileupload", "documentlabel");
			if (!uploadfile) {
				val = 1;
			}
		}
	}
	if (val == 1) {
		return false;
	} else {
		document.myvideosform.submit();
	}
}

function VideosFunction(){
	$('#publishupinput, #publishdowninput').datepicker($.extend({
		dateFormat: 'yy-mm-dd',
		showOn: 'both',
		buttonImage: 'images/jquery/datepicker/calendar.gif',
		buttonImageOnly: true
	}));
}

function SelectVideo(vid){
	if (vid != 0) {
		window.location = "myvideos.php?id=" + vid;
	}
}

function DeleteVideo(){
	$.prompt('<h3><img src="http://dev.iuz.pt/capview/images/jquery/warn.jpg" /> <b>WARNING</b></h3><br/>These items will be permanently deleted and cannot be recovered.<br/>Are you sure you want to proceed?', {
		callback: resultDeleteVideo,
		buttons: {
			Delete: document.getElementById("identry").value,
			Cancel: false
		}
	});
}

function resultDeleteVideo(v, m){
	if (v != false) {
		window.location = 'modules/public/myvideos/delete.php?val=' + v;
	}
}

function CallVideoDetails(id){
	window.location = 'modules/public/videos/vote.php?id=' + id;
}

function CallPlayer(file, type){

	if (type == "file") {
		videoname = "http://dev.iuz.pt/capview/media/videos/" + file;
	} else {
		videoname = file;
	}
	
	flowplayer("a.player", {src: 'flash/flowplayer.swf', wmode: 'opaque'}, {
		clip: {
			url: videoname,
			autoPlay: false,
			autoBuffering: true
		}
	});
}

var vid;
function CallVote(star, video){
	var starcount = "";
	
	if (star == 0) {
		starcount = "<img src='images/layout/star_lightgrey.gif' /><img src='images/layout/star_lightgrey.gif' /><img src='images/layout/star_lightgrey.gif' /><img src='images/layout/star_lightgrey.gif' />";
	} else if (star == 1) {
		starcount = "<img src='images/layout/star_darkgrey.gif' /><img src='images/layout/star_lightgrey.gif' /><img src='images/layout/star_lightgrey.gif' /><img src='images/layout/star_lightgrey.gif' />";
	} else if (star == 2) {
		starcount = "<img src='images/layout/star_darkgrey.gif' /><img src='images/layout/star_darkgrey.gif' /><img src='images/layout/star_lightgrey.gif' /><img src='images/layout/star_lightgrey.gif' />";
	} else if (star == 3) {
		starcount = "<img src='images/layout/star_darkgrey.gif' /><img src='images/layout/star_darkgrey.gif' /><img src='images/layout/star_darkgrey.gif' /><img src='images/layout/star_lightgrey.gif' />";
	} else if (star == 4) {
		starcount = "<img src='images/layout/star_darkgrey.gif' /><img src='images/layout/star_darkgrey.gif' /><img src='images/layout/star_darkgrey.gif' /><img src='images/layout/star_darkgrey.gif' />";
	}
	vid = video;
	var txtquest = "Confirm your vote";
	var starplus = star + 1;
	var txt = txtquest + ":<br/><br/><img src='images/layout/star_darkgrey.gif' />" + starcount;
	$.prompt(txt, {
		callback: resultCallVote,
		buttons: {
			Ok: starplus,
			Cancel: false
		}
	});
}


function resultCallVote(v, m){
	if (v != false) {
		$.ajax({
			type: 'POST',
			url: "modules/public/videos/registervote.php?star=" + v + "&id=" + vid,
			success: function(data){
				var resp;
				if (data == 1) {
					resp = "Your vote was saved successfully.";
				} else {
					resp = "There was a problem saving your vote. Please try again later.";
				}
				$.prompt(resp);
			}
		});
	}
}

function ShowDiv(divid){
	var classdiv = document.getElementById(divid).className;
	if (classdiv == "hide") {
		document.getElementById(divid).className = "";
	} else {
		document.getElementById(divid).className = "hide";
	}
}

function ValidateCommentsForm(){
	var val = 0;
	var obs = ValidateText("commentinput", "commentlabel");
	if (!obs) {
		val = 1;
	}
	if (val == 1) {
		return false;
	} else {
		document.commentsform.submit();
	}
}


function CallUserDetails(id){
	$.ajax({
		type: 'POST',
		url: "modules/public/registration/profile.php?id=" + id,
		success: function(data){
			$.prompt(data);
			CallGoogleMaps("getCoordinatesMember.php", id);
		}
	});
}

function SearchVideos(){
	document.formvid.submit();
}


