
var Commentable = {
	maxLength : 1024,
	init: function() {
		$('form.comment_form textarea').keyup(function() {
			var textarea_value = $(this).val();
			if(textarea_value.length > Commentable.maxLength) {
				$(this).val(textarea_value.substring(0, Commentable.maxLength));
			} else {
				var id = $(this).attr('id').split('_')[2];
				$('#comment_character_counter_' + id).text(Commentable.maxLength - textarea_value.length);	
			}
		}); 
	},
	toggle : function(link) {
		var id = $(link).attr('href').split('comments_')[1];
		$('div#comments_' + id).slideToggle();
		return false;
	}
}


var CharacterCounter = {
	maxLength : 1024,
	init: function() {
		$('form.character_count_form textarea').keyup(function() {
			var textarea_value = $(this).val();
			if(textarea_value.length > CharacterCounter.maxLength) {
				$(this).val(textarea_value.substring(0, CharacterCounter.maxLength));
			} else {
				var id = $(this).attr('id').split('_')[2];
				$(this).parent().parent().find('span.character_counter').text(Commentable.maxLength - textarea_value.length);	
			}
		}); 
	}
}


var Article = {
	current_page : 1,
	init: function() {
		//$('.article div.article_page:gt(0)').hide();
		$('#article ul.pagination li a').click(function() {Article.changePage(parseInt($(this).attr('rel')));return false;});
		Article.updateNextPrevious(1);
	},	
	changePage: function(page) {
		this.current_page = page;
		$('.article div.article_page').hide();
		$('.article div.article_page:eq('+(page-1)+')').show();
		$('#article ul.pagination li.page_link').removeClass('current');
		$('#article ul.pagination li:eq('+page+')').addClass('current');
		Article.updateNextPrevious(page);
	},
	updateNextPrevious: function(page) {
		var num_of_pages = $('#article ul.pagination li.page_link').size();
		if (page == num_of_pages) {
			$('#article ul.pagination li.next').html('<span><span>Nästa</span></span>');
		} else {
			if (!$('#article ul.pagination li.next a').size()) {
				$('#article ul.pagination li.next').html('<a href="#"><span>Nästa</span></a>');
				$('#article ul.pagination li.next a').click(function() {Article.changePage(parseInt($(this).attr('rel')));return false;});
			}
		}
		if (page == 1) {
			$('#article ul.pagination li.previous').html('<span><span>Föregående</span></span>');
		} else {
			if (!$('#article ul.pagination li.previous a').size()) {
				$('#article ul.pagination li.previous').html('<a href="#"><span>Föregående</span></a>');
				$('#article ul.pagination li.previous a').click(function() {Article.changePage(parseInt($(this).attr('rel')));return false;});
			}
				
		}
		$('#article ul.pagination li.next a').attr('rel', (page+1));
		$('#article ul.pagination li.previous a').attr('rel', (page-1));
	}
}

var Linker = {
	init: function() {
		$("a[rel='popup']").click(function() {
			var size = $(this).attr('rev');
			if (size) {
				size = size.split('x');
				var width = size[0]; 
				var height = size[1]; 			
			} else {
				var width = 640; 
				var height = 480; 
			}
			window.open($(this).attr('href'),'player','toolbar=0,scrollbars=no,menubar=0,resizable=0,width='+width+',height='+height + ',left=' + ((screen.width - width)/2) + ',top=' + ((screen.height - height)/2));
			return false;
		});	
		$("a[rel='gallery']").click(function() {
			var width = 993; 
			var height = 793; 
			var qs = $(this).attr('href').split('?')[1];
			window.open('/imageGallery/gallery_popup.php?'+qs,'player','toolbar=no,scrollbars=no,width='+width+',height='+height+',resizable=no,left=' + ((screen.width - width)/2) + ',top=' + ((screen.height - height)/2));
			return false;
		});
		$("form#forgot_password_form").hide();
		$("a.switch_form").click(function() {
			$('form#forgot_password_form').toggle();
			$('form#login_form').toggle();
			return false;
		});
		
    	$('.lightbox_gallery a.lightbox').lightBox();
    	$('.lightbox_gallery_2 a.lightbox').lightBox();
    	
	},
	popup : function(link) {
		var size = $(link).attr('rev');
		if (size) {
			size = size.split('x');
			var width = size[0]; 
			var height = size[1]; 			
		} else {
			var width = 640; 
			var height = 480; 
		}
		window.open($(link).attr('href'),'player','toolbar=0,scrollbars=no,menubar=0,resizable=0,width='+width+',height='+height + ',left=' + ((screen.width - width)/2) + ',top=' + ((screen.height - height)/2));
		return false;
	},
	popupWithScroll : function(link) {
		var size = $(link).attr('rev');
		if (size) {
			size = size.split('x');
			var width = size[0]; 
			var height = size[1]; 			
		} else {
			var width = 640; 
			var height = 480; 
		}
		window.open($(link).attr('href'),'player','toolbar=0,scrollbars=yes,menubar=0,resizable=0,width='+width+',height='+height + ',left=' + ((screen.width - width)/2) + ',top=' + ((screen.height - height)/2));
		return false;
	},
	gallery : function(link) {
		var width = 993; 
		var height = 703; 
		var qs = $(link).attr('href').split('?')[1];
		window.open('/imageGallery/gallery_popup.php?'+qs,'player','toolbar=no,scrollbars=no,width='+width+',height='+height+',resizable=no,left=' + ((screen.width - width)/2) + ',top=' + ((screen.height - height)/2));
		return false;
	}
}


