
unbubble = false;
bubble_ishover = false;
function unbubbleCron() {
	if (unbubble == true) {
		if (bubble_ishover == false) {
			$('div#bubble_info_box').hide();
		}
	}
	setTimeout(function() {
		unbubbleCron();
	}, 100);
}

function bubble(element) {
	$box = $('div#bubble_info_box');
	if ($box.length == 0) {
		$box = $('<div id="bubble_info_box" style="display: none; width:183px; position: absolute; top: -2000px; left: -2000px; background:url(bubbletop.png) no-repeat top"><div style="background: url(bubblebottom.png) no-repeat bottom; padding: 0px 0px 67px 0px"><div style="margin: 17px 0px 0px 0px; background: url(bubblemid.png); width:183px; overflow:hidden;"><div style="margin: 0px 24px 0px 24px; padding: 6px 0px 10px 0px; text-align: left;overflow:hidden" class="bubble_text"></div></div></div></div>');
		$('body').append($box);
		unbubbleCron();
	}
	$('div.bubble_text', $box).html($(element).attr('data_bubble_info'));
	if (!$(element).attr('data_bubble_y_modifier')) $(element).attr('data_bubble_y_modifier', '0');
	if (!$(element).attr('data_bubble_x_modifier')) $(element).attr('data_bubble_x_modifier', '0');
	$('div#bubble_info_box').css({
		'top': $(element).offset().top - $('div#bubble_info_box').height() - 7 + parseInt($(element).attr('data_bubble_y_modifier')),
		'left': $(element).offset().left - $('div#bubble_info_box').width() + 20 + parseInt($(element).attr('data_bubble_x_modifier'))
	}).show();
}


/*
   * * * * * * * 
   */

var videorec_id = '';

function videorec_callback (type, params) {
	switch (type) {
		case 'error':
			alert ("ERROR\n" + params ['message']);
			break;
		case 'finish':
			$.ajax({
				type: "POST",
				url: "ajax.php",
				async: true,
				data: {
					'saveVideo': params['http']
				},
				dataType: 'json',
				success: function(data) {
					updateUserInfo();
					$('div#cvFormStep3 input.next').show();
					$('div#cvFormStep3').hide();
					$('div#cvFormStep4').show();
				}
			});
			$('#' + videorec_id).hide ();
			break;
		case 'started':
			videorec_id = params ['id'];
			break;
	}
}

function positionCvForm() {
	$('div#enlargedFrame1')
		.css({
			'left': parseInt(($(window).width() / 2) - ($('div#enlargedFrame1').width() / 2)),
			'top': parseInt(($(window).height() / 2) - ($('div#enlargedFrame1').height() / 2) + $(window).scrollTop())
		});
		$contentBox = $($('div#enlargedFrame4').children()[0]);
		$('img#enlargedClose').css({
			'position': 'absolute',
			'top': $contentBox.offset().top + 5,
			'left': $contentBox.offset().left + $contentBox.innerWidth() - $('img#enlargedClose').width() - 5
		});
}

