﻿Shadowbox.init({
	language:   "en",
	players:    ["iframe", "html"]
});

$(document).ready(function(){
	setupLogin();
	setupPoll();
	setupLikes();
	setupComments();
	setupRegistration();
	setupBookmarks();
	setupPortfolio();
	setupBlogImages();
	setupSettingsAndPortfolioLinks();
	setupUserSettings();
	setupPortfolioEdit();
	setupToolTip();
	setupLatestTip();
	//setupCursorialScroll();
	//setupEventsScroll();
	
	
	
	/*
	Shadowbox.open({
		content:    '/shadowbox/vaelkommen/',
		player:		'iframe',
		title:      "Välkommen",
		height:     531,
		width:      460
	});	
	*/
	
	window.onload = function() {
		
		var site_type = $.cookie('site_type');
		var mediesverige_popup = $.cookie('mediesverige_popup');
		var reklamsverige_popup = $.cookie('reklamsverige_popup');
		
		if (site_type == "mediesverige") {
			if (mediesverige_popup == null) {
				$.cookie('mediesverige_popup', 'set');
				Shadowbox.open({
					content:    '/images/site/intro-mediesverige.png',
					player:		'iframe',
					title:      "Välkommen",
					height:     548,
					width:      867
				});
			}
		}
		else if (site_type == "reklamsverige") {
			if (reklamsverige_popup == null) {
				$.cookie('reklamsverige_popup', 'set');
				Shadowbox.open({
					content:    '/images/site/intro-reklamsverige.png',
					player:		'iframe',
					title:      "Välkommen",
					height:     548,
					width:      867
				});
			}
		}
		else if (site_type == null) {
			if (mediesverige_popup == null) {
				$.cookie('mediesverige_popup', 'set');
				Shadowbox.open({
						content:    '/images/site/intro-mediesverige.png',
						player:		'iframe',
						title:      "Välkommen",
						height:     548,
						width:      867
					});
			}
		}
		
	};
	/*
	Shadowbox.open({
			content:    '/shadowbox/villkor/',
			player:		'iframe',
			title:      "Villkor",
			height:     531,
			width:      460
		});
	*/
});

function setupLogin() {
	if ($('.login-area').length == 0)
		return;
	
	$('.login-area .password-input-clear').focus(function() {
		$('.login-area .password-input-clear').css('display', 'none');
		$('.login-area .password-input').css('display', 'block');
		$('.login-area .password-input').focus();
	});
	$('.login-area .password-input').blur(function() {
		if ($('.login-area .password-input').val() == '') {
			$('.login-area .password-input').css('display', 'none');
			$('.login-area .password-input-clear').css('display', 'block');
		}
	});
}

function setupPoll() {
	$('.vote .vote-link').click(function() {
		$('.vote .vote-link').text('');
		var num = $(this).parent().find('.answer-num').text();
		var id = $('#poll_id').text();
		
		$.ajax({
			  url: '/ajax/pollvote/',
			  type: 'POST',
			  data: {answer_num:num, poll_id:id},
			  success: function (data) {
				if (data.perc) {
					$('.vote .answer:eq(0)').find('.perc').text(data.perc[0] + '%');
					$('.vote .answer:eq(1)').find('.perc').text(data.perc[1] + '%');
					$('.vote .answer:eq(2)').find('.perc').text(data.perc[2] + '%');
					
					$('.vote .answer:eq(0)').find('.bar').css("width", data.perc[0] + '%');
					$('.vote .answer:eq(1)').find('.bar').css("width", data.perc[1] + '%');
					$('.vote .answer:eq(2)').find('.bar').css("width", data.perc[2] + '%');
				}
				
			  },
			  dataType: 'json'
		});
		
		return false;
	});
}

function setupLikes() {
	$('.blog-page .entry .likes-link').click(likesBlog);
	$('.start-blog .top-entry .likes-link').click(likesBlog);
	$('.latest-blog-entry .likes-link').click(likesBlog);
	$('.portfolio .entry .likes-link').click(likesPortfolio);
	$('.portfolio .top-entry .likes-link').click(likesPortfolio);
	$('.header .likes-link').click(likesSite);
}

function likesBlog() {
	var blog_id = $(this).parent().parent().parent().find('.blog-id').text();
	likes($(this), blog_id, "blog");
	return false;
}

function likesPortfolio() {
	var portfolio_id = $(this).parent().parent().parent().find('.portfolio-id').text();
	likes($(this), portfolio_id, "portfolio");
	return false;
}

function likesSite() {
	likes($(this), null, "site");
	return false;
}

function likes(a_link, a_id, a_type) {
	$.ajax({
		  url: '/ajax/likes/',
		  type: 'POST',
		  data: {id:a_id, type:a_type},
		  success: function (data) {
			
		  }
	});
	
	var num = parseInt(a_link.siblings('.likes').text());
	num = num + 1;
	a_link.siblings('.likes').text(num);
	
	a_link.text('');
}

var loadedComments = new Array();
var openComments = new Array();
var sendingComment = false;

function setupComments() {
	$('.start-blog .top-entry .actions .comment-link').click(blogCommentClick);
	$('.blog-page .entry .actions .comment-link').click(blogCommentClick);
	$('.portfolio .actions .comment-link').click(portfolioCommentClick);
	
	$('.start-blog .top-entry .comments .submit-button').click(blogSubmitClick);
	$('.blog-page .entry .comments .submit-button').click(blogSubmitClick);
	$('.portfolio .comments .submit-button').click(portfolioSubmitClick);
	
	$('.blog-page').find('.entry').each(function(i,element) {
		if (!$(element).find('.comments').hasClass('hidden')) {
			var entry_id = $(element).find('.blog-id').text();
			var commentDiv = $(element).find('.comments');
			comment(entry_id, "blog", commentDiv);
		}
	});
}

function blogCommentClick()
{
	var entry_id = $(this).parent().parent().parent().find('.blog-id').text();
	var commentDiv = $(this).parent().parent().parent().find('.comments');
	comment(entry_id, "blog", commentDiv);
	return false;
}

function portfolioCommentClick()
{
	var entry_id = $(this).parent().parent().parent().find('.portfolio-id').text();
	var commentDiv = $(this).parent().parent().parent().find('.comments');
	comment(entry_id, "portfolio", commentDiv);
	return false;
}

function comment(a_id, a_type, a_comment_div)
{
	if (!loadedComments[a_type])
		loadedComments[a_type] = new Array();
	if (!openComments[a_type])
		openComments[a_type] = new Array();
		
	var commentList = a_comment_div.find('.comments-list');

	if (!loadedComments[a_type][a_id]) {
		loadedComments[a_type][a_id] = true;
		$.ajax({
			url: '/ajax/comments/',
			type: 'POST',
			data: {type:a_type,id:a_id},
			success: function(data){
				placeComments(commentList, data);
			},
			dataType: 'json'
		});
	}
	
	if (openComments[a_type][a_id]) {
		openComments[a_type][a_id] = false;
		a_comment_div.slideUp('slow', function() {
		
		});
	}
	else {
		openComments[a_type][a_id] = true;
		a_comment_div.slideDown('slow', function() {
		
		});
	}
}

