
//maxes life a bit easier
var ajax = "../clazzez/Ajax.php";
var blinking;

/*
 * GOOGLE ANALYTICS
 */
var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-26492640-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

$(document).ready(function(){
	
	//validation for the register form
	$(".subscribeform").submit(function(e){
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		$(this).find("input[type='text'], input[type='password']").each(function(){
			if($(this).val() == ''){
				$(this).addClass('warning');
				e.preventDefault();
			}	
			else{
				if($(this).attr('name') == 'email'){
					if(emailReg.test($(this).val())){
						if($(this).attr('name') == 'pword'){
							if($(this).val() != $(".subscribeform input[name='pwordval']").val()){
								e.preventDefault();	
							}
						}
					}
					else{
						$(this).addClass('warning');
						e.preventDefault();
					}
				}
			}
		});
	});
	
	if($("#invitefbfriends"))
	{
		$.post("../clazzez/Ajax.php",{first:'invitefbfriends'},
				function(msg)
				{
					if(msg != "")
					{	
						$("#invitefbfriends").html(msg);
						$("#invitefbfriends").show();
					}
				}
		);
	}
	//validation keyup handlers
	$(".subscribeform input[type='text']").keyup(function(){
		if($(this).val() != ''){
			$(this).removeClass('warning');
		}
		else $(this).addClass('warning');
	});
	
	$(".subscribeform input[name='pword']").keyup(function(){
		
		if($(".subscribeform input[name='pwordval']").val() == "" || $(".subscribeform input[name='pwordval']").val() != $(this).val() || $(".subscribeform input[name='pword']").val().length < 6){
			$(".subscribeform input[name='pwordval']").addClass('warning');
			$(this).addClass('warning');
		}
		else{ 
			$(".subscribeform input[name='pwordval']").removeClass('warning');
			$(this).removeClass('warning');
		}
	});
	$(".subscribeform input[name='pwordval']").keyup(function(){
		if($(".subscribeform input[name='pword']").val() == "" || $(".subscribeform input[name='pword']").val() != $(this).val() || $(".subscribeform input[name='pwordval']").val().length < 6){
			$(".subscribeform input[name='pword']").addClass('warning');
			$(this).addClass('warning');
		}
		else{ 
			$(".subscribeform input[name='pword']").removeClass('warning');
			$(this).removeClass('warning');
		}
		
	});
	//and finally the onkey for the email
	$(".subscribeform input[name='email']").keyup(function(){
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		if(!emailReg.test($(this).val()))
			$(this).addClass('warning');
		else $(this).removeClass('warning');
	});
	
	
	//this code is used to replace all of our placeholder elements to work on all browsers
	if(!$.browser.webkit){
		$('[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.val() == input.attr('placeholder')) {
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		  }
		}).blur();
		$('[placeholder]').parents('form').submit(function() {
		  $(this).find('[placeholder]').each(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
			  input.val('');
			}
		  })
		});
	}
	
	//Used to submit and validate the friend email invitation box
	$("#invitefriendsform").submit(function(e){
		e.preventDefault();
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		var emailInput = $("#invitefriendsform input[type=text]");
		var emailSubmit = $("#invitefriendsform input[type=submit]");
		var emailLoading = $("#invitefriends #emailloader");
		var error = $("#invitefriendsform #invitemailerror");
		var email = emailInput.val();
		if(email != ''){
			if(emailReg.test(email)){
				emailInput.css('borderColor', '#3E606F');
				error.css('display', 'none');
				emailSubmit.attr('disabled','disabled');
				emailLoading.css('display', 'block');
				
				//send out the mail via AJAX.php
				$.get('../clazzez/Ajax.php?first=sendinviteemail', $("#invitefriendsform").serialize(), function(e){
					emailSubmit.attr('disabled','');
					emailLoading.css('display', 'none');
					error.html('Your email has been sent to: '+emailInput.val()+'!');
					error.css('display', 'block');
					emailInput.val('');
				});
			}
			else {
				emailInput.css('borderColor', 'red');
				error.html('Please provide a valid email addess');
				error.css('display', 'block');
			}
		}
		else {
			emailInput.css('borderColor', 'red');
			error.html('Please provide an email addess');
			error.css('display', 'block');
		}
			
		});	
	//show the advanced search box on tips page
	$("#tipsadvancedsearch").toggle(function(){
		$("#searchtips-advanced").fadeIn();newnotifications
	}, function(){
		$("#searchtips-advanced").fadeOut();
	});
	
	//toggle to show the breeds for each specie (tips)
	$(".speciepick").toggle(function(){
		var id = $(this).attr('rel');
		$("#"+id).slideDown();
	},function(){
		var id = $(this).attr('rel');
		$("#"+id).slideUp();
	});
	
	//toggle to show all breeds for each specie (tips)
	$("#expandtips").toggle(function(){
		$(".breed-tips").slideDown();
		$("#expandtips").css('backgroundImage', 'url(../../images/layout/collapse_icon.png)');
	}, function(){
		$(".breed-tips").slideUp();
		$("#expandtips").css('backgroundImage', 'url(../../images/layout/expand_icon.png)');
	});
	
	//show popup that allows users to write tips
	$(".write-tip").click(function(){
		
		var data = new Object();
		data.first = 'writetip';
		if($(this).attr('rel') != ''){
			data.breedid = $(this).attr('rel');
		}
		$.post('../clazzez/Ajax.php', data , function(e){
			if(!$("#writeatipwrapper").length)
				$('body').append(e);
			else{
				$("#writeatipwrapper").remove();
				$('body').append(e);
			}
			$("#writeatipwrapper").dialog({height:'auto', width:'auto',resizable:false, draggable:false, modal:true, close: function(event, ui) {$("#writeatipwrapper").remove();}}).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
			$(".write-tip-cancel").click(function(){
				$("#writeatipwrapper").dialog('close');
			});
		});
	});
	
	
	//add the handlers so that our tip objects work
	assignEditTipHandlers();
	//add the general tip class handlers
	assignTipHandlers();
	
	
	//method to load more tips in managetips.php
	$("#loadmoretips").click(function(){
		var rel = $(this).attr('rel');
		
		//create the post data
		var data = new Object();
		data.first = 'loadmoretips';
		data.second = $(this).attr('start');
		data.third = 5;
		data.rel = rel;
		
		//make all the exceptions to the sent data
		if(rel == "toprated" || rel=="mostviewed" || rel=="latest"){
			data.breedid = $("#tips").attr('breedid');
		}
		$(this).html('<center class="title">Loading...</center>');
		$.post("../clazzez/Ajax.php", data, function(e){
			$("#tips").html($("#tips").html()+e);
			$("#loadmoretips").attr('start', parseInt($("#loadmoretips").attr('start')) + 5);
			
			if(rel == "manage")
				assignEditTipHandlers();
			else if(rel == "toprated" || rel == "mostviewed" || rel=="latest")
				assignTipHandlers();
			
			isMoreTipsToBeDisplayed();
		});
	});
	
	//assign handlers to the tip orderer
	$("#tiporderer a").click(function(){
		
		$("#tiporderer a").each(function(){$(this).removeClass('selected');});
		//$("#loadmoretips").attr('start', 5);
		//alert('start: '+$("#loadmoretips").attr('start'));
		//$("#loadmoretips").css('display', 'block');
		isMoreTipsToBeDisplayed();
		var data = new Object();
		data.first = 'loadmoretips';
		data.second = 0;
		data.breedid = $("#tips").attr('breedid');
		
		//if the user already loaded more than 5 results on a tab, then display this in the next aswell
		if(parseInt($("#loadmoretips").attr('start')) > 5)
			data.startof = $("#loadmoretips").attr('start');
		
		if($(this).attr('rel') == "mostviewed")
			data.rel = 'mostviewed';
		else if($(this).attr('rel') == "toprated")
			data.rel = 'toprated';
		else if($(this).attr('rel') == "latest")
			data.rel = 'latest';
		
		
		if($(this).attr('rel') == "mostviewed"){
			$(this).addClass('selected');
			$.post('../clazzez/Ajax.php', data, function(e){
				$("#tips").replaceWith(e);
				$("#loadmoretips").attr('rel', 'mostviewed');
				assignTipHandlers();
			});
		}
		else if($(this).attr('rel') == "toprated"){
			$(this).addClass('selected');
			$.post('../clazzez/Ajax.php', data, function(e){
				$("#tips").replaceWith(e);
				$("#loadmoretips").attr('rel', 'toprated');
				assignTipHandlers();
			});
		}
		else if($(this).attr('rel') == "latest"){
			$(this).addClass('selected');
			$.post('../clazzez/Ajax.php', data, function(e){
				$("#tips").replaceWith(e);
				$("#loadmoretips").attr('rel', 'latest');
				assignTipHandlers();
			});
		}
	});
	
	//handle the pet deletion buttons
	$(".delete-pet").toggle(function(){
		$(".deletion-confirmation-settings[rel="+$(this).attr('rel')+"]").fadeIn();
	}, function(){
		$(".deletion-confirmation-settings[rel="+$(this).attr('rel')+"]").fadeOut();
	});
	
	//delete a pet via ajax on pet settings page
	$(".delete-pet-form").submit(function(e){
		e.preventDefault();
		$(".delete-pet-form img").attr('src', '../images/layout/logospinningourwhite.gif');
		$(".delete-pet-form img").fadeIn();
		$.post("../clazzez/Pettzer.php",$(this).serialize(), function(e){
			$("#center").html(e);
			window.location = '';
		});
	});
	
	$(".add-pet").click(function(){
		popUp('addpetstep1','');
	});
	
	//toggles the expand and collapse of pet settings on settings.php
	$("#psettingsexpand").toggle(function(){
		//$(".petsettingstable").slideUp();
		$("#psettingsexpand").attr('src', '../images/layout/collapse_icon.png');
	}, function(){
		//$(".petsettingstable").slideDown();
		$("#psettingsexpand").attr('src', '../images/layout/	.png');
	});
	
	//make sure that the petsettingsblocks open when clicked (rows) in settings.php
	$(".psettingsBlock").click(function(){
		//togglePetSettingsBlock('tableSettingsDiv'+$(this).attr('rel'));
		//$(this).unbind('click');
		//$(this).css('cursor','default');
	});
	
	$(".psettingsBlock").hover(function(){
		$(this).find('img').attr('src', '../images/layout/thumb_verylight.png');
	}, function(){
		$(this).find('img').attr('src', '../images/layout/thumb_transparent.png');
	});
	
	//open and close the notificationsicon
	$("#notificationsicon").toggle(function(){
		$("#notifications").fadeIn();
		if(blinking != null)
			clearInterval(blinking);
		getNotifications();
	}, function(){
		$("#notifications").fadeOut();
	});
	
	$("#notifications").blur(function(){
		$(this).fadeOut();
	});
	
	$('#inboxoptionscheckbox').click(function(){selectAllInboxMessages();});
	
	$('#inboxoptionselect').click(function(){selectAllInboxMessages();});
	
	$('#inboxoptionmark').click(function(){markMultipleInboxMessages();});
	
	$('#inboxoptiondelete').click(function(){deleteMultipleInboxMessages();});

	$('.sendmessage').click(function(){
		getMailPopup();
	});
	
	$(".inboxreply").click(function(){
		getMailReplyPopup($(this).attr('id'), $(this).attr('name'));
	});
	
	addAlbumManagementHandlers();
	
	$('#seemorenotifications').click(function(){getMoreNotifications($(this));});
	$('#description').keyup(function(){countDescription();});
	
	//$('.addProductPetButton').click(function(){alert('BWOOOIIINNN');});
	
	$("#resetpwform").submit(function(e){
		e.preventDefault();
		$.post('resetpassword.php', $(this).serialize(), function(e){
			var json = jQuery.parseJSON(e);
			if(json.succes){
				$("#resetpwform").find("img").fadeIn();
				$("#error").fadeOut();
			}
			else{
				$("#error").hide();
				$("#error").html(json.error);
				$("#error").fadeIn();
			}
		});
	});
	
	
	//handlers for the reset password form on usersettings.php
	$('#resetpasswordform input[name="newpassword"], #resetpasswordform input[name="newpasswordconfirm"]').keyup(function(){
		var newpassword = $('#resetpasswordform input[name="newpassword"]');
		var confirm = $("#resetpasswordform input[name='newpasswordconfirm']");
		
		if(newpassword.val().length < 6){
			newpassword.addClass('warning');
			confirm.addClass('warning');
		}else{
			newpassword.removeClass('warning');
				confirm.removeClass('warning');
		}
		
		if(newpassword.val() != '' && confirm.val() != ''){
			if(newpassword.val() != confirm.val()){
				newpassword.addClass('warning');
				confirm.addClass('warning');
			}
			else{
				newpassword.removeClass('warning');
				confirm.removeClass('warning');
			}
		}
	});
	
	$('#resetpasswordform input[name="oldpassword"]').keyup(function(){
		if($(this).val()!='')
			 $(this).removeClass('warning');
		else  $(this).addClass('warning');
	});
	
	$("#resetpasswordform").submit(function(e){
		e.preventDefault();
		if($(this).find('input[name="oldpassword"]').val() == ''){
			$(this).find('input[name="oldpassword"]').addClass('warning');
		}
		
		if($(this).find('input[name="oldpassword"]').val().length > 0 
				&& $(this).find('input[name="newpasswordconfirm"]').val() == $(this).find('input[name="newpassword"]').val() 
				&& $(this).find('input[name="newpassword"]').val().length >= 6){
			//passed the correct data
			$.post('../clazzez/Ajax.php', $(this).serialize(), function(d){
				if(d)
					showAlert('Your password has been reset.');
				else{
					$('input[name="oldpassword"]').addClass('warning');
					 showAlert('Your password could not be changed at this time. Perhaps your old password was entered faultly.');
					 
				}
					
			});
		}
	});
	$("#prodsettingsform").submit(function(e){
		e.preventDefault();
		updateProduct( $(this) , $(this).attr('rel') );
	});
	
	//toggle delete account
	$("#deleteaccounttoggle").toggle(function(){
		$("#deleteaccount").fadeIn();
	}, function(){
		$("#deleteaccount").fadeOut();
	});
	
	$(".friends").click(function(e){
		e.preventDefault();
		$.post('../clazzez/Ajax.php', {first:'getfriendspopup', second:$(this).attr('rel')}, function(r){
			$("#center").append(r);
			$("#friendspopup").dialog({height:'300', width:'500',resizable:false, draggable:false, modal:true, close: function(event, ui) {$("#friendspopup").remove();}}).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
			$("#friendspopup input[rel='close']").click(function(){$("#friendspopup").dialog('close');});
			
		});
	});
	
	$("#dismisstranslationwarning").submit(function(e){
		e.preventDefault();
		$.cookie("translationwarningdismissed", "1", {expires:14, path:"/"});
		$(this).parent().slideUp({duration:1000});
	});
	
	$("#dismisschristmaswarning").submit(function(e){
		e.preventDefault();
		$.cookie("christmaswarningdismissed", "1", {expires:14, path:"/"});
		$(this).parent().slideUp({duration:1000});
	});
	
	$("#dismissnewtranslation").submit(function(e){
		e.preventDefault();
		$.cookie("newtranslationdismissed", "1", {expires:14, path:"/"});
		$(this).parent().slideUp({duration:1000});
	});
	
	//THIS IS VERY IMPORTANT
	//IT MAKES SURE USERS THAT USER THAT ARE NOT LOGGED IN CANNOT DO CERTAIN ACTIONS ON THE WEBSITE
	//THIS SPECIFICATION OF THIS METHOD SHOULD STAY ON THE BOTTOM OF THIS PAGE TO ENSURE THE PROPER WORKING
	
	setPermissionsOnElements();
	
	//enable people to care about businesses
	$(".care-business").click(function(e){
		e.preventDefault();
		$.post('../clazzez/Ajax.php', {first:'carebusiness', second:$(this).attr('rel')}, function(a){
			$("#businesscares").html(a);
		});
	});
	
	addProductSettingsHandlers();
	addProductPictureHandlers();
	addBlinkingNotificationsHandlers();
	addProductCareHandlers();
	addChristmasCompetitionHandlers();
});