function updateUserInfo() {
	$.ajax({
		type: "POST",
		url: "ajax.php",
		async: true,
		data: {
			'getUserInfo': 'getUserInfo'
		},
		dataType: 'json',
		success: function(data) {
			if (data['error'] != '') {
				$('div#logoutboxwrapper').hide();
				$('div#loginboxwrapper').show();
				$('img#uppdateracvpuff').hide();
				$('img#lagguppcvpuff').show();
			} else {
				$('span#logoutboxlogin').html(data['login']);
				var fields = ['personal1'];
				for (var i = 0; i < fields.length; i++) {
					if ((data[fields[i]] == '') && ($('input[name="' + fields[i] + '"]').attr('data_default') != '')) {
						data[fields[i]] = $('input[name="' + fields[i] + '"]').attr('data_default');
					}
					$('textarea[name="' + fields[i] + '"]').val(data[fields[i]]);

				}
				$('input.branschbox').each(function() {
					var c = false;
					if (data.tags instanceof Array) {
						for (var i = 0; i < data.tags.length; i++) {
							if (data.tags[i] == $(this).next('label').html()) {
								c = true;
							}
						}
					}
					$(this).attr('checked', c);
				});
				if (data['hasVideo'] == '1') {

					if (data['youtube'] != '') {

						$('div#cvFormStep3 input[type="radio"]').each(function() {
							$(this).hide();
						});
						$('input#videomethodwebcam').closest('h5').hide();
						$('div#videorecorder').html('').hide();
						$('div#youtubevideoarea').append('<div style="padding: 0px 0px 9px 15px; width: 225px; height:169px;"><object width="225" height="169"><param name="wmode" value="opaque"></param><param name="movie" value="http://www.youtube.com/v/' + data['youtube'] + '?autoplay=0"></param><param name="autoplay" value="0"></param><embed wmode="opaque" src="http://www.youtube.com/v/' + data['youtube'] + '?autoplay=0" type="application/x-shockwave-flash" width="225" height="169" autoplay="0"></embed></object></div>');
						$('div#youtubevideoarea').show();
						$('div#belowvideoarea').html('');
						$('div#cvFormStep3 input.next').show();
						$('div#youtubearea div.inputs').hide();
						$('div#youtubearea').show();
						$('div#belowyoutubearea').html('<div id="filmaom"><h5>Gör om ditt CV</h5><p><a href="">Ta bort filmen och gör en ny.</a></p><p>Du kan alltid logga in på cirkusen.com och ändra eller ta bort ditt CV.</p></div>').show();
						$('div#filmaom a').click(function() {

							$('div#cvFormStep3 input.next').hide();

							$.ajax({
								type: "POST",
								url: "ajax.php",
								async: true,
								data: {
									'removeVideo': 'removeVideo'
								},
								dataType: 'json',
								success: function(data) {
									updateUserInfo();
								}
							});

							return false;
						});

					} else {

						$('div#cvFormStep3 input[type="radio"]').each(function() {
							$(this).hide();
						});
						$('input#videomethodyoutube').closest('h5').hide();
						$('div#videoarea').show();
						$('div#youtubevideoarea').html('').hide();
						$('div#belowyoutubearea').html('').hide();
						$('div#videorecorder').html('').hide();
						$('div#videoplayer').html('<div data_videoplayer="' + data['personal4'] + '" width="225" height="169" data_autoplay="false" data_autosize="false" data_repeat="false">videoplayer</div>').show();
						$('div#belowvideoarea').html('<div id="filmaom"><h5>Gör om ditt CV</h5><p><a href="">Ta bort filmen och gör en ny.</a></p><p>Du kan alltid logga in på cirkusen.com och ändra eller ta bort ditt CV.</p></div>').show();
						videoplayer.init();
						$('div#cvFormStep3 input.next').show();
						$('div#filmaom a').click(function() {

							$('div#cvFormStep3 input.next').hide();

							$.ajax({
								type: "POST",
								url: "ajax.php",
								async: true,
								data: {
									'removeVideo': 'removeVideo'
								},
								dataType: 'json',
								success: function(data) {
									updateUserInfo();
								}
							});

							return false;
						});
					}
				} else {

					$('div#cvFormStep3 input[type="radio"]').each(function() {
						this.checked = false;
						$(this).show();
					});
					$('input#videomethodwebcam').closest('h5').show();
					$('input#videomethodyoutube').closest('h5').show();
					$('div#videoarea').hide();
					$('div#youtubearea').hide();

					$('div#youtubevideoarea').html('').hide();

					$('div#videoplayer').html('').hide();
					$('div#belowvideoarea').html('').hide();
					$('div#belowyoutubearea').html('').hide();
					$('div#cvFormStep3 div.inputs').show();
					$('div#cvFormStep3 input.next').hide();
					$('div#videorecorder').html('<div data_videorec="true" data_bandwidth="50000" data_record_src="playerimages/record.png" data_play_src="playerimages/play.png" data_stop_src="playerimages/stop.png" data_finish_src="playerimages/finish.png" data_callback="videorec_callback" data_r5mc_project="88.80.16.137" data_r5mc_secret="development">videorec</div>').show();
					videorec.init();
				}
				$('div#loginboxwrapper').hide();
				$('div#logoutboxwrapper').show();
				$('img#lagguppcvpuff').hide();
				$('img#uppdateracvpuff').show();
			}
		},
		error: function() {
			setTimeout(function() { updateUserInfo() }, 1000);
		}
	});
}