var Emoticon = {
	URL: '/community/emoticonPopup.php',
	target: null,
	
	init: function() {
		$("textarea").focus(function() {
			Emoticon.target = this;		
		});
		$("img.emoticon").click(function() {
			var width = 500; 
			var height = 250; 
			var w = window.open(Emoticon.URL,'emoticon','toolbar=no,scrollbars=no,width='+width+',height='+height+',resizable=no,left=' + ((screen.width - width)/2) + ',top=' + ((screen.height - height)/2));
			//$(this).parent().parent().find('textarea').focus();
			return false;
		});
		$("#emoticon_holder img").click(function() {
			//var val = $(window.opener.Emoticon.target).val();			
			//Emoticon.insert(window.opener.Emoticon.target, $(this).attr('title'));
			insertEmoticonFromPopup($(this).attr('title'));
		});
	},
	insert : function (el,ins) { 
	    if (el.setSelectionRange){ 
	        el.value = el.value.substring(0,el.selectionStart) + ins + el.value.substring(el.selectionStart,el.selectionEnd) + el.value.substring(el.selectionEnd,el.value.length); 
	    } 
	    else if (document.selection && document.selection.createRange) { 
	        el.focus(); 
	        var range = document.selection.createRange(); 
	        range.text = ins + range.text; 
	    } 
	} 
}


var Searcher = {
	DEFAULT_VALUE : 'Sök på finest...',
	init: function() {
		if ($("input#search_input_field").val() == '') {
			$("input#search_input_field").val(Searcher.DEFAULT_VALUE);
		}
		$("input#search_input_field").focus(function() {
			if ($(this).val() == Searcher.DEFAULT_VALUE) {
				$(this).val('');
			}
		});	
	}
}



var Login = {
	DEFAULT_VALUE_USERNAME : 'Användarnamn',
	DEFAULT_VALUE_PASSWORD : 'Lösenord',
	init: function() {
		if ($("input#login_username_input").val() == '') {
			$("input#login_username_input").val(Login.DEFAULT_VALUE_USERNAME);
		}
		$("input#login_username_input").focus(function() {
			if ($(this).val() == Login.DEFAULT_VALUE_USERNAME) {
				$(this).val('');
			}
		});	
		if ($("input#login_password_input").val() == '') {
			$("input#login_password_input").val(Login.DEFAULT_VALUE_PASSWORD);
		}
		$("input#login_password_input").focus(function() {
			if ($(this).val() == Login.DEFAULT_VALUE_PASSWORD) {
				$(this).val('');
			}
		});	
	}
}