function blogSubmitClick()
{
	if (sendingComment)
			return;
		
	sendingComment = true;
	
	var _id = $(this).parent().parent().find('.blog-id').text();
	submitComment($(this), "blog", _id);
}

function portfolioSubmitClick()
{
	if (sendingComment)
			return;
		
	sendingComment = true;
	
	var _id = $(this).parent().parent().find('.portfolio-id').text();
	submitComment($(this), "portfolio", _id);
}

function submitComment(a_submit, a_type, a_id)
{
	var _name = a_submit.parent().find('.name-input').val();
	var _email = a_submit.parent().find('.email-input').val();
	var _comment = a_submit.parent().find('textarea').val();
	
	var commentDiv = a_submit.parent().find('.comments-list');

	$.ajax({
		url: '/ajax/comments/',
		type: 'POST',
		data: {type:a_type,id:a_id,name:_name,email:_email,comment:_comment},
		success: function(data){
			sendingComment = false;
			placeComments(commentDiv, data);
		},
		dataType: 'json'
	});
	
	a_submit.parent().find('textarea').val('');
}

function placeComments(commentDiv, data)
{
	commentDiv.text('');
	$(data.comments).each(function(i, comment){
		commentDiv.append('<div class="comment">'
							+'<div class="comment-id hidden">'+comment.comment_id+'</div>'
							+'<div class="author"><a href="'+comment.author_url+'">'+comment.author+'</a></div>'
							+'<div class="date">'+comment.date+'</div>'
							+'<div class="text">'+comment.comment+'</div>'
							+'<div class="report"><a href="">Anmäl kommentar »</a></div>'
							+'<div class="comment-separator">//</div>'
							+'</div>');
	});
	
	$(commentDiv).find('.comment .report a').unbind();
	$(commentDiv).find('.comment .report a').click(function() {
		var id = $(this).parent().parent().find('.comment-id').text();
			$.ajax({
			url: '/ajax/report-comment/',
			type: 'POST',
			data: {'comment_id':id},
			success: function(data) {
			},
			dataType: 'json'
		});
		$(this).parent().text('Anmäld!');
		return false;
	});
}

var registration_step = 1;
var switching = false;
var fileUpload;
var profile_name_ok = false;
var profile_name_checking = false;
var email_ok = false;
var email_checking = false;

function setupRegistration()
{
	if($('.register').length == 0)
		return;

	$('.register .box1').fadeIn();
	
	$('.register .prev-button').click(registrationPrev);
	$('.register .next-button').click(registrationNext);
	
	$('.register .terms-link').click(function() {
		Shadowbox.open({
			content:    '/shadowbox/villkor/',
			player:		'iframe',
			title:      "Villkor",
			height:     531,
			width:      460
		});

		return false;
	});
	
	$('.register .whyshouldichoose-link').click(function() {
		Shadowbox.open({
			content:    '/shadowbox/varfor-maste-jag-valja/',
			player:		'iframe',
			title:      "Varfor maste jag valja?",
			height:     200,
			width:      300
		});

		return false;
	});
	
	updateRegistrationControls();
	
	fileUpload = new AjaxUpload('upload-button', {
	  // Location of the server-side upload script
	  // NOTE: You are not allowed to upload files to another domain
	  action: '/ajax/create-member/',
	  // File upload name
	  name: 'userfile',
	  // Additional data to send
	  //data: {
	  //	example_key1 : 'example_value',
	  //	example_key2 : 'example_value2'
	  // },
	  // Submit file after selection
	  autoSubmit: false,
	  // The type of data that you're expecting back from the server.
	  // HTML (text) and XML are detected automatically.
	  // Useful when you are using JSON data as a response, set to "json" in that case.
	  // Also set server response type to text/html, otherwise it will not work in IE6
	  responseType: "json",
	  // Fired after the file is selected
	  // Useful when autoSubmit is disabled
	  // You can return false to cancel upload
	  // @param file basename of uploaded file
	  // @param extension of that file
	  onChange: function(file, extension){
		$('.register .box3 .upload-input').val(file);
	  },
	  // Fired before the file is uploaded
	  // You can return false to cancel upload
	  // @param file basename of uploaded file
	  // @param extension of that file
	  onSubmit: function(file, extension) {},
	  // Fired when file upload is completed
	  // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
	  // @param file basename of uploaded file
	  // @param response server response
	  onComplete: registerSubmitComplete
	});
}

function updateRegistrationControls()
{
	if (registration_step == 1) {
		$('.register .prev-button').addClass('prev-button-inactive');
	}
	else if (registration_step == 6) {
		$('.register .prev-button').addClass('prev-button-inactive');
		$('.register .next-button').addClass('next-button-inactive');
		$('.register .prev-button').fadeOut();
		$('.register .next-button').fadeOut();
	}
	else {
		$('.register .prev-button').removeClass('prev-button-inactive');
	}
	
	$('.register .indikator').removeClass('indikator-active');
	$('.register .indikator' + registration_step).addClass('indikator-active');
}

function registrationPrev()
{
	if (switching)
		return;
	
	if (registration_step == 1 || registration_step == 6)
		return;
		
	switching = true;
	
	$('.register .box' + registration_step).fadeOut('lagom', function() {
		$('.register .box' + registration_step).fadeIn('lagom', function() {
			switching = false;
		});
	});
	
	registration_step--;
	updateRegistrationControls();
}

function registrationNext()
{
	if (switching)
		return;
	
	var firstName = $('.register .box1 .first-name-input').val();
	var lastName = $('.register .box1 .last-name-input').val();
	var memberType = $('.register .box2 select option:selected').val();
	var email = $('.register .box2 .email-input').val();
	var city = $('.register .box2 .city-input').val();
	var country = $('.register .box2 .country-input').val();
	var job = $('.register .box2 .job-input').val();
	var file = $('.register .box3 .upload-input').val();
	var profileName = $('.register .box4 .profile-input').val();
	var termsCheck = $('.register .box5 .checkbox-input:checked').val();
	var password = $('.register .box5 .password-input').val();
	var passwordRepeat = $('.register .box5 .password-repeat-input').val();
	
	if (registration_step == 1) {
		if (firstName == "" || lastName == "") {
			registrationMessage("Du måste ange för och efternamn");
			return;
		}
	}
	else if (registration_step == 2) {
		if (memberType == "chose") {
			registrationMessage("Du måste välja vilken sida du vill bli medlem på");
			return;
		}
		if (email == "" || city == "" || country == "" || job == "") {
			registrationMessage("Du måste fylla i alla fält");
			return;
		}
		if (email_checking) {
			return;
		}
		if (!email_ok) {
			email_checking = true;
			registrationMessage("Kontrollerar email...");
			$('.register .next-button').addClass('nav-button-inactive');
			checkEmail(email);
			return;
		}
		email_ok = false;
	}
	else if (registration_step == 3) {
		if (file == "") {
			registrationMessage("Du måste välja en profilbild");
			return;
		}
	}
	else if (registration_step == 4) {
		if (profileName == "") {
			registrationMessage("Du måste ange ett profilnamn");
			return;
		}
		if (profile_name_checking) {
			return;
		}
		if (!profile_name_ok) {
			profile_name_checking = true;
			registrationMessage("Kontrollerar profilnamn...");
			$('.register .next-button').addClass('nav-button-inactive');
			checkProfilename(profileName);
			return;
		}
		profile_name_ok = false;
	}
	else if (registration_step == 5) {
		if (password == "") {
			registrationMessage("Du måste ange ett lösenord");
			return;
		}
		if (password != passwordRepeat) {
			registrationMessage("Lösenordet stämmer inte överens med det verifierade lösenordet");
			return;
		}
		if (termsCheck != "agree") {
			registrationMessage("Du måste godkänna villkoren");
			return;
		}
	}
	else if (registration_step == 6) {
		return;
	}
	
	registrationMessage("");
	
	switching = true;
	$('.register .box' + registration_step).fadeOut('lagom', function() {
		$('.register .box' + registration_step).fadeIn('lagom', function() {
			switching = false;
			
			if (registration_step == 6) {
				createMember(firstName, lastName, memberType, email, city, country, job, profileName, password);
			}
		});
	});
	
	registration_step++;
	updateRegistrationControls();
}