function updateProduct(form,id)
{
	alert(form.serialize()+"<br>id:"+id);
	/*
	 * $.post('../clazzez/Ajax.php',{first:'updateproduct','second})
	 * 
	 * 
	 */
}

function addProductButton(a)
{	
	a.preventDefault();
	$.post('../clazzez/Ajax.php', {first:'addproductpopup'}, function(e){
		$(e).dialog({ resizable: false,modal:true, width:'auto', position:'center',close:function(){$('#addproduct').remove();} }).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
		$('#submitproduct').click(function(){addProduct($('#productform'));});
		$('#cancelproduct').click(function(){$('#addproduct').dialog('close');});
	});
}

function addProduct(form)
{
	var error = false;
	var title = $(form).find('input[name=title]').val();
	var desc = $(form).find('textarea[name=description]').val();
	var price = $(form).find('input[name=price]').val();
	
	if(title == '')
	{
		$(form).find('input[name=title]').css({'border':'solid 1px #FF0000','padding':'1px'});
		error = true;
	}
	if(desc == '')
	{
		$(form).find('textarea[name=description]').css({'border':'solid 1px #FF0000','padding':'1px'});
		error = true;
	}
	if(!error)
	{
		$.post('../clazzez/Ajax.php',{first:'addproduct',second:title,third:desc, fourth:price},
				function(msg)
				{
					$('#psettings').html(msg);
					$('#addproduct').dialog('close');
					addProductSettingsHandlers();
				});
	}
}