function getYoutubeCode(url) {
	re = new RegExp('youtube\.com');
	if (!url.match(re)) return '';
	re = new RegExp('[&?]v=([^&]+)');
	if (url.match(re)) {
		m = re.exec(url);
		if (m == null) return '';
		return m[1];
	}
	return '';
}

function cvForm() {
	dimScreen(function() {

		$.ajax({
			type: "POST",
			url: "cvForm.php",
			async: true,
			data: data,
			dataType: 'html',
			success: function(data) {
				$("body").append('<div id="enlargedFrame1" style="position: absolute; left:-2000; top:-2000"><div id="enlargedFrame2"><div id="enlargedFrame3"><div id="enlargedFrame4"><div id="cvFormBox" style="width: 370px; background: #fff;"></div></div></div></div></div><img src="close.gif" id="enlargedClose" width="15" height="15" style="cursor: pointer" />');
				$('div#cvFormBox').html(data);
				updateUserInfo();
				fixForm($('div#cvFormBox'));
				$('div.cvFormNav input.cancel, div.cvFormNav input.finish, img#enlargedClose').each(function() {
					$(this).click(function() {
						runKlajaxLoader = true;
						undimScreen();
						$('img#enlargedClose').remove();
						$('div#enlargedFrame1').fadeOut(200, function() {
							$(this).remove();
						});
					});
				});
				if ($('div#loginboxwrapper').css('display') == 'block') {
					$('div#cvFormStep1').show();
				} else {
					$('div#cvFormStep2').show();
				}
				/*
				* STEP 1
				*/
				$('div#cvFormStep1 input.next').click(function() {
					$.ajax({
						type: "POST",
						url: "ajax.php",
						async: true,
						dataType: 'json',
						data: {
							'login': $('div#cvFormStep1 input[name="login"]').val(),
							'password': $('div#cvFormStep1 input[name="password"]').val(),
							'password2': $('div#cvFormStep1 input[name="password2"]').val(),
							'year': $('div#cvFormStep1 select[name="year"]').val(),
							'city': $('div#cvFormStep1 select[name="city"]').val()
						},
						success: function(data) {
							if (data['error'] != '') {
								alert(data['error']);
							} else {
								$.cookie('session', data['cookie'], {
									path: '/',
									expires: 0
								});
								updateUserInfo();
								$('div#cvFormStep1').hide(300);
								$('div#cvFormStep2').show(400, function() {
										positionCvForm();
								});
							}
						},
						error: function() {
							alert('Anslutningen till Internet fungerade inte. Försök igen.');
						}
					});

				});
				/*
				* STEP 2
				*/
				$('div#cvFormStep2 input[type="text"], div#cvFormStep2 textarea').each(function() {
					$(this).blur(function() {
						data = new Object();
						data[$(this).attr('name')] = $(this).val();
						if ($(this).val() == $(this).attr('data_default')) data[$(this).attr('name')] = '';
						$.ajax({
							type: "POST",
							url: "ajax.php",
							async: true,
							dataType: 'json',
							data: data
						});

					});
				});
				$('div#cvFormStep2 input.next').click(function() {
					$('div#cvFormStep2').hide(300);
					$('div#cvFormStep3').show(400, function() {
							positionCvForm();
							videorec.init();
							videoplayer.init();
					});
				});

				/*
				* STEP 3
				*/

				$('div#cvFormStep3 input.next').hide().click(function() {
					$('div#cvFormStep3').hide(300);
					$('div#cvFormStep4').show(400, function() {
							positionCvForm();
					});
				});
				$('input[name="videomethod"]').click(function() {
					if ($('input[name="videomethod"]:checked').val() == 'webcam') {
						$('div#videoarea').show(400, function() {
							positionCvForm();
						});
						$('div#youtubearea').hide(400);
					} else {
						$('div#videoarea').hide(400, function() {
							positionCvForm();
						});
						$('div#youtubearea').show(400);
					}
				});
				$('input#findyoutube').click(function() {
					youtubeCode = getYoutubeCode($('input[name="youtubeurl"]').val());
					if (youtubeCode == '') {
						alert('Tyvärr, kunde inte tolka youtubeadressen. Dubbelkontrollera adressen och försök igen!');
					} else {

						$.ajax({
							type: "POST",
							url: "ajax.php",
							async: true,
							data: {
								'saveYoutubeVideo': youtubeCode
							},
							dataType: 'json',
							success: function(data) {
								updateUserInfo();
							}
						});

					}
				});

				/*
				* STEP 4
				*/

				$('input.branschbox').click(function() {
					if ($(this).is(':checked')) {
						$.ajax({
							type: "POST",
							url: "ajax.php",
							async: true,
							dataType: 'json',
							data: {
								'addTag': $(this).next('label').html()
							}
						});
					} else {
						$.ajax({
							type: "POST",
							url: "ajax.php",
							async: true,
							dataType: 'json',
							data: {
								'rmTag': $(this).next('label').html()
							}
						});
					}
				});


				$('div.cvFormNav input.prev').each(function() {
					$(this).click(function() {
						$(this).closest('div.cvFormStep').each(function() {
							$(this).hide(400);
							$(this).prev('div.cvFormStep').show(400, function() {
								positionCvForm();
							});
						});
					});
				});
				positionCvForm();
				$(window).resize(function() {
					positionCvForm();
				});
				$(window).scroll(function() {
					positionCvForm();
				});

				$('div#dimming').click(function() {
					runKlajaxLoader = true;
					undimScreen();
					$('img#enlargedClose').remove();
					$('div#enlargedFrame1').fadeOut(200, function() {
						$(this).remove();
					});
				});
			},
			error: function() {
				undimScreen();
			}
		});
	});
}