function registrationMessage(message)
{
	$('.register .message').text(message);
}

function createMember(firstName, lastName, memberType, email, city, country, job, profileName, password)
{
	fileUpload.setData({'first_name': firstName, 'last_name': lastName, 'member_type': memberType, 'email': email, 'city': city, 'country': country, 'job': job, 'profile_name': profileName, 'password': password});
	fileUpload.submit();
}

function registerSubmitComplete(file, response)
{
	$('.register .box6 h1').text('6. Klart!');
	$('.register .box6 .finished-message').fadeIn();
}

function checkEmail(mail)
{
	$.ajax({
		url: '/ajax/check-email/',
		type: 'POST',
		data: {email:mail},
		success: function(data){
			email_checking = false;
			$('.register .next-button').removeClass('nav-button-inactive');
			if (data == "ok") {
				email_ok = true;
				registrationNext();
			}
			else {
				registrationMessage("Din epost är redan registrerad!");
			}
		},
		dataType: 'json'
	});
}

function checkProfilename(name)
{
	$.ajax({
		url: '/ajax/check-profilename/',
		type: 'POST',
		data: {profile_name:name},
		success: function(data){
			profile_name_checking = false;
			$('.register .next-button').removeClass('nav-button-inactive');
			if (data == "ok") {
				profile_name_ok = true;
				registrationNext();
			}
			else {
				registrationMessage("Ditt profilnamn är upptaget, pröva nåt annat!");
			}
		},
		dataType: 'json'
	});
}

function setupBookmarks()
{
	if ($('.actions .bookmark-link').length > 0) {
		$('.blog-page .entry .actions .bookmark-link').click(bookmarkBlog);
		$('.latest-blog-entry .actions .bookmark-link').click(bookmarkBlog);
		$('.start-blog .top-entry .actions .bookmark-link').click(bookmarkBlog);
		$('.portfolio .actions .bookmark-link').click(bookmarkPortfolio);
	}
	if ($('.add-friend-link').length > 0) {
		$('.add-friend-link').click(bookmarkMember);
	}
}

function bookmarkBlog()
{
	var entry_id = $(this).parent().parent().parent().find('.blog-id').text();
	bookmark($(this), "blog", entry_id);
	return false;
}

function bookmarkPortfolio()
{
	var entry_id = $(this).parent().parent().parent().find('.portfolio-id').text();
	bookmark($(this), "portfolio", entry_id);
	return false;
}

function bookmarkMember()
{
	var target_member_id = $(this).parent().find('.target-member-id').text();
	bookmark($(this), "member", target_member_id);
	return false;
}

function bookmark(a_link,a_type,a_id)
{
	$.ajax({
		url: '/ajax/bookmark/',
		type: 'POST',
		data: {type:a_type,type_id:a_id},
		success: function(data){
		},
		dataType: 'json'
	});
	a_link.text('Bokmärkt!');
}

var openImages = new Object();

function setupPortfolio()
{
	if ($('.portfolio').length == 0)
		return;
		
	$('.portfolio .entry .more-images-link').click(function() {
		var entry = $(this).parent();
		portfolioToggleMoreImages(entry);		
		return false;
	});
	
	$('.portfolio .entry .more-images-link2').click(function() {
		var entry = $(this).parent().parent();
		portfolioToggleMoreImages(entry);
		return false;
	});
	
	$('.portfolio .entry .more-images-link3').click(function() {
		var entry = $(this).parent().parent().parent();
		portfolioToggleMoreImages(entry);
		return false;
	});
	
	$('.portfolio .entry .delete-link').click(function() {

		var id = $(this).parent().parent().find('.portfolio-id').text();
		
		$.ajax({
			url: '/ajax/delete-portfolio/',
			type: 'POST',
			data: {'portfolio_id':id},
			success: function(data){
			},
			dataType: 'json'
		});
		
		$(this).parent().parent().remove();
		location.href = "/community/min-profil/portfolio/";
		return false;
	});
	
}

function portfolioToggleMoreImages(entry)
{
	var id = $(entry).find('.portfolio-id').text();
		
	if (openImages[id]) {
		openImages[id] = false;
		$(entry).find('.additional-images').slideUp();
		$(entry).find('.more-images-link a').text('Se fler bilder »');
		$(entry).find('.images-arrow').fadeIn();
	}
	else {
		openImages[id] = true;
		$(entry).find('.additional-images').slideDown();
		$(entry).find('.more-images-link a').text('Göm bilder «');
		$(entry).find('.images-arrow').fadeOut();
	}
}

function setupBlogImages()
{
	if ($('.start-blog .top-entry').length != 0) {
		$('.start-blog .top-entry .show-additional-images-link').toggle(function() {
			$(this).parent().find('.additional-images').slideDown();
			$(this).parent().parent().find('.images-arrow').fadeOut();
			return false;
		}, function() {
			$(this).parent().find('.additional-images').slideUp();
			$(this).parent().parent().find('.images-arrow').fadeIn();
			return false;
		});		
	}
	
	/*
	if ($('.blog-page .entry').legnth != 0) {
		$('.blog-page .entry .show-additional-images-link').toggle(function() {
			$(this).parent().find('.additional-images').slideDown();
			$(this).parent().find('.images-arrow').fadeOut();
			return false;
		}, function() {
			$(this).parent().find('.additional-images').slideUp();
			$(this).parent().find('.images-arrow').fadeIn();
			return false;
		});			
	}
	*/
}

var savingSettings = false;
var displayingSettings = false;
var displayingPortfolio = false;

var uploadingImage = false;
var profileImageChanged = false;
var profileImageUpload;

var uploadingCv = false;
var profileCvChanged = false;
var profileCvDeleted = false;
var profileCvUpload;

