﻿
function htmlencode(str) {
	return $('<div/>').text(str).html();
}

function quoteescape(str) {
	return str.replace(/'/g, "\\'");
}

function ColumnsSetHeight() {
	if ($("#cv-block-0").height() > $("#cv-block-1").height()) {
		$("#cv-block-1").height($("#cv-block-0").height());
	} else {
		$("#cv-block-0").height($("#cv-block-1").height());
	}
}

function VideoSizeFix() {
	$("#cv-block-1 .text-video").attr("width", 284).attr("height", 236).find("embed").attr("width", 284).attr("height", 236);
	$("#cv-block-0 .text-video").attr("width", 425).attr("height", 344).find("embed").attr("width", 425).attr("height", 344);
}

function ScrollToContentFromUrl() {
	try {
		if ("#ambitie" == document.location.hash) {
			$(".intro-cv-list-fixed #add-ambition").click();
		} else if ("#opleiding" == document.location.hash) {
			$(".intro-cv-list-fixed #add-education").click();
		} else if ("#werkervaring" == document.location.hash) {
			$(".intro-cv-list-fixed #add-workexperience").click();
		} else if ("#extra" == document.location.hash) {
			$(".intro-cv-list-fixed #add-outsidework").click();
		} else if ("#karakter" == document.location.hash) {
			$(".intro-cv-list-fixed #add-tests").click();
		} else if ("#tekst" == document.location.hash) {
			$(".intro-cv-list-flex #add-text").click();}
		else if ("#freelancer" == document.location.hash) {
            $(".intro-cv-list-fixed #add-freelancer").click();
		}		
	} catch (ex) { }
}

function InitSlideshows() {
	$('.slideshow-scroller .next').hide();
	$('.slideshow-scroller .prev').hide();

//	$('.slideshow-scroller:has(.sections li:gt(0))').find('.next').show();
	$('.slideshow-scroller').each(function() {
		if (1 < $(this).find(".sections li").size()) $(this).find('.next').show();
	});


	$('.slideshow-scroller').serialScroll({
		target: '.sections',
		items: 'li',
		prev: 'img.prev',
		next: 'img.next',
		axis: 'xy',
		navigation: '#navigation li a',
		duration: 700,
		force: true,
		exclude: 0,
		cycle: false,
		step: 1,
		lazy: true,
		onBefore: function(e, elem, $pane, $items, pos) {
			try {
				// hide arrows at limits
				var $prev = $pane.parent().find('.prev'),
				    $next = $pane.parent().find('.next');

				$prev.add($next).show();
				if (pos == 0)
					$prev.hide();
				else if (pos == $items.length - 1)
					$next.hide();

				e.preventDefault();
				if (this.blur)
					this.blur();
			} catch (ex) { }
		}
	});
}

function sortable_drag_stop(event, obj) {
	try {
		$(".cv-block-sidebar .cv-large-block").prependTo(".cv-block");

		var $target = obj.item;

		var ctype = $target.attr("id").replace("cv-", "");
		var cid = ctype.split("-")[1];
		if (undefined == cid) cid = 0;
		ctype = ctype.split("-")[0];

		var col = $target.parent().attr("id").replace("cv-block-", "");
		var pos = $("#" + $target.parent().attr("id") + " > li").length - $target.parent().find("#" + $target.attr("id") + " ~ li").length;

		$.ajax({
			type: "POST",
			data: "{'contentType':'" + ctype + "','contentId':'" + cid + "','columnId':'" + col + "','position':'" + pos + "'}",
			url: "/WebServices/AjaxHelper.asmx/UpdatePortfolioPosition",
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		});

		ColumnsSetHeight();
		VideoSizeFix();
	} catch (ex) { }
}

function sortable_drag_over(event, obj) {
	try {
		if (obj.item.hasClass("cv-large-block") && $(".placeholder").parent().hasClass("cv-block-sidebar")) {
			$(".placeholder").addClass("placeholder-incorrect");
		} else if ("" != obj.item.html()) {
			$(".placeholder").removeClass("placeholder-incorrect");
		}
	} catch (ex) { }
}

function sortable_init(sortorders) {
    
	try {
		if (undefined != sortorders) {
			sortorders = sortorders["d"].split(";");

			for (var i = 0; i < sortorders.length; i++) {
				var $column = $("#cv-block-" + i).attr("id");

				var items = sortorders[i].split(",");
				for (var j = items.length - 1; j >= 0; j--) {
					if ("" != items[j]) {
						var id = items[j].split("/")[0];
						var state = items[j].split("/")[1]
						$("#cv-" + id).prependTo("#cv-block-" + i);
						if (0 == state) $("#cv-" + id).find(".collapsible-cv-close").click();
					}
				}
			}
			$("#cv-users").prependTo("#cv-block-1");
		}
	} catch (ex) { }
	
	if (0 == $(".cv-block-public").size()) {
		$(".cv-block").sortable({
			connectWith: [".cv-block-sidebar"],
			handle: "h2",
			placeholder: "placeholder",
			forcePlaceholderSize: true,
			revert: true,
			tolerance: "pointer",
			over: sortable_drag_over,
			stop: sortable_drag_stop
		});
		$(".cv-block-sidebar").sortable({
			connectWith: [".cv-block"],
			handle: "h2",
			placeholder: "placeholder",
			forcePlaceholderSize: true,
			revert: true,
			tolerance: "pointer",
			over: sortable_drag_over,
			stop: sortable_drag_stop
		});
	}

	VideoSizeFix();
	ScrollToContentFromUrl();
}

var FicaalCollapsableIsSet = false; // for saving collapseBar state of visual cv FREELANCE //TODO BETTER

function InitCVPositions(userid) {
	if (0 < $(".cv-block").size()) {
		// put objects in the right order

		var url = "/WebServices/AjaxHelper.asmx/GetPortfolioPositions";
		var params = "{}";
		if (undefined != userid) {
			url = "/WebServices/AjaxHelper.asmx/GetPortfolioPositionsForUser";
			params = "{userId:" + userid + "}";
		}

		$.ajax({
			type: "POST",
			data: params,
			url: url,
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(response) {
				//alert("success");
				sortable_init(response);
			},
			failure: function(msg) {
				sortable_init();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//alert(textStatus + ": " + errorThrown);
				sortable_init();
			}
		});
	}
}

function getEmptyBlockId(blockType) {
	var $matches;

	if ("text" == blockType) {
		$matches = $(".cv-item:has(.text-display:empty):not(:has(.slideshow-scroller)):not(:has(embed))");
	} else if ("video" == blockType) {
		$matches = $(".cv-item:has(embed[src=''])");
	} else if ("slideshow" == blockType) {
		$matches = $(".cv-item:has(.slideshow-scroller:has(img[src='']))");
	}

	if (undefined != $matches && 0 != $matches.size()) return $matches.attr("id").replace("cv-text-", "");
	return 0;
}

function InitCVOpenClose() {

	$(".collapsible-cv-close, .collapsible-cv-close-edit").unbind("click").live('click', function() {
      
		if ($(this).hasClass("delete")) {
			// flex block
			if (!(confirm("Weet je zeker dat je dit blok wilt verwijderen?"))) {
				return;
			} else {
				$(this).parent().parent().parent().parent().remove();
			}
		} else {
			// fixed block
			$(this).parent().parent().parent().parent().slideUp();
		}


		var $target = $(this).parent().parent().parent().parent();
		var ctype = $target.attr("id").replace("cv-", "");
		var cid = ctype.split("-")[1];
		if (undefined == cid) cid = 0;
		ctype = ctype.split("-")[0];

		$.ajax({
			type: "POST",
			data: "{'contentType':'" + ctype + "','contentId':'" + cid + "','state':'0'}",
			url: "/WebServices/AjaxHelper.asmx/UpdatePortfolioState",
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		});
	});

	$(".intro-cv-list-fixed a").unbind("click").click(function() {
		var selector = "#" + this.id.replace("add-", "cv-");
		$(selector).slideDown();
		$.scrollTo(selector, { duration: 200 });

		var $target = $(selector);
		var ctype = $target.attr("id").replace("cv-", "");
		var cid = ctype.split("-")[1];
		if (undefined == cid) cid = 0;
		ctype = ctype.split("-")[0];

		$.ajax({
			type: "POST",
			data: "{'contentType':'" + ctype + "','contentId':'" + cid + "','state':'1'}",
			url: "/WebServices/AjaxHelper.asmx/UpdatePortfolioState",
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		});
	});

	$(".intro-cv-list-flex a").unbind("click").click(function() {
		var blockType = this.id.replace("add-", "");

		var emptyBlockId = getEmptyBlockId(blockType);

		if (0 != emptyBlockId) {
			$.scrollTo("#cv-text-" + emptyBlockId, { duration: 200 });
			if (!$("#cv-text-" + emptyBlockId + " .edit-button").hasClass("active")) $("#cv-text-" + emptyBlockId + " .edit-button").click();
		} else {
			$.ajax({
				type: "POST",
				data: "{}",
				url: "/WebServices/AjaxHelper.asmx/CreateUserText",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function(response) {
					var newId = response["d"];

					$.get("/Web/Home/MyText.aspx?type=" + blockType, function(data) {
						var blockHTML = data;
						blockHTML = blockHTML.replace("</div></form>", "");
						blockHTML = blockHTML.substring(blockHTML.indexOf('<div id="text-control">') + 23);
						blockHTML = "<li id='cv-text-" + newId + "' class='cv-item'><div>" + blockHTML + "</div></li>";

						$("#cv-block-0").prepend(blockHTML);
						InitCVEdit();
						$("#cv-text-" + newId + " .edit-button").click();
						$.scrollTo("#cv-text-" + newId, { duration: 200 });

						InitCVOpenClose();

						$.ajax({
							type: "POST",
							data: "{'contentType':'text','contentId':'" + newId + "','columnId':'0','position':'1'}",
							url: "/WebServices/AjaxHelper.asmx/UpdatePortfolioPosition",
							contentType: "application/json; charset=utf-8",
							dataType: "json"
						});

					});
				}
			});
		}
	});
}

function deleteImage(event) {
	if (confirm("Weet je zeker dat je deze afbeelding wilt verwijderen?")) {
		//var $container = $(event.target || event.srcElement).parent().parent().parent().parent().parent();
		var url = $(event.target || event.srcElement).parent().find("input").html();
		$(event.target || event.srcElement).parent().remove();
	}
}

function addImage(event) {
	var $container = $(event.target || event.srcElement).parent().parent().parent().parent();
	var url = $(event.target || event.srcElement).parent().parent().find(".image-new").val();

	if ("" != url && "http://" != url) {
		$container.find(".slide-edit ol").append("<li class='image-edit'><input type='text' value='" + url + "'> <img class='delete' src='/Web/Static/images/buttons/delete.gif' alt='delete' onclick='deleteImage(event) ' /></li>");
		$(event.target || event.srcElement).parent().parent().find(".image-new").val("http://");
	}
}

function InitCVEdit() {
	$(".cv-item .edit-text").unbind("click").click(function() {

		var $button = $(this);
		var $container = $button.parent().parent().parent();
		var editorId = "editor_" + $container.parent().attr("id").replace("cv-text-", "");

		if ($button.hasClass("active")) {
			CvModeView($button, $container, editorId);
		} else {
			CvModeEdit($button, $container, editorId);
		}

		return false;
	});
}

function CvModeEdit($button, $container, editorId) {
	var $video = $container.find(".text-video");
	if (0 != $video.size()) {
		//var url = $video.find("param[name='movie']").attr("value").replace("&hl=en&fs=1&rel=0", "");
		var url = "";
		try {
			url = $video.find("embed").attr("src").replace("&hl=en&fs=1&rel=0", "");
		} catch (e) { }
		$container.find(".middle-nobg").prepend("<div class='video-edit'><h4>Voeg een youtube video toe</h4><div>Je kunt in je visual cv youtube video's toevoegen. Je vult eenvoudig de url van de youtube pagina in waarop de video te bekijken is.</div> <input type='text' value='" + url + "' /></div>");
		$video.css("display", "none");
	}

	var $feed = $container.find(".text-feed");
	if (0 != $feed.size()) {
		var url = $feed.find(".text-feed-url").html();

		$container.find(".middle-nobg").prepend("<div class='feed-edit'><h4>Voeg een rss-feed toe</h4><div>Je kunt in je visual cv rss-feeds toevoegen. Je vult eenvoudig de url van de feed in.</div> <input type='text' value='" + url + "' /></div>");
		$feed.css("display", "none");
	}
	
	var $slideshow = $container.find(".image-scroller");
	if (0 != $slideshow.size()) {
		$container.find(".middle-nobg").prepend("<div class='slide-edit'><h4>Voeg afbeeldingen toe aan je slideshow</h4><div>Je kunt foto's laten zien, of afbeeldingen die bij je werk horen. Vul de url's van de afbeeldingen in in de volgorde die je zelf wilt en dan worden ze netjes in de slideshow gezet.</div><ol></ol></div");

		var $images = $slideshow.find("li > img");
		for (i = 0; i < $images.size(); i++) {
			$container.find(".slide-edit ol").append("<li class='image-edit'><input type='text' value='" + $($images[i]).attr("src") + "' /> <img class='delete' src='/Web/Static/images/buttons/delete.gif' alt='delete' onclick='deleteImage(event) ' /></li>");
		}
		$container.find(".slide-edit").append("<input class='image-new' type='text' value='http://' /> <a class='button' onclick='addImage(event)'><span>Voeg toe</span></a>");

		$slideshow.css("display", "none");
	}

	var title = $container.find("h2").html();
	if ("" == title || " " == title || "&nbsp;" == title) title = stringMyContent;
	$container.find("h2").after("<div class='title-edit'><h4>titel</h4><input type='text' value='" + title + "' /></div>");
	$container.find("h2").css("display", "none");

	if (0 != $video.size() || 0 != $slideshow.size()) $container.find(".text-edit .text-explanation").css("display", "none");

	$container.find("textarea").attr("name", editorId);
	$container.find("textarea").attr("id", editorId);
	$container.find("textarea").html(htmlencode($container.find(".text-display").html()));

	if (0 == $container.find("iframe").size()) {
		tinyMCE.init({
			mode: "exact",
			elements: editorId,
			theme: "advanced",
			plugins: "safari,layer,inlinepopups,media",
			theme_advanced_buttons1: "code,|,bold,italic,strikethrough,|,numlist,bullist,|,link,image,",
			theme_advanced_buttons2: "",
			theme_advanced_buttons3: "",
			theme_advanced_buttons4: "",
			theme_advanced_toolbar_location: "top",
			theme_advanced_toolbar_align: "left",
			theme_advanced_path_location: "none",
			theme_advanced_resizing: "false",
			theme_advanced_source_editor_height: "300",
			fix_nesting: "true"
		});
	}
	$container.find("#" + editorId + "_parent").css("display", "block");
	$container.find("iframe body").html($container.find(".text-display").html());

	$container.find(".text-display").css("display", "none");
	$container.find(".text-edit").css("display", "block");
	$container.find(".corner-buttonfloat").css("display", "none");

	$button.addClass("active");

	$button.after("<a class='collapsible-cv-close-edit delete' title='Verwijderen'><img src='/Web/Static/images/buttons/delete.gif' alt='X'/></a>");
	InitCVOpenClose();

	var $btntext = $button.find("span");
	var tmp = $btntext.attr("rel");
	$btntext.attr("rel", $btntext.html());
	$btntext.html(tmp);
}

function CvModeView($button, $container, editorId) {
	var hasSlideshow = false;
	var $slideshow = $container.find(".slide-edit");
	var $video = $container.find(".video-edit");
	var $feed = $container.find(".feed-edit");

	if (0 != $slideshow.size()) {
		hasSlideshow = true;

		// update slideshow li's
		$container.find(".image-scroller ul").empty();
		var $images = $container.find(".image-edit input");
		var imageUrls = "";
		for (i = 0; i < $images.size(); i++) {
			var image_url = $($images[i]).val();
			if ("" != image_url && "http://" != image_url) {
				if (-1 == image_url.indexOf("http://")) image_url = "http://" + image_url;

				$container.find(".image-scroller ul").append("<li><img src='" + image_url + "' alt='' /></li>");
				imageUrls = imageUrls + ";" + image_url;
			}
		}
		if (0 == $images.size()) $container.find(".image-scroller ul").append("<li><img src='' alt='' /></li>");

		$.ajax({
			type: "POST",
			data: "{'id':'" + $container.parent().attr("id").replace("cv-text-", "") + "','title':'" + quoteescape($container.find(".title-edit input").val()) + "','text':'" + quoteescape(tinymce.EditorManager.get(editorId).getContent()) + "','imageUrls':'" + imageUrls + "'}",
			url: "/WebServices/AjaxHelper.asmx/UpdateUserSlideshow",
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		});

		$slideshow.remove();
		$container.find(".image-scroller").css("display", "");

		CvTextModeView($button, $container, editorId);

	} else if (0 != $video.size()) {
		var url = $video.find("input").val();

		$.ajax({
			type: "POST",
			data: "{'id':'" + $container.parent().attr("id").replace("cv-text-", "") + "','title':'" + quoteescape($container.find(".title-edit input").val()) + "','text':'" + quoteescape(tinymce.EditorManager.get(editorId).getContent()) + "','videoUrl':'" + url + "'}",
			url: "/WebServices/AjaxHelper.asmx/UpdateUserVideo",
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		});

		var embed_url = "";
		if (-1 != url.indexOf("watch"))
			embed_url = "http://www.youtube.com/v/" + url.split("v=")[1].substring(0, 11) + "&hl=en&fs=1&rel=0";
		else
			embed_url = url;
		$container.find("param[name='movie']").attr("value", embed_url);
		$container.find("embed").attr("src", embed_url);
		$video.remove();
		$container.find(".text-video").css("display", "");
		// force refresh to fix IE
		$container.find(".text-video").html($container.find(".text-video").html());

		CvTextModeView($button, $container, editorId);

	} else if (0 != $feed.size()) {
		var url = $feed.find("input").val();

		$.ajax({
			type: "POST",
			data: "{'id':'" + $container.parent().attr("id").replace("cv-text-", "") + "','title':'" + quoteescape($container.find(".title-edit input").val()) + "','text':'" + quoteescape(tinymce.EditorManager.get(editorId).getContent()) + "','feedUrl':'" + url + "'}",
			url: "/WebServices/AjaxHelper.asmx/UpdateUserFeed",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(response) {
				$feed.remove();

				$.ajax({
					type: "POST",
					data: "{'feedUrl':'" + url + "'}",
					url: "/WebServices/AjaxHelper.asmx/FeedContent",
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					success: function(response) {
						$container.find(".text-feed-content").html(response["d"]);
					}
				});

//				$.ajax({
//					type: "POST",
//					data: "{'feedUrl':'" + url + "'}",
//					url: "/WebServices/AjaxHelper.asmx/FeedTitle",
//					contentType: "application/json; charset=utf-8",
//					dataType: "json",
//					success: function(response) {
//						$container.find("h2").html(response["d"]);
//					}
//				});

				$container.find(".text-feed-content").html("");

				$container.find(".text-feed-url").html(url);
				$container.find(".text-feed").css("display", "");

				CvTextModeView($button, $container, editorId);
			}
		});
	} else {
		$.ajax({
			type: "POST",
			data: "{'id':'" + $container.parent().attr("id").replace("cv-text-", "") + "','title':'" + quoteescape($container.find(".title-edit input").val()) + "','text':'" + quoteescape(tinymce.EditorManager.get(editorId).getContent()) + "'}",
			url: "/WebServices/AjaxHelper.asmx/UpdateUserText",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(response) {
				CvTextModeView($button, $container, editorId);
				
				if (hasSlideshow) InitSlideshows();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert(textStatus + ": De tekst kan niet opgeslagen worden. Sorry.");
			}
		});
	}
}

function CvTextModeView($button, $container, editorId) {

	//title
	$container.find("h2").html($container.find(".title-edit input").val());
	$container.find(".title-edit").remove();
	$container.find("h2").css("display", "");

	//content
	$container.find(".text-display").html(tinymce.EditorManager.get(editorId).getContent());
	$container.find(".text-edit").css("display", "none");
	$container.find(".text-display").css("display", "");
	$container.find("#" + editorId + "_parent").css("display", "none");

	$container.find(".corner-buttonfloat").css("display", "");

	$button.removeClass("active");
	$button.parent().find(".collapsible-cv-close-edit").remove();

	var $btntext = $button.find("span");
	var tmp = $btntext.attr("rel");
	$btntext.attr("rel", $btntext.html());
	$btntext.html(tmp);
}