function addAlbumManagementHandlers(){
	//function for managealbums.php
	$(".petpreview").click(function(){
		
		var user = $(this).attr('user') == 'true';
		var pettyid = $(this).attr('rel');
		
		$(".petpreview").each(function(){
			$(this).removeClass('selectedpet');
			$("#pictures").css('display', 'none');
		});
		$(this).addClass('selectedpet');
		
		if(user){
			
			$("#pickalbums").fadeOut();
			$("#pickalbum").fadeOut();
			$("#addalbum").fadeOut();
			
			$.post('../clazzez/Ajax.php', {first:'getalbumwithpictures', second:pettyid}, function(e){
				$("#pictures").html(e);
				deletionwarnings = false;
				$('#pictures').fadeIn();
				addPicturePreviewHandlers();
			});
			
			return false;
		}
		
		
		
		$("#pettyidforalbum").val(pettyid);
		$.post('../clazzez/Ajax.php', {first:'getpetalbums', second:$(this).attr('rel')}, function(e){
			$("#pickalbum").css('display', 'none');
			$("#pickalbums").css('display', 'none');
			$("#addalbum").css('display', 'none');
			$("#pickalbum").html(e);
			$("#pickalbum").fadeIn();
			$("#pickalbums").fadeIn();
			addAlbumPreviewHandlers();
		});
	});
	
	$("#add_album").toggle(function(){
		$("#addalbum").slideDown();
	}, function(){
		$("#addalbum").slideUp();
	});
	
	$("#addalbumform").submit(function(e){
		e.preventDefault();
		$.post('../clazzez/Ajax.php', $(this).serialize(), function(e){
			$('#pickalbum').html(e);
			$("#addalbumform input[type='text']").val('');
			addAlbumPreviewHandlers();
		});
	});
	
	$(".upload_pictures").click(function(){
		getUploadPicturesPopup($(this).attr('rel'));
	});
}

function addUploadPicturesPopUpHandlers(){
	$(".upload_pictures").click(function(){
		getUploadPicturesPopup($(this).attr('rel'));
	});
}

function getUploadPicturesPopup(albumid){
	$.post('../clazzez/Ajax.php', {first:'upload_pictures', second:albumid}, function(e){
		if($("#upload-pictures-popup").length == 0){
			$('body').append(e);
			$("#upload-pictures-popup").dialog({width:'600px', height:'auto',resizable:false, draggable:false, modal:true, close: function(event, ui) {
				$("#upload-pictures-popup").remove(); 
				addUploadPicturesPopUpHandlers();
				}
			}).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
			
			$("#uploadform").submit(function(e){
				$('body').append('<center><img src="../../images/layout/logospinningourwhite.gif" /></center>');
				$("#uploadform").hide();
			});
			closeAndFinishPictureUploadPopUp();
		}
	});
}

function frameLoaded(){
	try{
		var obj = jQuery.parseJSON($("#frame").contents().find("body").html());
		if(obj.error != null){
			$("#uploaderrors").html('There were one or more errors with uploading your files: <br><br>' + obj.error);
			$("#uploaderrors").append('<br><br><input id="tryuploadagain" type="button" class="petButton" value="Try Again" />');
			$("#frame").hide();
			
			$("#tryuploadagain").click(function(){
				var aid=$("#albumidrecover").val();
				$("#upload-pictures-popup").dialog('close');
				getUploadPicturesPopup(aid);
			});
			return false;	
		}
		
		$.each(obj, function(i, url){
			if(url != 'profilepicturechanged'){
				$("#previews").append('<img style="display:none;" class="bordered" width="100" src="'+url+'" />');
			}
			else{
				if(url ='profilepicturechanged'){
					$("#profilepic").hide();
					$("#profilepic").attr('src', $('#previews > img').attr('src'));
					$("#profilepic").fadeIn();
				}
				
			}
		});		
		$("#frame").hide();
		$("#picuploadsucces").fadeIn();
		
		closeAndFinishPictureUploadPopUp();
		
		var i = 2000;
		$("#previews img").each(function(){
			$(this).fadeIn({duration:i});
			i += 250;
		});
	}
	catch(e){
		//don't do anything here
		//$("#previews").html('Parsing went wrong'+ e);
	}
		
}

function closeAndFinishPictureUploadPopUp(){
	$("#closeuploadpicspopup, #closeuploadpictures").click(function(){
		$("#upload-pictures-popup").dialog('close');
		
		if($("#selectproductpicture").length > 0){
			var prodid = $("input[name=saveprod]").attr('p');
			$("#selectproductpicture").dialog('close');
			selectProductPicture(prodid);
		}
		else{
			var id = $(".albumpreview.bordered.selectedalbum").attr('rel');
			if(id == null){
				var id = $(".petpreview.bordered.selectedpet").attr('rel');
			}
			$.post('../clazzez/Ajax.php', {first:'getalbumwithpictures', second:id}, function(e){
				$("#pictures").html(e);
				deletionwarnings = false;
				addPicturePreviewHandlers();
			});
		}
	});
}

function addAlbumPreviewHandlers(){
	$(".albumpreview").click(function(){
		$(".albumpreview").each(function(){
			$(this).removeClass('selectedalbum');
			$("#pictures").css('display', 'none');
		});
		$(this).addClass('selectedalbum');
		
		if($(this).attr('title') != "Profile Pictures" && $(this).attr('title') != "User Profile Pictures"){
			$("#delete-album").show();
			var albumid = $(this).attr('rel');
			var title = $(this).attr('title');
			$("#delete-album").toggle(function(){
				$("#sure-delete-album").html('Are you sure that you want to delete the album: '+title+'? <div id="delete-album-confirm" class="bordered"><span>DELETE</span><div class="delete_icon"></div></div>');
				$("#sure-delete-album").show();
				$("#delete-album-confirm").click(function(){
					var petid = $(".petpreview.bordered.selectedpet").attr('rel');
					$.post('../clazzez/Ajax.php', {first:'deletealbum', second:albumid, third:petid}, function(e){
						$('#pickalbum').html(e);
						addAlbumPreviewHandlers();
						$("#sure-delete-album").fadeOut();
						$("#delete-album-confirm").fadeOut();
						$("#pictures").fadeOut();
					});
				});
			}, function(){
				$("#sure-delete-album").fadeOut();
			});
		}else $("#delete-album").hide();
		
		
		$.post('../clazzez/Ajax.php', {first:'getalbumwithpictures', second:$(this).attr('rel')}, function(e){
			$("#pictures").html(e);
			$("#pictures").fadeIn();
			addPicturePreviewHandlers();
		});
	});
}

function addPicturePreviewHandlers(){
	
	$(".suredelete").click(function(){
		$.post('../clazzez/Ajax.php', {first:'deletepicture', second:$(this).attr('rel'), third:$(this).attr('albumid')}, function(e){
			$("#pictures").html(e);
			addPicturePreviewHandlers();
		});
	});
	
	$(".picturepreview").click(function(){
		$(".picturepreview").each(function(){
			$(this).removeClass('selectedpicture');
		});
		$(this).addClass('selectedpicture');
	});		
	

	$(".delete_picture").toggle(function(){
		$(this).parent().find('.suredelete').fadeIn();
	}, function(){
		$(this).parent().find('.suredelete').fadeOut();
	});
	
	
	if(deletionwarnings){
		$(".suredelete").each(function(){
			$(this).fadeIn();
			
		});
	}
	
	$(".setasprofile").click(function(){
		var upp = $(this).attr('upp') == "true";
		if(upp == false){
			$.post('../clazzez/Ajax.php', {first:'setprofilepicture', second:$(this).attr('rel'), third:$(this).attr('pid')}, function(e){
				//alert('set pet profile picture'+e);
				location.reload();
			});
		}else{
			
			$.post('../clazzez/Ajax.php', {first:'setprofilepicture', second:$(this).attr('rel'), upp:'true'}, function(e){
				//alert('set user profile picture'+e);
				location.reload();
			});
		}
	});
	
	$(".upload_pictures").click(function(){
		$.post('../clazzez/Ajax.php', {first:'upload_pictures', second:$(this).attr('rel')}, function(e){
			if($("#upload-pictures-popup").length == 1)
				$("#upload-pictures-popup").remove();
			$('body').append(e);			
			$("#upload-pictures-popup").dialog({width:'600px', height:'auto',resizable:false, draggable:false, modal:true, close: function(event, ui) {$("#upload-pictures-popup").remove();}}).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
			closeAndFinishPictureUploadPopUp();
			$("#uploadform").submit(function(e){
				$('body').append('<center><img src="../../images/layout/logospinningourwhite.gif" /></center>');
				$("#uploadform").hide();
			});
		});
	});
	
	$("#toggledeletionwarnings").toggle(function(){
		deletionwarnings = true;
		$(".suredelete").each(function(){
			$(this).fadeIn();
		});
	}, function(){
		deletionwarnings = false;
		$(".suredelete").each(function(){
			$(this).fadeOut();
		});
	});
}