function setupSettingsAndPortfolioLinks()
{
	if ($('.usermenu').length == 0)
		return;
		
	if ($('.userstuff').length == 0)
		return;
		
	$('.usermenu .settings-link').click(function() {
		if (displayingPortfolio) {
			$('.userstuff2').slideToggle("lagom", function() {
				$('.userstuff').slideToggle();
				displayingPortfolio = false;
			});
		}
		else {
			$('.userstuff').slideToggle();
		}
		
		displayingSettings = !displayingSettings;
		
		return false;
	});
	
	$('.usermenu .portfolio-link').click(function() {
		if (displayingSettings) {
			$('.userstuff').slideToggle("lagom", function() {
				$('.userstuff2').slideToggle();
				displayingSettings = false;
			});
		}
		else {
			$('.userstuff2').slideToggle();
		}
		
		displayingPortfolio = !displayingPortfolio;
		
		return false;
	});
	
	$('.userstuff .close-link').click(function() {
		$('.userstuff').slideToggle();
		displayingSettings = false;
		return false;
	});
	$('.userstuff2 .close-link').click(function() {
		$('.userstuff2').slideToggle();
		displayingPortfolio = false;
		return false;
	});
}

var adsNew = new Object();
var adsModified = new Object();
var adsDeleted = new Object();
var localIdCounter = 1;

var rssSubscriptions = new Object();

function setupUserSettings()
{
	if ($('.userstuff .user-settings').length == 0)
		return;
	
	$('.userstuff .user-settings .activities .entry .delete-activity-link').click(function() {
		var id = $(this).parent().parent().find('.activity-id').text();
		
		$.ajax({
			url: '/ajax/delete-activity/',
			type: 'POST',
			data: { 'member_activity_id': id },
			success: function(data){
			},
			dataType: 'json'
		});
		
		$(this).parent().parent().remove();
		
		return false;
	});
	
	$('.userstuff .user-settings .rss .rss-entry input').change(function(e) {
		var id = $(this).val();
		var checked = $(this).attr("checked");
		rssSubscriptions[id] = checked;
	});
		
	$('upload-member-image a').click(function() {
		return false;
	});
	profileImageUpload = new AjaxUpload('upload-member-image', {
	  action: '/ajax/upload-member-image/',
	  name: 'userfile',
	  autoSubmit: false,
	  responseType: "json",
	  onChange: function(file, extension) {
		profileImageUpload.submit();
	  },
	  onSubmit: function(file, extension) {},
	  onComplete: function(file, response) {
		$('.userstuff .user-settings .profile-image img').attr('src', response);
		profileImageChanged = true;
	  }
	});
	
	$('.cv .add-thing .upload-link a').click(function() {
		return false;
	});
	profileCvUpload = new AjaxUpload('upload-member-cv', {
	  action: '/ajax/upload-member-cv/',
	  name: 'userfile',
	  autoSubmit: false,
	  responseType: "json",
	  onChange: function(file, extension) {
		profileCvUpload.submit();
	  },
	  onSubmit: function(file, extension) {},
	  onComplete: function(file, response) {
		$('.userstuff .user-settings .cv-text').html('<a href="' + response + '">CV</a>');
		$('.userstuff .user-settings .add-thing .delete-link').removeClass("hidden");
		profileCvChanged = true;
		profileCvDeleted = false;
	  }
	});
	$('.cv .add-thing .delete-link a').click(function() {
		$('.cv .cv-text').text('Ingen CV upplagd');
		$('.userstuff .user-settings .add-thing .delete-link').addClass("hidden");
		profileCvChanged = false;
		profileCvDeleted = true;
		return false;
	});
		
	$('.userstuff .user-settings .submit-input').click(function() {
		if (savingSettings)
			return false;
		savingSettings = true;
		
		var fullName = $('.user-settings .name-input').val();
		var jobTitle = $('.user-settings .job-input').val();
		var company = $('.user-settings .company-input').val();
		var companyUrl = $('.user-settings .company-url-input').val();
		var cityName = $('.user-settings .city-input').val();
		var statusTitle = $('.user-settings .status-title-input').val();
		var statusText = $('.user-settings .status-text-input').val();
		
		$.ajax({
			url: '/ajax/save-settings/',
			type: 'POST',
			data: {name:fullName,
				   job_title:jobTitle,
				   company_name:company,
				   company_url:companyUrl,
				   city:cityName,
				   status_title:statusTitle,
				   status_text:statusText,
				   image_change:profileImageChanged,
				   cv_change:profileCvChanged,
				   cv_delete:profileCvDeleted,
				   ads_new: adsNew,
				   ads_deleted: adsDeleted,
				   ads_modified: adsModified,
				   rss_subscriptions: rssSubscriptions
					},
			success: function(data){
				location.reload();
			},
			dataType: 'json'
		});
	});
	
	$('.userstuff .user-settings .ad .edit-link').click(adEditClick);
	$('.userstuff .user-settings .ad .delete-link').click(adDeleteClick);
	$('.userstuff .user-settings .ad .cancel-link').click(adCancelClick);
	$('.userstuff .user-settings .ad .ok-link').click(adOkClick);
	
	$('.userstuff .user-settings .add-ad-link').click(function() {
		var p = $('.userstuff .user-settings .add-ad-link').text();
		var newAd = $('.userstuff .user-settings .ad-template').clone(true);
		
		if($(newAd).find('.show .title'))
		{
			$('.userstuff .user-settings .add-ad-link').text('Lägg till en till löpsedel »');
		}
		else
		{
			$('.userstuff .user-settings .add-ad-link').text('Lägg till löpsedel »');
		}
		
		$(newAd).removeClass("ad-template");
		$(newAd).removeClass("hidden");
		$(newAd).addClass("ad");
		$(newAd).find('.show').addClass("hidden");
		$(newAd).find('.edit').removeClass("hidden");
		$(newAd).find('.show .title').text('Titel');
		$(newAd).find('.show .description').text('Beskrivning');
		$(newAd).find('.edit .title-input').val('Titel');
		$(newAd).find('.edit .description-input').val('Beskrivning');
		$(newAd).find('.ad-id').text(localIdCounter);
		$(newAd).prependTo('.userstuff .user-settings .right');
		
		var info = new Object();
		info["title"] = "Titel";
		info["description"] = "Beskrivning";
		adsNew[localIdCounter + ''] = info;
		
		localIdCounter++;
		
		$(newAd).find('.edit-link').click(adEditClick);
		$(newAd).find('.delete-link').click(adDeleteClick);
		$(newAd).find('.cancel-link').click(adCancelClick);
		$(newAd).find('.ok-link').click(adOkClick);
		
		return false;
	});
}