var Blog = {
	initEditor: function (elementId, a) {
		tinyMCE.init({
				relative_urls : false,
			    convert_urls : false,
				mode : "exact",
				elements : elementId,
				theme : "advanced",
				plugins : "media" ,
				entity_encoding : "raw",
				
				content_css : "/client/v3/css/tinymce.css" ,
				//force_br_newlines : false,
				force_p_newlines : false,    
				//convert_newlines_to_brs : false,

				theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,link,unlink",
				theme_advanced_buttons2 : "fontselect,fontsizeselect,|,forecolor,backcolor,|,code",
				theme_advanced_buttons3 : "",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_path_location : "bottom",
				media_strict : false,
				invalid_elements : (!a ? 'script' : ''),
				extended_valid_elements : 'embed[src|quality|bgcolor|width|height|name|align|type|pluginpage]' + (a ? ',script' : ''),  
				extended_valid_elements : 'object[classid|width|height|codebase|data|type|bgcolor|*],param[name|value|_value]',
	    		extended_valid_elements : "a[name|href|target|title],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|name|style],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]"
		});
		
		$('#editBlogEntryPublishedCheckbox').click(function() {
			$('#published_selects').toggle();
		});
		if (!$('#editBlogEntryPublishedCheckbox:checked').attr('checked')) {
			$('#published_selects').hide();
		}
		
		
		$(function(){
			$('#pick_date').datePicker({
				createButton:false,
				startDate:'01/01/2005',
				endDate:'31/12/2011'
			}).bind(
				'click',
				function() {
					updateSelects($(this).dpGetSelected()[0]);
					$(this).dpDisplay();
					return false;
			}).bind(
				'dateSelected',
				function(e, selectedDate, $td, state) {
					updateSelects(selectedDate);
				}
			).bind(
			'dpClosed',
			function(e, selected) {
				updateSelects(selected[0]);
			}
		);
		
		var updateSelects = function (selectedDate) {
			
			var selectedDate = new Date(selectedDate);
			var month = selectedDate.getMonth()+1;month = month+'';
			month = month.length == 1 ? '0' + month : month;
			var day = selectedDate.getDate()+'';
			day = day.length == 1 ? '0' + day : day;
			$('#blogEntryPublishDaySelect option[value=' + day + ']').attr('selected', 'selected');
			$('#blogEntryPublishMonthSelect option[value=' + month + ']').attr('selected', 'selected');
			$('#blogEntryPublishYearSelect option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
		}
		// listen for when the selects are changed and update the picker
		$('#blogEntryPublishDaySelect, #blogEntryPublishMonthSelect, #blogEntryPublishYearSelect').bind('change', function() {
			var d = new Date(
				$('#blogEntryPublishYearSelect').val(),
				$('#blogEntryPublishMonthSelect').val()-1,
				$('#blogEntryPublishDaySelect').val()
			);
			$('#pick_date').dpSetSelected(d.asString());
			}
			);
		});
		
	},
	initBlogCategoriesSelect : function() {
		$('#blog_categories_form .checkbox input').click(function() {
			console.log($('#blog_categories_form .checkbox input:checked').size());
			if ($(this).is(':checked') && $('#blog_categories_form .checkbox input:checked').size() >= 4) {
				return false;
			}
		});
	}
}
var Alerts = {
	init: function() {
		if($('#logged_in').size() == 0) return;
		$.interval(30, function() {
			$.getJSON("/json/getLoggedInUserInfo.php", function(data){
				$('li#unread_messages a').text(data.numUserMailboxUnreadMails);
				data.numUserMailboxUnreadMails > 0 ? $('li#unread_messages').addClass('unread') : $('li#unread_messages').removeClass('unread');
				$('li#unread_guestbook_entries a').text(data.numUserGuestbookUnreadEntries);
				data.numUserGuestbookUnreadEntries > 0 ? $('li#unread_guestbook_entries').addClass('unread') : $('li#unread_guestbook_entries').removeClass('unread');
				$('li#new_friendrequests a').text(data.numUserRelationEvents);
				data.numUserRelationEvents > 0 ? $('li#new_friendrequests').addClass('unread') : $('li#new_friendrequests').removeClass('unread');
			});	
		});
		
	}
}

var Signup = {
	init: function () {
		if ($('form#signup_form')) {
			$('input#live_in_sweden_checkbox').click(function() {
				Signup.checkField();
			});
			Signup.checkField();
		}
	},
	checkField : function() {
		if($('input#live_in_sweden_checkbox:checked').size()) {
			$('#birth_number_holder').hide();
		} else {
			$('#birth_number_holder').show();
		}
	}
}
var Hoverable = {
	init: function () {
		$(".hoverable").mouseover(function(){
      		$(this).addClass("hover");
    	}).mouseout(function(){
      		$(this).removeClass("hover");
    	});
	}
}

var Calendar = {
	HOLDER : "div#blog_calendar div.content",
	URL : "calendar.php",
	CALENDAR_TABLE : "div#blog_calendar table",
	NEXT_MONTH : "div#blog_calendar a.next_month",
	PREV_MONTH : "div#blog_calendar a.prev_month",
	init: function() {
		$(Calendar.NEXT_MONTH + ',' + Calendar.PREV_MONTH).click(function() {
			var qs = $(this).attr('href').split('?')[1];
			var url = Calendar.URL + '?' + qs;
			$(Calendar.HOLDER).css('height', $(Calendar.HOLDER).height());
			$(Calendar.CALENDAR_TABLE).fadeOut('normal', function() {
				$(Calendar.HOLDER).html('<h3>Laddar...</h3>');
				$(Calendar.HOLDER).load(url, function() {
					$(Calendar.HOLDER).css('height', '');
					Calendar.init();
				});
			});
			return false;
		});	
	}
}


var ForgotPassword = {
	init: function() {
		$('#forgot_password_form').submit(function() {
			$(this).animate({opacity : 0.2});
			$.post('/json/sendRecoveryToEmail.php', { sendRecoveryToEmail: $('#forgot_password_email').val() }, function() {
				$('#forgot_password_form').animate({opacity : 1});
				$('#forgot_password_form fieldset').html('<p>Inloggnings uppgifter har skickats till din mail</p>');
			})	
			return false;
		});
	}
}

function init() {
	Alerts.init();
	Searcher.init();
	Login.init();
	Linker.init();
	Hoverable.init();
	Commentable.init();
	Article.init();	
	CharacterCounter.init();
	Emoticon.init();
	Signup.init();
	Calendar.init();
	ForgotPassword.init();
	
	// SIDEBAR SCROLL
	var sideAds = $('#right_ads, #left_ads');
	var actualView = $(window);
	var ads_following = false;
	
	actualView.scroll(function() {
		var topOffset = actualView.scrollTop();		
		if(topOffset > 630) {
			if(!ads_following) {
				
				var topDist = {"top": 0, "position": "fixed"};
				sideAds.css(topDist);
				ads_following = true;
			}
			
		} else {
			if(ads_following) {
				sideAds.attr("style", " ");
				ads_following = false;
			}
			
		}
	});

	
	//$( '#right_ads, #left_ads' ).scrollFollow({speed: 1000});
	$('.new_comment .text input, .new_comment textarea').inlineLabel();
}


$(document).ready(init);