var deletionwarnings = false;

function getMoreNotifications(div)
{
	var start = div.find('a')[0].id;
	$.post("../clazzez/Ajax.php",{first:'loadmorenotifications',second:start},
			function(msg){
		div.replaceWith(msg);
		$('#seemorenotifications').click(function(){getMoreNotifications($(this));});
	});
}

function isMoreTipsToBeDisplayed(){
	var rel = $("#loadmoretips").attr('rel');
	//set up the post data to see if they can still expand
	var data = new Object();
	data.first = 'canloadmoretips';
	data.second = $("#loadmoretips").attr('start');
	data.rel = rel;
	
	//make all the exceptions to the sent data
	if(rel == "toprated" || rel =="mostviewed" || rel=="latest"){
		data.breedid = $("#tips").attr('breedid');
	}
	$.post("../clazzez/Ajax.php", data , function(i){
		if(!i){
			$("#loadmoretips").fadeOut();
			$("#loadmoretips").attr('start', $(".tip").length-1);
		}
		else $("#loadmoretips").fadeIn();
	});
	$("#loadmoretips").html('<center class="title">Load 5 more</center>');
}

function assignTipHandlers(){
	$(".tip.bordered").hover(function(){
		$(this).find(".petthumb img").attr('src', '../images/layout/thumb_verylight.png');
	}, function(){
		$(this).find(".petthumb img").attr('src', '../images/layout/thumb_transparent.png');
	});
	$(".tip.bordered[link]").each(function(){
		$(this).css('cursor','pointer');
		$(this).attr('title', 'Read Tip');
		$(this).click(function(){
			window.location = $(this).attr('link');
		});
	});
	
}

function assignEditTipHandlers(){
	//toggle the deletion warning on managetips.php
	$(".petButton.delete").toggle(function(){
		$(".suretipdelete[rel='"+$(this).attr('rel')+"']").slideDown();
	}, function(){
		$(".suretipdelete[rel='"+$(this).attr('rel')+"']").slideUp();
	});
	
	//delete the tip on managetips.php
	$(".petButton.deletesure").click(function(e){
		var button = $(this);
		$.post('../clazzez/Ajax.php', {first:'deletetip', second:$(this).attr('rel')}, function(event){
			if(event){
				$(".tip.bordered[rel='"+button.attr('rel')+"']").slideUp();
			}
		});
	});
	
	//toggle the edit tip popup on managetips.php
	$(".petButton.edit").click(function(){
		$.post('../clazzez/Ajax.php', {first:'edittip', second:$(this).attr('rel')}, function(e){
			if(!$("#edittipwrapper").length)
				$('body').append(e);
			else{
				$("#edittipwrapper").remove();
				$('body').append(e);
			}
			$("#edittipwrapper").dialog({height:'auto', width:'auto',resizable:false, draggable:false, modal:true, close: function(event, ui) {$("#edittipwrapper").remove();}}).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
			$(".petButton.edit-tip-cancel").click(function(){
				$("#edittipwrapper").dialog('close');
			});
		});
	});
}

//Thomas Checked 18-07-1011
//Toggles the notification div
function toggleActivity()
{
	var id = "notificationsopened";
	if( $('#notificationsopened').css('display') == 'none')
	{
		$('#notificationsopened').show();
		getNotifications();
		$('#notificationsclosed').attr('class', 'notificationsclosed');
	}
	else 
		$('#notificationsopened').hide();
}



//this method will overlay the given div with a loading icon
//please send a jquery selector (i.e. #mydiv or .mydiv)
//THIS METHOD HAS BEEN ABBANDONED
function displayLoading(divsel){
	var div = $(divsel);
	var clone = div.clone();
	var wrapper = '<div class="loadingblanket"></div>';
	
	div.parent().prepend(wrapper);
	wrapper = $(".loadingblanket");
	wrapper.append(clone);
	wrapper.height(clone.height());
	wrapper.width(clone.width());

	clone.html('');
	clone.height(div.height());
	clone.css('position','absolute');
	clone.css('z-index','999');
	clone.css('opacity','0.5');
	clone.css('text-align','center');
	clone.css('vertical-align', 'middle');
	clone.css('color', '#FCFFF5');
	wrapper.append('<div class="loadinblankettext" style="opacity:1;">LOADING...</div>');
}


function clearInput(element, original)
{
	if(element.value == original)
		element.value = "";
}

function setInputValue(value, element, original)
{
	if(element.value == original || element.value == '')
	{
		element.value = value;
	}
}

var rightMenuOpen = false;

function showRightMenu()
{
	$('right_menu_wrapper').morph('height:100px; margin-top:10px;', { duration:0.5}); 
	$('right_menu_hidden').morph('height:65px;', { duration:0.5});
	var thumbarray = document.getElementsByName("thumbs");

	for(var i = 0; i < thumbarray.length; i++)
	{
		windowname = thumbarray[i].id;
		//document.getElementById(windowname).stle.display ="block";
		setTimeout("Grow('"+windowname+"')", i*200);
	}
}

function Grow(windowname)
{
	Effect.Grow(windowname);
}

function hide(windowname)
{
	document.getElementById(windowname).style.display = 'none';
}



function closeRightMenu()
{
	$('right_menu_wrapper').morph('height:28px; margin-top:75px;', { duration:0.5}); 
	$('right_menu_hidden').morph('height:1px;', { duration:0.5});
	
	var thumbarray = document.getElementsByName("thumbs");
	//alert(thumbarray);
	for(var i = 0; i < thumbarray.length; i++)
	{
		setTimeout("hide('"+thumbarray[i].id+"')", 500);
	}
}

function toggleRightMenu()
{
	Effect.ScrollTo('Header');
	if(!rightMenuOpen)
	{
		showRightMenu();
		rightMenuOpen = true;
	}
	else if(rightMenuOpen)
	{
		closeRightMenu();
		rightMenuOpen = false;
	}
}

function showThumbs()
{
	var thumbarray = document.getElementsByName("thumbs");
	//alert(thumbarray);
	for(var i = 0; i < thumbarray.length; i++)
	{
		thumbarray[i].style.display = "block";
	}
}

function togglePetSettingsBlock(id)
{
	if(document.getElementById(id).style.display == "none")
	{
		$("#"+id).slideDown();
	}
	else {
		$("#"+id).slideUp();
	};
}

function toggleHiddenPostStatus()
{
	if(document.getElementById('hiddenPostStatus') != null)
	{
		if(document.getElementById("hiddenPostStatus").style.display == "none")
		{
			
			Effect.BlindDown("hiddenPostStatus", {duration:0.3});
		}
		else
		{
			if(document.getElementById('snapwrapper').innerHTML == "")
			{
				Effect.BlindUp("hiddenPostStatus", {duration:0.3});
				Effect.BlindUp("snapwrapper", {duration:0.3});
			}
		}
	}
}

function toggleComment(id)
{
	if($('#'+id).css("display") == 'none')
	{
		var arr = id.split("comment");
		
		if(!arr[1])
			arr = id.split("walltowall");
		
		var idinput = "commentinput"+arr[1];
		
		$('#'+id).show(); 
		$('#'+id+' input[type=text]').focus();
		
		//Effect.Grow(id, {duration:0.5});
		//setTimeout('document.getElementById(\''+idinput+'\').focus()', 500);
	}
	else
	{
		$('#'+id).hide(); 
	}
	
	/*
	
	if(document.getElementById(id).style.display == "none")
	{
		var arr = id.split("comment");
		
		if(!arr[1])
			arr = id.split("walltowall");
		
		var idinput = "commentinput"+arr[1];
		Effect.Grow(id, {duration:0.5});
		setTimeout('document.getElementById(\''+idinput+'\').focus()', 500);
	}
	else Effect.BlindUp(id, {duration:0.5});*/
}