function adEditClick()
{
	$(this).parent().parent().parent().find('.show').addClass("hidden");
	$(this).parent().parent().parent().find('.edit').removeClass("hidden");
	return false;
}
function adDeleteClick()
{
	var ad = $(this).parent().parent().parent();
	var newAd = $(ad).hasClass("new-ad");
	var adId = $(ad).find('.ad-id').text();

	if (newAd) {
		delete adsNew[adId];
	}
	else {
		adsDeleted[adId] = adId;
	}
	
	$(this).parent().parent().parent().remove();
	
	//bipin
	if($('.userstuff .user-settings').find('.ad').text() != '')
	{
		$('.userstuff .user-settings .add-ad-link').text('Lägg till en till löpsedel »');
	}
	else
	{
		$('.userstuff .user-settings .add-ad-link').text('Lägg till löpsedel »');
	}
	return false;
}
function adCancelClick()
{
	$(this).parent().parent().parent().find('.edit').addClass("hidden");
	$(this).parent().parent().parent().find('.show').removeClass("hidden");
	
	return false;
}
function adOkClick()
{
	var ad = $(this).parent().parent().parent();
	
	var newAd = $(ad).hasClass("new-ad");
	var adId = $(ad).find('.ad-id').text();

	var title = $(ad).find('.title-input').val();
	var desc = $(ad).find('.description-input').val();
	
	if (newAd) {
		var info = adsNew[adId];
		info["title"] = title;
		info["description"] = desc;
		adsNew[adId] = info;
	}
	else {
		var info = adsModified[adId];
		if (info == null)
			info = new Object();
		info["title"] = title;
		info["description"] = desc;
		info["id"] = adId;
		adsModified[adId] = info;
	}
	
	$(ad).find('.show .title').text(title);
	$(ad).find('.show .description').text(desc);

	$(ad).find('.edit').addClass("hidden");
	$(ad).find('.show').removeClass("hidden");
	return false;
}

var portfolioType = "normal";
var portfolioNormalShowUploads = 1;
var portfolioJournalistShowUploads = 1;

var portfolioUploading = false;
var portfolioUploadingType;
var portfolioId;

var portfolioNormalUploads = new Array();
var portfolioNormalUploadsQueue = new Array();

var portfolioJournalistUploads = new Array();
var portfolioJournalistUploadsQueue = new Array();


