var Togglable = {
	cookie_glue : ':',
	cookie_name : 'toggled',
	
	hide_all_text : 'Komprimera alla',
	show_all_text : 'Visa alla',

	hide_item_text : 'Göm',
	show_item_text : 'Visa',
	hide_item_class : 'toggle_up',
	show_item_class : 'toggle_down',
	
	init: function() {
		var cookie = $.cookie(this.cookie_name);
		cookie = cookie ? cookie.split(this.cookie_glue) : new Array();

		jQuery.each(cookie, function() {
			if(this != '') $("#" + this).addClass('hidden').find("div.content").hide();
		});
		
		$('div.togglable').each(function() {
			if ($(this).hasClass('hidden')) {
				$(this).append('<a href="#" class="'+Togglable.show_item_class+'" title="'+Togglable.show_item_text+'"><span>'+Togglable.show_item_text+'</span></a>');
			} else {
				$(this).append('<a href="#" class="'+Togglable.hide_item_class+'" title="'+Togglable.hide_item_text+'"><span>'+Togglable.hide_item_text+'</span></a>');
			}
		});
		
		$('.togglable a.toggle_up, .togglable a.toggle_down, .togglable h2').click(function() {
			Togglable.toggleItem($(this).parent());
			return false;
		});
		
		this.initToggleAll();
	},
	toggleItem : function(item) {
		item.find('.content').slideToggle();
		if (item.hasClass('hidden')) {
			var toggle = item.find('.'+Togglable.show_item_class);
			toggle.attr('title', Togglable.show_item_text).find('span').text(Togglable.show_item_text);
			toggle.addClass(Togglable.hide_item_class).removeClass(Togglable.show_item_class);
			Togglable.saveToggled('show', item.attr('id'));
		} else {
			var toggle = item.find('.'+Togglable.hide_item_class);
			toggle.attr('title', Togglable.hide_item_text).find('span').text(Togglable.hide_item_text);
			toggle.addClass(Togglable.show_item_class).removeClass(Togglable.hide_item_class);
			Togglable.saveToggled('hide', item.attr('id'));
		}
		item.toggleClass('hidden');
		this.checkToggleAll();
	},
	checkToggleAll : function() {	
		var toggle_all = $('#toggle_all');
		if (this.allIsHidden() && toggle_all.find('span').text() == this.hide_all_text) {
			toggle_all.find('span').text(this.show_all_text);
			toggle_all.attr('title', this.show_all_text);
		} else if (this.allIsVisible() && toggle_all.find('span').text() == this.show_all_text) {
			toggle_all.find('span').text(this.hide_all_text);
			toggle_all.attr('title', this.hide_all_text);
		}
		
	},
	allIsHidden : function() {	
		return $('div.hidden').size() == $('div.togglable').size();
	},
	allIsVisible : function() {	
		return $('div.hidden').size() == 0;
	},
	initToggleAll : function() {
		if (!this.allIsHidden()) {
			$('#profile_info_side .togglable::last').after('<a href="#" class="button" id="toggle_all" title="' + this.hide_all_text +'"><span>' + this.hide_all_text +'</span></a>');
		} else {
			$('#profile_info_side .togglable::last').after('<a href="#" class="button" id="toggle_all" title="' + this.show_all_text +'"><span>' + this.show_all_text +'</span></a>');
		}
		

		$('a#toggle_all').click(function() {
			if ($('#toggle_all span').text() == Togglable.hide_all_text) {
				$('div.togglable').each(function() {
					if (!$(this).hasClass('hidden')) {
						Togglable.toggleItem($(this));
					}
				});
			} else {
				$('div.hidden').each(function() {
					Togglable.toggleItem($(this));
				});
			}
			Togglable.checkToggleAll();
			return false;
		});
	},

	saveToggled : function(action, id) {
		var cookie = $.cookie(this.cookie_name);
		cookie = cookie ? cookie.split(this.cookie_glue) : new Array();
		if (action == 'show') {
			var save = new Array();
			if (cookie && cookie.length > 0) {
				for (x in cookie) {
					if (cookie[x] != id && cookie[x] != '') {
						save.push(cookie[x]);
					}
				}
			}
		} else {
			var save = cookie;
			var already_set = false;
			for (x in cookie) {
				if (cookie[x] == id) already_set = true;
			}
			if (!already_set) save[cookie.length] = id;
		}
		var date = new Date();
		date.setTime(date.getTime() + (100 * 24 * 60 * 60 * 365));
		$.cookie(this.cookie_name, save.join(this.cookie_glue), { path: '/', expires: date });
	}
}



var Commentable = {
	maxLength : 1024,
	init: function() {
		//$('#blog div.comments_holder_hidden, #double_blog div.comments_holder_hidden').hide();
		
		/*$('div.blog_entry ul.actions li.comment a.toggle_comments').click(function() {
			var id = $(this).attr('href').split('comments_')[1];
			$('div#comments_' + id).slideToggle();
			return false;
		});*/
		$('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();
    	
	},
	gallery : function(link) {
		var width = 993; 
		var height = 758; 
		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;
	},
	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=1,menubar=0,resizable=1,width='+width+',height='+height + ',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, type) {
			tinyMCE.init({
				relative_urls : false,
			    convert_urls : false,
				mode : "exact",
				elements : elementId,
				theme : "advanced",
				plugins : "media, safari" ,
				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 : 'script',
				extended_valid_elements : 'embed[src|quality|bgcolor|width|height|name|align|type|pluginpage]',  
				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],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/' + ((new Date().getYear()) + 1901)
			}).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($('div#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 CheckAll = {
	init: function () {
		$('input.check_all').click(function() {
			$("input[type='checkbox']").attr('checked', $(this).is(':checked'));
		});
	}
}

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('<p>Laddar...</p>');
				$(Calendar.HOLDER).load(url, function() {
					$(Calendar.HOLDER).css('height', '');
					Calendar.init();
				});
			});
			return false;
		});	
	}
}

function init() {
	Alerts.init();
	Searcher.init();
	Login.init();
	Linker.init();
	Togglable.init();
	Hoverable.init();
	Commentable.init();
	Article.init();	
	CharacterCounter.init();
	Emoticon.init();
	Signup.init();
	Calendar.init();
	CheckAll.init();
	
	initEmoticonTargets();
}


$(document).ready(init);



/* --------------- Emoticon popup --------------- */

function insertEmoticonFromPopup(code) {

	/* The document that contains this global variable is the top parent */
	var root = window.opener ? window.opener : window;
	while(root.opener) root = root.opener;

	if(root.emoticonTarget != null) root.emoticonTarget.value += code;
}

var emoticonTarget;
function initEmoticonTargets() {
	var textareas = document.getElementsByTagName('textarea');
	for(var i = 0; i < textareas.length; i++) {
		var oldOnclick = textareas[i].onclick;
		textareas[i].onclick = function() {
			if(typeof oldOnclick == 'function') oldOnclick();
			/* The document that contains this global variable is the top parent */
			var root = window.opener ? window.opener : window;
			while(root.opener) root = root.opener;
			root.emoticonTarget = this;
		}
	}
}