function showRemovePost(id)
{
	if(document.getElementById(id).style.display == "none")
	{
		document.getElementById(id).style.display = "block";
	}
}

function hideRemovePost(id)
{
	document.getElementById(id).style.display = "none";
}

function toggleShowSure(id)
{
	id = 'sure' + id;
	if(document.getElementById(id).style.display == "none")
	{
		//document.getElementById(id).style.display = "block";
		$("#"+id).slideDown();//	Effect.BlindDown(, {duration:0.3});
	}
	else $("#"+id).slideUp();
}

function toggleShowSureComment(id)
{
	id = 'sureComment' + id;
	if(document.getElementById(id).style.display == "none")
	{
		//document.getElementById(id).style.display = "block";
		$("#"+id).slideDown();
	}
	else $("#"+id).slideUp();
}

function showHiddenComments(fid)
{
	var elements = document.getElementsByName("comment"+fid);
	if(elements.length == 0)
		elements = document.getElementsByName("commentwalltowall"+fid);
	for(var i =0; i < elements.length; i++)
	{
		elements[i].style.display = "block";
	}
}

function toggleUserInfo(id)
{
	if(document.getElementById(id).style.display == "none")
	{
		Effect.BlindDown(id);
	}
	else Effect.BlindUp(id);
}

//OLD
function toggletips(id)
{
	if(document.getElementById(id).style.display == "none")
	{
		//Effect.BlindDown(id);
		$("#"+id).slideDown();
	}
	else $("#"+id).slideUp();
}

function sz(t, size) {		
		a = t.value.split('\n');
		
		b=1;
		for (x=0;x < a.length; x++) {
			if (a[x].length >= t.cols) b+= Math.floor(a[x].length/size);
		}
		b+= a.length;
		if (b > t.rows) 
		{
			t.rows = b;
		}
}

function hideActivity(e){
	var div = document.getElementById('notificationsopened');
	var div2 = document.getElementById('notificationsclosed');
	var target=e?e.target:event.srcElement;
	
	//blacklist
	if(target!=div && target!=div2 && div!=null && div2!=null && target.className !="notificationHeader" && target.className != "notificationOld" && 
	   target.className !="notificationNew" && target.className !="notificationsopened" && target.id != "seeallnotifications"
		&& target.className!="mainSearchSuggestResult")
	{
		div.style.display='none';
		document.getElementById('search_suggest_all').style.display = "none";
	}
}


document.onclick = hideActivity;

function initAllPetgets()
{
		initPetgetsDragDropHandlers();
		$("#petgetpick").click(function(){
		$(this).addClass('selectedbutton');
		$("#petgetdragdrop").removeClass('selectedbutton');
		$('.petget').draggable('destroy');
		$('.petgetrow').each(function(){
			//$(this).css('backgroundColor', '#D1DBBD');
			$(this).addClass('petgetrowcandidate');
			$('.petget').css('cursor','pointer');
		});
		$('.petgetrow').click(function(){
			$(".petgetrow").each(function(){
				$(this).removeClass('selectedpetget');
			});
			$(this).addClass('selectedpetget');
			$("#petgetarrows").slideDown();
			$(".petgetdrop").addClass('petgetdropclick');
			$(".petgetdrop").click(function(){
				saveDroppedPetget($(this).attr('rel'), $(".selectedpetget").find(".petget").attr('rel'))
			});
		});
	});
	
	$("#petgetdragdrop").click(function(){
		initPetgetsDragDropHandlers();
		$(this).addClass('selectedbutton');
		$("#petgetpick").removeClass('selectedbutton');
		$('.petgetrow').each(function(){
			//$(this).css('backgroundColor', '#D1DBBD');
			$(this).removeClass('petgetrowcandidate');
			$(this).removeClass('selectedpetget');
			$('.petget').css('cursor','move');
		});
		$('.petgetrow').unbind('click');
		$("#petgetarrows").slideUp();
		$(".petgetdrop").removeClass('petgetdropclick');
		$(".petgetdrop").unbind('click');
	});
	
}

function initPetgetsDragDropHandlers(){
	$(".petget").draggable({revert:true, cursor:'move', appendTo:'body', helper:'clone', zIndex:2000});
	$(".petgetdrop").droppable({ accept: '.petget', hoverClass: 'petgetdropHover' ,drop: function(event, ui){
		saveDroppedPetget($(this).attr('rel'), $(ui.draggable).attr('rel'));
		ui.helper.fadeOut();
	}});
}

function saveDroppedPetget(place, pid){
	placePetget(pid, place);
}


function showDeletePetget(id)
{
	var pgd = document.getElementById(id);
		pgd.style.display = "block";
}

function hideDeletePetget(id)
{
	var pgd = document.getElementById(id);
		pgd.style.display = "none";
}

function toggleSureDeletePetget(id)
{
	var elem = document.getElementById(id);
	if(elem.style.display == "none")
	{
		$("#"+id).slideDown();
	}
	else $("#"+id).slideUp();
}

function togglePetgetPicker()
{
	var elem = document.getElementById('ppicker');
	if(elem.style.display == "none")
	{
		elem.style.display ="block";
		if($(".petget").length == 0)
			getPetgetCatalogue();
	}
	else elem.style.display ="none";
}

function toggleWriteATip()
{
	var elem = document.getElementById("writeatipwrapper");
	if(elem.style.display == "none")
	{
		Effect.BlindDown("writeatipwrapper", {duration:0.3});
	}
	else Effect.BlindUp("writeatipwrapper", {duration:0.3});
}

function togglePetSitterBcards()
{
	var elem = document.getElementById("petsitterbcards");
	if(elem.style.display == "none")
	{
		Effect.BlindDown("petsitterbcards", {duration:0.3});
	}
	else Effect.BlindUp("petsitterbcards", {duration:0.3});
}

function getGeoForSnap()
{
	if (navigator.geolocation) {
		document.getElementById('loadinglocation').style.display = "block";
		navigator.geolocation.getCurrentPosition(function(position) {
		postFeedWithSnap(position.coords.latitude, position.coords.longitude);
	
		});
	
		}
	else postFeedWithSnap(null, null);
}

function handleMediaScrollPosition()
{
	var cookie = getCookie("scrollpos");
	if(cookie == null)
	{
		var scrollpos = getScrollXY();
		setCookie("scrollpos", scrollpos[0]+"-"+scrollpos[1], "1", "/", "", "");
	}
	else
	{
		 var arr = cookie.split("-");
		window.scrollTo(arr[0], arr[1]);
	}
	loadPicture();
	setInterval(loadPicture, 100);
}

function updateScroll()
{
	var scrollpos = getScrollXY();
	setCookie("scrollpos", scrollpos[0]+"-"+scrollpos[1], "1", "/", "", "");
}

//This function is called every time a user scrolls on the media page, it returns the x and y offset:
function getScrollXY() {
	  var scrOfX = 0, scrOfY = 0;
	  if( typeof( window.pageYOffset ) == 'number' ) {
	    //Netscape compliant
	    scrOfY = window.pageYOffset;
	    scrOfX = window.pageXOffset;
	  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	    //DOM compliant
	    scrOfY = document.body.scrollTop;
	    scrOfX = document.body.scrollLeft;
	  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	    //IE6 standards compliant mode
	    scrOfY = document.documentElement.scrollTop;
	    scrOfX = document.documentElement.scrollLeft;
	  }
	  return [ scrOfX, scrOfY ];
}

var imageready = false;

function startPreloadingImage()
{
	var picturewrapper = document.getElementById('picturewrapper');
	var picture = document.getElementById('picture');
	var replacer = document.createElement('div');
	var preloader = document.createElement('img');
	var text = document.createElement('h2');
	text.innerHTML = 'loading...';
	
	preloader.setAttribute('src', '../images/layout/logospinningourwhite.gif');
	replacer.style.textAlign = 'center';
	replacer.style.color = '#3E606F';
	replacer.appendChild(preloader);
	replacer.appendChild(text);
	replacer.setAttribute('id', 'imgloader');
	replacer.setAttribute('width', '450');
	if(picture != null && picture != "")
		replacer.style.height = picture.height+"px";
	replacer.style.styleFloat = 'left';
	if(picture != null && picture != "")
		picturewrapper.replaceChild(replacer, picture);
}

/**
* Get a cookie value
* @param string cookie name
*/
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
 
/**
* Set a cookie
* @param string cookie name
* @param string cookie value
* @param string cookie expiration counter in days
* @param string cookie path
* @param string cookie domain
* @param bool secure?
*/
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
 