function setupPortfolioEdit()
{	
	
	if($('.userstuff2 .portfolio-edit .portfolio-id').html() == '')
	{
		$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
		
	}
	else
	{
		var catval = $('.userstuff2 .portfolio-edit select option:selected').val();
		if(catval == 'normal')
		{
			$('.userstuff2 .portfolio-edit .normal .more-upload-link').css('display', 'inline');
			var divcnt = 1;
			var counterdiv = 0;
			for(divcnt = 1;  divcnt <= 7; divcnt++)
			{
				if($('.userstuff2 .portfolio-edit .normal .upload' + divcnt).css("display") != 'none')
				{
					counterdiv = counterdiv + 1;
				}
				
			}
			portfolioNormalShowUploads = counterdiv;
			
		}
		else
		{
			$('.userstuff2 .portfolio-edit .journalist .more-upload-link').css('display', 'inline');
			var divcnt = 1;
			var counterdiv = 0;
			for(divcnt = 1;  divcnt <= 7; divcnt++)
			{
				if($('.userstuff2 .portfolio-edit .journalist .upload' + divcnt).css("display") != 'none')
				{
					counterdiv = counterdiv + 1;
				}
				
			}
			portfolioJournalistShowUploads = counterdiv;
		
		}
	}
	
	
	if ($('.userstuff2 .portfolio-edit').length == 0)
		return;
		
	portfolioType = $('.userstuff2 .portfolio-edit select option:selected').val();
	portfolioNormalShowUploads = $('.userstuff2 .portfolio-edit .normal .num-files-set').text();
	
	$('.userstuff2 .portfolio-edit select').change(function() {
		var val = $('.userstuff2 .portfolio-edit select option:selected').val();
		portfolioType = val;
		if (val == "normal") {
			$('.userstuff2 .portfolio-edit .journalist').fadeOut("lagom", function() {
				$('.userstuff2 .portfolio-edit .normal').fadeIn("lagom", function() {
				});
			});
		}
		else {
			$('.userstuff2 .portfolio-edit .normal').fadeOut("lagom", function() {
				$('.userstuff2 .portfolio-edit .journalist').fadeIn("lagom", function() {
				});
			});
		}
	});
	
	$('.userstuff2 .portfolio-edit .normal .more-upload-link').click(function() {
		
		$(this).remove();
		
		if (portfolioNormalShowUploads == 7)
			return;
		
		portfolioNormalShowUploads++;
		$('.userstuff2 .portfolio-edit .normal .upload' + portfolioNormalShowUploads).fadeIn();
		$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
		return false;
	});
	
	$('.userstuff2 .portfolio-edit .journalist .more-upload-link').click(function() {
		
		$(this).remove();
		
		if (portfolioJournalistShowUploads == 7)
			return;
		
		portfolioJournalistShowUploads++;
		$('.userstuff2 .portfolio-edit .journalist .upload' + portfolioJournalistShowUploads).fadeIn();
		$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
		return false;
	});
	
	portfolioNormalUploads.push(new AjaxUpload('portfolio-normal-upload1', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .normal .upload1 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.jpg' || ext == '.jpeg' || ext == '.JPEG' || ext == '.gif' || ext == '.GIF' || ext == '.tif' || ext == '.png')
			{
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				
				$('.userstuff2 .portfolio-edit .normal .upload1 .file-input').css('borderColor', '#EBEBEB');
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'block');
				portfolioNormalUploadsQueue.push(0);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioNormalUploadsQueue.pop(0);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .normal .upload1 .file-input').css('borderColor', '#dc3a09');
			}
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioNormalUploads.push(new AjaxUpload('portfolio-normal-upload2', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .normal .upload2 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.jpg' || ext == '.jpeg' || ext == '.JPEG' || ext == '.gif' || ext == '.GIF' || ext == '.tif' || ext == '.png')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .normal .upload2 .file-input').css('borderColor', '#EBEBEB');
				portfolioNormalUploadsQueue.push(1);
				
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioNormalUploadsQueue.pop(1);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .normal .upload2 .file-input').css('borderColor', '#dc3a09');
			}
			
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioNormalUploads.push(new AjaxUpload('portfolio-normal-upload3', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .normal .upload3 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.jpg' || ext == '.jpeg' || ext == '.JPEG' || ext == '.gif' || ext == '.GIF' || ext == '.tif' || ext == '.png')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .normal .upload3 .file-input').css('borderColor', '#EBEBEB');
				portfolioNormalUploadsQueue.push(2);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioNormalUploadsQueue.pop(2);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .normal .upload3 .file-input').css('borderColor', '#dc3a09');
			}
			
			//portfolioNormalUploadsQueue.push(2);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioNormalUploads.push(new AjaxUpload('portfolio-normal-upload4', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .normal .upload4 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.jpg' || ext == '.jpeg' || ext == '.JPEG' || ext == '.gif' || ext == '.GIF' || ext == '.tif' || ext == '.png')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .normal .upload4 .file-input').css('borderColor', '#EBEBEB');
				portfolioNormalUploadsQueue.push(3);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioNormalUploadsQueue.pop(3);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .normal .upload4 .file-input').css('borderColor', '#dc3a09');
			}
			//portfolioNormalUploadsQueue.push(3);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioNormalUploads.push(new AjaxUpload('portfolio-normal-upload5', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .normal .upload5 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.jpg' || ext == '.jpeg' || ext == '.JPEG' || ext == '.gif' || ext == '.GIF' || ext == '.tif' || ext == '.png')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .normal .upload5 .file-input').css('borderColor', '#EBEBEB');
				portfolioNormalUploadsQueue.push(4);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioNormalUploadsQueue.pop(4);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .normal .upload5 .file-input').css('borderColor', '#dc3a09');
			}
			//portfolioNormalUploadsQueue.push(4);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioNormalUploads.push(new AjaxUpload('portfolio-normal-upload6', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .normal .upload6 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.jpg' || ext == '.jpeg' || ext == '.JPEG' || ext == '.gif' || ext == '.GIF' || ext == '.tif' || ext == '.png')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .normal .upload6 .file-input').css('borderColor', '#EBEBEB');
				portfolioNormalUploadsQueue.push(5);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioNormalUploadsQueue.pop(5);
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				$('.userstuff2 .portfolio-edit .normal .upload6 .file-input').css('borderColor', '#dc3a09');
			}
			//portfolioNormalUploadsQueue.push(5);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	
	portfolioNormalUploads.push(new AjaxUpload('portfolio-normal-upload7', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .normal .upload7 .file-input').val(file);
			$('.userstuff2 .portfolio-edit .normal .upload6 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.jpg' || ext == '.jpeg' || ext == '.JPEG' || ext == '.gif' || ext == '.GIF' || ext == '.tif' || ext == '.png')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .normal .upload7 .file-input').css('borderColor', '#EBEBEB');
				portfolioNormalUploadsQueue.push(6);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioNormalUploadsQueue.pop(6);
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				$('.userstuff2 .portfolio-edit .normal .upload7 .file-input').css('borderColor', '#dc3a09');
			}
			//portfolioNormalUploadsQueue.push(6);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	
	
	
	portfolioJournalistUploads.push(new AjaxUpload('portfolio-journalist-upload1', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .journalist .upload1 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();

			if(ext == '.pdf')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .journalist .upload1 .file-input').css('borderColor', '#EBEBEB');
				
				portfolioJournalistUploadsQueue.push(0);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioJournalistUploadsQueue.pop(0);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .journalist .upload1 .file-input').css('borderColor', '#dc3a09');
			}
			//portfolioJournalistUploadsQueue.push(0);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioJournalistUploads.push(new AjaxUpload('portfolio-journalist-upload2', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .journalist .upload2 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.pdf')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .journalist .upload2 .file-input').css('borderColor', '#EBEBEB');
				portfolioJournalistUploadsQueue.push(1);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioJournalistUploadsQueue.pop(1);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .journalist .upload2 .file-input').css('borderColor', '#dc3a09');
			}
			//portfolioJournalistUploadsQueue.push(1);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioJournalistUploads.push(new AjaxUpload('portfolio-journalist-upload3', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .journalist .upload3 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.pdf')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .journalist .upload3 .file-input').css('borderColor', '#EBEBEB');
				
				portfolioJournalistUploadsQueue.push(2);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioJournalistUploadsQueue.pop(2);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .journalist .upload3 .file-input').css('borderColor', '#dc3a09');
			}
			//portfolioJournalistUploadsQueue.push(2);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioJournalistUploads.push(new AjaxUpload('portfolio-journalist-upload4', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .journalist .upload4 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.pdf')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .journalist .upload4 .file-input').css('borderColor', '#EBEBEB');
				
				portfolioJournalistUploadsQueue.push(3);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioJournalistUploadsQueue.pop(3);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .journalist .upload4 .file-input').css('borderColor', '#dc3a09');
			}
			//portfolioJournalistUploadsQueue.push(3);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioJournalistUploads.push(new AjaxUpload('portfolio-journalist-upload5', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .journalist .upload5 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.pdf')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .journalist .upload5 .file-input').css('borderColor', '#EBEBEB');
				
				portfolioJournalistUploadsQueue.push(4);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioJournalistUploadsQueue.pop(4);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .journalist .upload5 .file-input').css('borderColor', '#dc3a09');
			}
			//portfolioJournalistUploadsQueue.push(4);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioJournalistUploads.push(new AjaxUpload('portfolio-journalist-upload6', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .journalist .upload6 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.pdf')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .journalist .upload6 .file-input').css('borderColor', '#EBEBEB');
				
				portfolioJournalistUploadsQueue.push(5);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioJournalistUploadsQueue.pop(5);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .journalist .upload6 .file-input').css('borderColor', '#dc3a09');
			}
			//portfolioJournalistUploadsQueue.push(5);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	portfolioJournalistUploads.push(new AjaxUpload('portfolio-journalist-upload7', {
		action: '/ajax/save-portfolio/',
		name: 'userfile',
		autoSubmit: false,
		responseType: "json",
		onChange: function(file, extension) {
			$('.userstuff2 .portfolio-edit .journalist .upload7 .file-input').val(file);
			var ext = file.slice(file.lastIndexOf(".")).toLowerCase();
			
			if(ext == '.pdf')
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'inline');
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "false");
				
				$('.userstuff2 .portfolio-edit .journalist .upload7 .file-input').css('borderColor', '#EBEBEB');
				
				portfolioJournalistUploadsQueue.push(6);
			}
			else
			{
				$('.userstuff2 .portfolio-edit .more-upload-link').css('display', 'none');
				//portfolioJournalistUploadsQueue.pop(6);
				
				//var submitButton = $(this, "input[type='submit']");
				//$(submitButton).attr("disabled", "true");
				
				$('.userstuff2 .portfolio-edit .journalist .upload7 .file-input').css('borderColor', '#dc3a09');
			}			
			//portfolioJournalistUploadsQueue.push(6);
		},
		onSubmit: function(file, extension) {},
		onComplete: portfolioUploadComplete
	}));
	
	$('.userstuff2 .portfolio-edit .submit-button').click(function() {
		
		var portfolioType = $('.userstuff2 .portfolio-edit select option:selected').val();
		if($('.userstuff2 .portfolio-edit .portfolio-id').html() != '')
		{

			if (portfolioType == "normal") 
			{
					if (portfolioNormalUploadsQueue.length != 0) {
						portfolioUploadingType = portfolioType;
						$('.userstuff2 .portfolio-edit .bottom .status-message').text('Sparar portfolio, var god vänta...');
						var name = $('.userstuff2 .portfolio-edit .normal .name-input').val();
						var desc = $('.userstuff2 .portfolio-edit .normal .description-input').val();
						var id = $('.userstuff2 .portfolio-edit .portfolio-id').text();
						submitPortfolioData(id, name, desc, "", "normal");
					}
					else
					{
						portfolioUploadingType = portfolioType;
						$('.userstuff2 .portfolio-edit .bottom .status-message').text('Sparar portfolio, var god vänta...');
						var name = $('.userstuff2 .portfolio-edit .normal .name-input').val();
						var desc = $('.userstuff2 .portfolio-edit .normal .description-input').val();
						var id = $('.userstuff2 .portfolio-edit .portfolio-id').text();
						submitPortfolioData(id, name, desc, "", "normal");
					}
			}
			else 
			{
					
					if (portfolioJournalistUploadsQueue != 0) {
						portfolioUploadingType = portfolioType;
						$('.userstuff2 .portfolio-edit .bottom .status-message').text('Sparar portfolio, var god vänta...');
						var name = $('.userstuff2 .portfolio-edit .journalist .name-input').val();
						var desc = $('.userstuff2 .portfolio-edit .journalist .description-input').val();
						var extract = $('.userstuff2 .portfolio-edit .journalist .extract-input').val();
						var id = $('.userstuff2 .portfolio-edit .portfolio-id').text();
						submitPortfolioData(id, name, desc, extract, "journalist");
					}
					else
					{
						portfolioUploadingType = portfolioType;
						$('.userstuff2 .portfolio-edit .bottom .status-message').text('Sparar portfolio, var god vänta...');
						var name = $('.userstuff2 .portfolio-edit .journalist .name-input').val();
						var desc = $('.userstuff2 .portfolio-edit .journalist .description-input').val();
						var extract = $('.userstuff2 .portfolio-edit .journalist .extract-input').val();
						var id = $('.userstuff2 .portfolio-edit .portfolio-id').text();
						submitPortfolioData(id, name, desc, extract, "journalist");
					}
			}
			
		}
		
		if (portfolioNormalUploadsQueue.length != 0 && portfolioType == "normal") {
			if (portfolioUploading)
				return false;
			portfolioUploading = true;
			portfolioUploadingType = portfolioType;
			$('.userstuff2 .portfolio-edit .bottom .status-message').text('Sparar portfolio, var god vänta...');
		}
		
		if (portfolioJournalistUploadsQueue != 0 && portfolioType == "journalist") {
			if (portfolioUploading)
				return false;
			portfolioUploading = true;
			portfolioUploadingType = portfolioType;
			$('.userstuff2 .portfolio-edit .bottom .status-message').text('Sparar portfolio, var god vänta...');
		}
		
		if (portfolioType == "normal") {
			if (portfolioNormalUploadsQueue.length != 0) {
				var name = $('.userstuff2 .portfolio-edit .normal .name-input').val();
				var desc = $('.userstuff2 .portfolio-edit .normal .description-input').val();
				var id = $('.userstuff2 .portfolio-edit .portfolio-id').text();
				submitPortfolioData(id, name, desc, "", "normal");
			}
		}
		else {
			if (portfolioJournalistUploadsQueue != 0) {
				var name = $('.userstuff2 .portfolio-edit .journalist .name-input').val();
				var desc = $('.userstuff2 .portfolio-edit .journalist .description-input').val();
				var extract = $('.userstuff2 .portfolio-edit .journalist .extract-input').val();
				var id = $('.userstuff2 .portfolio-edit .portfolio-id').text();
				submitPortfolioData(id, name, desc, extract, "journalist");
			}
		}
		
		return false;
	});
}