function videoSelection() {
	if (($('select#bransch').val() == '') && ($('select#stad').val() == '')) {
		document.location.href = '#';
		return;
	}
	if ($('select#bransch').val() == '') {
		document.location.href = '#s' + $('select#stad').val();
		return;
	}
	if ($('select#stad').val() == '') {
		document.location.href = '#b' + $('select#bransch').val();
		return;
	}
	document.location.href = '#b' + $('select#bransch').val() + 's' + $('select#stad').val();
}

$(document).ready(function() {

	$('select#bransch, select#stad').change(function() {
		videoSelection();
	});

	$('*[data_bubble_info]').each(function() {
		$(this)
			.attr('data_bubble_info_initialized', 'true')
			.hover(function() {
				unbubble = false;
				bubble_ishover = true;
				bubble(this);
			}, function() {
				bubble_ishover = false;
				setTimeout(function() {
					unbubble = true;
				}, 400);
			});
	});


	addKlajaxPostInsertHook('*', function(element) {
		$('*[data_bubble_info]', element).each(function() {
			$(this)
				.attr('data_bubble_info_initialized', 'true')
				.hover(function() {
					unbubble = false;
					bubble_ishover = true;
					bubble(this);
				}, function() {
					bubble_ishover = false;
					setTimeout(function() {
						unbubble = true;
					}, 400);
				});
		});
	});
	addKlajaxPostInsertHook('feed', function(element) {
		if ($(element).attr('data_klajax_content_id') == '38') {
			$('div.textcontent', $(element)).append('<input id="ideaname" type="text" data_default="Ditt namn"/><input id="ideaphone" type="text" data_default="Ditt telefonnummer"/><input id="ideamail" type="text" data_default="Din e-postadress"/><textarea id="ideadescr" data_default="Beskriv din idé (max 5000 tecken)" /><input id="ideasubmit" type="button" value="Skicka" />');
			$('#ideaname, #ideaphone, #ideamail').css({
				'width': '300px',
				'color': '#8c8c8c'

			});
			$('#ideadescr').css({
				'width': '300px',
				'height': '150px',
				'color': '#8c8c8c'
			});
			$('#ideasubmit').click(function() {

				$.ajax({
					type: "POST",
					url: "formsubmit.php",
					async: true,
					dataType: 'html',
					data: {
						'form': 'Företagsidé',
						'namn': $('#ideaname').val(),
						'telefon': $('#ideaphone').val(),
						'mail': $('#ideamail').val(),
						'beskrivning': $('#ideadescr').val()
					},
					success: function(data) {
						alert('Tack! Din idé är emottagen.');
						$('#ideaname, #ideaphone, #ideamail, #ideadescr').each(function(){
							$(this).val($(this).attr('data_default'));
						});
					}
				});
				
			});
		}
	});
	addKlajaxHashChangeHook(function(hash) {
		if ((hash == 'tour') || (hash == 'vinn')) {
			if ($('div#cirkusfeeds div#feed').length == 0) {
				$('div#feed').remove();
				clearKlajaxCache('feed');
				$('div#cirkusfeeds').append('<div id="feed" data_klajax_container="feed" data_klajax_sort="data_time" data_klajax_sortorder="desc"/>');
				runKlajaxLoader = true;
			}
		}
		if (hash.substr(0,5) == 'video') {
			var videoid = parseInt(hash.substr(5));
			dimScreen();
			$.ajax({
				type: "POST",
				url: "profil.php",
				async: true,
				dataType: 'html',
				data: {
					'id': videoid
				},
				success: function(data) {
					$('body').append(data);
					$('div#feed').remove();
					clearKlajaxCache('feed');
					$('div#profilefeed').css('display', 'none').append($('<div id="feed" data_klajax_container="feed" data_klajax_sort="data_time" data_klajax_sortorder="desc"></div>'));
					$('div#profilefeed').show(400);
					$('body').append('<img src="close.gif" id="enlargedClose" width="15" height="15" style="cursor: pointer" />');
					$('div#dimming, img#enlargedClose').click(function() {
						removeEnlargedImage(function() {
							location.href="#";
						});
					});
					positionCvForm();
					videoplayer.init();
					$('div#profil div.entry').show(400);
					runKlajaxLoader = true;
				},
				error: function(data) {
					undimScreen();
				}
			});

		}
	});

	fixForm($('body'));
	updateUserInfo();

	$('img#lagguppcvpuff, img#uppdateracvpuff, #cirkmenucv').click(function() {
		cvForm();
		return false;
	});
	$('input#logoutbutton').click(function() {
		$.cookie('session', '', {
			path: '/',
			expires: 0
		});
		updateUserInfo();
	});
	$('input#login_button').click(function() {
		$.ajax({
			type: "POST",
			url: "ajax.php",
			async: true,
			dataType: 'json',
			data: {
				'login': $('input[id="login_email"]').val(),
				'password': $('input[id="login_pw"]').val()
			},
			success: function(data) {
				if (data['error'] != '') {
					alert('Fel login eller lösenord.');
				} else {
					$.cookie('session', data['cookie'], {
						path: '/',
						expires: 0
					});
					updateUserInfo();
				}
			}
		});
		$('input[id="login_pw"]').val('');
	});

	addKlajaxPostInsertHook('*', function(element) {
		$('input[data_default],textarea[data_default]', element).each (function () {
			if (this.value == '') {
				this.value = $(this).attr ('data_default');
			}
			$(this)
				.focus (function () {
					if (this.value == $(this).attr ('data_default')) {
						this.value = '';
					}
				})
				.blur (function () {
					if (this.value == '') {
						this.value = $(this).attr ('data_default');
					}
				});

		});
	});

	$(window).scroll(function() {
		if ($(window).scrollTop() > ($('div#wrapper').height() - $(window).height() - 20)) {
			$('ul[data_klajax_container="latestvideos"]').attr('data_klajax_limit', $('ul[data_klajax_container="latestvideos"] li:visible').length + 3);
			$('ul[data_klajax_container="latestvideos"] li').each(function() {
				showOrHideDependingOnHash($(this));
			});
			$('ul[data_klajax_container="mostcomments"]').attr('data_klajax_limit', $('ul[data_klajax_container="mostcomments"] li:visible').length + 3);
			$('ul[data_klajax_container="mostcomments"] li').each(function() {
				showOrHideDependingOnHash($(this));
			});
			$('ul[data_klajax_container="mostlikes"]').attr('data_klajax_limit', $('ul[data_klajax_container="mostlikes"] li:visible').length + 3);
			$('ul[data_klajax_container="mostlikes"] li').each(function() {
				showOrHideDependingOnHash($(this));
			});
		}
	});



	$('div#wrapper').fadeIn(400);

	initKlajax();

});