/**
* Remove a cookie
* @param string cookie name
* @param string cookie value
* @param string cookie path
* @param string cookie domain
*/
function deleteCookie ( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// show the about me text editor
function editAboutMe(id)
{
	var link = document.getElementById("editaboutmehref");
	if(link != null)
	{
		if(link.innerHTML == "Edit" || link.innerHTML == 'Pas Aan')
		{
			link.innerHTML = "Save";
			$("#aboutmeeditor").slideDown();
		}
		else 
		{
			link.innerHTML = "Edit";
			saveAboutMe(id);
		}
	}
}

function showPostOptions()
{
	var elem = document.getElementById("hiddenPostStatus");
	elem.style.display = "block";
}

function hidePostOptions()
{
	var elem = document.getElementById("hiddenPostStatus");
	elem.style.display = "none";
}

var numberofpets_toswitch = 0;
var petsshown = 0;
var effectisplaying = false;
var currentdot = 0;

function jumpToNextPets()
{
	if(!effectisplaying)
	{
		document.getElementById("scroll_left_arrow").style.display = "block";
		var thumbarr = document.getElementsByName("switcher_thumb");
		
		$(".switcher_thumb").animate({left:'-=240'}, 1000);
		
		/*for(var i = 0; i < thumbarr.length; i ++)
		{	
			var a = thumbarr[i];
			//new Effect.Move(a.id, {x:-240, y:0, mode:'relative', transition: Effect.Transitions.sinoidal, duration:1.0});
			$("#"+a.id).animate({left:'-=240'}, 1000);
			alert(a.id);
			this.effectisplaying = true;
			//setTimeout("effectstopped()", 1600);
		}
		*/
		
		this.numberofpets_toswitch = thumbarr.length;
		if(this.numberofpets_toswitch >=5)
			this.petsshown += 5;
		else this.petsshown += numberofpets_toswitch;
		
		if(this.numberofpets_toswitch - this.petsshown > 5)
		{
				document.getElementById("scroll_right_arrow").style.display = "block";
		}
		else
		{
			document.getElementById("scroll_right_arrow").style.display = "none";
		}
		
		var light_dots = document.getElementsByName("dot_light");
		var dark_dot = document.getElementsByName("dot_dark")[0];
		var dark_dots = 1;
		
		if(this.currentdot == 0 && light_dots.length > 0)
		{
			light_dots[0].setAttribute("class", "dot_dark");
			light_dots[0].setAttribute("name","dot_dark");
			dark_dot.setAttribute("class", "dot_light");
			dark_dot.setAttribute("name", "dot_light");
			
			this.currentdot ++;
		}
		else
		{
			light_dots[this.currentdot].setAttribute("class", "dot_dark");
			light_dots[this.currentdot].setAttribute("name","dot_dark");
			dark_dot.setAttribute("class", "dot_light");
			dark_dot.setAttribute("name", "dot_light");
			this.currentdot ++;
		}
		
	}
}

function jumpToPreviousPets()
{
	if(!effectisplaying)
	{
		document.getElementById("scroll_right_arrow").style.display = "block";
		
		var thumbarr = document.getElementsByName("switcher_thumb");
		$(".switcher_thumb").animate({left:'+=240'}, 1000);
		/*
		for(var i = 0; i < thumbarr.length; i ++)
		{	
			var a = thumbarr[i];
			new Effect.Move(a.id, {x:240, y:0, mode:'relative', transition: Effect.Transitions.sinoidal, duration:1.0});
			this.effectisplaying = true;
			setTimeout("effectstopped()", 1600);
		}
		*/
		if((this.petsshown - 5) >= 5)
		{
				document.getElementById("scroll_left_arrow").style.display = "block";
		}
		else
		{
			document.getElementById("scroll_left_arrow").style.display = "none";
		}
		this.petsshown -= 5;
		
		var light_dots = document.getElementsByName("dot_light");
		var dark_dot = document.getElementsByName("dot_dark")[0];
		var dark_dots = 1;
		
		if(this.currentdot == 0 && light_dots.length > 0)
		{
			light_dots[0].setAttribute("class", "dot_dark");
			light_dots[0].setAttribute("name","dot_dark");
			dark_dot.setAttribute("class", "dot_light");
			dark_dot.setAttribute("name", "dot_light");
			
			this.currentdot ++;
		}
		else
		{
			this.currentdot --;
			light_dots[this.currentdot].setAttribute("class", "dot_dark");
			light_dots[this.currentdot].setAttribute("name","dot_dark");
			dark_dot.setAttribute("class", "dot_light");
			dark_dot.setAttribute("name", "dot_light");
			
		}
	}
}

function effectstopped()
{
	effectisplaying = false;
}

function handlePetSwitch(pid)
{
	changePet(pid);
}


//this code can be used to show a little overlaying mini popup

function findPosX(obj)
{
  var curleft = 0;
  if(obj.offsetParent)
      while(1) 
      {
        curleft += obj.offsetLeft;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.x)
      curleft += obj.x;
  return curleft-50;
}

function findPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
      while(1)
      {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
      curtop += obj.y;
  return curtop-165;
}


function getMiniPopUp(obj, inject)
{
	//var pos = ObjectPosition(obj);
	var div = document.createElement("div");
	div.setAttribute("class", "mini_pop_up");
	
	var position = $("#"+obj.id).offset();	
	div.style.marginLeft = position.left-44+"px";
	div.style.marginTop = position.top-25+"px";
	div.innerHTML= inject;
	div.id = "minipopup";
	$('body').prepend(div);
}

function deleteMiniPopUp()
{
	var popup = document.getElementById("minipopup");
	var parent = popup.parentNode; 
	parent.removeChild(popup);	
}

function toggleEditAlbum(id)
{
	Effect.Appear(id);
}

function toggleDelAl(id)
{
	if(document.getElementById(id).style.display == "none")
		$("#"+id).slideDown();
	else $("#"+id).slideUp();
}

function toggleResetPW()
{
	if(document.getElementById("forgotdiv").style.display == "none")
		$("#forgotdiv").fadeIn();
	else $("#forgotdiv").fadeOut();
}

function toggleInboxAnswer(mainDiv)
{
	if(mainDiv.id == 'inboxmessagenew')
	{
		var messageid = getInboxMessageId(mainDiv);
		var fromid = getInboxFromId(mainDiv);
		if(messageid)
		{
			$.post('../clazzez/Ajax.php',{first:'markprivatemessage',second:messageid,third:fromid},
			function(msg){
				mainDiv.id = 'inboxmessageold';
				var answerDiv = getInboxAnswerDiv(mainDiv);
				if(answerDiv)
					answerDiv.style.display = 'block';
			});
		}
		
	}
	else
	{
		var answerDiv = getInboxAnswerDiv(mainDiv);
		if(answerDiv)
			answerDiv.style.display = 'block';
	}
}

function getInboxMessageId(maindiv)
{
	var mainNodes = maindiv.childNodes;
	var messageid = false;
	for(var i = 0; i < mainNodes.length; i++)
	{
		if(mainNodes[i].id == 'mid')
		{
			messageid = mainNodes[i].title;
		}
		else
		{
			if(mainNodes[i].childNodes.length > 0)
			{
				if(messageid == false)
					messageid = getInboxMessageId(mainNodes[i]);
			}
		}
	}
	return messageid;
}

function getInboxAnswerDiv(maindiv)
{
	var mainNodes = maindiv.childNodes;
	var answerDiv = false;
	for(var i = 0; i < mainNodes.length; i++)
	{
		if(mainNodes[i].id == 'inboxmessageanswer')
		{
			answerDiv = mainNodes[i];
		}
		else
		{
			if(mainNodes[i].childNodes.length > 0)
			{
				if(answerDiv == false)
					answerDiv = getInboxAnswerDiv(mainNodes[i]);
			}
		}
	}
	return answerDiv;
}

function getInboxFromId(maindiv)
{
	var mainNodes = maindiv.childNodes;
	var fromid = false;
	for(var i = 0; i < mainNodes.length; i++)
	{
		if(mainNodes[i].id == 'fid')
		{
			fromid = mainNodes[i].title;
		}
		else
		{
			if(mainNodes[i].childNodes.length > 0)
			{
				if(fromid == false)
					fromid = getInboxFromId(mainNodes[i]);
			}
		}
	}
	return fromid;
}

function selectAllInboxMessages()
{
	
	if($('#inboxmessages').length != 0)
	{
		
		var value = !$('#inboxoptionscheckbox').is(':checked');
		$('#inboxoptionscheckbox').attr('checked',value);
		
		var allCheckboxes = $('#inboxmessages').find('#inboxmessagecheckbox');
		for(var i = 0; i < allCheckboxes.length; i++)
			allCheckboxes[i].checked = value;	
	}
	else
	{
		var value = !$('#inboxoptionscheckbox').is(':checked');
		$('#inboxoptionscheckbox').attr('checked',value);
		
		var allCheckboxes = $('#outboxmessages').find('#inboxmessagecheckbox');
		for(var i = 0; i < allCheckboxes.length; i++)
			allCheckboxes[i].checked = value;	
	}
}

function markMultipleInboxMessages()
{
	$('#inboxmessages').find('#inboxmessageold, #inboxmessagenew').each(
			
			function(index,element)
			{
				if( $(element).find('#inboxmessagecheckbox').is(':checked') )
				{
					$.post('../clazzez/Ajax.php',{first:'markprivatemessage',second:$(element).find('#mid').attr('title')},
							function(msg)
							{
								if(msg == true)
								{
									$(element).attr('id','inboxmessageold');
									$(element).find('#inboxmessagecheckbox').attr('checked',false);
								}
							}
					);
				}
			}
	);
	$('#inboxoptionscheckbox').attr('checked',false);
}

function deleteMultipleInboxMessages()
{
	if($('#inboxmessages').length != 0)
	{
		$('#inboxmessages').find('#inboxmessageold, #inboxmessagenew').each(
				
				function(index,element)
				{
					if( $(element).find('#inboxmessagecheckbox').is(':checked') )
					{
						$.post('../clazzez/Ajax.php',{first:'deleteprivatemessage',second:$(element).find('#mid').attr('title'),third:'inbox'},
								function(msg)
								{
									if(msg == true)
									{
										$(element).hide();
									}
								}
						);
					}
				}
		);
	}
	else
	{
		$('#outboxmessages').find('#inboxmessageold, #inboxmessagenew').each(
				
				function(index,element)
				{
					if( $(element).find('#inboxmessagecheckbox').is(':checked') )
					{
						$.post('../clazzez/Ajax.php',{first:'deleteprivatemessage',second:$(element).find('#mid').attr('title'),third:'outbox'},
								function(msg)
								{
									if(msg == true)
									{
										$(element).hide();
									}
								}
						);
					}
				}
		);
	}


	$('#inboxoptionscheckbox').attr('checked',false);
}

var recipients = new Array();

function getMailPopup(uid)
{
	var mailPopup;
	$.post('../clazzez/Ajax.php',{first:'mailpopup',second:uid},function(msg){
		$(msg).dialog({title:'Send a private message',resizable:false,width:'430px', draggable:false, modal:true, close: function(event, ui) {$("#mailpopup").remove();}}).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
		$('.cancelmessage').click(function(){
			$("#mailpopup").dialog('close');
		});
		$("#recepient").tokenInput("../clazzez/Ajax.php?first=recepientquerry", {onAdd:function(item){
				recipients[recipients.length] = item.id;
				$("#recwarning").fadeOut();
		}, onDelete:function(item){
			recipients = jQuery.grep(recipients, function(n, i){
				return n != item.id;
			});
		}});
	});
}

function getMailReplyPopup(id, name){
	var uid= '';
	recipients[recipients.length] = id;
	$.post('../clazzez/Ajax.php',{first:'mailpopup',second:uid},function(msg){
		$(msg).dialog({title:'Send a private message',resizable:false,width:'430px', draggable:false, modal:true, close: function(event, ui) {$("#mailpopup").remove();}}).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
		$('.cancelmessage').click(function(){
			$("#mailpopup").dialog('close');
		});
		$("#recepient").tokenInput("../clazzez/Ajax.php?first=recepientquerry",  {onAdd:function(item){
				recipients[recipients.length] = item.id;
				$("#recwarning").fadeOut();
		}, onDelete:function(item){
			recipients = jQuery.grep(recipients, function(n, i){
				return n != item.id;
			});
		}, prePopulate: [{id:id, name:name}]});
	});
}

function sendMail()
{
	var message = $('#mailmessage').val();
	if(recipients.length > 0){
		if(message != ''){
			$('#mailmessage').css('borderColor', '#91AA9D');
		$.post('../clazzez/Ajax.php',{first:'sendprivatemessage',second:recipients,third:message},
			function(msg)
			{
				if(msg){
					$("#mailpopup").dialog('close');
					recipients = new Array();
					showAlert('Your message has been sent.');
				}
			});
		}
		else{$('#mailmessage').css('borderColor', 'red');}
	}
	else $("#recwarning").fadeIn();
}

function saveTip(){
	//get all the data
	var specieid = $("#specietipselector").val();
	var breedid = $("#breedtipselector").val();
	var title = $("#ntiptitle").val();
	var categorie = $("#ntipcategorie").val();
	var content = $("#ntipcontent").val();
	var id = $("#ntiptitle").attr('rel');
	//see if everything is filled out nicely
	if(title == ""){
		$("#ntiptitle").css('borderColor', 'red');
		return false;
	}else if(content == ""){
		$("#ntipcontent").css('borderColor', 'red');
		return false;
	}else if(categorie ==""){
		$("#ntipcategorie").css('borderColor', 'red');
		return false;
	}
	//post the updated data to the database;
	$.post('../clazzez/Ajax.php', {first:'savetip', id:id, specieid:specieid, breedid:breedid, title:title, categorie:categorie, content:content}, function(e){
		
		$("#edittipwrapper").dialog('close');
		updateTips();
		if(e != '')
			$('<div title="An error has occured">'+e+'</div>').dialog({ height: 80, modal: true });
	});
}

function updateTips(){
	$.post("../clazzez/Ajax.php", {first:'loadmoretips', second:0, third:($("#loadmoretips").attr('start'))}, function(e){
		$("#tips").html(e);
		
		assignEditTipHandlers();
		$.post("../clazzez/Ajax.php", {first:'canloadmoretips', second:parseInt($("#loadmoretips").attr('start'))}, function(i){
			if(!i){
				$("#loadmoretips").fadeOut();
			}
		});
		
	});
}

function inboxAcceptFriend(button)
{
	var button = $("#"+button.id);
	button.parent().fadeOut();
	$.post('../clazzez/Ajax.php',{first:'acceptfriend',second:$(button).attr('id')},function(msg){ $(button.parentNode).html('Accepted');});
}

function inboxIgnoreFriend(button)
{
	var button = $("#"+button.id);
	button.parent().fadeOut();
	$.post('../clazzez/Ajax.php',{first:'denyfriend',second:$(button).attr('id')},function(msg){ $(button.parentNode).html('Ignored');});
}

function toggleRegisterCommercial()
{
	if($('#commercialRegister').dialog('isOpen') != true){
		$('#commercialRegister').dialog({ resizable: false,dialogClass:'commercialRegister', modal:true, width:500, position:'center' }).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
		$('#crfsubmit').click(function(){registerCommercial($('#commercialRegister').find('form'));});
	}
	else
		$('#commercialRegister').dialog('close');
}

function registerCommercial(form)
{
	var errors = false;
	var password;
	
	form.find('input').each(
			function()
			{
				if(errors)
					return;
				if($(this).val() == '')
				{
					
					$(this).addClass('warning');
					errors = true;
					return;
				}
				else
				{
					$(this).removeClass('warning');
				}
				
				if($(this).attr('name') == 'owner'){
					if(!$(this).is(':checked')){
						$("#checkerror").show();
						errors = true;
						return;
					}
					else{
						$("#checkerror").hide();
						errors = false;
					}
				}
				
				if($(this).attr('name') == 'password')
					password = $(this);
				if($(this).attr('name') == 'confirm_password' && ( password.val() != $(this).val() || password.val().length < 6 || $(this).val().length < 6))
				{
					$(this).addClass('warning');
					password.addClass('warning');
					errors = true;	
				}
				if($(this).attr('name') == 'email'){
					var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
					if(!emailReg.test($(this).val())){
						$(this).addClass('warning');
						errors = true;
					}
					else $(this).removeClass('warning');
				}
			});
	
	if(!errors)
	{
		//alert('fname: '+form.find('input[name=first_name]').val()+'\n lname: '+form.find('input[name=last_name]').val()+'\n cname: '+form.find('input[name=company_name]').val()+'\n email: '+form.find('input[name=email]').val()+'\n pword: '+form.find('input[name=password]').val()+'\n cpword: '+form.find('input[name=confirm_password]').val()+'\n type: '+form.find('#company_type').val());
		$.post('../clazzez/Proccez.php',{
			registercommercial:true,
			first_name:form.find('input[name=first_name]').val(),
			last_name:form.find('input[name=last_name]').val(),
			company_name:form.find('input[name=company_name]').val(),
			email:form.find('input[name=email]').val(),
			password:form.find('input[name=password]').val(),
			confirm_password:form.find('input[name=confirm_password]').val(),
			type:form.find('#company_type').val()},
			function(msg)
			{
				//alert(msg);
				if(msg == 1)
				{
					toggleRegisterCommercial();
					$('<div>You\'ve successfully registered a business account on Petterz.<br><br>An email has been sent to '+form.find('input[name=email]').val()+' to verify your email address. Please follow the instructions in the email to proceed. Thank you for registering at Petterz.</div>').dialog({modal:true, resizable:false, draggable:false, title:'Registration Successful'});
				}
				else{
					var error = $.parseJSON(msg);
					$('<div id="businesserror" style="color:#3E606F;">The following error occured while registering:<br /><br />'+error.error+'<br /><br /></div>').dialog({modal:true, resizable:false, draggable:false, title:'An error occured'});
				}
			});
	}
}

function countDescription()
{
	if($('#description').val().length >= 500)
		$('#description').val(replaceAtIndex($('#description').val(),499,''));
}

function replaceAtIndex(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}

function addProductSettingsHandlers(){
	//enable adding of a product
	$('.addproductbutton').click(function(e){addProductButton(e);});
	
	//enables editing of a product
	$(".prodsettingsBlockOptions input[type='button']").click(function(e){
		
		var action = $(this).attr('action');
		
		//select a picture
		if(action == 'upload'){
			selectProductPicture($(this).attr('rel'));
		}
		//editing of a product
		else if(action == 'edit'){
			$.post('../clazzez/Ajax.php', {first:'editproduct', second:$(this).attr('rel')}, function(a){
				$(a).dialog({ resizable: false,modal:true, width:'auto', position:'center',close:function(){$('#editproduct').remove();} }).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
				$('#saveproduct').click(function(){
					$('#productform input:text, #productform textarea').each(function(){
						if($(this).val().length == 0)
							$(this).addClass('warning');
						else $(this).removeClass('warning');
					});
					if($(".warning").length == 0){
						$.post('../clazzez/Ajax.php', $("#productform").serialize(), function(b){
							$('#psettings').html(b);
							$('#editproduct').dialog('close');
							addProductSettingsHandlers();
						});
					}
				});
				$('#cancelproduct').click(function(){$('#editproduct').dialog('close');});
			});
		}
		//deletions
		else if(action == 'delete'){
			//show the warning first
			$(".toggledeletion[rel='"+$(this).attr('rel')+"']").slideDown();
		}
		else if(action == 'suredelete'){
			$.post('../clazzez/Ajax.php', {first:'deleteproduct', second:$(this).attr('rel')}, function(e){
				$("#psettings").html(e);
				addProductSettingsHandlers();
			});
		}
		
	});
}

function selectProductPicture(pid){
	//see if the business account has the product pictures 
	$.post('../clazzez/Ajax.php', {first:'selectproductpicture', second:pid}, function(e){
		$(e).dialog({ resizable: false,modal:true, width:500, position:'center',close:function(){$('#selectproductpicture').remove();} }).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
		addAlbumManagementHandlers();
		$("#selectproductpicture #close").click(function(){$("#selectproductpicture").dialog('close');});
		$("#selectproductpicture img").click(function(){
			$("#selectproductpicture img").each(function(){
				$(this).removeClass('selectedproductpicture');
			});
			$(this).addClass('selectedproductpicture');
			$("#selectproductpicture input[name=saveprod]").attr('rel', $(this).attr('rel'));
			$("#selectproductpicture input[name=deletepics]").attr('rel', $(this).attr('rel'));	
		});
		$("#selectproductpicture input[name=saveprod]").click(function(){
			if($(this).attr('rel') == '' || $(this).attr('rel') == null){
				$("#selectproductpicture #savewarning").slideDown();
			}else{
				$.post('../clazzez/Ajax.php', {first:'saveproductpicture', second:$(this).attr('rel'), third:$(this).attr('p')}, function(p){
					$('#psettings').html(p);
					$('#selectproductpicture').dialog('close');
					addProductSettingsHandlers();
				});
			}
		});
		$("#selectproductpicture input[name=deletepics]").click(function(){
			if($(this).attr('rel') == '' || $(this).attr('rel') == null){
				$("#selectproductpicture #savewarning").slideDown();
			}else{
				$.post('../clazzez/Ajax.php', {first:'deleteproductpicture', second:$(this).attr('rel')}, function(p){
					$('#selectproductpicture').dialog('close');
					$('#psettings').html(p);
					selectProductPicture(pid);
					addProductSettingsHandlers();
				});
			}
		});
	});
}

function addProductPictureHandlers(){
	$(".ppicture").click(function(){
		$.post('../clazzez/Ajax.php', {first:'getppicturepopup', second:$(this).attr('rel')}, function(e){
			$(e).dialog({ resizable: false,modal:true, width:'auto', position:'center',close:function(){$('#ppicture').remove();} }).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
			$("#ppicture #close").click(function(){$("#ppicture").dialog('close');});
		});
	});
}

var newnoticon;

function addBlinkingNotificationsHandlers(){
	if($(".newnotifications").length > 0){
		//we got new notifications
		blinking = setInterval(blinkNotificationIcon, 1000);

	}
}

function blinkNotificationIcon(){
	if($(".newnotifications").length > 0){
		newnoticon = $(".newnotifications");
		newnoticon.removeClass('newnotifications');
	}
	else newnoticon.addClass('newnotifications');
}

function addProductCareHandlers(){
	$(".careproduct a").click(function(){
		var rel = $(this).attr('rel');
		$.post('../clazzez/Ajax.php', {first:'careproduct', second:rel}, function(e){
			$(".careproduct[rel="+rel+"]").html(e);
		});
	});
}

function addChristmasCompetitionHandlers(){
	$("#vote").click(function(){
		addVote($(this).attr('rel'));
	});
	
	//add the countdown functionality
	var newYear = new Date(); 
	newYear = new Date("December 1, 2011 23:59:59"); 
	try {
		$("#countdown").countdown({until: newYear});
		//first show the contestors
		$(".contestor").each(function(i){
			$(this).delay(i*200).fadeIn(2000);
		});
	} catch (e) {
	}
	
	
	//handlers for entering the contest
	$("#enter-contest").click(function(){
		$.post(ajax, $("#enter-christmas-comp-form").serialize(), function(e){
			
			try {
				errors = $.parseJSON(e);
				$('<div>'+errors.error+'</div>').dialog({title:errors.type});
				return;
			} catch (e) {

			}
			$("#christmascont").html(e);
			addChristmasCompetitionHandlers();
			
		})
	});
	
	//handlers for leaving the contest
	$("#leave-contest").click(function(){
		var id = $(this).attr('rel');
		$("#sure-leave-contest").slideDown();
		$("#sure-leave-contest input[type=button]").click(function(){
			$.post(ajax, {first:'leavechristmascomp', second:id}, function(e){
				$("#christmascont").html(e);
				addChristmasCompetitionHandlers();
			})
		});
	});
	/*
	$(".contestor").hover(function(){
		$(".conthoverer").remove();
		var contestor = $(this);
		$.post(ajax, {first:'getcontestorhover', second:contestor.attr('rel')}, function(e){
			$('body').append(e);
			var hoverer = $(".conthoverer");
			hoverer.css('left', contestor.offset().left + contestor.width()/2 - hoverer.width()/2 +'px');
			hoverer.css('top', contestor.offset().top + contestor.height()/2 + 40+'px');
		});
	}, function(){
		$(".conthoverer").remove();
	});
	*/
	//the rules
	$(".christmasrules").click(function(){
		$.post(ajax, {first:'getchristmasrulespopup'}, function(e){
			$(e).dialog({modal:true, width:'600px', resizable:false});
			setPermissionsOnElements();
		});
	});
}

function setPermissionsOnElements(){
	$("*[req='member']").each(function(e){
		$(this).data('onClick', this.onclick);
			$.post(ajax, {first:'islogged'}, function(a){
				if(a){
					this.onclick = $(this).data('onClick');
				}
				else{
					$("*[req='member']").each(function(){
						$(this).unbind('click');
						this.onclick = function(event) {
							 $('#mustlogin').dialog({height:'420', width:'600',resizable:false, draggable:false, modal:true}).parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
							 $("#closemustlogin").click(function(){
								 $("#mustlogin").dialog('close');
							 });
						     return false;
						};
					});
				}
			});
		
	});
}