function submitPortfolioData(id, name, description, extract, type)
{
	$.ajax({
		url: '/ajax/save-portfolio/',
		type: 'POST',
		data: {'portfolio_id': id,
			   'name': name,
			   'description': description,
			   'extract': extract,
			   'type': type
			 	},
		success: portfolioDataUploadComplete,
		dataType: 'json'
	});
}

function portfolioDataUploadComplete(data)
{
	portfolioId = data;
	if(portfolioId == "FILEERROR" || portfolioId == '')
	{
		$('.userstuff2 .portfolio-edit .bottom .status-message').text("filen är ogiltig..");
	}
	else
	{
		portfolioUploadNext();
	}
}

function portfolioUploadComplete(file, response)
{
	portfolioUploadNext();
}

function portfolioUploadNext()
{
	
	if (portfolioUploadingType == "normal") {
		if (portfolioNormalUploadsQueue.length == 0) {
			location.href = "/community/min-profil/portfolio/";
		}
		else {
			var uploadIndex = portfolioNormalUploadsQueue.pop();
			var upload = portfolioNormalUploads[uploadIndex];
			upload.setData({'index': uploadIndex, 'portfolio_id': portfolioId});
			upload.submit();
		}
	}
	else if (portfolioUploadingType == "journalist") {
		if (portfolioJournalistUploadsQueue.length == 0) {
			location.href = "/community/min-profil/portfolio/";
		}
		else {
			var uploadIndex = portfolioJournalistUploadsQueue.pop();
			var upload = portfolioJournalistUploads[uploadIndex];
			upload.setData({'index': uploadIndex, 'portfolio_id': portfolioId});
			upload.submit();
		}
	}
}

var toolTipType = "news";

function setupToolTip()
{
	if ($('.blackie .enter-tip').length == 0)
		return;
		
	$(".blackie .enter-tip .start-date-input").datepicker();
	//$(".blackie .enter-tip .end-date-input").datepicker();
		
	$('.blackie .enter-tip .link-link').click(function() {
		toolsEnterTipUnselectAll();
		$('.blackie .enter-tip .link-link').addClass("selected-link");
		$('.blackie .enter-tip .link-box').removeClass("hidden");
		toolTipType = "link";
		return false;
	});
	$('.blackie .enter-tip .news-link').click(function() {
		toolsEnterTipUnselectAll();
		$('.blackie .enter-tip .news-link').addClass("selected-link");
		$('.blackie .enter-tip .news-box').removeClass("hidden");
		toolTipType = "news";
		return false;
	});
	$('.blackie .enter-tip .improvement-link').click(function() {
		toolsEnterTipUnselectAll();
		$('.blackie .enter-tip .improvement-link').addClass("selected-link");
		$('.blackie .enter-tip .improvement-box').removeClass("hidden");
		toolTipType = "improvement";
		return false;
	});
	$('.blackie .enter-tip .gossip-link').click(function() {
		toolsEnterTipUnselectAll();
		$('.blackie .enter-tip .gossip-link').addClass("selected-link");
		$('.blackie .enter-tip .gossip-box').removeClass("hidden");
		toolTipType = "gossip";
		return false;
	});
	$('.blackie .enter-tip .events-link').click(function() {
		toolsEnterTipUnselectAll();
		$('.blackie .enter-tip .events-link').addClass("selected-link");
		$('.blackie .enter-tip .events-box').removeClass("hidden");
		toolTipType = "event";
		return false;
	});
	
	var start_time_select = $('.blackie .enter-tip .events-box .start-time-select');
	//var end_time_select = $('.blackie .enter-tip .events-box .end-time-select');
	for (var i = 0; i < 24; i++) {
		for (var j = 0; j < 60; j += 15) {
			var h = i < 10 ? "0" + i : i;
			var m = j < 10 ? "0" + j : j;
			var t = h + ":" + m;
			$(start_time_select).append('<option value="' + t + '">' + t + '</option');
			//$(end_time_select).append('<option value="' + t + '">' + t + '</option');
		}
	}
	
	$('.blackie .enter-tip .submit-button').click(function() {
	
		var link;
		var title;
		var description;
		var event_start_date;
		//var event_end_date;
		var event_start_time;
		//var event_end_time;
		
		if (toolTipType == "link") {
			link = $('.blackie .enter-tip .link-box .link-input').val();
		}
		else if (toolTipType == "news") {
			title = $('.blackie .enter-tip .news-box .title-input').val();
			link = $('.blackie .enter-tip .news-box .tip-input').val();
		}
		else if (toolTipType == "improvement") {
			title = $('.blackie .enter-tip .improvement-box .title-input').val();
			description = $('.blackie .enter-tip .improvement-box textarea').val();
		}
		else if (toolTipType == "gossip") {
			title = $('.blackie .enter-tip .gossip-box .title-input').val();
			description = $('.blackie .enter-tip .gossip-box textarea').val();
		}
		else if (toolTipType == "event") {
			title = $('.blackie .enter-tip .events-box .title-input').val();
			description = $('.blackie .enter-tip .events-box textarea').val();
			event_start_date = $('.blackie .enter-tip .events-box .start-date-input').val();
			//event_end_date = $('.blackie .enter-tip .events-box .end-date-input').val();
			event_start_time = $('.blackie .enter-tip .events-box .start-time-select option:selected').val();
			//event_end_time = $('.blackie .enter-tip .events-box .end-time-select option:selected').val();
		}
	
		//date part in the following function 'event_end_date': event_end_date, , 'event_end_time': event_end_time
		$.ajax({
			url: '/ajax/save-tip/',
			type: 'POST',
			data: {'type': toolTipType, 'title': title, 'description': description, 'link': link, 'event_start_date': event_start_date, 
				'event_start_time': event_start_time},
			success: function(data){
			},
			dataType: 'json'
		});
	
		$('.blackie .enter-tip .link-box .link-input').val('http://');
		$('.blackie .enter-tip .news-box .title-input').val('Rubrik');
		$('.blackie .enter-tip .news-box .tip-input').val('http://');
		$('.blackie .enter-tip .improvement-box .title-input').val('Förslag på förbättring');
		$('.blackie .enter-tip .improvement-box textarea').val('Beskrivning');
		$('.blackie .enter-tip .gossip-box .title-input').val('En fågel viskade...');
		$('.blackie .enter-tip .gossip-box textarea').val('Beskrivning');
		$('.blackie .enter-tip .events-box .title-input').val('Rubrik');
		$('.blackie .enter-tip .events-box textarea').val('Beskrivning');
		$('.blackie .enter-tip .events-box .start-date-input').val('Start datum');
		$('.blackie .enter-tip .events-box .end-date-input').val('Slut datum');
		$('.blackie .enter-tip .status-message').text('Tack för ditt tips');
	});
}

function toolsEnterTipUnselectAll()
{
	$('.blackie .enter-tip .link-link').removeClass("selected-link");
	$('.blackie .enter-tip .news-link').removeClass("selected-link");
	$('.blackie .enter-tip .improvement-link').removeClass("selected-link");
	$('.blackie .enter-tip .gossip-link').removeClass("selected-link");
	$('.blackie .enter-tip .events-link').removeClass("selected-link");
	
	$('.blackie .enter-tip .link-box').addClass("hidden");
	$('.blackie .enter-tip .news-box').addClass("hidden");
	$('.blackie .enter-tip .improvement-box').addClass("hidden");
	$('.blackie .enter-tip .gossip-box').addClass("hidden");
	$('.blackie .enter-tip .events-box').addClass("hidden");
	
	$('.blackie .enter-tip .status-message').text('');
}

function setupCursorialScroll()
{
	if ($('.cursorial').length == 0)
		return;
	
	$('.cursorial .cursorial-more-link').click(function() {
		$('.cursorial .hidden').each(function(i, e) {
			if (i < 4) {
				$(e).removeClass("hidden");
			}
		});
		if ($('.cursorial .hidden').length == 0)
			$(this).remove();
		return false;
	});
}

function setupEventsScroll()
{
	if ($('.events').length == 0)
		return;
	
	$('.events .events-more-link').click(function() {
		$('.events .hidden').each(function(i, e) {
			if (i < 4) {
				$(e).removeClass("hidden");
			}
		});
		if ($('.events .hidden').length == 0)
			$(this).remove();
		return false;
	});
}

var tipPage = 1;
var tipType;

function setupLatestTip()
{
	if ($('.latest-tip').length == 0)
		return;
		
	tipType = $('.latest-tip .type').text();
	fetchLatestTip();
	
	$('.latest-tip .tip-links .all-link').click(function() {
		latestTipLinkClick('.all-link', 'all', 'Alla');
		return false;
	});
	$('.latest-tip .tip-links .news-link').click(function() {
		latestTipLinkClick('.news-link', 'news', 'Nyheter');
		return false;
	});
	$('.latest-tip .tip-links .improvements-link').click(function() {
		latestTipLinkClick('.improvements-link', 'improvement', 'Förbättringar på siten');
		return false;
	});
	$('.latest-tip .tip-links .gossip-link').click(function() {
		latestTipLinkClick('.gossip-link', 'gossip', 'Skvaller');
		return false;
	});
	$('.latest-tip .tip-links .events-link').click(function() {
		latestTipLinkClick('.events-link', 'event', 'Händelser');
		return false;
	});
	$('.latest-tip .tip-links .links-link').click(function() {
		latestTipLinkClick('.links-link', 'link', 'Nyttiga länkar');
		return false;
	});
	
	$('.latest-tip .more-items-link').click(function() {
		tipPage++;
		fetchLatestTip();
		return false;
	});
}

function latestTipLinkClick(link, type, title)
{
	tipPage = 1;
	tipType = type;
	latestTipUnselectAll();
	$('.latest-tip .tip-links').find(link).addClass('active');
	fetchLatestTip();
	$('.latest-tip .type-title').text(title);
	$('.latest-tip .entries').text('');
}

function fetchLatestTip()
{
	var div = $('.latest-tip .entries');
	$('.latest-tip .status').text('Hämtar tips...');
	$.ajax({
		url: '/ajax/latest-tip/',
		type: 'POST',
		data: {'type': tipType, 'page': tipPage},
		success: function(data){
			$('.latest-tip .status').text('');
			placeLatestTip(div, data);
			if (data.more == "true") {
				$('.latest-tip .more').removeClass("hidden");
			}
			else {
				$('.latest-tip .more').addClass("hidden");
			}
		},
		dataType: 'json'
	});
}

function latestTipUnselectAll()
{
	$('.latest-tip .tip-links .all-link').removeClass('active');
	$('.latest-tip .tip-links .news-link').removeClass('active');
	$('.latest-tip .tip-links .improvements-link').removeClass('active');
	$('.latest-tip .tip-links .gossip-link').removeClass('active');
	$('.latest-tip .tip-links .events-link').removeClass('active');
	$('.latest-tip .tip-links .links-link').removeClass('active');
}

function placeLatestTip(where, data)
{
	$(data.tips).each(function(i, entry) {
		var s = '<div class="entry">';
		if (entry.title != null) {
			s += '<div class="title">' + entry.title + '</div';
		}
		if (entry.description != null) {
			s += '<div class="description">' + entry.description + '</div>';
		}
		if (entry.event_start_date != null) {
			s += '<div class="start-date">Start datum: ' + entry.event_start_date + '</div>';
		}
		if (entry.event_end_date != null) {
			//s += '<div class="end-date">Slut datum: ' + entry.event_end_date + '</div>';
		}
		if (entry.link != null) {
			s += '<div class="link"><a target="_blank" href="' + entry.link + '">' + entry.link + '</a></div>';
		}
		s += '<div class="from">Inskickat av <a href="' + entry.author_link + '">' + entry.author_name + '</a></div><div class="separator"></div></div>';
		$(where).append(s);
	});
}
// JavaScript Document